From 7dcfa616e6216e396c431d4e36926030ab80f8d7 Mon Sep 17 00:00:00 2001 From: Smoffyy Date: Wed, 14 Oct 2026 19:35:01 -0500 Subject: [PATCH 01/13] Update packages --- .github/workflows/release.yml | 116 ++++++++++++++++++++++++++++++++++ AGENTS.md | 2 + CHANGELOG.md | 12 ++++ Cargo.lock | 39 ++++++------ crates/quill-agent/Cargo.toml | 2 +- crates/quill-code/Cargo.toml | 4 +- crates/quill-code/build.rs | 2 +- 7 files changed, 154 insertions(+), 23 deletions(-) create mode 100644 .github/workflows/release.yml create mode 100644 CHANGELOG.md diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..8fdded0 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,116 @@ +name: Release + +on: + push: + branches: [main] + paths: [Cargo.toml, CHANGELOG.md] + workflow_dispatch: + +concurrency: + group: release + cancel-in-progress: false + +permissions: + contents: write + +jobs: + prepare: + runs-on: ubuntu-latest + outputs: + version: ${{ steps.version.outputs.version }} + release: ${{ steps.version.outputs.release }} + title: ${{ steps.changelog.outputs.title }} + notes: ${{ steps.changelog.outputs.notes }} + steps: + - uses: actions/checkout@v4 + - id: version + env: + GH_TOKEN: ${{ github.token }} + run: | + version=$(cargo metadata --no-deps --format-version 1 | jq -r '.packages[] | select(.name == "quill-code") | .version') + echo "version=$version" >> "$GITHUB_OUTPUT" + if gh release list --limit 1000 --json tagName --jq '.[].tagName' | grep -Fqx "v$version"; then + echo "v$version already has a release" + echo "release=false" >> "$GITHUB_OUTPUT" + else + echo "release=true" >> "$GITHUB_OUTPUT" + fi + - id: changelog + if: steps.version.outputs.release == 'true' + env: + VERSION: ${{ steps.version.outputs.version }} + run: | + title=$(awk -v v="$VERSION" '$1 == "##" && $2 == v { print substr($0, 4); exit }' CHANGELOG.md) + if [ -z "$title" ]; then + echo "::error file=CHANGELOG.md::No '## $VERSION' section in CHANGELOG.md" + exit 1 + fi + echo "title=$title" >> "$GITHUB_OUTPUT" + { + echo "notes<> "$GITHUB_OUTPUT" + + build: + needs: prepare + if: needs.prepare.outputs.release == 'true' + strategy: + fail-fast: false + matrix: + include: + - os: windows-latest + target: x86_64-pc-windows-msvc + - os: ubuntu-22.04 + target: x86_64-unknown-linux-gnu + - os: macos-latest + target: aarch64-apple-darwin + - os: macos-latest + target: x86_64-apple-darwin + runs-on: ${{ matrix.os }} + steps: + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@stable + with: + targets: ${{ matrix.target }} + - uses: Swatinem/rust-cache@v2 + with: + key: ${{ matrix.target }} + - if: runner.os == 'Linux' + run: sudo apt-get update && sudo apt-get install -y build-essential pkg-config libssl-dev libfontconfig-dev libxkbcommon-dev libxkbcommon-x11-dev libwayland-dev + - run: cargo build -p quill-code --release --locked --target ${{ matrix.target }} + - shell: bash + env: + NAME: quill-code-${{ needs.prepare.outputs.version }}-${{ matrix.target }} + run: | + mkdir "$NAME" + cp LICENSE README.md assets/fonts/OFL.txt "$NAME" + if [ "$RUNNER_OS" = Windows ]; then + cp target/${{ matrix.target }}/release/quill-code.exe "$NAME" + 7z a -tzip "$NAME.zip" "$NAME" + else + cp target/${{ matrix.target }}/release/quill-code "$NAME" + tar czf "$NAME.tar.gz" "$NAME" + fi + - uses: actions/upload-artifact@v4 + with: + name: ${{ matrix.target }} + path: quill-code-*.* + if-no-files-found: error + + release: + needs: [prepare, build] + runs-on: ubuntu-latest + steps: + - uses: actions/download-artifact@v4 + with: + path: dist + merge-multiple: true + - env: + GH_TOKEN: ${{ github.token }} + TAG: v${{ needs.prepare.outputs.version }} + TITLE: ${{ needs.prepare.outputs.title }} + NOTES: ${{ needs.prepare.outputs.notes }} + run: | + printf '%s\n' "$NOTES" > notes.md + gh release create "$TAG" dist/* --repo "$GITHUB_REPOSITORY" --draft --target "$GITHUB_SHA" --title "$TITLE" --notes-file notes.md \ No newline at end of file diff --git a/AGENTS.md b/AGENTS.md index c9021ff..f5de981 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -15,6 +15,8 @@ A native desktop control surface for coding agents on local models. The assistan CI (`.github/workflows/ci.yml`, Windows) runs build, clippy, test and `cargo deny check`. All must stay green. +Releases (`.github/workflows/release.yml`) run when `main` gets a workspace version that has no release yet. The version needs a `## ` section in `CHANGELOG.md`, whose heading becomes the release title and whose body the notes. Windows, Linux and both macOS targets are built and attached to a draft release tagged `v`, which is published by hand. + ## Rules that do not bend - **No telemetry.** No analytics, crash reporting or update pings. The app talks only to the model server the user configured, to git remotes through the user's own `git`, and to the GitHub API for what the user asked for: creating a repository, opening a pull request, and reading pull request status for branches whose origin is on GitHub. `deny.toml` bans the usual telemetry crates; do not add network calls anywhere else. diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..12e63ae --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,12 @@ +# Changelog + +Each release is a `## ` heading, optionally followed by ` - `. When the workspace version in `Cargo.toml` reaches `main` without a release, the Release workflow builds Windows, Linux and macOS, takes the heading as the release title and the section below it as the notes, and opens a draft release tagged `v`. + +## 0.1.0 - First preview + +- Projects and threads, with several agents running at once and a sidebar that shows each thread's branch, commit, uncommitted work, unpushed commits, pull request and model. +- A tool-calling agent that lists, reads, searches, writes and edits files, runs commands, commits and opens pull requests, under Ask first, Trust edits and Autopilot access modes. +- Isolated copies (git worktrees) so parallel threads never collide. +- A commit dialog that can push, open a pull request page or publish a new GitHub repository, and new projects that can start on GitHub with a first branch of your choosing. +- Slash commands, @ file mentions, image and file attachments with previews, pinned models with Ctrl+1 to 9, a context ring, a PowerShell drawer and saved history. +- Models, context windows, vision and thinking controls detected from the server. \ No newline at end of file diff --git a/Cargo.lock b/Cargo.lock index 767b5ff..8478493 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2185,7 +2185,7 @@ dependencies = [ "serde", "serde_json", "serde_repr", - "similar", + "similar 2.7.0", "smallvec", "smol", "tracing", @@ -4932,14 +4932,14 @@ dependencies = [ "quill-llama", "serde", "serde_json", - "similar", + "similar 3.2.0", ] [[package]] name = "quill-code" version = "0.1.0" dependencies = [ - "base64 0.22.1", + "base64 0.23.1", "futures", "gpui-kit", "quill-agent", @@ -4948,7 +4948,7 @@ dependencies = [ "serde", "serde_json", "ureq", - "winres", + "winresource", ] [[package]] @@ -5556,9 +5556,9 @@ dependencies = [ [[package]] name = "rustls" -version = "0.23.45" +version = "0.23.46" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d41d731c7d2f962d1ccc364cec258de3c0e93b38c2fb3ba97ac74513048d634" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" dependencies = [ "once_cell", "ring", @@ -5972,6 +5972,15 @@ dependencies = [ "unicode-segmentation", ] +[[package]] +name = "similar" +version = "3.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4f66ca1f7aca2474dc10c942eb22feffc897735f54cd1db90138c2fddb490987" +dependencies = [ + "bstr", +] + [[package]] name = "simplecss" version = "0.2.2" @@ -6546,15 +6555,6 @@ dependencies = [ "tokio", ] -[[package]] -name = "toml" -version = "0.5.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f4f7f0dd8d50a853a531c426359045b1998f04219d88799810762cd4ad314234" -dependencies = [ - "serde", -] - [[package]] name = "toml" version = "0.8.23" @@ -8092,12 +8092,13 @@ dependencies = [ ] [[package]] -name = "winres" -version = "0.1.12" +name = "winresource" +version = "0.1.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b68db261ef59e9e52806f688020631e987592bd83619edccda9c47d42cde4f6c" +checksum = "a2bc6d36480b829272a5bdabf08e6dca8004761c1da7e35efef800540c66221b" dependencies = [ - "toml 0.5.11", + "toml 1.1.8+spec-1.1.0", + "version_check", ] [[package]] diff --git a/crates/quill-agent/Cargo.toml b/crates/quill-agent/Cargo.toml index a1ca59a..3247642 100644 --- a/crates/quill-agent/Cargo.toml +++ b/crates/quill-agent/Cargo.toml @@ -10,4 +10,4 @@ publish.workspace = true quill-llama.workspace = true serde = { version = "1", features = ["derive"] } serde_json = "1" -similar = "2" \ No newline at end of file +similar = "3" \ No newline at end of file diff --git a/crates/quill-code/Cargo.toml b/crates/quill-code/Cargo.toml index 82441c8..3a2ad2c 100644 --- a/crates/quill-code/Cargo.toml +++ b/crates/quill-code/Cargo.toml @@ -7,7 +7,7 @@ authors.workspace = true publish.workspace = true [dependencies] -base64 = "0.22" +base64 = "0.23" quill-agent.workspace = true quill-llama.workspace = true quill-weave.workspace = true @@ -18,4 +18,4 @@ serde_json = "1" ureq = { version = "3.4.2", default-features = false, features = ["json", "native-tls"] } [build-dependencies] -winres = "0.1" \ No newline at end of file +winresource = "0.1" \ No newline at end of file diff --git a/crates/quill-code/build.rs b/crates/quill-code/build.rs index e62760c..5bb5e84 100644 --- a/crates/quill-code/build.rs +++ b/crates/quill-code/build.rs @@ -1,6 +1,6 @@ fn main() { println!("cargo:rerun-if-changed=../../assets/brand/app.ico"); if std::env::var("CARGO_CFG_TARGET_OS").is_ok_and(|os| os == "windows") { - winres::WindowsResource::new().set_icon("../../assets/brand/app.ico").compile().expect("embed the app icon"); + winresource::WindowsResource::new().set_icon("../../assets/brand/app.ico").compile().expect("embed the app icon"); } } \ No newline at end of file From 32d85fc1c26ac919de03cf8e9b1e89a4c52ead92 Mon Sep 17 00:00:00 2001 From: Smoffyy Date: Thu, 15 Oct 2026 02:48:21 -0500 Subject: [PATCH 02/13] Massive overhaul --- AGENTS.md | 87 +- Cargo.lock | 235 +++- Cargo.toml | 6 +- assets/icons/claude.svg | 1 + assets/icons/key.svg | 1 + assets/icons/llama-cpp.svg | 7 - assets/icons/openai.svg | 1 + crates/quill-agent/examples/probe.rs | 34 - crates/quill-agent/src/lib.rs | 331 ----- crates/quill-agent/src/prompt.rs | 109 -- crates/quill-agent/src/tools.rs | 616 --------- crates/quill-code/Cargo.toml | 6 +- crates/quill-code/src/add_project.rs | 16 +- crates/quill-code/src/backend.rs | 473 ++++++- crates/quill-code/src/commit_dialog.rs | 63 +- crates/quill-code/src/composer.rs | 834 ++++++++---- crates/quill-code/src/config.rs | 102 +- crates/quill-code/src/context_ring.rs | 2 +- crates/quill-code/src/icons.rs | 11 +- crates/quill-code/src/main.rs | 10 +- crates/quill-code/src/mentions.rs | 6 +- crates/quill-code/src/model_settings.rs | 538 ++++++++ crates/quill-code/src/motion.rs | 67 + crates/quill-code/src/palette.rs | 129 +- crates/quill-code/src/panel.rs | 61 +- crates/quill-code/src/project.rs | 31 +- crates/quill-code/src/publish.rs | 35 - crates/quill-code/src/settings.rs | 1168 +++++++++++------ crates/quill-code/src/shell.rs | 1053 +++++++++++---- crates/quill-code/src/terminal.rs | 2 +- crates/quill-code/src/thread.rs | 292 ++++- crates/quill-code/src/thread_view.rs | 1004 ++++++++++---- crates/quill-code/src/ui.rs | 95 +- crates/quill-code/src/usage.rs | 264 ++++ crates/quill-code/src/weave.rs | 6 - crates/quill-code/src/workspace.rs | 390 ++++-- crates/quill-config/Cargo.toml | 14 + crates/quill-config/src/lib.rs | 403 ++++++ crates/quill-config/src/models.rs | 304 +++++ crates/quill-config/src/paths.rs | 26 + crates/quill-config/src/secrets.rs | 49 + crates/{quill-agent => quill-core}/Cargo.toml | 8 +- crates/quill-core/examples/probe.rs | 73 ++ crates/quill-core/src/claude_code.rs | 780 +++++++++++ crates/quill-core/src/context.rs | 160 +++ .../{quill-agent => quill-core}/src/diff.rs | 0 .../src/instructions.rs | 7 +- crates/quill-core/src/lib.rs | 19 + crates/quill-core/src/options.rs | 119 ++ crates/quill-core/src/policy.rs | 162 +++ crates/quill-core/src/prompt.rs | 141 ++ crates/quill-core/src/protocol.rs | 114 ++ crates/quill-core/src/session.rs | 264 ++++ crates/quill-core/src/tools/args.rs | 66 + crates/quill-core/src/tools/fs.rs | 757 +++++++++++ crates/quill-core/src/tools/git.rs | 136 ++ crates/quill-core/src/tools/mod.rs | 252 ++++ crates/quill-core/src/tools/patch.rs | 348 +++++ crates/quill-core/src/tools/paths.rs | 62 + crates/quill-core/src/tools/plan.rs | 158 +++ crates/quill-core/src/tools/shell.rs | 277 ++++ crates/quill-core/src/turn.rs | 542 ++++++++ crates/quill-git/Cargo.toml | 11 + crates/{quill-code => quill-git}/src/git.rs | 0 .../{quill-code => quill-git}/src/github.rs | 0 crates/quill-git/src/lib.rs | 4 + crates/quill-llama/src/lib.rs | 551 -------- .../Cargo.toml | 4 +- crates/quill-providers/src/anthropic.rs | 458 +++++++ crates/quill-providers/src/lib.rs | 320 +++++ crates/quill-providers/src/message.rs | 164 +++ crates/quill-providers/src/openai.rs | 400 ++++++ deny.toml | 5 +- 73 files changed, 11990 insertions(+), 3254 deletions(-) create mode 100644 assets/icons/claude.svg create mode 100644 assets/icons/key.svg delete mode 100644 assets/icons/llama-cpp.svg create mode 100644 assets/icons/openai.svg delete mode 100644 crates/quill-agent/examples/probe.rs delete mode 100644 crates/quill-agent/src/lib.rs delete mode 100644 crates/quill-agent/src/prompt.rs delete mode 100644 crates/quill-agent/src/tools.rs create mode 100644 crates/quill-code/src/model_settings.rs create mode 100644 crates/quill-code/src/motion.rs delete mode 100644 crates/quill-code/src/publish.rs create mode 100644 crates/quill-code/src/usage.rs create mode 100644 crates/quill-config/Cargo.toml create mode 100644 crates/quill-config/src/lib.rs create mode 100644 crates/quill-config/src/models.rs create mode 100644 crates/quill-config/src/paths.rs create mode 100644 crates/quill-config/src/secrets.rs rename crates/{quill-agent => quill-core}/Cargo.toml (63%) create mode 100644 crates/quill-core/examples/probe.rs create mode 100644 crates/quill-core/src/claude_code.rs create mode 100644 crates/quill-core/src/context.rs rename crates/{quill-agent => quill-core}/src/diff.rs (100%) rename crates/{quill-agent => quill-core}/src/instructions.rs (87%) create mode 100644 crates/quill-core/src/lib.rs create mode 100644 crates/quill-core/src/options.rs create mode 100644 crates/quill-core/src/policy.rs create mode 100644 crates/quill-core/src/prompt.rs create mode 100644 crates/quill-core/src/protocol.rs create mode 100644 crates/quill-core/src/session.rs create mode 100644 crates/quill-core/src/tools/args.rs create mode 100644 crates/quill-core/src/tools/fs.rs create mode 100644 crates/quill-core/src/tools/git.rs create mode 100644 crates/quill-core/src/tools/mod.rs create mode 100644 crates/quill-core/src/tools/patch.rs create mode 100644 crates/quill-core/src/tools/paths.rs create mode 100644 crates/quill-core/src/tools/plan.rs create mode 100644 crates/quill-core/src/tools/shell.rs create mode 100644 crates/quill-core/src/turn.rs create mode 100644 crates/quill-git/Cargo.toml rename crates/{quill-code => quill-git}/src/git.rs (100%) rename crates/{quill-code => quill-git}/src/github.rs (100%) create mode 100644 crates/quill-git/src/lib.rs delete mode 100644 crates/quill-llama/src/lib.rs rename crates/{quill-llama => quill-providers}/Cargo.toml (84%) create mode 100644 crates/quill-providers/src/anthropic.rs create mode 100644 crates/quill-providers/src/lib.rs create mode 100644 crates/quill-providers/src/message.rs create mode 100644 crates/quill-providers/src/openai.rs diff --git a/AGENTS.md b/AGENTS.md index f5de981..a024e81 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -11,7 +11,7 @@ A native desktop control surface for coding agents on local models. The assistan | `cargo clippy --workspace --all-targets` | Lints, must be clean | | `cargo fmt --all` | Formatting (`rustfmt.toml`); strip the trailing newline it adds | | `cargo deny check` | Licence and banned-crate policy (`deny.toml`) | -| `cargo run -p quill-agent --example probe -- ""` | Run one agent turn headless in `%TEMP%\quill-probe` | +| `cargo run -p quill-core --example probe -- ""` | Run one agent turn headless in `%TEMP%\quill-probe` | CI (`.github/workflows/ci.yml`, Windows) runs build, clippy, test and `cargo deny check`. All must stay green. @@ -19,46 +19,72 @@ Releases (`.github/workflows/release.yml`) run when `main` gets a workspace vers ## Rules that do not bend -- **No telemetry.** No analytics, crash reporting or update pings. The app talks only to the model server the user configured, to git remotes through the user's own `git`, and to the GitHub API for what the user asked for: creating a repository, opening a pull request, and reading pull request status for branches whose origin is on GitHub. `deny.toml` bans the usual telemetry crates; do not add network calls anywhere else. -- **Permissive licences only.** The project is MIT. Dependencies must pass `cargo deny check`; the only exceptions are build-time `option-ext` (MPL-2.0) and the `webpki-root-certs` data crate (CDLA-Permissive-2.0) that ureq's `native-tls` feature pulls in. Never depend on or copy from Zed's GPL crates (anything in the Zed repository other than `gpui`). Nothing GPL is bundled: Git features use the user's installed `git` and say "Needs Git" without it. +- **No telemetry.** No analytics, crash reporting or update pings. The app talks only to the model providers the user configured (local servers, OpenAI-compatible services, Anthropic), to the Claude Code program the user installed, to git remotes through the user's own `git`, and to the GitHub API for what the user asked for: creating a repository, opening a pull request, and reading pull request status for branches whose origin is on GitHub. `deny.toml` bans the usual telemetry crates; do not add network calls anywhere else. +- **Permissive licences only.** The project is MIT. Dependencies must pass `cargo deny check`; the only exceptions are build-time `option-ext` (MPL-2.0) and the `webpki-root-certs` data crate (CDLA-Permissive-2.0) that ureq's `native-tls` feature pulls in. Unmaintained-crate advisories are checked for direct dependencies only (`unmaintained = "workspace"`), because gpui's own tree carries a few with no upgrade path. Never depend on or copy from Zed's GPL crates (anything in the Zed repository other than `gpui`). Nothing GPL is bundled: Git features use the user's installed `git` and say "Needs Git" without it. - **GitHub sign-in is Git's.** The app never stores a token. `github.rs` asks `git credential fill` for one, so Git Credential Manager signs the user in the first time they publish. Background checks pass `GCM_INTERACTIVE=never` so they can never pop a sign-in window. -- **Models are detected, not configured.** `/v1/models` gives the list, status, vision and the window size (llama.cpp `meta.n_ctx` or `--ctx-size`, vLLM `max_model_len`, LM Studio `loaded_context_length`, then `context_length`). `/props?model=` gives llama.cpp's template capabilities; reading it for an unloaded model loads it, so it is only read for the selected model. +- **Models are detected, not configured.** `/v1/models` gives the list, status, vision and the window size (llama.cpp `meta.n_ctx` or `--ctx-size`, vLLM `max_model_len`, LM Studio `loaded_context_length`, then `context_length`). `/props?model=` gives llama.cpp's template capabilities; reading it for an unloaded model loads it, so it is only read for the selected model. Anthropic's `/v1/models` gives window, output limit, vision, effort levels and server-side compaction. Claude Code models are the aliases listed for it (`fable`, `opus`, `sonnet`, `haiku`); the exact version each one resolves to is read from Claude Code's init event and cached in `%APPDATA%\quill-code\claude-models.json`, so the picker says "Claude Haiku 5.5". Settings only fill in what a provider does not report. +- **Keys live in the system keychain.** API keys are stored with the `keyring` crate in Windows Credential Manager under the service `quill-code` and the provider's id, never in `settings.json` or a thread. `OPENAI_API_KEY` and `ANTHROPIC_API_KEY` are used only for providers pointing at the official addresses. Claude Code always runs on the user's own sign-in: Quill never reads its credentials and removes `ANTHROPIC_API_KEY` from its environment so a stray key does not bill the API instead of the user's plan. ## Layout ``` crates/ - quill-llama/ OpenAI-compatible client tuned for llama.cpp: models, props, streaming chat with tool-call deltas and usage - quill-agent/ the agent engine, no UI - lib.rs agent loop (stream, collect tool calls, approve, execute, repeat), Access, Approval, Publisher - prompt.rs Quill's system prompt: identity, workspace, tools, native shell guidance, workflow, git, reply - tools.rs list/read/search/write/edit/run plus commit_changes and open_pull_request, path guard, aliases, shell runner + quill-providers/ model access, no UI: the Provider trait, Message, Effort, streaming events with tool-call deltas, usage, stop reasons + openai.rs OpenAI-compatible chat completions: llama.cpp and other local servers (props, template thinking), and cloud + services with a Bearer key and reasoning_effort + anthropic.rs the Messages API over raw HTTP: Models API, adaptive thinking with effort, tool use with eager input + streaming, prompt caching, refusal fallbacks, server-side compaction, native content replay + message.rs chat messages with images and tool calls, stored in OpenAI shape plus the provider's native content + quill-core/ the agent engine, no UI + protocol.rs Event (serde, tagged) and the shared types: ToolView, Approval, Decision, PlanStep, Outcome + session.rs one thread per session: Op queue (Turn, Steer, Decide, Answer, Compact, Shutdown), inbox, history; the Engine + (a Provider, or Claude Code) is chosen per turn + claude_code.rs drives the user's `claude` CLI over stream-json: one process per thread, permission prompts through + Quill's policy and approval card, tool rows and diffs, TodoWrite as the plan, steering, interrupt, resume, + handoff of earlier history when another model ran in between + turn.rs the turn loop: stream, collect calls, admit (prepare, policy, approval), run read-only batches in parallel + policy.rs Access presets, Effect, Rule and verdicts, read-only command detection + context.rs token estimate, auto-compaction (summary of earlier turns), trimming old tool output + options.rs Limits, Toolsets and Shell, with their defaults + prompt.rs Quill's system prompt, built from the enabled tools + tools/ the Tool trait and registry: list_dir, find_files, grep, read_file, write_file, edit_file, apply_patch, + shell, update_plan, ask_user, commit_changes, open_pull_request; aliases, lenient arguments, path guard diff.rs line diffs grouped into hunks instructions.rs AGENTS.md, CLAUDE.md (with @imports), GEMINI.md, copilot instructions examples/probe.rs headless agent run against a real server + quill-git/ the user's git: status snapshot, commit, branch, push, worktrees, remote parsing; github.rs for the GitHub API + quill-config/ typed settings in layers (defaults, %APPDATA%\quill-code\settings.json, a project's .quill/settings.json), + migration from the old config.json, limits and rules for the engine, app paths; + models.rs (providers, model references, role models, per-model overrides), secrets.rs (API keys in the keychain) quill-weave/ the weave mark's maths quill-code/ the desktop app main.rs startup: fonts, assets, config, palette, window shell.rs window: title bar, sidebar timeline, layout, menus, toasts, repo and pull request caches - workspace.rs model: threads, runs (several at once), approvals, isolated copies, persistence hooks - thread.rs Thread, Turn and Item data, summaries, history repair (serde, tested) - thread_view.rs transcript: bubbles with image previews, step rows, final answer, changes card - composer.rs prompt box: chips, slash commands, @ mentions, attachments, context ring, approval card, workspace strip + workspace.rs model: threads, one session per thread, runs (several at once), approvals, questions, steering, isolated copies + thread.rs Thread, Turn and Item data (tools, plans, questions, steers, notes), summaries, history repair, v1 loading + thread_view.rs transcript: bubbles, live activity header, grouped exploring, timed tool rows with live output, folding + reasoning, plan card, final answer with the weave beside the latest, changes card, try again + composer.rs prompt box: pill chips, slash commands, @ mentions, attachments, context ring, approval card (diff preview, + Enter allows, Esc denies), question card, workspace strip + motion.rs animation helpers and the motion setting context_ring.rs context gauge and its label commit_dialog.rs commit, new branch, push, pull request page, publish to GitHub - publish.rs the app's Publisher: what commit_changes and open_pull_request do - git.rs status snapshot, commit, branch, push, worktrees, remote parsing - github.rs repository and pull request API through Git's stored credential terminal.rs PowerShell drawer - panel.rs right panel: Review and Files tabs + panel.rs right panel: Review, Files and Usage tabs + usage.rs usage log (%APPDATA%\quill-code\usage.jsonl, one line per finished turn, seeded from existing threads) + and the Usage tab: this chat's cost and tokens per turn, totals for today, 7 and 30 days, all time, by model add_project.rs Add project sheet: start fresh (first branch, optional GitHub repo), open a folder, clone - settings.rs Settings: General, Models, Instructions, Projects, Version - backend.rs model server connection, selected model, detected thinking + settings.rs Settings, built on gpui-component's settings pages: General, Models, Agent, Tools, Permissions, Instructions, + Projects, Advanced, Version; every field reads and writes the settings global, with search and reset + backend.rs every provider's connection and models, the selected model, its reasoning control (on/off or effort), + engines and one-shot writers for a model, local server scan, learned Claude versions + model_settings.rs Settings, Models: provider cards (address, key, on/off), add and find providers, effort, side-job models, + overrides for the model in use mentions.rs slash commands, @ file index and ranking attachments.rs images as data URLs, text files as fenced blocks project.rs badges, create, clone, open in VS Code or Explorer store.rs threads in %APPDATA%\quill-code\threads, sent images in ...\images\ - config.rs settings in %APPDATA%\quill-code\config.json; projects in ~/.quill-code/projects, isolated copies in ~/.quill-code/worktrees + config.rs the settings global: load, save on every change, reload when the file changes, refuse to save over a broken file icons.rs the Icon enum; every SVG is embedded version.rs, weave.rs, palette.rs, assets.rs, ui.rs assets/ brand/ (weave icons), icons/ (interface icons), fonts/ (Open Sans, OFL) @@ -66,9 +92,19 @@ assets/ brand/ (weave icons), icons/ (interface icons), fonts/ (Open Sans, OFL) ## How a turn runs -`Workspace::send` builds a `quill_agent::Task`: Quill's system prompt, the full history, the access mode and, when the workdir is a Git repository, a `Publisher` that gives the agent `commit_changes` and `open_pull_request`. It runs `quill_agent::run` on the background executor. Events come back through an unbounded channel and `Workspace::apply` turns them into `Item`s on the turn; `Usage` sets the thread's `context_used`, which the context ring shows against the model's window. Every run is keyed by thread and turn index, so a stopped run can never write into a newer turn. Anything the access mode does not allow waits on an `mpsc` reply that the approval card answers. Stop sets the run's `AtomicBool`; `repair_history` answers any tool call left without a result, because llama.cpp templates reject dangling tool calls. Threads are saved when a turn starts and finishes; a turn still running at shutdown is marked Stopped on load. +Each thread gets a `quill_core` session the first time it sends, started with the thread's history. `Workspace::send` builds a `TurnContext` (engine, model, summariser, thinking or effort, output limit, server compaction, context window, workdir, access, toolsets, personal instructions, limits, rules) and sends `Op::Turn` with a fresh cancel flag. The session owns the history: it pushes every message itself and reports it with `Event::Message`, which the workspace mirrors into the thread for saving. Events come back through an unbounded channel and `Workspace::apply` turns them into `Item`s; every turn event carries its turn index, so a stopped run can never write into a newer turn. Messages typed while a run is going become `Op::Steer` and are added before the next step. A tool is prepared first (so edits have their diff), then the policy decides; anything that needs the user emits `ApprovalRequested` and waits for `Op::Decide`, and `ask_user` waits for `Op::Answer`. Stop sets the cancel flag; the engine answers every open tool call, because llama.cpp templates reject dangling tool calls. A new turn sent while a stopped one is still winding down queues behind it. When the window fills past the compaction threshold, earlier turns are summarised and old tool output is trimmed. Threads are saved when a turn starts and finishes; a turn still running at shutdown is marked Stopped on load. -Access modes: Ask first asks before edits, commits, commands and pull requests; Trust edits asks only before commands and pull requests; Autopilot never asks. "Allow everything in this thread" raises the mode inside the running agent only. +With Claude Code as the engine, Claude Code runs the loop and its own tools; Quill turns its stream into the same events (text, tool rows with diffs, plan, questions, usage, cost, context window) and mirrors the messages into the thread's history, so another model can carry on in the same thread. Each permission prompt goes through Quill's policy and approval card. Ask first runs Claude Code in `manual` mode, the other presets in `acceptEdits`. The session id is saved on the thread and resumed with `--resume`. If another model answered in between, a fresh Claude session starts with a transcript of the thread. Messages sent while it works are sent after its current reply, stop is a control-request interrupt, and cost comes from its result. + +Access modes: Ask first asks before edits, commands, commits and pull requests; Trust edits makes edits and runs read-only commands on its own; Autopilot never asks, except before fetching from the web. Rules (allow, ask or deny a tool, optionally for a command prefix) override the preset; the approval card's "Always allow" choices add rules for the session, and "Allow everything in this thread" raises the session to Autopilot. + +## Settings + +Everything that can be tuned is a typed field in `quill_config::Settings`, saved as `settings.json` and shown in Settings; nothing tunable is hard-coded elsewhere. A turn uses the user's settings with the project's `.quill/settings.json` merged on top (objects merge, values and lists replace), so a project can set its own rules, tools or limits. `Settings::limits()` turns them into the engine's `Limits`. A new setting needs a field with a default in `quill-config` and an item in `settings.rs`. + +## Usage and cost + +Every model call reports `Tokens` (prompt, completion, cache read, cache write), summed on the turn. Cost comes from Claude Code's own result, from Anthropic's published prices (`quill_config::default_price`, cache-aware) for Anthropic API models, or from a price the user sets per model in Settings, Models; local models are free. Each finished or stopped turn is appended to the usage log, so overall totals survive deleting threads. The chat's total shows on its sidebar row and on the toolbar's Usage button. Claude Code models are named with the version their alias points to (`quill_config::claude_latest`), replaced by the version Claude Code reports once it runs. ## Sidebar @@ -83,10 +119,13 @@ Threads are grouped into In motion (running or waiting on the user), Past day, P ## Look and feel -- One theme: the dark palette and its light counterpart, following the Windows setting live. Every colour lives in `palette.rs`; components read `palette(cx)`. +- One theme in two modes: the ink palette, dark and light, following Windows live unless Appearance pins one. Every colour lives in `palette.rs` (surfaces `sidebar`, `bg`, `raised`, `menu_bg`; one `accent` with `accent_soft` and `accent_text`); components read `palette(cx)`. +- Primary actions use the accent (`ui::button` with `Tone::Primary`); secondary, ghost and danger tones cover the rest. Menus, cards and the composer are rounded (10 to 20 px) with a 1 px border; the composer gets an accent ring when focused. +- Motion lives in `motion.rs`: `rise` for things that appear, `pop` for menus, `spin` for working rows, `shimmer` for live labels, springs for the sidebar width and the panel tabs. Appearance's Motion setting scales every duration and Off sets GPUI's reduce-motion. +- The title bar holds the sidebar toggle, breadcrumbs and a toolbar (Open in, Commit, Review, Files, Terminal); there is no floating card. Ctrl K opens the command launcher, Ctrl N a new thread, Ctrl B the sidebar, Ctrl , settings, Ctrl ` the terminal. - Open Sans everywhere (`palette::FONT`), Consolas for code (`ui::MONO`). - The weave is drawn live, never as an image, and stays monochrome; `quill-weave` is pinned by tests to exact reference frames. Model marks are the same weave seeded from the model's name. -- Interface icons are our own, drawn in one style (24 viewBox, 1.5 stroke), all in `assets/icons` and listed in `icons.rs`. Draw a new icon in that style rather than borrowing another product's. +- Interface icons are our own, drawn in one style (24 viewBox, 1.5 stroke), all in `assets/icons` and listed in `icons.rs`. Draw a new icon in that style rather than borrowing another product's. The two exceptions are `claude.svg` and `openai.svg`, the providers' own marks (from Simple Icons), shown only in the model picker and Settings to say which backend a model comes from; in a chat the model is shown by the weave. Local servers have no mark, so their models keep the weave in the picker. ## Conventions diff --git a/Cargo.lock b/Cargo.lock index 8478493..b499bff 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -104,11 +104,22 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0" dependencies = [ "cfg-if", - "cipher", + "cipher 0.4.4", "cpufeatures 0.2.17", "zeroize", ] +[[package]] +name = "aes" +version = "0.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "35f0f96ce78e38c3dc6d8948aa8163d06385be74000f3c7a95bf1eef35d3ea32" +dependencies = [ + "cipher 0.5.2", + "cpubits", + "cpufeatures 0.3.1", +] + [[package]] name = "ahash" version = "0.8.12" @@ -187,6 +198,17 @@ version = "1.0.104" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" +[[package]] +name = "apple-native-keyring-store" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b350bfd03649e07aa05c0a81b3e15934374e585c98204a57e20b9d49f49bb9a" +dependencies = [ + "keyring-core", + "log", + "security-framework", +] + [[package]] name = "arbitrary" version = "1.5.0" @@ -632,6 +654,15 @@ dependencies = [ "generic-array", ] +[[package]] +name = "block-padding" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "710f1dd022ef4e93f8a438b4ba958de7f64308434fa6a87104481645cc30068b" +dependencies = [ + "hybrid-array", +] + [[package]] name = "block2" version = "0.5.1" @@ -754,7 +785,16 @@ version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "26b52a9543ae338f279b96b0b9fed9c8093744685043739079ce85cd58f289a6" dependencies = [ - "cipher", + "cipher 0.4.4", +] + +[[package]] +name = "cbc" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce2dc9ee5f88d11e0beb842c88b33c8a5cf0d1329c4b19494af42b07dbfe8896" +dependencies = [ + "cipher 0.5.2", ] [[package]] @@ -831,10 +871,26 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" dependencies = [ "crypto-common 0.1.7", - "inout", + "inout 0.1.4", "zeroize", ] +[[package]] +name = "cipher" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c" +dependencies = [ + "crypto-common 0.2.2", + "inout 0.2.3", +] + +[[package]] +name = "cmov" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a" + [[package]] name = "cocoa" version = "0.25.0" @@ -1132,6 +1188,12 @@ dependencies = [ "unicode-segmentation", ] +[[package]] +name = "cpubits" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15b85f9c39137c3a891689859392b1bd49812121d0d61c9caf00d46ed5ce06ae" + [[package]] name = "cpufeatures" version = "0.2.17" @@ -1219,6 +1281,15 @@ dependencies = [ "linktime-proc-macro", ] +[[package]] +name = "ctutils" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03bb0e1cc970d482d121d9a1744999169b69a07470b3d644a7894e53fcaf4574" +dependencies = [ + "cmov", +] + [[package]] name = "data-url" version = "0.3.2" @@ -1283,6 +1354,7 @@ dependencies = [ "block-buffer 0.12.1", "const-oid", "crypto-common 0.2.2", + "ctutils", ] [[package]] @@ -2852,7 +2924,16 @@ version = "0.12.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7b5f8eb2ad728638ea2c7d47a21db23b7b58a72ed6a38256b8a1849f15fbbdf7" dependencies = [ - "hmac", + "hmac 0.12.1", +] + +[[package]] +name = "hkdf" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4aaa26c720c68b866f2c96ef5c1264b3e6f473fe5d4ce61cd44bbe913e553018" +dependencies = [ + "hmac 0.13.0", ] [[package]] @@ -2864,6 +2945,15 @@ dependencies = [ "digest 0.10.7", ] +[[package]] +name = "hmac" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f" +dependencies = [ + "digest 0.11.3", +] + [[package]] name = "html5ever" version = "0.27.0" @@ -3217,10 +3307,20 @@ version = "0.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01" dependencies = [ - "block-padding", + "block-padding 0.3.3", "generic-array", ] +[[package]] +name = "inout" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8c0d789294fb457b791f7797a04478704788f30b407e5d0b01deaa846572d9f" +dependencies = [ + "block-padding 0.4.2", + "hybrid-array", +] + [[package]] name = "instant" version = "0.1.13" @@ -3360,6 +3460,27 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "keyring" +version = "4.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2270074a3d26bcac93c1dc5d2845eb4c089e8d761ccf6e0ea266a16004640627" +dependencies = [ + "apple-native-keyring-store", + "keyring-core", + "windows-native-keyring-store", + "zbus-secret-service-keyring-store", +] + +[[package]] +name = "keyring-core" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29fbf4b551298c67925f38cf341a1ada797a75f1837bdf8ae1fc8e2ebc6efb59" +dependencies = [ + "log", +] + [[package]] name = "khronos-egl" version = "6.0.0" @@ -4407,21 +4528,21 @@ version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "78f2bfed90f1618b4b48dcad9307f25e14ae894e2949642c87c351601d62cebd" dependencies = [ - "aes", + "aes 0.8.4", "ashpd", "async-fs", "async-io", "async-lock", "blocking", - "cbc", - "cipher", + "cbc 0.1.2", + "cipher 0.4.4", "digest 0.10.7", "endi", "futures-lite", "futures-util", "getrandom 0.4.3", - "hkdf", - "hmac", + "hkdf 0.12.4", + "hmac 0.12.1", "md-5", "num", "num-bigint-dig", @@ -4581,7 +4702,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8ed6a7761f76e3b9f92dfb0a60a6a6477c61024b775147ff0973a02653abaf2" dependencies = [ "digest 0.10.7", - "hmac", + "hmac 0.12.1", ] [[package]] @@ -4926,33 +5047,58 @@ dependencies = [ ] [[package]] -name = "quill-agent" +name = "quill-code" +version = "0.1.0" +dependencies = [ + "base64 0.23.1", + "futures", + "gpui-kit", + "quill-config", + "quill-core", + "quill-git", + "quill-providers", + "quill-weave", + "serde", + "serde_json", + "ureq", + "winresource", +] + +[[package]] +name = "quill-config" version = "0.1.0" dependencies = [ - "quill-llama", + "keyring", + "quill-core", + "quill-providers", "serde", "serde_json", - "similar 3.2.0", ] [[package]] -name = "quill-code" +name = "quill-core" version = "0.1.0" dependencies = [ - "base64 0.23.1", - "futures", - "gpui-kit", - "quill-agent", - "quill-llama", - "quill-weave", + "globset", + "ignore", + "quill-git", + "quill-providers", + "regex", "serde", + "serde_json", + "similar 3.2.0", +] + +[[package]] +name = "quill-git" +version = "0.1.0" +dependencies = [ "serde_json", "ureq", - "winresource", ] [[package]] -name = "quill-llama" +name = "quill-providers" version = "0.1.0" dependencies = [ "serde", @@ -5725,6 +5871,25 @@ version = "4.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1c107b6f4780854c8b126e228ea8869f4d7b71260f962fefb57b996b8959ba6b" +[[package]] +name = "secret-service" +version = "5.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5107b24b91445dd2aa449a258a1807b63240942157292354dc5bfdbeb8bc6db8" +dependencies = [ + "aes 0.9.3", + "cbc 0.2.1", + "futures-util", + "getrandom 0.4.3", + "hkdf 0.13.0", + "hybrid-array", + "num", + "once_cell", + "serde", + "sha2 0.11.1", + "zbus", +] + [[package]] name = "security-framework" version = "3.7.0" @@ -7699,6 +7864,19 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" +[[package]] +name = "windows-native-keyring-store" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "063426e76fdec7438d56bb777f67e318a84a25c707b07e575cb8b78e10c028f8" +dependencies = [ + "byteorder", + "keyring-core", + "regex", + "windows-sys 0.61.2", + "zeroize", +] + [[package]] name = "windows-numerics" version = "0.2.0" @@ -8334,6 +8512,17 @@ dependencies = [ "zvariant", ] +[[package]] +name = "zbus-secret-service-keyring-store" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "74801d001b9e7729adb4f1825b67b398185fed424749aa3d8bacf70417137d9a" +dependencies = [ + "keyring-core", + "secret-service", + "zbus", +] + [[package]] name = "zbus_macros" version = "5.19.0" diff --git a/Cargo.toml b/Cargo.toml index 50500f9..cb940ad 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,8 +10,10 @@ authors = ["Smoffyy"] publish = false [workspace.dependencies] -quill-agent = { path = "crates/quill-agent" } -quill-llama = { path = "crates/quill-llama" } +quill-config = { path = "crates/quill-config" } +quill-core = { path = "crates/quill-core" } +quill-git = { path = "crates/quill-git" } +quill-providers = { path = "crates/quill-providers" } quill-weave = { path = "crates/quill-weave" } gpui-kit = "0.7.3" diff --git a/assets/icons/claude.svg b/assets/icons/claude.svg new file mode 100644 index 0000000..1beee86 --- /dev/null +++ b/assets/icons/claude.svg @@ -0,0 +1 @@ +Claude \ No newline at end of file diff --git a/assets/icons/key.svg b/assets/icons/key.svg new file mode 100644 index 0000000..d8a2f61 --- /dev/null +++ b/assets/icons/key.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/assets/icons/llama-cpp.svg b/assets/icons/llama-cpp.svg deleted file mode 100644 index d036b22..0000000 --- a/assets/icons/llama-cpp.svg +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - \ No newline at end of file diff --git a/assets/icons/openai.svg b/assets/icons/openai.svg new file mode 100644 index 0000000..ebbdab0 --- /dev/null +++ b/assets/icons/openai.svg @@ -0,0 +1 @@ +OpenAI \ No newline at end of file diff --git a/crates/quill-agent/examples/probe.rs b/crates/quill-agent/examples/probe.rs deleted file mode 100644 index bc4d809..0000000 --- a/crates/quill-agent/examples/probe.rs +++ /dev/null @@ -1,34 +0,0 @@ -use std::sync::atomic::AtomicBool; - -use quill_agent::{Access, AgentEvent, Task, run, system_prompt}; -use quill_llama::Message; - -fn main() { - let mut args = std::env::args().skip(1); - let url = args.next().unwrap_or_else(|| "http://127.0.0.1:9931".into()); - let model = args.next().unwrap_or_default(); - let prompt = args.next().unwrap_or_else(|| "Create hello.py that prints a greeting, then run it.".into()); - let root = std::env::temp_dir().join("quill-probe"); - std::fs::create_dir_all(&root).expect("probe folder"); - let task = Task { - server_url: url, - system: system_prompt(&model, Some(&root), false, ""), - model, - thinking: Some(false), - root: Some(root.clone()), - access: Access::Full, - history: vec![Message::user(prompt)], - publisher: None, - }; - println!("working in {}", root.display()); - let cancel = AtomicBool::new(false); - let result = run(task, &cancel, |event| match event { - AgentEvent::Text(text) => print!("{text}"), - AgentEvent::ToolStarted { kind, target, .. } => println!("\n[{}] {target}", kind.name()), - AgentEvent::ToolFinished { ok, output, .. } => { - println!(" -> {} {}", if ok { "ok" } else { "failed" }, output.lines().next().unwrap_or_default()) - } - _ => {} - }); - println!("\nresult: {result:?}"); -} \ No newline at end of file diff --git a/crates/quill-agent/src/lib.rs b/crates/quill-agent/src/lib.rs deleted file mode 100644 index 6ad1df1..0000000 --- a/crates/quill-agent/src/lib.rs +++ /dev/null @@ -1,331 +0,0 @@ -mod diff; -mod instructions; -mod prompt; -mod tools; - -use std::path::{Path, PathBuf}; -use std::sync::Arc; -use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::mpsc::{RecvTimeoutError, Sender, channel}; -use std::time::Duration; - -use quill_llama::{ChatRequest, Error, Event, Message, Server, ToolCall}; -use serde::{Deserialize, Serialize}; - -pub use diff::{DiffLine, FileDiff, LineKind, diff_text}; -pub use instructions::project_instructions; -pub use prompt::system_prompt; -pub use tools::ToolKind; - -const MAX_STEPS: usize = 50; - -#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub enum Access { - #[serde(alias = "manual")] - Supervised, - AutoEdits, - #[default] - #[serde(alias = "auto")] - Full, -} - -impl Access { - pub const ALL: [Access; 3] = [Access::Supervised, Access::AutoEdits, Access::Full]; - - pub fn label(self) -> &'static str { - match self { - Access::Supervised => "Ask first", - Access::AutoEdits => "Trust edits", - Access::Full => "Autopilot", - } - } - - pub fn description(self) -> &'static str { - match self { - Access::Supervised => "Checks with you before every edit and command", - Access::AutoEdits => "Applies edits on its own, checks before running commands", - Access::Full => "Edits and runs commands without stopping to ask", - } - } - - fn asks_for_edits(self) -> bool { - self == Access::Supervised - } - - fn asks_for_commands(self) -> bool { - self != Access::Full - } -} - -#[derive(Debug, Clone, PartialEq)] -pub enum Approval { - FileChange(FileDiff), - Command(String), - Commit(String), - PullRequest(String), -} - -pub trait Publisher: Send + Sync { - fn commit(&self, root: &Path, message: &str, branch: Option<&str>) -> Result; - fn open_pull_request(&self, root: &Path, title: &str, body: &str) -> Result; -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Decision { - Approve, - Decline, - AlwaysAllow, -} - -#[derive(Debug)] -pub enum AgentEvent { - Reasoning(String), - Text(String), - StepDone, - ToolStarted { id: String, kind: ToolKind, target: String }, - ToolFinished { id: String, ok: bool, output: String, diff: Option }, - NeedsApproval { id: String, approval: Approval, reply: Sender }, - Message(Message), - Usage { prompt: u64, completion: u64 }, -} - -pub struct Task { - pub server_url: String, - pub model: String, - pub thinking: Option, - pub root: Option, - pub access: Access, - pub system: String, - pub history: Vec, - pub publisher: Option>, -} - -#[derive(Default)] -struct PendingCall { - id: Option, - name: String, - arguments: String, -} - -pub fn run(task: Task, cancel: &AtomicBool, mut emit: impl FnMut(AgentEvent)) -> Result<(), Error> { - let server = Server::new(&task.server_url); - let tool_schemas = if task.root.is_some() { tools::schemas(task.publisher.is_some()) } else { Vec::new() }; - let mut messages = vec![Message::system(task.system.clone())]; - messages.extend(task.history.iter().cloned()); - let mut access = task.access; - for step in 0..MAX_STEPS { - let mut text = String::new(); - let mut pending: Vec = Vec::new(); - let request = - ChatRequest { model: task.model.clone(), messages: messages.clone(), thinking: task.thinking, tools: tool_schemas.clone() }; - server.stream_chat(&request, cancel, |event| match event { - Event::Reasoning(chunk) => emit(AgentEvent::Reasoning(chunk)), - Event::Content(chunk) => { - text.push_str(&chunk); - emit(AgentEvent::Text(chunk)); - } - Event::ToolCall { index, id, name, arguments } => { - if pending.len() <= index { - pending.resize_with(index + 1, PendingCall::default); - } - let call = &mut pending[index]; - if id.is_some() { - call.id = id; - } - if let Some(name) = name { - call.name.push_str(&name); - } - call.arguments.push_str(&arguments); - } - Event::Usage { prompt, completion } => emit(AgentEvent::Usage { prompt, completion }), - })?; - if cancel.load(Ordering::Relaxed) { - return Ok(()); - } - emit(AgentEvent::StepDone); - let calls: Vec = pending - .into_iter() - .enumerate() - .filter(|(_, call)| !call.name.is_empty()) - .map(|(index, call)| ToolCall::new(call.id.unwrap_or_else(|| format!("call_{step}_{index}")), call.name, call.arguments)) - .collect(); - let assistant = Message::assistant(text, calls.clone()); - messages.push(assistant.clone()); - emit(AgentEvent::Message(assistant)); - if calls.is_empty() { - return Ok(()); - } - for call in &calls { - if cancel.load(Ordering::Relaxed) { - return Ok(()); - } - let output = match task.root.as_deref() { - Some(root) => execute(root, task.publisher.as_deref(), call, &mut access, cancel, &mut emit), - None => "No project is open, so tools are unavailable. Answer directly.".into(), - }; - let result = Message::tool(call.id.clone(), output); - messages.push(result.clone()); - emit(AgentEvent::Message(result)); - } - } - Err(Error(format!("Stopped after {MAX_STEPS} steps. Send a follow-up to let the agent continue."))) -} - -fn ask(id: &str, approval: Approval, cancel: &AtomicBool, emit: &mut impl FnMut(AgentEvent)) -> Decision { - let (reply, answer) = channel(); - emit(AgentEvent::NeedsApproval { id: id.to_string(), approval, reply }); - loop { - match answer.recv_timeout(Duration::from_millis(200)) { - Ok(decision) => return decision, - Err(RecvTimeoutError::Timeout) if cancel.load(Ordering::Relaxed) => return Decision::Decline, - Err(RecvTimeoutError::Timeout) => {} - Err(RecvTimeoutError::Disconnected) => return Decision::Decline, - } - } -} - -fn execute( - root: &Path, - publisher: Option<&dyn Publisher>, - call: &ToolCall, - access: &mut Access, - cancel: &AtomicBool, - emit: &mut impl FnMut(AgentEvent), -) -> String { - let git = publisher.is_some(); - let Some(kind) = ToolKind::resolve(&call.function.name).filter(|kind| git || !matches!(kind, ToolKind::Commit | ToolKind::PullRequest)) - else { - let names: Vec = tools::schemas(git).iter().filter_map(|t| t["function"]["name"].as_str().map(str::to_string)).collect(); - return format!("Error: there is no tool called \"{}\". The tools are {}.", call.function.name, names.join(", ")); - }; - let args = tools::parse_args(&call.function.arguments); - let id = call.id.clone(); - emit(AgentEvent::ToolStarted { id: id.clone(), kind, target: tools::describe(kind, &args) }); - let (ok, output, diff) = if let Some(raw) = args.get("__invalid").and_then(|v| v.as_str()) { - (false, format!("The arguments were not valid JSON: {raw}. Send a JSON object, for example {{\"path\": \"src/main.rs\"}}."), None) - } else { - match kind { - ToolKind::List => settle(tools::list(root, &args)), - ToolKind::Read => settle(tools::read(root, &args)), - ToolKind::Search => settle(tools::search(root, &args)), - ToolKind::Write | ToolKind::Edit => change(root, kind, &args, &id, access, cancel, emit), - ToolKind::Run => command(root, &args, &id, access, cancel, emit), - ToolKind::Commit | ToolKind::PullRequest => match publisher { - Some(publisher) => publish(root, publisher, kind, &args, &id, access, cancel, emit), - None => (false, "Git tools are not available here.".into(), None), - }, - } - }; - emit(AgentEvent::ToolFinished { id, ok, output: output.clone(), diff }); - if ok { output } else { format!("Error: {output}") } -} - -fn settle(result: Result) -> (bool, String, Option) { - match result { - Ok(output) => (true, output, None), - Err(error) => (false, error, None), - } -} - -fn change( - root: &Path, - kind: ToolKind, - args: &serde_json::Value, - id: &str, - access: &mut Access, - cancel: &AtomicBool, - emit: &mut impl FnMut(AgentEvent), -) -> (bool, String, Option) { - let change = match tools::plan_change(root, kind, args) { - Ok(change) => change, - Err(error) => return (false, error, None), - }; - if access.asks_for_edits() { - match ask(id, Approval::FileChange(change.diff.clone()), cancel, emit) { - Decision::Decline => return (false, "The user declined this change. Ask what they would like instead.".into(), None), - Decision::AlwaysAllow => *access = Access::AutoEdits, - Decision::Approve => {} - } - } - if let Err(error) = tools::apply(&change) { - return (false, error, None); - } - let verb = if change.diff.created { "Created" } else { "Updated" }; - let summary = format!("{verb} {} (+{} -{})", change.diff.path, change.diff.added, change.diff.removed); - (true, summary, Some(change.diff)) -} - -fn command( - root: &Path, - args: &serde_json::Value, - id: &str, - access: &mut Access, - cancel: &AtomicBool, - emit: &mut impl FnMut(AgentEvent), -) -> (bool, String, Option) { - let Some(command) = tools::arg(args, &tools::COMMAND_KEYS).map(str::trim).filter(|c| !c.is_empty()) else { - return (false, "run_command needs a \"command\".".into(), None); - }; - if access.asks_for_commands() { - match ask(id, Approval::Command(command.to_string()), cancel, emit) { - Decision::Decline => return (false, "The user declined running this command. Ask what they would like instead.".into(), None), - Decision::AlwaysAllow => *access = Access::Full, - Decision::Approve => {} - } - } - let (ok, output) = tools::run(root, command, tools::command_timeout(args), cancel); - (ok, output, None) -} - -#[allow(clippy::too_many_arguments)] -fn publish( - root: &Path, - publisher: &dyn Publisher, - kind: ToolKind, - args: &serde_json::Value, - id: &str, - access: &mut Access, - cancel: &AtomicBool, - emit: &mut impl FnMut(AgentEvent), -) -> (bool, String, Option) { - let text = |keys: &[&str]| tools::arg(args, keys).map(str::trim).filter(|t| !t.is_empty()); - let branch = text(&tools::BRANCH_KEYS); - let (approval, asks, widened) = if kind == ToolKind::Commit { - let Some(message) = text(&tools::MESSAGE_KEYS) else { - return (false, "commit_changes needs a \"message\".".into(), None); - }; - let summary = branch.map_or_else(|| message.to_string(), |branch| format!("{message} (on {branch})")); - (Approval::Commit(summary), access.asks_for_edits(), Access::AutoEdits) - } else { - let Some(title) = text(&tools::TITLE_KEYS) else { - return (false, "open_pull_request needs a \"title\".".into(), None); - }; - (Approval::PullRequest(title.to_string()), access.asks_for_commands(), Access::Full) - }; - if asks { - match ask(id, approval, cancel, emit) { - Decision::Decline => return (false, "The user declined this. Ask what they would like instead.".into(), None), - Decision::AlwaysAllow => *access = widened, - Decision::Approve => {} - } - } - let result = match kind { - ToolKind::Commit => publisher.commit(root, text(&tools::MESSAGE_KEYS).unwrap_or_default(), branch), - _ => publisher.open_pull_request(root, text(&tools::TITLE_KEYS).unwrap_or_default(), text(&tools::BODY_KEYS).unwrap_or_default()), - }; - settle(result) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn access_reads_old_settings() { - let auto: Access = serde_json::from_str("\"auto\"").unwrap(); - let manual: Access = serde_json::from_str("\"manual\"").unwrap(); - assert_eq!((auto, manual), (Access::Full, Access::Supervised)); - assert_eq!(serde_json::to_string(&Access::AutoEdits).unwrap(), "\"auto_edits\""); - } -} \ No newline at end of file diff --git a/crates/quill-agent/src/prompt.rs b/crates/quill-agent/src/prompt.rs deleted file mode 100644 index d15b672..0000000 --- a/crates/quill-agent/src/prompt.rs +++ /dev/null @@ -1,109 +0,0 @@ -use std::path::Path; - -use crate::instructions::project_instructions; -use crate::tools::{os_name, shell_name}; - -const TOOLS: &str = "# Your tools - -- list_files shows how the project is laid out. Start with it in a project you have not seen yet. -- read_file reads a file with line numbers. Read a file before you change it, and in a large file read only the lines you need. -- search finds text across the project, ignoring case. Use it to find where something is defined or used. -- write_file creates a new file or replaces a whole file. -- edit_file replaces an exact piece of text in a file. Copy old_text exactly from read_file output without the line numbers, and include enough surrounding lines to make it unique. -- run_command runs a shell command in the project folder and returns its output and exit code."; - -const GIT_TOOLS: &str = " -- commit_changes stages every change in the project and commits it, optionally on a new branch. -- open_pull_request pushes the current branch to GitHub and opens a pull request into the main branch."; - -const WINDOWS_SHELL: &str = "# Commands on Windows - -run_command uses Windows PowerShell, so write PowerShell, not bash or cmd: -- Use cmdlets such as Get-ChildItem, Get-Content, Select-String, New-Item, Copy-Item, Move-Item and Remove-Item. Do not use ls -la, grep, cat with flags, rm -rf, touch or export. -- Separate commands with a semicolon. Set environment variables with $env:NAME = 'value'. -- Paths use backslashes, and paths with spaces need quotes. -- Run programs installed on the computer, such as python, node, npm, cargo, dotnet or go, by name."; - -const UNIX_SHELL: &str = "# Commands - -run_command uses sh, so write POSIX shell. Combine commands with && and quote paths that contain spaces. Run programs installed on the computer, such as python3, node, npm, cargo or go, by name."; - -const COMMAND_RULES: &str = "Commands must finish on their own. Pass flags that skip prompts, such as -y, and do not start servers, watchers or anything else that waits forever; a command is stopped when its timeout runs out. To look at files, prefer list_files, read_file and search over shell commands."; - -const WORKFLOW: &str = "# How to work - -1. Understand the request. If it is unclear in a way that changes the result, ask one short question. Otherwise make a sensible choice and mention it. -2. Explore before changing anything: find the relevant files and read them. -3. Make focused changes that follow the project's existing style, naming and structure. Do not reformat or rewrite code the task does not touch. -4. Check your work: build, run or test the code with run_command when the project allows it, and fix whatever broke. -5. When a tool call fails, read the error and change your approach. Never repeat a call that failed in exactly the same way. -6. When the user declines a change or a command, do not try it again in another form. Ask what they would like instead. - -Keep going until the task is done. Do not stop between ordinary steps to ask for permission; the app asks the user when it needs to."; - -const GIT: &str = "# Git - -The project uses Git. To commit, push or open a pull request, use commit_changes and open_pull_request rather than running git yourself. Commit or open a pull request only when the user asks for it. Put work meant for a pull request on a new branch with a short, descriptive name such as fix-login. Write commit messages as one short summary line in the imperative mood, followed by details only when they help."; - -const REPLY: &str = "# Your reply - -When you finish, reply with a short summary of what you changed and how you checked it. The user sees every tool call and diff, so do not paste file contents back. Use Markdown, with fenced code blocks for code. Be direct and concise."; - -pub fn system_prompt(model: &str, root: Option<&Path>, git: bool, personal: &str) -> String { - let os = os_name(); - let mut sections = vec![format!( - "You are Quill, the coding agent built into quill-code. You run on the user's own {os} computer and are powered by the {model} model. If the user asks which model you are, say so." - )]; - match root { - Some(root) => { - sections.push(format!( - "# Your workspace\n\nYou work in the project folder {}. Paths you give to tools are relative to it, and you cannot reach files outside it. Use your tools to do the work rather than describing what you would do.", - root.display() - )); - sections.push(if git { format!("{TOOLS}{GIT_TOOLS}") } else { TOOLS.to_string() }); - let shell = if shell_name() == "PowerShell" { WINDOWS_SHELL } else { UNIX_SHELL }; - sections.push(format!("{shell}\n\n{COMMAND_RULES}")); - sections.push(WORKFLOW.to_string()); - if git { - sections.push(GIT.to_string()); - } - sections.push(REPLY.to_string()); - let project = project_instructions(root); - if !project.is_empty() { - sections.push(format!("# Project instructions\n\n{project}")); - } - } - None => sections.push( - "No project is open in this conversation, so you have no tools. Answer from what you know, and when the user wants you to work on their files, suggest opening a project in quill-code. Use Markdown, with fenced code blocks for code. Be direct and concise.".into(), - ), - } - let personal = personal.trim(); - if !personal.is_empty() { - sections.push(format!("# The user's instructions\n\n{personal}")); - } - sections.join("\n\n") -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn quill_is_the_assistant_whatever_the_model() { - let prompt = system_prompt("qwen", None, false, ""); - assert!(prompt.starts_with("You are Quill")); - assert!(prompt.contains("powered by the qwen model")); - assert!(prompt.contains("no tools")); - } - - #[test] - fn projects_get_tools_shell_and_workflow() { - let dir = std::env::temp_dir(); - let prompt = system_prompt("m", Some(&dir), false, ""); - assert!(prompt.contains("edit_file") && prompt.contains("# How to work")); - assert!(prompt.contains(if cfg!(windows) { "Windows PowerShell" } else { "POSIX shell" })); - assert!(!prompt.contains("open_pull_request")); - assert!(system_prompt("m", Some(&dir), true, "").contains("open_pull_request")); - assert!(system_prompt("m", None, false, "Use tabs.").ends_with("# The user's instructions\n\nUse tabs.")); - } -} \ No newline at end of file diff --git a/crates/quill-agent/src/tools.rs b/crates/quill-agent/src/tools.rs deleted file mode 100644 index 0369be8..0000000 --- a/crates/quill-agent/src/tools.rs +++ /dev/null @@ -1,616 +0,0 @@ -use std::fs; -use std::io::Read; -use std::path::{Component, Path, PathBuf}; -use std::process::{Command, Stdio}; -use std::sync::atomic::{AtomicBool, Ordering}; -use std::time::{Duration, Instant}; - -use serde::{Deserialize, Serialize}; -use serde_json::{Value, json}; - -use crate::diff::{FileDiff, diff_text}; - -const IGNORED: [&str; 12] = - [".git", "node_modules", "target", "dist", "build", ".venv", "venv", "__pycache__", ".next", ".idea", ".vs", "bin"]; -const MAX_LIST: usize = 400; -const MAX_READ_LINES: usize = 1500; -const MAX_MATCHES: usize = 100; -const MAX_OUTPUT: usize = 30_000; - -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -pub enum ToolKind { - List, - Read, - Search, - Write, - Edit, - Run, - Commit, - PullRequest, -} - -impl ToolKind { - pub fn resolve(name: &str) -> Option { - let name = name.trim().to_ascii_lowercase().replace(['-', ' '], "_"); - match name.as_str() { - "list_files" | "list" | "ls" | "list_dir" | "list_directory" | "tree" => Some(ToolKind::List), - "read_file" | "read" | "view" | "cat" | "open_file" | "view_file" => Some(ToolKind::Read), - "search" | "search_files" | "grep" | "find_in_files" | "search_code" => Some(ToolKind::Search), - "write_file" | "write" | "create_file" | "save_file" => Some(ToolKind::Write), - "edit_file" | "edit" | "str_replace" | "replace_in_file" | "apply_edit" => Some(ToolKind::Edit), - "run_command" | "run" | "bash" | "shell" | "powershell" | "exec" | "execute_command" | "terminal" => Some(ToolKind::Run), - "commit_changes" | "commit" | "git_commit" | "create_commit" => Some(ToolKind::Commit), - "open_pull_request" | "pull_request" | "create_pull_request" | "open_pr" | "create_pr" => Some(ToolKind::PullRequest), - _ => None, - } - } - - pub fn name(self) -> &'static str { - match self { - ToolKind::List => "list_files", - ToolKind::Read => "read_file", - ToolKind::Search => "search", - ToolKind::Write => "write_file", - ToolKind::Edit => "edit_file", - ToolKind::Run => "run_command", - ToolKind::Commit => "commit_changes", - ToolKind::PullRequest => "open_pull_request", - } - } -} - -pub fn schemas(git: bool) -> Vec { - let tool = |name: &str, description: &str, properties: Value, required: &[&str]| { - json!({ - "type": "function", - "function": { - "name": name, - "description": description, - "parameters": { "type": "object", "properties": properties, "required": required } - } - }) - }; - let mut tools = vec![ - tool( - "list_files", - "List files and folders in the project, a few levels deep. Use it first to see how the project is laid out.", - json!({ "path": { "type": "string", "description": "Folder relative to the project root. Leave empty for the root." } }), - &[], - ), - tool( - "read_file", - "Read a text file with line numbers. Always read a file before editing it.", - json!({ - "path": { "type": "string", "description": "File path relative to the project root." }, - "start_line": { "type": "integer", "description": "First line to show, starting at 1." }, - "end_line": { "type": "integer", "description": "Last line to show." } - }), - &["path"], - ), - tool( - "search", - "Search every text file in the project for a piece of text, case-insensitive. Returns matching lines with their paths and line numbers.", - json!({ - "query": { "type": "string", "description": "Text to look for." }, - "path": { "type": "string", "description": "Optional folder to limit the search to." } - }), - &["query"], - ), - tool( - "write_file", - "Create a file or replace its whole content. Use it for new files; prefer edit_file for changes to existing files.", - json!({ - "path": { "type": "string", "description": "File path relative to the project root." }, - "content": { "type": "string", "description": "The complete content of the file." } - }), - &["path", "content"], - ), - tool( - "edit_file", - "Replace an exact piece of text in a file. old_text must match the file exactly, including spaces, and appear once unless replace_all is true.", - json!({ - "path": { "type": "string", "description": "File path relative to the project root." }, - "old_text": { "type": "string", "description": "Exact text to replace, copied from the file." }, - "new_text": { "type": "string", "description": "Replacement text. Use an empty string to delete." }, - "replace_all": { "type": "boolean", "description": "Replace every occurrence." } - }), - &["path", "old_text", "new_text"], - ), - tool( - "run_command", - &format!( - "Run a {} command in the project folder and return its output and exit code. Use it to build, test and run code.", - shell_name() - ), - json!({ - "command": { "type": "string", "description": format!("The {} command to run.", shell_name()) }, - "timeout_seconds": { "type": "integer", "description": "How long to wait before stopping it. Default 120, maximum 600." } - }), - &["command"], - ), - ]; - if git { - tools.push(tool( - "commit_changes", - "Stage every change in the project and commit it. Give a branch to commit on a new branch, which a pull request needs when you are on the main branch or not on a branch.", - json!({ - "message": { "type": "string", "description": "Commit message: a short summary line, optionally followed by a blank line and details." }, - "branch": { "type": "string", "description": "Optional branch to create or switch to before committing, for example fix-login." } - }), - &["message"], - )); - tools.push(tool( - "open_pull_request", - "Push the current branch to GitHub and open a pull request into the main branch. Commit your work with commit_changes first.", - json!({ - "title": { "type": "string", "description": "Pull request title." }, - "body": { "type": "string", "description": "What changed and why, in Markdown." } - }), - &["title"], - )); - } - tools -} - -pub fn parse_args(arguments: &str) -> Value { - let text = arguments.trim(); - if text.is_empty() { - return json!({}); - } - serde_json::from_str(text).unwrap_or_else(|_| json!({ "__invalid": text })) -} - -pub fn arg<'a>(args: &'a Value, keys: &[&str]) -> Option<&'a str> { - keys.iter().find_map(|key| args.get(*key).and_then(Value::as_str)) -} - -fn arg_number(args: &Value, keys: &[&str]) -> Option { - keys.iter().find_map(|key| { - let value = args.get(*key)?; - value.as_u64().or_else(|| value.as_str()?.trim().parse().ok()) - }) -} - -fn arg_bool(args: &Value, key: &str) -> bool { - args.get(key).is_some_and(|v| v.as_bool().unwrap_or_else(|| v.as_str() == Some("true"))) -} - -pub const PATH_KEYS: [&str; 5] = ["path", "file_path", "file", "filename", "filepath"]; -const CONTENT_KEYS: [&str; 6] = ["content", "contents", "text", "file_text", "code", "body"]; -const OLD_KEYS: [&str; 6] = ["old_text", "old_str", "old_string", "old", "search", "find"]; -const NEW_KEYS: [&str; 6] = ["new_text", "new_str", "new_string", "new", "replace", "replacement"]; -pub const COMMAND_KEYS: [&str; 3] = ["command", "cmd", "script"]; -pub const MESSAGE_KEYS: [&str; 3] = ["message", "commit_message", "msg"]; -pub const BRANCH_KEYS: [&str; 3] = ["branch", "branch_name", "new_branch"]; -pub const TITLE_KEYS: [&str; 2] = ["title", "pr_title"]; -pub const BODY_KEYS: [&str; 3] = ["body", "description", "pr_body"]; -const QUERY_KEYS: [&str; 4] = ["query", "pattern", "text", "q"]; - -pub fn describe(kind: ToolKind, args: &Value) -> String { - match kind { - ToolKind::Run => arg(args, &COMMAND_KEYS).unwrap_or_default().trim().to_string(), - ToolKind::Search => arg(args, &QUERY_KEYS).unwrap_or_default().to_string(), - ToolKind::Commit => arg(args, &MESSAGE_KEYS).unwrap_or_default().lines().next().unwrap_or_default().trim().to_string(), - ToolKind::PullRequest => arg(args, &TITLE_KEYS).unwrap_or_default().trim().to_string(), - _ => { - let path = arg(args, &PATH_KEYS).unwrap_or_default().trim().replace('\\', "/"); - if path.is_empty() && kind == ToolKind::List { ".".into() } else { path } - } - } -} - -fn same_or_inside(path: &Path, root: &Path) -> bool { - let path = path.to_string_lossy().to_lowercase().replace('/', "\\"); - let root = root.to_string_lossy().to_lowercase().replace('/', "\\"); - let root = root.trim_end_matches('\\'); - path == root || path.starts_with(&format!("{root}\\")) -} - -pub fn resolve_path(root: &Path, rel: &str) -> Result { - let rel = rel.trim().trim_matches('"'); - let candidate = Path::new(rel); - let joined = if candidate.is_absolute() { candidate.to_path_buf() } else { root.join(candidate) }; - let mut out = PathBuf::new(); - for component in joined.components() { - match component { - Component::ParentDir => { - if !out.pop() { - return Err(outside()); - } - } - Component::CurDir => {} - other => out.push(other), - } - } - if same_or_inside(&out, root) { Ok(out) } else { Err(outside()) } -} - -fn outside() -> String { - "That path is outside the project. Use a path relative to the project root, such as \"src/main.rs\".".into() -} - -pub fn display(root: &Path, path: &Path) -> String { - path.strip_prefix(root).map(|rel| rel.to_string_lossy().replace('\\', "/")).unwrap_or_else(|_| path.to_string_lossy().into_owned()) -} - -fn ignored(name: &str) -> bool { - IGNORED.contains(&name) -} - -fn sorted_entries(dir: &Path) -> Vec<(String, PathBuf, bool)> { - let Ok(read) = fs::read_dir(dir) else { return Vec::new() }; - let mut entries: Vec<_> = read - .filter_map(Result::ok) - .map(|e| { - let is_dir = e.file_type().is_ok_and(|t| t.is_dir()); - (e.file_name().to_string_lossy().into_owned(), e.path(), is_dir) - }) - .collect(); - entries.sort_by(|a, b| b.2.cmp(&a.2).then_with(|| a.0.to_lowercase().cmp(&b.0.to_lowercase()))); - entries -} - -pub fn list(root: &Path, args: &Value) -> Result { - let dir = resolve_path(root, arg(args, &PATH_KEYS).unwrap_or_default())?; - if !dir.is_dir() { - return Err(format!("{} is not a folder.", display(root, &dir))); - } - let mut lines = Vec::new(); - let mut more = 0; - walk_tree(&dir, 0, 3, &mut lines, &mut more); - if lines.is_empty() { - return Ok("The folder is empty.".into()); - } - if more > 0 { - lines.push(format!("... and {more} more entries. List a subfolder to see them.")); - } - Ok(lines.join("\n")) -} - -fn walk_tree(dir: &Path, depth: usize, max_depth: usize, lines: &mut Vec, more: &mut usize) { - for (name, path, is_dir) in sorted_entries(dir) { - if lines.len() >= MAX_LIST { - *more += 1; - continue; - } - let indent = " ".repeat(depth); - if is_dir { - if ignored(&name) { - lines.push(format!("{indent}{name}/ (skipped)")); - continue; - } - lines.push(format!("{indent}{name}/")); - if depth + 1 < max_depth { - walk_tree(&path, depth + 1, max_depth, lines, more); - } - } else { - lines.push(format!("{indent}{name}")); - } - } -} - -fn read_text(path: &Path) -> Result { - let bytes = fs::read(path).map_err(|e| e.to_string())?; - if bytes.iter().take(8192).any(|b| *b == 0) { - return Err("That is a binary file, so it cannot be shown as text.".into()); - } - Ok(String::from_utf8_lossy(&bytes).into_owned()) -} - -pub fn read(root: &Path, args: &Value) -> Result { - let rel = arg(args, &PATH_KEYS).ok_or("read_file needs a \"path\".")?; - let path = resolve_path(root, rel)?; - if !path.is_file() { - return Err(format!("{} does not exist. Use list_files to see what is there.", display(root, &path))); - } - let text = read_text(&path)?; - let lines: Vec<&str> = text.lines().collect(); - if lines.is_empty() { - return Ok("The file is empty.".into()); - } - let start = arg_number(args, &["start_line", "start", "from"]).unwrap_or(1).max(1) as usize; - let end = - arg_number(args, &["end_line", "end", "to"]).map_or(lines.len(), |e| e as usize).min(lines.len()).min(start + MAX_READ_LINES - 1); - if start > lines.len() { - return Err(format!("The file only has {} lines.", lines.len())); - } - let mut out: Vec = (start..=end).map(|n| format!("{n:>5} {}", lines[n - 1])).collect(); - if end < lines.len() || start > 1 { - out.push(format!("(showing lines {start}-{end} of {}; pass start_line to read more)", lines.len())); - } - Ok(out.join("\n")) -} - -fn walk_files(dir: &Path, files: &mut Vec) { - for (name, path, is_dir) in sorted_entries(dir) { - if files.len() >= 5000 { - return; - } - if is_dir { - if !ignored(&name) { - walk_files(&path, files); - } - } else { - files.push(path); - } - } -} - -pub fn search(root: &Path, args: &Value) -> Result { - let query = arg(args, &QUERY_KEYS).filter(|q| !q.trim().is_empty()).ok_or("search needs a \"query\".")?; - let dir = resolve_path(root, arg(args, &PATH_KEYS).unwrap_or_default())?; - let needle = query.to_lowercase(); - let mut files = Vec::new(); - walk_files(&dir, &mut files); - let mut matches = Vec::new(); - let mut extra = 0; - for file in files { - if fs::metadata(&file).map_or(true, |m| m.len() > 1_000_000) { - continue; - } - let Ok(text) = read_text(&file) else { continue }; - for (index, line) in text.lines().enumerate() { - if line.to_lowercase().contains(&needle) { - if matches.len() < MAX_MATCHES { - let shown: String = line.trim().chars().take(200).collect(); - matches.push(format!("{}:{}: {shown}", display(root, &file), index + 1)); - } else { - extra += 1; - } - } - } - } - if matches.is_empty() { - return Ok(format!("No matches for \"{query}\".")); - } - if extra > 0 { - matches.push(format!("... and {extra} more matches. Narrow the search with a longer query or a path.")); - } - Ok(matches.join("\n")) -} - -pub struct Change { - pub path: PathBuf, - pub after: String, - pub diff: FileDiff, -} - -pub fn plan_change(root: &Path, kind: ToolKind, args: &Value) -> Result { - let rel = arg(args, &PATH_KEYS).ok_or(format!("{} needs a \"path\".", kind.name()))?; - let path = resolve_path(root, rel)?; - if path.is_dir() { - return Err(format!("{} is a folder, not a file.", display(root, &path))); - } - let before = if path.is_file() { Some(read_text(&path)?) } else { None }; - let after = match kind { - ToolKind::Write => arg(args, &CONTENT_KEYS).ok_or("write_file needs \"content\": the complete text of the file.")?.to_string(), - _ => { - let current = before.as_deref().ok_or(format!("{} does not exist. Use write_file to create it.", display(root, &path)))?; - let old = arg(args, &OLD_KEYS).ok_or("edit_file needs \"old_text\", copied exactly from the file.")?; - let new = arg(args, &NEW_KEYS).ok_or("edit_file needs \"new_text\". Use an empty string to delete.")?; - replace(current, old, new, arg_bool(args, "replace_all"))? - } - }; - let diff = diff_text(&display(root, &path), before.as_deref(), &after); - Ok(Change { path, after, diff }) -} - -fn replace(current: &str, old: &str, new: &str, all: bool) -> Result { - if old.is_empty() { - return Err("old_text is empty. Copy the exact text you want to replace from the file.".into()); - } - let crlf = current.contains("\r\n") && !old.contains("\r\n"); - let (old, new) = if crlf { (old.replace('\n', "\r\n"), new.replace('\n', "\r\n")) } else { (old.to_string(), new.to_string()) }; - match current.matches(old.as_str()).count() { - 0 => Err("old_text was not found in the file. Read the file again and copy the text exactly, including indentation.".into()), - 1 => Ok(current.replacen(old.as_str(), &new, 1)), - _ if all => Ok(current.replace(old.as_str(), &new)), - n => Err(format!("old_text appears {n} times. Include more surrounding lines so it is unique, or set replace_all.")), - } -} - -pub fn apply(change: &Change) -> Result<(), String> { - if let Some(dir) = change.path.parent() { - fs::create_dir_all(dir).map_err(|e| e.to_string())?; - } - fs::write(&change.path, &change.after).map_err(|e| e.to_string()) -} - -pub fn command_timeout(args: &Value) -> Duration { - Duration::from_secs(arg_number(args, &["timeout_seconds", "timeout"]).unwrap_or(120).clamp(1, 600)) -} - -pub fn shell_name() -> &'static str { - if cfg!(windows) { "PowerShell" } else { "sh" } -} - -pub fn os_name() -> &'static str { - match std::env::consts::OS { - "windows" => "Windows", - "macos" => "macOS", - "linux" => "Linux", - other => other, - } -} - -fn shell(command: &str) -> Command { - if cfg!(windows) { - let mut cmd = Command::new("powershell"); - cmd.args([ - "-NoLogo", - "-NoProfile", - "-NonInteractive", - "-ExecutionPolicy", - "Bypass", - "-Command", - &format!("[Console]::OutputEncoding=[Text.Encoding]::UTF8; $ProgressPreference='SilentlyContinue'; {command}"), - ]); - hide_window(&mut cmd); - cmd - } else { - let mut cmd = Command::new("sh"); - cmd.args(["-c", command]); - cmd - } -} - -#[cfg(windows)] -fn hide_window(cmd: &mut Command) { - use std::os::windows::process::CommandExt; - cmd.creation_flags(0x0800_0000); -} - -#[cfg(not(windows))] -fn hide_window(_: &mut Command) {} - -fn cap(text: String) -> String { - if text.len() <= MAX_OUTPUT { - return text; - } - let mut head = MAX_OUTPUT * 2 / 3; - while !text.is_char_boundary(head) { - head -= 1; - } - let mut tail = text.len() - MAX_OUTPUT / 3; - while !text.is_char_boundary(tail) { - tail += 1; - } - format!("{}\n... [output cut] ...\n{}", &text[..head], &text[tail..]) -} - -pub fn run(root: &Path, command: &str, timeout: Duration, cancel: &AtomicBool) -> (bool, String) { - let child = shell(command).current_dir(root).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn(); - let mut child = match child { - Ok(child) => child, - Err(e) => return (false, format!("The command could not start: {e}")), - }; - let mut stdout = child.stdout.take(); - let mut stderr = child.stderr.take(); - let out = std::thread::spawn(move || { - let mut buf = Vec::new(); - if let Some(s) = stdout.as_mut() { - let _ = s.read_to_end(&mut buf); - } - buf - }); - let err = std::thread::spawn(move || { - let mut buf = Vec::new(); - if let Some(s) = stderr.as_mut() { - let _ = s.read_to_end(&mut buf); - } - buf - }); - let started = Instant::now(); - let (status, note) = loop { - match child.try_wait() { - Ok(Some(status)) => break (Some(status), None), - Ok(None) if cancel.load(Ordering::Relaxed) => { - let _ = child.kill(); - break (None, Some("Stopped by the user.".to_string())); - } - Ok(None) if started.elapsed() > timeout => { - let _ = child.kill(); - break (None, Some(format!("Stopped after {} seconds without finishing.", timeout.as_secs()))); - } - Ok(None) => std::thread::sleep(Duration::from_millis(50)), - Err(e) => break (None, Some(e.to_string())), - } - }; - let _ = child.wait(); - let mut text = String::from_utf8_lossy(&out.join().unwrap_or_default()).into_owned(); - let err_text = String::from_utf8_lossy(&err.join().unwrap_or_default()).into_owned(); - if !err_text.trim().is_empty() { - if !text.is_empty() && !text.ends_with('\n') { - text.push('\n'); - } - text.push_str(&err_text); - } - let text = text.trim_end().to_string(); - let ok = status.is_some_and(|s| s.success()); - let mut report = match (status.and_then(|s| s.code()), note) { - (_, Some(note)) => note, - (Some(code), None) => format!("Exit code {code}"), - (None, None) => "Exited".into(), - }; - if !text.is_empty() { - report.push('\n'); - report.push_str(&text); - } - (ok, cap(report)) -} - -#[cfg(test)] -mod tests { - use super::*; - - fn temp_root(name: &str) -> PathBuf { - let dir = std::env::temp_dir().join(format!("quill-tools-{name}-{}", std::process::id())); - let _ = fs::remove_dir_all(&dir); - fs::create_dir_all(&dir).unwrap(); - dir - } - - #[test] - fn aliases_resolve_to_tools() { - assert_eq!(ToolKind::resolve("bash"), Some(ToolKind::Run)); - assert_eq!(ToolKind::resolve("str_replace"), Some(ToolKind::Edit)); - assert_eq!(ToolKind::resolve("Read-File"), Some(ToolKind::Read)); - assert_eq!(ToolKind::resolve("teleport"), None); - } - - #[test] - fn paths_cannot_leave_the_project() { - let root = PathBuf::from(r"C:\work\proj"); - assert!(resolve_path(&root, "src/main.rs").is_ok()); - assert!(resolve_path(&root, "../other").is_err()); - assert!(resolve_path(&root, r"C:\Windows\System32").is_err()); - assert!(resolve_path(&root, r"c:\WORK\proj\a.txt").is_ok()); - assert!(resolve_path(&root, r"C:\work\project2\a.txt").is_err()); - } - - #[test] - fn edits_need_a_unique_match() { - assert_eq!(replace("a b a", "b", "c", false).unwrap(), "a c a"); - assert!(replace("a b a", "a", "c", false).unwrap_err().contains("2 times")); - assert_eq!(replace("a b a", "a", "c", true).unwrap(), "c b c"); - assert!(replace("x", "y", "z", false).is_err()); - assert_eq!(replace("one\r\ntwo\r\n", "one\ntwo", "1\n2", false).unwrap(), "1\r\n2\r\n"); - } - - #[test] - fn files_are_planned_then_written() { - let root = temp_root("write"); - let change = plan_change(&root, ToolKind::Write, &json!({ "path": "src/a.txt", "content": "hi\n" })).unwrap(); - assert!(change.diff.created); - apply(&change).unwrap(); - let edit = plan_change(&root, ToolKind::Edit, &json!({ "file_path": "src/a.txt", "old_str": "hi", "new_str": "hello" })).unwrap(); - assert_eq!((edit.diff.added, edit.diff.removed), (1, 1)); - apply(&edit).unwrap(); - assert_eq!(fs::read_to_string(root.join("src/a.txt")).unwrap(), "hello\n"); - let listing = list(&root, &json!({})).unwrap(); - assert!(listing.contains("src/") && listing.contains(" a.txt")); - assert!(read(&root, &json!({ "path": "src/a.txt" })).unwrap().contains(" 1 hello")); - assert!(search(&root, &json!({ "query": "HELLO" })).unwrap().contains("src/a.txt:1: hello")); - fs::remove_dir_all(&root).unwrap(); - } - - #[test] - fn commands_report_exit_codes() { - let root = temp_root("run"); - let cancel = AtomicBool::new(false); - let (ok, output) = run(&root, "echo quill", Duration::from_secs(60), &cancel); - assert!(ok, "{output}"); - assert!(output.starts_with("Exit code 0") && output.contains("quill")); - let (ok, output) = run(&root, "exit 3", Duration::from_secs(60), &cancel); - assert!(!ok); - assert!(output.starts_with("Exit code 3")); - fs::remove_dir_all(&root).unwrap(); - } - - #[test] - fn broken_arguments_are_kept_for_the_error() { - assert_eq!(parse_args("{\"path\": \"a\"}")["path"], "a"); - assert!(parse_args("{oops").get("__invalid").is_some()); - assert_eq!(parse_args(""), json!({})); - } -} \ No newline at end of file diff --git a/crates/quill-code/Cargo.toml b/crates/quill-code/Cargo.toml index 3a2ad2c..ec67376 100644 --- a/crates/quill-code/Cargo.toml +++ b/crates/quill-code/Cargo.toml @@ -8,8 +8,10 @@ publish.workspace = true [dependencies] base64 = "0.23" -quill-agent.workspace = true -quill-llama.workspace = true +quill-config.workspace = true +quill-core.workspace = true +quill-git.workspace = true +quill-providers.workspace = true quill-weave.workspace = true futures = "0.3" gpui-kit.workspace = true diff --git a/crates/quill-code/src/add_project.rs b/crates/quill-code/src/add_project.rs index 6aa563b..c6b2f7a 100644 --- a/crates/quill-code/src/add_project.rs +++ b/crates/quill-code/src/add_project.rs @@ -6,13 +6,13 @@ use gpui_kit::{ SharedString, Styled, Subscription, Window, div, prelude::*, px, }; -use crate::config::projects_dir; -use crate::git; -use crate::github::Visibility; +use crate::config::Config; use crate::icons::Icon; use crate::palette::{Palette, palette}; use crate::project; use crate::ui::{MONO, icon}; +use quill_git as git; +use quill_git::github::Visibility; pub enum AddProjectEvent { Added(PathBuf, Option), @@ -137,12 +137,16 @@ impl AddProject { let name = self.value(cx); let git_branch = self.git.then_some(branch); let visibility = self.visibility.filter(|_| self.git); - self.run(cx, move || project::create(&name, git_branch.as_deref(), visibility).map(|created| (created.path, created.note))); + let base = Config::get(cx).projects_dir(); + self.run(cx, move || { + project::create(&base, &name, git_branch.as_deref(), visibility).map(|created| (created.path, created.note)) + }); } Step::GitUrl => { let url = self.value(cx); if !url.is_empty() { - self.run(cx, move || project::clone(&url).map(|path| (path, None))); + let base = Config::get(cx).projects_dir(); + self.run(cx, move || project::clone(&base, &url).map(|path| (path, None))); } } } @@ -300,7 +304,7 @@ fn key_hint(key: &'static str, label: &'static str, p: Palette) -> impl IntoElem impl Render for AddProject { fn render(&mut self, window: &mut Window, cx: &mut Context) -> impl IntoElement { let p = palette(cx); - let home = projects_dir().display().to_string(); + let home = Config::get(cx).projects_dir().display().to_string(); let body = match self.step { Step::Sources => { let sources = self.sources(cx); diff --git a/crates/quill-code/src/backend.rs b/crates/quill-code/src/backend.rs index 2a3bdcb..8779732 100644 --- a/crates/quill-code/src/backend.rs +++ b/crates/quill-code/src/backend.rs @@ -1,5 +1,14 @@ +use std::collections::HashMap; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::sync::atomic::AtomicBool; + use gpui_kit::{App, Context, SharedString}; -use quill_llama::{Model, Props, Server, Thinking, guess_thinking, normalize_url}; +use quill_config::{LOCAL_PORTS, ModelRef, Price, Provider as ProviderConfig, ProviderKind, api_key, claude_latest, default_price}; +use quill_core::{ClaudeCode, Engine, claude_complete, claude_version, find_claude}; +use quill_providers::{ + Anthropic, ChatRequest, Effort, Event, Message, Model, OpenAi, Props, Provider, Status, Thinking, guess_thinking, normalize_url, +}; use crate::config::Config; @@ -8,120 +17,458 @@ pub enum Connection { Checking, Online, Offline(SharedString), + NeedsKey, + Off, } -pub struct Backend { +#[derive(Clone)] +pub struct Source { + pub config: ProviderConfig, pub connection: Connection, pub models: Vec, - props: Option<(String, Props)>, + pub detail: Option, + key: Option, + binary: Option, +} + +impl Source { + pub fn ready(&self) -> bool { + self.connection == Connection::Online + } + + pub fn status(&self) -> SharedString { + match &self.connection { + Connection::Checking => "Connecting".into(), + Connection::Online if self.config.kind == ProviderKind::ClaudeCode => { + format!("Claude Code {} · your Claude plan", self.detail.clone().unwrap_or_default()).into() + } + Connection::Online => { + let count = self.models.len(); + format!("{count} {}", if count == 1 { "model" } else { "models" }).into() + } + Connection::Offline(error) => error.clone(), + Connection::NeedsKey => "Add an API key to use it".into(), + Connection::Off => "Turned off".into(), + } + } +} + +#[derive(Clone, PartialEq)] +pub enum Control { + None, + Toggle, + Effort(Vec), +} + +#[derive(Clone)] +pub enum Writer { + Model { provider: Arc, model: String, effort: Option }, + Claude { binary: PathBuf, model: String }, +} + +impl Writer { + pub fn write(&self, system: &str, user: &str) -> Result { + match self { + Writer::Model { provider, model, effort } => { + let request = ChatRequest { + model: model.clone(), + messages: vec![Message::system(system), Message::user(user)], + thinking: Some(false), + effort: *effort, + ..ChatRequest::default() + }; + let mut text = String::new(); + provider + .stream(&request, &AtomicBool::new(false), &mut |event| { + if let Event::Content(chunk) = event { + text.push_str(&chunk); + } + }) + .map_err(|e| e.to_string())?; + Ok(match text.rfind("") { + Some(end) => text[end + 8..].trim().to_string(), + None => text.trim().to_string(), + }) + } + Writer::Claude { binary, model } => claude_complete(binary, model, &format!("{system}\n\n{user}")), + } + } +} + +struct Found { + connection: Connection, + models: Vec, + detail: Option, + key: Option, + binary: Option, +} + +impl Found { + fn offline(error: impl Into) -> Found { + Found { connection: Connection::Offline(error.into()), models: Vec::new(), detail: None, key: None, binary: None } + } + + fn listed(result: Result, quill_providers::Error>, key: Option) -> Found { + match result { + Ok(models) => Found { connection: Connection::Online, models, detail: None, key, binary: None }, + Err(error) => Found::offline(error.to_string()), + } + } +} + +pub fn claude_label(id: &str) -> String { + let mut words = vec!["Claude".to_string()]; + let mut version = Vec::new(); + for part in id.trim_start_matches("claude-").split('-') { + if part.chars().all(|c| c.is_ascii_digit()) { + if part.len() <= 2 { + version.push(part); + } + } else { + let mut chars = part.chars(); + words.extend(chars.next().map(|first| format!("{}{}", first.to_uppercase(), chars.as_str()))); + } + } + if !version.is_empty() { + words.push(version.join(".")); + } + words.join(" ") +} + +fn names_path() -> std::path::PathBuf { + quill_config::app_dir().join("claude-models.json") +} + +fn load_names() -> HashMap { + std::fs::read_to_string(names_path()).ok().and_then(|text| serde_json::from_str(&text).ok()).unwrap_or_default() +} + +fn probe(config: &ProviderConfig, names: &HashMap) -> Found { + match config.kind { + ProviderKind::Local => Found::listed(OpenAi::new(&config.url).models(), None), + ProviderKind::OpenAi | ProviderKind::Anthropic => { + let Some(key) = api_key(config) else { + return Found { connection: Connection::NeedsKey, ..Found::offline("") }; + }; + let result = match config.kind { + ProviderKind::OpenAi => OpenAi::cloud(&config.url, Some(key.clone())).models(), + _ => Anthropic::new(&config.url, &key).models(), + }; + Found::listed(result, Some(key)) + } + ProviderKind::ClaudeCode => { + let configured = Some(Path::new(config.url.trim())).filter(|path| !path.as_os_str().is_empty()); + let Some(binary) = find_claude(configured) else { + return Found::offline("Claude Code is not installed. Install it, sign in once in a terminal, then refresh."); + }; + let Some(version) = claude_version(&binary) else { + return Found::offline(format!("{} did not answer.", binary.display())); + }; + let models = config + .models + .iter() + .map(|alias| Model { + name: Some(claude_label(names.get(alias).map(String::as_str).or(claude_latest(alias)).unwrap_or(alias))), + vision: true, + efforts: Effort::ALL.to_vec(), + ..Model::new(alias.clone()) + }) + .collect(); + Found { connection: Connection::Online, models, detail: Some(version), key: None, binary: Some(binary) } + } + } +} + +pub struct Backend { + pub sources: Vec, + props: Option<(ModelRef, Props)>, + windows: HashMap, + names: HashMap, + generation: usize, } impl Backend { pub fn new(cx: &mut Context) -> Self { - let mut backend = Backend { connection: Connection::Checking, models: Vec::new(), props: None }; + let mut backend = Backend { sources: Vec::new(), props: None, windows: HashMap::new(), names: load_names(), generation: 0 }; backend.refresh(cx); backend } - pub fn url(cx: &App) -> String { - Config::get(cx).server_url.clone() + pub fn selected_ref(cx: &App) -> Option { + Config::get(cx).models.selected.clone() + } + + pub fn source(&self, id: &str) -> Option<&Source> { + self.sources.iter().find(|source| source.config.id == id) } - pub fn selected_id(cx: &App) -> Option { - Config::get(cx).model.clone() + pub fn find(&self, model: &ModelRef) -> Option<(&Source, &Model)> { + let source = self.source(&model.provider)?; + source.models.iter().find(|m| m.id == model.model).map(|m| (source, m)) } - pub fn selected<'a>(&'a self, cx: &App) -> Option<&'a Model> { - let id = Self::selected_id(cx)?; - self.models.iter().find(|m| m.id == id) + pub fn selected(&self, cx: &App) -> Option<(&Source, &Model)> { + self.find(&Self::selected_ref(cx)?) + } + + pub fn effective(&self, model: &ModelRef, cx: &App) -> Option { + let (_, found) = self.find(model)?; + let mut found = found.clone(); + if let Some(window) = self.windows.get(model) { + found.context = Some(*window); + } + if let Some(props) = self.props.as_ref().filter(|(r, _)| r == model).map(|(_, props)| props) { + found.context = props.context.or(found.context); + found.vision |= props.vision; + } + if let Some(over) = Config::get(cx).models.override_for(model) { + found.context = over.context.or(found.context); + found.max_output = over.max_output.or(found.max_output); + found.vision = over.vision.unwrap_or(found.vision); + } + Some(found) } pub fn refresh(&mut self, cx: &mut Context) { - self.connection = Connection::Checking; + let providers = Config::get(cx).models.providers.clone(); + self.generation += 1; + let generation = self.generation; + let previous = std::mem::take(&mut self.sources); + self.sources = providers + .into_iter() + .map(|config| { + let old = previous.iter().find(|s| s.config.id == config.id && s.config.kind == config.kind && s.config.url == config.url); + Source { + connection: if config.enabled { Connection::Checking } else { Connection::Off }, + models: old.filter(|_| config.enabled).map(|s| s.models.clone()).unwrap_or_default(), + detail: old.and_then(|s| s.detail.clone()), + key: old.and_then(|s| s.key.clone()), + binary: old.and_then(|s| s.binary.clone()), + config, + } + }) + .collect(); cx.notify(); - let url = Self::url(cx); - let task = cx.background_executor().spawn(async move { Server::new(&url).models() }); - cx.spawn(async move |this, cx| { - let result = task.await; - _ = this.update(cx, |this, cx| { - match result { - Ok(models) => { - this.models = models; - this.connection = Connection::Online; - if let Some(model) = this.selected(cx).filter(|m| m.status == quill_llama::Status::Loaded) { - let id = model.id.clone(); - this.fetch_props(id, cx); - } + for source in self.sources.iter().filter(|s| s.config.enabled) { + let config = source.config.clone(); + let id = config.id.clone(); + let names = self.names.clone(); + let task = cx.background_executor().spawn(async move { probe(&config, &names) }); + cx.spawn(async move |this, cx| { + let found = task.await; + _ = this.update(cx, |this, cx| { + if this.generation != generation { + return; } - Err(error) => { - this.models.clear(); - this.connection = Connection::Offline(error.to_string().into()); + let Some(source) = this.sources.iter_mut().find(|s| s.config.id == id) else { return }; + source.connection = found.connection; + source.models = found.models; + source.detail = found.detail; + source.key = found.key; + source.binary = found.binary; + let kind = source.config.kind; + if let Some(selected) = Self::selected_ref(cx).filter(|r| r.provider == id && kind == ProviderKind::Local) { + let loaded = this.find(&selected).is_some_and(|(_, m)| m.status == Status::Loaded); + if loaded { + this.fetch_props(selected, cx); + } } - } - cx.notify(); - }); - }) - .detach(); + cx.notify(); + }); + }) + .detach(); + } } - pub fn set_url(&mut self, url: &str, cx: &mut Context) { - let url = normalize_url(url); - Config::update(cx, |config| config.server_url = url); + pub fn select(&mut self, model: ModelRef, cx: &mut Context) { + Config::update(cx, |config| config.models.selected = Some(model.clone())); self.props = None; - self.refresh(cx); + if self.source(&model.provider).is_some_and(|s| s.config.kind == ProviderKind::Local) { + self.fetch_props(model, cx); + } + cx.notify(); } - pub fn select(&mut self, id: String, cx: &mut Context) { - Config::update(cx, |config| config.model = Some(id.clone())); - self.props = None; - self.fetch_props(id, cx); + pub fn set_thinking(&mut self, on: bool, cx: &mut Context) { + Config::update(cx, |config| config.models.thinking = on); cx.notify(); } - pub fn set_thinking(&mut self, on: bool, cx: &mut Context) { - Config::update(cx, |config| config.thinking = on); + pub fn set_effort(&mut self, effort: Effort, cx: &mut Context) { + Config::update(cx, |config| config.models.effort = effort); cx.notify(); } - pub fn thinking(&self, cx: &App) -> Thinking { - let Some(id) = Self::selected_id(cx) else { return Thinking::None }; - match &self.props { - Some((props_id, props)) if *props_id == id => props.thinking, - _ => guess_thinking(&id), + pub fn control(&self, cx: &App) -> Control { + let Some(selected) = Self::selected_ref(cx) else { return Control::None }; + let Some((source, model)) = self.find(&selected) else { return Control::None }; + if !model.efforts.is_empty() { + return Control::Effort(model.efforts.clone()); } + if source.config.kind != ProviderKind::Local { + return Control::None; + } + let thinking = match &self.props { + Some((r, props)) if *r == selected => props.thinking, + _ => guess_thinking(&model.id), + }; + if thinking == Thinking::Toggle { Control::Toggle } else { Control::None } } pub fn request_thinking(&self, cx: &App) -> Option { - (self.thinking(cx) == Thinking::Toggle).then(|| Config::get(cx).thinking) + (self.control(cx) == Control::Toggle).then(|| Config::get(cx).models.thinking) } - pub fn mark_used(&mut self, id: &str, cx: &mut Context) { - let needs_props = !matches!(&self.props, Some((props_id, _)) if props_id == id); - if let Some(model) = self.models.iter_mut().find(|m| m.id == id) { - model.status = quill_llama::Status::Loaded; + pub fn request_effort(&self, cx: &App) -> Option { + match self.control(cx) { + Control::Effort(levels) => Config::get(cx).models.effort.nearest(&levels), + _ => None, } - if needs_props { - self.fetch_props(id.to_string(), cx); + } + + pub fn engine(&self, model: &ModelRef) -> Result { + let source = self.source(&model.provider).ok_or("That model's provider was removed. Choose another model.")?; + let config = &source.config; + let key = || source.key.clone().ok_or_else(|| format!("{} needs an API key. Add one in Settings, Models.", config.name)); + Ok(match config.kind { + ProviderKind::Local => Engine::Model(Arc::new(OpenAi::new(&config.url))), + ProviderKind::OpenAi => Engine::Model(Arc::new(OpenAi::cloud(&config.url, Some(key()?)))), + ProviderKind::Anthropic => Engine::Model(Arc::new(Anthropic::new(&config.url, &key()?).with_fallback(config.fallback))), + ProviderKind::ClaudeCode => { + let binary = source.binary.clone().ok_or("Claude Code was not found. Install it, then refresh the model list.")?; + Engine::ClaudeCode(ClaudeCode { binary, resume: None }) + } + }) + } + + pub fn writer(&self, model: &ModelRef, cx: &App) -> Result { + let effort = self.effective(model, cx).and_then(|m| Effort::Low.nearest(&m.efforts)); + Ok(match self.engine(model)? { + Engine::Model(provider) => Writer::Model { provider, model: model.model.clone(), effort }, + Engine::ClaudeCode(claude) => Writer::Claude { binary: claude.binary, model: model.model.clone() }, + }) + } + + pub fn price(&self, model: &ModelRef, cx: &App) -> Option { + if let Some(price) = Config::get(cx).models.override_for(model).and_then(|o| o.price) { + return Some(price); + } + let kind = self.source(&model.provider)?.config.kind; + if kind == ProviderKind::Anthropic { default_price(&model.model) } else { None } + } + + pub fn learn_model(&mut self, model: &ModelRef, resolved: &str, cx: &mut Context) { + let claude = self.source(&model.provider).is_some_and(|s| s.config.kind == ProviderKind::ClaudeCode); + if !claude || self.names.get(&model.model).map(String::as_str) == Some(resolved) { + return; + } + self.names.insert(model.model.clone(), resolved.to_string()); + if let Ok(text) = serde_json::to_string_pretty(&self.names) { + let _ = std::fs::write(names_path(), text); + } + let found = + self.sources.iter_mut().find(|s| s.config.id == model.provider).and_then(|s| s.models.iter_mut().find(|m| m.id == model.model)); + if let Some(found) = found { + found.name = Some(claude_label(resolved)); + } + cx.notify(); + } + + pub fn learn_window(&mut self, model: &ModelRef, tokens: u64, cx: &mut Context) { + if self.windows.insert(model.clone(), tokens) != Some(tokens) { + cx.notify(); + } + } + + pub fn mark_used(&mut self, model: &ModelRef, cx: &mut Context) { + let local = self.source(&model.provider).is_some_and(|s| s.config.kind == ProviderKind::Local); + if !local { + return; + } + if let Some(found) = + self.sources.iter_mut().find(|s| s.config.id == model.provider).and_then(|s| s.models.iter_mut().find(|m| m.id == model.model)) + { + found.status = Status::Loaded; + } + if !matches!(&self.props, Some((r, _)) if r == model) { + self.fetch_props(model.clone(), cx); } cx.notify(); } - fn fetch_props(&mut self, id: String, cx: &mut Context) { - let url = Self::url(cx); - let wanted = id.clone(); - let task = cx.background_executor().spawn(async move { Server::new(&url).props(&wanted) }); + fn fetch_props(&mut self, model: ModelRef, cx: &mut Context) { + let Some(url) = self.source(&model.provider).map(|s| s.config.url.clone()) else { return }; + let wanted = model.model.clone(); + let task = cx.background_executor().spawn(async move { OpenAi::new(&url).props(&wanted) }); cx.spawn(async move |this, cx| { if let Ok(props) = task.await { _ = this.update(cx, |this, cx| { - if let Some(model) = this.models.iter_mut().find(|m| m.id == id) { - model.status = quill_llama::Status::Loaded; - model.context = props.context.or(model.context); + let found = this + .sources + .iter_mut() + .find(|s| s.config.id == model.provider) + .and_then(|s| s.models.iter_mut().find(|m| m.id == model.model)); + if let Some(found) = found { + found.status = Status::Loaded; } - this.props = Some((id, props)); + this.props = Some((model, props)); cx.notify(); }); } }) .detach(); } + + pub fn scan(&mut self, cx: &mut Context) -> gpui_kit::Task { + let known: Vec = Config::get(cx).models.providers.iter().map(|p| normalize_url(&p.url)).collect(); + let task = cx.background_executor().spawn(async move { + let urls: Vec = + LOCAL_PORTS.iter().map(|port| format!("http://127.0.0.1:{port}")).filter(|url| !known.contains(url)).collect(); + std::thread::scope(|scope| { + let checks: Vec<_> = urls.iter().map(|url| scope.spawn(move || OpenAi::new(url).models().is_ok())).collect(); + urls.iter().zip(checks).filter_map(|(url, check)| check.join().unwrap_or(false).then(|| url.clone())).collect::>() + }) + }); + cx.spawn(async move |this, cx| { + let found = task.await; + let count = found.len(); + _ = this.update(cx, |this, cx| { + if count == 0 { + return; + } + Config::update(cx, |config| { + for url in found { + let id = config.models.fresh_id(ProviderKind::Local); + let port = url.rsplit(':').next().unwrap_or_default().to_string(); + let mut provider = ProviderConfig::new(&id, &format!("Local server on {port}"), ProviderKind::Local); + provider.url = url; + config.models.providers.push(provider); + } + }); + this.refresh(cx); + }); + count + }) + } +} +pub fn provider_icon(kind: ProviderKind) -> crate::icons::Icon { + use crate::icons::Icon; + match kind { + ProviderKind::Local => Icon::Server, + ProviderKind::OpenAi => Icon::OpenAi, + ProviderKind::Anthropic | ProviderKind::ClaudeCode => Icon::Claude, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn claude_models_read_with_their_version() { + assert_eq!(claude_label("claude-haiku-5-5"), "Claude Haiku 5.5"); + assert_eq!(claude_label("claude-haiku-4-5-20251001"), "Claude Haiku 4.5"); + assert_eq!(claude_label("claude-fable-5-1"), "Claude Fable 5.1"); + assert_eq!(claude_label("opus"), "Claude Opus"); + } } \ No newline at end of file diff --git a/crates/quill-code/src/commit_dialog.rs b/crates/quill-code/src/commit_dialog.rs index 344fda6..d2be604 100644 --- a/crates/quill-code/src/commit_dialog.rs +++ b/crates/quill-code/src/commit_dialog.rs @@ -1,21 +1,19 @@ use std::collections::HashSet; use std::path::PathBuf; -use std::sync::atomic::AtomicBool; -use gpui_kit::component::input::{Input, InputState, Textarea, TextareaState}; -use gpui_kit::{ - Context, Div, Entity, EventEmitter, FontWeight, IntoElement, MouseButton, ParentElement, Render, SharedString, Stateful, Styled, - Window, div, prelude::*, px, -}; -use quill_llama::{ChatRequest, Event, Message, Server}; - -use crate::git::{self, FileStatus}; -use crate::github::{self, Visibility}; +use crate::backend::Writer; use crate::icons::Icon; use crate::palette::{Palette, palette}; use crate::project; use crate::thread_view::file_icon; use crate::ui::{MONO, icon}; +use gpui_kit::component::input::{Input, InputState, Textarea, TextareaState}; +use gpui_kit::{ + Context, Div, Entity, EventEmitter, FontWeight, IntoElement, MouseButton, ParentElement, Render, SharedString, Stateful, Styled, + Window, div, prelude::*, px, +}; +use quill_git::github::{self, Visibility}; +use quill_git::{self as git, FileStatus}; pub enum CommitEvent { Close, @@ -43,14 +41,13 @@ pub struct CommitDialog { new_branch: Option>, stage: Stage, error: Option, - server_url: String, - model: Option, + writer: Result, } impl EventEmitter for CommitDialog {} impl CommitDialog { - pub fn new(root: PathBuf, server_url: String, model: Option, window: &mut Window, cx: &mut Context) -> Self { + pub fn new(root: PathBuf, writer: Result, window: &mut Window, cx: &mut Context) -> Self { let message = cx.new(|cx| { TextareaState::new(window, cx) .placeholder("Describe the change, or leave this empty and the model will write it") @@ -74,8 +71,7 @@ impl CommitDialog { new_branch: None, stage: Stage::Ready, error, - server_url, - model, + writer, } } @@ -121,7 +117,7 @@ impl CommitDialog { return; } let message = self.message.read(cx).value().trim().to_string(); - let (root, url, model) = (self.root.clone(), self.server_url.clone(), self.model.clone()); + let (root, writer) = (self.root.clone(), self.writer.clone()); self.error = None; self.stage = Stage::Working(if message.is_empty() { "Writing a commit message" } else { "Committing" }); cx.notify(); @@ -130,7 +126,7 @@ impl CommitDialog { git::create_branch(&root, name)?; } git::stage(&root, &files)?; - let message = if message.is_empty() { write_message(&root, &url, model.as_deref())? } else { message }; + let message = if message.is_empty() { write_message(&root, writer)? } else { message }; let sha = git::commit(&root, &files, &message)?; Ok::<_, String>((sha, git::branch(&root).unwrap_or_default())) }); @@ -264,31 +260,10 @@ impl CommitDialog { } } -fn write_message(root: &std::path::Path, url: &str, model: Option<&str>) -> Result { - let model = model.ok_or("Choose a model first, or type a commit message yourself.")?; - let request = ChatRequest { - model: model.to_string(), - messages: vec![ - Message::system( - "You write git commit messages. Reply with the message only: one summary line in the imperative mood under 72 characters, then, only if it helps, a blank line and a few short bullet points.", - ), - Message::user(git::staged_diff(root, 12_000)), - ], - thinking: Some(false), - tools: Vec::new(), - }; - let mut text = String::new(); - Server::new(url) - .stream_chat(&request, &AtomicBool::new(false), |event| { - if let Event::Content(chunk) = event { - text.push_str(&chunk); - } - }) - .map_err(|e| e.to_string())?; - let text = match text.rfind("") { - Some(end) => text[end + 8..].to_string(), - None => text, - }; +const COMMIT_SYSTEM: &str = "You write git commit messages. Reply with the message only: one summary line in the imperative mood under 72 characters, then, only if it helps, a blank line and a few short bullet points."; + +fn write_message(root: &std::path::Path, writer: Result) -> Result { + let text = writer?.write(COMMIT_SYSTEM, &git::staged_diff(root, 12_000))?; let text = text.trim().trim_matches('`').trim().to_string(); if text.is_empty() { Err("The model returned an empty message. Type one yourself.".into()) } else { Ok(text) } } @@ -303,7 +278,7 @@ fn check(on: bool, p: Palette) -> Div { .rounded(px(4.)) .border_1() .border_color(if on { p.text } else { p.border }) - .when(on, |b| b.bg(p.text).child(icon(Icon::Check, 12., p.bg))) + .when(on, |b| b.bg(p.accent).border_color(p.accent).child(icon(Icon::Check, 12., p.accent_text))) } fn button(id: &'static str, label: impl Into, primary: bool, p: Palette) -> Stateful
{ @@ -319,7 +294,7 @@ fn button(id: &'static str, label: impl Into, primary: bool, p: Pa .cursor_pointer() .map(|b| { if primary { - b.bg(p.text).text_color(p.bg).font_weight(FontWeight::SEMIBOLD).hover(|s| s.opacity(0.9)) + b.bg(p.accent).text_color(p.accent_text).font_weight(FontWeight::SEMIBOLD).hover(|s| s.opacity(0.9)) } else { b.border_1().border_color(p.border).text_color(p.text).hover(move |s| s.bg(p.row_hover)) } diff --git a/crates/quill-code/src/composer.rs b/crates/quill-code/src/composer.rs index 44e1ce2..90846d0 100644 --- a/crates/quill-code/src/composer.rs +++ b/crates/quill-code/src/composer.rs @@ -1,31 +1,34 @@ +use std::collections::HashMap; use std::path::PathBuf; use gpui_kit::component::input::{Input, InputEvent, InputState, Position, Textarea, TextareaState}; use gpui_kit::{ - Anchor, App, Context, Div, Entity, EventEmitter, ExternalPaths, Focusable, FontWeight, IntoElement, KeystrokeEvent, ObjectFit, - ParentElement, PathPromptOptions, Render, SharedString, Stateful, Styled, Subscription, Window, div, img, prelude::*, px, svg, + Anchor, App, Context, Div, Entity, EventEmitter, ExternalPaths, Focusable, FontWeight, Hsla, IntoElement, KeystrokeEvent, ObjectFit, + ParentElement, PathPromptOptions, Render, SharedString, Stateful, Styled, Subscription, Window, div, img, prelude::*, px, }; -use quill_agent::{Access, Decision}; -use quill_llama::{Model, Status, Thinking, context_label}; +use quill_config::{ModelRef, ProviderKind}; +use quill_core::{Access, Decision, FileDiff}; +use quill_providers::{Model, Status, context_label}; use quill_weave::State; use crate::attachments::Attachment; -use crate::backend::{Backend, Connection}; +use crate::backend::{Backend, Connection, Control, Source, provider_icon}; use crate::config::Config; use crate::context_ring; -use crate::git::{self, Branches}; use crate::icons::Icon; use crate::mentions::{self, Command, Trigger}; use crate::palette::{Palette, palette}; use crate::project; -use crate::ui::{MONO, icon, menu_item, menu_label, menu_panel, popup, separator}; -use crate::weave::{WeaveMark, model_mark}; +use crate::ui::{MONO, Tone, button, icon, kbd, menu_item, menu_label, menu_panel, popup, separator, tip}; +use crate::weave::WeaveMark; use crate::workspace::Prompt; +use quill_git::{self as git, Branches}; pub enum ComposerEvent { Submit(Prompt), Stop, Decide(Decision), + Answer(String), OpenModelSettings, Command(Command), SetIsolated(bool), @@ -36,9 +39,18 @@ pub enum ComposerEvent { #[derive(Clone)] pub struct ApprovalCard { - pub title: &'static str, + pub title: String, pub target: String, pub stats: Option<(usize, usize)>, + pub diffs: Vec, + pub similar: Option, + pub tool: String, +} + +#[derive(Clone)] +pub struct QuestionCard { + pub question: String, + pub options: Vec, } #[derive(Clone)] @@ -62,6 +74,12 @@ enum Menu { ApprovalMore, } +#[derive(Clone, PartialEq)] +enum ModelTab { + Pinned, + Source(String), +} + #[derive(Clone, PartialEq)] enum Suggestions { Commands(Vec), @@ -86,9 +104,13 @@ pub struct Composer { branch_error: Option, backend: Entity, mark: Entity, + marks: HashMap>, menu: Option, + model_tab: Option, busy: bool, approval: Option, + question: Option, + show_diff: bool, strip: Option, attachments: Vec, context_used: Option, @@ -147,9 +169,13 @@ impl Composer { branch_error: None, backend, mark: cx.new(|_| WeaveMark::new(State::Idle)), + marks: HashMap::new(), menu: None, + model_tab: None, busy: false, approval: None, + question: None, + show_diff: false, strip: None, attachments: Vec::new(), context_used: None, @@ -168,13 +194,18 @@ impl Composer { &mut self, busy: bool, approval: Option, + question: Option, strip: Option, context_used: Option, cx: &mut Context, ) { self.busy = busy; self.context_used = context_used; + if approval.as_ref().map(|a| &a.target) != self.approval.as_ref().map(|a| &a.target) { + self.show_diff = false; + } self.approval = approval; + self.question = question; if self.strip.as_ref().map(|s| &s.root) != strip.as_ref().map(|s| &s.root) { self.files = None; } @@ -193,13 +224,14 @@ impl Composer { && !modifiers.shift && let Some(index) = key.parse::().ok().filter(|n| (1..=9).contains(n)) { - let pinned = Config::get(cx).pinned_models.clone(); - if let Some(id) = pinned.get(index - 1).cloned() { - self.backend.update(cx, |backend, cx| backend.select(id, cx)); + let pinned = Config::get(cx).models.pinned.clone(); + if let Some(model) = pinned.get(index - 1).cloned() { + self.backend.update(cx, |backend, cx| backend.select(model, cx)); cx.stop_propagation(); } return; } + let focused = self.input.read(cx).focus_handle(cx).is_focused(window); if key == "escape" { if self.menu.is_some() { self.close(cx); @@ -208,9 +240,23 @@ impl Composer { self.suggestions = None; cx.notify(); cx.stop_propagation(); + } else if self.approval.is_some() && focused { + cx.emit(ComposerEvent::Decide(Decision::Decline)); + cx.stop_propagation(); } return; } + if key == "enter" + && !modifiers.shift + && focused + && self.approval.is_some() + && self.suggestions.is_none() + && self.input.read(cx).value().trim().is_empty() + { + cx.emit(ComposerEvent::Decide(Decision::Approve)); + cx.stop_propagation(); + return; + } let Some(count) = self.suggestions.as_ref().map(Suggestions::len) else { return }; if !self.input.read(cx).focus_handle(cx).is_focused(window) || count == 0 { return; @@ -276,10 +322,14 @@ impl Composer { match command { Command::Model => self.open(Menu::Model, window, cx), Command::Mode => self.open(Menu::Access, window, cx), - Command::Reasoning => { - let on = !Config::get(cx).thinking; - self.backend.update(cx, |backend, cx| backend.set_thinking(on, cx)); - } + Command::Reasoning => match self.backend.read(cx).control(cx) { + Control::Toggle => { + let on = !Config::get(cx).models.thinking; + self.backend.update(cx, |backend, cx| backend.set_thinking(on, cx)); + } + Control::Effort(_) => self.open(Menu::Thinking, window, cx), + Control::None => {} + }, Command::Init if !self.busy => { cx.emit(ComposerEvent::Submit(Prompt { text: mentions::INIT_PROMPT.into(), attachments: Vec::new() })); } @@ -288,10 +338,18 @@ impl Composer { } fn submit(&mut self, window: &mut Window, cx: &mut Context) { - if self.busy || self.suggestions.is_some() { + if self.suggestions.is_some() { return; } let text = self.input.read(cx).value().trim().to_string(); + if self.question.is_some() && !text.is_empty() { + self.input.update(cx, |input, cx| input.set_value("", window, cx)); + cx.emit(ComposerEvent::Answer(text)); + return; + } + if self.busy && text.is_empty() { + return; + } if text.is_empty() && self.attachments.is_empty() { return; } @@ -335,6 +393,7 @@ impl Composer { }); } if menu == Menu::Model { + self.model_tab = None; self.backend.update(cx, |backend, cx| backend.refresh(cx)); self.search.update(cx, |search, cx| { search.set_value("", window, cx); @@ -359,32 +418,61 @@ impl Composer { fn model_label(&self, cx: &App) -> (bool, SharedString) { let backend = self.backend.read(cx); - if let Some(model) = backend.selected(cx) { - return (true, model.id.clone().into()); + if let Some((_, model)) = backend.selected(cx) { + return (true, model.label().to_string().into()); } - match (&backend.connection, Backend::selected_id(cx)) { - (Connection::Checking, Some(id)) => (true, id.into()), - (Connection::Online, _) if !backend.models.is_empty() => (false, "Choose a model".into()), - (Connection::Checking, None) => (false, "Connecting".into()), + let checking = backend.sources.iter().any(|s| s.connection == Connection::Checking); + match Backend::selected_ref(cx) { + Some(selected) if checking => (true, selected.model.into()), + _ if backend.sources.iter().any(|s| s.ready() && !s.models.is_empty()) => (false, "Choose a model".into()), + _ if checking => (false, "Connecting".into()), _ => (false, "No model connected".into()), } } - fn model_row(&self, model: &Model, shortcut: Option, cx: &mut Context) -> Stateful
{ + fn model_mark(&mut self, model: &str, cx: &mut Context) -> Entity { + self.marks.entry(model.to_string()).or_insert_with(|| cx.new(|_| WeaveMark::new(State::Idle).seeded(model))).clone() + } + + fn model_row(&mut self, source: &Source, model: &Model, shortcut: Option, cx: &mut Context) -> Stateful
{ let p = palette(cx); - let id = model.id.clone(); - let pin_id = model.id.clone(); - let selected = Backend::selected_id(cx).as_deref() == Some(model.id.as_str()); - let pinned = Config::get(cx).pinned_models.contains(&model.id); - let mut detail = vec![model.status.label().to_string()]; + let backend_logo = source.config.kind != ProviderKind::Local; + let mark = if backend_logo { + div() + .size_full() + .flex() + .items_center() + .justify_center() + .child(icon(provider_icon(source.config.kind), 18., p.text)) + .into_any_element() + } else { + self.model_mark(&model.id, cx).into_any_element() + }; + let target = ModelRef::new(source.config.id.clone(), model.id.clone()); + let selected = Backend::selected_ref(cx).as_ref() == Some(&target); + let pinned = Config::get(cx).models.pinned.contains(&target); + let local = source.config.kind == ProviderKind::Local; + let mut detail = Vec::new(); + if local { + detail.push(model.status.label().to_string()); + } if let Some(context) = model.context { detail.push(format!("{} context", context_label(context))); } if model.vision { detail.push("Vision".into()); } + if !model.efforts.is_empty() { + detail.push("Reasoning".into()); + } + if model.name.is_some() && !local { + detail.push(model.id.clone()); + } + let ready = !local || model.status == Status::Loaded; + let key = format!("{}-{}", source.config.id, model.id); + let pin_target = target.clone(); div() - .id(SharedString::from(format!("model-{id}"))) + .id(SharedString::from(format!("model-{key}"))) .flex() .items_center() .gap(px(10.)) @@ -394,43 +482,28 @@ impl Composer { .cursor_pointer() .when(selected, |row| row.bg(p.row_active)) .hover(move |style| style.bg(p.row_hover)) - .child( - div().relative().flex_shrink_0().child(model_mark(&model.id, 24., p.text)).child( - div() - .absolute() - .right_0() - .bottom_0() - .size(px(8.)) - .rounded_full() - .border_1() - .border_color(p.menu_bg) - .bg(if model.status == Status::Loaded { p.success } else { p.text_faint.opacity(0.5) }), - ), - ) + .child(div().relative().flex_shrink_0().size(px(24.)).child(mark).child( + div().absolute().right_0().bottom_0().size(px(8.)).rounded_full().border_1().border_color(p.menu_bg).bg(if ready { + p.success + } else { + p.text_faint.opacity(0.5) + }), + )) .child( div() .flex_1() .min_w_0() .flex() .flex_col() - .child(div().text_size(px(13.5)).text_color(p.text).child(model.id.clone())) - .child(div().text_size(px(12.)).text_color(p.text_faint).child(detail.join(" · "))), + .child(div().text_size(px(13.5)).text_color(p.text).child(model.label().to_string())) + .when(!detail.is_empty(), |col| { + col.child(div().text_size(px(12.)).text_color(p.text_faint).text_ellipsis().child(detail.join(" · "))) + }), ) - .when_some(shortcut, |row, n| { - row.child( - div() - .px(px(5.)) - .rounded(px(5.)) - .border_1() - .border_color(p.border_soft) - .text_size(px(11.)) - .text_color(p.text_faint) - .child(format!("Ctrl+{n}")), - ) - }) + .when_some(shortcut, |row, n| row.child(kbd(format!("Ctrl+{n}"), p))) .child( div() - .id(SharedString::from(format!("pin-{pin_id}"))) + .id(SharedString::from(format!("pin-{key}"))) .size(px(24.)) .flex() .flex_shrink_0() @@ -438,126 +511,260 @@ impl Composer { .justify_center() .rounded(px(6.)) .hover(move |style| style.bg(p.row_active)) + .tooltip(tip(if pinned { "Unpin" } else { "Pin to the top" })) .child(icon(Icon::Pin, 13., if pinned { p.accent } else { p.text_faint.opacity(0.6) })) .on_click(cx.listener(move |_, _, _, cx| { cx.stop_propagation(); - let id = pin_id.clone(); + let target = pin_target.clone(); Config::update(cx, |config| { - if config.pinned_models.contains(&id) { - config.pinned_models.retain(|m| *m != id); + if config.models.pinned.contains(&target) { + config.models.pinned.retain(|m| *m != target); } else { - config.pinned_models.push(id); + config.models.pinned.push(target); } }); cx.notify(); })), ) .on_click(cx.listener(move |this, _, _, cx| { - let id = id.clone(); - this.backend.update(cx, |backend, cx| backend.select(id, cx)); + let target = target.clone(); + this.backend.update(cx, |backend, cx| backend.select(target, cx)); this.close(cx); })) } - fn model_menu(&self, cx: &mut Context) -> impl IntoElement + use<> { + fn source_header(&self, source: &Source, cx: &App) -> Div { + let p = palette(cx); + let color = match source.connection { + Connection::Online => p.success, + Connection::Checking => p.text_faint, + _ => p.warning, + }; + div() + .flex() + .items_center() + .gap(px(8.)) + .px(px(10.)) + .pt(px(8.)) + .pb(px(4.)) + .child(icon(provider_icon(source.config.kind), 14., p.text_muted)) + .child(div().text_size(px(12.5)).font_weight(FontWeight::SEMIBOLD).text_color(p.text_muted).child(source.config.name.clone())) + .child(div().size(px(6.)).flex_shrink_0().rounded_full().bg(color)) + .child(div().flex_1().min_w_0().text_size(px(12.)).text_color(p.text_faint).text_ellipsis().child(source.status())) + } + + fn current_tab(&self, sources: &[Source], has_pinned: bool, cx: &App) -> Option { + let valid = |tab: &ModelTab| match tab { + ModelTab::Pinned => has_pinned, + ModelTab::Source(id) => sources.iter().any(|s| s.config.id == *id), + }; + self.model_tab + .clone() + .filter(valid) + .or_else(|| Backend::selected_ref(cx).map(|r| ModelTab::Source(r.provider)).filter(valid)) + .or_else(|| sources.iter().find(|s| !s.models.is_empty()).or(sources.first()).map(|s| ModelTab::Source(s.config.id.clone()))) + } + + #[allow(clippy::too_many_arguments)] + fn tab_button( + &self, + id: SharedString, + name: Icon, + label: String, + dot: Option, + on: bool, + tab: ModelTab, + cx: &mut Context, + ) -> Stateful
{ + let p = palette(cx); + div() + .id(id) + .relative() + .flex() + .flex_shrink_0() + .items_center() + .justify_center() + .size(px(34.)) + .rounded(px(9.)) + .cursor_pointer() + .when(on, |tab| tab.bg(p.row_active)) + .hover(move |style| style.bg(if on { p.row_active } else { p.row_hover })) + .tooltip(tip(label)) + .child(icon(name, 18., if on { p.text } else { p.text_muted })) + .when_some(dot, |button, color| { + button.child( + div().absolute().right(px(5.)).bottom(px(5.)).size(px(7.)).rounded_full().border_1().border_color(p.menu_bg).bg(color), + ) + }) + .on_click(cx.listener(move |this, _, window, cx| { + this.search.update(cx, |search, cx| search.set_value("", window, cx)); + this.model_tab = Some(tab.clone()); + cx.notify(); + })) + } + + fn model_menu(&mut self, cx: &mut Context) -> impl IntoElement + use<> { let p = palette(cx); - let backend = self.backend.read(cx); - let url = Backend::url(cx); let query = self.search.read(cx).value().trim().to_lowercase(); - let pinned_ids = Config::get(cx).pinned_models.clone(); - let models = backend.models.clone(); - let connection = backend.connection.clone(); - let mut menu = menu_panel(p).w(px(360.)).child( + let pinned_refs = Config::get(cx).models.pinned.clone(); + let sources: Vec = self.backend.read(cx).sources.iter().filter(|s| s.connection != Connection::Off).cloned().collect(); + let pinned: Vec<(Source, Model)> = pinned_refs + .iter() + .filter_map(|r| { + let source = sources.iter().find(|s| s.config.id == r.provider)?; + source.models.iter().find(|m| m.id == r.model).map(|m| (source.clone(), m.clone())) + }) + .collect(); + let current = self.current_tab(&sources, !pinned.is_empty(), cx); + let searching = !query.is_empty(); + let mut rail = div().flex().flex_col().items_center().gap(px(4.)).w(px(36.)).flex_shrink_0().pt(px(2.)); + if !pinned.is_empty() { + let on = !searching && current == Some(ModelTab::Pinned); + rail = rail.child(self.tab_button("tab-pinned".into(), Icon::Pin, "Pinned".into(), None, on, ModelTab::Pinned, cx)); + } + for source in &sources { + let color = match source.connection { + Connection::Online => p.success, + Connection::Checking => p.text_faint, + _ => p.warning, + }; + let tab = ModelTab::Source(source.config.id.clone()); + let on = !searching && current.as_ref() == Some(&tab); + let id = SharedString::from(format!("tab-{}", source.config.id)); + rail = rail.child(self.tab_button(id, provider_icon(source.config.kind), source.config.name.clone(), Some(color), on, tab, cx)); + } + rail = rail.child(div().flex_1()).child( div() + .id("server-settings") .flex() .items_center() - .gap(px(8.)) - .px(px(10.)) - .pt(px(6.)) - .pb(px(6.)) - .child(svg().path(Icon::LlamaCpp.path()).size(px(16.)).text_color(p.text)) - .child(div().flex_1().text_size(px(13.)).font_weight(FontWeight::SEMIBOLD).text_color(p.text).child("llama.cpp")) - .child( - div() - .id("refresh-models") - .flex() - .items_center() - .justify_center() - .size(px(24.)) - .rounded(px(6.)) - .cursor_pointer() - .hover(move |style| style.bg(p.row_hover)) - .child(icon(Icon::Refresh, 13., p.text_faint)) - .on_click(cx.listener(|this, _, _, cx| this.backend.update(cx, |b, cx| b.refresh(cx)))), - ), + .justify_center() + .size(px(34.)) + .rounded(px(9.)) + .cursor_pointer() + .hover(move |style| style.bg(p.row_hover)) + .tooltip(tip("Providers and models")) + .child(icon(Icon::Sliders, 17., p.text_faint)) + .on_click(cx.listener(|this, _, _, cx| { + this.close(cx); + cx.emit(ComposerEvent::OpenModelSettings); + })), ); - menu = menu.child(search_box(&self.search, p)); - match &connection { - Connection::Checking if models.is_empty() => menu = menu.child(note("Looking for models", p)), - Connection::Offline(error) => { - menu = menu - .child(note(format!("Can't reach llama.cpp at {url}"), p)) - .child(div().px(px(10.)).pb(px(6.)).text_size(px(12.)).text_color(p.text_faint).child(error.clone())); - } - _ if models.is_empty() => menu = menu.child(note("This server has no models", p)), - _ => {} - } - let mut body = div().id("model-list").max_h(px(380.)).overflow_y_scroll().flex().flex_col().gap(px(1.)); - if query.is_empty() { - let pinned: Vec<&Model> = pinned_ids.iter().filter_map(|id| models.iter().find(|m| m.id == *id)).collect(); - if !pinned.is_empty() { - body = body.child(menu_label("Pinned", p)); - for (n, model) in pinned.iter().enumerate() { - body = body.child(self.model_row(model, (n < 9).then_some(n + 1), cx)); + let matches = + |model: &Model| !searching || model.id.to_lowercase().contains(&query) || model.label().to_lowercase().contains(&query); + let mut list = div().id("model-list").flex_1().min_h_0().overflow_y_scroll().flex().flex_col().gap(px(1.)); + if searching { + let mut shown = 0; + for source in &sources { + let models: Vec<&Model> = source.models.iter().filter(|m| matches(m)).collect(); + if models.is_empty() { + continue; + } + list = list.child(self.source_header(source, cx)); + for model in models { + shown += 1; + list = list.child(self.model_row(source, model, None, cx)); } - body = body.child(menu_label("Everything on this server", p)); } - for model in models.iter().filter(|m| !pinned_ids.contains(&m.id)) { - body = body.child(self.model_row(model, None, cx)); + if shown == 0 { + list = list.child(note("No model matches", p)); } } else { - let found: Vec<&Model> = models.iter().filter(|m| m.id.to_lowercase().contains(&query)).collect(); - if found.is_empty() { - body = body.child(note("No model matches", p)); - } - for model in found { - body = body.child(self.model_row(model, None, cx)); + match ¤t { + Some(ModelTab::Pinned) => { + for (n, (source, model)) in pinned.iter().enumerate() { + list = list.child(self.model_row(source, model, (n < 9).then_some(n + 1), cx)); + } + } + Some(ModelTab::Source(id)) => { + if let Some(source) = sources.iter().find(|s| s.config.id == *id) { + list = list.child(self.source_header(source, cx)); + for model in &source.models { + list = list.child(self.model_row(source, model, None, cx)); + } + if source.models.is_empty() { + list = list.child(match source.connection { + Connection::Checking => note("Looking for models", p).into_any_element(), + Connection::Online => note("This provider lists no models", p).into_any_element(), + _ => menu_item("setup-provider", Some(Icon::Sliders), "Set up this provider", None, false, p) + .on_click(cx.listener(|this, _, _, cx| { + this.close(cx); + cx.emit(ComposerEvent::OpenModelSettings); + })) + .into_any_element(), + }); + } + } + } + None => list = list.child(note("No providers are turned on", p)), } } - menu.child(body).child(separator(p)).child( - menu_item("server-settings", Some(Icon::Server), url, None, false, p) - .child(div().text_size(px(12.5)).text_color(p.text_muted).child("Change")) - .on_click(cx.listener(|this, _, _, cx| { - this.close(cx); - cx.emit(ComposerEvent::OpenModelSettings); - })), + let search_row = div().flex().items_center().gap(px(2.)).child(div().flex_1().child(search_box(&self.search, p))).child( + div() + .id("refresh-models") + .flex() + .flex_shrink_0() + .items_center() + .justify_center() + .size(px(30.)) + .mb(px(4.)) + .mr(px(2.)) + .rounded(px(8.)) + .cursor_pointer() + .hover(move |style| style.bg(p.row_hover)) + .tooltip(tip("Look for models again")) + .child(icon(Icon::Refresh, 14., p.text_faint)) + .on_click(cx.listener(|this, _, _, cx| this.backend.update(cx, |b, cx| b.refresh(cx)))), + ); + menu_panel(p).w(px(390.)).child( + div() + .flex() + .gap(px(6.)) + .h(px(330.)) + .child(rail) + .child(div().w(px(1.)).flex_shrink_0().my(px(2.)).bg(p.border_soft)) + .child(div().flex_1().min_w_0().flex().flex_col().child(search_row).child(list)), ) } fn thinking_menu(&self, cx: &mut Context) -> impl IntoElement + use<> { let p = palette(cx); - let on = Config::get(cx).thinking; - menu_panel(p).w(px(240.)).child(menu_label("Reasoning", p)).children( - [ - (true, "Think it through", "Reason before replying, slower but sharper"), - (false, "Reply directly", "Skip the reasoning step"), - ] - .map(|(value, label, detail)| { - menu_item(label, None, label, Some(detail.into()), on == value, p).on_click(cx.listener(move |this, _, _, cx| { - this.backend.update(cx, |b, cx| b.set_thinking(value, cx)); - this.close(cx); + let models = &Config::get(cx).models; + let (on, chosen) = (models.thinking, models.effort); + match self.backend.read(cx).control(cx) { + Control::Effort(levels) => { + let current = chosen.nearest(&levels); + menu_panel(p).w(px(270.)).child(menu_label("Effort", p)).children(levels.into_iter().map(|effort| { + menu_item(effort.wire(), None, effort.label(), Some(effort.description().into()), current == Some(effort), p).on_click( + cx.listener(move |this, _, _, cx| { + this.backend.update(cx, |b, cx| b.set_effort(effort, cx)); + this.close(cx); + }), + ) })) - }), - ) + } + _ => menu_panel(p).w(px(240.)).child(menu_label("Reasoning", p)).children( + [ + (true, "Think it through", "Reason before replying, slower but sharper"), + (false, "Reply directly", "Skip the reasoning step"), + ] + .map(|(value, label, detail)| { + menu_item(label, None, label, Some(detail.into()), on == value, p).on_click(cx.listener(move |this, _, _, cx| { + this.backend.update(cx, |b, cx| b.set_thinking(value, cx)); + this.close(cx); + })) + }), + ), + } } fn access_menu(&self, cx: &mut Context) -> impl IntoElement + use<> { let p = palette(cx); - let current = Config::get(cx).access; + let current = Config::get(cx).agent.access; menu_panel(p).w(px(360.)).child(menu_label("What the agent may do on its own", p)).children(Access::ALL.map(|access| { menu_item(access.label(), Some(access_icon(access)), access.label(), Some(access.description().into()), access == current, p) .on_click(cx.listener(move |this, _, _, cx| { - Config::update(cx, |config| config.access = access); + Config::update(cx, |config| config.agent.access = access); this.close(cx); })) })) @@ -783,7 +990,7 @@ impl Composer { let p = palette(cx); let isolated = strip.isolated; let choosing = strip.can_isolate && !strip.locked; - let projects = Config::get(cx).projects.clone(); + let projects = Config::get(cx).general.projects.clone(); let current = strip.project.clone(); let locked = strip.locked; let mut menu = menu_panel(p).w(px(360.)); @@ -856,11 +1063,10 @@ impl Composer { .px(px(8.)) .min_w_0() .rounded(px(8.)) - .text_size(px(13.5)) + .text_size(px(13.)) .text_color(if open { p.text } else { p.text_muted }) .cursor_pointer() - .when(open, |chip| chip.bg(p.row_active)) - .hover(move |style| style.bg(p.row_hover).text_color(p.text)) + .hover(move |style| style.text_color(p.text)) .on_click(cx.listener(move |this, _, window, cx| this.toggle(menu, window, cx))) } @@ -929,18 +1135,98 @@ impl Composer { ) } + fn question_card(&self, card: &QuestionCard, cx: &mut Context) -> impl IntoElement + use<> { + let p = palette(cx); + let view = div() + .flex() + .flex_col() + .gap(px(10.)) + .px(px(14.)) + .py(px(12.)) + .rounded(px(16.)) + .border_1() + .border_color(p.accent.opacity(0.4)) + .bg(p.raised) + .shadow_lg() + .child( + div() + .flex() + .items_center() + .gap(px(12.)) + .child( + div() + .size(px(30.)) + .flex_shrink_0() + .flex() + .items_center() + .justify_center() + .rounded_full() + .bg(p.accent_soft) + .child(icon(Icon::Chat, 15., p.accent)), + ) + .child( + div() + .flex_1() + .min_w_0() + .flex() + .flex_col() + .gap(px(1.)) + .child(div().text_size(px(12.)).font_weight(FontWeight::SEMIBOLD).text_color(p.accent).child("Quill is asking")) + .child(div().text_size(px(14.)).text_color(p.text).child(card.question.clone())), + ), + ) + .when(!card.options.is_empty(), |col| { + col.child(div().pl(px(42.)).flex().flex_wrap().gap(px(6.)).children(card.options.iter().enumerate().map( + |(index, option)| { + let answer = option.clone(); + div() + .id(("question-option", index)) + .px(px(12.)) + .h(px(30.)) + .flex() + .items_center() + .rounded_full() + .border_1() + .border_color(p.border) + .text_size(px(13.)) + .text_color(p.text) + .cursor_pointer() + .hover(move |style| style.bg(p.accent_soft).border_color(p.accent.opacity(0.5))) + .child(option.clone()) + .on_click(cx.listener(move |_, _, _, cx| cx.emit(ComposerEvent::Answer(answer.clone())))) + }, + ))) + }) + .child(div().pl(px(42.)).text_size(px(12.)).text_color(p.text_faint).child("Or type an answer below and press Enter")); + crate::motion::rise("question-card", view, 10., cx) + } + fn approval_card(&self, card: &ApprovalCard, window: &Window, cx: &mut Context) -> impl IntoElement + use<> { let p = palette(cx); let more_open = self.menu == Some(Menu::ApprovalMore); let more = more_open.then(|| { + let decide = |decision: Decision| { + cx.listener(move |this: &mut Self, _: &gpui_kit::ClickEvent, _: &mut Window, cx: &mut Context| { + this.close(cx); + cx.emit(ComposerEvent::Decide(decision)); + }) + }; + let similar = card.similar.clone().map(|similar| { + menu_item("allow-similar", Some(Icon::Check), format!("Always allow \"{similar}\""), None, false, p) + .on_click(decide(Decision::AllowSimilar)) + }); + let tool = (!card.tool.is_empty()).then(|| { + menu_item("allow-tool", Some(Icon::Shield), format!("Always allow: {}", card.tool), None, false, p) + .on_click(decide(Decision::AllowTool)) + }); let menu = menu_panel(p) - .w(px(250.)) - .child(menu_item("allow-thread", Some(Icon::Bolt), "Allow everything in this thread", None, false, p).on_click( - cx.listener(|this, _, _, cx| { - this.close(cx); - cx.emit(ComposerEvent::Decide(Decision::AlwaysAllow)); - }), - )) + .w(px(280.)) + .children(similar) + .children(tool) + .child( + menu_item("allow-thread", Some(Icon::Bolt), "Allow everything in this thread", None, false, p) + .on_click(decide(Decision::AllowAll)), + ) .child(menu_item("stop-run", Some(Icon::CircleStop), "Stop the agent", None, false, p).on_click(cx.listener( |this, _, _, cx| { this.close(cx); @@ -949,102 +1235,127 @@ impl Composer { ))); popup(window, cx, Anchor::BottomRight, menu, |this, cx| this.close(cx)) }); - div() + let show_diff = self.show_diff && !card.diffs.is_empty(); + let preview = show_diff.then(|| { + div() + .id("approval-diff") + .max_h(px(260.)) + .overflow_y_scroll() + .rounded(px(10.)) + .bg(p.sidebar) + .border_1() + .border_color(p.border_soft) + .py(px(6.)) + .children(card.diffs.iter().map(|diff| { + div() + .flex() + .flex_col() + .gap(px(4.)) + .when(card.diffs.len() > 1, |col| { + col.child( + div().px(px(10.)).font_family(MONO).text_size(px(12.)).text_color(p.text_muted).child(diff.path.clone()), + ) + }) + .child(crate::thread_view::diff_lines(diff, 40, p)) + })) + }); + let card_view = div() .flex() - .items_center() - .gap(px(12.)) - .px(px(16.)) - .py(px(10.)) - .rounded(px(14.)) + .flex_col() + .gap(px(10.)) + .px(px(14.)) + .py(px(12.)) + .rounded(px(16.)) .border_1() - .border_color(p.warning.opacity(0.45)) - .bg(p.warning.opacity(0.08)) - .child(icon(Icon::Shield, 17., p.warning)) + .border_color(p.warning.opacity(0.4)) + .bg(p.raised) + .shadow_lg() .child( div() - .flex_1() - .min_w_0() .flex() - .flex_col() - .gap(px(2.)) - .child(div().text_size(px(12.5)).font_weight(FontWeight::SEMIBOLD).text_color(p.warning).child(card.title)) + .items_center() + .gap(px(12.)) .child( div() + .size(px(30.)) + .flex_shrink_0() .flex() .items_center() - .gap(px(8.)) + .justify_center() + .rounded_full() + .bg(p.warning.opacity(0.14)) + .child(icon(Icon::Shield, 15., p.warning)), + ) + .child( + div() + .flex_1() + .min_w_0() + .flex() + .flex_col() + .gap(px(1.)) + .child(div().text_size(px(13.)).font_weight(FontWeight::SEMIBOLD).text_color(p.text).child(card.title.clone())) .child( div() - .min_w_0() - .overflow_hidden() - .text_ellipsis() - .whitespace_nowrap() - .font_family(MONO) - .text_size(px(13.)) - .text_color(p.text) - .child(card.target.clone()), - ) - .when_some(card.stats, |row, (added, removed)| { - row.child(div().text_size(px(12.)).text_color(p.add).child(format!("+{added}"))) - .child(div().text_size(px(12.)).text_color(p.del).child(format!("-{removed}"))) - }), - ), - ) - .child( - div() - .id("deny") - .h(px(30.)) - .px(px(12.)) - .flex() - .items_center() - .rounded(px(8.)) - .border_1() - .border_color(p.border) - .text_size(px(13.)) - .text_color(p.text) - .cursor_pointer() - .hover(move |style| style.bg(p.row_hover)) - .child("Deny") - .on_click(cx.listener(|_, _, _, cx| cx.emit(ComposerEvent::Decide(Decision::Decline)))), + .flex() + .items_center() + .gap(px(8.)) + .child( + div() + .min_w_0() + .overflow_hidden() + .text_ellipsis() + .whitespace_nowrap() + .font_family(MONO) + .text_size(px(12.5)) + .text_color(p.text_muted) + .child(card.target.clone()), + ) + .when_some(card.stats, |row, (added, removed)| { + row.child(div().text_size(px(12.)).text_color(p.add).child(format!("+{added}"))) + .child(div().text_size(px(12.)).text_color(p.del).child(format!("−{removed}"))) + }), + ), + ) + .when(!card.diffs.is_empty(), |row| { + row.child( + button("approval-show", if show_diff { "Hide changes" } else { "Show changes" }, Tone::Ghost, p).on_click( + cx.listener(|this, _, _, cx| { + this.show_diff = !this.show_diff; + cx.notify(); + }), + ), + ) + }), ) + .children(preview) .child( div() - .id("allow") - .h(px(30.)) - .px(px(14.)) .flex() .items_center() - .rounded(px(8.)) - .bg(p.text) - .text_size(px(13.)) - .font_weight(FontWeight::SEMIBOLD) - .text_color(p.bg) - .cursor_pointer() - .hover(|style| style.opacity(0.9)) - .child("Allow") - .on_click(cx.listener(|_, _, _, cx| cx.emit(ComposerEvent::Decide(Decision::Approve)))), - ) - .child( - div() - .relative() + .gap(px(8.)) + .child(div().flex_1().text_size(px(12.)).text_color(p.text_faint).child("Enter to allow · Esc to deny")) .child( div() - .id("approval-more") - .size(px(30.)) - .flex() - .items_center() - .justify_center() - .rounded(px(8.)) - .border_1() - .border_color(p.border) - .cursor_pointer() - .when(more_open, |b| b.bg(p.row_active)) - .hover(move |style| style.bg(p.row_hover)) - .child(icon(Icon::Dots, 15., p.text_muted)) - .on_click(cx.listener(|this, _, window, cx| this.toggle(Menu::ApprovalMore, window, cx))), + .relative() + .child( + button("approval-more", "Always allow", Tone::Ghost, p) + .when(more_open, |b| b.bg(p.row_active)) + .child(icon(Icon::ChevronDown, 12., p.text_faint)) + .on_click(cx.listener(|this, _, window, cx| this.toggle(Menu::ApprovalMore, window, cx))), + ) + .children(more), ) - .children(more), - ) + .child( + button("deny", "Deny", Tone::Secondary, p) + .child(kbd("Esc", p)) + .on_click(cx.listener(|_, _, _, cx| cx.emit(ComposerEvent::Decide(Decision::Decline)))), + ) + .child( + button("allow", "Allow", Tone::Primary, p) + .on_click(cx.listener(|_, _, _, cx| cx.emit(ComposerEvent::Decide(Decision::Approve)))), + ), + ); + crate::motion::rise("approval-card", card_view, 10., cx) } fn attachment_chips(&self, cx: &mut Context) -> impl IntoElement + use<> { @@ -1126,20 +1437,24 @@ pub fn access_icon(access: Access) -> Icon { } } -fn divider(p: Palette) -> impl IntoElement { - div().w(px(1.)).h(px(16.)).mx(px(2.)).bg(p.border) -} - impl Render for Composer { fn render(&mut self, window: &mut Window, cx: &mut Context) -> impl IntoElement { let p = palette(cx); let empty = self.input.read(cx).value().trim().is_empty() && self.attachments.is_empty(); let busy = self.busy; - let access = Config::get(cx).access; - let thinking = self.backend.read(cx).thinking(cx) == Thinking::Toggle; - let thinking_on = Config::get(cx).thinking; + let access = Config::get(cx).agent.access; + let control = self.backend.read(cx).control(cx); + let thinking = control != Control::None; + let thinking_label = match &control { + Control::Effort(levels) => Config::get(cx).models.effort.nearest(levels).map_or("Effort", |e| e.label()), + _ if Config::get(cx).models.thinking => "Thinking", + _ => "Direct", + }; let (has_model, label) = self.model_label(cx); - let window_size = self.backend.read(cx).selected(cx).and_then(|m| m.context); + let provider_logo = Backend::selected_ref(cx) + .and_then(|model| Config::get(cx).models.provider(&model.provider).map(|provider| provider.kind)) + .filter(|kind| *kind != ProviderKind::Local); + let window_size = Backend::selected_ref(cx).and_then(|model| self.backend.read(cx).effective(&model, cx)).and_then(|m| m.context); let menu = self.menu.filter(|m| *m != Menu::ApprovalMore); let model_menu = (menu == Some(Menu::Model)).then(|| { let content = self.model_menu(cx); @@ -1169,14 +1484,17 @@ impl Render for Composer { let chips = (!self.attachments.is_empty()).then(|| self.attachment_chips(cx)); let model_chip = self .chip("model-chip", Menu::Model, cx) - .when(has_model, |chip| chip.child(div().size(px(16.)).flex_shrink_0().child(self.mark.clone()))) - .when(!has_model, |chip| chip.child(svg().path(Icon::LlamaCpp.path()).size(px(14.)).text_color(p.text_faint))) + .when(has_model, |chip| match provider_logo { + Some(kind) => chip.child(icon(provider_icon(kind), 15., p.text)), + None => chip.child(div().size(px(16.)).flex_shrink_0().child(self.mark.clone())), + }) + .when(!has_model, |chip| chip.child(icon(Icon::Cube, 14., p.text_faint))) .child(div().min_w_0().overflow_hidden().whitespace_nowrap().text_ellipsis().child(label)) .child(icon(Icon::ChevronDown, 13., p.text_faint)); let thinking_chip = self .chip("thinking-chip", Menu::Thinking, cx) .child(icon(Icon::Bulb, 15., p.text_muted)) - .child(if thinking_on { "Thinking" } else { "Direct" }) + .child(thinking_label) .child(icon(Icon::ChevronDown, 13., p.text_faint)); let access_chip = self .chip("access-chip", Menu::Access, cx) @@ -1204,21 +1522,30 @@ impl Render for Composer { .size(px(34.)) .rounded_full() .map(|send| { - if busy { - send.bg(p.danger).cursor_pointer().child(icon(Icon::Stop, 12., gpui_kit::white())) + if busy && empty { + send.bg(p.danger).cursor_pointer().hover(|s| s.opacity(0.9)).tooltip(tip("Stop the agent")).child(icon( + Icon::Stop, + 12., + gpui_kit::white(), + )) } else if empty { send.bg(p.fill).child(icon(Icon::ArrowUp, 16., p.text_faint)) } else { - send.bg(p.text).cursor_pointer().hover(|s| s.opacity(0.9)).child(icon(Icon::ArrowUp, 16., p.bg)) + send.bg(p.accent) + .cursor_pointer() + .hover(|s| s.opacity(0.9)) + .tooltip(tip(if busy { "Add this while the agent works" } else { "Send" })) + .child(icon(Icon::ArrowUp, 16., p.accent_text)) } }) .on_click(cx.listener(move |this, _, window, cx| { - if busy { + if busy && empty { cx.emit(ComposerEvent::Stop); } else { this.submit(window, cx); } })); + let question = self.question.clone().map(|card| self.question_card(&card, cx)); let strip = self.strip.clone().map(|strip| { let open = self.menu == Some(Menu::Workspace); let branch_open = self.menu == Some(Menu::Branch); @@ -1286,28 +1613,32 @@ impl Render for Composer { ) }) }); + let focused = self.input.read(cx).focus_handle(cx).is_focused(window); + let width = f32::from(Config::get(cx).appearance.transcript_width.clamp(560, 1600)) - 56.; div() .w_full() - .max_w(px(760.)) + .max_w(px(width)) .flex() .flex_col() .gap(px(8.)) .children(approval) + .children(question) .children(suggestions) .child( div() .id("composer-box") .flex() .flex_col() - .gap(px(6.)) + .gap(px(8.)) .pt(px(12.)) - .pb(px(8.)) - .px(px(10.)) - .rounded(px(18.)) + .pb(px(10.)) + .px(px(12.)) + .rounded(px(20.)) .bg(p.composer_bg) .border_1() - .border_color(p.composer_ring) - .hover(move |style| style.border_color(p.composer_ring_hover)) + .border_color(if focused { p.accent.opacity(0.55) } else { p.composer_ring }) + .shadow_lg() + .hover(move |style| style.border_color(if focused { p.accent.opacity(0.7) } else { p.composer_ring_hover })) .drag_over::(move |style, _, _, _| style.border_color(p.link).bg(p.link.opacity(0.06))) .on_drop(cx.listener(|this, paths: &ExternalPaths, _, cx| this.add_files(paths.paths().to_vec(), cx))) .children(chips) @@ -1316,13 +1647,10 @@ impl Render for Composer { div() .flex() .items_center() - .gap(px(2.)) + .gap(px(6.)) .min_w_0() .child(div().relative().min_w_0().child(model_chip).children(model_menu)) - .when(thinking, |row| { - row.child(divider(p)).child(div().relative().child(thinking_chip).children(thinking_menu)) - }) - .child(divider(p)) + .when(thinking, |row| row.child(div().relative().child(thinking_chip).children(thinking_menu))) .child(div().relative().child(access_chip).children(access_menu)) .child(div().flex_1()) .when(has_model, |row| row.child(context_ring::ring(self.context_used, window_size, p))) diff --git a/crates/quill-code/src/config.rs b/crates/quill-code/src/config.rs index 8f74765..29cf7a1 100644 --- a/crates/quill-code/src/config.rs +++ b/crates/quill-code/src/config.rs @@ -1,91 +1,63 @@ -use std::fs; use std::path::PathBuf; +use std::time::SystemTime; use gpui_kit::{App, Global}; -use quill_agent::Access; -use serde::{Deserialize, Serialize}; +use quill_config::{Settings, settings_path}; -#[derive(Clone, Serialize, Deserialize)] -#[serde(default)] -pub struct Config { - pub server_url: String, - pub model: Option, - pub thinking: bool, - #[serde(alias = "mode")] - pub access: Access, - pub projects: Vec, - pub pinned_models: Vec, -} +pub use quill_config::{app_dir, personal_instructions_path, read_personal_instructions, write_personal_instructions}; -impl Default for Config { - fn default() -> Self { - Config { - server_url: "http://127.0.0.1:9931".into(), - model: None, - thinking: true, - access: Access::Full, - projects: Vec::new(), - pinned_models: Vec::new(), - } - } +pub struct Config { + settings: Settings, + error: Option, + read_at: Option, } impl Global for Config {} -pub fn home_dir() -> PathBuf { - std::env::var_os("USERPROFILE").or_else(|| std::env::var_os("HOME")).map(PathBuf::from).unwrap_or_default() -} - -pub fn app_dir() -> PathBuf { - std::env::var_os("APPDATA").map(PathBuf::from).unwrap_or_else(home_dir).join("quill-code") -} - -pub fn projects_dir() -> PathBuf { - home_dir().join(".quill-code").join("projects") +fn modified() -> Option { + std::fs::metadata(settings_path()).and_then(|m| m.modified()).ok() } -pub fn worktrees_dir() -> PathBuf { - home_dir().join(".quill-code").join("worktrees") -} - -pub fn personal_instructions_path() -> PathBuf { - home_dir().join(".quill-code").join("AGENTS.md") -} +impl Config { + pub fn load() -> Config { + let loaded = quill_config::load(); + Config { settings: loaded.settings, error: loaded.error, read_at: modified() } + } -pub fn read_personal_instructions() -> String { - fs::read_to_string(personal_instructions_path()).unwrap_or_default() -} + pub fn get(cx: &App) -> &Settings { + &cx.global::().settings + } -pub fn write_personal_instructions(text: &str) -> std::io::Result<()> { - let path = personal_instructions_path(); - if let Some(dir) = path.parent() { - fs::create_dir_all(dir)?; + pub fn error(cx: &App) -> Option { + cx.global::().error.clone() } - fs::write(path, text) -} -impl Config { - pub fn load() -> Config { - fs::read_to_string(app_dir().join("config.json")).ok().and_then(|text| serde_json::from_str(&text).ok()).unwrap_or_default() + pub fn update(cx: &mut App, edit: impl FnOnce(&mut Settings)) { + let config = cx.global_mut::(); + edit(&mut config.settings); + if config.error.is_none() && quill_config::save(&config.settings).is_ok() { + config.read_at = modified(); + } } - pub fn get(cx: &App) -> &Config { - cx.global::() + pub fn reload(cx: &mut App) -> bool { + if cx.global::().read_at == modified() { + return false; + } + cx.set_global(Config::load()); + true } - pub fn update(cx: &mut App, edit: impl FnOnce(&mut Config)) { + pub fn replace(cx: &mut App, settings: Settings) { let config = cx.global_mut::(); - edit(config); - let dir = app_dir(); - if let Ok(text) = serde_json::to_string_pretty(config) { - let _ = fs::create_dir_all(&dir).and_then(|_| fs::write(dir.join("config.json"), text)); + config.error = None; + config.settings = settings; + if quill_config::save(&config.settings).is_ok() { + config.read_at = modified(); } } pub fn add_project(cx: &mut App, path: PathBuf) { - Config::update(cx, |config| { - config.projects.retain(|p| p != &path); - config.projects.insert(0, path); - }); + Config::update(cx, |settings| settings.add_project(path)); } } \ No newline at end of file diff --git a/crates/quill-code/src/context_ring.rs b/crates/quill-code/src/context_ring.rs index d12dac1..c8a212d 100644 --- a/crates/quill-code/src/context_ring.rs +++ b/crates/quill-code/src/context_ring.rs @@ -2,7 +2,7 @@ use std::f32::consts::{FRAC_PI_2, TAU}; use gpui_kit::component::tooltip::Tooltip; use gpui_kit::{Bounds, Div, Hsla, ParentElement, PathBuilder, Pixels, Stateful, Styled, Window, canvas, div, point, prelude::*, px}; -use quill_llama::context_label; +use quill_providers::context_label; use crate::palette::Palette; diff --git a/crates/quill-code/src/icons.rs b/crates/quill-code/src/icons.rs index 6d67e3e..e5908d8 100644 --- a/crates/quill-code/src/icons.rs +++ b/crates/quill-code/src/icons.rs @@ -41,6 +41,7 @@ icons! { CircleAlert => "circle-alert", CircleStop => "circle-stop", CircleX => "circle-x", + Claude => "claude", Code => "code", Commit => "git-commit", Compose => "compose", @@ -60,14 +61,19 @@ icons! { FolderOpen => "folder-open", FolderPlus => "folder-plus", FolderTree => "folder-tree", + Gauge => "gauge", Gear => "gear", Globe => "globe", Image => "image-icon", Info => "info", Isolated => "isolated", - LlamaCpp => "llama-cpp", + Key => "key", + ListChecks => "list-checks", Link => "link", Loader => "loader", + OpenAi => "openai", + Palette => "palette", + Panel => "panel", Paperclip => "paperclip", Pencil => "pencil", Pin => "pin", @@ -80,8 +86,11 @@ icons! { Shield => "shield", Sliders => "sliders", Slash => "slash", + Sparkles => "sparkles", + Steer => "steer", Stop => "stop", Terminal => "terminal", Trash => "trash", + Wrench => "wrench", X => "x", } \ No newline at end of file diff --git a/crates/quill-code/src/main.rs b/crates/quill-code/src/main.rs index 70f3b24..733e0ca 100644 --- a/crates/quill-code/src/main.rs +++ b/crates/quill-code/src/main.rs @@ -8,14 +8,13 @@ mod commit_dialog; mod composer; mod config; mod context_ring; -mod git; -mod github; mod icons; mod mentions; +mod model_settings; +mod motion; mod palette; mod panel; mod project; -mod publish; mod settings; mod shell; mod smooth_scroll; @@ -24,6 +23,7 @@ mod terminal; mod thread; mod thread_view; mod ui; +mod usage; mod version; mod weave; mod workspace; @@ -47,7 +47,9 @@ fn main() { gpui_kit::init(cx); load_fonts(cx); cx.set_global(config::Config::load()); - palette::apply(cx.window_appearance(), None, cx); + let appearance = config::Config::get(cx).appearance.clone(); + motion::apply(appearance.motion, cx); + palette::apply(palette::resolve(appearance.theme, cx.window_appearance()), None, cx); cx.on_window_closed(|cx, _| { if cx.windows().is_empty() { cx.quit(); diff --git a/crates/quill-code/src/mentions.rs b/crates/quill-code/src/mentions.rs index 66267cf..9866fd4 100644 --- a/crates/quill-code/src/mentions.rs +++ b/crates/quill-code/src/mentions.rs @@ -100,10 +100,11 @@ pub enum Command { Terminal, Commit, Init, + Compact, } impl Command { - pub const ALL: [Command; 9] = [ + pub const ALL: [Command; 10] = [ Command::New, Command::Init, Command::Model, @@ -113,6 +114,7 @@ impl Command { Command::Files, Command::Terminal, Command::Commit, + Command::Compact, ]; pub fn name(self) -> &'static str { @@ -126,6 +128,7 @@ impl Command { Command::Terminal => "terminal", Command::Commit => "commit", Command::Init => "init", + Command::Compact => "compact", } } @@ -140,6 +143,7 @@ impl Command { Command::Terminal => "Open a PowerShell terminal in the project", Command::Commit => "Commit your work, then push or open a pull request", Command::Init => "Have the agent write an AGENTS.md that explains this project", + Command::Compact => "Summarise earlier turns to free up the model's context", } } diff --git a/crates/quill-code/src/model_settings.rs b/crates/quill-code/src/model_settings.rs new file mode 100644 index 0000000..f6607a7 --- /dev/null +++ b/crates/quill-code/src/model_settings.rs @@ -0,0 +1,538 @@ +use gpui_kit::component::input::{Input, InputState}; +use gpui_kit::component::setting::{NumberFieldOptions, SettingField, SettingGroup, SettingItem}; +use gpui_kit::{AnyElement, App, Div, Entity, FontWeight, IntoElement, ParentElement, SharedString, Styled, Window, div, prelude::*, px}; +use quill_config::{KeySource, ModelRef, Price, Provider, ProviderKind, forget_key, key_source, store_key}; +use quill_providers::{Effort, context_label, normalize_url}; + +use crate::backend::{Backend, Connection, provider_icon}; +use crate::config::Config; +use crate::icons::Icon; +use crate::palette::palette; +use crate::settings::{change, ghost, secondary, show_note}; +use crate::ui::{Tone, button, icon}; + +type Note = Entity>; + +pub fn groups(backend: Entity, note: Note, cx: &App) -> Vec { + let count = Config::get(cx).models.providers.len(); + let mut providers = SettingGroup::new() + .title("Providers") + .description("Where models come from. Every model a provider offers shows up in the prompt box, grouped by provider."); + for index in 0..count { + let backend = backend.clone(); + let note = note.clone(); + providers = providers.item( + SettingItem::render(move |_, window, cx| provider_card(index, &backend, ¬e, window, cx)) + .keywords(["provider", "key", "server"]), + ); + } + let adding = backend.clone(); + providers = providers.item(SettingItem::render(move |_, _, cx| add_row(&adding, ¬e, cx)).keywords(["add", "detect", "find"])); + vec![providers, defaults(), roles(&backend, cx), this_model(&backend, cx)] +} + +fn provider_card(index: usize, backend: &Entity, note: &Note, window: &mut Window, cx: &mut App) -> AnyElement { + let p = palette(cx); + let Some(provider) = Config::get(cx).models.providers.get(index).cloned() else { return div().into_any_element() }; + let source = backend.read(cx).source(&provider.id).cloned(); + let connection = source.as_ref().map_or(Connection::Checking, |s| s.connection.clone()); + let status = source.as_ref().map(|s| s.status()).unwrap_or_else(|| "Connecting".into()); + let color = match connection { + Connection::Online => p.success, + Connection::Checking | Connection::Off => p.text_faint, + Connection::NeedsKey => p.warning, + Connection::Offline(_) => p.danger, + }; + let id = provider.id.clone(); + let url_value = provider.url.clone(); + let address = window.use_keyed_state(SharedString::from(format!("provider-url-{id}")), cx, move |window, cx| { + let placeholder = + if provider_kind(index, cx) == ProviderKind::ClaudeCode { "Found automatically" } else { quill_config::DEFAULT_SERVER }; + InputState::new(window, cx).placeholder(placeholder).default_value(url_value) + }); + let key_input = window.use_keyed_state(SharedString::from(format!("provider-key-{id}")), cx, |window, cx| { + let mut state = InputState::new(window, cx).placeholder("Paste an API key"); + state.set_masked(true, window, cx); + state + }); + let header = div() + .flex() + .items_center() + .gap(px(10.)) + .child(icon(provider_icon(provider.kind), 18., p.text)) + .child( + div() + .flex_1() + .min_w_0() + .flex() + .flex_col() + .child(div().text_size(px(14.)).font_weight(FontWeight::SEMIBOLD).text_color(p.text).child(provider.name.clone())) + .when(provider.name != provider.kind.label(), |col| { + col.child(div().text_size(px(12.)).text_color(p.text_faint).child(provider.kind.label())) + }), + ) + .child(ghost(("provider-refresh", index), Icon::Refresh, p).tooltip(crate::ui::tip("Check again")).on_click({ + let backend = backend.clone(); + move |_, _, cx| backend.update(cx, |b, cx| b.refresh(cx)) + })) + .child(button(("provider-toggle", index), if provider.enabled { "Turn off" } else { "Turn on" }, Tone::Secondary, p).on_click({ + let backend = backend.clone(); + move |_, _, cx| { + change(cx, |s| { + if let Some(entry) = s.models.providers.get_mut(index) { + entry.enabled = !entry.enabled; + } + }); + backend.update(cx, |b, cx| b.refresh(cx)); + } + })) + .child(ghost(("provider-remove", index), Icon::Trash, p).tooltip(crate::ui::tip("Remove this provider")).on_click({ + let backend = backend.clone(); + let id = id.clone(); + move |_, _, cx| { + let _ = forget_key(&id); + change(cx, |s| { + if index < s.models.providers.len() { + s.models.providers.remove(index); + } + }); + backend.update(cx, |b, cx| b.refresh(cx)); + } + })); + let status_line = div() + .flex() + .items_start() + .gap(px(8.)) + .text_size(px(12.5)) + .text_color(p.text_muted) + .child(div().mt(px(5.)).size(px(7.)).flex_shrink_0().rounded_full().bg(color)) + .child(div().flex_1().min_w_0().child(status)); + let address_label = if provider.kind == ProviderKind::ClaudeCode { "Program" } else { "Address" }; + let address_row = field_row( + address_label, + div().flex().gap(px(8.)).child(div().flex_1().child(Input::new(&address))).child( + secondary(("provider-connect", index), "Connect", p).on_click({ + let backend = backend.clone(); + let address = address.clone(); + move |_, _, cx| { + let text = address.read(cx).value().trim().to_string(); + change(cx, |s| { + if let Some(entry) = s.models.providers.get_mut(index) { + entry.url = if entry.kind == ProviderKind::ClaudeCode || text.is_empty() { text } else { normalize_url(&text) }; + } + }); + backend.update(cx, |b, cx| b.refresh(cx)); + } + }), + ), + cx, + ); + let mut card = div() + .w_full() + .flex() + .flex_col() + .gap(px(10.)) + .p(px(14.)) + .rounded(px(12.)) + .border_1() + .border_color(p.border_soft) + .bg(p.raised) + .child(header) + .child(status_line) + .child(address_row); + if provider.kind.needs_key() { + card = card.child(key_row(index, &provider, &key_input, backend, note, cx)); + } + if provider.kind == ProviderKind::ClaudeCode { + card = card.child(aliases(index, &provider, window, cx)); + } + if provider.kind == ProviderKind::Anthropic { + let on = provider.fallback; + card = card.child( + div() + .flex() + .items_center() + .gap(px(10.)) + .child( + div() + .flex_1() + .text_size(px(12.5)) + .text_color(p.text_muted) + .child("When a model declines a request, let Anthropic retry it on the model it recommends."), + ) + .child(button(("provider-fallback", index), if on { "Retrying" } else { "Not retrying" }, Tone::Secondary, p).on_click( + move |_, _, cx| { + change(cx, |s| { + if let Some(entry) = s.models.providers.get_mut(index) { + entry.fallback = !on; + } + }) + }, + )), + ); + } + card.into_any_element() +} + +fn provider_kind(index: usize, cx: &App) -> ProviderKind { + Config::get(cx).models.providers.get(index).map(|p| p.kind).unwrap_or_default() +} + +fn field_row(label: &'static str, content: impl IntoElement, cx: &App) -> Div { + let p = palette(cx); + div() + .flex() + .items_center() + .gap(px(12.)) + .child(div().w(px(76.)).flex_shrink_0().text_size(px(12.5)).text_color(p.text_faint).child(label)) + .child(div().flex_1().min_w_0().child(content)) +} + +fn key_row(index: usize, provider: &Provider, input: &Entity, backend: &Entity, note: &Note, cx: &App) -> AnyElement { + let p = palette(cx); + let source = match key_source(provider) { + KeySource::Stored => "Saved in Windows Credential Manager.".to_string(), + KeySource::Environment(name) => format!("Using {name} from your environment."), + KeySource::Missing => "No key yet. Keys are kept in Windows Credential Manager, never in settings.json.".to_string(), + }; + let stored = key_source(provider) == KeySource::Stored; + let id = provider.id.clone(); + let row = div() + .flex() + .gap(px(8.)) + .child(div().flex_1().child(Input::new(input).mask_toggle())) + .child(secondary(("provider-key-save", index), "Save key", p).on_click({ + let (input, backend, note, id) = (input.clone(), backend.clone(), note.clone(), id.clone()); + move |_, window, cx| { + let key = input.read(cx).value().trim().to_string(); + if key.is_empty() { + return; + } + let result = store_key(&id, &key).map(|_| "Key saved".to_string()); + show_note(¬e, result, cx); + input.update(cx, |input, cx| input.set_value("", window, cx)); + backend.update(cx, |b, cx| b.refresh(cx)); + } + })) + .when(stored, |row| { + let (backend, note, id) = (backend.clone(), note.clone(), id.clone()); + row.child(ghost(("provider-key-forget", index), Icon::Trash, p).tooltip(crate::ui::tip("Forget the saved key")).on_click( + move |_, _, cx| { + show_note(¬e, forget_key(&id).map(|_| "Key removed".to_string()), cx); + backend.update(cx, |b, cx| b.refresh(cx)); + }, + )) + }); + div() + .flex() + .flex_col() + .gap(px(6.)) + .child(field_row("API key", row, cx)) + .child( + div() + .pl(px(88.)) + .flex() + .items_center() + .gap(px(6.)) + .text_size(px(12.)) + .text_color(p.text_faint) + .child(icon(Icon::Key, 12., p.text_faint)) + .child(source), + ) + .into_any_element() +} + +fn aliases(index: usize, provider: &Provider, window: &mut Window, cx: &mut App) -> AnyElement { + let p = palette(cx); + let input = window.use_keyed_state(SharedString::from(format!("provider-alias-{}", provider.id)), cx, |window, cx| { + InputState::new(window, cx).placeholder("Add a model, such as opus or claude-sonnet-5-5") + }); + let chips = div().flex().flex_wrap().gap(px(6.)).children(provider.models.iter().enumerate().map(|(n, alias)| { + div() + .flex() + .items_center() + .gap(px(4.)) + .pl(px(9.)) + .pr(px(3.)) + .h(px(26.)) + .rounded(px(7.)) + .bg(p.fill) + .border_1() + .border_color(p.border_soft) + .font_family(crate::ui::MONO) + .text_size(px(12.5)) + .text_color(p.text) + .child(alias.clone()) + .child(ghost((SharedString::from(format!("alias-remove-{index}")), n), Icon::X, p).size(px(20.)).on_click(move |_, _, cx| { + change(cx, |s| { + if let Some(entry) = s.models.providers.get_mut(index) + && n < entry.models.len() + { + entry.models.remove(n); + } + }) + })) + })); + let add = input.clone(); + let row = div().flex().gap(px(8.)).child(div().flex_1().child(Input::new(&input))).child( + secondary(("alias-add", index), "Add", p).on_click(move |_, window, cx| { + let value = add.read(cx).value().trim().to_string(); + if value.is_empty() { + return; + } + change(cx, |s| { + if let Some(entry) = s.models.providers.get_mut(index) + && !entry.models.contains(&value) + { + entry.models.push(value); + } + }); + add.update(cx, |input, cx| input.set_value("", window, cx)); + }), + ); + div().flex().flex_col().gap(px(8.)).child(field_row("Models", chips, cx)).child(div().pl(px(88.)).child(row)).into_any_element() +} + +fn add_row(backend: &Entity, note: &Note, cx: &App) -> AnyElement { + let p = palette(cx); + let shown = note.read(cx).clone(); + let scan = { + let (backend, note) = (backend.clone(), note.clone()); + move |_: &gpui_kit::ClickEvent, _: &mut Window, cx: &mut App| { + show_note(¬e, Ok("Looking on this computer".into()), cx); + let task = backend.update(cx, |b, cx| b.scan(cx)); + let note = note.clone(); + cx.spawn(async move |cx| { + let found = task.await; + let text = match found { + 0 => "No other servers answered on the usual ports".to_string(), + 1 => "Found a server and added it".to_string(), + n => format!("Found {n} servers and added them"), + }; + cx.update(|cx| show_note(¬e, Ok(text), cx)); + }) + .detach(); + } + }; + div() + .w_full() + .flex() + .flex_col() + .gap(px(10.)) + .child(div().text_size(px(13.)).text_color(p.text_muted).child("Add a provider")) + .child(div().flex().flex_wrap().gap(px(8.)).children(ProviderKind::ALL.map(|kind| { + let backend = backend.clone(); + button(SharedString::from(format!("add-provider-{}", kind.label())), kind.label(), Tone::Secondary, p) + .tooltip(crate::ui::tip(kind.description())) + .on_click(move |_, _, cx| { + change(cx, |s| { + let id = s.models.fresh_id(kind); + let taken = s.models.providers.iter().filter(|p| p.kind == kind).count(); + let name = if taken == 0 { kind.label().to_string() } else { format!("{} {}", kind.label(), taken + 1) }; + s.models.providers.push(Provider::new(&id, &name, kind)); + }); + backend.update(cx, |b, cx| b.refresh(cx)); + }) + }))) + .child( + div() + .flex() + .items_center() + .gap(px(10.)) + .child(button("scan-servers", "Find local servers", Tone::Primary, p).on_click(scan)) + .child(div().text_size(px(12.5)).text_color(p.text_faint).child(format!( + "Looks on this computer at ports {}.", + quill_config::LOCAL_PORTS.map(|port| port.to_string()).join(", ") + ))) + .when_some(shown, |row, (ok, text)| { + row.child(div().text_size(px(12.5)).text_color(if ok { p.success } else { p.danger }).child(text)) + }), + ) + .into_any_element() +} + +fn defaults() -> SettingGroup { + let options = Effort::ALL.iter().map(|e| (SharedString::from(e.wire()), SharedString::from(e.label()))).collect(); + SettingGroup::new() + .title("Reasoning") + .item( + SettingItem::new( + "Effort", + SettingField::dropdown( + options, + |cx| Config::get(cx).models.effort.wire().into(), + |value, cx| { + if let Some(effort) = Effort::ALL.into_iter().find(|e| e.wire() == value.as_ref()) { + change(cx, |s| s.models.effort = effort); + } + }, + ) + .default_value(Effort::High.wire()), + ) + .description( + "How hard Claude, OpenAI reasoning models and Claude Code think. A model that lacks a level uses the nearest one.", + ), + ) + .item( + SettingItem::new( + "Thinking on local models", + SettingField::switch(|cx| Config::get(cx).models.thinking, |on, cx| change(cx, |s| s.models.thinking = on)) + .default_value(true), + ) + .description("Let local models whose chat template supports it think before they answer."), + ) +} + +fn encode(model: &ModelRef) -> SharedString { + format!("{}\t{}", model.provider, model.model).into() +} + +fn decode(value: &str) -> Option { + value.split_once('\t').map(|(provider, model)| ModelRef::new(provider, model)) +} + +fn role_item( + title: &'static str, + description: &'static str, + options: Vec<(SharedString, SharedString)>, + get: fn(&quill_config::Roles) -> Option, + set: fn(&mut quill_config::Roles, Option), +) -> SettingItem { + SettingItem::new( + title, + SettingField::dropdown( + options, + move |cx| get(&Config::get(cx).models.roles).map(|m| encode(&m)).unwrap_or_default(), + move |value, cx| change(cx, |s| set(&mut s.models.roles, decode(&value))), + ) + .default_value(""), + ) + .description(description) +} + +fn roles(backend: &Entity, cx: &App) -> SettingGroup { + let mut options = vec![(SharedString::default(), SharedString::from("Same as the chat"))]; + for source in backend.read(cx).sources.iter().filter(|s| s.ready()) { + for model in &source.models { + let target = ModelRef::new(source.config.id.clone(), model.id.clone()); + options.push((encode(&target), format!("{} · {}", source.config.name, model.label()).into())); + } + } + SettingGroup::new() + .title("Models for side jobs") + .item(role_item( + "Summaries", + "Writes the summary when a long thread is compacted. A small, fast model works well.", + options.clone(), + |roles| roles.compaction.clone(), + |roles, model| roles.compaction = model, + )) + .item(role_item( + "Commit messages", + "Writes commit messages when you leave the message empty.", + options, + |roles| roles.commit.clone(), + |roles, model| roles.commit = model, + )) +} + +fn this_model(backend: &Entity, cx: &App) -> SettingGroup { + let Some(model) = Backend::selected_ref(cx) else { + return SettingGroup::new().title("The model in use").description("Choose a model in the prompt box to adjust it here."); + }; + let detected = backend.read(cx).find(&model).map(|(_, m)| m.clone()); + let label = detected.as_ref().map_or(model.model.clone(), |m| m.label().to_string()); + let window = detected.as_ref().and_then(|m| m.context).map_or("not reported".to_string(), context_label); + let number = |title: &'static str, + description: String, + step: f64, + get: fn(&quill_config::Override) -> Option, + set: fn(&mut quill_config::Override, Option)| { + let (read, write) = (model.clone(), model.clone()); + SettingItem::new( + title, + SettingField::number_input( + NumberFieldOptions { min: 0., max: 10_000_000., step }, + move |cx| Config::get(cx).models.override_for(&read).and_then(get).unwrap_or(0) as f64, + move |value, cx| change(cx, |s| set(s.models.override_mut(&write), (value >= 1.).then_some(value as u64))), + ) + .default_value(0.), + ) + .description(description) + }; + let (read, write) = (model.clone(), model.clone()); + SettingGroup::new() + .title(format!("The model in use: {label}")) + .description("Fill in what the provider does not report. Zero keeps the detected value.") + .item(number( + "Context window", + format!("Tokens the model can read at once. Detected: {window}."), + 1024., + |o| o.context, + |o, v| o.context = v, + )) + .item(number( + "Longest reply", + "Tokens one reply may use. Zero uses the provider's default.".into(), + 1024., + |o| o.max_output, + |o, v| o.max_output = v, + )) + .item( + SettingItem::new( + "Images", + SettingField::dropdown( + vec![ + ("detected".into(), "As detected".into()), + ("yes".into(), "Accepts images".into()), + ("no".into(), "Text only".into()), + ], + move |cx| match Config::get(cx).models.override_for(&read).and_then(|o| o.vision) { + Some(true) => "yes".into(), + Some(false) => "no".into(), + None => "detected".into(), + }, + move |value, cx| { + let vision = match value.as_ref() { + "yes" => Some(true), + "no" => Some(false), + _ => None, + }; + change(cx, |s| s.models.override_mut(&write).vision = vision); + }, + ) + .default_value("detected"), + ) + .description("Whether pictures you attach are sent to this model."), + ) + .item(price_item("Input price", &model, false)) + .item(price_item("Output price", &model, true)) +} + +fn price_item(title: &'static str, model: &ModelRef, output: bool) -> SettingItem { + let (read, write) = (model.clone(), model.clone()); + SettingItem::new( + title, + SettingField::number_input( + NumberFieldOptions { min: 0., max: 1000., step: 0.05 }, + move |cx| { + let price = Config::get(cx).models.override_for(&read).and_then(|o| o.price); + price.map_or(0., |price| if output { price.output } else { price.input }) + }, + move |value, cx| { + change(cx, |s| { + let entry = s.models.override_mut(&write); + let current = entry.price.unwrap_or(Price::new(0., 0.)); + let (input, out) = if output { (current.input, value) } else { (value, current.output) }; + entry.price = (input > 0. || out > 0.).then(|| Price::new(input, out)); + }) + }, + ) + .default_value(0.), + ) + .description(if output { + "Dollars per million tokens the model writes." + } else { + "Dollars per million tokens sent, used to work out what a chat costs. Cached input counts at a tenth. Zero uses the published price for Anthropic models, and no price otherwise." + }) +} \ No newline at end of file diff --git a/crates/quill-code/src/motion.rs b/crates/quill-code/src/motion.rs new file mode 100644 index 0000000..2f229e7 --- /dev/null +++ b/crates/quill-code/src/motion.rs @@ -0,0 +1,67 @@ +use std::time::Duration; + +use gpui_kit::base::animation::ease_out_cubic; +use gpui_kit::{ + Animation, AnimationExt, App, ElementId, Global, IntoElement, Styled, Svg, Transformation, percentage, pulsating_between, px, +}; +use quill_config::Motion; + +pub const QUICK: u64 = 140; +pub const BASE: u64 = 220; + +#[derive(Clone, Copy)] +pub struct Pace { + scale: f32, +} + +impl Global for Pace {} + +pub fn apply(motion: Motion, cx: &mut App) { + cx.set_reduce_motion(motion == Motion::Off); + let scale = match motion { + Motion::Full => 1.0, + Motion::Reduced => 0.5, + Motion::Off => 0.0, + }; + cx.set_global(Pace { scale }); +} + +pub fn duration(ms: u64, cx: &App) -> Duration { + let scale = cx.try_global::().map_or(1.0, |pace| pace.scale); + Duration::from_millis((ms as f32 * scale).round() as u64) +} + +pub fn rise, E: IntoElement + Styled + 'static>( + id: I, + element: E, + distance: f32, + cx: &App, +) -> impl IntoElement + use { + element.relative().with_animation(id, Animation::new(duration(BASE, cx)).with_easing(ease_out_cubic), move |el, t| { + el.opacity(t).top(px((1.0 - t) * distance)) + }) +} + +pub fn pop, E: IntoElement + Styled + 'static>( + id: I, + element: E, + from_below: bool, + cx: &App, +) -> impl IntoElement + use { + let distance = if from_below { 6.0 } else { -6.0 }; + element.relative().with_animation(id, Animation::new(duration(QUICK, cx)).with_easing(ease_out_cubic), move |el, t| { + el.opacity(t).top(px((1.0 - t) * distance)) + }) +} + +pub fn spin(id: impl Into, svg: Svg) -> impl IntoElement { + svg.with_animation(id, Animation::new(Duration::from_millis(900)).repeat(), |svg, t| { + svg.with_transformation(Transformation::rotate(percentage(t))) + }) +} + +pub fn shimmer, E: IntoElement + Styled + 'static>(id: I, element: E) -> impl IntoElement + use { + element.with_animation(id, Animation::new(Duration::from_millis(1600)).repeat().with_easing(pulsating_between(0.45, 1.0)), |el, t| { + el.opacity(t) + }) +} \ No newline at end of file diff --git a/crates/quill-code/src/palette.rs b/crates/quill-code/src/palette.rs index 4b9a276..26d1d06 100644 --- a/crates/quill-code/src/palette.rs +++ b/crates/quill-code/src/palette.rs @@ -1,5 +1,6 @@ use gpui_kit::component::{Theme, ThemeMode}; use gpui_kit::{App, Global, Hsla, Window, WindowAppearance, px, rgb, rgba, transparent_black}; +use quill_config::Theme as ThemeChoice; pub const FONT: &str = "Open Sans"; @@ -8,6 +9,7 @@ pub struct Palette { pub dark: bool, pub bg: Hsla, pub sidebar: Hsla, + pub raised: Hsla, pub surface_2: Hsla, pub surface_hover: Hsla, pub border: Hsla, @@ -16,6 +18,8 @@ pub struct Palette { pub text_muted: Hsla, pub text_faint: Hsla, pub accent: Hsla, + pub accent_soft: Hsla, + pub accent_text: Hsla, pub sidebar_text: Hsla, pub row_hover: Hsla, pub row_active: Hsla, @@ -49,66 +53,72 @@ impl Palette { pub fn dark() -> Self { Palette { dark: true, - bg: hex(0x151515), - sidebar: hex(0x111111), - surface_2: hex(0x20201f), - surface_hover: hex(0x262625), - border: hexa(0xffffff1a), - border_soft: hexa(0xffffff14), - text: hex(0xffffff), - text_muted: hex(0xc3c2b7), - text_faint: hex(0x898781), - accent: hex(0xc6613f), - sidebar_text: hex(0xc3c2b7), - row_hover: hexa(0xffffff13), - row_active: hexa(0xffffff1a), - composer_bg: hex(0x20201f), - composer_ring: hexa(0xffffff1a), - composer_ring_hover: hexa(0xffffff33), - menu_bg: hex(0x20201f), - fill: hexa(0xffffff0d), - add: hex(0x32d74b), - del: hex(0xff2c56), - link: hex(0x6da7ec), - focus_ring: hex(0x5598e7), - danger: hex(0xe5484d), - warning: hex(0xe2b03f), - success: hex(0x4caf7d), - selection: hex(0x3d3d3d), - scroll_thumb: hexa(0xe1e0d959), + bg: hex(0x131316), + sidebar: hex(0x0c0c0e), + raised: hex(0x1a1a1f), + surface_2: hex(0x18181c), + surface_hover: hex(0x202026), + border: hexa(0xffffff1c), + border_soft: hexa(0xffffff10), + text: hex(0xececf1), + text_muted: hex(0xb0b2ba), + text_faint: hex(0x777983), + accent: hex(0x8e9cff), + accent_soft: hexa(0x8e9cff24), + accent_text: hex(0x0c0c14), + sidebar_text: hex(0xb0b2ba), + row_hover: hexa(0xffffff0d), + row_active: hexa(0xffffff15), + composer_bg: hex(0x1a1a1f), + composer_ring: hexa(0xffffff17), + composer_ring_hover: hexa(0xffffff2b), + menu_bg: hex(0x1c1c22), + fill: hexa(0xffffff0a), + add: hex(0x4ac26b), + del: hex(0xf0616d), + link: hex(0x9aa7ff), + focus_ring: hex(0x8e9cff), + danger: hex(0xf0616d), + warning: hex(0xe8b558), + success: hex(0x4cc38a), + selection: hexa(0x8e9cff47), + scroll_thumb: hexa(0xffffff33), } } pub fn light() -> Self { Palette { dark: false, - bg: hex(0xf8f8f6), - sidebar: hex(0xf7f7f4), - surface_2: hex(0xefeee7), - surface_hover: hex(0xefeeeb), - border: hex(0xdddddd), - border_soft: hexa(0x00000014), - text: hex(0x121212), - text_muted: hex(0x3d3d3a), - text_faint: hex(0x7b7974), - accent: hex(0xc9663f), - sidebar_text: hex(0x3d3d3a), - row_hover: hexa(0x0000000f), - row_active: hexa(0x00000014), + bg: hex(0xffffff), + sidebar: hex(0xf3f3f5), + raised: hex(0xffffff), + surface_2: hex(0xf6f6f8), + surface_hover: hex(0xefeff2), + border: hexa(0x0000001c), + border_soft: hexa(0x00000010), + text: hex(0x18181b), + text_muted: hex(0x4b4d55), + text_faint: hex(0x878992), + accent: hex(0x5865e8), + accent_soft: hexa(0x5865e81c), + accent_text: hex(0xffffff), + sidebar_text: hex(0x4b4d55), + row_hover: hexa(0x0000000b), + row_active: hexa(0x00000013), composer_bg: hex(0xffffff), composer_ring: hexa(0x0000001a), - composer_ring_hover: hexa(0x00000033), + composer_ring_hover: hexa(0x0000002e), menu_bg: hex(0xffffff), - fill: hexa(0x1f1e1d0b), - add: hex(0x15803d), - del: hex(0xd1243f), - link: hex(0x2a78d6), - focus_ring: hex(0x5598e7), - danger: hex(0xd1243f), + fill: hexa(0x0000000a), + add: hex(0x1a7f37), + del: hex(0xcf222e), + link: hex(0x4553d6), + focus_ring: hex(0x5865e8), + danger: hex(0xcf222e), warning: hex(0xb7791f), - success: hex(0x15803d), - selection: hex(0xd8d6cc), - scroll_thumb: hexa(0x1f1e1d40), + success: hex(0x1a7f37), + selection: hexa(0x5865e833), + scroll_thumb: hexa(0x00000033), } } @@ -120,6 +130,14 @@ impl Palette { } } +pub fn resolve(theme: ThemeChoice, system: WindowAppearance) -> WindowAppearance { + match theme { + ThemeChoice::System => system, + ThemeChoice::Dark => WindowAppearance::Dark, + ThemeChoice::Light => WindowAppearance::Light, + } +} + pub fn palette(cx: &App) -> Palette { *cx.global::() } @@ -149,26 +167,29 @@ pub fn apply(appearance: WindowAppearance, window: Option<&mut Window>, cx: &mut colors.accent_foreground = palette.text; colors.popover = palette.menu_bg; colors.popover_foreground = palette.text; - colors.primary = palette.text; - colors.primary_foreground = palette.bg; + colors.primary = palette.accent; + colors.primary_foreground = palette.accent_text; + colors.primary_hover = palette.accent.opacity(0.9); + colors.primary_active = palette.accent.opacity(0.8); colors.secondary = palette.fill; colors.secondary_foreground = palette.text; colors.secondary_hover = palette.row_hover; colors.secondary_active = palette.row_active; colors.list = palette.bg; colors.list_hover = palette.row_hover; - colors.list_active = palette.row_active; + colors.list_active = palette.accent_soft; colors.list_active_border = transparent_black(); colors.link = palette.link; colors.danger = palette.danger; colors.warning = palette.warning; colors.success = palette.success; + colors.switch = palette.accent; colors.title_bar = palette.sidebar; colors.title_bar_border = palette.sidebar; colors.sidebar = palette.sidebar; colors.sidebar_foreground = palette.sidebar_text; colors.sidebar_border = palette.sidebar; - colors.sidebar_accent = palette.row_hover; + colors.sidebar_accent = palette.row_active; colors.sidebar_accent_foreground = palette.text; colors.window_border = palette.border; colors.scrollbar = transparent_black(); diff --git a/crates/quill-code/src/panel.rs b/crates/quill-code/src/panel.rs index 58f5f64..1515926 100644 --- a/crates/quill-code/src/panel.rs +++ b/crates/quill-code/src/panel.rs @@ -4,22 +4,25 @@ use std::path::{Path, PathBuf}; use gpui_kit::component::input::{Input, InputEvent, InputState}; use gpui_kit::{ - Context, Entity, EventEmitter, FontWeight, IntoElement, ParentElement, Render, SharedString, Styled, Subscription, Window, div, - prelude::*, px, uniform_list, + AnimationExt, Context, Entity, EventEmitter, FontWeight, IntoElement, ParentElement, Render, SharedString, SpringAnimation, + SpringConfig, Styled, Subscription, Window, div, prelude::*, px, uniform_list, }; -use quill_agent::FileDiff; +use quill_core::FileDiff; use crate::icons::Icon; use crate::palette::{Palette, palette}; use crate::thread_view::{diff_lines, file_icon}; use crate::ui::{MONO, icon}; +use crate::usage::UsageView; const SKIP: [&str; 6] = [".git", "node_modules", "target", ".venv", "__pycache__", ".next"]; +const TAB_WIDTH: f32 = 96.; #[derive(Clone, Copy, PartialEq, Eq)] pub enum Tab { Diff, Files, + Usage, } pub struct ClosePanel; @@ -46,6 +49,7 @@ struct DiffFile { pub struct Panel { pub tab: Tab, + usage: Entity, root: Option, title: String, files: Vec, @@ -87,7 +91,7 @@ fn collect(dir: &Path, needle: &str, out: &mut Vec) { } impl Panel { - pub fn new(window: &mut Window, cx: &mut Context) -> Self { + pub fn new(usage: Entity, window: &mut Window, cx: &mut Context) -> Self { let search = cx.new(|cx| InputState::new(window, cx).placeholder("Search files")); let subscription = cx.subscribe(&search, |this, search, event: &InputEvent, cx| { if let InputEvent::Change = event { @@ -101,6 +105,7 @@ impl Panel { }); Panel { tab: Tab::Diff, + usage, root: None, title: String::new(), files: Vec::new(), @@ -156,6 +161,11 @@ impl Panel { cx.notify(); } + pub fn show_usage(&mut self, cx: &mut Context) { + self.tab = Tab::Usage; + cx.notify(); + } + fn select(&mut self, tab: Tab, cx: &mut Context) { self.tab = tab; cx.notify(); @@ -204,15 +214,15 @@ impl Panel { let on = self.tab == tab; div() .id(label) + .w(px(TAB_WIDTH)) .flex() .items_center() + .justify_center() .gap(px(6.)) - .h(px(28.)) - .px(px(10.)) + .h(px(26.)) .rounded(px(8.)) .text_size(px(13.)) .text_color(if on { p.text } else { p.text_faint }) - .when(on, |b| b.bg(p.row_active)) .cursor_pointer() .hover(move |style| style.text_color(p.text)) .child(icon(name, 14., if on { p.text } else { p.text_faint })) @@ -220,6 +230,39 @@ impl Panel { .on_click(cx.listener(move |this, _, _, cx| this.select(tab, cx))) } + fn tabs(&self, p: Palette, cx: &mut Context) -> impl IntoElement + use<> { + let index = match self.tab { + Tab::Diff => 0., + Tab::Files => 1., + Tab::Usage => 2., + }; + div() + .relative() + .flex() + .p(px(3.)) + .rounded(px(10.)) + .bg(p.fill) + .child( + div() + .absolute() + .top(px(3.)) + .w(px(TAB_WIDTH)) + .h(px(26.)) + .rounded(px(8.)) + .bg(p.raised) + .border_1() + .border_color(p.border_soft) + .with_spring( + "panel-tab-indicator", + SpringAnimation::new(SpringConfig::new(420., 40., 1.)).to(px(3. + index * TAB_WIDTH)), + |el, x| el.left(x), + ), + ) + .child(self.tab_button(Tab::Diff, Icon::FileDiff, "Review", p, cx)) + .child(self.tab_button(Tab::Files, Icon::Files, "Files", p, cx)) + .child(self.tab_button(Tab::Usage, Icon::Gauge, "Usage", p, cx)) + } + fn diff_tab(&self, p: Palette, cx: &mut Context) -> impl IntoElement + use<> { let added: usize = self.files.iter().map(|f| f.added).sum(); let removed: usize = self.files.iter().map(|f| f.removed).sum(); @@ -475,6 +518,7 @@ impl Render for Panel { let body = match self.tab { Tab::Diff => self.diff_tab(p, cx).into_any_element(), Tab::Files => self.files_tab(p, cx).into_any_element(), + Tab::Usage => self.usage.clone().into_any_element(), }; div() .size_full() @@ -491,8 +535,7 @@ impl Render for Panel { .px(px(8.)) .border_b_1() .border_color(p.border_soft) - .child(self.tab_button(Tab::Diff, Icon::FileDiff, "Review", p, cx)) - .child(self.tab_button(Tab::Files, Icon::Files, "Files", p, cx)) + .child(self.tabs(p, cx)) .child(div().flex_1()) .child( div() diff --git a/crates/quill-code/src/project.rs b/crates/quill-code/src/project.rs index d6c3684..c64a7e5 100644 --- a/crates/quill-code/src/project.rs +++ b/crates/quill-code/src/project.rs @@ -4,9 +4,8 @@ use std::process::{Command, Stdio}; use gpui_kit::{Hsla, hsla}; -use crate::config::projects_dir; -use crate::git::{self, hidden}; -use crate::github::{self, Visibility}; +use quill_git::github::{self, Visibility}; +use quill_git::{self as git, hidden}; pub fn name(path: &Path) -> String { path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| path.display().to_string()) @@ -42,6 +41,23 @@ pub fn open_folder(path: &Path) { let _ = Command::new("explorer").arg(path).spawn(); } +pub fn short_path(path: &Path) -> String { + let home = quill_config::home_dir(); + let shown = match path.strip_prefix(&home) { + Ok(rest) if !home.as_os_str().is_empty() => Path::new("~").join(rest), + _ => path.to_path_buf(), + }; + let parts: Vec = shown.components().map(|c| c.as_os_str().to_string_lossy().into_owned()).collect(); + if parts.len() <= 4 { + return shown.display().to_string(); + } + format!("{}\\…\\{}", parts[0], parts[parts.len() - 2..].join("\\")) +} + +pub fn open_file(path: &Path) { + let _ = hidden("cmd").args(["/C", "start", ""]).arg(path).spawn(); +} + pub fn clean_name(raw: &str) -> String { raw.trim() .chars() @@ -56,12 +72,12 @@ pub struct Created { pub note: Option, } -pub fn create(raw: &str, git_branch: Option<&str>, publish: Option) -> Result { +pub fn create(base: &Path, raw: &str, git_branch: Option<&str>, publish: Option) -> Result { let name = clean_name(raw); if name.is_empty() { return Err("Give the project a name.".into()); } - let dir = projects_dir().join(&name); + let dir = base.join(&name); if dir.exists() { return Err(format!("{} already exists.", dir.display())); } @@ -82,13 +98,12 @@ pub fn repo_name(url: &str) -> String { clean_name(last.trim_end_matches(".git")) } -pub fn clone(url: &str) -> Result { +pub fn clone(base: &Path, url: &str) -> Result { let name = repo_name(url); if name.is_empty() { return Err("That does not look like a Git URL.".into()); } - let base = projects_dir(); - fs::create_dir_all(&base).map_err(|e| e.to_string())?; + fs::create_dir_all(base).map_err(|e| e.to_string())?; let mut dir = base.join(&name); let mut n = 2; while dir.exists() { diff --git a/crates/quill-code/src/publish.rs b/crates/quill-code/src/publish.rs deleted file mode 100644 index 362a619..0000000 --- a/crates/quill-code/src/publish.rs +++ /dev/null @@ -1,35 +0,0 @@ -use std::path::Path; - -use quill_agent::Publisher; - -use crate::{git, github}; - -pub struct GitPublisher; - -impl Publisher for GitPublisher { - fn commit(&self, root: &Path, message: &str, branch: Option<&str>) -> Result { - if let Some(branch) = branch.filter(|b| git::branch(root).as_deref() != Some(*b)) { - if !git::valid_branch(branch) { - return Err(format!("\"{branch}\" is not a branch name Git accepts.")); - } - git::create_branch(root, branch).or_else(|_| git::switch_branch(root, branch))?; - } - let sha = git::commit_all(root, message)?; - let on = git::branch(root).unwrap_or_else(|| "a detached HEAD".into()); - Ok(format!("Committed {sha} on {on}.")) - } - - fn open_pull_request(&self, root: &Path, title: &str, body: &str) -> Result { - let branch = git::branch(root).ok_or("Not on a branch. Commit to a new branch with commit_changes first.")?; - let base = git::default_branch(root); - if branch == base { - return Err(format!("You are on {base}, the main branch. Commit the work to a new branch with commit_changes first.")); - } - let remote = - git::remote_url(root).ok_or("This repository has no remote called origin, so there is nowhere to open a pull request.")?; - let slug = git::github_slug(&remote).ok_or("Pull requests can only be opened for repositories on GitHub.")?; - git::push(root, &branch)?; - let url = github::create_pull_request(&slug, &branch, &base, title, body)?; - Ok(format!("Pushed {branch} and opened a pull request into {base}: {url}")) - } -} \ No newline at end of file diff --git a/crates/quill-code/src/settings.rs b/crates/quill-code/src/settings.rs index 6da5647..6f83c0e 100644 --- a/crates/quill-code/src/settings.rs +++ b/crates/quill-code/src/settings.rs @@ -1,41 +1,64 @@ use std::time::Duration; -use gpui_kit::component::input::{Input, InputEvent, InputState, Textarea, TextareaState}; -use gpui_kit::component::switch::Switch; +use gpui_kit::component::Icon as ComponentIcon; +use gpui_kit::component::input::{Input, InputState, Textarea, TextareaState}; +use gpui_kit::component::setting::{ + NumberFieldOptions, SelectIndex, SettingField, SettingGroup, SettingItem, SettingPage, Settings as Pages, +}; use gpui_kit::{ - AnyElement, Context, Div, Entity, EventEmitter, FontWeight, IntoElement, ParentElement, Render, SharedString, Styled, Subscription, - Window, div, prelude::*, px, svg, + AnyElement, App, Context, Div, Entity, EventEmitter, FontWeight, IntoElement, ParentElement, Render, SharedString, Styled, + Subscription, WeakEntity, Window, div, prelude::*, px, }; -use quill_agent::Access; -use quill_llama::{Status, context_label}; +use quill_config::{Motion, Reasoning, Settings as Prefs, Theme, settings_path}; +use quill_core::{Access, Rule, RuleAction, Shell}; -use crate::backend::{Backend, Connection}; -use crate::composer::access_icon; +use crate::backend::Backend; use crate::config::{Config, personal_instructions_path, read_personal_instructions, write_personal_instructions}; use crate::icons::Icon; use crate::palette::{Palette, palette}; use crate::project; -use crate::ui::{badge, icon, page}; +use crate::ui::{Tone, badge, button, icon}; use crate::version::VersionPage; #[derive(Clone, Copy, PartialEq, Eq)] pub enum Section { General, + Appearance, Models, + Agent, + Tools, + Permissions, Instructions, Projects, + Advanced, Version, } impl Section { - const ALL: [Section; 5] = [Section::General, Section::Models, Section::Instructions, Section::Projects, Section::Version]; + const ALL: [Section; 10] = [ + Section::General, + Section::Appearance, + Section::Models, + Section::Agent, + Section::Tools, + Section::Permissions, + Section::Instructions, + Section::Projects, + Section::Advanced, + Section::Version, + ]; fn label(self) -> &'static str { match self { Section::General => "General", + Section::Appearance => "Appearance", Section::Models => "Models", + Section::Agent => "Agent", + Section::Tools => "Tools", + Section::Permissions => "Permissions", Section::Instructions => "Instructions", Section::Projects => "Projects", + Section::Advanced => "Advanced", Section::Version => "Version", } } @@ -43,9 +66,14 @@ impl Section { fn icon(self) -> Icon { match self { Section::General => Icon::Sliders, + Section::Appearance => Icon::Palette, Section::Models => Icon::Cube, + Section::Agent => Icon::Bolt, + Section::Tools => Icon::Wrench, + Section::Permissions => Icon::Shield, Section::Instructions => Icon::FileText, Section::Projects => Icon::Folder, + Section::Advanced => Icon::Gear, Section::Version => Icon::Info, } } @@ -57,12 +85,12 @@ pub enum SettingsEvent { } pub struct Settings { - pub section: Section, + section: Section, + opened: usize, backend: Entity, - url: Entity, instructions: Entity, version: Entity, - saved: Option>, + note: Entity>, _subscriptions: Vec, } @@ -70,389 +98,752 @@ impl EventEmitter for Settings {} impl Settings { pub fn new(backend: Entity, window: &mut Window, cx: &mut Context) -> Self { - let url_text = Backend::url(cx); - let url = cx.new(|cx| InputState::new(window, cx).placeholder("http://127.0.0.1:9931").default_value(url_text)); let instructions = cx.new(|cx| { TextareaState::new(window, cx) .placeholder("For example: Prefer small, focused changes. Explain risky changes before making them.") .auto_grow(8, 28) .default_value(read_personal_instructions()) }); + let note = cx.new(|_| None); let subscriptions = vec![ - cx.subscribe_in(&url, window, |this, _, event: &InputEvent, _, cx| { - if let InputEvent::PressEnter { .. } = event { - this.connect(cx); - } - }), cx.observe(&backend, |_, _, cx| cx.notify()), + cx.observe(¬e, |_, _, cx| cx.notify()), + cx.observe_global::(|_, cx| cx.notify()), ]; Settings { section: Section::General, + opened: 0, backend, - url, instructions, version: cx.new(VersionPage::new), - saved: None, + note, _subscriptions: subscriptions, } } pub fn open(&mut self, section: Section, cx: &mut Context) { self.section = section; + self.opened += 1; if section == Section::Models { self.backend.update(cx, |b, cx| b.refresh(cx)); } cx.notify(); } - fn connect(&mut self, cx: &mut Context) { - let url = self.url.read(cx).value().to_string(); - if !url.trim().is_empty() { - self.backend.update(cx, |backend, cx| backend.set_url(&url, cx)); - } + fn pages(&self, this: WeakEntity, cx: &App) -> Vec { + Section::ALL + .iter() + .map(|section| { + let page = SettingPage::new(section.label()).icon(ComponentIcon::empty().path(section.icon().path())).resettable(false); + let groups = match section { + Section::General => general(), + Section::Appearance => appearance(), + Section::Models => crate::model_settings::groups(self.backend.clone(), self.note.clone(), cx), + Section::Agent => agent(), + Section::Tools => tools(), + Section::Permissions => permissions(), + Section::Instructions => vec![instructions(self.instructions.clone(), self.note.clone())], + Section::Projects => vec![projects(this.clone())], + Section::Advanced => advanced(self.note.clone()), + Section::Version => { + let version = self.version.clone(); + vec![SettingGroup::new().item(SettingItem::render(move |_, _, _| div().w_full().child(version.clone())))] + } + }; + page.groups(groups) + }) + .collect() } +} - fn save_instructions(&mut self, cx: &mut Context) { - let text = self.instructions.read(cx).value().to_string(); - self.saved = Some(write_personal_instructions(&text).map_err(|e| e.to_string().into())); - cx.notify(); - cx.spawn(async move |this, cx| { - cx.background_executor().timer(Duration::from_millis(1600)).await; - _ = this.update(cx, |this, cx| { - if matches!(this.saved, Some(Ok(()))) { - this.saved = None; - cx.notify(); - } - }); - }) - .detach(); +pub(crate) fn change(cx: &mut App, edit: impl FnOnce(&mut Prefs)) { + Config::update(cx, edit); +} + +fn switch(title: &str, description: &str, get: fn(&Prefs) -> bool, set: fn(&mut Prefs, bool)) -> SettingItem { + let default = get(&Prefs::default()); + SettingItem::new( + title.to_string(), + SettingField::switch(move |cx| get(Config::get(cx)), move |on, cx| change(cx, |s| set(s, on))).default_value(default), + ) + .description(description.to_string()) +} + +fn number(title: &str, description: &str, range: (f64, f64, f64), get: fn(&Prefs) -> f64, set: fn(&mut Prefs, f64)) -> SettingItem { + let (min, max, step) = range; + let default = get(&Prefs::default()); + SettingItem::new( + title.to_string(), + SettingField::number_input( + NumberFieldOptions { min, max, step }, + move |cx| get(Config::get(cx)), + move |value, cx| change(cx, |s| set(s, value.clamp(min, max))), + ) + .default_value(default), + ) + .description(description.to_string()) +} + +fn choice( + title: &str, + description: &str, + options: Vec<(&'static str, &'static str)>, + get: fn(&Prefs) -> &'static str, + set: fn(&mut Prefs, &str), +) -> SettingItem { + let default = get(&Prefs::default()); + let options = options.into_iter().map(|(value, label)| (SharedString::from(value), SharedString::from(label))).collect(); + SettingItem::new( + title.to_string(), + SettingField::dropdown(options, move |cx| get(Config::get(cx)).into(), move |value, cx| change(cx, |s| set(s, &value))) + .default_value(default), + ) + .description(description.to_string()) +} + +fn access_key(access: Access) -> &'static str { + match access { + Access::Supervised => "supervised", + Access::AutoEdits => "auto_edits", + Access::Full => "full", } +} - fn nav(&self, p: Palette, cx: &mut Context) -> impl IntoElement + use<> { - div() - .w(px(248.)) - .h_full() - .flex_shrink_0() - .flex() - .flex_col() - .gap(px(1.)) - .px(px(8.)) - .pb(px(8.)) - .child( - div() - .px(px(10.)) - .pt(px(4.)) - .pb(px(12.)) - .text_size(px(16.)) - .font_weight(FontWeight::SEMIBOLD) - .text_color(p.text) - .child("Settings"), - ) - .children(Section::ALL.map(|section| { - let on = self.section == section; - div() - .id(section.label()) - .flex() - .items_center() - .gap(px(10.)) - .h(px(34.)) - .px(px(10.)) - .rounded(px(8.)) - .text_size(px(14.)) - .text_color(if on { p.text } else { p.sidebar_text }) - .cursor_pointer() - .when(on, |row| row.bg(p.row_active)) - .hover(move |style| style.bg(p.row_hover).text_color(p.text)) - .child(icon(section.icon(), 16., if on { p.text } else { p.sidebar_text })) - .child(section.label()) - .on_click(cx.listener(move |this, _, _, cx| this.open(section, cx))) - })) - .child(div().flex_1()) - .child( - div() - .id("settings-back") - .flex() - .items_center() - .gap(px(10.)) - .h(px(34.)) - .px(px(10.)) - .rounded(px(8.)) - .text_size(px(14.)) - .text_color(p.sidebar_text) - .cursor_pointer() - .hover(move |style| style.bg(p.row_hover).text_color(p.text)) - .child(icon(Icon::ArrowLeft, 16., p.sidebar_text)) - .child("Back") - .on_click(cx.listener(|_, _, _, cx| cx.emit(SettingsEvent::Back))), - ) +fn shell_key(shell: Shell) -> &'static str { + match shell { + Shell::PowerShell => "powershell", + Shell::Pwsh => "pwsh", + Shell::Cmd => "cmd", + Shell::Bash => "bash", + Shell::Sh => "sh", } +} - fn general(&self, p: Palette, cx: &mut Context) -> AnyElement { - let config = Config::get(cx).clone(); - div() - .flex() - .flex_col() - .child(heading("New threads", p)) - .child( - card(p) - .child(row( - "Permissions", - "What agents may do without asking. You can also change it from the prompt box.", - div().flex().flex_col().gap(px(2.)).w(px(260.)).children(Access::ALL.map(|access| { - let on = config.access == access; - div() - .id(access.label()) - .flex() - .items_center() - .gap(px(8.)) - .h(px(30.)) - .px(px(10.)) - .rounded(px(8.)) - .text_size(px(13.5)) - .text_color(if on { p.text } else { p.text_muted }) - .when(on, |seg| seg.bg(p.row_active)) - .cursor_pointer() - .hover(move |style| style.bg(p.row_hover)) - .child(icon(access_icon(access), 14., if on { p.text } else { p.text_faint })) - .child(access.label()) - .on_click(cx.listener(move |_, _, _, cx| { - Config::update(cx, |config| config.access = access); - cx.notify(); - })) - })), - p, - )) - .child(row( - "Thinking", - "Let models that support it think before they answer. Detected from each model's chat template.", - Switch::new("thinking-default").checked(config.thinking).on_click({ - let backend = self.backend.clone(); - move |on, _, cx| backend.update(cx, |b, cx| b.set_thinking(*on, cx)) - }), - p, - )), - ) - .into_any_element() +fn general() -> Vec { + vec![ + SettingGroup::new() + .title("New threads") + .item(choice( + "Permissions", + "What agents may do without asking. You can also change it from the prompt box.", + Access::ALL.iter().map(|a| (access_key(*a), a.label())).collect(), + |s| access_key(s.agent.access), + |s, value| s.agent.access = Access::ALL.into_iter().find(|a| access_key(*a) == value).unwrap_or_default(), + )) + .item(switch( + "Remember the last project", + "New threads start in the project you used last, even after a restart.", + |s| s.general.remember_project, + |s, on| s.general.remember_project = on, + )), + SettingGroup::new() + .title("Folders") + .item(path_item( + "projects-dir", + "New projects", + "Where new and cloned projects are created.", + |s| s.projects_dir(), + |s, path| s.general.projects_dir = path, + )) + .item(path_item( + "worktrees-dir", + "Isolated copies", + "Where isolated copies of projects are made for threads that should not touch your working folder.", + |s| s.worktrees_dir(), + |s, path| s.general.worktrees_dir = path, + )), + ] +} + +fn theme_key(theme: Theme) -> &'static str { + match theme { + Theme::System => "system", + Theme::Dark => "dark", + Theme::Light => "light", } +} - fn models(&self, p: Palette, cx: &mut Context) -> AnyElement { - let backend = self.backend.read(cx); - let (color, status): (_, SharedString) = match &backend.connection { - Connection::Checking => (p.text_faint, "Connecting".into()), - Connection::Online => { - let count = backend.models.len(); - (p.success, format!("Connected · {count} {}", if count == 1 { "model" } else { "models" }).into()) - } - Connection::Offline(error) => (p.danger, error.clone()), - }; - let selected = Backend::selected_id(cx); - let models: Vec<_> = backend.models.clone(); - div() - .flex() - .flex_col() - .child(heading("llama.cpp", p)) - .child( - card(p) - .child( - div() - .flex() - .flex_col() - .gap(px(10.)) - .px(px(18.)) - .py(px(16.)) - .child( - div() - .flex() - .items_center() - .gap(px(10.)) - .child(svg().path(Icon::LlamaCpp.path()).size(px(20.)).text_color(p.text)) - .child( - div() - .flex() - .flex_col() - .child( - div() - .text_size(px(14.5)) - .font_weight(FontWeight::SEMIBOLD) - .text_color(p.text) - .child("Server address"), - ) - .child(div().text_size(px(13.)).text_color(p.text_faint).child( - "In router mode every model the server can load is listed here and in the prompt box.", - )), - ), - ) - .child( - div() - .flex() - .gap(px(8.)) - .child(div().flex_1().child(Input::new(&self.url))) - .child(primary("connect", "Connect", p).on_click(cx.listener(|this, _, _, cx| this.connect(cx)))), - ) - .child( - div() - .flex() - .items_center() - .gap(px(8.)) - .text_size(px(12.5)) - .text_color(p.text_muted) - .child(div().size(px(8.)).flex_shrink_0().rounded_full().bg(color)) - .child(status), - ), - ) - .children(models.into_iter().map(|model| { - let mut detail = vec![model.status.label().to_string()]; - if let Some(context) = model.context { - detail.push(format!("{} context", context_label(context))); - } - if model.vision { - detail.push("Vision".into()); - } - let chosen = selected.as_deref() == Some(model.id.as_str()); - let id = model.id.clone(); - div() - .id(SharedString::from(format!("settings-model-{}", model.id))) - .flex() - .items_center() - .gap(px(12.)) - .px(px(18.)) - .py(px(10.)) - .border_t_1() - .border_color(p.border_soft) - .cursor_pointer() - .hover(move |style| style.bg(p.row_hover)) - .child(div().size(px(8.)).rounded_full().bg(if model.status == Status::Loaded { - p.success - } else { - p.text_faint.opacity(0.4) - })) - .child( - div() - .flex_1() - .flex() - .flex_col() - .child(div().text_size(px(14.)).text_color(p.text).child(model.id.clone())) - .child(div().text_size(px(12.5)).text_color(p.text_faint).child(detail.join(" · "))), - ) - .when(chosen, |row| row.child(div().text_size(px(12.5)).text_color(p.text_muted).child("In use"))) - .on_click(cx.listener(move |this, _, _, cx| { - let id = id.clone(); - this.backend.update(cx, |b, cx| b.select(id, cx)); - })) - })), - ) - .into_any_element() +fn motion_key(motion: Motion) -> &'static str { + match motion { + Motion::Full => "full", + Motion::Reduced => "reduced", + Motion::Off => "off", } +} - fn instructions(&self, p: Palette, cx: &mut Context) -> AnyElement { - let note = match &self.saved { - Some(Ok(())) => Some((p.success, SharedString::from("Saved"))), - Some(Err(error)) => Some((p.danger, error.clone())), - None => None, - }; - div() - .flex() - .flex_col() - .child(heading("Personal instructions", p)) - .child(div().mb(px(12.)).text_size(px(13.5)).text_color(p.text_muted).child(format!( - "Added to every thread, in every project, after the project's own AGENTS.md or CLAUDE.md. Saved as {}", - personal_instructions_path().display() - ))) - .child(Textarea::new(&self.instructions)) - .child( - div() - .flex() - .items_center() - .gap(px(10.)) - .mt(px(12.)) - .child(primary("save-instructions", "Save", p).on_click(cx.listener(|this, _, _, cx| this.save_instructions(cx)))) - .when_some(note, |row, (color, text)| row.child(div().text_size(px(12.5)).text_color(color).child(text))), - ) - .into_any_element() +fn reasoning_key(reasoning: Reasoning) -> &'static str { + match reasoning { + Reasoning::Expanded => "expanded", + Reasoning::Collapsed => "collapsed", + Reasoning::Hidden => "hidden", } +} - fn projects(&self, p: Palette, cx: &mut Context) -> AnyElement { - let projects = Config::get(cx).projects.clone(); - div() - .flex() - .flex_col() - .child(div().flex().items_center().child(div().flex_1().child(heading("Projects", p))).child( - primary("settings-add-project", "Add project", p).on_click(cx.listener(|_, _, _, cx| cx.emit(SettingsEvent::AddProject))), +fn appearance() -> Vec { + vec![ + SettingGroup::new() + .title("Look") + .item(choice( + "Theme", + "Dark, light, or follow Windows as it changes through the day.", + vec![("system", "Match Windows"), ("dark", "Dark"), ("light", "Light")], + |s| theme_key(s.appearance.theme), + |s, value| { + s.appearance.theme = + [Theme::System, Theme::Dark, Theme::Light].into_iter().find(|t| theme_key(*t) == value).unwrap_or_default() + }, )) - .child( - card(p) - .when(projects.is_empty(), |c| { - c.child(div().px(px(18.)).py(px(16.)).text_size(px(13.5)).text_color(p.text_faint).child("No projects yet.")) - }) - .children(projects.into_iter().enumerate().map(|(index, path)| { - let name = project::name(&path); - let open = path.clone(); - div() - .flex() - .items_center() - .gap(px(12.)) - .px(px(18.)) - .py(px(12.)) - .when(index > 0, |r| r.border_t_1().border_color(p.border_soft)) - .child(badge(&name, 22.)) - .child( - div() - .flex_1() - .min_w_0() - .flex() - .flex_col() - .child(div().text_size(px(14.)).text_color(p.text).child(name)) - .child(div().text_size(px(12.5)).text_color(p.text_faint).child(path.display().to_string())), - ) - .child(ghost(("open-project", index), Icon::FolderOpen, p).on_click(move |_, _, _| project::open_folder(&open))) - .child(ghost(("remove-project", index), Icon::Trash, p).on_click(cx.listener(move |_, _, _, cx| { - Config::update(cx, |config| { - config.projects.remove(index); - }); - cx.notify(); - }))) - })), + .item(number( + "Reading width", + "How wide replies and the prompt box may grow, in pixels.", + (560., 1600., 20.), + |s| f64::from(s.appearance.transcript_width), + |s, v| s.appearance.transcript_width = v as u16, + )) + .item(switch( + "Show the sidebar", + "The thread list on the left. Ctrl B toggles it.", + |s| s.appearance.sidebar, + |s, on| s.appearance.sidebar = on, + )), + SettingGroup::new().title("Motion").item(choice( + "Animations", + "Menus, cards and rows ease in and out. Reduced keeps them short; off turns them off everywhere.", + vec![("full", "Full"), ("reduced", "Reduced"), ("off", "Off")], + |s| motion_key(s.appearance.motion), + |s, value| { + s.appearance.motion = + [Motion::Full, Motion::Reduced, Motion::Off].into_iter().find(|m| motion_key(*m) == value).unwrap_or_default() + }, + )), + SettingGroup::new() + .title("Replies") + .item(choice( + "Reasoning", + "How the model's thinking is shown once it has finished.", + vec![("expanded", "Shown"), ("collapsed", "Folded"), ("hidden", "Hidden")], + |s| reasoning_key(s.appearance.reasoning), + |s, value| { + s.appearance.reasoning = [Reasoning::Expanded, Reasoning::Collapsed, Reasoning::Hidden] + .into_iter() + .find(|r| reasoning_key(*r) == value) + .unwrap_or_default() + }, + )) + .item(switch( + "Group exploring", + "Fold a run of reads and searches into a single row you can open.", + |s| s.appearance.group_exploration, + |s, on| s.appearance.group_exploration = on, + )), + ] +} + +fn path_item( + key: &'static str, + title: &str, + description: &str, + get: fn(&Prefs) -> std::path::PathBuf, + set: fn(&mut Prefs, Option), +) -> SettingItem { + SettingItem::new( + title.to_string(), + SettingField::input( + move |cx| get(Config::get(cx)).display().to_string().into(), + move |value, cx| { + let value = value.trim().to_string(); + let path = (!value.is_empty()).then(|| std::path::PathBuf::from(value)); + change(cx, |s| set(s, path)); + }, + ) + .on_reset(move |cx| get(Config::get(cx)) != get(&Prefs::default()), move |_, cx| change(cx, |s| set(s, None))), + ) + .keywords([key]) + .description(description.to_string()) +} + +fn agent() -> Vec { + vec![ + SettingGroup::new() + .title("Turns") + .item(number( + "Most steps per reply", + "How many model calls one reply may make before it stops and waits for you.", + (1., 1000., 5.), + |s| s.agent.max_steps as f64, + |s, v| s.agent.max_steps = v as usize, + )) + .item(switch( + "Read in parallel", + "Run several file reads and searches at the same time when the model asks for them together.", + |s| s.agent.parallel_tools, + |s, on| s.agent.parallel_tools = on, + )), + SettingGroup::new() + .title("Context") + .item(switch( + "Compact automatically", + "When the conversation nears the model's window, summarise earlier turns and trim old tool output.", + |s| s.agent.auto_compact, + |s, on| s.agent.auto_compact = on, + )) + .item(number( + "Compact at", + "How full the window gets, in percent, before compacting.", + (30., 98., 1.), + |s| f64::from(s.agent.compact_at), + |s, v| s.agent.compact_at = v as u8, + )), + SettingGroup::new().title("Project instructions").item(list_item( + "instruction-files", + "Instruction files", + "Files read from the project root and given to the agent, in this order.", + "AGENTS.md", + |s| s.agent.instruction_files.clone(), + |s, list| s.agent.instruction_files = list, + )), + ] +} + +fn tools() -> Vec { + let mut available = + SettingGroup::new().title("Available tools").description("Turn a tool off and the agent is never offered it.").item(switch( + "Git tools", + "Offer commit_changes and open_pull_request in projects that use Git.", + |s| s.tools.git, + |s, on| s.tools.git = on, + )); + for tool in quill_core::tools::all() { + let spec = tool.spec(); + let name = spec.name; + available = available.item( + SettingItem::new( + spec.title, + SettingField::switch( + move |cx| !Config::get(cx).tools.disabled.iter().any(|t| t == name), + move |on, cx| { + change(cx, |s| { + s.tools.disabled.retain(|t| t != name); + if !on { + s.tools.disabled.push(name.to_string()); + } + }) + }, + ) + .default_value(true), ) - .into_any_element() + .description(spec.summary) + .keywords([name]), + ); } + vec![ + SettingGroup::new() + .title("Commands") + .item(choice( + "Shell", + "The shell the agent's commands run in.", + Shell::ALL.iter().map(|shell| (shell_key(*shell), shell.label())).collect(), + |s| shell_key(s.tools.shell), + |s, value| s.tools.shell = Shell::ALL.into_iter().find(|shell| shell_key(*shell) == value).unwrap_or_default(), + )) + .item(number( + "Command timeout", + "Seconds a command may run when the agent does not ask for longer.", + (5., 3600., 5.), + |s| s.tools.command_timeout as f64, + |s, v| s.tools.command_timeout = v as u64, + )) + .item(number( + "Longest timeout", + "The most seconds the agent may ask a single command to run.", + (10., 7200., 10.), + |s| s.tools.max_command_timeout as f64, + |s, v| s.tools.max_command_timeout = v as u64, + )), + SettingGroup::new() + .title("Output") + .item(number( + "Command output", + "Characters of command output kept for the model; the middle is cut beyond this.", + (1000., 500_000., 1000.), + |s| s.tools.max_output as f64, + |s, v| s.tools.max_output = v as usize, + )) + .item(number( + "Lines per read", + "The most lines one read_file call returns.", + (50., 20_000., 50.), + |s| s.tools.max_read_lines as f64, + |s, v| s.tools.max_read_lines = v as usize, + )) + .item(number( + "Search matches", + "The most matches grep and find_files return.", + (10., 5000., 10.), + |s| s.tools.max_matches as f64, + |s, v| s.tools.max_matches = v as usize, + )) + .item(number( + "Folder entries", + "The most entries list_dir shows.", + (20., 5000., 20.), + |s| s.tools.max_list as f64, + |s, v| s.tools.max_list = v as usize, + )), + SettingGroup::new().title("Files").item(list_item( + "ignored-folders", + "Skipped folders", + "Folders the file tools never look inside, on top of .gitignore.", + "node_modules", + |s| s.tools.ignored.clone(), + |s, list| s.tools.ignored = list, + )), + available, + ] } -fn heading(text: &'static str, p: Palette) -> Div { - div().pb(px(10.)).text_size(px(15.)).text_color(p.text_muted).child(text) +fn permissions() -> Vec { + vec![ + SettingGroup::new() + .title("Rules") + .description("Rules override the permission mode. A pattern matches a command's start, or anything when empty; end it with * to match a prefix.") + .item(SettingItem::render(|_, window, cx| rules_editor(window, cx)).keywords(["allow", "deny", "ask", "rule"])), + SettingGroup::new().title("Read-only commands").item(list_item( + "safe-commands", + "Commands that only look", + "With Trust edits, commands made only of these run without asking.", + "git status", + |s| s.permissions.safe_commands.clone(), + |s, list| s.permissions.safe_commands = list, + )), + ] } -fn card(p: Palette) -> Div { +fn action_label(action: RuleAction) -> &'static str { + match action { + RuleAction::Allow => "Allow", + RuleAction::Ask => "Ask", + RuleAction::Deny => "Deny", + } +} + +fn rules_editor(window: &mut Window, cx: &mut App) -> AnyElement { + let p = palette(cx); + let tool = window.use_keyed_state("rule-tool", cx, |window, cx| InputState::new(window, cx).placeholder("Tool, such as shell, or *")); + let pattern = + window.use_keyed_state("rule-pattern", cx, |window, cx| InputState::new(window, cx).placeholder("Pattern, such as npm test")); + let rules = Config::get(cx).permissions.rules.clone(); + let add = |action: RuleAction| { + let tool = tool.clone(); + let pattern = pattern.clone(); + move |_: &gpui_kit::ClickEvent, window: &mut Window, cx: &mut App| { + let name = tool.read(cx).value().trim().to_string(); + if name.is_empty() { + return; + } + let text = pattern.read(cx).value().trim().to_string(); + change(cx, |s| s.permissions.rules.push(Rule { tool: name, pattern: text, action })); + tool.update(cx, |input, cx| input.set_value("", window, cx)); + pattern.update(cx, |input, cx| input.set_value("", window, cx)); + } + }; div() - .mb(px(28.)) - .rounded(px(14.)) - .bg(p.surface_2.opacity(0.5)) - .border_1() - .border_color(p.border_soft) + .w_full() .flex() .flex_col() - .overflow_hidden() + .gap(px(8.)) + .when(rules.is_empty(), |col| col.child(div().text_size(px(13.)).text_color(p.text_faint).child("No rules yet."))) + .children(rules.into_iter().enumerate().map(|(index, rule)| { + let tone = match rule.action { + RuleAction::Allow => p.success, + RuleAction::Ask => p.warning, + RuleAction::Deny => p.danger, + }; + div() + .flex() + .items_center() + .gap(px(10.)) + .px(px(10.)) + .py(px(6.)) + .rounded(px(8.)) + .bg(p.fill) + .child( + div() + .px(px(6.)) + .rounded(px(5.)) + .bg(tone.opacity(0.14)) + .text_size(px(12.)) + .text_color(tone) + .child(action_label(rule.action)), + ) + .child(div().font_family(crate::ui::MONO).text_size(px(13.)).text_color(p.text).child(rule.tool.clone())) + .child( + div() + .flex_1() + .min_w_0() + .font_family(crate::ui::MONO) + .text_size(px(13.)) + .text_color(p.text_muted) + .child(if rule.pattern.is_empty() { "anything".to_string() } else { rule.pattern.clone() }), + ) + .child(ghost(("remove-rule", index), Icon::X, p).on_click(move |_, _, cx| { + change(cx, |s| { + if index < s.permissions.rules.len() { + s.permissions.rules.remove(index); + } + }) + })) + })) + .child( + div() + .flex() + .gap(px(8.)) + .child(div().w(px(180.)).child(Input::new(&tool))) + .child(div().flex_1().child(Input::new(&pattern))) + .child(secondary("add-allow", "Allow", p).on_click(add(RuleAction::Allow))) + .child(secondary("add-ask", "Ask", p).on_click(add(RuleAction::Ask))) + .child(secondary("add-deny", "Deny", p).on_click(add(RuleAction::Deny))), + ) + .into_any_element() +} + +fn list_item( + key: &'static str, + title: &str, + description: &str, + placeholder: &'static str, + get: fn(&Prefs) -> Vec, + set: fn(&mut Prefs, Vec), +) -> SettingItem { + let title = title.to_string(); + let description = description.to_string(); + SettingItem::render(move |_, window, cx| list_editor(key, &title, &description, placeholder, get, set, window, cx)) + .keywords([key, placeholder]) + .on_reset(move |cx| get(Config::get(cx)) != get(&Prefs::default()), move |_, cx| change(cx, |s| set(s, get(&Prefs::default())))) } -fn row(title: &'static str, detail: &'static str, control: impl IntoElement, p: Palette) -> Div { +#[allow(clippy::too_many_arguments)] +fn list_editor( + key: &'static str, + title: &str, + description: &str, + placeholder: &'static str, + get: fn(&Prefs) -> Vec, + set: fn(&mut Prefs, Vec), + window: &mut Window, + cx: &mut App, +) -> AnyElement { + let p = palette(cx); + let input = + window.use_keyed_state(key, cx, |window, cx| InputState::new(window, cx).placeholder(format!("Add, such as {placeholder}"))); + let items = get(Config::get(cx)); + let adding = input.clone(); div() + .w_full() .flex() - .items_center() - .gap(px(24.)) - .px(px(18.)) - .py(px(16.)) - .border_b_1() - .border_color(p.border_soft) + .flex_col() + .gap(px(8.)) .child( div() - .flex_1() - .min_w_0() .flex() .flex_col() - .gap(px(3.)) - .child(div().text_size(px(14.5)).font_weight(FontWeight::SEMIBOLD).text_color(p.text).child(title)) - .child(div().text_size(px(13.)).text_color(p.text_faint).child(detail)), + .gap(px(2.)) + .child(div().text_sm().text_color(p.text).child(title.to_string())) + .child(div().text_sm().text_color(p.text_faint).child(description.to_string())), ) - .child(control) + .child(div().flex().flex_wrap().gap(px(6.)).children(items.iter().enumerate().map(|(index, item)| { + div() + .flex() + .items_center() + .gap(px(4.)) + .pl(px(9.)) + .pr(px(3.)) + .h(px(26.)) + .rounded(px(7.)) + .bg(p.fill) + .border_1() + .border_color(p.border_soft) + .font_family(crate::ui::MONO) + .text_size(px(12.5)) + .text_color(p.text) + .child(item.clone()) + .child(ghost((SharedString::from(format!("{key}-remove")), index), Icon::X, p).size(px(20.)).on_click(move |_, _, cx| { + change(cx, |s| { + let mut list = get(s); + if index < list.len() { + list.remove(index); + } + set(s, list); + }) + })) + }))) + .child(div().flex().gap(px(8.)).child(div().flex_1().child(Input::new(&input))).child( + secondary(SharedString::from(format!("{key}-add")), "Add", p).on_click(move |_, window, cx| { + let value = adding.read(cx).value().trim().to_string(); + if value.is_empty() { + return; + } + change(cx, |s| { + let mut list = get(s); + if !list.contains(&value) { + list.push(value); + } + set(s, list); + }); + adding.update(cx, |input, cx| input.set_value("", window, cx)); + }), + )) + .into_any_element() +} + +fn instructions(textarea: Entity, note: Entity>) -> SettingGroup { + SettingGroup::new() + .title("Personal instructions") + .description(format!( + "Added to every thread, in every project, after the project's own instruction files. Saved as {}", + personal_instructions_path().display() + )) + .item(SettingItem::render(move |_, _, cx| { + let p = palette(cx); + let shown = note.read(cx).clone(); + let save_text = textarea.clone(); + let save_note = note.clone(); + div().w_full().flex().flex_col().gap(px(12.)).child(Textarea::new(&textarea)).child( + div() + .flex() + .items_center() + .gap(px(10.)) + .child(primary("save-instructions", "Save", p).on_click(move |_, _, cx| { + let text = save_text.read(cx).value().to_string(); + let result = write_personal_instructions(&text); + show_note(&save_note, result.map(|_| "Saved".into()).map_err(|e| e.to_string()), cx); + })) + .when_some(shown, |row, (ok, text)| { + row.child(div().text_size(px(12.5)).text_color(if ok { p.success } else { p.danger }).child(text)) + }), + ) + })) +} + +pub(crate) fn show_note(note: &Entity>, result: Result, cx: &mut App) { + let value = match result { + Ok(text) => (true, SharedString::from(text)), + Err(error) => (false, SharedString::from(error)), + }; + note.update(cx, |note, cx| { + *note = Some(value); + cx.notify(); + }); + let note = note.clone(); + cx.spawn(async move |cx| { + cx.background_executor().timer(Duration::from_millis(1800)).await; + note.update(cx, |note, cx| { + *note = None; + cx.notify(); + }); + }) + .detach(); +} + +fn projects(this: WeakEntity) -> SettingGroup { + SettingGroup::new().title("Projects").item(SettingItem::render(move |_, _, cx| { + let p = palette(cx); + let projects = Config::get(cx).general.projects.clone(); + div() + .w_full() + .flex() + .flex_col() + .gap(px(4.)) + .when(projects.is_empty(), |c| c.child(div().text_size(px(13.5)).text_color(p.text_faint).child("No projects yet."))) + .children(projects.into_iter().enumerate().map(|(index, path)| { + let name = project::name(&path); + let open = path.clone(); + div() + .flex() + .items_center() + .gap(px(12.)) + .py(px(8.)) + .child(badge(&name, 22.)) + .child( + div() + .flex_1() + .min_w_0() + .flex() + .flex_col() + .child(div().text_size(px(14.)).text_color(p.text).child(name)) + .child(div().text_size(px(12.5)).text_color(p.text_faint).text_ellipsis().child(path.display().to_string())), + ) + .child(ghost(("open-project", index), Icon::FolderOpen, p).on_click(move |_, _, _| project::open_folder(&open))) + .child(ghost(("remove-project", index), Icon::Trash, p).on_click(move |_, _, cx| { + change(cx, |s| { + if index < s.general.projects.len() { + s.general.projects.remove(index); + } + }) + })) + })) + .child(div().pt(px(6.)).child({ + let this = this.clone(); + primary("settings-add-project", "Add project", p).on_click(move |_, _, cx| { + let _ = this.update(cx, |_, cx| cx.emit(SettingsEvent::AddProject)); + }) + })) + })) +} + +fn advanced(note: Entity>) -> Vec { + vec![SettingGroup::new().title("Settings file").item(SettingItem::render(move |_, _, cx| { + let p = palette(cx); + let error = Config::error(cx); + let shown = note.read(cx).clone(); + let reload_note = note.clone(); + let reset_note = note.clone(); + div() + .w_full() + .flex() + .flex_col() + .gap(px(12.)) + .child(div().text_size(px(13.)).text_color(p.text_faint).child(format!( + "Every setting lives in {}. A project can override any of them in .quill/settings.json at its root.", + settings_path().display() + ))) + .when_some(error, |col, error| { + col.child( + div() + .px(px(12.)) + .py(px(10.)) + .rounded(px(10.)) + .bg(p.danger.opacity(0.1)) + .text_size(px(13.)) + .text_color(p.danger) + .child(format!("{error}. Changes made here are not saved until the file is fixed or reset.")), + ) + }) + .child( + div() + .flex() + .items_center() + .gap(px(8.)) + .child(secondary("open-settings-file", "Open the file", p).on_click(|_, _, _| project::open_file(&settings_path()))) + .child(secondary("reload-settings", "Reload", p).on_click(move |_, _, cx| { + let changed = Config::reload(cx); + show_note(&reload_note, Ok(if changed { "Reloaded".into() } else { "Already up to date".into() }), cx); + })) + .child(button("reset-settings", "Reset to defaults", Tone::Danger, p).on_click(move |_, _, cx| { + let current = Config::get(cx).clone(); + let mut fresh = Prefs::default(); + fresh.general.projects = current.general.projects; + fresh.models.providers = current.models.providers; + fresh.models.selected = current.models.selected; + fresh.models.pinned = current.models.pinned; + Config::replace(cx, fresh); + show_note(&reset_note, Ok("Everything else is back to its default".into()), cx); + })) + .when_some(shown, |row, (ok, text)| { + row.child(div().text_size(px(12.5)).text_color(if ok { p.success } else { p.danger }).child(text)) + }), + ) + }))] } fn primary(id: &'static str, label: &'static str, p: Palette) -> gpui_kit::Stateful
{ @@ -464,8 +855,8 @@ fn primary(id: &'static str, label: &'static str, p: Palette) -> gpui_kit::State .h(px(32.)) .px(px(14.)) .rounded(px(8.)) - .bg(p.text) - .text_color(p.bg) + .bg(p.accent) + .text_color(p.accent_text) .text_size(px(13.5)) .font_weight(FontWeight::SEMIBOLD) .cursor_pointer() @@ -473,54 +864,83 @@ fn primary(id: &'static str, label: &'static str, p: Palette) -> gpui_kit::State .child(label) } -fn ghost(id: impl Into, name: Icon, p: Palette) -> gpui_kit::Stateful
{ +pub(crate) fn secondary(id: impl Into, label: &'static str, p: Palette) -> gpui_kit::Stateful
{ + div() + .id(id) + .flex() + .flex_shrink_0() + .items_center() + .justify_center() + .h(px(32.)) + .px(px(12.)) + .rounded(px(8.)) + .border_1() + .border_color(p.border) + .text_color(p.text) + .text_size(px(13.)) + .cursor_pointer() + .hover(move |style| style.bg(p.row_hover)) + .child(label) +} + +pub(crate) fn ghost(id: impl Into, name: Icon, p: Palette) -> gpui_kit::Stateful
{ div() .id(id) .size(px(30.)) .flex() + .flex_shrink_0() .items_center() .justify_center() .rounded(px(8.)) .cursor_pointer() .hover(move |style| style.bg(p.row_hover)) - .child(icon(name, 15., p.text_muted)) + .child(icon(name, 14., p.text_muted)) } impl Render for Settings { fn render(&mut self, _: &mut Window, cx: &mut Context) -> impl IntoElement { let p = palette(cx); - let content = match self.section { - Section::General => self.general(p, cx), - Section::Models => self.models(p, cx), - Section::Instructions => self.instructions(p, cx), - Section::Projects => self.projects(p, cx), - Section::Version => { - return div().size_full().flex().child(self.nav(p, cx)).child(self.main(self.version.clone().into_any_element(), p)); - } - }; - div().size_full().flex().child(self.nav(p, cx)).child( - self.main( - page("settings-page") - .child(div().max_w(px(820.)).mx_auto().px(px(36.)).pt(px(36.)).pb(px(40.)).child(content)) - .into_any_element(), - p, - ), - ) - } -} - -impl Settings { - fn main(&self, content: AnyElement, p: Palette) -> impl IntoElement + use<> { + let page_ix = Section::ALL.iter().position(|s| *s == self.section).unwrap_or(0); div() - .flex_1() - .min_w_0() - .h_full() + .size_full() + .flex() + .flex_col() .bg(p.bg) - .rounded_tl(px(10.)) - .border_t_1() - .border_l_1() - .border_color(p.border_soft) - .overflow_hidden() - .child(content) + .child( + div() + .flex() + .items_center() + .gap(px(10.)) + .px(px(14.)) + .h(px(44.)) + .border_b_1() + .border_color(p.border_soft) + .child( + div() + .id("settings-back") + .flex() + .items_center() + .gap(px(8.)) + .h(px(30.)) + .px(px(10.)) + .rounded(px(8.)) + .text_size(px(13.5)) + .text_color(p.text_muted) + .cursor_pointer() + .hover(move |style| style.bg(p.row_hover).text_color(p.text)) + .child(icon(Icon::ArrowLeft, 15., p.text_muted)) + .child("Back to threads") + .on_click(cx.listener(|_, _, _, cx| cx.emit(SettingsEvent::Back))), + ) + .child(div().text_size(px(15.)).font_weight(FontWeight::SEMIBOLD).text_color(p.text).child("Settings")), + ) + .child( + div().flex_1().min_h_0().child( + Pages::new(SharedString::from(format!("quill-settings-{}", self.opened))) + .sidebar_width(px(240.)) + .default_selected_index(SelectIndex { page_ix, group_ix: None }) + .pages(self.pages(cx.entity().downgrade(), cx)), + ), + ) } } \ No newline at end of file diff --git a/crates/quill-code/src/shell.rs b/crates/quill-code/src/shell.rs index 70618ea..7c8df3f 100644 --- a/crates/quill-code/src/shell.rs +++ b/crates/quill-code/src/shell.rs @@ -5,39 +5,44 @@ use std::time::{Duration, SystemTime, UNIX_EPOCH}; use gpui_kit::component::input::{Input, InputEvent, InputState}; use gpui_kit::component::{Sizable, TitleBar}; use gpui_kit::{ - Anchor, AnyElement, Context, Div, Entity, FontWeight, Hsla, IntoElement, KeystrokeEvent, MouseButton, MouseDownEvent, ParentElement, - Pixels, Point, Render, SharedString, Stateful, StyleRefinement, Styled, Subscription, Task, Window, anchored, deferred, div, point, - prelude::*, px, + Anchor, AnimationExt, AnyElement, Context, Div, Entity, FontWeight, Hsla, IntoElement, KeystrokeEvent, MouseButton, MouseDownEvent, + ParentElement, Pixels, Point, Render, SharedString, SpringAnimation, SpringConfig, Stateful, StyleRefinement, Styled, Subscription, + Task, Window, anchored, deferred, div, point, prelude::*, px, }; -use quill_agent::Approval; +use quill_config::{Motion, ProviderKind, Theme as ThemeChoice}; +use quill_core::Access; +use quill_git::github::{self, PullRequest, PullState}; +use quill_git::{self as git, Snapshot}; use quill_weave::State; use crate::add_project::{AddProject, AddProjectEvent}; -use crate::backend::Backend; +use crate::backend::{Backend, provider_icon}; use crate::commit_dialog::{CommitDialog, CommitEvent}; -use crate::composer::{ApprovalCard, Composer, ComposerEvent, Strip}; +use crate::composer::{ApprovalCard, Composer, ComposerEvent, QuestionCard, Strip, access_icon}; use crate::config::Config; -use crate::git::{self, Snapshot}; -use crate::github::{self, PullRequest, PullState}; use crate::icons::Icon; -use crate::mentions::Command; -use crate::palette::{self, FONT, Palette, palette}; +use crate::mentions::{Command, INIT_PROMPT}; +use crate::motion; +use crate::palette::{self, FONT, palette}; use crate::panel::{ClosePanel, Panel, Tab}; use crate::project; use crate::settings::{Section, Settings, SettingsEvent}; use crate::terminal::{CloseTerminal, Terminal}; use crate::thread::{Item, Thread, ago, now_ms}; -use crate::thread_view::{OpenDiff, ThreadView}; -use crate::ui::{MONO, badge, icon, menu_item, menu_label, menu_panel, popup, separator}; +use crate::thread_view::{ThreadEvent, ThreadView}; +use crate::ui::{MONO, badge, icon, icon_button, kbd, menu_item, menu_label, menu_panel, popup, separator, tip}; +use crate::usage::UsageView; use crate::version::{APP_NAME, VERSION}; use crate::weave::WeaveMark; -use crate::workspace::Workspace; +use crate::workspace::{Prompt, Workspace}; const GREETINGS: [&str; 4] = ["Where should we start?", "What are we building today?", "Ready when you are.", "What needs fixing?"]; +const SIDEBAR: f32 = 280.; #[derive(Clone, Copy, PartialEq)] enum Menu { Project, + Open, Thread(u64, Point), } @@ -50,7 +55,54 @@ struct RepoInfo { snapshot: Snapshot, } +#[derive(Clone, Copy, PartialEq)] +enum ToastKind { + Done, + Problem, +} + +#[derive(Clone)] +struct Toast { + kind: ToastKind, + title: SharedString, + detail: SharedString, + serial: usize, +} + +#[derive(Clone)] +enum Action { + NewThread, + QuickChat, + Project(PathBuf), + AddProject, + Settings(Section), + Sidebar, + Terminal, + Review, + Files, + Usage, + Commit, + Compact, + Stop, + Access(Access), +} + +struct Entry { + icon: Icon, + label: String, + detail: String, + keys: Option<&'static str>, + action: Action, +} + +struct Launcher { + input: Entity, + highlighted: usize, + _subscription: Subscription, +} + pub struct Shell { + backend: Entity, workspace: Entity, composer: Entity, thread_view: Entity, @@ -69,8 +121,11 @@ pub struct Shell { menu: Option, renaming: Option<(u64, Entity, Subscription)>, confirm_delete: Option, - toast: Option<(SharedString, SharedString)>, + toast: Option, + toasts: usize, toast_timer: Option>, + launcher: Option, + appearance: (ThemeChoice, Motion), greeting: &'static str, git: bool, editor: bool, @@ -88,18 +143,24 @@ impl Shell { let workspace = cx.new(|_| Workspace::new(backend.clone())); let composer = cx.new(|cx| Composer::new(backend.clone(), window, cx)); let thread_view = cx.new(|cx| ThreadView::new(workspace.clone(), cx)); - let panel = cx.new(|cx| Panel::new(window, cx)); + let usage = cx.new(|cx| UsageView::new(workspace.clone(), cx)); + let panel = cx.new(|cx| Panel::new(usage, window, cx)); let terminal = cx.new(|cx| Terminal::new(window, cx)); let settings = cx.new(|cx| Settings::new(backend.clone(), window, cx)); - let search = cx.new(|cx| InputState::new(window, cx).placeholder("Find a thread")); + let search = cx.new(|cx| InputState::new(window, cx).placeholder("Search threads")); let weak = cx.entity().downgrade(); let subscriptions = vec![ - cx.observe_window_appearance(window, |_, window, cx| palette::apply(window.appearance(), Some(window), cx)), + cx.observe_window_appearance(window, |_, window, cx| { + let theme = Config::get(cx).appearance.theme; + palette::apply(palette::resolve(theme, window.appearance()), Some(window), cx); + }), + cx.observe_global_in::(window, |this, window, cx| this.apply_appearance(window, cx)), cx.observe(&workspace, |this, _, cx| this.sync(cx)), cx.observe_window_activation(window, |this, window, cx| { if window.is_window_active() { this.repos.clear(); this.pulls.clear(); + Config::reload(cx); this.sync(cx); } }), @@ -115,6 +176,12 @@ impl Shell { this.workspace.update(cx, |w, cx| w.decide(id, decision, cx)); } } + ComposerEvent::Answer(text) => { + let text = text.clone(); + if let Some(id) = this.workspace.read(cx).active { + this.workspace.update(cx, |w, cx| w.answer(id, text, cx)); + } + } ComposerEvent::OpenModelSettings => this.open_settings(Section::Models, window, cx), ComposerEvent::Command(command) => this.run_command(*command, window, cx), ComposerEvent::SetIsolated(isolated) => { @@ -129,7 +196,13 @@ impl Shell { this.sync(cx); } }), - cx.subscribe(&thread_view, |this, _, OpenDiff { thread, turn }, cx| this.open_diff(*thread, Some(*turn), cx)), + cx.subscribe(&thread_view, |this, _, event, cx| match event { + ThreadEvent::OpenDiff { thread, turn } => this.open_diff(*thread, Some(*turn), cx), + ThreadEvent::Retry { thread, turn } => { + let (thread, turn) = (*thread, *turn); + this.workspace.update(cx, |w, cx| w.retry(thread, turn, cx)); + } + }), cx.subscribe(&panel, |this, _, _: &ClosePanel, cx| { this.panel_open = false; cx.notify(); @@ -160,8 +233,15 @@ impl Shell { }), ]; let seed = SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |d| d.as_secs()) as usize; + let settings_now = Config::get(cx).clone(); + if settings_now.general.remember_project + && let Some(path) = settings_now.general.last_project.clone().filter(|p| p.is_dir()) + { + workspace.update(cx, |w, cx| w.start_new(Some(path), cx)); + } composer.update(cx, |composer, cx| composer.focus(window, cx)); let mut shell = Shell { + backend: backend.clone(), workspace, composer, thread_view, @@ -181,7 +261,10 @@ impl Shell { renaming: None, confirm_delete: None, toast: None, + toasts: 0, toast_timer: None, + launcher: None, + appearance: (settings_now.appearance.theme, settings_now.appearance.motion), greeting: GREETINGS[seed % GREETINGS.len()], git: project::git_available(), editor: project::editor_available(), @@ -195,8 +278,75 @@ impl Shell { shell } + fn apply_appearance(&mut self, window: &mut Window, cx: &mut Context) { + let appearance = Config::get(cx).appearance.clone(); + let wanted = (appearance.theme, appearance.motion); + if wanted != self.appearance { + self.appearance = wanted; + palette::apply(palette::resolve(appearance.theme, window.appearance()), Some(window), cx); + motion::apply(appearance.motion, cx); + } + cx.notify(); + } + fn intercept(&mut self, event: &KeystrokeEvent, window: &mut Window, cx: &mut Context) { - if event.keystroke.key != "escape" { + let keystroke = &event.keystroke; + let key = keystroke.key.as_str(); + let control = keystroke.modifiers.control && !keystroke.modifiers.alt; + if self.launcher.is_some() { + match key { + "escape" => self.close_launcher(window, cx), + "up" | "down" => { + let count = self.entries(cx).len().max(1); + if let Some(launcher) = self.launcher.as_mut() { + launcher.highlighted = + if key == "up" { (launcher.highlighted + count - 1) % count } else { (launcher.highlighted + 1) % count }; + } + cx.notify(); + } + "enter" => { + let index = self.launcher.as_ref().map_or(0, |l| l.highlighted); + if let Some(entry) = self.entries(cx).into_iter().nth(index) { + self.close_launcher(window, cx); + self.perform(entry.action, window, cx); + } + } + _ => return, + } + cx.stop_propagation(); + return; + } + if control && !keystroke.modifiers.shift { + let handled = match key { + "k" => { + self.open_launcher(window, cx); + true + } + "n" => { + let project = self.workspace.read(cx).project(); + self.new_thread(project, window, cx); + true + } + "b" => { + self.toggle_sidebar(cx); + true + } + "," => { + self.open_settings(Section::General, window, cx); + true + } + "`" => { + self.toggle_terminal(window, cx); + true + } + _ => false, + }; + if handled { + cx.stop_propagation(); + } + return; + } + if key != "escape" { return; } if self.commit.take().is_some() { @@ -262,21 +412,24 @@ impl Shell { let workdir = workspace.workdir(); let isolated = workspace.isolated(); let locked = workspace.active.is_some(); - let (busy, approval) = match workspace.active { + let (busy, approval, question) = match workspace.active { Some(id) => ( workspace.running(id), - workspace.pending(id).map(|pending| match &pending.approval { - Approval::FileChange(diff) => { - ApprovalCard { title: "Wants to change a file", target: diff.path.clone(), stats: Some((diff.added, diff.removed)) } - } - Approval::Command(command) => ApprovalCard { title: "Wants to run a command", target: command.clone(), stats: None }, - Approval::Commit(message) => ApprovalCard { title: "Wants to commit", target: message.clone(), stats: None }, - Approval::PullRequest(title) => { - ApprovalCard { title: "Wants to open a pull request", target: title.clone(), stats: None } + workspace.pending(id).map(|pending| { + let diffs = &pending.approval.diffs; + let stats = (!diffs.is_empty()).then(|| (diffs.iter().map(|d| d.added).sum(), diffs.iter().map(|d| d.removed).sum())); + ApprovalCard { + title: pending.approval.title.clone(), + target: pending.approval.subject.clone(), + stats, + diffs: pending.approval.diffs.clone(), + similar: pending.approval.similar.clone(), + tool: quill_core::tools::title(&pending.tool), } }), + workspace.asked(id).map(|asked| QuestionCard { question: asked.question.clone(), options: asked.options.clone() }), ), - None => (false, None), + None => (false, None, None), }; if running < self.running { self.repos.clear(); @@ -299,7 +452,7 @@ impl Shell { _ => None, }; let context_used = self.workspace.read(cx).active_thread().and_then(|t| t.context_used); - self.composer.update(cx, |composer, cx| composer.set_context(busy, approval, strip, context_used, cx)); + self.composer.update(cx, |composer, cx| composer.set_context(busy, approval, question, strip, context_used, cx)); self.panel.update(cx, |panel, cx| panel.set_root(workdir.clone(), cx)); self.terminal.update(cx, |terminal, cx| terminal.set_root(workdir, cx)); cx.notify(); @@ -318,6 +471,10 @@ impl Shell { fn new_thread(&mut self, project: Option, window: &mut Window, cx: &mut Context) { self.in_settings = false; self.menu = None; + if Config::get(cx).general.remember_project && Config::get(cx).general.last_project != project { + let remembered = project.clone(); + Config::update(cx, |s| s.general.last_project = remembered); + } self.workspace.update(cx, |w, cx| w.start_new(project, cx)); self.focus_composer(window, cx); } @@ -332,10 +489,123 @@ impl Shell { Command::Files => self.toggle_panel(Tab::Files, cx), Command::Terminal => self.toggle_terminal(window, cx), Command::Commit => self.open_commit(window, cx), + Command::Compact => self.compact(cx), _ => {} } } + fn compact(&mut self, cx: &mut Context) { + match self.workspace.read(cx).active { + Some(id) if !self.workspace.read(cx).running(id) => { + self.workspace.update(cx, |w, cx| w.compact(id, cx)); + self.show_toast( + "Compacting this thread".into(), + "Earlier turns are being summarised to free up the model's window.".into(), + cx, + ); + } + Some(_) => self.show_problem("Wait for the reply to finish".into(), "A thread can be compacted between replies.".into(), cx), + None => self.show_problem("Nothing to compact yet".into(), "Open a thread first.".into(), cx), + } + } + + fn perform(&mut self, action: Action, window: &mut Window, cx: &mut Context) { + match action { + Action::NewThread => { + let project = self.workspace.read(cx).project(); + self.new_thread(project, window, cx); + } + Action::QuickChat => self.new_thread(None, window, cx), + Action::Project(path) => self.new_thread(Some(path), window, cx), + Action::AddProject => self.show_add_project(window, cx), + Action::Settings(section) => self.open_settings(section, window, cx), + Action::Sidebar => self.toggle_sidebar(cx), + Action::Terminal => self.toggle_terminal(window, cx), + Action::Review => self.toggle_panel(Tab::Diff, cx), + Action::Files => self.toggle_panel(Tab::Files, cx), + Action::Usage => self.toggle_panel(Tab::Usage, cx), + Action::Commit => self.open_commit(window, cx), + Action::Compact => self.compact(cx), + Action::Stop => self.stop_active(cx), + Action::Access(access) => Config::update(cx, |s| s.agent.access = access), + } + } + + fn entries(&self, cx: &Context) -> Vec { + let query = self.launcher.as_ref().map(|l| l.input.read(cx).value().trim().to_lowercase()).unwrap_or_default(); + let entry = |icon, label: &str, detail: &str, keys, action| Entry { + icon, + label: label.to_string(), + detail: detail.to_string(), + keys, + action, + }; + let mut all = vec![ + entry(Icon::Compose, "New thread", "Start a fresh thread in this project", Some("Ctrl N"), Action::NewThread), + entry(Icon::Chat, "Quick chat", "Talk to the model without a project or tools", None, Action::QuickChat), + entry(Icon::FolderPlus, "Add a project", "Start fresh, open a folder or clone a repository", None, Action::AddProject), + entry(Icon::Sliders, "Settings", "Every option, with search", Some("Ctrl ,"), Action::Settings(Section::General)), + entry(Icon::Cube, "Models", "Connect a server and pick a model", None, Action::Settings(Section::Models)), + entry(Icon::Bolt, "Toggle the sidebar", "Show or hide the thread list", Some("Ctrl B"), Action::Sidebar), + entry(Icon::Terminal, "Toggle the terminal", "A PowerShell drawer in the project", Some("Ctrl `"), Action::Terminal), + entry(Icon::FileDiff, "Review changes", "What the last reply changed", None, Action::Review), + entry(Icon::Files, "Browse files", "The project's files", None, Action::Files), + entry(Icon::Gauge, "Usage", "What this chat and everything else has cost", None, Action::Usage), + entry(Icon::Commit, "Commit", "Commit your work, push or open a pull request", None, Action::Commit), + entry(Icon::Eraser, "Compact this thread", "Summarise earlier turns to free up context", None, Action::Compact), + entry(Icon::CircleStop, "Stop the agent", "Stop the reply that is running", None, Action::Stop), + ]; + for access in Access::ALL { + all.push(entry( + access_icon(access), + &format!("Permissions: {}", access.label()), + access.description(), + None, + Action::Access(access), + )); + } + for path in &Config::get(cx).general.projects { + all.push(entry( + Icon::Folder, + &format!("Open {}", project::name(path)), + &path.display().to_string(), + None, + Action::Project(path.clone()), + )); + } + all.into_iter() + .filter(|e| query.is_empty() || e.label.to_lowercase().contains(&query) || e.detail.to_lowercase().contains(&query)) + .take(12) + .collect() + } + + fn open_launcher(&mut self, window: &mut Window, cx: &mut Context) { + let input = cx.new(|cx| InputState::new(window, cx).placeholder("Type a command or a project")); + let subscription = cx.subscribe(&input, |this, _, event: &InputEvent, cx| { + if let InputEvent::Change = event + && let Some(launcher) = this.launcher.as_mut() + { + launcher.highlighted = 0; + cx.notify(); + } + }); + input.update(cx, |input, cx| input.focus(window, cx)); + self.menu = None; + self.launcher = Some(Launcher { input, highlighted: 0, _subscription: subscription }); + cx.notify(); + } + + fn close_launcher(&mut self, window: &mut Window, cx: &mut Context) { + self.launcher = None; + self.focus_composer(window, cx); + cx.notify(); + } + + fn toggle_sidebar(&mut self, cx: &mut Context) { + Config::update(cx, |s| s.appearance.sidebar = !s.appearance.sidebar); + cx.notify(); + } + fn open_settings(&mut self, section: Section, _: &mut Window, cx: &mut Context) { self.in_settings = true; self.menu = None; @@ -369,16 +639,20 @@ impl Shell { fn open_commit(&mut self, window: &mut Window, cx: &mut Context) { let Some(root) = self.workspace.read(cx).workdir() else { - self.show_toast("Pick a project first".into(), "Commits need a project that uses Git.".into(), cx); + self.show_problem("Pick a project first".into(), "Commits need a project that uses Git.".into(), cx); return; }; if !self.repo(&root).repo { - self.show_toast("Not a Git repository".into(), root.display().to_string(), cx); + self.show_problem("Not a Git repository".into(), root.display().to_string(), cx); return; } self.menu = None; - let (url, model) = (Backend::url(cx), Backend::selected_id(cx)); - let dialog = cx.new(|cx| CommitDialog::new(root, url, model, window, cx)); + let role = Config::get(cx).models.roles.commit.clone().or_else(|| Backend::selected_ref(cx)); + let writer = match role { + Some(model) => self.backend.read(cx).writer(&model, cx), + None => Err("Choose a model first, or type a commit message yourself.".into()), + }; + let dialog = cx.new(|cx| CommitDialog::new(root, writer, window, cx)); let subscription = cx.subscribe_in(&dialog, window, |this, _, event, window, cx| match event { CommitEvent::Close => { this.commit = None; @@ -397,8 +671,9 @@ impl Shell { cx.notify(); } - fn show_toast(&mut self, title: String, detail: String, cx: &mut Context) { - self.toast = Some((title.into(), detail.into())); + fn push_toast(&mut self, kind: ToastKind, title: String, detail: String, cx: &mut Context) { + self.toasts += 1; + self.toast = Some(Toast { kind, title: title.into(), detail: detail.into(), serial: self.toasts }); self.toast_timer = Some(cx.spawn(async move |this, cx| { cx.background_executor().timer(Duration::from_secs(4)).await; _ = this.update(cx, |this, cx| { @@ -409,6 +684,14 @@ impl Shell { cx.notify(); } + fn show_toast(&mut self, title: String, detail: String, cx: &mut Context) { + self.push_toast(ToastKind::Done, title, detail, cx); + } + + fn show_problem(&mut self, title: String, detail: String, cx: &mut Context) { + self.push_toast(ToastKind::Problem, title, detail, cx); + } + fn open_diff(&mut self, thread: u64, turn: Option, cx: &mut Context) { let workspace = self.workspace.read(cx); let Some(found) = workspace.threads.iter().find(|t| t.id == thread) else { return }; @@ -438,6 +721,10 @@ impl Shell { self.panel.update(cx, |panel, cx| panel.show_files(cx)); self.panel_open = true; } + Tab::Usage => { + self.panel.update(cx, |panel, cx| panel.show_usage(cx)); + self.panel_open = true; + } } cx.notify(); } @@ -475,7 +762,7 @@ impl Shell { self.close_menu(cx); match self.workspace.update(cx, |w, cx| w.remove_isolated(id, cx)) { Ok(()) => self.show_toast("Removed the isolated copy".into(), "The thread now works in the project folder.".into(), cx), - Err(error) => self.show_toast("Could not remove the copy".into(), error, cx), + Err(error) => self.show_problem("Could not remove the copy".into(), error, cx), } } @@ -493,35 +780,55 @@ impl Shell { let id = thread.id; let active = !self.in_settings && workspace.active == Some(id); let running = workspace.running(id); - let pending = workspace.pending(id).is_some(); + let pending = workspace.waiting(id); let project_name = thread.project.as_ref().map(|path| project::name(path)); let elapsed = thread.turns.last().map(|t| t.elapsed_secs()).unwrap_or(0); - let motion = match thread.turns.last().and_then(|t| t.items.last()) { + let motion_state = match thread.turns.last().and_then(|t| t.items.last()) { _ if !running || pending => State::Idle, Some(Item::Text(_)) => State::Generating, _ => State::Thinking, }; let model = thread.turns.iter().rev().find_map(|turn| turn.model.clone()).or_else(|| thread.model.clone()); - let weave = model.map(|model| { + let logo = thread + .provider + .as_deref() + .and_then(|id| Config::get(cx).models.provider(id)) + .map(|provider| provider.kind) + .filter(|kind| *kind != ProviderKind::Local); + let weave = model.filter(|_| logo.is_none()).map(|model| { let fresh = self.marks.get(&id).is_none_or(|(seeded, _)| *seeded != model); if fresh { let mark = cx.new(|_| WeaveMark::new(State::Idle).seeded(&model).opacity(0.7)); self.marks.insert(id, (model, mark)); } let mark = self.marks[&id].1.clone(); - mark.update(cx, |mark, cx| mark.set_state(motion, cx)); + mark.update(cx, |mark, cx| mark.set_state(motion_state, cx)); mark }); let status = if pending { - div().px(px(6.)).rounded(px(5.)).bg(p.warning.opacity(0.14)).text_color(p.warning).child("Needs you") + div() + .px(px(6.)) + .h(px(18.)) + .flex() + .items_center() + .rounded(px(6.)) + .bg(p.warning.opacity(0.14)) + .text_color(p.warning) + .child("Needs you") } else if running { - div().flex().items_center().gap(px(4.)).text_color(p.link).child(icon(Icon::Loader, 12., p.link)).child(format!("{elapsed}s")) + div() + .flex() + .items_center() + .gap(px(4.)) + .text_color(p.accent) + .child(motion::spin(SharedString::from(format!("row-spin-{id}")), icon(Icon::Loader, 12., p.accent))) + .child(format!("{elapsed}s")) } else { div().text_color(p.text_faint).child(ago(thread.updated)) }; let mark = match &project_name { Some(name) => badge(name, 26.), - None => div().size(px(26.)).flex_shrink_0().flex().items_center().justify_center().rounded(px(7.)).bg(p.fill).child(icon( + None => div().size(px(26.)).flex_shrink_0().flex().items_center().justify_center().rounded(px(8.)).bg(p.fill).child(icon( Icon::Chat, 14., p.text_muted, @@ -556,6 +863,7 @@ impl Shell { .when(thread.worktree.is_some() || branch.is_some(), |row| row.child("·")) .when(thread.worktree.is_some(), |row| row.child(icon(Icon::Isolated, 11., p.text_faint))) .when_some(branch, |row, branch| row.child(div().overflow_hidden().text_ellipsis().child(branch))); + let spent: f64 = thread.turns.iter().filter_map(|turn| turn.cost).sum(); let footer = div() .flex() .items_center() @@ -575,18 +883,23 @@ impl Shell { }; row.child(stat(Icon::PullRequest, format!("#{}", pull.number), color)) }) - .when_some(weave, |row, weave| row.child(div().size(px(16.)).flex_shrink_0().child(weave))); + .when(spent > 0.0, |row| row.child(div().flex_shrink_0().text_color(p.text_muted).child(crate::usage::money(spent)))) + .when_some(weave, |row, weave| row.child(div().size(px(16.)).flex_shrink_0().child(weave))) + .when_some(logo, |row, kind| row.child(div().flex_shrink_0().child(icon(provider_icon(kind), 14., p.text_muted)))); div() .id(SharedString::from(format!("thread-{id}"))) + .group(SharedString::from(format!("thread-row-{id}"))) + .relative() .flex() .items_start() .gap(px(10.)) .px(px(10.)) - .py(px(8.)) - .rounded(px(8.)) + .py(px(9.)) + .rounded(px(10.)) .cursor_pointer() .when(active, |row| row.bg(p.row_active)) - .hover(move |style| style.bg(p.row_hover)) + .hover(move |style| style.bg(if active { p.row_active } else { p.row_hover })) + .when(active, |row| row.child(div().absolute().left(px(-8.)).top(px(14.)).w(px(3.)).h(px(18.)).rounded_full().bg(p.accent))) .child(div().mt(px(2.)).child(mark)) .child( div() @@ -601,6 +914,33 @@ impl Shell { .child(place) .child(footer), ) + .child( + div() + .id(SharedString::from(format!("thread-more-{id}"))) + .absolute() + .top(px(7.)) + .right(px(6.)) + .size(px(24.)) + .flex() + .items_center() + .justify_center() + .rounded(px(7.)) + .bg(p.surface_hover) + .border_1() + .border_color(p.border_soft) + .invisible() + .group_hover(SharedString::from(format!("thread-row-{id}")), |style| style.visible()) + .child(icon(Icon::Dots, 14., p.text_muted)) + .on_mouse_down( + MouseButton::Left, + cx.listener(move |this, event: &MouseDownEvent, _, cx| { + cx.stop_propagation(); + this.menu = Some(Menu::Thread(id, event.position)); + this.confirm_delete = None; + cx.notify(); + }), + ), + ) .on_click(cx.listener(move |this, _, window, cx| { this.in_settings = false; this.workspace.update(cx, |w, cx| w.activate(id, cx)); @@ -633,18 +973,18 @@ impl Shell { let mut groups: Vec>> = SECTIONS.iter().map(|_| Vec::new()).collect(); for thread in &threads { let workspace = self.workspace.read(cx); - let live = workspace.running(thread.id) || workspace.pending(thread.id).is_some(); + let live = workspace.running(thread.id) || workspace.waiting(thread.id); groups[section(live, thread.updated)].push(self.thread_row(thread, cx)); } let sections = SECTIONS.iter().zip(groups).filter(|(_, rows)| !rows.is_empty()).map(|(label, rows)| { div() .flex() .flex_col() - .gap(px(1.)) + .gap(px(2.)) .child( div() .px(px(10.)) - .pt(px(10.)) + .pt(px(14.)) .pb(px(4.)) .text_size(px(11.5)) .font_weight(FontWeight::SEMIBOLD) @@ -654,19 +994,44 @@ impl Shell { .children(rows) }); div() - .w(px(272.)) + .w(px(SIDEBAR)) .h_full() .flex_shrink_0() .flex() .flex_col() - .px(px(8.)) - .pb(px(8.)) + .px(px(10.)) + .pb(px(10.)) + .child( + div() + .id("new-thread") + .flex() + .items_center() + .gap(px(10.)) + .h(px(38.)) + .px(px(12.)) + .rounded(px(10.)) + .bg(p.raised) + .border_1() + .border_color(p.border_soft) + .text_size(px(13.5)) + .font_weight(FontWeight::MEDIUM) + .text_color(p.text) + .cursor_pointer() + .hover(move |style| style.bg(p.surface_hover)) + .child(icon(Icon::Compose, 16., p.text)) + .child(div().flex_1().child("New thread")) + .child(kbd("Ctrl N", p)) + .on_click(cx.listener(|this, _, window, cx| { + let project = this.workspace.read(cx).project(); + this.new_thread(project, window, cx); + })), + ) .child( div() .flex() .items_center() .gap(px(4.)) - .pb(px(10.)) + .pt(px(8.)) .child( div() .flex_1() @@ -676,25 +1041,26 @@ impl Shell { .items_center() .rounded(px(9.)) .bg(p.fill) - .text_size(px(13.5)) + .text_size(px(13.)) .child(Input::new(&self.search).appearance(false).prefix(icon(Icon::Search, 14., p.text_faint))), ) .child( - icon_button("add-project", Icon::FolderPlus, p) + icon_button("add-project", Icon::FolderPlus, "Add a project", p) .on_click(cx.listener(|this, _, window, cx| this.show_add_project(window, cx))), - ) - .child(icon_button("new-thread", Icon::Compose, p).on_click(cx.listener(|this, _, window, cx| { - let project = this.workspace.read(cx).project(); - this.new_thread(project, window, cx); - }))), + ), ) .child(div().id("threads").flex_1().min_h_0().overflow_y_scroll().flex().flex_col().children(sections).when(empty, |list| { list.child( - div().pt(px(24.)).flex().justify_center().text_size(px(13.5)).text_color(p.text_faint).child(if filter.is_empty() { - "Your threads will show up here" - } else { - "Nothing matches that" - }), + div() + .pt(px(28.)) + .flex() + .flex_col() + .items_center() + .gap(px(6.)) + .text_size(px(13.)) + .text_color(p.text_faint) + .child(icon(Icon::Chat, 18., p.text_faint)) + .child(if filter.is_empty() { "Your threads will show up here" } else { "Nothing matches that" }), ) })) .child( @@ -702,21 +1068,27 @@ impl Shell { .flex() .items_center() .gap(px(2.)) - .pt(px(6.)) + .pt(px(8.)) + .border_t_1() + .border_color(p.border_soft) .child( - icon_button("open-settings", Icon::Gear, p) + icon_button("open-settings", Icon::Gear, "Settings Ctrl ,", p) .on_click(cx.listener(|this, _, window, cx| this.open_settings(Section::General, window, cx))), ) .child( - icon_button("open-models", Icon::Cube, p) + icon_button("open-models", Icon::Cube, "Models", p) .on_click(cx.listener(|this, _, window, cx| this.open_settings(Section::Models, window, cx))), ) + .child( + icon_button("open-launcher", Icon::Search, "Commands Ctrl K", p) + .on_click(cx.listener(|this, _, window, cx| this.open_launcher(window, cx))), + ) .child(div().flex_1()) .child( div() .id("open-version") .px(px(8.)) - .h(px(28.)) + .h(px(26.)) .flex() .items_center() .rounded(px(7.)) @@ -741,21 +1113,15 @@ impl Shell { let project_name = project_path.as_ref().map(|path| project::name(path)); let picker = (self.menu == Some(Menu::Project)).then(|| { let current = project_path.clone(); - let projects = Config::get(cx).projects.clone(); + let projects = Config::get(cx).general.projects.clone(); let menu = menu_panel(p) .w(px(320.)) - .child(menu_label("Your projects", p)) + .child(menu_label("Projects", p)) .children(projects.into_iter().enumerate().map(|(i, path)| { let chosen = current.as_ref() == Some(&path); - menu_item( - ("pick-project", i), - Some(Icon::Folder), - project::name(&path), - Some(path.display().to_string().into()), - chosen, - p, - ) - .on_click(cx.listener(move |this, _, window, cx| this.new_thread(Some(path.clone()), window, cx))) + let parent = path.parent().map(project::short_path).unwrap_or_default(); + menu_item(("pick-project", i), Some(Icon::Folder), project::name(&path), Some(parent.into()), chosen, p) + .on_click(cx.listener(move |this, _, window, cx| this.new_thread(Some(path.clone()), window, cx))) })) .child(separator(p)) .child( @@ -778,9 +1144,9 @@ impl Shell { div() .flex() .items_center() - .gap(px(8.)) + .gap(px(6.)) .min_w_0() - .text_size(px(14.)) + .text_size(px(13.5)) .child( div() .relative() @@ -793,11 +1159,11 @@ impl Shell { .gap(px(7.)) .h(px(28.)) .px(px(8.)) - .rounded(px(7.)) + .rounded(px(8.)) .text_color(p.text_muted) .when(!locked, |b| b.cursor_pointer().hover(move |style| style.bg(p.row_hover).text_color(p.text))) .child(match &project_name { - Some(name) => badge(name, 16.).into_any_element(), + Some(name) => badge(name, 18.).into_any_element(), None => icon(Icon::Chat, 15., p.text_faint).into_any_element(), }) .child(project_name.clone().unwrap_or_else(|| "Quick chat".into())) @@ -812,7 +1178,7 @@ impl Shell { ) .children(picker), ) - .child(div().text_color(p.text_faint).child("/")) + .child(icon(Icon::ChevronRight, 13., p.text_faint)) .child( div() .min_w_0() @@ -825,65 +1191,140 @@ impl Shell { ) } - fn env_card(&mut self, cx: &mut Context) -> Option> { + fn toolbar(&mut self, window: &Window, cx: &mut Context) -> Div { let p = palette(cx); - let path = self.workspace.read(cx).workdir()?; - let info = self.repo(&path); + let workdir = self.workspace.read(cx).workdir(); + let info = workdir.as_ref().map(|root| self.repo(root)).unwrap_or_default(); let changes = self.workspace.read(cx).active_thread().and_then(|t| { t.turns.iter().rev().find(|turn| turn.diffs().next().is_some()).map(|turn| { let c = turn.changes(); (c.iter().map(|x| x.added).sum::(), c.iter().map(|x| x.removed).sum::()) }) }); - let editor = self.editor; - let open_path = path.clone(); - let reveal_path = path.clone(); - Some( + let panel_tab = self.panel.read(cx).tab; + let review_on = self.panel_open && panel_tab == Tab::Diff; + let files_on = self.panel_open && panel_tab == Tab::Files; + let usage_on = self.panel_open && panel_tab == Tab::Usage; + let spent: f64 = + self.workspace.read(cx).active_thread().map_or(0.0, |thread| thread.turns.iter().filter_map(|turn| turn.cost).sum()); + let open_menu = (self.menu == Some(Menu::Open)).then(|| { + let editor = self.editor; + let reveal = workdir.clone().unwrap_or_default(); + let code = reveal.clone(); + let menu = menu_panel(p) + .w(px(240.)) + .child(menu_label("Open this project in", p)) + .when(editor, |menu| { + menu.child(menu_item("open-vscode", Some(Icon::Code), "VS Code", None, false, p).on_click(cx.listener( + move |this, _, _, cx| { + project::open_in_editor(&code); + this.close_menu(cx); + }, + ))) + }) + .child(menu_item("open-explorer", Some(Icon::FolderOpen), "File Explorer", None, false, p).on_click(cx.listener( + move |this, _, _, cx| { + project::open_folder(&reveal); + this.close_menu(cx); + }, + ))) + .child(menu_item("open-terminal", Some(Icon::Terminal), "Terminal drawer", None, false, p).on_click(cx.listener( + |this, _, window, cx| { + this.close_menu(cx); + this.toggle_terminal(window, cx); + }, + ))); + popup(window, cx, Anchor::TopRight, menu, |this, cx| this.close_menu(cx)) + }); + let pill = |id: &'static str, on: bool| { div() - .absolute() - .top(px(14.)) - .right(px(14.)) - .w(px(250.)) - .p(px(5.)) - .rounded(px(14.)) - .bg(p.menu_bg) - .border_1() - .border_color(p.border_soft) + .id(id) + .occlude() .flex() - .flex_col() - .gap(px(1.)) - .when(editor, |card| { - card.child( - menu_item("open-vscode", Some(Icon::Code), "Open in VS Code", None, false, p) - .on_click(move |_, _, _| project::open_in_editor(&open_path)), - ) - }) - .child( - menu_item("open-explorer", Some(Icon::FolderOpen), "Show in File Explorer", None, false, p) - .on_click(move |_, _, _| project::open_folder(&reveal_path)), + .flex_shrink_0() + .items_center() + .gap(px(6.)) + .h(px(28.)) + .px(px(9.)) + .rounded(px(8.)) + .text_size(px(12.5)) + .text_color(if on { p.text } else { p.text_muted }) + .cursor_pointer() + .when(on, |b| b.bg(p.row_active)) + .hover(move |style| style.bg(p.row_hover).text_color(p.text)) + }; + div() + .flex() + .items_center() + .gap(px(2.)) + .when(workdir.is_some(), |bar| { + bar.child( + div() + .relative() + .child( + pill("toolbar-open", self.menu == Some(Menu::Open)) + .tooltip(tip("Open the project in another app")) + .child(icon(Icon::FolderOpen, 14., p.text_muted)) + .child("Open") + .child(icon(Icon::ChevronDown, 12., p.text_faint)) + .on_click(cx.listener(|this, _, _, cx| { + this.menu = Some(Menu::Open); + cx.notify(); + })), + ) + .children(open_menu), ) - .child(separator(p)) - .child(match info.branch { - Some(branch) => menu_item("branch", Some(Icon::Branch), branch, None, false, p), - None => { - menu_item("no-git", Some(Icon::Branch), if info.repo { "No commits yet" } else { "Not using Git" }, None, false, p) - } - }) - .child( - menu_item("changes", Some(Icon::FileDiff), "Edits in this thread", None, false, p) - .when_some(changes, |row, (added, removed)| { - row.child(div().text_size(px(12.)).text_color(p.add).child(format!("+{added}"))) - .child(div().text_size(px(12.)).text_color(p.del).child(format!("-{removed}"))) + }) + .when(info.repo, |bar| { + bar.child( + pill("toolbar-commit", self.commit.is_some()) + .tooltip(tip("Commit, push or open a pull request")) + .child(icon(Icon::Commit, 14., p.text_muted)) + .child("Commit") + .when(info.snapshot.changed > 0, |b| { + b.child( + div() + .px(px(5.)) + .rounded(px(5.)) + .bg(p.warning.opacity(0.16)) + .text_size(px(11.)) + .text_color(p.warning) + .child(info.snapshot.changed.to_string()), + ) }) - .on_click(cx.listener(|this, _, _, cx| this.toggle_panel(Tab::Diff, cx))), + .on_click(cx.listener(|this, _, window, cx| this.open_commit(window, cx))), ) - .when(info.repo, |card| { - card.child( - menu_item("commit-work", Some(Icon::Commit), "Commit your work", None, false, p) - .on_click(cx.listener(|this, _, window, cx| this.open_commit(window, cx))), - ) - }), - ) + }) + .child(div().w(px(1.)).h(px(16.)).mx(px(4.)).bg(p.border_soft)) + .child( + pill("toolbar-review", review_on) + .tooltip(tip("Review what the last reply changed")) + .child(icon(Icon::FileDiff, 14., p.text_muted)) + .when_some(changes, |b, (added, removed)| { + b.child(div().text_color(p.add).child(format!("+{added}"))) + .child(div().text_color(p.del).child(format!("−{removed}"))) + }) + .on_click(cx.listener(|this, _, _, cx| this.toggle_panel(Tab::Diff, cx))), + ) + .child( + pill("toolbar-files", files_on) + .tooltip(tip("Browse the project's files")) + .child(icon(Icon::Files, 14., p.text_muted)) + .on_click(cx.listener(|this, _, _, cx| this.toggle_panel(Tab::Files, cx))), + ) + .child( + pill("toolbar-usage", usage_on) + .tooltip(tip("Usage and cost")) + .child(icon(Icon::Gauge, 14., p.text_muted)) + .when(spent > 0.0, |b| b.child(div().text_color(p.text_muted).child(crate::usage::money(spent)))) + .on_click(cx.listener(|this, _, _, cx| this.toggle_panel(Tab::Usage, cx))), + ) + .child( + pill("toolbar-terminal", self.terminal_open) + .tooltip(tip("Terminal Ctrl `")) + .child(icon(Icon::Terminal, 14., p.text_muted)) + .on_click(cx.listener(|this, _, window, cx| this.toggle_terminal(window, cx))), + ) } fn fresh(&self, cx: &mut Context) -> AnyElement { @@ -898,6 +1339,23 @@ impl Shell { .into_any_element(), None => div().child(self.greeting).into_any_element(), }; + let starters: Vec<(Icon, &str, String)> = match &project { + Some(_) => vec![ + ( + Icon::Sparkles, + "Explain this project", + "Explain how this project is laid out and how its main parts fit together.".into(), + ), + (Icon::Search, "Find a bug", "Look for a bug in this project, explain it, and fix it.".into()), + (Icon::Check, "Add tests", "Find code in this project that has no tests and add focused tests for it.".into()), + (Icon::FileText, "Write AGENTS.md", INIT_PROMPT.into()), + ], + None => vec![ + (Icon::Bulb, "Explain a concept", "Explain how async and await work in Rust, with a small example.".into()), + (Icon::Code, "Draft a function", "Write a function that parses a duration like 1h30m into seconds.".into()), + (Icon::Chat, "Review an idea", "I have an idea for a feature. Ask me about it, then tell me what could go wrong.".into()), + ], + }; div() .size_full() .flex() @@ -906,8 +1364,13 @@ impl Shell { .justify_center() .px(px(32.)) .pb(px(72.)) - .child(div().size(px(76.)).child(self.hero.clone())) - .child(div().mt(px(18.)).text_size(px(30.)).line_height(px(38.)).text_color(p.text).child(heading)) + .child(motion::rise("hero", div().size(px(84.)).child(self.hero.clone()), 10., cx)) + .child(motion::rise( + "hero-heading", + div().mt(px(18.)).text_size(px(30.)).line_height(px(38.)).text_color(p.text).child(heading), + 8., + cx, + )) .child( div() .id("fresh-sub") @@ -930,6 +1393,36 @@ impl Shell { })), ) .child(div().mt(px(26.)).w_full().flex().justify_center().child(self.composer.clone())) + .child(div().mt(px(16.)).flex().flex_wrap().justify_center().gap(px(8.)).children(starters.into_iter().enumerate().map( + |(index, (name, label, prompt))| { + motion::rise( + ("starter-rise", index), + div() + .id(("starter", index)) + .flex() + .items_center() + .gap(px(7.)) + .h(px(32.)) + .px(px(12.)) + .rounded_full() + .border_1() + .border_color(p.border_soft) + .bg(p.fill) + .text_size(px(13.)) + .text_color(p.text_muted) + .cursor_pointer() + .hover(move |style| style.bg(p.row_hover).text_color(p.text).border_color(p.border)) + .child(icon(name, 14., p.text_faint)) + .child(label) + .on_click(cx.listener(move |this, _, _, cx| { + let prompt = Prompt { text: prompt.clone(), attachments: Vec::new() }; + this.workspace.update(cx, |w, cx| w.send(prompt, cx)); + })), + 6., + cx, + ) + }, + ))) .into_any_element() } @@ -995,7 +1488,158 @@ impl Shell { ) .with_priority(1), ) - .child(deferred(anchored().position(position).snap_to_window().child(menu)).with_priority(2)) + .child( + deferred(anchored().position(position).snap_to_window().child(motion::pop("thread-menu", menu, false, cx))) + .with_priority(2), + ) + } + + fn launcher_view(&self, cx: &mut Context) -> Option> { + let launcher = self.launcher.as_ref()?; + let p = palette(cx); + let entries = self.entries(cx); + let highlighted = launcher.highlighted.min(entries.len().saturating_sub(1)); + let list = div().id("launcher-list").max_h(px(440.)).overflow_y_scroll().flex().flex_col().gap(px(2.)).p(px(6.)).children( + entries.into_iter().enumerate().map(|(index, entry)| { + let on = index == highlighted; + let action = entry.action.clone(); + div() + .id(("launcher-entry", index)) + .flex() + .items_center() + .gap(px(12.)) + .px(px(12.)) + .py(px(8.)) + .rounded(px(9.)) + .cursor_pointer() + .when(on, |row| row.bg(p.accent_soft)) + .hover(move |style| style.bg(if on { p.accent_soft } else { p.row_hover })) + .child(icon(entry.icon, 16., if on { p.accent } else { p.text_muted })) + .child( + div() + .flex_1() + .min_w_0() + .flex() + .flex_col() + .child(div().text_size(px(13.5)).text_color(p.text).child(entry.label)) + .child( + div() + .overflow_hidden() + .whitespace_nowrap() + .text_ellipsis() + .text_size(px(12.)) + .text_color(p.text_faint) + .child(entry.detail), + ), + ) + .when_some(entry.keys, |row, keys| row.child(kbd(keys, p))) + .on_click(cx.listener(move |this, _, window, cx| { + this.close_launcher(window, cx); + this.perform(action.clone(), window, cx); + })) + }), + ); + let panel = div() + .w(px(580.)) + .rounded(px(16.)) + .bg(p.menu_bg) + .border_1() + .border_color(p.border) + .shadow_lg() + .overflow_hidden() + .flex() + .flex_col() + .child( + div() + .flex() + .items_center() + .gap(px(10.)) + .px(px(16.)) + .h(px(50.)) + .border_b_1() + .border_color(p.border_soft) + .text_size(px(14.5)) + .child(icon(Icon::Search, 16., p.text_faint)) + .child(div().flex_1().child(Input::new(&launcher.input).appearance(false))), + ) + .child(list) + .child( + div() + .flex() + .items_center() + .gap(px(12.)) + .px(px(16.)) + .py(px(8.)) + .border_t_1() + .border_color(p.border_soft) + .text_size(px(11.5)) + .text_color(p.text_faint) + .child("↑↓ to move") + .child("Enter to run") + .child("Esc to close"), + ); + Some( + div() + .absolute() + .top_0() + .left_0() + .size_full() + .child( + div() + .id("launcher-backdrop") + .absolute() + .top_0() + .left_0() + .size_full() + .bg(gpui_kit::black().opacity(if p.dark { 0.45 } else { 0.2 })) + .occlude() + .on_mouse_down(MouseButton::Left, cx.listener(|this, _, window, cx| this.close_launcher(window, cx))), + ) + .child( + div() + .absolute() + .top(px(90.)) + .left_0() + .w_full() + .flex() + .justify_center() + .child(motion::pop("launcher", panel, false, cx)), + ), + ) + } + + fn toast_view(&self, cx: &mut Context) -> Option> { + let toast = self.toast.clone()?; + let p = palette(cx); + let (mark, tone) = match toast.kind { + ToastKind::Done => (Icon::CheckCircle, p.success), + ToastKind::Problem => (Icon::CircleAlert, p.danger), + }; + let card = div() + .w(px(360.)) + .flex() + .gap(px(10.)) + .px(px(14.)) + .py(px(12.)) + .rounded(px(14.)) + .bg(p.menu_bg) + .border_1() + .border_color(p.border) + .shadow_lg() + .child(div().pt(px(1.)).child(icon(mark, 16., tone))) + .child( + div() + .flex_1() + .min_w_0() + .flex() + .flex_col() + .gap(px(2.)) + .child(div().text_size(px(13.5)).font_weight(FontWeight::SEMIBOLD).text_color(p.text).child(toast.title)) + .when(!toast.detail.is_empty(), |col| { + col.child(div().text_size(px(12.5)).text_color(p.text_faint).child(toast.detail)) + }), + ); + Some(div().absolute().bottom(px(22.)).right(px(22.)).child(motion::rise(("toast", toast.serial), card, 14., cx))) } } @@ -1016,65 +1660,34 @@ fn stat(name: Icon, text: String, color: Hsla) -> Div { div().flex().items_center().gap(px(3.)).text_color(color).child(icon(name, 12., color)).child(text) } -fn icon_button(id: &'static str, name: Icon, p: Palette) -> Stateful
{ - div() - .id(id) - .flex() - .flex_shrink_0() - .items_center() - .justify_center() - .size(px(30.)) - .rounded(px(8.)) - .cursor_pointer() - .hover(move |style| style.bg(p.row_hover)) - .child(icon(name, 16., p.text_muted)) -} - impl Render for Shell { fn render(&mut self, window: &mut Window, cx: &mut Context) -> impl IntoElement { let p = palette(cx); let has_thread = self.workspace.read(cx).active.is_some(); - let has_repo = self.workspace.read(cx).workdir().is_some_and(|root| self.repo(&root).repo); - let panel_open = self.panel_open; - let panel_tab = self.panel.read(cx).tab; - let mut bar = div().flex().items_center().h_full().flex_1().pr(px(8.)).child( - div() - .w(px(272.)) - .flex_shrink_0() - .flex() - .items_center() - .gap(px(8.)) - .pl(px(6.)) - .child(div().size(px(20.)).child(self.brand.clone())) - .child(div().text_size(px(14.5)).font_weight(FontWeight::SEMIBOLD).text_color(p.text).child(APP_NAME)), - ); + let sidebar_open = Config::get(cx).appearance.sidebar && !self.in_settings; + let spring = SpringAnimation::new(SpringConfig::new(420., 42., 1.)); + let left = div() + .w(px(SIDEBAR - 8.)) + .flex_shrink_0() + .flex() + .items_center() + .gap(px(8.)) + .pl(px(6.)) + .child( + icon_button("toggle-sidebar", Icon::Panel, "Sidebar Ctrl B", p) + .occlude() + .on_click(cx.listener(|this, _, _, cx| this.toggle_sidebar(cx))), + ) + .child(div().size(px(18.)).child(self.brand.clone())) + .child(div().text_size(px(14.)).font_weight(FontWeight::SEMIBOLD).text_color(p.text).child(APP_NAME)); + let mut bar = div().flex().items_center().h_full().flex_1().min_w_0().pr(px(8.)).child(left); if self.in_settings { - bar = bar.child(div().text_size(px(14.)).text_color(p.text_muted).child("Settings")); + bar = bar.child(div().flex_1()); } else { - bar = bar.child(self.breadcrumb(window, cx)).child(div().flex_1()); - if has_repo { - bar = bar.child( - icon_button("title-commit", Icon::Commit, p) - .occlude() - .when(self.commit.is_some(), |b| b.bg(p.row_active)) - .on_click(cx.listener(|this, _, window, cx| this.open_commit(window, cx))), - ); - } - bar = bar.child( - icon_button("toggle-terminal", Icon::Terminal, p) - .occlude() - .when(self.terminal_open, |b| b.bg(p.row_active)) - .on_click(cx.listener(|this, _, window, cx| this.toggle_terminal(window, cx))), - ); - for (id, name, tab) in [("toggle-files", Icon::Files, Tab::Files), ("toggle-diff", Icon::FileDiff, Tab::Diff)] { - let on = panel_open && panel_tab == tab; - bar = bar.child( - icon_button(id, name, p) - .occlude() - .when(on, |b| b.bg(p.row_active)) - .on_click(cx.listener(move |this, _, _, cx| this.toggle_panel(tab, cx))), - ); - } + let toolbar = self.toolbar(window, cx); + bar = bar + .child(div().flex().flex_1().w(px(0.)).min_w_0().overflow_hidden().child(self.breadcrumb(window, cx))) + .child(toolbar.flex_shrink_0()); } let body: AnyElement = if self.in_settings { self.settings.clone().cached(StyleRefinement::default().size_full()).into_any_element() @@ -1090,15 +1703,18 @@ impl Render for Shell { } else { self.fresh(cx) }; - let wide = window.viewport_size().width >= px(1700.); - let env = if panel_open || (has_thread && !wide) { None } else { self.env_card(cx) }; - let panel_width = px(((window.viewport_size().width.as_f32() - 272.) * 0.44).clamp(380., 640.)); + let panel_width = px(((window.viewport_size().width.as_f32() - SIDEBAR) * 0.44).clamp(380., 660.)); let sidebar = self.sidebar(cx); let terminal_open = self.terminal_open; + let panel_open = self.panel_open; div() .size_full() .flex() - .child(sidebar) + .child(div().h_full().flex_shrink_0().overflow_hidden().child(sidebar).with_spring( + "sidebar-width", + spring.clone().to(if sidebar_open { px(SIDEBAR) } else { px(0.) }), + |el, width| el.w(width), + )) .child( div() .flex_1() @@ -1106,9 +1722,8 @@ impl Render for Shell { .h_full() .flex() .bg(p.bg) - .rounded_tl(px(10.)) + .when(sidebar_open, |main| main.rounded_tl(px(12.)).border_l_1()) .border_t_1() - .border_l_1() .border_color(p.border_soft) .overflow_hidden() .child( @@ -1118,20 +1733,24 @@ impl Render for Shell { .h_full() .flex() .flex_col() - .child(div().relative().flex_1().min_h_0().child(center).children(env)) + .child(div().relative().flex_1().min_h_0().child(center)) .when(terminal_open, |col| { - col.child( + col.child(motion::rise( + "terminal-drawer", div() .h(px(280.)) .flex_shrink_0() .border_t_1() .border_color(p.border_soft) .child(self.terminal.clone().cached(StyleRefinement::default().size_full())), - ) + 24., + cx, + )) }), ) .when(panel_open, |main| { - main.child( + main.child(motion::rise( + "side-panel", div() .w(panel_width) .flex_shrink_0() @@ -1139,7 +1758,9 @@ impl Render for Shell { .border_l_1() .border_color(p.border_soft) .child(self.panel.clone().cached(StyleRefinement::default().size_full())), - ) + 0., + cx, + )) }), ) .into_any_element() @@ -1148,33 +1769,8 @@ impl Render for Shell { Some(Menu::Thread(id, position)) => Some(self.thread_menu(id, position, cx)), _ => None, }; - let toast = self.toast.clone().map(|(title, detail)| { - div() - .absolute() - .top(px(48.)) - .right(px(18.)) - .w(px(360.)) - .flex() - .gap(px(10.)) - .px(px(14.)) - .py(px(12.)) - .rounded(px(12.)) - .bg(p.menu_bg) - .border_1() - .border_color(p.border) - .shadow_lg() - .child(icon(Icon::CheckCircle, 16., p.success)) - .child( - div() - .flex_1() - .min_w_0() - .flex() - .flex_col() - .gap(px(2.)) - .child(div().text_size(px(13.5)).font_weight(FontWeight::SEMIBOLD).text_color(p.text).child(title)) - .when(!detail.is_empty(), |col| col.child(div().text_size(px(12.5)).text_color(p.text_faint).child(detail))), - ) - }); + let toast = self.toast_view(cx); + let launcher = self.launcher_view(cx); div() .size_full() .relative() @@ -1189,6 +1785,7 @@ impl Render for Shell { .children(self.add_project.clone()) .children(self.commit.clone()) .children(toast) + .children(launcher) } } diff --git a/crates/quill-code/src/terminal.rs b/crates/quill-code/src/terminal.rs index 1fcd0de..9e7d43d 100644 --- a/crates/quill-code/src/terminal.rs +++ b/crates/quill-code/src/terminal.rs @@ -10,10 +10,10 @@ use gpui_kit::{ Subscription, UniformListScrollHandle, Window, div, prelude::*, px, uniform_list, }; -use crate::git::hidden; use crate::icons::Icon; use crate::palette::palette; use crate::ui::{MONO, icon}; +use quill_git::hidden; const DONE: &str = "__quill_done__"; const MAX_LINES: usize = 5000; diff --git a/crates/quill-code/src/thread.rs b/crates/quill-code/src/thread.rs index 9b79fa8..87cd03b 100644 --- a/crates/quill-code/src/thread.rs +++ b/crates/quill-code/src/thread.rs @@ -2,8 +2,9 @@ use std::collections::BTreeMap; use std::path::PathBuf; use std::time::{SystemTime, UNIX_EPOCH}; -use quill_agent::{FileDiff, ToolKind}; -use quill_llama::Message; +use quill_core::tools::legacy; +use quill_core::{Category, ClaudeLink, FileDiff, PlanStep, ToolView}; +use quill_providers::{Message, Tokens}; use serde::{Deserialize, Serialize}; pub fn now_ms() -> u64 { @@ -27,15 +28,118 @@ pub enum ToolStatus { } #[derive(Clone, Serialize, Deserialize)] +#[serde(from = "RawTool")] pub struct ToolItem { pub id: String, - pub kind: ToolKind, + pub tool: String, + pub category: Category, + pub active: String, + pub done: String, pub target: String, pub status: ToolStatus, pub output: String, - pub diff: Option, - #[serde(skip)] - pub open: bool, + pub diffs: Vec, + pub image: Option, + pub started: u64, + pub ended: Option, +} + +#[derive(Deserialize)] +struct RawTool { + id: String, + #[serde(default)] + tool: Option, + #[serde(default)] + kind: Option, + #[serde(default)] + category: Option, + #[serde(default)] + active: Option, + #[serde(default)] + done: Option, + #[serde(default)] + target: String, + status: ToolStatus, + #[serde(default)] + output: String, + #[serde(default)] + diffs: Vec, + #[serde(default)] + diff: Option, + #[serde(default)] + image: Option, + #[serde(default)] + started: u64, + #[serde(default)] + ended: Option, +} + +impl From for ToolItem { + fn from(raw: RawTool) -> ToolItem { + let view = match (raw.tool, raw.category, raw.active, raw.done) { + (Some(tool), Some(category), Some(active), Some(done)) => { + ToolView { id: raw.id.clone(), tool, category, active, done, target: String::new() } + } + (tool, ..) => legacy(&tool.or(raw.kind).unwrap_or_default()), + }; + let diffs = if raw.diffs.is_empty() { raw.diff.into_iter().collect() } else { raw.diffs }; + ToolItem { + id: raw.id, + tool: view.tool, + category: view.category, + active: view.active, + done: view.done, + target: raw.target, + status: raw.status, + output: raw.output, + diffs, + image: raw.image, + started: raw.started, + ended: raw.ended, + } + } +} + +impl ToolItem { + pub fn new(view: ToolView) -> ToolItem { + ToolItem { + id: view.id, + tool: view.tool, + category: view.category, + active: view.active, + done: view.done, + target: view.target, + status: ToolStatus::Running, + output: String::new(), + diffs: Vec::new(), + image: None, + started: now_ms(), + ended: None, + } + } + + pub fn working(&self) -> bool { + matches!(self.status, ToolStatus::Running | ToolStatus::Waiting) + } + + pub fn seconds(&self) -> Option { + let ended = self.ended?; + (self.started > 0 && ended >= self.started).then(|| (ended - self.started) as f32 / 1000.0) + } + + pub fn exit_code(&self) -> Option { + self.output.lines().next()?.strip_prefix("Exit code ")?.trim().parse().ok() + } + + pub fn verb(&self) -> &str { + if self.working() { + &self.active + } else if self.diffs.len() == 1 && self.diffs[0].created { + "Created" + } else { + &self.done + } + } } #[derive(Clone, Serialize, Deserialize)] @@ -43,6 +147,10 @@ pub enum Item { Reasoning(String), Text(String), Tool(ToolItem), + Plan { steps: Vec, explanation: Option }, + Question { id: String, question: String, options: Vec, answer: Option }, + Steer(String), + Note(String), } #[derive(Clone, Serialize, Deserialize)] @@ -58,6 +166,10 @@ pub struct Turn { pub images: Vec, #[serde(default)] pub model: Option, + #[serde(default)] + pub cost: Option, + #[serde(default)] + pub usage: Tokens, #[serde(skip)] pub expanded: bool, } @@ -80,6 +192,8 @@ impl Turn { attachments, images: Vec::new(), model: None, + cost: None, + usage: Tokens::default(), expanded: false, } } @@ -106,6 +220,20 @@ impl Turn { } } + pub fn set_plan(&mut self, steps: Vec, explanation: Option) { + let found = self.items.iter_mut().find_map(|item| match item { + Item::Plan { steps, explanation } => Some((steps, explanation)), + _ => None, + }); + match found { + Some((old_steps, old_explanation)) => { + *old_steps = steps; + *old_explanation = explanation; + } + None => self.items.push(Item::Plan { steps, explanation }), + } + } + pub fn tool_mut(&mut self, id: &str) -> Option<&mut ToolItem> { self.items.iter_mut().rev().find_map(|item| match item { Item::Tool(tool) if tool.id == id => Some(tool), @@ -113,6 +241,16 @@ impl Turn { }) } + pub fn answer(&mut self, id: &str, text: &str) { + for item in &mut self.items { + if let Item::Question { id: question, answer, .. } = item + && question == id + { + *answer = Some(text.to_string()); + } + } + } + pub fn finish(&mut self, state: TurnState) { if !self.working() { return; @@ -120,14 +258,27 @@ impl Turn { self.worked_ms = Some(now_ms().saturating_sub(self.started)); for item in &mut self.items { if let Item::Tool(tool) = item - && matches!(tool.status, ToolStatus::Running | ToolStatus::Waiting) + && tool.working() { tool.status = ToolStatus::Failed; } } + if state == TurnState::Done { + self.promote_reasoning(); + } self.state = state; } + fn promote_reasoning(&mut self) { + let last = self.items.iter_mut().rev().find(|item| !matches!(item, Item::Text(t) if t.trim().is_empty())); + if let Some(item) = last + && let Item::Reasoning(text) = item + { + let text = std::mem::take(text).trim().to_string(); + *item = Item::Text(text); + } + } + pub fn final_text(&self) -> Option { if self.working() { return None; @@ -161,31 +312,46 @@ impl Turn { } pub fn diffs(&self) -> impl Iterator { - self.items.iter().filter_map(|item| match item { - Item::Tool(ToolItem { diff: Some(diff), status: ToolStatus::Done, .. }) => Some(diff), - _ => None, - }) + self.items + .iter() + .filter_map(|item| match item { + Item::Tool(ToolItem { diffs, status: ToolStatus::Done, .. }) => Some(diffs.iter()), + _ => None, + }) + .flatten() } pub fn summary(&self) -> String { let files = self.changes().len(); - let mut commands = 0; - let mut other = 0; + let (mut commands, mut reads, mut searches, mut other, mut asked) = (0, 0, 0, 0, 0); for item in &self.items { if let Item::Tool(tool) = item { - match tool.kind { - ToolKind::Run => commands += 1, - ToolKind::Write | ToolKind::Edit => {} + match (tool.category, tool.tool.as_str()) { + (Category::Command, _) => commands += 1, + (Category::Explore, "read_file") => reads += 1, + (Category::Explore, _) => searches += 1, + (Category::Question, _) => asked += 1, + (Category::Edit | Category::Plan, _) => {} _ => other += 1, } } } + let count = |n: usize, one: &str, many: &str| format!("{n} {}", if n == 1 { one } else { many }); let mut parts = Vec::new(); if files > 0 { - parts.push(format!("changed {files} {}", if files == 1 { "file" } else { "files" })); + parts.push(format!("changed {}", count(files, "file", "files"))); } if commands > 0 { - parts.push(format!("ran {commands} {}", if commands == 1 { "command" } else { "commands" })); + parts.push(format!("ran {}", count(commands, "command", "commands"))); + } + if reads > 0 { + parts.push(format!("read {}", count(reads, "file", "files"))); + } + if searches > 0 { + parts.push(format!("searched {}", count(searches, "time", "times"))); + } + if asked > 0 { + parts.push(format!("asked you {}", count(asked, "question", "questions"))); } if other > 0 { let noun = if other == 1 { "action" } else { "actions" }; @@ -220,6 +386,12 @@ pub struct Thread { pub model: Option, #[serde(default)] pub context_used: Option, + #[serde(default)] + pub context_window: Option, + #[serde(default)] + pub provider: Option, + #[serde(default)] + pub claude: Option, } impl Thread { @@ -236,6 +408,9 @@ impl Thread { worktree: None, model: None, context_used: None, + context_window: None, + provider: None, + claude: None, } } @@ -281,10 +456,15 @@ pub fn ago(ms: u64) -> String { #[cfg(test)] mod tests { use super::*; - use quill_agent::diff_text; - - fn tool(id: &str, kind: ToolKind, diff: Option) -> Item { - Item::Tool(ToolItem { id: id.into(), kind, target: "x".into(), status: ToolStatus::Done, output: String::new(), diff, open: false }) + use quill_core::{StepStatus, diff_text}; + + fn tool(id: &str, name: &str, diffs: Vec) -> Item { + let mut item = ToolItem::new(legacy(name)); + item.id = id.into(); + item.target = "x".into(); + item.status = ToolStatus::Done; + item.diffs = diffs; + Item::Tool(item) } #[test] @@ -292,7 +472,7 @@ mod tests { let mut turn = Turn::new("p".into(), Vec::new()); turn.push_text("Hel"); turn.push_text("lo"); - turn.items.push(tool("1", ToolKind::Read, None)); + turn.items.push(tool("1", "read_file", Vec::new())); turn.push_text("Done"); assert_eq!(turn.items.len(), 3); assert!(turn.final_text().is_none()); @@ -300,55 +480,83 @@ mod tests { assert_eq!(turn.final_text(), Some(2)); } + #[test] + fn reasoning_that_ends_a_turn_becomes_the_answer() { + let mut turn = Turn::new("p".into(), Vec::new()); + turn.push_reasoning("Checking"); + turn.items.push(tool("1", "shell", Vec::new())); + turn.push_reasoning("All updated."); + turn.push_text("\n"); + turn.finish(TurnState::Done); + assert_eq!(turn.final_text(), Some(2)); + assert!(matches!(&turn.items[0], Item::Reasoning(_))); + assert!(matches!(&turn.items[2], Item::Text(t) if t == "All updated.")); + } + #[test] fn summary_reads_like_a_sentence() { let mut turn = Turn::new("p".into(), Vec::new()); - turn.items.push(tool("1", ToolKind::Write, Some(diff_text("a.py", None, "x\n")))); - turn.items.push(tool("2", ToolKind::Run, None)); - turn.items.push(tool("3", ToolKind::Read, None)); - turn.items.push(tool("4", ToolKind::List, None)); - assert_eq!(turn.summary(), "Changed 1 file, ran 1 command, and performed 2 other actions"); + turn.items.push(tool("1", "write_file", vec![diff_text("a.py", None, "x\n")])); + turn.items.push(tool("2", "shell", Vec::new())); + turn.items.push(tool("3", "read_file", Vec::new())); + turn.items.push(tool("4", "list_dir", Vec::new())); + assert_eq!(turn.summary(), "Changed 1 file, ran 1 command, read 1 file, and searched 1 time"); let mut reads = Turn::new("p".into(), Vec::new()); - reads.items.push(tool("1", ToolKind::Read, None)); - assert_eq!(reads.summary(), "Performed 1 action"); + reads.items.push(tool("1", "read_file", Vec::new())); + assert_eq!(reads.summary(), "Read 1 file"); } #[test] fn changes_add_up_per_file() { let mut turn = Turn::new("p".into(), Vec::new()); - turn.items.push(tool("1", ToolKind::Write, Some(diff_text("a.py", None, "x\ny\n")))); - turn.items.push(tool("2", ToolKind::Edit, Some(diff_text("a.py", Some("x\ny\n"), "x\nz\n")))); + turn.items.push(tool("1", "write_file", vec![diff_text("a.py", None, "x\ny\n")])); + turn.items.push(tool("2", "edit_file", vec![diff_text("a.py", Some("x\ny\n"), "x\nz\n")])); let changes = turn.changes(); assert_eq!(changes.len(), 1); assert_eq!((changes[0].added, changes[0].removed, changes[0].created), (3, 1, true)); } + #[test] + fn plans_update_in_place() { + let mut turn = Turn::new("p".into(), Vec::new()); + let step = |status| vec![PlanStep { text: "a".into(), status }]; + turn.set_plan(step(StepStatus::Active), None); + turn.push_text("working"); + turn.set_plan(step(StepStatus::Done), Some("finished".into())); + assert_eq!(turn.items.len(), 2); + assert!(matches!(&turn.items[0], Item::Plan { steps, .. } if steps[0].status == StepStatus::Done)); + } + #[test] fn unfinished_turns_stop_on_recovery() { let mut thread = Thread::new(None, "hi"); let mut turn = Turn::new("hi".into(), Vec::new()); - turn.items.push(Item::Tool(ToolItem { - id: "1".into(), - kind: ToolKind::Run, - target: "x".into(), - status: ToolStatus::Running, - output: String::new(), - diff: None, - open: false, - })); + let mut running = ToolItem::new(legacy("shell")); + running.id = "1".into(); + turn.items.push(Item::Tool(running)); thread.turns.push(turn); thread.recover(); assert!(thread.turns[0].state == TurnState::Stopped); assert!(matches!(&thread.turns[0].items[0], Item::Tool(t) if t.status == ToolStatus::Failed)); } + #[test] + fn version_one_threads_still_load() { + let old = r#"{"Tool":{"id":"c1","kind":"Run","target":"npm test","status":"Done","output":"ok","diff":null}}"#; + let Item::Tool(tool) = serde_json::from_str::(old).unwrap() else { panic!("a tool item") }; + assert_eq!((tool.tool.as_str(), tool.category, tool.target.as_str()), ("shell", Category::Command, "npm test")); + let saved = serde_json::to_string(&Item::Tool(tool)).unwrap(); + let Item::Tool(again) = serde_json::from_str::(&saved).unwrap() else { panic!("a tool item") }; + assert_eq!(again.tool, "shell"); + } + #[test] fn interrupted_tool_calls_get_answers() { let mut history = vec![ Message::user("go"), Message::assistant( "", - vec![quill_llama::ToolCall::new("a", "read_file", "{}"), quill_llama::ToolCall::new("b", "list_files", "{}")], + vec![quill_providers::ToolCall::new("a", "read_file", "{}"), quill_providers::ToolCall::new("b", "list_files", "{}")], ), Message::tool("a", "ok"), ]; diff --git a/crates/quill-code/src/thread_view.rs b/crates/quill-code/src/thread_view.rs index 2cecca9..24cb18d 100644 --- a/crates/quill-code/src/thread_view.rs +++ b/crates/quill-code/src/thread_view.rs @@ -1,3 +1,4 @@ +use std::collections::HashSet; use std::time::{Duration, Instant}; use gpui_kit::component::text::TextView; @@ -5,10 +6,13 @@ use gpui_kit::{ AnyElement, ClipboardItem, Context, Div, Entity, EventEmitter, FontWeight, IntoElement, ObjectFit, ParentElement, Render, ScrollHandle, ScrollWheelEvent, SharedString, Stateful, Styled, Subscription, Task, Window, div, img, point, prelude::*, px, relative, }; -use quill_agent::{FileDiff, LineKind, ToolKind}; +use quill_config::Reasoning; +use quill_core::{Category, FileDiff, LineKind, PlanStep, StepStatus}; use quill_weave::State; +use crate::config::Config; use crate::icons::Icon; +use crate::motion; use crate::palette::{Palette, palette}; use crate::project; use crate::smooth_scroll::SmoothScroll; @@ -18,10 +22,11 @@ use crate::weave::WeaveMark; use crate::workspace::Workspace; const COPIED_FOR: Duration = Duration::from_millis(1500); +const LIVE_LINES: usize = 14; -pub struct OpenDiff { - pub thread: u64, - pub turn: usize, +pub enum ThreadEvent { + OpenDiff { thread: u64, turn: usize }, + Retry { thread: u64, turn: usize }, } pub struct ThreadView { @@ -32,10 +37,16 @@ pub struct ThreadView { copied: Option, copy_reset: Option>, shown: Option, - _subscription: Subscription, + open: HashSet, + _subscriptions: Vec, } -impl EventEmitter for ThreadView {} +impl EventEmitter for ThreadView {} + +enum Block<'a> { + One(usize, &'a Item), + Explore(Vec<&'a ToolItem>), +} pub fn file_icon(path: &str) -> Icon { let ext = path.rsplit('.').next().unwrap_or_default().to_ascii_lowercase(); @@ -91,58 +102,154 @@ pub fn diff_lines(diff: &FileDiff, limit: usize, p: Palette) -> Div { }) } -fn verb(tool: &ToolItem) -> &'static str { - let running = matches!(tool.status, ToolStatus::Running | ToolStatus::Waiting); - match (tool.kind, running) { - (ToolKind::List, true) => "Looking through", - (ToolKind::List, false) => "Looked through", - (ToolKind::Read, true) => "Opening", - (ToolKind::Read, false) => "Opened", - (ToolKind::Search, true) => "Hunting for", - (ToolKind::Search, false) => "Hunted for", - (ToolKind::Write, true) => "Writing", - (ToolKind::Write, false) => { - if tool.diff.as_ref().is_some_and(|d| d.created) { - "Added" - } else { - "Rewrote" +pub fn tool_icon(tool: &ToolItem) -> Icon { + match tool.tool.as_str() { + "list_dir" => Icon::FolderTree, + "read_file" => Icon::FileText, + "write_file" => Icon::FilePlus, + "commit_changes" => Icon::Commit, + "open_pull_request" => Icon::PullRequest, + _ => match tool.category { + Category::Explore => Icon::Search, + Category::Edit => Icon::Compose, + Category::Command => Icon::Terminal, + Category::Plan => Icon::Check, + Category::Question => Icon::Chat, + Category::Git => Icon::Branch, + Category::Web => Icon::Globe, + Category::Desktop => Icon::Cube, + Category::Agent => Icon::Bolt, + Category::Other => Icon::Sliders, + }, + } +} + +fn hidden_tool(tool: &ToolItem) -> bool { + matches!(tool.category, Category::Plan | Category::Question) +} + +fn flush<'a>(items: &'a [Item], run: &mut Vec, out: &mut Vec>) { + match run.as_slice() { + [] => {} + [one] => out.push(Block::One(*one, &items[*one])), + many => out.push(Block::Explore( + many.iter() + .filter_map(|index| match &items[*index] { + Item::Tool(tool) => Some(tool), + _ => None, + }) + .collect(), + )), + } + run.clear(); +} + +fn blocks(items: &[Item], skip: Option, group: bool) -> Vec> { + let mut out = Vec::new(); + let mut run: Vec = Vec::new(); + for (index, item) in items.iter().enumerate() { + if Some(index) == skip || matches!(item, Item::Plan { .. }) { + continue; + } + match item { + Item::Tool(tool) if hidden_tool(tool) => continue, + Item::Tool(tool) if group && tool.category == Category::Explore => run.push(index), + Item::Text(text) | Item::Reasoning(text) if text.trim().is_empty() => continue, + _ => { + flush(items, &mut run, &mut out); + out.push(Block::One(index, item)); } } - (ToolKind::Edit, true) => "Changing", - (ToolKind::Edit, false) => "Changed", - (ToolKind::Run, true) => "Running", - (ToolKind::Run, false) => "Ran", - (ToolKind::Commit, true) => "Committing", - (ToolKind::Commit, false) => "Committed", - (ToolKind::PullRequest, true) => "Opening a pull request", - (ToolKind::PullRequest, false) => "Opened a pull request", } + flush(items, &mut run, &mut out); + out +} + +fn explored(tools: &[&ToolItem]) -> String { + let count = |names: &[&str]| tools.iter().filter(|t| names.contains(&t.tool.as_str())).count(); + let (reads, searches, lists) = (count(&["read_file"]), count(&["grep", "find_files"]), count(&["list_dir"])); + let other = tools.len() - reads - searches - lists; + let plural = |n: usize, one: &str, many: &str| format!("{n} {}", if n == 1 { one } else { many }); + let mut parts = Vec::new(); + if reads > 0 { + parts.push(plural(reads, "file", "files")); + } + if searches > 0 { + parts.push(plural(searches, "search", "searches")); + } + if lists > 0 { + parts.push(plural(lists, "folder", "folders")); + } + if other > 0 { + parts.push(plural(other, "lookup", "lookups")); + } + parts.join(", ") +} + +fn strip_ansi(text: &str) -> String { + let mut out = String::with_capacity(text.len()); + let mut chars = text.chars().peekable(); + while let Some(c) = chars.next() { + if c == '\u{1b}' { + if chars.peek() == Some(&'[') { + chars.next(); + for next in chars.by_ref() { + if next.is_ascii_alphabetic() { + break; + } + } + } + continue; + } + if c != '\r' { + out.push(c); + } + } + out +} + +fn head(text: &str, lines: usize) -> String { + let all: Vec<&str> = text.lines().collect(); + if all.len() <= lines { + return text.to_string(); + } + format!("{}\n… {} more lines", all[..lines].join("\n"), all.len() - lines) +} + +fn tail(text: &str, lines: usize) -> String { + let all: Vec<&str> = text.lines().collect(); + if all.len() <= lines { + return text.to_string(); + } + format!("… {} earlier lines\n{}", all.len() - lines, all[all.len() - lines..].join("\n")) } -fn kind_icon(kind: ToolKind) -> Icon { - match kind { - ToolKind::List => Icon::FolderTree, - ToolKind::Read => Icon::FileText, - ToolKind::Search => Icon::Search, - ToolKind::Write => Icon::FilePlus, - ToolKind::Edit => Icon::Compose, - ToolKind::Run => Icon::Terminal, - ToolKind::Commit => Icon::Commit, - ToolKind::PullRequest => Icon::PullRequest, +fn seconds_label(seconds: f32) -> String { + if seconds < 10.0 { format!("{seconds:.1}s") } else { format!("{}s", seconds.round() as u64) } +} + +fn command_body(output: &str) -> &str { + match output.split_once('\n') { + Some((first, rest)) if first.starts_with("Exit code") || first.starts_with("Stopped") => rest, + None if output.starts_with("Exit code") => "", + _ => output, } } impl ThreadView { pub fn new(workspace: Entity, cx: &mut Context) -> Self { - let subscription = cx.observe(&workspace, |this, workspace, cx| { - let active = workspace.read(cx).active; - if active != this.shown { - this.shown = active; - this.smooth.cancel(); - this.scroll.scroll_to_bottom(); - } - cx.notify(); - }); + let subscriptions = vec![ + cx.observe(&workspace, |this, workspace, cx| { + let active = workspace.read(cx).active; + if active != this.shown { + this.shown = active; + this.smooth.cancel(); + this.scroll.scroll_to_bottom(); + } + cx.notify(); + }), + cx.observe_global::(|_, cx| cx.notify()), + ]; ThreadView { workspace, status: cx.new(|_| WeaveMark::new(State::Thinking)), @@ -151,7 +258,8 @@ impl ThreadView { copied: None, copy_reset: None, shown: None, - _subscription: subscription, + open: HashSet::new(), + _subscriptions: subscriptions, } } @@ -176,6 +284,13 @@ impl ThreadView { } } + fn toggle(&mut self, key: String, cx: &mut Context) { + if !self.open.remove(&key) { + self.open.insert(key); + } + cx.notify(); + } + fn copy(&mut self, id: SharedString, text: String, cx: &mut Context) { cx.write_to_clipboard(ClipboardItem::new_string(text)); self.copied = Some(id); @@ -206,26 +321,126 @@ impl ThreadView { .on_click(cx.listener(move |this, _, _, cx| this.copy(click.clone(), text.clone(), cx))) } - fn tool_row(&self, thread: u64, turn: usize, tool: &ToolItem, cx: &mut Context) -> AnyElement { + fn row_shell(&self, key: &str, open: bool, has_detail: bool, cx: &mut Context) -> Stateful
{ let p = palette(cx); - let id = tool.id.clone(); - let failed = tool.status == ToolStatus::Failed; - let waiting = tool.status == ToolStatus::Waiting; - let running = tool.status == ToolStatus::Running; - let target = if tool.target.is_empty() { tool.kind.name().to_string() } else { tool.target.clone() }; - let has_detail = !tool.output.is_empty() || tool.diff.is_some(); - let row = div() - .id(SharedString::from(format!("tool-{thread}-{turn}-{id}"))) + let toggle = key.to_string(); + div() + .id(SharedString::from(key.to_string())) .flex() .items_center() .gap(px(10.)) .min_h(px(30.)) - .px(px(6.)) - .mx(px(-6.)) + .px(px(8.)) + .mx(px(-8.)) .rounded(px(8.)) .text_size(px(14.)) - .when(has_detail, |row| row.cursor_pointer().hover(move |style| style.bg(p.row_hover))) - .child(icon(kind_icon(tool.kind), 15., if failed { p.danger } else { p.text_faint })) + .when(open, |row| row.bg(p.fill)) + .when(has_detail, |row| { + row.cursor_pointer() + .hover(move |style| style.bg(p.row_hover)) + .on_click(cx.listener(move |this, _, _, cx| this.toggle(toggle.clone(), cx))) + }) + } + + fn status_mark(&self, key: &str, tool: &ToolItem, p: Palette) -> AnyElement { + match tool.status { + ToolStatus::Running => { + motion::spin(SharedString::from(format!("{key}-spin")), icon(Icon::Loader, 14., p.text_faint)).into_any_element() + } + ToolStatus::Waiting => div() + .px(px(7.)) + .h(px(20.)) + .flex() + .items_center() + .rounded(px(6.)) + .bg(p.warning.opacity(0.14)) + .text_size(px(12.)) + .text_color(p.warning) + .child("Needs your OK") + .into_any_element(), + ToolStatus::Failed => icon(Icon::CircleX, 14., p.danger).into_any_element(), + ToolStatus::Done => div().into_any_element(), + } + } + + fn tool_body(&self, key: &str, tool: &ToolItem, command: bool, cx: &mut Context) -> AnyElement { + let p = palette(cx); + let failed = tool.status == ToolStatus::Failed; + let content: AnyElement = if !tool.diffs.is_empty() { + div() + .flex() + .flex_col() + .gap(px(10.)) + .children(tool.diffs.iter().map(|diff| { + div() + .flex() + .flex_col() + .gap(px(4.)) + .when(tool.diffs.len() > 1, |col| { + col.child(div().font_family(MONO).text_size(px(12.)).text_color(p.text_muted).child(diff.path.clone())) + }) + .child(diff_lines(diff, 80, p)) + })) + .into_any_element() + } else if command { + let output = strip_ansi(&tool.output); + let body = command_body(&output); + let shown = if tool.working() { tail(body, LIVE_LINES) } else { head(body, 120) }; + div() + .flex() + .flex_col() + .gap(px(6.)) + .font_family(MONO) + .text_size(px(12.5)) + .line_height(px(19.)) + .child(div().text_color(p.link).child(format!("$ {}", tool.target))) + .when(!shown.trim().is_empty(), |col| col.child(div().text_color(p.text_muted).child(shown))) + .into_any_element() + } else { + div() + .font_family(MONO) + .text_size(px(12.5)) + .line_height(px(19.)) + .text_color(if failed { p.danger } else { p.text_muted }) + .child(head(&tool.output, 40)) + .into_any_element() + }; + motion::rise( + SharedString::from(format!("{key}-body")), + div() + .ml(px(25.)) + .mt(px(2.)) + .mb(px(6.)) + .py(px(8.)) + .px(px(10.)) + .rounded(px(10.)) + .bg(if command { p.sidebar } else { p.fill }) + .border_1() + .border_color(p.border_soft) + .overflow_hidden() + .child(content), + -4., + cx, + ) + .into_any_element() + } + + fn tool_row(&self, thread: u64, turn: usize, tool: &ToolItem, cx: &mut Context) -> AnyElement { + let p = palette(cx); + let key = format!("tool-{thread}-{turn}-{}", tool.id); + let open = self.open.contains(&key); + let failed = tool.status == ToolStatus::Failed; + let command = tool.category == Category::Command; + let target = + if tool.target.is_empty() { tool.tool.replace('_', " ") } else { tool.target.lines().next().unwrap_or_default().to_string() }; + let added: usize = tool.diffs.iter().map(|d| d.added).sum(); + let removed: usize = tool.diffs.iter().map(|d| d.removed).sum(); + let has_detail = !tool.output.trim().is_empty() || !tool.diffs.is_empty(); + let live = command && tool.status == ToolStatus::Running && !tool.output.trim().is_empty(); + let exit = if command { tool.exit_code().filter(|code| *code != 0) } else { None }; + let row = self + .row_shell(&key, open, has_detail, cx) + .child(icon(tool_icon(tool), 15., if failed { p.danger } else { p.text_faint })) .child( div() .flex_1() @@ -234,7 +449,7 @@ impl ThreadView { .items_center() .gap(px(6.)) .overflow_hidden() - .child(div().flex_shrink_0().text_color(p.text_faint).child(verb(tool))) + .child(div().flex_shrink_0().text_color(p.text_faint).child(tool.verb().to_string())) .child( div() .min_w_0() @@ -242,57 +457,121 @@ impl ThreadView { .whitespace_nowrap() .text_ellipsis() .text_color(p.text_muted) - .when(tool.kind == ToolKind::Run, |t| t.font_family(MONO).text_size(px(13.))) + .when(command, |t| t.font_family(MONO).text_size(px(13.))) .child(target), ) - .when_some(tool.diff.as_ref(), |row, diff| { - row.child(div().flex_shrink_0().text_size(px(12.5)).text_color(p.add).child(format!("+{}", diff.added))) - .child(div().flex_shrink_0().text_size(px(12.5)).text_color(p.del).child(format!("-{}", diff.removed))) + .when(!tool.diffs.is_empty(), |row| { + row.child(div().flex_shrink_0().text_size(px(12.5)).text_color(p.add).child(format!("+{added}"))) + .child(div().flex_shrink_0().text_size(px(12.5)).text_color(p.del).child(format!("−{removed}"))) }), ) - .when(waiting, |row| row.child(div().text_size(px(12.5)).text_color(p.warning).child("Needs your OK"))) - .when(running, |row| row.child(icon(Icon::Loader, 14., p.text_faint))) - .when(failed, |row| row.child(icon(Icon::CircleX, 14., p.danger))) - .when(has_detail, |row| row.child(icon(if tool.open { Icon::ChevronDown } else { Icon::ChevronRight }, 14., p.text_faint))) - .on_click(cx.listener(move |this, _, _, cx| { - let id = id.clone(); - this.workspace.update(cx, |w, cx| w.toggle_tool(thread, turn, &id, cx)); - })); - let detail = tool.open.then(|| { - let body: AnyElement = match (&tool.diff, tool.kind) { - (Some(diff), _) => diff_lines(diff, 60, p).into_any_element(), - (None, ToolKind::Run) => div() + .when_some(exit, |row, code| { + row.child( + div() + .px(px(6.)) + .rounded(px(5.)) + .bg(p.danger.opacity(0.12)) + .text_size(px(11.5)) + .text_color(p.danger) + .child(format!("exit {code}")), + ) + }) + .when_some(tool.seconds().filter(|s| *s >= 1.0), |row, seconds| { + row.child(div().text_size(px(12.)).text_color(p.text_faint).child(seconds_label(seconds))) + }) + .child(self.status_mark(&key, tool, p)) + .when(has_detail, |row| row.child(icon(if open { Icon::ChevronDown } else { Icon::ChevronRight }, 13., p.text_faint))); + let body = (open || live).then(|| self.tool_body(&key, tool, command, cx)); + div().flex().flex_col().child(row).children(body).into_any_element() + } + + fn explore_group(&self, thread: u64, turn: usize, tools: &[&ToolItem], cx: &mut Context) -> AnyElement { + let p = palette(cx); + let key = format!("explore-{thread}-{turn}-{}", tools[0].id); + let open = self.open.contains(&key); + let working = tools.iter().any(|t| t.working()); + let failed = tools.iter().filter(|t| t.status == ToolStatus::Failed).count(); + let row = self + .row_shell(&key, open, true, cx) + .child(icon(Icon::Search, 15., p.text_faint)) + .child( + div() + .flex_1() + .min_w_0() .flex() - .flex_col() + .items_center() .gap(px(6.)) - .font_family(MONO) - .text_size(px(12.5)) - .line_height(px(19.)) - .child(div().text_color(p.link).child(format!("> {}", tool.target))) - .child(div().text_color(p.text_muted).child(clip(&tool.output, 60))) - .into_any_element(), - _ => div() - .font_family(MONO) - .text_size(px(12.5)) - .line_height(px(19.)) - .text_color(if failed { p.danger } else { p.text_muted }) - .child(clip(&tool.output, 30)) - .into_any_element(), - }; + .child(div().text_color(p.text_faint).child(if working { "Exploring" } else { "Explored" })) + .child( + div() + .min_w_0() + .overflow_hidden() + .whitespace_nowrap() + .text_ellipsis() + .text_color(p.text_muted) + .child(explored(tools)), + ), + ) + .when(failed > 0, |row| row.child(div().text_size(px(12.)).text_color(p.danger).child(format!("{failed} failed")))) + .when(working, |row| row.child(motion::spin(SharedString::from(format!("{key}-spin")), icon(Icon::Loader, 14., p.text_faint)))) + .child(icon(if open { Icon::ChevronDown } else { Icon::ChevronRight }, 13., p.text_faint)); + let inner = open.then(|| { + let rows: Vec = tools.iter().map(|tool| self.tool_row(thread, turn, tool, cx)).collect(); + motion::rise( + SharedString::from(format!("{key}-inner")), + div().ml(px(14.)).pl(px(10.)).border_l_1().border_color(p.border_soft).flex().flex_col().children(rows), + -4., + cx, + ) + }); + div().flex().flex_col().child(row).children(inner).into_any_element() + } + + fn reasoning(&self, thread: u64, turn: usize, index: usize, text: &str, streaming: bool, cx: &mut Context) -> Option { + let p = palette(cx); + let mode = Config::get(cx).appearance.reasoning; + if mode == Reasoning::Hidden && !streaming { + return None; + } + let key = format!("think-{thread}-{turn}-{index}"); + let open = (mode == Reasoning::Expanded) != self.open.contains(&key); + let text = text.trim().to_string(); + let preview = text.lines().rev().find(|line| !line.trim().is_empty()).unwrap_or_default().trim().to_string(); + let label = div().flex_shrink_0().text_color(p.text_faint).child(if streaming { "Thinking" } else { "Thought" }); + let label: AnyElement = if streaming { + motion::shimmer(SharedString::from(format!("{key}-shimmer")), label).into_any_element() + } else { + label.into_any_element() + }; + let row = self + .row_shell(&key, open, true, cx) + .child(icon(Icon::Bulb, 15., p.text_faint)) + .child(div().flex_1().min_w_0().flex().items_center().gap(px(6.)).child(label).when(!open, |row| { + row.child( + div() + .min_w_0() + .overflow_hidden() + .whitespace_nowrap() + .text_ellipsis() + .text_size(px(13.)) + .text_color(p.text_faint) + .child(preview), + ) + })) + .child(icon(if open { Icon::ChevronDown } else { Icon::ChevronRight }, 13., p.text_faint)); + let body = open.then(|| { div() .ml(px(25.)) - .mt(px(2.)) - .mb(px(6.)) - .py(px(8.)) - .px(px(10.)) - .rounded(px(10.)) - .bg(p.fill) - .border_1() + .mb(px(4.)) + .pl(px(12.)) + .border_l_2() .border_color(p.border_soft) - .overflow_hidden() - .child(body) + .text_size(px(13.5)) + .line_height(px(21.)) + .text_color(p.text_faint) + .child(text.clone()) }); - div().flex().flex_col().child(row).children(detail).into_any_element() + Some(div().flex().flex_col().child(row).children(body).into_any_element()) } fn changes_card(&self, thread: u64, turn: usize, changes: &[FileChanges], cx: &mut Context) -> impl IntoElement + use<> { @@ -316,31 +595,32 @@ impl ThreadView { .px(px(14.)) .py(px(10.)) .text_size(px(13.5)) + .child(icon(Icon::FileDiff, 15., p.text_muted)) .child( div() .font_weight(FontWeight::SEMIBOLD) .text_color(p.text) - .child(format!("{count} {} touched", if count == 1 { "file" } else { "files" })), + .child(format!("{count} {} changed", if count == 1 { "file" } else { "files" })), ) .child(div().text_size(px(12.5)).text_color(p.add).child(format!("+{added}"))) - .child(div().text_size(px(12.5)).text_color(p.del).child(format!("-{removed}"))) + .child(div().text_size(px(12.5)).text_color(p.del).child(format!("−{removed}"))) .child(div().flex_1()) .child( div() .id(SharedString::from(format!("open-diff-{thread}-{turn}"))) .flex() .items_center() - .gap(px(5.)) - .px(px(8.)) - .h(px(26.)) + .px(px(10.)) + .h(px(28.)) .rounded(px(7.)) + .border_1() + .border_color(p.border) .text_size(px(12.5)) - .text_color(p.text_muted) + .text_color(p.text) .cursor_pointer() - .hover(move |style| style.bg(p.row_hover).text_color(p.text)) - .child(icon(Icon::FileDiff, 14., p.text_muted)) + .hover(move |style| style.bg(p.row_hover)) .child("Review") - .on_click(cx.listener(move |_, _, _, cx| cx.emit(OpenDiff { thread, turn }))), + .on_click(cx.listener(move |_, _, _, cx| cx.emit(ThreadEvent::OpenDiff { thread, turn }))), ), ) .children(changes.iter().map(|change| { @@ -354,22 +634,112 @@ impl ThreadView { .border_color(p.border_soft) .child(icon(file_icon(&change.path), 15., p.text_muted)) .child(div().flex_1().min_w_0().font_family(MONO).text_size(px(13.)).text_color(p.text).child(change.path.clone())) - .when(change.created, |row| row.child(div().text_size(px(11.5)).text_color(p.text_faint).child("new"))) + .when(change.created, |row| { + row.child( + div() + .px(px(6.)) + .rounded(px(5.)) + .bg(p.success.opacity(0.12)) + .text_size(px(11.)) + .text_color(p.success) + .child("new"), + ) + }) .child(div().w(px(44.)).flex().justify_end().text_size(px(12.5)).text_color(p.add).child(format!("+{}", change.added))) .child( - div().w(px(44.)).flex().justify_end().text_size(px(12.5)).text_color(p.del).child(format!("-{}", change.removed)), + div().w(px(44.)).flex().justify_end().text_size(px(12.5)).text_color(p.del).child(format!("−{}", change.removed)), ) })) } - fn turn_view(&self, thread: &Thread, index: usize, turn: &Turn, pending: bool, cx: &mut Context) -> Div { + fn activity(turn: &Turn, waiting: bool, asked: bool) -> String { + if asked { + return "Waiting for your answer".into(); + } + if waiting { + return "Waiting for your OK".into(); + } + match turn.items.iter().rev().find(|item| !matches!(item, Item::Plan { .. } | Item::Note(_) | Item::Steer(_))) { + None => "Warming up the model".into(), + Some(Item::Reasoning(_)) => "Thinking".into(), + Some(Item::Text(_)) => "Writing".into(), + Some(Item::Tool(tool)) if tool.working() => { + let target = tool.target.lines().next().unwrap_or_default(); + if target.is_empty() { tool.active.clone() } else { format!("{} {target}", tool.active) } + } + _ => "Thinking".into(), + } + } + + fn header(&self, thread: &Thread, index: usize, turn: &Turn, waiting: bool, asked: bool, cx: &mut Context) -> Option { let p = palette(cx); let tid = thread.id; - let latest = index + 1 == thread.turns.len(); - let working = turn.working(); - let final_text = turn.final_text(); - let show_steps = working || turn.expanded; - let mut column = div().flex().flex_col().gap(px(12.)); + if turn.working() { + let tone = if waiting || asked { p.warning } else { p.text_faint }; + let label = div() + .min_w_0() + .overflow_hidden() + .whitespace_nowrap() + .text_ellipsis() + .text_color(tone) + .child(Self::activity(turn, waiting, asked)); + return Some( + div() + .flex() + .items_center() + .gap(px(10.)) + .pb(px(8.)) + .mb(px(2.)) + .border_b_1() + .border_color(p.border_soft) + .text_size(px(13.5)) + .child(motion::shimmer(SharedString::from(format!("activity-{tid}-{index}")), label)) + .child(div().flex_1()) + .child(div().flex_shrink_0().text_size(px(12.5)).text_color(p.text_faint).child(format!("{}s", turn.elapsed_secs()))) + .into_any_element(), + ); + } + if !turn.has_steps() { + return None; + } + let expanded = turn.expanded; + Some( + div() + .id(SharedString::from(format!("worked-{tid}-{index}"))) + .flex() + .items_center() + .gap(px(6.)) + .pb(px(8.)) + .mb(px(2.)) + .border_b_1() + .border_color(p.border_soft) + .text_size(px(13.5)) + .text_color(if expanded { p.text } else { p.text_faint }) + .cursor_pointer() + .hover(move |style| style.text_color(p.text)) + .child(format!("Worked for {}s", turn.elapsed_secs())) + .child(icon(if expanded { Icon::ChevronDown } else { Icon::ChevronRight }, 13., p.text_faint)) + .when(!expanded, |row| { + row.child( + div() + .ml(px(4.)) + .min_w_0() + .overflow_hidden() + .whitespace_nowrap() + .text_ellipsis() + .text_color(p.text_faint) + .child(turn.summary()), + ) + }) + .on_click(cx.listener(move |this, _, _, cx| this.workspace.update(cx, |w, cx| w.toggle_turn(tid, index, cx)))) + .into_any_element(), + ) + } + + fn prompt(&self, thread: &Thread, index: usize, turn: &Turn, cx: &mut Context) -> Div { + let p = palette(cx); + let tid = thread.id; + let mut column = div().flex().flex_col().gap(px(8.)); if !turn.images.is_empty() { column = column.child(div().flex().flex_wrap().justify_end().gap(px(8.)).children(turn.images.iter().enumerate().map( |(n, path)| { @@ -388,8 +758,8 @@ impl ThreadView { }, ))); } - let prompt_group = SharedString::from(format!("prompt-{tid}-{index}")); - let message = div() + let group = SharedString::from(format!("prompt-{tid}-{index}")); + let bubble = div() .max_w(relative(0.85)) .px(px(16.)) .py(px(10.)) @@ -415,78 +785,125 @@ impl ThreadView { .child(name.clone()) }))) }); - column = column.child( - div().group(prompt_group.clone()).flex().flex_col().items_end().gap(px(2.)).child(message).child( + column.child( + div().group(group.clone()).flex().flex_col().items_end().gap(px(2.)).child(bubble).child( self.copy_button(SharedString::from(format!("copy-prompt-{tid}-{index}")), turn.prompt.clone(), cx) .invisible() - .group_hover(prompt_group, |style| style.visible()), + .group_hover(group, |style| style.visible()), ), - ); - let mut agent = div().flex().flex_col().gap(px(4.)); - if working { - agent = agent.child( - div() - .pb(px(6.)) - .mb(px(4.)) - .border_b_1() - .border_color(p.border_soft) - .text_size(px(13.5)) - .text_color(p.text_faint) - .child(format!("Agent running · {}s", turn.elapsed_secs())), - ); - } else if turn.has_steps() { - agent = agent.child( - div() - .id(SharedString::from(format!("worked-{tid}-{index}"))) + ) + } + + fn block(&self, tid: u64, index: usize, turn: &Turn, block: &Block<'_>, cx: &mut Context) -> Option { + let p = palette(cx); + let last = turn.items.len().saturating_sub(1); + let element = match block { + Block::Explore(tools) => self.explore_group(tid, index, tools, cx), + Block::One(item_index, item) => match item { + Item::Reasoning(text) => return self.reasoning(tid, index, *item_index, text, turn.working() && *item_index == last, cx), + Item::Text(text) => div() + .py(px(4.)) + .text_size(px(14.5)) + .line_height(px(24.)) + .text_color(p.text) + .child(TextView::markdown(SharedString::from(format!("md-{tid}-{index}-{item_index}")), text.clone())) + .into_any_element(), + Item::Tool(tool) => self.tool_row(tid, index, tool, cx), + Item::Question { question, answer, .. } => div() + .flex() + .gap(px(10.)) + .py(px(4.)) + .child(div().pt(px(3.)).child(icon(Icon::Chat, 15., p.link))) + .child( + div() + .flex_1() + .min_w_0() + .flex() + .flex_col() + .gap(px(2.)) + .text_size(px(13.5)) + .child(div().text_color(p.text).child(question.clone())) + .child(div().text_color(if answer.is_some() { p.text_muted } else { p.warning }).child(match answer { + Some(answer) => format!("You answered: {answer}"), + None => "Waiting for your answer".to_string(), + })), + ) + .into_any_element(), + Item::Steer(text) => div() + .flex() + .justify_end() + .py(px(2.)) + .child( + div() + .max_w(relative(0.8)) + .flex() + .flex_col() + .items_end() + .gap(px(2.)) + .child( + div() + .flex() + .items_center() + .gap(px(4.)) + .text_size(px(11.5)) + .text_color(p.text_faint) + .child(icon(Icon::Steer, 12., p.text_faint)) + .child("Added while working"), + ) + .child( + div() + .px(px(12.)) + .py(px(6.)) + .rounded(px(14.)) + .border_1() + .border_color(p.border_soft) + .text_size(px(13.5)) + .text_color(p.text_muted) + .child(text.clone()), + ), + ) + .into_any_element(), + Item::Note(text) => div() .flex() .items_center() - .gap(px(6.)) - .pb(px(6.)) - .mb(px(4.)) - .border_b_1() - .border_color(p.border_soft) - .text_size(px(13.5)) - .text_color(if turn.expanded { p.text } else { p.text_faint }) - .cursor_pointer() - .hover(move |style| style.text_color(p.text)) - .child(format!("Finished in {}s", turn.elapsed_secs())) - .child(icon(if turn.expanded { Icon::ChevronDown } else { Icon::ChevronRight }, 13., p.text_faint)) - .when(!turn.expanded, |row| row.child(div().ml(px(4.)).text_color(p.text_faint).child(format!("· {}", turn.summary())))) - .on_click(cx.listener(move |this, _, _, cx| this.workspace.update(cx, |w, cx| w.toggle_turn(tid, index, cx)))), - ); + .gap(px(8.)) + .py(px(4.)) + .text_size(px(12.5)) + .text_color(p.text_faint) + .child(icon(Icon::Info, 13., p.text_faint)) + .child(text.clone()) + .into_any_element(), + Item::Plan { .. } => return None, + }, + }; + Some(element) + } + + fn turn_view(&self, thread: &Thread, index: usize, turn: &Turn, waiting: bool, asked: bool, cx: &mut Context) -> Div { + let p = palette(cx); + let tid = thread.id; + let latest = index + 1 == thread.turns.len(); + let working = turn.working(); + let final_text = turn.final_text(); + let show_steps = working || turn.expanded; + let group = Config::get(cx).appearance.group_exploration; + let mut agent = div().flex().flex_col().gap(px(4.)); + if let Some(header) = self.header(thread, index, turn, waiting, asked, cx) { + agent = agent.child(header); } if show_steps { - for (item_index, item) in turn.items.iter().enumerate() { - if Some(item_index) == final_text { - continue; + let plan = turn.items.iter().find_map(|item| match item { + Item::Plan { steps, explanation } => Some((steps, explanation)), + _ => None, + }); + if let Some((steps, explanation)) = plan { + agent = agent.child(plan_card(steps, explanation.as_deref(), p)); + } + for (n, block) in blocks(&turn.items, final_text, group).iter().enumerate() { + if let Some(element) = self.block(tid, index, turn, block, cx) { + let id = SharedString::from(format!("block-{tid}-{index}-{n}")); + agent = agent.child(if working { motion::rise(id, div().child(element), 6., cx).into_any_element() } else { element }); } - agent = agent.child(match item { - Item::Reasoning(text) if !text.trim().is_empty() => div() - .flex() - .gap(px(10.)) - .py(px(4.)) - .child(div().pt(px(3.)).child(icon(Icon::Bulb, 15., p.text_faint))) - .child( - div() - .flex_1() - .min_w_0() - .text_size(px(13.5)) - .line_height(px(21.)) - .text_color(p.text_faint) - .line_clamp(4) - .child(text.trim().to_string()), - ) - .into_any_element(), - Item::Text(text) if !text.trim().is_empty() => div() - .py(px(4.)) - .text_size(px(14.5)) - .line_height(px(24.)) - .text_color(p.text) - .child(TextView::markdown(SharedString::from(format!("md-{tid}-{index}-{item_index}")), text.clone())) - .into_any_element(), - Item::Tool(tool) => self.tool_row(tid, index, tool, cx), - _ => div().into_any_element(), - }); } } if let Some(item_index) = final_text @@ -496,50 +913,48 @@ impl ThreadView { let copy = self .copy_button(SharedString::from(format!("copy-reply-{tid}-{index}")), text.clone(), cx) .when(!latest, |button| button.invisible().group_hover(reply_group.clone(), |style| style.visible())); + let mut model = turn.model.clone().unwrap_or_default(); + if let Some(usd) = turn.cost.filter(|usd| *usd > 0.0) { + model = format!("{model} · {}", if usd < 0.01 { format!("${usd:.4}") } else { format!("${usd:.2}") }); + } agent = agent.child( div() .group(reply_group) .flex() .flex_col() - .gap(px(2.)) + .gap(px(4.)) .child( div() - .pt(px(4.)) + .pt(px(6.)) .text_size(px(14.5)) .line_height(px(24.)) .text_color(p.text) .child(TextView::markdown(SharedString::from(format!("md-{tid}-{index}-{item_index}")), text.clone())), ) - .child(copy), - ); - } - if working { - let label = if pending { - "Waiting on you" - } else { - match turn.items.last() { - None => "Warming up the model", - Some(Item::Reasoning(_)) => "Thinking", - Some(Item::Text(_)) => "Writing", - Some(Item::Tool(tool)) if tool.status == ToolStatus::Running => "Using a tool", - Some(Item::Tool(_)) => "Thinking", - } - }; - agent = agent.child( - div() - .flex() - .items_center() - .gap(px(8.)) - .pt(px(6.)) - .text_size(px(13.5)) - .text_color(p.text_faint) - .child(div().size(px(20.)).child(self.status.clone())) - .child(label), + .child( + div() + .flex() + .items_center() + .gap(px(8.)) + .child(copy) + .when(!model.is_empty(), |row| row.child(div().text_size(px(12.)).text_color(p.text_faint).child(model))), + ), ); } match &turn.state { TurnState::Stopped => { - agent = agent.child(div().pt(px(4.)).text_size(px(13.)).text_color(p.text_faint).child("You stopped this reply")) + agent = agent.child( + div() + .pt(px(4.)) + .flex() + .items_center() + .gap(px(8.)) + .text_size(px(13.)) + .text_color(p.text_faint) + .child(icon(Icon::CircleStop, 14., p.text_faint)) + .child("You stopped this reply") + .when(latest, |row| row.child(self.retry_button(tid, index, cx))), + ) } TurnState::Failed(error) => { agent = agent.child( @@ -547,15 +962,18 @@ impl ThreadView { .mt(px(4.)) .flex() .items_start() - .gap(px(8.)) + .gap(px(10.)) .px(px(12.)) .py(px(10.)) .rounded(px(10.)) .bg(p.danger.opacity(0.1)) + .border_1() + .border_color(p.danger.opacity(0.25)) .text_size(px(13.5)) .text_color(p.danger) - .child(icon(Icon::CircleAlert, 15., p.danger)) - .child(div().flex_1().child(error.clone())), + .child(div().pt(px(1.)).child(icon(Icon::CircleAlert, 15., p.danger))) + .child(div().flex_1().child(error.clone())) + .when(latest, |row| row.child(self.retry_button(tid, index, cx))), ) } _ => {} @@ -564,17 +982,93 @@ impl ThreadView { if !working && !changes.is_empty() { agent = agent.child(self.changes_card(tid, index, &changes, cx)); } - column = column.child(agent); - column + let gutter = + div().w(px(26.)).flex_shrink_0().pt(px(1.)).when(latest, |gutter| gutter.child(div().size(px(24.)).child(self.status.clone()))); + let response = div().flex().gap(px(12.)).child(gutter).child(agent.flex_1().min_w_0()); + div().flex().flex_col().gap(px(14.)).child(self.prompt(thread, index, turn, cx)).child(response) } -} -fn clip(text: &str, lines: usize) -> String { - let all: Vec<&str> = text.lines().collect(); - if all.len() <= lines { - return text.to_string(); + fn retry_button(&self, thread: u64, turn: usize, cx: &mut Context) -> Stateful
{ + let p = palette(cx); + div() + .id(SharedString::from(format!("retry-{thread}-{turn}"))) + .flex() + .flex_shrink_0() + .items_center() + .gap(px(5.)) + .px(px(10.)) + .h(px(26.)) + .rounded(px(7.)) + .border_1() + .border_color(p.border) + .text_size(px(12.5)) + .text_color(p.text) + .cursor_pointer() + .hover(move |style| style.bg(p.row_hover)) + .child(icon(Icon::Retry, 13., p.text_muted)) + .child("Try again") + .on_click(cx.listener(move |_, _, _, cx| cx.emit(ThreadEvent::Retry { thread, turn }))) } - format!("{}\n… {} more lines", all[..lines].join("\n"), all.len() - lines) +} + +fn plan_card(steps: &[PlanStep], explanation: Option<&str>, p: Palette) -> Div { + let done = steps.iter().filter(|step| step.status == StepStatus::Done).count(); + let ratio = if steps.is_empty() { 0.0 } else { done as f32 / steps.len() as f32 }; + div() + .my(px(4.)) + .px(px(14.)) + .py(px(12.)) + .rounded(px(12.)) + .bg(p.fill) + .border_1() + .border_color(p.border_soft) + .flex() + .flex_col() + .gap(px(8.)) + .child( + div() + .flex() + .items_center() + .gap(px(10.)) + .text_size(px(12.5)) + .text_color(p.text_faint) + .child(icon(Icon::ListChecks, 14., p.text_muted)) + .child(div().font_weight(FontWeight::SEMIBOLD).text_color(p.text_muted).child("Plan")) + .child(format!("{done} of {} done", steps.len())) + .child( + div() + .flex_1() + .h(px(4.)) + .rounded_full() + .bg(p.border_soft) + .child(div().h_full().w(relative(ratio)).rounded_full().bg(p.success)), + ), + ) + .children(steps.iter().map(|step| { + let mark = match step.status { + StepStatus::Done => icon(Icon::CheckCircle, 15., p.success).into_any_element(), + StepStatus::Active => icon(Icon::Loader, 15., p.link).into_any_element(), + StepStatus::Pending => { + div().size(px(13.)).m(px(1.)).rounded_full().border_1().border_color(p.text_faint).into_any_element() + } + }; + div() + .flex() + .items_center() + .gap(px(10.)) + .text_size(px(13.5)) + .text_color(match step.status { + StepStatus::Done => p.text_faint, + StepStatus::Active => p.text, + StepStatus::Pending => p.text_muted, + }) + .when(step.status == StepStatus::Done, |row| row.line_through()) + .child(div().flex_shrink_0().child(mark)) + .child(step.text.clone()) + })) + .when_some(explanation, |card, text| { + card.child(div().pt(px(2.)).text_size(px(12.5)).text_color(p.text_faint).child(text.to_string())) + }) } impl Render for ThreadView { @@ -585,8 +1079,10 @@ impl Render for ThreadView { } let workspace = self.workspace.read(cx); let Some(thread) = workspace.active_thread().cloned() else { return div().size_full() }; - let pending = workspace.pending(thread.id).is_some(); - let state = if pending { + let waiting = workspace.pending(thread.id).is_some(); + let asked = workspace.asked(thread.id).is_some(); + let working = thread.turns.last().is_some_and(|t| t.working()); + let state = if waiting || asked || !working { State::Idle } else { match thread.turns.last().and_then(|t| t.items.last()) { @@ -595,12 +1091,13 @@ impl Render for ThreadView { } }; self.status.update(cx, |mark, cx| mark.set_state(state, cx)); + let width = f32::from(Config::get(cx).appearance.transcript_width.clamp(560, 1600)); let last = thread.turns.len().saturating_sub(1); let turns: Vec
= thread .turns .iter() .enumerate() - .map(|(index, turn)| self.turn_view(&thread, index, turn, pending && index == last, cx)) + .map(|(index, turn)| self.turn_view(&thread, index, turn, waiting && index == last, asked && index == last, cx)) .collect(); div().size_full().child( div() @@ -609,7 +1106,54 @@ impl Render for ThreadView { .overflow_y_hidden() .track_scroll(&self.scroll) .on_scroll_wheel(cx.listener(Self::wheel)) - .child(div().max_w(px(820.)).mx_auto().px(px(28.)).pt(px(20.)).pb(px(40.)).flex().flex_col().gap(px(32.)).children(turns)), + .child(div().max_w(px(width)).mx_auto().px(px(28.)).pt(px(20.)).pb(px(40.)).flex().flex_col().gap(px(36.)).children(turns)), ) } +} + +#[cfg(test)] +mod tests { + use super::*; + use quill_core::tools::legacy; + + fn tool(name: &str) -> Item { + let mut item = ToolItem::new(legacy(name)); + item.id = name.into(); + item.status = ToolStatus::Done; + Item::Tool(item) + } + + #[test] + fn exploration_runs_become_one_group() { + let items = vec![tool("read_file"), tool("grep"), tool("list_dir"), tool("shell"), tool("read_file"), Item::Text("done".into())]; + let grouped = blocks(&items, Some(5), true); + assert_eq!(grouped.len(), 3); + assert!(matches!(&grouped[0], Block::Explore(tools) if tools.len() == 3)); + assert!(matches!(&grouped[1], Block::One(3, _))); + assert!(matches!(&grouped[2], Block::One(4, _))); + assert_eq!(blocks(&items, Some(5), false).len(), 5); + } + + #[test] + fn exploration_reads_like_a_count() { + let items = [tool("read_file"), tool("read_file"), tool("grep")]; + let tools: Vec<&ToolItem> = items + .iter() + .filter_map(|item| match item { + Item::Tool(tool) => Some(tool), + _ => None, + }) + .collect(); + assert_eq!(explored(&tools), "2 files, 1 search"); + } + + #[test] + fn terminal_output_is_cleaned_for_display() { + assert_eq!(strip_ansi("\u{1b}[32mok\u{1b}[0m\r\n"), "ok\n"); + assert_eq!(tail("a\nb\nc", 2), "… 1 earlier lines\nb\nc"); + assert_eq!(command_body("Exit code 0\nhello"), "hello"); + assert_eq!(command_body("Exit code 0"), ""); + assert_eq!(seconds_label(2.34), "2.3s"); + assert_eq!(seconds_label(42.6), "43s"); + } } \ No newline at end of file diff --git a/crates/quill-code/src/ui.rs b/crates/quill-code/src/ui.rs index 71bb636..09879bc 100644 --- a/crates/quill-code/src/ui.rs +++ b/crates/quill-code/src/ui.rs @@ -1,6 +1,7 @@ +use gpui_kit::component::tooltip::Tooltip; use gpui_kit::{ - Anchor, AnyElement, Context, Div, ElementId, FontWeight, Hsla, IntoElement, MouseButton, ParentElement, SharedString, Stateful, Styled, - Svg, Window, anchored, deferred, div, point, prelude::*, px, svg, + Anchor, AnyElement, AnyView, App, Context, Div, ElementId, FontWeight, Hsla, IntoElement, MouseButton, ParentElement, SharedString, + Stateful, Styled, Svg, Window, anchored, deferred, div, point, prelude::*, px, svg, }; use crate::icons::Icon; @@ -8,20 +9,88 @@ use crate::palette::Palette; pub const MONO: &str = "Consolas"; +#[derive(Clone, Copy, PartialEq, Eq)] +pub enum Tone { + Primary, + Secondary, + Ghost, + Danger, +} + pub fn icon(name: Icon, size: f32, color: Hsla) -> Svg { svg().path(name.path()).flex_shrink_0().size(px(size)).text_color(color) } -pub fn page(id: &'static str) -> Stateful
{ - div().id(id).size_full().overflow_y_scroll() +pub fn tip(text: impl Into) -> impl Fn(&mut Window, &mut App) -> AnyView + 'static { + let text = text.into(); + move |window, cx| Tooltip::new(text.clone()).build(window, cx) +} + +pub fn button(id: impl Into, label: impl Into, tone: Tone, p: Palette) -> Stateful
{ + let base = div() + .id(id) + .flex() + .flex_shrink_0() + .items_center() + .justify_center() + .gap(px(6.)) + .h(px(30.)) + .px(px(12.)) + .rounded(px(8.)) + .text_size(px(13.)) + .cursor_pointer() + .child(label.into()); + match tone { + Tone::Primary => base.bg(p.accent).text_color(p.accent_text).font_weight(FontWeight::SEMIBOLD).hover(|style| style.opacity(0.9)), + Tone::Secondary => base.border_1().border_color(p.border).text_color(p.text).hover(move |style| style.bg(p.row_hover)), + Tone::Ghost => base.text_color(p.text_muted).hover(move |style| style.bg(p.row_hover).text_color(p.text)), + Tone::Danger => base.bg(p.danger.opacity(0.14)).text_color(p.danger).hover(move |style| style.bg(p.danger.opacity(0.22))), + } +} + +pub fn icon_button(id: impl Into, name: Icon, label: &'static str, p: Palette) -> Stateful
{ + div() + .id(id) + .flex() + .flex_shrink_0() + .items_center() + .justify_center() + .size(px(30.)) + .rounded(px(8.)) + .cursor_pointer() + .hover(move |style| style.bg(p.row_hover)) + .tooltip(tip(label)) + .child(icon(name, 16., p.text_muted)) +} + +pub fn kbd(text: impl Into, p: Palette) -> Div { + div() + .flex_shrink_0() + .px(px(5.)) + .h(px(18.)) + .flex() + .items_center() + .rounded(px(5.)) + .border_1() + .border_color(p.border) + .text_size(px(11.)) + .text_color(p.text_faint) + .child(text.into()) } pub fn menu_panel(p: Palette) -> Div { - div().occlude().p(px(5.)).rounded(px(12.)).bg(p.menu_bg).border_1().border_color(p.border).shadow_lg().flex().flex_col().gap(px(1.)) + div().occlude().p(px(6.)).rounded(px(14.)).bg(p.menu_bg).border_1().border_color(p.border).shadow_lg().flex().flex_col().gap(px(2.)) } pub fn menu_label(text: impl Into, p: Palette) -> Div { - div().px(px(10.)).pt(px(6.)).pb(px(4.)).text_size(px(12.)).text_color(p.text_faint).child(text.into()) + div() + .px(px(10.)) + .pt(px(6.)) + .pb(px(4.)) + .text_size(px(11.5)) + .font_weight(FontWeight::SEMIBOLD) + .text_color(p.text_faint) + .child(text.into()) } pub fn menu_item( @@ -39,11 +108,12 @@ pub fn menu_item( .gap(px(10.)) .px(px(10.)) .py(px(if detail.is_some() { 7. } else { 6. })) - .rounded(px(8.)) + .rounded(px(9.)) .text_color(p.text) .cursor_pointer() - .hover(move |style| style.bg(p.row_hover)) - .when_some(name, |row, name| row.child(icon(name, 15., p.text_muted))) + .when(checked, |row| row.bg(p.accent_soft)) + .hover(move |style| style.bg(if checked { p.accent_soft } else { p.row_hover })) + .when_some(name, |row, name| row.child(icon(name, 15., if checked { p.accent } else { p.text_muted }))) .child( div() .flex_1() @@ -53,7 +123,7 @@ pub fn menu_item( .child(div().text_size(px(13.5)).child(label.into())) .when_some(detail, |col, detail| col.child(div().text_size(px(12.)).text_color(p.text_faint).child(detail))), ) - .when(checked, |row| row.child(icon(Icon::Check, 15., p.text))) + .when(checked, |row| row.child(icon(Icon::Check, 15., p.accent))) } pub fn separator(p: Palette) -> Div { @@ -74,6 +144,7 @@ pub fn popup( }; let top = matches!(anchor, Anchor::TopLeft | Anchor::TopRight); let right = matches!(anchor, Anchor::TopRight | Anchor::BottomRight); + let menu = crate::motion::pop("popup-menu", div().child(menu), !top, cx); div() .absolute() .top_0() @@ -112,9 +183,9 @@ pub fn badge(name: &str, size: f32) -> Div { .items_center() .justify_center() .size(px(size)) - .rounded(px(size * 0.28)) + .rounded(px(size * 0.3)) .bg(crate::project::color(name)) - .text_size(px(size * 0.5)) + .text_size(px(size * 0.46)) .font_weight(FontWeight::SEMIBOLD) .text_color(gpui_kit::white()) .child(crate::project::initials(name)) diff --git a/crates/quill-code/src/usage.rs b/crates/quill-code/src/usage.rs new file mode 100644 index 0000000..16c03bb --- /dev/null +++ b/crates/quill-code/src/usage.rs @@ -0,0 +1,264 @@ +use std::collections::HashMap; +use std::fs; +use std::io::Write; +use std::path::PathBuf; + +use gpui_kit::{ + Context, Div, Entity, FontWeight, IntoElement, ParentElement, Render, SharedString, Styled, Subscription, Window, div, prelude::*, px, +}; +use quill_config::claude_latest; +use quill_providers::Tokens; +use serde::{Deserialize, Serialize}; + +use crate::backend::claude_label; +use crate::config::app_dir; +use crate::icons::Icon; +use crate::palette::{Palette, palette}; +use crate::thread::{Thread, Turn, now_ms}; +use crate::ui::icon; +use crate::workspace::Workspace; + +const DAY: u64 = 24 * 60 * 60 * 1000; + +#[derive(Clone, Serialize, Deserialize)] +pub struct Record { + pub at: u64, + pub thread: u64, + pub provider: String, + pub model: String, + pub tokens: Tokens, + pub cost: Option, +} + +fn ledger_path() -> PathBuf { + app_dir().join("usage.jsonl") +} + +pub fn load(threads: &[Thread]) -> Vec { + if let Ok(text) = fs::read_to_string(ledger_path()) { + return text.lines().filter_map(|line| serde_json::from_str(line).ok()).collect(); + } + let mut records: Vec = + threads + .iter() + .flat_map(|thread| { + thread.turns.iter().filter(|turn| !turn.working()).filter_map(|turn| { + record(thread.id, thread.provider.as_deref(), turn).map(|record| Record { at: turn.started, ..record }) + }) + }) + .collect(); + records.sort_by_key(|record| record.at); + records.iter().for_each(append); + records +} + +pub fn append(record: &Record) { + let Ok(line) = serde_json::to_string(record) else { return }; + let _ = fs::create_dir_all(app_dir()); + if let Ok(mut file) = fs::OpenOptions::new().create(true).append(true).open(ledger_path()) { + let _ = writeln!(file, "{line}"); + } +} + +pub fn record(thread: u64, provider: Option<&str>, turn: &Turn) -> Option { + (turn.usage.total() > 0 || turn.cost.is_some()).then(|| Record { + at: now_ms(), + thread, + provider: provider.unwrap_or_default().to_string(), + model: turn.model.clone().unwrap_or_default(), + tokens: turn.usage, + cost: turn.cost, + }) +} + +pub fn money(usd: f64) -> String { + if usd == 0.0 { + "$0".into() + } else if usd < 0.01 { + format!("${usd:.4}") + } else { + format!("${usd:.2}") + } +} + +pub fn count(tokens: u64) -> String { + match tokens { + 0..1000 => tokens.to_string(), + 1000..1_000_000 => format!("{:.1}K", tokens as f64 / 1000.0), + _ => format!("{:.2}M", tokens as f64 / 1_000_000.0), + } +} + +#[derive(Default, Clone, Copy)] +struct Sum { + tokens: Tokens, + cost: f64, + priced: bool, + turns: usize, +} + +impl Sum { + fn add(&mut self, tokens: Tokens, cost: Option) { + self.tokens.add(tokens); + self.cost += cost.unwrap_or(0.0); + self.priced |= cost.is_some(); + self.turns += 1; + } +} + +pub struct UsageView { + workspace: Entity, + _subscription: Subscription, +} + +impl UsageView { + pub fn new(workspace: Entity, cx: &mut Context) -> Self { + let subscription = cx.observe(&workspace, |_, _, cx| cx.notify()); + UsageView { workspace, _subscription: subscription } + } +} + +fn section(title: &'static str, p: Palette) -> Div { + div().pt(px(14.)).pb(px(8.)).text_size(px(12.)).font_weight(FontWeight::SEMIBOLD).text_color(p.text_faint).child(title) +} + +fn model_name(label: &str) -> String { + claude_latest(label).map_or_else(|| label.to_string(), claude_label) +} + +fn tokens_line(tokens: Tokens) -> String { + if tokens.total() == 0 { + return String::new(); + } + let mut line = format!("{} in", count(tokens.prompt)); + if tokens.cache_read > 0 { + line.push_str(&format!(" ({} cached)", count(tokens.cache_read))); + } + line.push_str(&format!(" · {} out", count(tokens.completion))); + line +} + +fn cost_text(sum: &Sum) -> String { + if sum.priced { money(sum.cost) } else { "Free".into() } +} + +fn tile(label: &'static str, sum: Sum, p: Palette) -> Div { + div() + .flex_1() + .min_w(px(120.)) + .flex() + .flex_col() + .gap(px(2.)) + .p(px(10.)) + .rounded(px(10.)) + .bg(p.fill) + .child(div().text_size(px(12.)).text_color(p.text_faint).child(label)) + .child(div().text_size(px(17.)).font_weight(FontWeight::SEMIBOLD).text_color(p.text).child(money(sum.cost))) + .child(div().text_size(px(11.5)).text_color(p.text_faint).child(format!("{} tokens", count(sum.tokens.total())))) +} + +fn row(left: String, middle: String, right: String, p: Palette) -> Div { + div() + .flex() + .items_center() + .gap(px(10.)) + .py(px(6.)) + .border_b_1() + .border_color(p.border_soft) + .text_size(px(12.5)) + .child(div().flex_1().min_w_0().text_ellipsis().whitespace_nowrap().overflow_hidden().text_color(p.text).child(left)) + .child(div().flex_shrink_0().text_color(p.text_faint).child(middle)) + .child(div().w(px(64.)).flex_shrink_0().flex().justify_end().text_color(p.text_muted).child(right)) +} + +impl Render for UsageView { + fn render(&mut self, _: &mut Window, cx: &mut Context) -> impl IntoElement { + let p = palette(cx); + let workspace = self.workspace.read(cx); + let mut body = div().id("usage-body").size_full().overflow_y_scroll().px(px(16.)).pb(px(20.)).flex().flex_col(); + match workspace.active_thread() { + Some(thread) => { + let mut total = Sum::default(); + for turn in &thread.turns { + total.add(turn.usage, turn.cost); + } + body = body.child(section("This chat", p)).child( + div() + .flex() + .items_end() + .gap(px(10.)) + .child(div().text_size(px(26.)).font_weight(FontWeight::SEMIBOLD).text_color(p.text).child(cost_text(&total))) + .child(div().pb(px(5.)).text_size(px(12.5)).text_color(p.text_faint).child(tokens_line(total.tokens))), + ); + for (index, turn) in thread.turns.iter().enumerate().filter(|(_, t)| t.usage.total() > 0 || t.cost.is_some()) { + let model = model_name(turn.model.as_deref().unwrap_or_default()); + let cost = turn.cost.map_or_else(|| "Free".to_string(), money); + body = body.child(row(format!("{}. {model}", index + 1), tokens_line(turn.usage), cost, p)); + } + } + None => { + body = body + .child(section("This chat", p)) + .child(div().text_size(px(13.)).text_color(p.text_faint).child("Open a thread to see what it has used.")); + } + } + let now = now_ms(); + let mut windows = [Sum::default(); 4]; + let mut models: HashMap = HashMap::new(); + for record in &workspace.usage { + for (sum, days) in windows.iter_mut().zip([1, 7, 30, u64::MAX / DAY]) { + if now.saturating_sub(record.at) < days.saturating_mul(DAY) { + sum.add(record.tokens, record.cost); + } + } + models.entry(model_name(&record.model)).or_default().add(record.tokens, record.cost); + } + let [day, week, month, all] = windows; + body = body.child(section("Everything", p)).child( + div() + .flex() + .flex_wrap() + .gap(px(8.)) + .child(tile("Today", day, p)) + .child(tile("Past 7 days", week, p)) + .child(tile("Past 30 days", month, p)) + .child(tile("All time", all, p)), + ); + let mut models: Vec<(String, Sum)> = models.into_iter().collect(); + models.sort_by(|a, b| b.1.cost.total_cmp(&a.1.cost).then(b.1.tokens.total().cmp(&a.1.tokens.total()))); + if !models.is_empty() { + body = body.child(section("By model", p)); + for (model, sum) in models { + let turns = format!("{} {}", sum.turns, if sum.turns == 1 { "turn" } else { "turns" }); + body = body.child(row(model, format!("{turns} · {} tokens", count(sum.tokens.total())), cost_text(&sum), p)); + } + } + body.child( + div() + .pt(px(14.)) + .flex() + .items_start() + .gap(px(6.)) + .text_size(px(11.5)) + .text_color(p.text_faint) + .child(div().mt(px(2.)).child(icon(Icon::Info, 12., p.text_faint))) + .child(div().flex_1().min_w_0().child(SharedString::from( + "Claude Code reports its own cost. Anthropic API costs are worked out from Anthropic's published prices, cache included; set a price for any other model in Settings, Models. Local models are free.", + ))), + ) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn amounts_read_naturally() { + assert_eq!(money(0.0023), "$0.0023"); + assert_eq!(money(1.5), "$1.50"); + assert_eq!(count(950), "950"); + assert_eq!(count(52_300), "52.3K"); + assert_eq!(count(2_500_000), "2.50M"); + } +} \ No newline at end of file diff --git a/crates/quill-code/src/weave.rs b/crates/quill-code/src/weave.rs index 53604da..791ca4a 100644 --- a/crates/quill-code/src/weave.rs +++ b/crates/quill-code/src/weave.rs @@ -111,10 +111,4 @@ fn paint(bounds: Bounds, params: &Params, clock: &Clock, poke: f64, opac let bounds = Bounds::new(point(px(x as f32), px(y as f32)), size(px((r * 2.0) as f32), px((r * 2.0) as f32))); window.paint_quad(fill(bounds, color.opacity(alpha)).corner_radii(px(r as f32))); } -} - -pub fn model_mark(model: &str, side: f32, color: Hsla) -> impl IntoElement + use<> { - let clock = Clock::seeded(name_hash(model) as u64); - let params = State::Idle.params(); - canvas(|_, _, _| (), move |bounds, _, window, _| paint(bounds, ¶ms, &clock, 0.0, 1.0, color, window)).size(px(side)).flex_shrink_0() } \ No newline at end of file diff --git a/crates/quill-code/src/workspace.rs b/crates/quill-code/src/workspace.rs index 648222c..6fee254 100644 --- a/crates/quill-code/src/workspace.rs +++ b/crates/quill-code/src/workspace.rs @@ -1,24 +1,23 @@ use std::collections::HashMap; -use std::path::PathBuf; +use std::path::{Path, PathBuf}; use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::mpsc::Sender; use std::time::Duration; use futures::StreamExt; -use gpui_kit::{Context, Entity, Task as GpuiTask}; -use quill_agent::{AgentEvent, Approval, Decision, Publisher, Task, system_prompt}; -use quill_llama::Message; +use gpui_kit::{App, Context, Entity, Task as GpuiTask}; +use quill_config::ModelRef; +use quill_core::{Approval, Decision, Engine, Event, Input, Op, Outcome, SessionHandle, Summarizer, Toolsets, TurnContext, spawn}; use crate::attachments::{self, Attachment}; use crate::backend::Backend; -use crate::config::worktrees_dir; use crate::config::{Config, read_personal_instructions}; -use crate::git; use crate::mentions::mentioned; -use crate::publish::GitPublisher; use crate::store; -use crate::thread::{Item, Thread, ToolItem, ToolStatus, Turn, TurnState, now_ms, repair_history}; +use crate::thread::{Item, Thread, ToolItem, ToolStatus, Turn, TurnState, now_ms}; +use crate::usage; + +const MAX_LIVE_OUTPUT: usize = 200_000; #[derive(Clone)] pub struct Prompt { @@ -26,28 +25,30 @@ pub struct Prompt { pub attachments: Vec, } -fn isolated_copy(thread: &Thread) -> Result { +fn isolated_copy(thread: &Thread, base: &Path) -> Result { let project = thread.project.as_ref().ok_or("An isolated copy needs a project.")?; - let path = worktrees_dir().join(format!("{}-{}", crate::project::name(project), thread.id)); - git::add_worktree(project, &path)?; + let path = base.join(format!("{}-{}", crate::project::name(project), thread.id)); + quill_git::add_worktree(project, &path)?; Ok(path) } -enum Update { - Event(AgentEvent), - Finished(Result<(), String>), -} - pub struct Pending { - pub tool_id: String, + pub id: String, + pub tool: String, pub approval: Approval, - reply: Sender, +} + +pub struct Asked { + pub id: String, + pub question: String, + pub options: Vec, } struct Run { turn: usize, cancel: Arc, pending: Option, + asked: Option, } pub struct Workspace { @@ -55,21 +56,27 @@ pub struct Workspace { pub active: Option, pub draft_project: Option, pub draft_isolated: bool, + sessions: HashMap, runs: HashMap, backend: Entity, ticker: Option>, + pub usage: Vec, } impl Workspace { pub fn new(backend: Entity) -> Self { + let threads = store::load_threads(); + let usage = usage::load(&threads); Workspace { - threads: store::load_threads(), + threads, active: None, draft_project: None, draft_isolated: false, + sessions: HashMap::new(), runs: HashMap::new(), backend, ticker: None, + usage, } } @@ -113,7 +120,7 @@ impl Workspace { self.stop(id, cx); let thread = self.thread_mut(id).ok_or("That thread no longer exists.")?; let (Some(project), Some(worktree)) = (thread.project.clone(), thread.worktree.clone()) else { return Ok(()) }; - git::remove_worktree(&project, &worktree)?; + quill_git::remove_worktree(&project, &worktree)?; thread.worktree = None; store::save(thread); cx.notify(); @@ -132,6 +139,14 @@ impl Workspace { self.runs.get(&id).and_then(|run| run.pending.as_ref()) } + pub fn asked(&self, id: u64) -> Option<&Asked> { + self.runs.get(&id).and_then(|run| run.asked.as_ref()) + } + + pub fn waiting(&self, id: u64) -> bool { + self.runs.get(&id).is_some_and(|run| run.pending.is_some() || run.asked.is_some()) + } + pub fn start_new(&mut self, project: Option, cx: &mut Context) { self.active = None; self.draft_project = project; @@ -154,6 +169,9 @@ impl Workspace { pub fn delete(&mut self, id: u64, cx: &mut Context) { self.stop(id, cx); + if let Some(session) = self.sessions.remove(&id) { + session.send(Op::Shutdown); + } self.threads.retain(|t| t.id != id); store::delete(id); if self.active == Some(id) { @@ -169,9 +187,34 @@ impl Workspace { cx.notify(); } - pub fn toggle_tool(&mut self, id: u64, turn: usize, tool: &str, cx: &mut Context) { - if let Some(tool) = self.thread_mut(id).and_then(|t| t.turns.get_mut(turn)).and_then(|t| t.tool_mut(tool)) { - tool.open = !tool.open; + fn session(&mut self, id: u64, cx: &mut Context) -> SessionHandle { + if let Some(session) = self.sessions.get(&id) { + return session.clone(); + } + let history = self.threads.iter().find(|t| t.id == id).map(|t| t.history.clone()).unwrap_or_default(); + let (tx, mut rx) = futures::channel::mpsc::unbounded(); + let session = spawn(history, move |event| { + let _ = tx.unbounded_send(event); + }); + cx.spawn(async move |this, cx| { + while let Some(event) = rx.next().await { + if this.update(cx, |workspace, cx| workspace.apply(id, event, cx)).is_err() { + break; + } + } + }) + .detach(); + self.sessions.insert(id, session.clone()); + session + } + + fn steer(&mut self, id: u64, text: String, cx: &mut Context) { + let Some(turn) = self.runs.get(&id).map(|run| run.turn) else { return }; + if let Some(turn) = self.thread_mut(id).and_then(|thread| thread.turns.get_mut(turn)) { + turn.items.push(Item::Steer(text.clone())); + } + if let Some(session) = self.sessions.get(&id) { + session.send(Op::Steer(text)); } cx.notify(); } @@ -179,7 +222,7 @@ impl Workspace { pub fn send(&mut self, prompt: Prompt, cx: &mut Context) { let Prompt { text, attachments } = prompt; let id = match self.active { - Some(id) if self.running(id) => return, + Some(id) if self.running(id) => return self.steer(id, text, cx), Some(id) => id, None => { let thread = Thread::new(self.draft_project.take(), &text); @@ -190,12 +233,11 @@ impl Workspace { } }; let isolate = std::mem::take(&mut self.draft_isolated); - let model = Backend::selected_id(cx); - let vision = self.backend.read(cx).selected(cx).is_some_and(|m| m.vision); - let thinking = self.backend.read(cx).request_thinking(cx); - let url = Backend::url(cx); - let access = Config::get(cx).access; - let personal = read_personal_instructions(); + let model = Backend::selected_ref(cx); + let found = model.as_ref().and_then(|model| self.backend.read(cx).effective(model, cx)); + let vision = found.as_ref().is_some_and(|m| m.vision); + let label = found.as_ref().map(|m| m.label().to_string()); + let settings = Config::get(cx).clone(); let Some(thread) = self.thread_mut(id) else { return }; let index = thread.turns.len(); let mut names = Vec::new(); @@ -210,7 +252,7 @@ impl Workspace { turn.images = images; thread.turns.push(turn); thread.updated = now_ms(); - let failure = match (&model, isolate.then(|| isolated_copy(thread)).transpose()) { + let failure = match (&model, isolate.then(|| isolated_copy(thread, &settings.worktrees_dir())).transpose()) { (None, _) => Some("Choose a model from the model menu in the prompt box first.".to_string()), (_, Err(error)) => Some(error), (Some(_), Ok(worktree)) => { @@ -228,9 +270,10 @@ impl Workspace { cx.notify(); return; } - let model = model.unwrap_or_default(); - thread.model = Some(model.clone()); - thread.turns[index].model = Some(model.clone()); + let Some(model) = model else { return }; + thread.model = Some(model.model.clone()); + thread.provider = Some(model.provider.clone()); + thread.turns[index].model = label.or_else(|| Some(model.model.clone())); let root = thread.workdir().filter(|p| p.is_dir()); let mentions: Vec<(String, PathBuf)> = match &root { Some(root) => mentioned(&text) @@ -246,44 +289,84 @@ impl Workspace { if !prepared.skipped.is_empty() { content.push_str(&format!("\n\n(Not attached: {}.)", prepared.skipped.join(", "))); } - thread.history.push(Message::user_with_images(content, prepared.images)); - let publisher: Option> = - root.as_deref().filter(|root| git::snapshot(root).is_some()).map(|_| Arc::new(GitPublisher) as Arc); - let task = Task { - server_url: url, - system: system_prompt(&model, root.as_deref(), publisher.is_some(), &personal), - model: model.clone(), - thinking, - root, - access, - history: thread.history.clone(), - publisher, - }; store::save(thread); - self.backend.update(cx, |backend, cx| backend.mark_used(&model, cx)); - let cancel = Arc::new(AtomicBool::new(false)); - self.runs.insert(id, Run { turn: index, cancel: cancel.clone(), pending: None }); - let (tx, mut rx) = futures::channel::mpsc::unbounded(); - cx.background_executor() - .spawn(async move { - let result = quill_agent::run(task, &cancel, |event| { - let _ = tx.unbounded_send(Update::Event(event)); - }); - let _ = tx.unbounded_send(Update::Finished(result.map_err(|e| e.to_string()))); - }) - .detach(); - cx.spawn(async move |this, cx| { - while let Some(update) = rx.next().await { - if this.update(cx, |workspace, cx| workspace.apply(id, index, update, cx)).is_err() { - break; + let context = match self.threads.iter().find(|t| t.id == id).map(|thread| self.context(&model, thread, cx)) { + Some(Ok(context)) => context, + Some(Err(error)) => { + if let Some(thread) = self.thread_mut(id) { + if let Some(turn) = thread.turns.last_mut() { + turn.finish(TurnState::Failed(error)); + } + store::save(thread); } + cx.notify(); + return; } - }) - .detach(); + None => return, + }; + self.backend.update(cx, |backend, cx| backend.mark_used(&model, cx)); + let cancel = Arc::new(AtomicBool::new(false)); + self.runs.insert(id, Run { turn: index, cancel: cancel.clone(), pending: None, asked: None }); + let session = self.session(id, cx); + session.send(Op::Turn { turn: index, input: Input { text: content, images: prepared.images }, context, cancel }); self.ensure_ticker(cx); cx.notify(); } + fn context(&self, model: &ModelRef, thread: &Thread, cx: &App) -> Result { + let backend = self.backend.read(cx); + let mut engine = backend.engine(model)?; + if let Engine::ClaudeCode(claude) = &mut engine { + claude.resume = thread.claude.clone(); + } + let found = backend.effective(model, cx); + let root = thread.workdir().filter(|p| p.is_dir()); + let settings = Config::get(cx).for_project(root.as_deref()); + let git = settings.tools.git && root.as_deref().is_some_and(|root| quill_git::snapshot(root).is_some()); + let summarizer = + settings.models.roles.compaction.as_ref().filter(|role| *role != model).and_then(|role| match backend.engine(role) { + Ok(Engine::Model(provider)) => Some(Summarizer { provider, model: role.model.clone() }), + _ => None, + }); + Ok(TurnContext { + engine, + model: model.model.clone(), + summarizer, + thinking: backend.request_thinking(cx), + effort: backend.request_effort(cx), + max_output: settings.models.override_for(model).and_then(|o| o.max_output), + server_compaction: found.as_ref().is_some_and(|m| m.server_compaction), + context_window: found.and_then(|m| m.context).or(thread.context_window), + root, + access: settings.agent.access, + toolsets: Toolsets { git }, + personal: read_personal_instructions(), + instructions: settings.agent.instruction_files.clone(), + limits: settings.limits(), + rules: settings.permissions.rules.clone(), + }) + } + + pub fn compact(&mut self, id: u64, cx: &mut Context) { + if self.running(id) { + return; + } + let Some(model) = Backend::selected_ref(cx) else { return }; + let Some(thread) = self.threads.iter().find(|t| t.id == id).filter(|t| !t.history.is_empty()) else { return }; + let Ok(context) = self.context(&model, thread, cx) else { return }; + let session = self.session(id, cx); + session.send(Op::Compact { context, cancel: Arc::default() }); + } + + pub fn retry(&mut self, id: u64, turn: usize, cx: &mut Context) { + if self.running(id) { + return; + } + let Some(text) = self.threads.iter().find(|t| t.id == id).and_then(|t| t.turns.get(turn)).map(|t| t.prompt.clone()) else { return }; + self.active = Some(id); + self.send(Prompt { text, attachments: Vec::new() }, cx); + } + fn ensure_ticker(&mut self, cx: &mut Context) { if self.ticker.is_some() { return; @@ -308,62 +391,111 @@ impl Workspace { })); } - fn apply(&mut self, id: u64, index: usize, update: Update, cx: &mut Context) { - if self.runs.get(&id).is_none_or(|run| run.turn != index) { - return; - } + fn apply(&mut self, id: u64, event: Event, cx: &mut Context) { let Some(thread) = self.threads.iter_mut().find(|t| t.id == id) else { return }; - if let Update::Event(AgentEvent::Usage { prompt, completion }) = update { - thread.context_used = Some(prompt + completion); - cx.notify(); + match event { + Event::Message { message } => { + thread.history.push(message); + return; + } + Event::ClaudeSession { link } => { + thread.claude = Some(link); + return; + } + Event::ContextWindow { tokens } => { + thread.context_window = Some(tokens); + if let (Some(provider), Some(model)) = (thread.provider.clone(), thread.model.clone()) { + self.backend.update(cx, |backend, cx| backend.learn_window(&ModelRef::new(provider, model), tokens, cx)); + } + cx.notify(); + return; + } + Event::Compacted { history } => { + thread.history = history; + let index = self.runs.get(&id).map(|run| run.turn).or(thread.turns.len().checked_sub(1)); + if let Some(turn) = index.and_then(|index| thread.turns.get_mut(index)) { + turn.items.push(Item::Note("Earlier conversation was summarised to make room.".into())); + } + store::save(thread); + cx.notify(); + return; + } + _ => {} + } + let Some(run) = self.runs.get_mut(&id) else { return }; + if event_turn(&event) != Some(run.turn) { return; } - let Some(turn) = thread.turns.get_mut(index) else { return }; - match update { - Update::Event(AgentEvent::Reasoning(text)) => turn.push_reasoning(&text), - Update::Event(AgentEvent::Text(text)) => turn.push_text(&text), - Update::Event(AgentEvent::StepDone) | Update::Event(AgentEvent::Usage { .. }) => {} - Update::Event(AgentEvent::ToolStarted { id: tool_id, kind, target }) => { - turn.items.push(Item::Tool(ToolItem { - id: tool_id, - kind, - target, - status: ToolStatus::Running, - output: String::new(), - diff: None, - open: false, - })); + let Some(turn) = thread.turns.get_mut(run.turn) else { return }; + match event { + Event::Reasoning { text, .. } => turn.push_reasoning(&text), + Event::Text { text, .. } => turn.push_text(&text), + Event::ToolBegin { view, .. } => turn.items.push(Item::Tool(ToolItem::new(view))), + Event::ToolOutput { id: tool_id, chunk, .. } => { + if let Some(tool) = turn.tool_mut(&tool_id) + && tool.output.len() < MAX_LIVE_OUTPUT + { + tool.output.push_str(&chunk); + } } - Update::Event(AgentEvent::ToolFinished { id: tool_id, ok, output, diff }) => { + Event::ToolEnd { id: tool_id, ok, output, diffs, image, .. } => { if let Some(tool) = turn.tool_mut(&tool_id) { tool.status = if ok { ToolStatus::Done } else { ToolStatus::Failed }; tool.output = output; - tool.diff = diff; + tool.diffs = diffs; + tool.image = image; + tool.ended = Some(now_ms()); } - if let Some(run) = self.runs.get_mut(&id) { + if run.pending.as_ref().is_some_and(|pending| pending.id == tool_id) { run.pending = None; } } - Update::Event(AgentEvent::NeedsApproval { id: tool_id, approval, reply }) => { - if let Some(tool) = turn.tool_mut(&tool_id) { - tool.status = ToolStatus::Waiting; + Event::ApprovalRequested { id: tool_id, approval, .. } => { + let tool = match turn.tool_mut(&tool_id) { + Some(tool) => { + tool.status = ToolStatus::Waiting; + tool.tool.clone() + } + None => String::new(), + }; + run.pending = Some(Pending { id: tool_id, tool, approval }); + } + Event::QuestionAsked { id: tool_id, question, options, .. } => { + turn.items.push(Item::Question { id: tool_id.clone(), question: question.clone(), options: options.clone(), answer: None }); + run.asked = Some(Asked { id: tool_id, question, options }); + } + Event::PlanUpdated { steps, explanation, .. } => turn.set_plan(steps, explanation), + Event::Usage { tokens, .. } => { + thread.context_used = Some(tokens.total()); + turn.usage.add(tokens); + let model = thread.provider.clone().zip(thread.model.clone()).map(|(provider, model)| ModelRef::new(provider, model)); + if let Some(price) = model.and_then(|model| self.backend.read(cx).price(&model, cx)) { + turn.cost = Some(turn.cost.unwrap_or(0.0) + price.cost(tokens)); } - if let Some(run) = self.runs.get_mut(&id) { - run.pending = Some(Pending { tool_id, approval, reply }); + } + Event::Cost { usd, .. } => turn.cost = Some(turn.cost.unwrap_or(0.0) + usd), + Event::ModelResolved { model, .. } => { + turn.model = Some(crate::backend::claude_label(&model)); + if let (Some(provider), Some(alias)) = (thread.provider.clone(), thread.model.clone()) { + self.backend.update(cx, |backend, cx| backend.learn_model(&ModelRef::new(provider, alias), &model, cx)); } } - Update::Event(AgentEvent::Message(message)) => thread.history.push(message), - Update::Finished(result) => { - turn.finish(match result { - Ok(()) => TurnState::Done, - Err(error) => TurnState::Failed(error), + Event::TurnFinished { outcome, .. } => { + turn.finish(match outcome { + Outcome::Done => TurnState::Done, + Outcome::Stopped => TurnState::Stopped, + Outcome::Failed(error) => TurnState::Failed(error), }); + if let Some(record) = usage::record(thread.id, thread.provider.as_deref(), turn) { + usage::append(&record); + self.usage.push(record); + } thread.updated = now_ms(); - repair_history(&mut thread.history); store::save(thread); self.runs.remove(&id); self.backend.update(cx, |backend, cx| backend.refresh(cx)); } + _ => {} } cx.notify(); } @@ -371,25 +503,63 @@ impl Workspace { pub fn stop(&mut self, id: u64, cx: &mut Context) { let Some(run) = self.runs.remove(&id) else { return }; run.cancel.store(true, Ordering::Relaxed); - if let Some(pending) = run.pending { - let _ = pending.reply.send(Decision::Decline); - } - if let Some(thread) = self.thread_mut(id) { + let mut stopped = None; + if let Some(thread) = self.threads.iter_mut().find(|t| t.id == id) { if let Some(turn) = thread.turns.get_mut(run.turn) { turn.finish(TurnState::Stopped); + stopped = usage::record(thread.id, thread.provider.as_deref(), turn); } - repair_history(&mut thread.history); store::save(thread); } + if let Some(record) = stopped { + usage::append(&record); + self.usage.push(record); + } cx.notify(); } pub fn decide(&mut self, id: u64, decision: Decision, cx: &mut Context) { - let Some(pending) = self.runs.get_mut(&id).and_then(|run| run.pending.take()) else { return }; - if let Some(tool) = self.thread_mut(id).and_then(|t| t.turns.last_mut()).and_then(|t| t.tool_mut(&pending.tool_id)) { + let Some(run) = self.runs.get_mut(&id) else { return }; + let Some(pending) = run.pending.take() else { return }; + let turn = run.turn; + if let Some(tool) = self.thread_mut(id).and_then(|t| t.turns.get_mut(turn)).and_then(|t| t.tool_mut(&pending.id)) { tool.status = ToolStatus::Running; } - let _ = pending.reply.send(decision); + if let Some(session) = self.sessions.get(&id) { + session.send(Op::Decide { id: pending.id, decision }); + } cx.notify(); } + + pub fn answer(&mut self, id: u64, text: String, cx: &mut Context) { + let Some(run) = self.runs.get_mut(&id) else { return }; + let Some(asked) = run.asked.take() else { return }; + let turn = run.turn; + if let Some(turn) = self.thread_mut(id).and_then(|t| t.turns.get_mut(turn)) { + turn.answer(&asked.id, &text); + } + if let Some(session) = self.sessions.get(&id) { + session.send(Op::Answer { id: asked.id, text }); + } + cx.notify(); + } +} + +fn event_turn(event: &Event) -> Option { + match event { + Event::TurnStarted { turn } + | Event::Reasoning { turn, .. } + | Event::Text { turn, .. } + | Event::ToolBegin { turn, .. } + | Event::ToolOutput { turn, .. } + | Event::ToolEnd { turn, .. } + | Event::ApprovalRequested { turn, .. } + | Event::QuestionAsked { turn, .. } + | Event::PlanUpdated { turn, .. } + | Event::Usage { turn, .. } + | Event::Cost { turn, .. } + | Event::ModelResolved { turn, .. } + | Event::TurnFinished { turn, .. } => Some(*turn), + Event::Message { .. } | Event::Compacted { .. } | Event::ContextWindow { .. } | Event::ClaudeSession { .. } => None, + } } \ No newline at end of file diff --git a/crates/quill-config/Cargo.toml b/crates/quill-config/Cargo.toml new file mode 100644 index 0000000..496efd5 --- /dev/null +++ b/crates/quill-config/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "quill-config" +version.workspace = true +edition.workspace = true +license.workspace = true +authors.workspace = true +publish.workspace = true + +[dependencies] +keyring = "4.2.0" +quill-core.workspace = true +quill-providers.workspace = true +serde = { version = "1", features = ["derive"] } +serde_json = "1" \ No newline at end of file diff --git a/crates/quill-config/src/lib.rs b/crates/quill-config/src/lib.rs new file mode 100644 index 0000000..95ab1b0 --- /dev/null +++ b/crates/quill-config/src/lib.rs @@ -0,0 +1,403 @@ +mod models; +mod paths; +mod secrets; + +use std::fs; +use std::path::{Path, PathBuf}; + +use quill_core::{Access, Limits, Rule, Shell}; +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +pub use models::{ + DEFAULT_SERVER, LOCAL_PORTS, ModelRef, Models, Override, Price, Provider, ProviderKind, Roles, claude_latest, default_price, + default_providers, +}; +pub use paths::{app_dir, home_dir, personal_instructions_path, read_personal_instructions, write_personal_instructions}; +pub use secrets::{KeySource, api_key, forget_key, key_source, store_key}; + +pub const INSTRUCTION_FILES: [&str; 4] = ["AGENTS.md", "CLAUDE.md", "GEMINI.md", ".github/copilot-instructions.md"]; + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct General { + pub projects: Vec, + pub projects_dir: Option, + pub worktrees_dir: Option, + pub remember_project: bool, + pub last_project: Option, +} + +impl Default for General { + fn default() -> Self { + General { projects: Vec::new(), projects_dir: None, worktrees_dir: None, remember_project: true, last_project: None } + } +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Theme { + #[default] + System, + Dark, + Light, +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Motion { + #[default] + Full, + Reduced, + Off, +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Reasoning { + Expanded, + #[default] + Collapsed, + Hidden, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct Appearance { + pub theme: Theme, + pub motion: Motion, + pub reasoning: Reasoning, + pub transcript_width: u16, + pub sidebar: bool, + pub group_exploration: bool, +} + +impl Default for Appearance { + fn default() -> Self { + Appearance { + theme: Theme::System, + motion: Motion::Full, + reasoning: Reasoning::Collapsed, + transcript_width: 820, + sidebar: true, + group_exploration: true, + } + } +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct Agent { + pub access: Access, + pub max_steps: usize, + pub auto_compact: bool, + pub compact_at: u8, + pub parallel_tools: bool, + pub instruction_files: Vec, +} + +impl Default for Agent { + fn default() -> Self { + let limits = Limits::default(); + Agent { + access: Access::Full, + max_steps: limits.max_steps, + auto_compact: true, + compact_at: (limits.compact_at * 100.0).round() as u8, + parallel_tools: limits.parallel_tools, + instruction_files: INSTRUCTION_FILES.iter().map(|s| s.to_string()).collect(), + } + } +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct Tools { + pub shell: Shell, + pub command_timeout: u64, + pub max_command_timeout: u64, + pub max_output: usize, + pub max_read_lines: usize, + pub max_matches: usize, + pub max_list: usize, + pub ignored: Vec, + pub disabled: Vec, + pub git: bool, +} + +impl Default for Tools { + fn default() -> Self { + let limits = Limits::default(); + Tools { + shell: limits.shell, + command_timeout: limits.command_timeout, + max_command_timeout: limits.max_command_timeout, + max_output: limits.max_output, + max_read_lines: limits.max_read_lines, + max_matches: limits.max_matches, + max_list: limits.max_list, + ignored: limits.ignored, + disabled: Vec::new(), + git: true, + } + } +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct Permissions { + pub rules: Vec, + pub safe_commands: Vec, +} + +impl Default for Permissions { + fn default() -> Self { + Permissions { rules: Vec::new(), safe_commands: Limits::default().safe_commands } + } +} + +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct Settings { + pub general: General, + pub appearance: Appearance, + pub models: Models, + pub agent: Agent, + pub tools: Tools, + pub permissions: Permissions, +} + +#[derive(Deserialize)] +#[serde(default)] +struct Legacy { + server_url: String, + model: Option, + thinking: bool, + #[serde(alias = "mode")] + access: Access, + projects: Vec, + pinned_models: Vec, +} + +impl Default for Legacy { + fn default() -> Self { + Legacy { + server_url: DEFAULT_SERVER.into(), + model: None, + thinking: true, + access: Access::Full, + projects: Vec::new(), + pinned_models: Vec::new(), + } + } +} + +impl From for Settings { + fn from(old: Legacy) -> Settings { + let mut settings = Settings::default(); + settings.models.providers[0].url = old.server_url; + settings.models.selected = old.model.map(|model| ModelRef::new("local", model)); + settings.models.thinking = old.thinking; + settings.models.pinned = old.pinned_models.into_iter().map(|model| ModelRef::new("local", model)).collect(); + settings.agent.access = old.access; + settings.general.projects = old.projects; + settings + } +} + +pub fn settings_path() -> PathBuf { + app_dir().join("settings.json") +} + +pub fn project_settings_path(root: &Path) -> PathBuf { + root.join(".quill").join("settings.json") +} + +pub fn merge(base: &mut Value, over: Value) { + match (base, over) { + (Value::Object(base), Value::Object(over)) => { + for (key, value) in over { + merge(base.entry(key).or_insert(Value::Null), value); + } + } + (slot, value) => *slot = value, + } +} + +pub struct Loaded { + pub settings: Settings, + pub error: Option, +} + +pub fn parse(text: &str) -> Result { + let mut value: Value = serde_json::from_str(text).map_err(|e| format!("settings.json could not be read: {e}"))?; + migrate(&mut value); + serde_json::from_value(value).map_err(|e| format!("settings.json could not be read: {e}")) +} + +fn migrate(value: &mut Value) { + let Some(models) = value.get_mut("models").and_then(Value::as_object_mut) else { return }; + let Some(url) = models.remove("server_url") else { return }; + if !models.contains_key("providers") { + let mut providers = default_providers(); + if let Some(url) = url.as_str() { + providers[0].url = url.to_string(); + } + models.insert("providers".into(), serde_json::to_value(providers).unwrap_or_default()); + } +} + +pub fn load() -> Loaded { + match fs::read_to_string(settings_path()) { + Ok(text) => match parse(&text) { + Ok(settings) => Loaded { settings, error: None }, + Err(error) => Loaded { settings: Settings::default(), error: Some(error) }, + }, + Err(_) => { + let settings = fs::read_to_string(app_dir().join("config.json")) + .ok() + .and_then(|text| serde_json::from_str::(&text).ok()) + .map(Settings::from) + .unwrap_or_default(); + let _ = save(&settings); + Loaded { settings, error: None } + } + } +} + +pub fn save(settings: &Settings) -> std::io::Result<()> { + let text = serde_json::to_string_pretty(settings).map_err(std::io::Error::other)?; + fs::create_dir_all(app_dir())?; + fs::write(settings_path(), text) +} + +impl Settings { + pub fn for_project(&self, root: Option<&Path>) -> Settings { + let Some(text) = root.and_then(|root| fs::read_to_string(project_settings_path(root)).ok()) else { return self.clone() }; + let Ok(over) = serde_json::from_str::(&text) else { return self.clone() }; + let Ok(mut base) = serde_json::to_value(self) else { return self.clone() }; + merge(&mut base, over); + serde_json::from_value(base).unwrap_or_else(|_| self.clone()) + } + + pub fn limits(&self) -> Limits { + Limits { + max_steps: self.agent.max_steps.max(1), + command_timeout: self.tools.command_timeout.max(1), + max_command_timeout: self.tools.max_command_timeout.max(self.tools.command_timeout).max(1), + max_output: self.tools.max_output.max(1000), + max_read_lines: self.tools.max_read_lines.max(10), + max_matches: self.tools.max_matches.max(1), + max_list: self.tools.max_list.max(10), + compact_at: if self.agent.auto_compact { f32::from(self.agent.compact_at.clamp(30, 98)) / 100.0 } else { f32::MAX }, + parallel_tools: self.agent.parallel_tools, + shell: self.tools.shell, + ignored: self.tools.ignored.clone(), + safe_commands: self.permissions.safe_commands.clone(), + disabled_tools: self.tools.disabled.clone(), + } + } + + pub fn projects_dir(&self) -> PathBuf { + self.general.projects_dir.clone().unwrap_or_else(|| home_dir().join(".quill-code").join("projects")) + } + + pub fn worktrees_dir(&self) -> PathBuf { + self.general.worktrees_dir.clone().unwrap_or_else(|| home_dir().join(".quill-code").join("worktrees")) + } + + pub fn add_project(&mut self, path: PathBuf) { + self.general.projects.retain(|p| p != &path); + self.general.projects.insert(0, path); + } + + pub fn value(&self) -> Value { + serde_json::to_value(self).unwrap_or(Value::Null) + } + + pub fn defaults() -> Value { + Settings::default().value() + } +} + +#[cfg(test)] +mod tests { + use super::*; + use quill_core::RuleAction; + use serde_json::json; + + #[test] + fn missing_fields_take_defaults() { + let settings = parse(r#"{ "agent": { "max_steps": 12 } }"#).unwrap(); + assert_eq!(settings.agent.max_steps, 12); + assert_eq!(settings.tools, Tools::default()); + assert_eq!(settings.models.providers[0].url, DEFAULT_SERVER); + assert!(parse("{ broken").is_err()); + } + + #[test] + fn a_single_server_becomes_the_local_provider() { + let settings = parse(r#"{ "models": { "server_url": "http://box:8080", "selected": "qwen", "pinned": ["qwen"] } }"#).unwrap(); + assert_eq!(settings.models.providers.len(), 4); + assert_eq!(settings.models.provider("local").unwrap().url, "http://box:8080"); + assert_eq!(settings.models.selected, Some(ModelRef::new("local", "qwen"))); + assert_eq!(settings.models.pinned, vec![ModelRef::new("local", "qwen")]); + } + + #[test] + fn old_config_files_migrate() { + let old: Legacy = serde_json::from_value(json!({ + "server_url": "http://box:8080", "model": "qwen", "thinking": false, "mode": "manual", + "projects": ["C:\\work\\a"], "pinned_models": ["qwen"] + })) + .unwrap(); + let settings = Settings::from(old); + assert_eq!(settings.models.providers[0].url, "http://box:8080"); + assert_eq!(settings.models.selected, Some(ModelRef::new("local", "qwen"))); + assert!(!settings.models.thinking); + assert_eq!(settings.agent.access, Access::Supervised); + assert_eq!(settings.general.projects, vec![PathBuf::from("C:\\work\\a")]); + assert_eq!(settings.models.pinned, vec![ModelRef::new("local", "qwen")]); + } + + #[test] + fn objects_merge_and_values_replace() { + let mut base = json!({ "agent": { "max_steps": 100, "access": "full" }, "tools": { "ignored": ["a", "b"] } }); + merge(&mut base, json!({ "agent": { "access": "supervised" }, "tools": { "ignored": ["c"] } })); + assert_eq!(base, json!({ "agent": { "max_steps": 100, "access": "supervised" }, "tools": { "ignored": ["c"] } })); + } + + #[test] + fn projects_can_override_their_own_settings() { + let root = std::env::temp_dir().join(format!("quill-config-{}", std::process::id())); + let _ = fs::remove_dir_all(&root); + fs::create_dir_all(root.join(".quill")).unwrap(); + fs::write( + project_settings_path(&root), + r#"{ "agent": { "access": "supervised" }, "permissions": { "rules": [{ "tool": "shell", "pattern": "npm test", "action": "allow" }] } }"#, + ) + .unwrap(); + let user = Settings { agent: Agent { max_steps: 7, ..Agent::default() }, ..Settings::default() }; + let effective = user.for_project(Some(&root)); + assert_eq!(effective.agent.access, Access::Supervised); + assert_eq!(effective.agent.max_steps, 7); + assert_eq!(effective.permissions.rules[0].action, RuleAction::Allow); + assert_eq!(user.for_project(None), user); + fs::remove_dir_all(&root).unwrap(); + } + + #[test] + fn limits_follow_the_settings() { + let mut settings = Settings::default(); + settings.tools.shell = Shell::Cmd; + settings.tools.disabled = vec!["shell".into()]; + settings.agent.compact_at = 70; + let limits = settings.limits(); + assert_eq!(limits.shell, Shell::Cmd); + assert_eq!(limits.disabled_tools, vec!["shell".to_string()]); + assert!((limits.compact_at - 0.7).abs() < 0.001); + settings.agent.auto_compact = false; + assert_eq!(settings.limits().compact_at, f32::MAX); + assert_eq!(Settings::default().limits(), Limits::default()); + } +} \ No newline at end of file diff --git a/crates/quill-config/src/models.rs b/crates/quill-config/src/models.rs new file mode 100644 index 0000000..9af9a39 --- /dev/null +++ b/crates/quill-config/src/models.rs @@ -0,0 +1,304 @@ +use quill_providers::{ANTHROPIC_URL, Effort, OPENAI_URL, Tokens, normalize_url}; +use serde::{Deserialize, Serialize}; + +pub const DEFAULT_SERVER: &str = "http://127.0.0.1:9931"; +pub const LOCAL_PORTS: [u16; 6] = [9931, 8080, 1234, 11434, 8000, 5000]; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ProviderKind { + #[default] + Local, + OpenAi, + Anthropic, + ClaudeCode, +} + +impl ProviderKind { + pub const ALL: [ProviderKind; 4] = [ProviderKind::Local, ProviderKind::OpenAi, ProviderKind::Anthropic, ProviderKind::ClaudeCode]; + + pub fn label(self) -> &'static str { + match self { + ProviderKind::Local => "Local server", + ProviderKind::OpenAi => "OpenAI-compatible", + ProviderKind::Anthropic => "Anthropic", + ProviderKind::ClaudeCode => "Claude Code", + } + } + + pub fn description(self) -> &'static str { + match self { + ProviderKind::Local => "llama.cpp, LM Studio, Ollama, vLLM or anything with an OpenAI-style API on your network", + ProviderKind::OpenAi => "OpenAI or a hosted OpenAI-style service such as OpenRouter, with an API key", + ProviderKind::Anthropic => "Claude models through the Anthropic API, with an API key", + ProviderKind::ClaudeCode => "Claude models through your installed Claude Code and its sign-in, no key needed", + } + } + + pub fn needs_key(self) -> bool { + matches!(self, ProviderKind::OpenAi | ProviderKind::Anthropic) + } + + pub fn default_url(self) -> &'static str { + match self { + ProviderKind::Local => DEFAULT_SERVER, + ProviderKind::OpenAi => OPENAI_URL, + ProviderKind::Anthropic => ANTHROPIC_URL, + ProviderKind::ClaudeCode => "", + } + } + + pub fn env_key(self) -> Option<&'static str> { + match self { + ProviderKind::OpenAi => Some("OPENAI_API_KEY"), + ProviderKind::Anthropic => Some("ANTHROPIC_API_KEY"), + _ => None, + } + } +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct Provider { + pub id: String, + pub name: String, + pub kind: ProviderKind, + pub url: String, + pub enabled: bool, + pub models: Vec, + pub fallback: bool, +} + +impl Default for Provider { + fn default() -> Self { + Provider::new("local", "Local server", ProviderKind::Local) + } +} + +impl Provider { + pub fn new(id: &str, name: &str, kind: ProviderKind) -> Provider { + let models = + if kind == ProviderKind::ClaudeCode { ["fable", "opus", "sonnet", "haiku"].map(String::from).to_vec() } else { Vec::new() }; + Provider { id: id.into(), name: name.into(), kind, url: kind.default_url().into(), enabled: true, models, fallback: true } + } + + pub fn official(&self) -> bool { + self.kind.needs_key() && normalize_url(&self.url) == normalize_url(self.kind.default_url()) + } +} + +pub fn default_providers() -> Vec { + vec![ + Provider::new("local", "Local server", ProviderKind::Local), + Provider::new("claude-code", "Claude Code", ProviderKind::ClaudeCode), + Provider::new("anthropic", "Anthropic", ProviderKind::Anthropic), + Provider::new("openai", "OpenAI", ProviderKind::OpenAi), + ] +} + +#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(from = "RawRef")] +pub struct ModelRef { + pub provider: String, + pub model: String, +} + +#[derive(Deserialize)] +#[serde(untagged)] +enum RawRef { + Legacy(String), + Full { provider: String, model: String }, +} + +impl From for ModelRef { + fn from(raw: RawRef) -> ModelRef { + match raw { + RawRef::Legacy(model) => ModelRef::new("local", model), + RawRef::Full { provider, model } => ModelRef { provider, model }, + } + } +} + +impl ModelRef { + pub fn new(provider: impl Into, model: impl Into) -> ModelRef { + ModelRef { provider: provider.into(), model: model.into() } + } +} + +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct Roles { + pub compaction: Option, + pub commit: Option, + pub subagent: Option, +} + +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +pub struct Price { + pub input: f64, + pub output: f64, + pub cache_read: f64, + pub cache_write: f64, +} + +impl Price { + pub fn new(input: f64, output: f64) -> Price { + Price { input, output, cache_read: input * 0.1, cache_write: input * 1.25 } + } + + pub fn cost(&self, tokens: Tokens) -> f64 { + let fresh = tokens.prompt.saturating_sub(tokens.cache_read + tokens.cache_write) as f64; + let total = fresh * self.input + + tokens.cache_read as f64 * self.cache_read + + tokens.cache_write as f64 * self.cache_write + + tokens.completion as f64 * self.output; + total / 1_000_000.0 + } +} + +const ANTHROPIC_PRICES: [(&str, f64, f64, Option); 11] = [ + ("claude-fable-5-1", 10.0, 50.0, Some(0.25)), + ("claude-mythos-5-1", 10.0, 50.0, Some(0.25)), + ("claude-fable-5", 10.0, 50.0, Some(1.0)), + ("claude-mythos-5", 10.0, 50.0, Some(1.0)), + ("claude-opus-5-5", 4.0, 20.0, Some(0.2)), + ("claude-opus-5", 5.0, 25.0, None), + ("claude-opus-4", 5.0, 25.0, None), + ("claude-sonnet-5", 2.0, 10.0, Some(0.2)), + ("claude-sonnet-4", 3.0, 15.0, None), + ("claude-haiku-5", 0.1, 0.5, None), + ("claude-haiku-4", 1.0, 5.0, None), +]; + +pub fn default_price(model: &str) -> Option { + let (_, input, output, read) = ANTHROPIC_PRICES.iter().find(|(family, ..)| model.starts_with(family))?; + let price = Price::new(*input, *output); + Some(Price { cache_read: read.unwrap_or(price.cache_read), ..price }) +} + +const CLAUDE_LATEST: [(&str, &str); 4] = + [("fable", "claude-fable-5-1"), ("opus", "claude-opus-5-5"), ("sonnet", "claude-sonnet-5-5"), ("haiku", "claude-haiku-5-5")]; + +pub fn claude_latest(alias: &str) -> Option<&'static str> { + CLAUDE_LATEST.iter().find(|(name, _)| *name == alias).map(|(_, id)| *id) +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Override { + pub model: ModelRef, + #[serde(default)] + pub context: Option, + #[serde(default)] + pub max_output: Option, + #[serde(default)] + pub vision: Option, + #[serde(default)] + pub price: Option, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct Models { + pub providers: Vec, + pub selected: Option, + pub pinned: Vec, + pub thinking: bool, + pub effort: Effort, + pub roles: Roles, + pub overrides: Vec, +} + +impl Default for Models { + fn default() -> Self { + Models { + providers: default_providers(), + selected: None, + pinned: Vec::new(), + thinking: true, + effort: Effort::High, + roles: Roles::default(), + overrides: Vec::new(), + } + } +} + +impl Models { + pub fn provider(&self, id: &str) -> Option<&Provider> { + self.providers.iter().find(|provider| provider.id == id) + } + + pub fn override_for(&self, model: &ModelRef) -> Option<&Override> { + self.overrides.iter().find(|entry| entry.model == *model) + } + + pub fn override_mut(&mut self, model: &ModelRef) -> &mut Override { + let index = match self.overrides.iter().position(|entry| entry.model == *model) { + Some(index) => index, + None => { + self.overrides.push(Override { model: model.clone(), context: None, max_output: None, vision: None, price: None }); + self.overrides.len() - 1 + } + }; + &mut self.overrides[index] + } + + pub fn fresh_id(&self, kind: ProviderKind) -> String { + let base = match kind { + ProviderKind::Local => "local", + ProviderKind::OpenAi => "openai", + ProviderKind::Anthropic => "anthropic", + ProviderKind::ClaudeCode => "claude-code", + }; + (1..) + .map(|n| if n == 1 { base.to_string() } else { format!("{base}-{n}") }) + .find(|id| self.provider(id).is_none()) + .unwrap_or_default() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn model_refs_read_old_plain_names() { + let old: ModelRef = serde_json::from_str("\"qwen3.5-4b\"").unwrap(); + assert_eq!(old, ModelRef::new("local", "qwen3.5-4b")); + let new: ModelRef = serde_json::from_str(r#"{ "provider": "openai", "model": "gpt-5" }"#).unwrap(); + assert_eq!(new, ModelRef::new("openai", "gpt-5")); + assert_eq!(serde_json::to_value(&new).unwrap()["provider"], "openai"); + } + + #[test] + fn providers_know_their_defaults() { + let models = Models::default(); + assert_eq!(models.providers.len(), 4); + assert_eq!(models.provider("claude-code").unwrap().models.len(), 4); + assert!(models.provider("anthropic").unwrap().official()); + assert!(!models.provider("local").unwrap().official()); + assert_eq!(models.fresh_id(ProviderKind::Local), "local-2"); + assert_eq!(models.fresh_id(ProviderKind::ClaudeCode), "claude-code-2"); + } + + #[test] + fn prices_follow_the_model_family_and_the_cache() { + let opus = default_price("claude-opus-5-5").unwrap(); + assert_eq!((opus.input, opus.output, opus.cache_read), (4.0, 20.0, 0.2)); + assert_eq!(default_price("claude-opus-5").unwrap().input, 5.0); + assert!(default_price("gpt-5").is_none()); + let tokens = Tokens { prompt: 1_000_000, completion: 100_000, cache_read: 800_000, cache_write: 0 }; + assert!((opus.cost(tokens) - (0.2 * 4.0 + 0.8 * 0.2 + 0.1 * 20.0)).abs() < 1e-9); + assert_eq!(claude_latest("haiku"), Some("claude-haiku-5-5")); + } + + #[test] + fn overrides_are_created_on_demand() { + let mut models = Models::default(); + let model = ModelRef::new("local", "m"); + assert!(models.override_for(&model).is_none()); + models.override_mut(&model).context = Some(8192); + models.override_mut(&model).vision = Some(true); + assert_eq!(models.overrides.len(), 1); + assert_eq!(models.override_for(&model).unwrap().context, Some(8192)); + } +} \ No newline at end of file diff --git a/crates/quill-config/src/paths.rs b/crates/quill-config/src/paths.rs new file mode 100644 index 0000000..95b3afd --- /dev/null +++ b/crates/quill-config/src/paths.rs @@ -0,0 +1,26 @@ +use std::fs; +use std::path::PathBuf; + +pub fn home_dir() -> PathBuf { + std::env::var_os("USERPROFILE").or_else(|| std::env::var_os("HOME")).map(PathBuf::from).unwrap_or_default() +} + +pub fn app_dir() -> PathBuf { + std::env::var_os("APPDATA").map(PathBuf::from).unwrap_or_else(home_dir).join("quill-code") +} + +pub fn personal_instructions_path() -> PathBuf { + home_dir().join(".quill-code").join("AGENTS.md") +} + +pub fn read_personal_instructions() -> String { + fs::read_to_string(personal_instructions_path()).unwrap_or_default() +} + +pub fn write_personal_instructions(text: &str) -> std::io::Result<()> { + let path = personal_instructions_path(); + if let Some(dir) = path.parent() { + fs::create_dir_all(dir)?; + } + fs::write(path, text) +} \ No newline at end of file diff --git a/crates/quill-config/src/secrets.rs b/crates/quill-config/src/secrets.rs new file mode 100644 index 0000000..5875f94 --- /dev/null +++ b/crates/quill-config/src/secrets.rs @@ -0,0 +1,49 @@ +use crate::models::Provider; + +const SERVICE: &str = "quill-code"; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum KeySource { + Stored, + Environment(&'static str), + Missing, +} + +fn entry(id: &str) -> Option { + keyring::Entry::new(SERVICE, id).ok() +} + +fn stored(id: &str) -> Option { + entry(id)?.get_password().ok().filter(|key| !key.trim().is_empty()) +} + +fn environment(provider: &Provider) -> Option<(&'static str, String)> { + let name = provider.kind.env_key().filter(|_| provider.official())?; + std::env::var(name).ok().filter(|key| !key.trim().is_empty()).map(|key| (name, key)) +} + +pub fn api_key(provider: &Provider) -> Option { + stored(&provider.id).or_else(|| environment(provider).map(|(_, key)| key)) +} + +pub fn key_source(provider: &Provider) -> KeySource { + if stored(&provider.id).is_some() { + KeySource::Stored + } else if let Some((name, _)) = environment(provider) { + KeySource::Environment(name) + } else { + KeySource::Missing + } +} + +pub fn store_key(id: &str, key: &str) -> Result<(), String> { + let entry = entry(id).ok_or("Windows Credential Manager is not available.")?; + entry.set_password(key.trim()).map_err(|e| format!("The key could not be saved: {e}")) +} + +pub fn forget_key(id: &str) -> Result<(), String> { + match entry(id).map(|entry| entry.delete_credential()) { + Some(Err(keyring::Error::NoEntry)) | Some(Ok(())) | None => Ok(()), + Some(Err(error)) => Err(format!("The key could not be removed: {error}")), + } +} \ No newline at end of file diff --git a/crates/quill-agent/Cargo.toml b/crates/quill-core/Cargo.toml similarity index 63% rename from crates/quill-agent/Cargo.toml rename to crates/quill-core/Cargo.toml index 3247642..231c6fa 100644 --- a/crates/quill-agent/Cargo.toml +++ b/crates/quill-core/Cargo.toml @@ -1,5 +1,5 @@ [package] -name = "quill-agent" +name = "quill-core" version.workspace = true edition.workspace = true license.workspace = true @@ -7,7 +7,11 @@ authors.workspace = true publish.workspace = true [dependencies] -quill-llama.workspace = true +globset = "0.4.20" +ignore = "0.4.33" +quill-git.workspace = true +quill-providers.workspace = true +regex = "1.13.1" serde = { version = "1", features = ["derive"] } serde_json = "1" similar = "3" \ No newline at end of file diff --git a/crates/quill-core/examples/probe.rs b/crates/quill-core/examples/probe.rs new file mode 100644 index 0000000..b2f5e6f --- /dev/null +++ b/crates/quill-core/examples/probe.rs @@ -0,0 +1,73 @@ +use std::sync::Arc; +use std::sync::mpsc::channel; + +use quill_core::{Access, ClaudeCode, Decision, Engine, Event, Input, Limits, Op, Toolsets, TurnContext, find_claude, spawn}; +use quill_providers::OpenAi; + +fn main() { + let mut args = std::env::args().skip(1); + let url = args.next().unwrap_or_else(|| "http://127.0.0.1:9931".into()); + let model = args.next().unwrap_or_default(); + let prompt = args.next().unwrap_or_else(|| "Create hello.py that prints a greeting, then run it.".into()); + let root = std::env::temp_dir().join("quill-probe"); + std::fs::create_dir_all(&root).expect("probe folder"); + let (tx, rx) = channel(); + let session = spawn(Vec::new(), move |event| { + let _ = tx.send(event); + }); + let engine = if url == "claude" { + Engine::ClaudeCode(ClaudeCode { binary: find_claude(None).expect("Claude Code is not installed"), resume: None }) + } else { + Engine::Model(Arc::new(OpenAi::new(&url))) + }; + let context = TurnContext { + engine, + model, + summarizer: None, + thinking: Some(false), + effort: None, + max_output: None, + server_compaction: false, + context_window: None, + root: Some(root.clone()), + access: Access::Full, + toolsets: Toolsets { git: false }, + personal: String::new(), + instructions: vec!["AGENTS.md".into()], + limits: Limits::default(), + rules: Vec::new(), + }; + println!("working in {}", root.display()); + session.send(Op::Turn { turn: 0, input: Input { text: prompt, images: Vec::new() }, context, cancel: Arc::default() }); + for event in rx { + match event { + Event::Text { text, .. } => print!("{text}"), + Event::ToolBegin { view, .. } => println!("\n[{}] {}", view.tool, view.target), + Event::ToolEnd { ok, output, diffs, .. } => { + println!(" -> {} {} ({} diffs)", if ok { "ok" } else { "failed" }, output.lines().next().unwrap_or_default(), diffs.len()) + } + Event::ApprovalRequested { id, approval, .. } => { + println!("\n approving: {} {}", approval.title, approval.subject); + session.send(Op::Decide { id, decision: Decision::Approve }); + } + Event::QuestionAsked { id, question, options, .. } => { + println!("\n question: {question} {options:?}"); + session.send(Op::Answer { id, text: options.first().cloned().unwrap_or_else(|| "Yes".into()) }); + } + Event::PlanUpdated { steps, .. } => { + for step in steps { + println!(" plan: {:?} {}", step.status, step.text); + } + } + Event::Usage { tokens, .. } => println!("\n usage: {} in, {} out", tokens.prompt, tokens.completion), + Event::Cost { usd, .. } => println!(" cost: ${usd:.4}"), + Event::ContextWindow { tokens } => println!(" window: {tokens}"), + Event::ClaudeSession { link } => println!(" claude session {} at {}", link.session, link.synced), + Event::TurnFinished { outcome, .. } => { + println!("\nresult: {outcome:?}"); + break; + } + _ => {} + } + } +} \ No newline at end of file diff --git a/crates/quill-core/src/claude_code.rs b/crates/quill-core/src/claude_code.rs new file mode 100644 index 0000000..45a33ba --- /dev/null +++ b/crates/quill-core/src/claude_code.rs @@ -0,0 +1,780 @@ +use std::collections::{HashMap, HashSet}; +use std::io::{BufRead, BufReader, Read, Write}; +use std::path::{Path, PathBuf}; +use std::process::{Child, ChildStdin, Command, Stdio}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::mpsc::{Receiver, RecvTimeoutError, channel}; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; + +use quill_providers::{Message, Tokens, ToolCall, image_block}; +use serde_json::{Value, json}; + +use crate::context; +use crate::diff::{FileDiff, diff_text}; +use crate::instructions::project_instructions; +use crate::policy::{Access, Effect}; +use crate::protocol::{Approval, Category, ClaudeLink, Event, Outcome, PlanStep, StepStatus, ToolView}; +use crate::session::{Input, Session, TurnContext}; +use crate::tools::{hide_window, similar}; +use crate::turn::{Request, STOPPED, permit}; + +const HANDOFF: &str = "You are picking up a conversation that started with another model in Quill. Here is what happened so far:"; +const IDENTITY: &str = "You are Quill, the coding agent in the Quill desktop app, running on Claude Code. The user follows your steps in Quill's transcript and answers permission prompts there."; + +#[derive(Debug, Clone, PartialEq)] +pub struct ClaudeCode { + pub binary: PathBuf, + pub resume: Option, +} + +pub fn find_claude(configured: Option<&Path>) -> Option { + if let Some(path) = configured.filter(|path| path.is_file()) { + return Some(path.to_path_buf()); + } + let names: &[&str] = if cfg!(windows) { &["claude.exe", "claude.cmd"] } else { &["claude"] }; + let dirs = std::env::var_os("PATH").map(|path| std::env::split_paths(&path).collect::>()).unwrap_or_default(); + let home = std::env::var_os("USERPROFILE").or_else(|| std::env::var_os("HOME")).map(PathBuf::from).unwrap_or_default(); + dirs.into_iter() + .chain([home.join(".local").join("bin"), home.join(".claude").join("local")]) + .flat_map(|dir| names.iter().map(move |name| dir.join(name))) + .find(|path| path.is_file()) +} + +pub fn claude_version(binary: &Path) -> Option { + let mut command = Command::new(binary); + command.arg("--version").stdin(Stdio::null()).stderr(Stdio::null()); + hide_window(&mut command); + let output = command.output().ok()?; + let text = String::from_utf8_lossy(&output.stdout); + let version = text.split_whitespace().next()?.to_string(); + output.status.success().then_some(version) +} + +pub fn complete(binary: &Path, model: &str, prompt: &str) -> Result { + let mut command = Command::new(binary); + command + .args(["-p", "--output-format", "text", "--max-turns", "1", "--model", model]) + .current_dir(scratch_dir()) + .env_remove("ANTHROPIC_API_KEY") + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()); + hide_window(&mut command); + let mut child = command.spawn().map_err(|e| format!("Claude Code could not start: {e}"))?; + if let Some(mut stdin) = child.stdin.take() { + stdin.write_all(prompt.as_bytes()).map_err(|e| e.to_string())?; + } + let output = child.wait_with_output().map_err(|e| e.to_string())?; + let text = String::from_utf8_lossy(&output.stdout).trim().to_string(); + if output.status.success() && !text.is_empty() { + Ok(text) + } else { + let error = String::from_utf8_lossy(&output.stderr).trim().to_string(); + Err(if error.is_empty() { text } else { error }) + } +} + +pub(crate) struct Process { + child: Child, + stdin: ChildStdin, + lines: Receiver, + errors: Arc>, + key: String, + spent: f64, +} + +enum Next { + Line(String), + Idle, + Closed, +} + +impl Process { + fn start(claude: &ClaudeCode, ctx: &TurnContext, root: &Path, resume: Option<&str>, key: String) -> Result { + let mut command = Command::new(&claude.binary); + command.args([ + "-p", + "--input-format", + "stream-json", + "--output-format", + "stream-json", + "--verbose", + "--include-partial-messages", + "--forward-subagent-text", + "--permission-prompts", + "host", + "--permission-prompt-tool", + "stdio", + ]); + command.arg("--model").arg(&ctx.model).arg("--permission-mode").arg(mode(ctx.access)); + command.arg("--max-turns").arg(ctx.limits.max_steps.to_string()); + if let Some(effort) = ctx.effort { + command.arg("--effort").arg(effort.wire()); + } + if let Some(session) = resume { + command.arg("--resume").arg(session); + } + if let Some(prompt) = append_prompt(ctx, root) { + command.arg("--append-system-prompt-file").arg(prompt); + } + command.current_dir(root).env_remove("ANTHROPIC_API_KEY").stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()); + hide_window(&mut command); + let mut child = command.spawn().map_err(|e| format!("Claude Code could not start: {e}"))?; + let stdin = child.stdin.take().ok_or("Claude Code has no input pipe.")?; + let stdout = child.stdout.take().ok_or("Claude Code has no output pipe.")?; + let stderr = child.stderr.take(); + let (tx, lines) = channel(); + std::thread::spawn(move || { + for line in BufReader::new(stdout).lines() { + let Ok(line) = line else { break }; + if tx.send(line).is_err() { + break; + } + } + }); + let errors = Arc::new(Mutex::new(String::new())); + if let Some(mut stderr) = stderr { + let errors = errors.clone(); + std::thread::spawn(move || { + let mut buffer = [0u8; 4096]; + while let Ok(read) = stderr.read(&mut buffer) { + if read == 0 { + break; + } + let mut text = errors.lock().expect("stderr lock"); + text.push_str(&String::from_utf8_lossy(&buffer[..read])); + if text.len() > 8000 { + let mut cut = text.len() - 4000; + while !text.is_char_boundary(cut) { + cut += 1; + } + text.drain(..cut); + } + } + }); + } + Ok(Process { child, stdin, lines, errors, key, spent: 0.0 }) + } + + fn send(&mut self, value: &Value) -> Result<(), String> { + writeln!(self.stdin, "{value}").and_then(|_| self.stdin.flush()).map_err(|_| self.failure()) + } + + fn next(&self, wait: Duration) -> Next { + match self.lines.recv_timeout(wait) { + Ok(line) => Next::Line(line), + Err(RecvTimeoutError::Timeout) => Next::Idle, + Err(RecvTimeoutError::Disconnected) => Next::Closed, + } + } + + fn failure(&self) -> String { + let errors = self.errors.lock().expect("stderr lock"); + let detail = errors.trim(); + if detail.is_empty() { "Claude Code stopped unexpectedly.".into() } else { format!("Claude Code stopped: {detail}") } + } +} + +impl Drop for Process { + fn drop(&mut self) { + let _ = self.child.kill(); + let _ = self.child.wait(); + } +} + +fn mode(access: Access) -> &'static str { + match access { + Access::Supervised => "manual", + Access::AutoEdits | Access::Full => "acceptEdits", + } +} + +fn append_prompt(ctx: &TurnContext, root: &Path) -> Option { + let files: Vec = ctx.instructions.iter().filter(|name| !name.eq_ignore_ascii_case("CLAUDE.md")).cloned().collect(); + let mut parts = vec![IDENTITY.to_string()]; + if !ctx.personal.trim().is_empty() { + parts.push(format!("# The user's personal instructions\n\n{}", ctx.personal.trim())); + } + let project = ctx.root.as_ref().map(|_| project_instructions(root, &files)).unwrap_or_default(); + if !project.is_empty() { + parts.push(format!("# Project instructions\n\n{project}")); + } + let dir = std::env::temp_dir().join("quill-claude"); + std::fs::create_dir_all(&dir).ok()?; + let path = dir.join(format!("prompt-{}-{}.md", std::process::id(), name_hash(&parts.join("\n")))); + std::fs::write(&path, parts.join("\n\n")).ok()?; + Some(path) +} + +fn name_hash(text: &str) -> u64 { + text.bytes().fold(0xcbf29ce484222325u64, |h, b| (h ^ b as u64).wrapping_mul(0x100000001b3)) +} + +fn spawn_key(ctx: &TurnContext, root: &Path) -> String { + format!("{}|{:?}|{}|{}|{}", ctx.model, ctx.effort, mode(ctx.access), ctx.limits.max_steps, root.display()) +} + +fn scratch_dir() -> PathBuf { + let dir = std::env::temp_dir().join("quill-chat"); + let _ = std::fs::create_dir_all(&dir); + dir +} + +fn stored_session(root: &Path, session: &str) -> bool { + let config = std::env::var_os("CLAUDE_CONFIG_DIR").map(PathBuf::from).unwrap_or_else(|| { + let home = std::env::var_os("USERPROFILE").or_else(|| std::env::var_os("HOME")).map(PathBuf::from).unwrap_or_default(); + home.join(".claude") + }); + let folder: String = root.to_string_lossy().chars().map(|c| if c.is_ascii_alphanumeric() { c } else { '-' }).collect(); + config.join("projects").join(folder).join(format!("{session}.jsonl")).is_file() +} + +fn user_message(text: &str, images: &[String]) -> Value { + let mut content: Vec = images.iter().map(|url| image_block(url)).collect(); + content.push(json!({ "type": "text", "text": text })); + json!({ "type": "user", "message": { "role": "user", "content": content } }) +} + +pub(crate) fn run( + session: &mut Session, + turn: usize, + input: Input, + ctx: &TurnContext, + claude: &ClaudeCode, + cancel: &AtomicBool, +) -> Outcome { + let root = ctx.root.clone().unwrap_or_else(scratch_dir); + if session.link.is_none() { + session.link = claude.resume.clone(); + } + let synced = session.link.as_ref().is_some_and(|link| link.synced == session.history.len()); + let key = spawn_key(ctx, &root); + if session.claude.as_ref().is_some_and(|process| process.key != key || !synced) { + session.claude = None; + } + let mut process = match session.claude.take() { + Some(process) => process, + None => { + let resume = + session.link.as_ref().filter(|link| synced && stored_session(&root, &link.session)).map(|link| link.session.clone()); + let fresh = resume.is_none(); + match Process::start(claude, ctx, &root, resume.as_deref(), key) { + Ok(process) => { + if fresh { + session.link = None; + } + process + } + Err(error) => return Outcome::Failed(error), + } + } + }; + let handoff = session.link.is_none() && !session.history.is_empty(); + let mut text = if handoff { + format!("{HANDOFF}\n\n{}\n\n---\n\n{}", context::transcript(&session.history, 60_000), input.text) + } else { + input.text.clone() + }; + let steers = session.inbox.lock().expect("inbox lock").steers(); + for steer in &steers { + session.push(Message::user(steer.clone())); + } + if !steers.is_empty() { + text = format!("{}\n\n{text}", steers.join("\n\n")); + } + session.push(Message::user_with_images(input.text, input.images.clone())); + if let Err(error) = process.send(&user_message(&text, &input.images)) { + return Outcome::Failed(error); + } + let mut mapper = Mapper { turn, root, ..Mapper::default() }; + let outcome = converse(session, &mut process, &mut mapper, ctx, cancel); + mapper.flush(session); + if let Some(id) = mapper.session.or_else(|| session.link.as_ref().map(|link| link.session.clone())) { + let link = ClaudeLink { session: id, synced: session.history.len() }; + session.link = Some(link.clone()); + session.emit(Event::ClaudeSession { link }); + } + if mapper.finished { + session.claude = Some(process); + } + outcome +} + +fn converse(session: &mut Session, process: &mut Process, mapper: &mut Mapper, ctx: &TurnContext, cancel: &AtomicBool) -> Outcome { + let mut deadline: Option = None; + loop { + if cancel.load(Ordering::Relaxed) && deadline.is_none() { + let interrupt = json!({ "type": "control_request", "request_id": format!("quill-stop-{}", mapper.turn), "request": { "subtype": "interrupt" } }); + let _ = process.send(&interrupt); + deadline = Some(Instant::now() + Duration::from_secs(8)); + } + if deadline.is_some_and(|deadline| Instant::now() > deadline) { + return Outcome::Stopped; + } + let line = match process.next(Duration::from_millis(100)) { + Next::Line(line) => line, + Next::Idle => continue, + Next::Closed => return if deadline.is_some() { Outcome::Stopped } else { Outcome::Failed(process.failure()) }, + }; + let Ok(value) = serde_json::from_str::(&line) else { continue }; + match value["type"].as_str().unwrap_or_default() { + "control_request" => { + let reply = control(session, mapper, ctx, &value["request"], cancel); + let response = json!({ "type": "control_response", "response": { "subtype": "success", "request_id": value["request_id"], "response": reply } }); + if let Err(error) = process.send(&response) { + return Outcome::Failed(error); + } + } + "result" => { + mapper.flush(session); + mapper.result(session, process, &value); + let steers = session.inbox.lock().expect("inbox lock").steers(); + if deadline.is_none() && !steers.is_empty() { + for text in &steers { + session.push(Message::user(text.clone())); + } + if let Err(error) = process.send(&user_message(&steers.join("\n\n"), &[])) { + return Outcome::Failed(error); + } + continue; + } + mapper.finished = true; + return outcome(&value, deadline.is_some()); + } + _ => mapper.apply(session, &value), + } + } +} + +fn outcome(result: &Value, stopped: bool) -> Outcome { + if stopped { + return Outcome::Stopped; + } + if result["subtype"] == "success" && !result["is_error"].as_bool().unwrap_or(false) { + return Outcome::Done; + } + let errors: Vec<&str> = result["errors"].as_array().map(|list| list.iter().filter_map(Value::as_str).collect()).unwrap_or_default(); + let detail = result["result"].as_str().filter(|text| !text.trim().is_empty()).map(str::to_string).unwrap_or_else(|| errors.join(" ")); + match result["subtype"].as_str() { + Some("error_max_turns") => Outcome::Failed("Claude Code reached its step limit. Send a follow-up to let it continue.".into()), + _ if detail.is_empty() => Outcome::Failed("Claude Code could not finish this turn.".into()), + _ => Outcome::Failed(detail), + } +} + +fn control(session: &mut Session, mapper: &mut Mapper, ctx: &TurnContext, request: &Value, cancel: &AtomicBool) -> Value { + if request["subtype"] != "can_use_tool" { + return json!({}); + } + let name = request["tool_name"].as_str().unwrap_or_default(); + let input = &request["input"]; + let id = request["tool_use_id"].as_str().map(str::to_string).unwrap_or_else(|| format!("claude-{}", mapper.tools.len())); + if name == "AskUserQuestion" { + return ask(session, mapper.turn, &id, input, cancel); + } + let check = classify(name, input, &mapper.root); + let request = Request { id: &id, tool: check.rule, effect: check.effect, subject: &check.subject, approval: &check.approval }; + match permit(session, mapper.turn, ctx, &request, cancel) { + Ok(()) => json!({ "behavior": "allow", "updatedInput": input }), + Err(reason) => json!({ "behavior": "deny", "message": reason }), + } +} + +fn ask(session: &mut Session, turn: usize, id: &str, input: &Value, cancel: &AtomicBool) -> Value { + let mut answers = serde_json::Map::new(); + for (n, item) in input["questions"].as_array().map(Vec::as_slice).unwrap_or(&[]).iter().enumerate() { + let question = item["question"].as_str().unwrap_or_default().to_string(); + let options: Vec = item["options"] + .as_array() + .map(|list| list.iter().filter_map(|option| option["label"].as_str().or(option.as_str()).map(str::to_string)).collect()) + .unwrap_or_default(); + let ask_id = format!("{id}-{n}"); + session.emit(Event::QuestionAsked { turn, id: ask_id.clone(), question: question.clone(), options }); + let answer = session.inbox.lock().expect("inbox lock").answer(&ask_id, cancel); + match answer { + Some(answer) => { + answers.insert(question, json!(answer)); + } + None => return json!({ "behavior": "deny", "message": STOPPED }), + } + } + let mut updated = input.clone(); + updated["answers"] = Value::Object(answers); + json!({ "behavior": "allow", "updatedInput": updated }) +} + +struct Check { + effect: Effect, + rule: &'static str, + subject: String, + approval: Approval, +} + +fn classify(name: &str, input: &Value, root: &Path) -> Check { + let text = |key: &str| input[key].as_str().unwrap_or_default().to_string(); + let path = |key: &str| relative(root, input[key].as_str().unwrap_or_default()); + let approval = |title: &str, subject: &str| Approval { title: title.into(), subject: subject.into(), diffs: Vec::new(), similar: None }; + let (effect, rule, subject, mut approval) = match name { + "Edit" | "MultiEdit" | "Write" | "NotebookEdit" => { + let key = if name == "NotebookEdit" { "notebook_path" } else { "file_path" }; + let subject = path(key); + let title = if name == "Write" { "Wants to write a file" } else { "Wants to change a file" }; + let rule = if name == "Write" { "write_file" } else { "edit_file" }; + (Effect::Write, rule, subject.clone(), approval(title, &subject)) + } + "Bash" | "PowerShell" => { + let command = text("command"); + let mut asked = approval("Wants to run a command", &command); + asked.similar = similar(&command); + (Effect::Execute, "shell", command, asked) + } + "WebFetch" => (Effect::Network, "fetch_url", text("url"), approval("Wants to fetch a web page", &text("url"))), + "WebSearch" => (Effect::Network, "web_search", text("query"), approval("Wants to search the web", &text("query"))), + "Read" | "Glob" | "Grep" | "LS" => { + let subject = [input["file_path"].as_str(), input["path"].as_str(), input["pattern"].as_str()] + .into_iter() + .flatten() + .next() + .unwrap_or_default(); + (Effect::ReadOutside, "read_file", subject.to_string(), approval("Wants to read outside the project", subject)) + } + "Task" | "Agent" => { + (Effect::Delegate, "agent", text("description"), approval("Wants to start a helper agent", &text("description"))) + } + other => { + let shown = other.trim_start_matches("mcp__").replace("__", " · "); + (Effect::Execute, "claude_tool", other.to_string(), approval(&format!("Wants to use {shown}"), &shown)) + } + }; + if effect == Effect::Write { + approval.diffs = planned_diff(name, input, root).into_iter().collect(); + } + Check { effect, rule, subject, approval } +} + +fn planned_diff(name: &str, input: &Value, root: &Path) -> Option { + let file = input["file_path"].as_str()?; + let before = std::fs::read_to_string(file).ok(); + let after = match name { + "Write" => input["content"].as_str()?.to_string(), + "Edit" => apply_edit(before.clone().unwrap_or_default(), input), + "MultiEdit" => input["edits"].as_array()?.iter().fold(before.clone().unwrap_or_default(), apply_edit), + _ => return None, + }; + Some(diff_text(&relative(root, file), before.as_deref(), &after)) +} + +fn apply_edit(text: String, edit: &Value) -> String { + let old = edit["old_string"].as_str().unwrap_or_default(); + let new = edit["new_string"].as_str().unwrap_or_default(); + if old.is_empty() { + return text; + } + if edit["replace_all"].as_bool().unwrap_or(false) { text.replace(old, new) } else { text.replacen(old, new, 1) } +} + +fn relative(root: &Path, path: &str) -> String { + let full = Path::new(path); + full.strip_prefix(root).map(|rel| rel.to_string_lossy().replace('\\', "/")).unwrap_or_else(|_| path.replace('\\', "/")) +} + +fn todos(input: &Value) -> Vec { + input["todos"] + .as_array() + .map(|list| { + list.iter() + .map(|todo| PlanStep { + text: todo["content"].as_str().unwrap_or_default().to_string(), + status: match todo["status"].as_str() { + Some("completed") => StepStatus::Done, + Some("in_progress") => StepStatus::Active, + _ => StepStatus::Pending, + }, + }) + .collect() + }) + .unwrap_or_default() +} + +fn view(id: &str, name: &str, input: &Value, root: &Path) -> ToolView { + let text = |key: &str| input[key].as_str().unwrap_or_default().to_string(); + let path = |key: &str| relative(root, input[key].as_str().unwrap_or_default()); + let (tool, category, active, done, target) = match name { + "Read" => ("read_file", Category::Explore, "Reading", "Read", path("file_path")), + "Glob" => ("find_files", Category::Explore, "Looking for", "Looked for", text("pattern")), + "Grep" => ("grep", Category::Explore, "Searching for", "Searched for", text("pattern")), + "LS" => ("list_dir", Category::Explore, "Looking through", "Looked through", path("path")), + "Edit" | "MultiEdit" => ("edit_file", Category::Edit, "Editing", "Edited", path("file_path")), + "NotebookEdit" => ("edit_file", Category::Edit, "Editing", "Edited", path("notebook_path")), + "Write" => ("write_file", Category::Edit, "Writing", "Wrote", path("file_path")), + "Bash" | "PowerShell" => ("shell", Category::Command, "Running", "Ran", text("command")), + "WebFetch" => ("fetch_url", Category::Web, "Fetching", "Fetched", text("url")), + "WebSearch" => ("web_search", Category::Web, "Searching the web for", "Searched the web for", text("query")), + "Task" | "Agent" => ("agent", Category::Agent, "Handing off", "Handed off", text("description")), + "Skill" => ("skill", Category::Other, "Using the skill", "Used the skill", text("skill")), + other => { + let shown = other.trim_start_matches("mcp__").replace("__", " · "); + return ToolView { + id: id.into(), + tool: other.into(), + category: Category::Other, + active: "Using".into(), + done: "Used".into(), + target: shown, + }; + } + }; + ToolView { id: id.into(), tool: tool.into(), category, active: active.into(), done: done.into(), target } +} + +fn result_content(content: &Value) -> (String, Option) { + match content { + Value::String(text) => (text.clone(), None), + Value::Array(blocks) => { + let text = blocks.iter().filter_map(|block| block["text"].as_str()).collect::>().join("\n"); + let image = blocks.iter().find(|block| block["type"] == "image").and_then(|block| { + let source = &block["source"]; + Some(format!("data:{};base64,{}", source["media_type"].as_str()?, source["data"].as_str()?)) + }); + (text, image) + } + _ => (String::new(), None), + } +} + +fn edit_diffs(block: &Value, detail: &Value, root: &Path) -> Vec { + let name = block["name"].as_str().unwrap_or_default(); + if !matches!(name, "Edit" | "MultiEdit" | "Write") { + return Vec::new(); + } + let Some(file) = detail["filePath"].as_str().or_else(|| block["input"]["file_path"].as_str()) else { return Vec::new() }; + let before = detail["originalFile"].as_str(); + let after = match name { + "Write" => block["input"]["content"].as_str().map(str::to_string), + _ => std::fs::read_to_string(file).ok(), + }; + after.map(|after| vec![diff_text(&relative(root, file), before, &after)]).unwrap_or_default() +} + +#[derive(Default)] +struct Mapper { + turn: usize, + root: PathBuf, + tools: HashMap, + hidden: HashSet, + message: Option, + text: String, + calls: Vec, + session: Option, + finished: bool, +} + +impl Mapper { + fn apply(&mut self, session: &mut Session, value: &Value) { + let parent = value["parent_tool_use_id"].as_str(); + match value["type"].as_str().unwrap_or_default() { + "system" if value["subtype"] == "init" => { + self.session = value["session_id"].as_str().map(str::to_string); + if let Some(model) = value["model"].as_str() { + session.emit(Event::ModelResolved { turn: self.turn, model: model.to_string() }); + } + } + "stream_event" if parent.is_none() => { + let event = &value["event"]; + if event["type"] == "message_delta" { + let tokens = Tokens::from_anthropic(&event["usage"]); + if tokens.prompt > 0 { + session.emit(Event::Usage { turn: self.turn, tokens }); + } + } + if event["type"] == "content_block_delta" && event["delta"]["type"] == "text_delta" { + let text = event["delta"]["text"].as_str().unwrap_or_default(); + if !text.is_empty() { + session.emit(Event::Text { turn: self.turn, text: text.to_string() }); + } + } + } + "assistant" => match parent { + Some(parent) => self.helper(session, parent, &value["message"]), + None => self.assistant(session, &value["message"]), + }, + "user" if parent.is_none() => { + let blocks = value["message"]["content"].as_array().map(Vec::as_slice).unwrap_or(&[]); + let results: Vec<&Value> = blocks.iter().filter(|block| block["type"] == "tool_result").collect(); + if results.is_empty() { + return; + } + self.flush(session); + let detail = (results.len() == 1).then_some(&value["tool_use_result"]); + for result in results { + self.end(session, result, detail); + } + } + _ => {} + } + } + + fn assistant(&mut self, session: &mut Session, message: &Value) { + let id = message["id"].as_str().map(str::to_string); + if id != self.message { + self.flush(session); + self.message = id; + } + for block in message["content"].as_array().map(Vec::as_slice).unwrap_or(&[]) { + match block["type"].as_str() { + Some("text") => { + if !self.text.is_empty() { + self.text.push_str("\n\n"); + } + self.text.push_str(block["text"].as_str().unwrap_or_default()); + } + Some("tool_use") => self.begin(session, block), + _ => {} + } + } + } + + fn helper(&self, session: &Session, parent: &str, message: &Value) { + for block in message["content"].as_array().map(Vec::as_slice).unwrap_or(&[]) { + let chunk = match block["type"].as_str() { + Some("text") => format!("{}\n", block["text"].as_str().unwrap_or_default().trim()), + Some("tool_use") => { + let view = view("", block["name"].as_str().unwrap_or_default(), &block["input"], &self.root); + format!("{} {}\n", view.done, view.target) + } + _ => continue, + }; + session.emit(Event::ToolOutput { turn: self.turn, id: parent.to_string(), chunk }); + } + } + + fn begin(&mut self, session: &mut Session, block: &Value) { + let id = block["id"].as_str().unwrap_or_default().to_string(); + let name = block["name"].as_str().unwrap_or_default(); + let input = &block["input"]; + self.calls.push(ToolCall::new(id.clone(), name, input.to_string())); + self.tools.insert(id.clone(), block.clone()); + match name { + "TodoWrite" => { + self.hidden.insert(id); + session.emit(Event::PlanUpdated { turn: self.turn, steps: todos(input), explanation: None }); + } + "AskUserQuestion" => { + self.hidden.insert(id); + } + _ => session.emit(Event::ToolBegin { turn: self.turn, view: view(&id, name, input, &self.root) }), + } + } + + fn end(&mut self, session: &mut Session, result: &Value, detail: Option<&Value>) { + let id = result["tool_use_id"].as_str().unwrap_or_default().to_string(); + let (text, image) = result_content(&result["content"]); + let ok = !result["is_error"].as_bool().unwrap_or(false); + session.push(Message::tool(id.clone(), if ok { text.clone() } else { format!("Error: {text}") })); + if self.hidden.contains(&id) { + return; + } + let diffs = match (self.tools.get(&id), detail) { + (Some(block), Some(detail)) if ok => edit_diffs(block, detail, &self.root), + _ => Vec::new(), + }; + session.emit(Event::ToolEnd { turn: self.turn, id, ok, output: text, diffs, image }); + } + + fn flush(&mut self, session: &mut Session) { + if self.text.trim().is_empty() && self.calls.is_empty() { + self.text.clear(); + return; + } + session.push(Message::assistant(std::mem::take(&mut self.text), std::mem::take(&mut self.calls))); + } + + fn result(&self, session: &Session, process: &mut Process, value: &Value) { + if let Some(total) = value["total_cost_usd"].as_f64() { + let usd = (total - process.spent).max(0.0); + process.spent = total; + session.emit(Event::Cost { turn: self.turn, usd }); + } + let window = value["modelUsage"].as_object().and_then(|models| models.values().filter_map(|m| m["contextWindow"].as_u64()).max()); + if let Some(tokens) = window { + session.emit(Event::ContextWindow { tokens }); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn claude_tools_look_like_quill_tools() { + let root = Path::new("C:\\work\\app"); + let read = view("t1", "Read", &json!({ "file_path": "C:\\work\\app\\src\\main.rs" }), root); + assert_eq!((read.tool.as_str(), read.category, read.target.as_str()), ("read_file", Category::Explore, "src/main.rs")); + let run = view("t2", "PowerShell", &json!({ "command": "Get-Content a.txt" }), root); + assert_eq!((run.tool.as_str(), run.category), ("shell", Category::Command)); + let mcp = view("t3", "mcp__github__create_issue", &json!({}), root); + assert_eq!(mcp.target, "github · create_issue"); + } + + #[test] + fn permission_prompts_map_onto_quill_policy() { + let root = Path::new("C:\\work\\app"); + let command = classify("Bash", &json!({ "command": "npm test -- --watch" }), root); + assert_eq!((command.effect, command.rule), (Effect::Execute, "shell")); + assert_eq!(command.approval.similar.as_deref(), Some("npm test")); + let fetch = classify("WebFetch", &json!({ "url": "https://example.com" }), root); + assert_eq!(fetch.effect, Effect::Network); + let write = classify("Write", &json!({ "file_path": "C:\\work\\app\\new.txt", "content": "hi" }), root); + assert_eq!((write.effect, write.subject.as_str()), (Effect::Write, "new.txt")); + assert_eq!(write.approval.diffs.len(), 1); + assert!(write.approval.diffs[0].created); + } + + #[test] + fn edits_apply_for_previews() { + let edit = json!({ "old_string": "a", "new_string": "b" }); + assert_eq!(apply_edit("a a".into(), &edit), "b a"); + let all = json!({ "old_string": "a", "new_string": "b", "replace_all": true }); + assert_eq!(apply_edit("a a".into(), &all), "b b"); + } + + #[test] + fn todos_become_plan_steps() { + let steps = todos(&json!({ "todos": [ + { "content": "Read the code", "status": "completed", "activeForm": "Reading" }, + { "content": "Fix it", "status": "in_progress" }, + { "content": "Test", "status": "pending" } + ]})); + let states: Vec = steps.iter().map(|s| s.status).collect(); + assert_eq!(states, vec![StepStatus::Done, StepStatus::Active, StepStatus::Pending]); + } + + #[test] + fn results_decide_the_outcome() { + assert_eq!(outcome(&json!({ "subtype": "success", "is_error": false }), false), Outcome::Done); + assert_eq!(outcome(&json!({ "subtype": "error_during_execution", "is_error": true }), true), Outcome::Stopped); + assert_eq!( + outcome(&json!({ "subtype": "success", "is_error": true, "result": "Not logged in · Please run /login" }), false), + Outcome::Failed("Not logged in · Please run /login".into()) + ); + assert!(matches!(outcome(&json!({ "subtype": "error_max_turns", "is_error": true }), false), Outcome::Failed(_))); + } + + #[test] + fn tool_results_keep_text_and_images() { + let (text, image) = result_content(&json!([ + { "type": "text", "text": "a screenshot" }, + { "type": "image", "source": { "type": "base64", "media_type": "image/png", "data": "AAAA" } } + ])); + assert_eq!(text, "a screenshot"); + assert_eq!(image.as_deref(), Some("data:image/png;base64,AAAA")); + } + + #[test] + fn session_folders_follow_claude_naming() { + let folder: String = "D:\\repos\\quill-code".chars().map(|c| if c.is_ascii_alphanumeric() { c } else { '-' }).collect(); + assert_eq!(folder, "D--repos-quill-code"); + } +} \ No newline at end of file diff --git a/crates/quill-core/src/context.rs b/crates/quill-core/src/context.rs new file mode 100644 index 0000000..18fd50a --- /dev/null +++ b/crates/quill-core/src/context.rs @@ -0,0 +1,160 @@ +use std::sync::atomic::AtomicBool; + +use quill_providers::{ChatRequest, Effort, Error, Event, Message, Provider, Role}; + +const SUMMARY: &str = "Summary of the conversation so far:"; + +const SUMMARIZE: &str = "You summarize a coding session so it can continue in a fresh context. Write a compact summary covering: what the user asked for, decisions made, files created or changed (with paths), commands run and their results, the current state, and what is left to do. Keep exact names, paths and error messages that matter. Reply with the summary only."; + +pub fn estimate(history: &[Message]) -> u64 { + let chars: usize = history + .iter() + .map(|m| { + m.content.len() + + m.images.len() * 3000 + + m.tool_calls.iter().map(|c| c.function.name.len() + c.function.arguments.len()).sum::() + }) + .sum(); + (chars / 4) as u64 + 2000 +} + +pub fn over(used: u64, window: Option, threshold: f32) -> bool { + window.is_some_and(|window| used as f32 > window as f32 * threshold) +} + +pub fn cut(history: &[Message]) -> Option { + history.iter().rposition(|m| m.role == Role::User).filter(|index| *index > 0) +} + +fn clip(text: &str, max: usize) -> String { + if text.len() <= max { + return text.to_string(); + } + let mut end = max; + while !text.is_char_boundary(end) { + end -= 1; + } + format!("{}…", &text[..end]) +} + +pub fn transcript(messages: &[Message], max_chars: usize) -> String { + let lines: Vec = messages + .iter() + .map(|m| match m.role { + Role::System => format!("System: {}", clip(&m.content, 2000)), + Role::User => format!("User: {}", clip(&m.content, 6000)), + Role::Assistant => { + let calls: Vec = + m.tool_calls.iter().map(|c| format!("[{} {}]", c.function.name, clip(&c.function.arguments, 400))).collect(); + format!("Assistant: {} {}", clip(&m.content, 4000), calls.join(" ")).trim_end().to_string() + } + Role::Tool => format!("Tool result: {}", clip(&m.content, 1500)), + }) + .collect(); + let text = lines.join("\n\n"); + if text.len() <= max_chars { + return text; + } + let mut start = text.len() - max_chars; + while !text.is_char_boundary(start) { + start += 1; + } + format!("[earlier part cut]\n{}", &text[start..]) +} + +pub fn summarize( + provider: &dyn Provider, + model: &str, + effort: Option, + window: Option, + head: &[Message], + cancel: &AtomicBool, +) -> Result { + let budget = window.map_or(48_000, |w| (w as usize).saturating_mul(2).max(8000)); + let request = ChatRequest { + model: model.to_string(), + messages: vec![Message::system(SUMMARIZE), Message::user(transcript(head, budget))], + thinking: Some(false), + effort, + ..ChatRequest::default() + }; + let mut text = String::new(); + provider.stream(&request, cancel, &mut |event| { + if let Event::Content(chunk) = event { + text.push_str(&chunk); + } + })?; + let text = match text.rfind("") { + Some(end) => text[end + 8..].trim().to_string(), + None => text.trim().to_string(), + }; + if text.is_empty() { Err(Error("The model returned an empty summary.".into())) } else { Ok(text) } +} + +pub fn join(summary: &str, mut tail: Vec) -> Vec { + if let Some(first) = tail.first_mut() { + first.content = format!("{SUMMARY}\n\n{summary}\n\n---\n\n{}", first.content); + } + tail +} + +pub fn trim_outputs(history: &mut [Message], keep: usize) -> bool { + let tools: Vec = history.iter().enumerate().filter(|(_, m)| m.role == Role::Tool).map(|(i, _)| i).collect(); + let mut changed = false; + for &index in tools.iter().rev().skip(keep) { + if history[index].content.len() > 600 { + history[index].content = format!("{} [older output trimmed to save space]", clip(&history[index].content, 400)); + changed = true; + } + } + changed +} + +#[cfg(test)] +mod tests { + use super::*; + use quill_providers::ToolCall; + + fn history() -> Vec { + vec![ + Message::user("first"), + Message::assistant("", vec![ToolCall::new("a", "read_file", "{}")]), + Message::tool("a", "x".repeat(2000)), + Message::assistant("done", Vec::new()), + Message::user("second"), + Message::assistant("ok", Vec::new()), + ] + } + + #[test] + fn compaction_keeps_the_latest_request() { + let history = history(); + assert_eq!(cut(&history), Some(4)); + assert_eq!(cut(&history[..4]), None); + let joined = join("They read a file.", history[4..].to_vec()); + assert!(joined[0].content.starts_with(SUMMARY) && joined[0].content.ends_with("second")); + assert_eq!(joined.len(), 2); + } + + #[test] + fn thresholds_and_estimates_decide_when() { + assert!(over(900, Some(1000), 0.8)); + assert!(!over(700, Some(1000), 0.8)); + assert!(!over(1_000_000, None, 0.8)); + assert!(estimate(&history()) > 2000); + } + + #[test] + fn old_tool_output_is_trimmed() { + let mut history = history(); + assert!(trim_outputs(&mut history, 0)); + assert!(history[2].content.len() < 600); + assert!(!trim_outputs(&mut history, 0)); + } + + #[test] + fn transcripts_keep_the_end_when_too_long() { + let text = transcript(&history(), 50); + assert!(text.starts_with("[earlier part cut]") && text.ends_with("ok")); + } +} \ No newline at end of file diff --git a/crates/quill-agent/src/diff.rs b/crates/quill-core/src/diff.rs similarity index 100% rename from crates/quill-agent/src/diff.rs rename to crates/quill-core/src/diff.rs diff --git a/crates/quill-agent/src/instructions.rs b/crates/quill-core/src/instructions.rs similarity index 87% rename from crates/quill-agent/src/instructions.rs rename to crates/quill-core/src/instructions.rs index e3ec6dd..da2a5a4 100644 --- a/crates/quill-agent/src/instructions.rs +++ b/crates/quill-core/src/instructions.rs @@ -16,10 +16,10 @@ fn expand_imports(root: &Path, text: &str) -> String { .join("\n") } -pub fn project_instructions(root: &Path) -> String { +pub fn project_instructions(root: &Path, files: &[String]) -> String { let mut seen: Vec = Vec::new(); let mut parts = Vec::new(); - for name in ["AGENTS.md", "CLAUDE.md", "GEMINI.md", ".github/copilot-instructions.md"] { + for name in files { let Ok(raw) = fs::read_to_string(root.join(name)) else { continue }; let text = expand_imports(root, &raw).trim().to_string(); if text.is_empty() || seen.contains(&text) { @@ -50,7 +50,8 @@ mod tests { fs::create_dir_all(&dir).unwrap(); fs::write(dir.join("AGENTS.md"), "Use tabs.").unwrap(); fs::write(dir.join("CLAUDE.md"), "@AGENTS.md").unwrap(); - let text = project_instructions(&dir); + let files: Vec = ["AGENTS.md", "CLAUDE.md"].iter().map(|s| s.to_string()).collect(); + let text = project_instructions(&dir, &files); assert_eq!(text.matches("Use tabs.").count(), 1); assert!(text.starts_with("## AGENTS.md")); fs::remove_dir_all(&dir).unwrap(); diff --git a/crates/quill-core/src/lib.rs b/crates/quill-core/src/lib.rs new file mode 100644 index 0000000..fabcb20 --- /dev/null +++ b/crates/quill-core/src/lib.rs @@ -0,0 +1,19 @@ +mod claude_code; +mod context; +pub mod diff; +mod instructions; +mod options; +mod policy; +mod prompt; +mod protocol; +mod session; +pub mod tools; +mod turn; + +pub use claude_code::{ClaudeCode, claude_version, complete as claude_complete, find_claude}; +pub use diff::{DiffLine, FileDiff, LineKind, diff_text}; +pub use instructions::project_instructions; +pub use options::{Limits, Shell, Toolsets}; +pub use policy::{Access, Effect, Rule, RuleAction, Verdict, read_only, verdict}; +pub use protocol::{Approval, Category, ClaudeLink, Decision, Event, Outcome, PlanStep, StepStatus, ToolView}; +pub use session::{Engine, Input, Op, SessionHandle, Summarizer, TurnContext, spawn}; \ No newline at end of file diff --git a/crates/quill-core/src/options.rs b/crates/quill-core/src/options.rs new file mode 100644 index 0000000..1076222 --- /dev/null +++ b/crates/quill-core/src/options.rs @@ -0,0 +1,119 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Shell { + PowerShell, + Pwsh, + Cmd, + Bash, + Sh, +} + +impl Default for Shell { + fn default() -> Self { + if cfg!(windows) { Shell::PowerShell } else { Shell::Sh } + } +} + +impl Shell { + pub const ALL: [Shell; 5] = [Shell::PowerShell, Shell::Pwsh, Shell::Cmd, Shell::Bash, Shell::Sh]; + + pub fn label(self) -> &'static str { + match self { + Shell::PowerShell => "Windows PowerShell", + Shell::Pwsh => "PowerShell 7", + Shell::Cmd => "Command Prompt", + Shell::Bash => "Bash", + Shell::Sh => "sh", + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub struct Toolsets { + pub git: bool, +} + +impl Default for Toolsets { + fn default() -> Self { + Toolsets { git: true } + } +} + +#[derive(Debug, Clone, PartialEq)] +pub struct Limits { + pub max_steps: usize, + pub command_timeout: u64, + pub max_command_timeout: u64, + pub max_output: usize, + pub max_read_lines: usize, + pub max_matches: usize, + pub max_list: usize, + pub compact_at: f32, + pub parallel_tools: bool, + pub shell: Shell, + pub ignored: Vec, + pub safe_commands: Vec, + pub disabled_tools: Vec, +} + +pub const IGNORED: [&str; 13] = + [".git", "node_modules", "target", "dist", "build", ".venv", "venv", "__pycache__", ".next", ".idea", ".vs", "bin", "obj"]; + +pub const SAFE_COMMANDS: [&str; 34] = [ + "git status", + "git diff", + "git log", + "git show", + "git branch", + "git remote -v", + "git rev-parse", + "Get-ChildItem", + "gci", + "ls", + "dir", + "Get-Content", + "gc", + "cat", + "type", + "Select-String", + "sls", + "Select-Object", + "Where-Object", + "Sort-Object", + "Measure-Object", + "Format-Table", + "Format-List", + "Get-Location", + "pwd", + "Get-Item", + "Test-Path", + "Resolve-Path", + "rg", + "findstr", + "where", + "Get-Command", + "echo", + "Write-Output", +]; + +impl Default for Limits { + fn default() -> Self { + Limits { + max_steps: 100, + command_timeout: 120, + max_command_timeout: 600, + max_output: 30_000, + max_read_lines: 1500, + max_matches: 200, + max_list: 400, + compact_at: 0.8, + parallel_tools: true, + shell: Shell::default(), + ignored: IGNORED.iter().map(|s| s.to_string()).collect(), + safe_commands: SAFE_COMMANDS.iter().map(|s| s.to_string()).collect(), + disabled_tools: Vec::new(), + } + } +} \ No newline at end of file diff --git a/crates/quill-core/src/policy.rs b/crates/quill-core/src/policy.rs new file mode 100644 index 0000000..5569e07 --- /dev/null +++ b/crates/quill-core/src/policy.rs @@ -0,0 +1,162 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Access { + #[serde(alias = "manual")] + Supervised, + AutoEdits, + #[default] + #[serde(alias = "auto")] + Full, +} + +impl Access { + pub const ALL: [Access; 3] = [Access::Supervised, Access::AutoEdits, Access::Full]; + + pub fn label(self) -> &'static str { + match self { + Access::Supervised => "Ask first", + Access::AutoEdits => "Trust edits", + Access::Full => "Autopilot", + } + } + + pub fn description(self) -> &'static str { + match self { + Access::Supervised => "Checks with you before every change and command", + Access::AutoEdits => "Makes edits and read-only commands on its own, checks before the rest", + Access::Full => "Works without stopping to ask, except before fetching from the web", + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Effect { + Read, + ReadOutside, + Write, + Execute, + Publish, + Network, + Desktop, + Delegate, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum RuleAction { + Allow, + Ask, + Deny, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct Rule { + pub tool: String, + #[serde(default)] + pub pattern: String, + pub action: RuleAction, +} + +impl Rule { + pub fn allow(tool: &str, pattern: &str) -> Rule { + Rule { tool: tool.to_string(), pattern: pattern.to_string(), action: RuleAction::Allow } + } + + pub fn matches(&self, tool: &str, subject: &str) -> bool { + (self.tool == "*" || self.tool.eq_ignore_ascii_case(tool)) && pattern_matches(&self.pattern, subject) + } +} + +fn pattern_matches(pattern: &str, subject: &str) -> bool { + let pattern = pattern.trim().to_lowercase(); + let subject = subject.trim().to_lowercase(); + if pattern.is_empty() || pattern == "*" { + return true; + } + match pattern.strip_suffix('*') { + Some(prefix) => subject.starts_with(prefix), + None => subject == pattern || subject.starts_with(&format!("{pattern} ")), + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Verdict { + Allow, + Ask, + Deny(String), +} + +pub fn verdict(access: Access, effect: Effect, tool: &str, subject: &str, rules: &[Rule], safe_commands: &[String]) -> Verdict { + if let Some(rule) = rules.iter().rev().find(|rule| rule.matches(tool, subject)) { + return match rule.action { + RuleAction::Allow => Verdict::Allow, + RuleAction::Ask => Verdict::Ask, + RuleAction::Deny => Verdict::Deny(format!("A rule in the user's settings blocks {tool} here.")), + }; + } + match effect { + Effect::Read => Verdict::Allow, + Effect::Network => Verdict::Ask, + _ if access == Access::Full => Verdict::Allow, + Effect::Write if access == Access::AutoEdits => Verdict::Allow, + Effect::Execute if access == Access::AutoEdits && read_only(subject, safe_commands) => Verdict::Allow, + _ => Verdict::Ask, + } +} + +pub fn read_only(command: &str, safe_commands: &[String]) -> bool { + if command.contains('>') || command.contains('`') || command.contains("$(") { + return false; + } + let mut parts = command.split(['|', ';', '&', '\n']).map(str::trim).filter(|part| !part.is_empty()).peekable(); + parts.peek().is_some() && parts.all(|part| safe_commands.iter().any(|safe| pattern_matches(safe, part))) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn safe() -> Vec { + ["git status", "Get-ChildItem", "Select-String"].iter().map(|s| s.to_string()).collect() + } + + #[test] + fn access_reads_old_settings() { + let auto: Access = serde_json::from_str("\"auto\"").unwrap(); + let manual: Access = serde_json::from_str("\"manual\"").unwrap(); + assert_eq!((auto, manual), (Access::Full, Access::Supervised)); + assert_eq!(serde_json::to_string(&Access::AutoEdits).unwrap(), "\"auto_edits\""); + } + + #[test] + fn presets_decide_by_effect() { + let ask = |access, effect| verdict(access, effect, "t", "x", &[], &safe()); + assert_eq!(ask(Access::Supervised, Effect::Read), Verdict::Allow); + assert_eq!(ask(Access::Supervised, Effect::Write), Verdict::Ask); + assert_eq!(ask(Access::AutoEdits, Effect::Write), Verdict::Allow); + assert_eq!(ask(Access::AutoEdits, Effect::Execute), Verdict::Ask); + assert_eq!(ask(Access::Full, Effect::Execute), Verdict::Allow); + assert_eq!(ask(Access::Full, Effect::ReadOutside), Verdict::Allow); + assert_eq!(ask(Access::Full, Effect::Network), Verdict::Ask); + assert_eq!(verdict(Access::AutoEdits, Effect::Execute, "shell", "git status", &[], &safe()), Verdict::Allow); + } + + #[test] + fn rules_win_over_presets() { + let rules = vec![Rule::allow("shell", "npm test"), Rule { tool: "*".into(), pattern: "rm*".into(), action: RuleAction::Deny }]; + assert_eq!(verdict(Access::Supervised, Effect::Execute, "shell", "npm test -- --watch", &rules, &[]), Verdict::Allow); + assert_eq!(verdict(Access::Supervised, Effect::Execute, "shell", "npm testing", &rules, &[]), Verdict::Ask); + assert!(matches!(verdict(Access::Full, Effect::Execute, "shell", "rm -rf x", &rules, &[]), Verdict::Deny(_))); + } + + #[test] + fn read_only_commands_are_recognised() { + assert!(read_only("git status", &safe())); + assert!(read_only("Get-ChildItem src | Select-String foo", &safe())); + assert!(!read_only("Get-ChildItem > out.txt", &safe())); + assert!(!read_only("git status; npm install", &safe())); + assert!(!read_only("", &safe())); + } +} \ No newline at end of file diff --git a/crates/quill-core/src/prompt.rs b/crates/quill-core/src/prompt.rs new file mode 100644 index 0000000..6b2eb8d --- /dev/null +++ b/crates/quill-core/src/prompt.rs @@ -0,0 +1,141 @@ +use std::path::Path; + +use crate::instructions::project_instructions; +use crate::options::Shell; +use crate::tools::{Tool, Toolset}; + +const POWERSHELL: &str = "# Commands + +shell runs Windows PowerShell, so write PowerShell, not bash or cmd: +- Use cmdlets such as Get-ChildItem, Get-Content, Select-String, New-Item, Copy-Item, Move-Item and Remove-Item. Do not use ls -la, grep, cat with flags, rm -rf, touch or export. +- Separate commands with a semicolon. Set environment variables with $env:NAME = 'value'. +- Paths use backslashes, and paths with spaces need quotes. +- Run programs installed on the computer, such as python, node, npm, cargo, dotnet or go, by name."; + +const CMD: &str = "# Commands + +shell runs the Windows Command Prompt, so write cmd syntax. Chain commands with &&, set variables with set NAME=value and quote paths that contain spaces."; + +const POSIX: &str = "# Commands + +shell runs a POSIX shell, so write sh syntax. Combine commands with && and quote paths that contain spaces. Run programs installed on the computer by name."; + +const COMMAND_RULES: &str = "Commands must finish on their own. Pass flags that skip prompts, such as -y, and do not start servers, watchers or anything else that waits forever; a command is stopped when its timeout runs out. To look at files, prefer list_dir, find_files, grep and read_file over shell commands."; + +const WORKFLOW: &str = "# How to work + +1. Understand the request. If it is unclear in a way that changes the result, ask with ask_user. Otherwise make a sensible choice and mention it. +2. For work with more than two steps, write a short plan with update_plan, keep one step in_progress, and update it as you go. +3. Explore before changing anything: find the relevant files and read them. +4. Make focused changes that follow the project's existing style, naming and structure. Do not reformat or rewrite code the task does not touch. +5. Check your work: build, run or test the code with shell when the project allows it, and fix whatever broke. +6. When a tool call fails, read the error and change your approach. Never repeat a call that failed in exactly the same way. +7. When the user declines a change or a command, do not try it again in another form. Ask what they would like instead. + +Keep going until the task is done. Do not stop between ordinary steps to ask for permission; the app asks the user when it needs to."; + +const GIT: &str = "# Git + +The project uses Git. To commit or open a pull request, use commit_changes and open_pull_request rather than running git yourself. Commit or open a pull request only when the user asks for it. Put work meant for a pull request on a new branch with a short, descriptive name such as fix-login. Write commit messages as one short summary line in the imperative mood, followed by details only when they help."; + +const REPLY: &str = "# Your reply + +When you finish, reply with a short summary of what you changed and how you checked it. The user sees every tool call and diff, so do not paste file contents back. Use Markdown, with fenced code blocks for code. Be direct and concise."; + +pub struct PromptContext<'a> { + pub model: &'a str, + pub root: Option<&'a Path>, + pub tools: &'a [Box], + pub shell: Shell, + pub personal: &'a str, + pub instructions: &'a [String], +} + +fn os_name() -> &'static str { + match std::env::consts::OS { + "windows" => "Windows", + "macos" => "macOS", + "linux" => "Linux", + other => other, + } +} + +pub fn system_prompt(ctx: &PromptContext<'_>) -> String { + let mut sections = vec![format!( + "You are Quill, the coding agent built into quill-code. You run on the user's own {} computer and are powered by the {} model. If the user asks which model you are, say so.", + os_name(), + ctx.model + )]; + match ctx.root { + Some(root) => { + sections.push(format!( + "# Your workspace\n\nYou work in the project folder {}. Paths you give to tools are relative to it. You change files only inside it; reading elsewhere may need the user's OK. Use your tools to do the work rather than describing what you would do.", + root.display() + )); + let lines: Vec = ctx.tools.iter().map(|tool| format!("- {}", tool.spec().guide)).collect(); + sections.push(format!("# Your tools\n\n{}", lines.join("\n"))); + let shell = match ctx.shell { + Shell::PowerShell | Shell::Pwsh => POWERSHELL, + Shell::Cmd => CMD, + Shell::Bash | Shell::Sh => POSIX, + }; + sections.push(format!("{shell}\n\n{COMMAND_RULES}")); + sections.push(WORKFLOW.to_string()); + if ctx.tools.iter().any(|tool| tool.spec().toolset == Toolset::Git) { + sections.push(GIT.to_string()); + } + sections.push(REPLY.to_string()); + let project = project_instructions(root, ctx.instructions); + if !project.is_empty() { + sections.push(format!("# Project instructions\n\n{project}")); + } + } + None => sections.push( + "No project is open in this conversation, so you have no tools. Answer from what you know, and when the user wants you to work on their files, suggest opening a project in quill-code. Use Markdown, with fenced code blocks for code. Be direct and concise.".into(), + ), + } + let personal = ctx.personal.trim(); + if !personal.is_empty() { + sections.push(format!("# The user's instructions\n\n{personal}")); + } + sections.join("\n\n") +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::options::{Limits, Toolsets}; + use crate::tools::enabled; + + fn prompt(root: Option<&Path>, git: bool, personal: &str) -> String { + let tools = enabled(Toolsets { git }, &Limits::default()); + let instructions = vec!["AGENTS.md".to_string()]; + system_prompt(&PromptContext { + model: "qwen", + root, + tools: &tools, + shell: Shell::PowerShell, + personal, + instructions: &instructions, + }) + } + + #[test] + fn quill_is_the_assistant_whatever_the_model() { + let text = prompt(None, false, ""); + assert!(text.starts_with("You are Quill")); + assert!(text.contains("powered by the qwen model")); + assert!(text.contains("no tools")); + } + + #[test] + fn projects_get_tools_shell_and_workflow() { + let dir = std::env::temp_dir(); + let text = prompt(Some(&dir), false, ""); + assert!(text.contains("edit_file") && text.contains("apply_patch") && text.contains("# How to work")); + assert!(text.contains("Windows PowerShell")); + assert!(!text.contains("open_pull_request")); + assert!(prompt(Some(&dir), true, "").contains("open_pull_request")); + assert!(prompt(None, false, "Use tabs.").ends_with("# The user's instructions\n\nUse tabs.")); + } +} \ No newline at end of file diff --git a/crates/quill-core/src/protocol.rs b/crates/quill-core/src/protocol.rs new file mode 100644 index 0000000..4c10063 --- /dev/null +++ b/crates/quill-core/src/protocol.rs @@ -0,0 +1,114 @@ +use quill_providers::{Message, Tokens}; +use serde::{Deserialize, Serialize}; + +use crate::diff::FileDiff; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Category { + Explore, + Edit, + Command, + Plan, + Question, + Git, + Web, + Desktop, + Agent, + Other, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct ToolView { + pub id: String, + pub tool: String, + pub category: Category, + pub active: String, + pub done: String, + pub target: String, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct Approval { + pub title: String, + pub subject: String, + #[serde(default)] + pub diffs: Vec, + #[serde(default)] + pub similar: Option, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Decision { + Approve, + Decline, + AllowSimilar, + AllowTool, + AllowAll, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum StepStatus { + Pending, + Active, + Done, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct PlanStep { + pub text: String, + pub status: StepStatus, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct ClaudeLink { + pub session: String, + pub synced: usize, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "outcome", content = "error", rename_all = "snake_case")] +pub enum Outcome { + Done, + Stopped, + Failed(String), +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(tag = "type", rename_all = "snake_case")] +pub enum Event { + TurnStarted { turn: usize }, + Reasoning { turn: usize, text: String }, + Text { turn: usize, text: String }, + ToolBegin { turn: usize, view: ToolView }, + ToolOutput { turn: usize, id: String, chunk: String }, + ToolEnd { turn: usize, id: String, ok: bool, output: String, diffs: Vec, image: Option }, + ApprovalRequested { turn: usize, id: String, approval: Approval }, + QuestionAsked { turn: usize, id: String, question: String, options: Vec }, + PlanUpdated { turn: usize, steps: Vec, explanation: Option }, + Message { message: Message }, + Compacted { history: Vec }, + Usage { turn: usize, tokens: Tokens }, + Cost { turn: usize, usd: f64 }, + ContextWindow { tokens: u64 }, + ModelResolved { turn: usize, model: String }, + ClaudeSession { link: ClaudeLink }, + TurnFinished { turn: usize, outcome: Outcome }, +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn events_round_trip_as_tagged_json() { + let event = Event::TurnFinished { turn: 2, outcome: Outcome::Failed("boom".into()) }; + let text = serde_json::to_string(&event).unwrap(); + assert!(text.contains("\"type\":\"turn_finished\"") && text.contains("\"outcome\":\"failed\"")); + assert_eq!(serde_json::from_str::(&text).unwrap(), event); + let message = Event::Message { message: Message::user("hi") }; + assert_eq!(serde_json::from_str::(&serde_json::to_string(&message).unwrap()).unwrap(), message); + } +} \ No newline at end of file diff --git a/crates/quill-core/src/session.rs b/crates/quill-core/src/session.rs new file mode 100644 index 0000000..298fe31 --- /dev/null +++ b/crates/quill-core/src/session.rs @@ -0,0 +1,264 @@ +use std::collections::{HashMap, VecDeque}; +use std::path::PathBuf; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::mpsc::{Receiver, RecvTimeoutError, Sender, channel}; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use quill_providers::{Effort, Message, Provider}; + +use crate::claude_code::{self, ClaudeCode}; +use crate::options::{Limits, Toolsets}; +use crate::policy::{Access, Rule}; +use crate::protocol::{ClaudeLink, Decision, Event, Outcome}; +use crate::turn; + +#[derive(Clone)] +pub enum Engine { + Model(Arc), + ClaudeCode(ClaudeCode), +} + +#[derive(Clone)] +pub struct Summarizer { + pub provider: Arc, + pub model: String, +} + +#[derive(Clone)] +pub struct TurnContext { + pub engine: Engine, + pub summarizer: Option, + pub model: String, + pub thinking: Option, + pub effort: Option, + pub max_output: Option, + pub server_compaction: bool, + pub context_window: Option, + pub root: Option, + pub access: Access, + pub toolsets: Toolsets, + pub personal: String, + pub instructions: Vec, + pub limits: Limits, + pub rules: Vec, +} + +pub struct Input { + pub text: String, + pub images: Vec, +} + +pub enum Op { + Turn { turn: usize, input: Input, context: TurnContext, cancel: Arc }, + Steer(String), + Decide { id: String, decision: Decision }, + Answer { id: String, text: String }, + Compact { context: TurnContext, cancel: Arc }, + Shutdown, +} + +#[derive(Clone)] +pub struct SessionHandle { + ops: Sender, +} + +impl SessionHandle { + pub fn send(&self, op: Op) -> bool { + self.ops.send(op).is_ok() + } +} + +pub(crate) type Sink = Arc; + +pub fn spawn(history: Vec, sink: impl Fn(Event) + Send + Sync + 'static) -> SessionHandle { + let (ops, rx) = channel(); + let session = Session { + history, + inbox: Mutex::new(Inbox { + rx, + queue: VecDeque::new(), + steers: Vec::new(), + decisions: HashMap::new(), + answers: HashMap::new(), + closed: false, + }), + sink: Arc::new(sink), + rules: Mutex::new(Vec::new()), + raised: AtomicBool::new(false), + used: None, + claude: None, + link: None, + }; + std::thread::Builder::new().name("quill-session".into()).spawn(move || session.run()).expect("start a session thread"); + SessionHandle { ops } +} + +pub(crate) struct Inbox { + rx: Receiver, + queue: VecDeque, + steers: Vec, + decisions: HashMap, + answers: HashMap, + closed: bool, +} + +impl Inbox { + fn take(&mut self, op: Op) -> Option { + match op { + Op::Steer(text) => self.steers.push(text), + Op::Decide { id, decision } => { + self.decisions.insert(id, decision); + } + Op::Answer { id, text } => { + self.answers.insert(id, text); + } + Op::Shutdown => self.closed = true, + other => return Some(other), + } + None + } + + fn take_running(&mut self, op: Op) { + if let Some(op) = self.take(op) { + self.queue.push_back(op); + } + } + + pub fn pump(&mut self) { + while let Ok(op) = self.rx.try_recv() { + self.take_running(op); + } + } + + pub fn steers(&mut self) -> Vec { + self.pump(); + std::mem::take(&mut self.steers) + } + + fn wait(&mut self, cancel: &AtomicBool, mut found: impl FnMut(&mut Inbox) -> Option) -> Option { + loop { + if let Some(value) = found(self) { + return Some(value); + } + if self.closed || cancel.load(Ordering::Relaxed) { + return None; + } + match self.rx.recv_timeout(Duration::from_millis(100)) { + Ok(op) => self.take_running(op), + Err(RecvTimeoutError::Timeout) => {} + Err(RecvTimeoutError::Disconnected) => self.closed = true, + } + } + } + + pub fn decision(&mut self, id: &str, cancel: &AtomicBool) -> Decision { + self.wait(cancel, |inbox| inbox.decisions.remove(id)).unwrap_or(Decision::Decline) + } + + pub fn answer(&mut self, id: &str, cancel: &AtomicBool) -> Option { + self.wait(cancel, |inbox| inbox.answers.remove(id)) + } + + fn next(&mut self) -> Option { + if let Some(op) = self.queue.pop_front() { + return Some(op); + } + while !self.closed { + match self.rx.recv() { + Ok(op) => { + if let Some(op) = self.take(op) { + return Some(op); + } + } + Err(_) => return None, + } + } + None + } +} + +pub(crate) struct Session { + pub history: Vec, + pub inbox: Mutex, + pub sink: Sink, + pub rules: Mutex>, + pub raised: AtomicBool, + pub used: Option, + pub claude: Option, + pub link: Option, +} + +impl Session { + fn run(mut self) { + loop { + let op = self.inbox.lock().expect("inbox lock").next(); + match op { + Some(Op::Turn { turn, input, context, cancel }) => { + self.emit(Event::TurnStarted { turn }); + let outcome = match &context.engine { + Engine::Model(provider) => turn::run(&mut self, turn, input, &context, provider.as_ref(), &cancel), + Engine::ClaudeCode(claude) => claude_code::run(&mut self, turn, input, &context, claude, &cancel), + }; + let outcome = if cancel.load(Ordering::Relaxed) && outcome == Outcome::Done { Outcome::Stopped } else { outcome }; + self.emit(Event::TurnFinished { turn, outcome }); + } + Some(Op::Compact { context, cancel }) => { + let _ = self.compact(&context, &cancel); + } + Some(_) => {} + None => break, + } + } + } + + pub fn emit(&self, event: Event) { + (self.sink)(event); + } + + pub fn push(&mut self, message: Message) { + self.history.push(message.clone()); + self.emit(Event::Message { message }); + } + + pub fn take_steers(&mut self) -> bool { + let steers = self.inbox.lock().expect("inbox lock").steers(); + let any = !steers.is_empty(); + for text in steers { + self.push(Message::user(text)); + } + any + } + + pub fn compact(&mut self, ctx: &TurnContext, cancel: &AtomicBool) -> Result<(), String> { + let Engine::Model(provider) = &ctx.engine else { + return Err("Claude Code keeps its own context and compacts it when it needs to.".into()); + }; + let mut changed = false; + if let Some(cut) = crate::context::cut(&self.history) { + let summary = match &ctx.summarizer { + Some(other) => { + crate::context::summarize(other.provider.as_ref(), &other.model, None, ctx.context_window, &self.history[..cut], cancel) + } + None => { + crate::context::summarize(provider.as_ref(), &ctx.model, ctx.effort, ctx.context_window, &self.history[..cut], cancel) + } + }; + if let Ok(summary) = summary { + let tail = self.history.split_off(cut); + self.history = crate::context::join(&summary, tail); + changed = true; + } + } + changed |= crate::context::trim_outputs(&mut self.history, 6); + if !changed { + return Err("There was nothing to compact.".into()); + } + for message in &mut self.history { + message.native = None; + } + self.used = None; + self.emit(Event::Compacted { history: self.history.clone() }); + Ok(()) + } +} \ No newline at end of file diff --git a/crates/quill-core/src/tools/args.rs b/crates/quill-core/src/tools/args.rs new file mode 100644 index 0000000..0712814 --- /dev/null +++ b/crates/quill-core/src/tools/args.rs @@ -0,0 +1,66 @@ +use serde_json::{Value, json}; + +pub const PATH: [&str; 6] = ["path", "file_path", "file", "filename", "filepath", "dir"]; +pub const CONTENT: [&str; 6] = ["content", "contents", "text", "file_text", "code", "body"]; +pub const OLD: [&str; 6] = ["old_text", "old_str", "old_string", "old", "search", "find"]; +pub const NEW: [&str; 6] = ["new_text", "new_str", "new_string", "new", "replace", "replacement"]; +pub const COMMAND: [&str; 3] = ["command", "cmd", "script"]; +pub const PATTERN: [&str; 5] = ["pattern", "query", "regex", "text", "q"]; +pub const GLOB: [&str; 3] = ["glob", "include", "file_pattern"]; +pub const MESSAGE: [&str; 3] = ["message", "commit_message", "msg"]; +pub const BRANCH: [&str; 3] = ["branch", "branch_name", "new_branch"]; +pub const TITLE: [&str; 2] = ["title", "pr_title"]; +pub const BODY: [&str; 3] = ["body", "description", "pr_body"]; +pub const PATCH: [&str; 4] = ["patch", "input", "diff", "content"]; + +pub fn parse(arguments: &str) -> Value { + let text = arguments.trim(); + if text.is_empty() { + return json!({}); + } + serde_json::from_str(text).unwrap_or_else(|_| json!({ "__invalid": text })) +} + +pub fn invalid(args: &Value) -> Option<&str> { + args.get("__invalid").and_then(Value::as_str) +} + +pub fn text<'a>(args: &'a Value, keys: &[&str]) -> Option<&'a str> { + keys.iter().find_map(|key| args.get(*key).and_then(Value::as_str)) +} + +pub fn trimmed<'a>(args: &'a Value, keys: &[&str]) -> Option<&'a str> { + text(args, keys).map(str::trim).filter(|value| !value.is_empty()) +} + +pub fn number(args: &Value, keys: &[&str]) -> Option { + keys.iter().find_map(|key| { + let value = args.get(*key)?; + value.as_u64().or_else(|| value.as_str()?.trim().parse().ok()) + }) +} + +pub fn flag(args: &Value, keys: &[&str]) -> bool { + keys.iter().any(|key| args.get(*key).is_some_and(|v| v.as_bool().unwrap_or_else(|| v.as_str() == Some("true")))) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn broken_arguments_are_kept_for_the_error() { + assert_eq!(parse("{\"path\": \"a\"}")["path"], "a"); + assert!(invalid(&parse("{oops")).is_some()); + assert_eq!(parse(""), json!({})); + } + + #[test] + fn lenient_keys_and_values_are_read() { + let args = json!({ "file_path": "a.rs", "start": "4", "replace_all": "true" }); + assert_eq!(text(&args, &PATH), Some("a.rs")); + assert_eq!(number(&args, &["start_line", "start"]), Some(4)); + assert!(flag(&args, &["replace_all"])); + assert!(!flag(&args, &["missing"])); + } +} \ No newline at end of file diff --git a/crates/quill-core/src/tools/fs.rs b/crates/quill-core/src/tools/fs.rs new file mode 100644 index 0000000..f8794d6 --- /dev/null +++ b/crates/quill-core/src/tools/fs.rs @@ -0,0 +1,757 @@ +use std::fs; +use std::path::{Path, PathBuf}; + +use globset::{GlobBuilder, GlobSet, GlobSetBuilder}; +use ignore::WalkBuilder; +use regex::RegexBuilder; +use serde_json::{Value, json}; + +use super::args::{self, CONTENT, GLOB, NEW, OLD, PATH, PATTERN}; +use super::paths::{display, inside, normalize, resolve}; +use super::{Action, Ctx, Output, Prepared, Spec, Tool, Toolset}; +use crate::diff::{FileDiff, diff_text}; +use crate::options::Limits; +use crate::policy::Effect; +use crate::protocol::Category; + +const MAX_FILE: u64 = 1_000_000; + +fn walker(dir: &Path, limits: &Limits, depth: Option) -> ignore::Walk { + let ignored = limits.ignored.clone(); + let mut builder = WalkBuilder::new(dir); + builder + .hidden(false) + .require_git(false) + .max_depth(depth) + .filter_entry(move |entry| { + let dir = entry.file_type().is_some_and(|t| t.is_dir()); + !(dir && entry.depth() > 0 && ignored.iter().any(|name| entry.file_name().to_string_lossy().eq_ignore_ascii_case(name))) + }) + .sort_by_file_path(|a, b| { + b.is_dir().cmp(&a.is_dir()).then_with(|| a.to_string_lossy().to_lowercase().cmp(&b.to_string_lossy().to_lowercase())) + }); + builder.build() +} + +fn files(dir: &Path, limits: &Limits) -> Vec { + walker(dir, limits, None) + .filter_map(Result::ok) + .filter(|entry| entry.file_type().is_some_and(|t| t.is_file())) + .map(|entry| entry.into_path()) + .collect() +} + +fn read_text(path: &Path) -> Result { + let bytes = fs::read(path).map_err(|e| e.to_string())?; + if bytes.iter().take(8192).any(|b| *b == 0) { + return Err("That is a binary file, so it cannot be shown as text.".into()); + } + Ok(String::from_utf8_lossy(&bytes).into_owned()) +} + +fn locate(root: &Path, args: &Value) -> Result<(PathBuf, Effect), String> { + let path = normalize(root, args::text(args, &PATH).unwrap_or_default())?; + let effect = if inside(&path, root) { Effect::Read } else { Effect::ReadOutside }; + Ok((path, effect)) +} + +fn reading(effect: Effect, path: &Path, action: Action) -> Prepared { + match effect { + Effect::Read => Prepared::read(action), + _ => Prepared::new(effect, path.display().to_string(), "Wants to read outside the project", action), + } +} + +fn glob_set(pattern: &str) -> Result { + let mut builder = GlobSetBuilder::new(); + for part in pattern.split(',').map(str::trim).filter(|part| !part.is_empty()) { + let glob = GlobBuilder::new(&part.replace('\\', "/")).case_insensitive(true).build().map_err(|e| e.to_string())?; + builder.add(glob); + } + builder.build().map_err(|e| e.to_string()) +} + +fn clip_line(line: &str) -> String { + let trimmed = line.trim(); + if trimmed.chars().count() > 300 { format!("{}…", trimmed.chars().take(300).collect::()) } else { trimmed.to_string() } +} + +pub struct ListDir; + +const LIST: Spec = Spec { + name: "list_dir", + title: "List folders", + summary: "Shows how a folder is laid out, skipping ignored folders.", + aliases: &["list_files", "list", "ls", "list_directory", "tree"], + toolset: Toolset::Core, + category: Category::Explore, + active: "Looking through", + done: "Looked through", + parallel: true, + description: "List the files and folders in a folder as a tree. Folders such as node_modules and anything in .gitignore are skipped. Use it first to see how a project is laid out.", + guide: "list_dir shows how a folder is laid out. Start with it in a project you have not seen.", +}; + +impl Tool for ListDir { + fn spec(&self) -> &'static Spec { + &LIST + } + + fn parameters(&self) -> Value { + json!({ + "type": "object", + "properties": { + "path": { "type": "string", "description": "Folder relative to the project root. Leave empty for the root." }, + "depth": { "type": "integer", "description": "How many levels to show, from 1 to 5. Default 2." } + } + }) + } + + fn target(&self, args: &Value) -> String { + args::trimmed(args, &PATH).map_or(".".into(), |path| path.replace('\\', "/")) + } + + fn prepare(&self, args: &Value, ctx: &Ctx<'_>) -> Result { + let (dir, effect) = locate(ctx.root, args)?; + let depth = args::number(args, &["depth", "levels", "max_depth"]).unwrap_or(2).clamp(1, 5) as usize; + let root = ctx.root.to_path_buf(); + let shown = dir.clone(); + Ok(reading(effect, &shown, Box::new(move |ctx: &Ctx<'_>| Output::settle(list(&root, &dir, depth, ctx.limits))))) + } +} + +fn list(root: &Path, dir: &Path, depth: usize, limits: &Limits) -> Result { + if !dir.is_dir() { + return Err(format!("{} is not a folder.", display(root, dir))); + } + let mut lines = Vec::new(); + let mut more = 0; + for entry in walker(dir, limits, Some(depth)).filter_map(Result::ok).filter(|entry| entry.depth() > 0) { + if lines.len() >= limits.max_list { + more += 1; + continue; + } + let indent = " ".repeat(entry.depth() - 1); + let slash = if entry.file_type().is_some_and(|t| t.is_dir()) { "/" } else { "" }; + lines.push(format!("{indent}{}{slash}", entry.file_name().to_string_lossy())); + } + if lines.is_empty() { + return Ok("The folder is empty.".into()); + } + if more > 0 { + lines.push(format!("... and {more} more entries. List a subfolder to see them.")); + } + Ok(lines.join("\n")) +} + +pub struct FindFiles; + +const FIND: Spec = Spec { + name: "find_files", + title: "Find files", + summary: "Finds files by name or path pattern.", + aliases: &["glob", "find", "find_file", "file_search", "find_by_name"], + toolset: Toolset::Core, + category: Category::Explore, + active: "Looking for", + done: "Looked for", + parallel: true, + description: "Find files whose path matches a glob pattern such as **/*.rs or src/**/test_*.py, case-insensitive. Separate several patterns with commas.", + guide: "find_files finds files by name or path pattern.", +}; + +impl Tool for FindFiles { + fn spec(&self) -> &'static Spec { + &FIND + } + + fn parameters(&self) -> Value { + json!({ + "type": "object", + "properties": { + "pattern": { "type": "string", "description": "Glob pattern, for example **/*.tsx or *config*." }, + "path": { "type": "string", "description": "Optional folder to search in." } + }, + "required": ["pattern"] + }) + } + + fn target(&self, args: &Value) -> String { + args::trimmed(args, &PATTERN).unwrap_or_default().to_string() + } + + fn prepare(&self, args: &Value, ctx: &Ctx<'_>) -> Result { + let pattern = args::trimmed(args, &PATTERN).ok_or("find_files needs a \"pattern\", such as **/*.rs.")?.to_string(); + let set = glob_set(&pattern)?; + let (dir, effect) = locate(ctx.root, args)?; + let root = ctx.root.to_path_buf(); + let shown = dir.clone(); + Ok(reading( + effect, + &shown, + Box::new(move |ctx: &Ctx<'_>| { + let mut found = Vec::new(); + let mut extra = 0; + for path in files(&dir, ctx.limits) { + let rel = display(&dir, &path); + if set.is_match(&rel) { + if found.len() < ctx.limits.max_matches { + found.push(display(&root, &path)); + } else { + extra += 1; + } + } + } + if found.is_empty() { + return Output::ok(format!("No files match \"{pattern}\".")); + } + if extra > 0 { + found.push(format!("... and {extra} more files. Use a narrower pattern.")); + } + Output::ok(found.join("\n")) + }), + )) + } +} + +pub struct Grep; + +const GREP: Spec = Spec { + name: "grep", + title: "Search files", + summary: "Searches file contents for text or a pattern.", + aliases: &["search", "search_files", "find_in_files", "search_code", "rg", "ripgrep", "grep_search"], + toolset: Toolset::Core, + category: Category::Explore, + active: "Searching for", + done: "Searched for", + parallel: true, + description: "Search the contents of every text file for a regular expression, case-insensitive unless case_sensitive is true. Returns path:line: text for each match. Plain text works too.", + guide: "grep searches file contents with a regular expression. Use it to find where something is defined or used.", +}; + +impl Tool for Grep { + fn spec(&self) -> &'static Spec { + &GREP + } + + fn parameters(&self) -> Value { + json!({ + "type": "object", + "properties": { + "pattern": { "type": "string", "description": "Regular expression or plain text to look for." }, + "path": { "type": "string", "description": "Optional folder or file to search in." }, + "glob": { "type": "string", "description": "Optional file filter, for example *.rs." }, + "case_sensitive": { "type": "boolean", "description": "Match letter case exactly. Default false." }, + "context": { "type": "integer", "description": "Lines of context to show around each match, 0 to 5. Default 0." } + }, + "required": ["pattern"] + }) + } + + fn target(&self, args: &Value) -> String { + args::text(args, &PATTERN).unwrap_or_default().to_string() + } + + fn prepare(&self, args: &Value, ctx: &Ctx<'_>) -> Result { + let pattern = args::text(args, &PATTERN).filter(|p| !p.trim().is_empty()).ok_or("grep needs a \"pattern\".")?.to_string(); + let case_sensitive = args::flag(args, &["case_sensitive", "match_case"]); + let regex = RegexBuilder::new(&pattern) + .case_insensitive(!case_sensitive) + .build() + .or_else(|_| RegexBuilder::new(®ex::escape(&pattern)).case_insensitive(!case_sensitive).build()) + .map_err(|e| e.to_string())?; + let filter = args::trimmed(args, &GLOB).map(glob_set).transpose()?; + let context = args::number(args, &["context", "context_lines", "-C"]).unwrap_or(0).min(5) as usize; + let (base, effect) = locate(ctx.root, args)?; + let root = ctx.root.to_path_buf(); + let shown = base.clone(); + Ok(reading( + effect, + &shown, + Box::new(move |ctx: &Ctx<'_>| { + let candidates = if base.is_file() { vec![base.clone()] } else { files(&base, ctx.limits) }; + let mut out = Vec::new(); + let mut matches = 0; + let mut extra = 0; + for file in candidates { + if filter.as_ref().is_some_and(|set| !set.is_match(display(&base, &file))) { + continue; + } + if fs::metadata(&file).map_or(true, |m| m.len() > MAX_FILE) { + continue; + } + let Ok(text) = read_text(&file) else { continue }; + let lines: Vec<&str> = text.lines().collect(); + let rel = display(&root, &file); + let mut printed: Option = None; + for (index, line) in lines.iter().enumerate() { + if !regex.is_match(line) { + continue; + } + if matches >= ctx.limits.max_matches { + extra += 1; + continue; + } + matches += 1; + let from = index.saturating_sub(context); + let to = (index + context).min(lines.len() - 1); + if context > 0 && printed.is_some_and(|last| from > last + 1) { + out.push("--".to_string()); + } + for (n, text) in lines.iter().enumerate().take(to + 1).skip(from) { + if printed.is_some_and(|last| n <= last) { + continue; + } + let sep = if n == index { ':' } else { '-' }; + out.push(format!("{rel}{sep}{}{sep} {}", n + 1, clip_line(text))); + printed = Some(n); + } + } + } + if out.is_empty() { + return Output::ok(format!("No matches for \"{pattern}\".")); + } + if extra > 0 { + out.push(format!("... and {extra} more matches. Narrow the search with a longer pattern, a path or a glob.")); + } + Output::ok(out.join("\n")) + }), + )) + } +} + +pub struct ReadFile; + +const READ: Spec = Spec { + name: "read_file", + title: "Read files", + summary: "Reads a file, or part of one, with line numbers.", + aliases: &["read", "view", "cat", "open_file", "view_file", "get_file"], + toolset: Toolset::Core, + category: Category::Explore, + active: "Reading", + done: "Read", + parallel: true, + description: "Read a text file with line numbers. Read a file before changing it. In a large file, read only the lines you need with start_line and end_line.", + guide: "read_file reads a file with line numbers. Read a file before you change it, and in a large file read only the lines you need.", +}; + +impl Tool for ReadFile { + fn spec(&self) -> &'static Spec { + &READ + } + + fn parameters(&self) -> Value { + json!({ + "type": "object", + "properties": { + "path": { "type": "string", "description": "File path relative to the project root." }, + "start_line": { "type": "integer", "description": "First line to show, starting at 1." }, + "end_line": { "type": "integer", "description": "Last line to show." } + }, + "required": ["path"] + }) + } + + fn target(&self, args: &Value) -> String { + args::text(args, &PATH).unwrap_or_default().trim().replace('\\', "/") + } + + fn prepare(&self, args: &Value, ctx: &Ctx<'_>) -> Result { + args::trimmed(args, &PATH).ok_or("read_file needs a \"path\".")?; + let (path, effect) = locate(ctx.root, args)?; + let start = args::number(args, &["start_line", "offset", "start", "from", "line"]).unwrap_or(1).max(1) as usize; + let end = args::number(args, &["end_line", "end", "to"]) + .map(|end| end as usize) + .or_else(|| args::number(args, &["limit", "lines", "count"]).map(|n| start + n as usize - 1)); + let root = ctx.root.to_path_buf(); + let shown = path.clone(); + Ok(reading(effect, &shown, Box::new(move |ctx: &Ctx<'_>| Output::settle(read(&root, &path, start, end, ctx.limits))))) + } +} + +fn read(root: &Path, path: &Path, start: usize, end: Option, limits: &Limits) -> Result { + if path.is_dir() { + return Err(format!("{} is a folder. Use list_dir to see what is in it.", display(root, path))); + } + if !path.is_file() { + return Err(format!("{} does not exist. Use list_dir or find_files to see what is there.", display(root, path))); + } + let text = read_text(path)?; + let lines: Vec<&str> = text.lines().collect(); + if lines.is_empty() { + return Ok("The file is empty.".into()); + } + if start > lines.len() { + return Err(format!("The file only has {} lines.", lines.len())); + } + let end = end.unwrap_or(lines.len()).min(lines.len()).min(start + limits.max_read_lines - 1).max(start); + let mut out: Vec = (start..=end) + .map(|n| if lines[n - 1].trim().is_empty() { format!("{n:>5}") } else { format!("{n:>5} {}", lines[n - 1]) }) + .collect(); + if end < lines.len() || start > 1 { + out.push(format!("(showing lines {start}-{end} of {}; pass start_line to read more)", lines.len())); + } + Ok(out.join("\n")) +} + +struct Change { + path: PathBuf, + after: String, + diff: FileDiff, +} + +fn planned(change: Change, title: &str) -> Prepared { + let summary = |diff: &FileDiff| { + let verb = if diff.created { "Created" } else { "Updated" }; + format!("{verb} {} (+{} -{})", diff.path, diff.added, diff.removed) + }; + let diff = change.diff.clone(); + let mut prepared = Prepared::new( + Effect::Write, + diff.path.clone(), + title, + Box::new(move |_: &Ctx<'_>| match write(&change.path, &change.after) { + Ok(()) => Output { diffs: vec![change.diff.clone()], ..Output::ok(summary(&change.diff)) }, + Err(error) => Output::fail(error), + }), + ); + prepared.approval.diffs = vec![diff]; + prepared +} + +pub fn write(path: &Path, text: &str) -> Result<(), String> { + if let Some(dir) = path.parent() { + fs::create_dir_all(dir).map_err(|e| e.to_string())?; + } + fs::write(path, text).map_err(|e| e.to_string()) +} + +fn target_file(root: &Path, args: &Value, tool: &str) -> Result<(PathBuf, Option), String> { + let rel = args::trimmed(args, &PATH).ok_or(format!("{tool} needs a \"path\"."))?; + let path = resolve(root, rel)?; + if path.is_dir() { + return Err(format!("{} is a folder, not a file.", display(root, &path))); + } + let before = if path.is_file() { Some(read_text(&path)?) } else { None }; + Ok((path, before)) +} + +pub struct WriteFile; + +const WRITE: Spec = Spec { + name: "write_file", + title: "Write files", + summary: "Creates a file or replaces a whole file.", + aliases: &["write", "create_file", "save_file", "create"], + toolset: Toolset::Core, + category: Category::Edit, + active: "Writing", + done: "Wrote", + parallel: false, + description: "Create a file or replace its whole content. Use it for new files; prefer edit_file or apply_patch for changes to existing files.", + guide: "write_file creates a new file or replaces a whole file.", +}; + +impl Tool for WriteFile { + fn spec(&self) -> &'static Spec { + &WRITE + } + + fn parameters(&self) -> Value { + json!({ + "type": "object", + "properties": { + "path": { "type": "string", "description": "File path relative to the project root." }, + "content": { "type": "string", "description": "The complete content of the file." } + }, + "required": ["path", "content"] + }) + } + + fn target(&self, args: &Value) -> String { + args::text(args, &PATH).unwrap_or_default().trim().replace('\\', "/") + } + + fn prepare(&self, args: &Value, ctx: &Ctx<'_>) -> Result { + let (path, before) = target_file(ctx.root, args, "write_file")?; + let after = args::text(args, &CONTENT).ok_or("write_file needs \"content\": the complete text of the file.")?.to_string(); + let diff = diff_text(&display(ctx.root, &path), before.as_deref(), &after); + let title = if diff.created { "Wants to create a file" } else { "Wants to rewrite a file" }; + Ok(planned(Change { path, after, diff }, title)) + } +} + +pub struct EditFile; + +const EDIT: Spec = Spec { + name: "edit_file", + title: "Edit files", + summary: "Replaces exact text in a file, one or several places at once.", + aliases: &["edit", "str_replace", "replace_in_file", "apply_edit", "multi_edit", "multiedit"], + toolset: Toolset::Core, + category: Category::Edit, + active: "Editing", + done: "Edited", + parallel: false, + description: "Replace exact text in a file. old_text must match the file exactly, including spaces, and appear once unless replace_all is true. To make several changes to one file at once, pass edits: a list of {old_text, new_text, replace_all}. All edits apply or none do.", + guide: "edit_file replaces exact text in a file. Copy old_text exactly from read_file output without the line numbers, with enough surrounding lines to make it unique. Pass edits to change several places at once.", +}; + +impl Tool for EditFile { + fn spec(&self) -> &'static Spec { + &EDIT + } + + fn parameters(&self) -> Value { + json!({ + "type": "object", + "properties": { + "path": { "type": "string", "description": "File path relative to the project root." }, + "old_text": { "type": "string", "description": "Exact text to replace, copied from the file." }, + "new_text": { "type": "string", "description": "Replacement text. Use an empty string to delete." }, + "replace_all": { "type": "boolean", "description": "Replace every occurrence." }, + "edits": { + "type": "array", + "description": "Several replacements in one file, applied in order.", + "items": { + "type": "object", + "properties": { + "old_text": { "type": "string" }, + "new_text": { "type": "string" }, + "replace_all": { "type": "boolean" } + }, + "required": ["old_text", "new_text"] + } + } + }, + "required": ["path"] + }) + } + + fn target(&self, args: &Value) -> String { + args::text(args, &PATH).unwrap_or_default().trim().replace('\\', "/") + } + + fn prepare(&self, args: &Value, ctx: &Ctx<'_>) -> Result { + let (path, before) = target_file(ctx.root, args, "edit_file")?; + let current = before.as_deref().ok_or(format!("{} does not exist. Use write_file to create it.", display(ctx.root, &path)))?; + let edits = edits(args)?; + let mut after = current.to_string(); + for (index, (old, new, all)) in edits.iter().enumerate() { + after = replace(&after, old, new, *all) + .map_err(|error| if edits.len() > 1 { format!("Edit {}: {error}", index + 1) } else { error })?; + } + let diff = diff_text(&display(ctx.root, &path), before.as_deref(), &after); + Ok(planned(Change { path, after, diff }, "Wants to change a file")) + } +} + +fn edits(args: &Value) -> Result, String> { + let one = |value: &Value| -> Result<(String, String, bool), String> { + let old = args::text(value, &OLD).ok_or("edit_file needs \"old_text\", copied exactly from the file.")?; + let new = args::text(value, &NEW).ok_or("edit_file needs \"new_text\". Use an empty string to delete.")?; + Ok((old.to_string(), new.to_string(), args::flag(value, &["replace_all", "all"]))) + }; + match args.get("edits").and_then(Value::as_array) { + Some(list) if !list.is_empty() => list.iter().map(one).collect(), + _ => Ok(vec![one(args)?]), + } +} + +pub fn replace(current: &str, old: &str, new: &str, all: bool) -> Result { + if old.is_empty() { + return Err("old_text is empty. Copy the exact text you want to replace from the file.".into()); + } + let crlf = current.contains("\r\n") && !old.contains("\r\n"); + let (old, new) = if crlf { (old.replace('\n', "\r\n"), new.replace('\n', "\r\n")) } else { (old.to_string(), new.to_string()) }; + match current.matches(old.as_str()).count() { + 0 => loose_replace(current, &old, &new).ok_or_else(|| { + "old_text was not found in the file. Read the file again and copy the text exactly, including indentation.".into() + }), + 1 => Ok(current.replacen(old.as_str(), &new, 1)), + _ if all => Ok(current.replace(old.as_str(), &new)), + n => Err(format!("old_text appears {n} times. Include more surrounding lines so it is unique, or set replace_all.")), + } +} + +fn without_numbers(text: &str) -> String { + let lines: Vec<&str> = text.lines().collect(); + let numbered: Vec> = lines + .iter() + .map(|line| { + let trimmed = line.trim_start(); + let digits = trimmed.chars().take_while(char::is_ascii_digit).count(); + let number = trimmed[..digits].parse().ok()?; + let rest = &trimmed[digits..]; + let body = rest.strip_prefix(" ").or_else(|| rest.strip_prefix('\t')).or_else(|| rest.strip_prefix('→')); + match body { + Some(body) => Some((number, body)), + None if rest.trim().is_empty() => Some((number, "")), + None => None, + } + }) + .collect(); + let consecutive = numbered.windows(2).all(|pair| matches!(pair, [Some((a, _)), Some((b, _))] if b == &(a + 1))); + if lines.is_empty() || numbered.iter().any(Option::is_none) || !consecutive { + return text.to_string(); + } + numbered.into_iter().flatten().map(|(_, body)| body).collect::>().join("\n") +} + +fn loose_replace(current: &str, old: &str, new: &str) -> Option { + let old = without_numbers(old.trim_matches(['\r', '\n'])); + let new = without_numbers(new.trim_matches(['\r', '\n'])); + let wanted: Vec<&str> = old.lines().collect(); + let lines: Vec<&str> = current.lines().collect(); + if wanted.is_empty() || wanted.len() > lines.len() { + return None; + } + for pass in 0..2 { + let same = |a: &str, b: &str| if pass == 0 { a.trim_end() == b.trim_end() } else { a.trim() == b.trim() }; + let hits: Vec = + (0..=lines.len() - wanted.len()).filter(|at| wanted.iter().enumerate().all(|(k, want)| same(lines[at + k], want))).collect(); + if let [at] = hits.as_slice() { + let sep = if current.contains("\r\n") { "\r\n" } else { "\n" }; + let mut out: Vec<&str> = lines[..*at].to_vec(); + out.extend(new.lines()); + out.extend(&lines[at + wanted.len()..]); + let mut text = out.join(sep); + if current.ends_with('\n') && !text.is_empty() { + text.push_str(sep); + } + return Some(text); + } + if hits.len() > 1 { + return None; + } + } + None +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::protocol::PlanStep; + use crate::tools::Host; + use std::sync::atomic::AtomicBool; + + struct Quiet; + + impl Host for Quiet { + fn output(&self, _: &str) {} + fn plan(&self, _: Vec, _: Option) {} + fn ask(&self, _: &str, _: &[String]) -> Option { + None + } + } + + fn temp_root(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("quill-tools-{name}-{}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(&dir).unwrap(); + dir + } + + fn run(tool: &dyn Tool, root: &Path, args: Value) -> Result { + let limits = Limits::default(); + let cancel = AtomicBool::new(false); + let ctx = Ctx { root, limits: &limits, cancel: &cancel, host: &Quiet }; + let prepared = tool.prepare(&args, &ctx)?; + Ok((prepared.action)(&ctx)) + } + + #[test] + fn edits_need_a_unique_match() { + assert_eq!(replace("a b a", "b", "c", false).unwrap(), "a c a"); + assert!(replace("a b a", "a", "c", false).unwrap_err().contains("2 times")); + assert_eq!(replace("a b a", "a", "c", true).unwrap(), "c b c"); + assert!(replace("x", "y", "z", false).is_err()); + assert_eq!(replace("one\r\ntwo\r\n", "one\ntwo", "1\n2", false).unwrap(), "1\r\n2\r\n"); + } + + #[test] + fn small_model_mistakes_still_edit() { + let file = "def greet(name):\n return \"Hello \" + name\n\nprint(greet(\"world\"))\n"; + let spaces = "def greet(name):\n return \"Hello \" + name\n \nprint(greet(\"world\"))"; + let fixed = replace(file, spaces, "def greet(name):\n return \"Hi \" + name\n\nprint(greet(\"world\"))", false).unwrap(); + assert_eq!(fixed, "def greet(name):\n return \"Hi \" + name\n\nprint(greet(\"world\"))\n"); + let numbered = " 1 def greet(name):\n 2 return \"Hello \" + name"; + let fixed = replace(file, numbered, "def greet(person):\n return \"Hello \" + person", false).unwrap(); + assert!(fixed.starts_with("def greet(person):\n return \"Hello \" + person\n\n")); + let indented = " def greet(name):\n return \"Hello \" + name"; + assert!(replace(file, indented, "x", false).unwrap().starts_with("x\n")); + assert!(replace("a\nb\na\nb\n", "a \nb", "c", false).is_err()); + } + + #[test] + fn empty_lines_show_no_trailing_spaces() { + let root = temp_root("blank"); + fs::write(root.join("a.txt"), "one\n\ntwo\n").unwrap(); + let text = run(&ReadFile, &root, json!({ "path": "a.txt" })).unwrap().text; + assert!(text.lines().nth(1) == Some(" 2"), "{text:?}"); + fs::remove_dir_all(&root).unwrap(); + } + + #[test] + fn files_are_written_edited_listed_and_searched() { + let root = temp_root("write"); + let created = run(&WriteFile, &root, json!({ "path": "src/a.txt", "content": "hi\n" })).unwrap(); + assert!(created.ok && created.diffs[0].created); + let edited = run(&EditFile, &root, json!({ "file_path": "src/a.txt", "old_str": "hi", "new_str": "hello" })).unwrap(); + assert_eq!((edited.diffs[0].added, edited.diffs[0].removed), (1, 1)); + assert_eq!(fs::read_to_string(root.join("src/a.txt")).unwrap(), "hello\n"); + let listing = run(&ListDir, &root, json!({})).unwrap().text; + assert!(listing.contains("src/") && listing.contains(" a.txt"), "{listing}"); + assert!(run(&ReadFile, &root, json!({ "path": "src/a.txt" })).unwrap().text.contains(" 1 hello")); + assert!(run(&Grep, &root, json!({ "pattern": "HELLO" })).unwrap().text.contains("src/a.txt:1: hello")); + assert!(run(&FindFiles, &root, json!({ "pattern": "**/*.txt" })).unwrap().text.contains("src/a.txt")); + fs::remove_dir_all(&root).unwrap(); + } + + #[test] + fn several_edits_apply_together_or_not_at_all() { + let root = temp_root("multi"); + fs::write(root.join("a.txt"), "one\ntwo\nthree\n").unwrap(); + let edits = json!({ "path": "a.txt", "edits": [ + { "old_text": "one", "new_text": "1" }, + { "old_text": "three", "new_text": "3" } + ]}); + assert!(run(&EditFile, &root, edits).unwrap().ok); + assert_eq!(fs::read_to_string(root.join("a.txt")).unwrap(), "1\ntwo\n3\n"); + let broken = json!({ "path": "a.txt", "edits": [ + { "old_text": "two", "new_text": "2" }, + { "old_text": "missing", "new_text": "x" } + ]}); + assert!(run(&EditFile, &root, broken).unwrap_err().starts_with("Edit 2:")); + assert_eq!(fs::read_to_string(root.join("a.txt")).unwrap(), "1\ntwo\n3\n"); + fs::remove_dir_all(&root).unwrap(); + } + + #[test] + fn ignored_folders_and_gitignore_are_skipped() { + let root = temp_root("ignore"); + fs::create_dir_all(root.join("node_modules/pkg")).unwrap(); + fs::write(root.join("node_modules/pkg/index.js"), "needle").unwrap(); + fs::write(root.join(".gitignore"), "secret.txt\n").unwrap(); + fs::write(root.join("secret.txt"), "needle").unwrap(); + fs::write(root.join("kept.txt"), "needle").unwrap(); + let found = run(&Grep, &root, json!({ "pattern": "needle" })).unwrap().text; + assert!(found.contains("kept.txt") && !found.contains("node_modules") && !found.contains("secret"), "{found}"); + fs::remove_dir_all(&root).unwrap(); + } + + #[test] + fn reading_outside_the_project_needs_a_check() { + let root = temp_root("outside"); + let limits = Limits::default(); + let cancel = AtomicBool::new(false); + let ctx = Ctx { root: &root, limits: &limits, cancel: &cancel, host: &Quiet }; + let outside = std::env::temp_dir().join("elsewhere.txt"); + let prepared = ReadFile.prepare(&json!({ "path": outside.to_string_lossy() }), &ctx).unwrap(); + assert_eq!(prepared.effect, Effect::ReadOutside); + assert!(WriteFile.prepare(&json!({ "path": outside.to_string_lossy(), "content": "x" }), &ctx).is_err()); + fs::remove_dir_all(&root).unwrap(); + } +} \ No newline at end of file diff --git a/crates/quill-core/src/tools/git.rs b/crates/quill-core/src/tools/git.rs new file mode 100644 index 0000000..4ab0b27 --- /dev/null +++ b/crates/quill-core/src/tools/git.rs @@ -0,0 +1,136 @@ +use std::path::Path; + +use serde_json::{Value, json}; + +use super::args::{self, BODY, BRANCH, MESSAGE, TITLE}; +use super::{Ctx, Output, Prepared, Spec, Tool, Toolset}; +use crate::policy::Effect; +use crate::protocol::Category; + +pub struct CommitChanges; + +const COMMIT: Spec = Spec { + name: "commit_changes", + title: "Commit", + summary: "Stages every change and commits it, optionally on a new branch.", + aliases: &["commit", "git_commit", "create_commit"], + toolset: Toolset::Git, + category: Category::Git, + active: "Committing", + done: "Committed", + parallel: false, + description: "Stage every change in the project and commit it. Give a branch to commit on a new branch, which a pull request needs when you are on the main branch or not on a branch.", + guide: "commit_changes stages every change and commits it, optionally on a new branch.", +}; + +fn commit(root: &Path, message: &str, branch: Option<&str>) -> Result { + if let Some(branch) = branch.filter(|b| quill_git::branch(root).as_deref() != Some(*b)) { + if !quill_git::valid_branch(branch) { + return Err(format!("\"{branch}\" is not a branch name Git accepts.")); + } + quill_git::create_branch(root, branch).or_else(|_| quill_git::switch_branch(root, branch))?; + } + let sha = quill_git::commit_all(root, message)?; + let on = quill_git::branch(root).unwrap_or_else(|| "a detached HEAD".into()); + Ok(format!("Committed {sha} on {on}.")) +} + +impl Tool for CommitChanges { + fn spec(&self) -> &'static Spec { + &COMMIT + } + + fn parameters(&self) -> Value { + json!({ + "type": "object", + "properties": { + "message": { "type": "string", "description": "Commit message: a short summary line, optionally followed by a blank line and details." }, + "branch": { "type": "string", "description": "Optional branch to create or switch to before committing, for example fix-login." } + }, + "required": ["message"] + }) + } + + fn target(&self, args: &Value) -> String { + args::text(args, &MESSAGE).unwrap_or_default().lines().next().unwrap_or_default().trim().to_string() + } + + fn prepare(&self, args: &Value, ctx: &Ctx<'_>) -> Result { + let message = args::trimmed(args, &MESSAGE).ok_or("commit_changes needs a \"message\".")?.to_string(); + let branch = args::trimmed(args, &BRANCH).map(str::to_string); + let subject = match &branch { + Some(branch) => format!("{} (on {branch})", self.target(args)), + None => self.target(args), + }; + let root = ctx.root.to_path_buf(); + Ok(Prepared::new( + Effect::Publish, + subject, + "Wants to commit", + Box::new(move |_: &Ctx<'_>| Output::settle(commit(&root, &message, branch.as_deref()))), + )) + } +} + +pub struct OpenPullRequest; + +const PULL: Spec = Spec { + name: "open_pull_request", + title: "Open pull requests", + summary: "Pushes the branch to GitHub and opens a pull request.", + aliases: &["pull_request", "create_pull_request", "open_pr", "create_pr"], + toolset: Toolset::Git, + category: Category::Git, + active: "Opening a pull request", + done: "Opened a pull request", + parallel: false, + description: "Push the current branch to GitHub and open a pull request into the main branch. Commit your work with commit_changes first.", + guide: "open_pull_request pushes the current branch to GitHub and opens a pull request into the main branch.", +}; + +fn open(root: &Path, title: &str, body: &str) -> Result { + let branch = quill_git::branch(root).ok_or("Not on a branch. Commit to a new branch with commit_changes first.")?; + let base = quill_git::default_branch(root); + if branch == base { + return Err(format!("You are on {base}, the main branch. Commit the work to a new branch with commit_changes first.")); + } + let remote = + quill_git::remote_url(root).ok_or("This repository has no remote called origin, so there is nowhere to open a pull request.")?; + let slug = quill_git::github_slug(&remote).ok_or("Pull requests can only be opened for repositories on GitHub.")?; + quill_git::push(root, &branch)?; + let url = quill_git::github::create_pull_request(&slug, &branch, &base, title, body)?; + Ok(format!("Pushed {branch} and opened a pull request into {base}: {url}")) +} + +impl Tool for OpenPullRequest { + fn spec(&self) -> &'static Spec { + &PULL + } + + fn parameters(&self) -> Value { + json!({ + "type": "object", + "properties": { + "title": { "type": "string", "description": "Pull request title." }, + "body": { "type": "string", "description": "What changed and why, in Markdown." } + }, + "required": ["title"] + }) + } + + fn target(&self, args: &Value) -> String { + args::text(args, &TITLE).unwrap_or_default().trim().to_string() + } + + fn prepare(&self, args: &Value, ctx: &Ctx<'_>) -> Result { + let title = args::trimmed(args, &TITLE).ok_or("open_pull_request needs a \"title\".")?.to_string(); + let body = args::text(args, &BODY).unwrap_or_default().trim().to_string(); + let root = ctx.root.to_path_buf(); + Ok(Prepared::new( + Effect::Publish, + title.clone(), + "Wants to open a pull request", + Box::new(move |_: &Ctx<'_>| Output::settle(open(&root, &title, &body))), + )) + } +} \ No newline at end of file diff --git a/crates/quill-core/src/tools/mod.rs b/crates/quill-core/src/tools/mod.rs new file mode 100644 index 0000000..847371a --- /dev/null +++ b/crates/quill-core/src/tools/mod.rs @@ -0,0 +1,252 @@ +mod args; +mod fs; +mod git; +mod patch; +mod paths; +mod plan; +mod shell; + +use std::path::Path; +use std::sync::atomic::AtomicBool; + +use quill_providers::ToolSpec; +use serde_json::Value; + +use crate::diff::FileDiff; +use crate::options::{Limits, Toolsets}; +use crate::policy::Effect; +use crate::protocol::{Approval, Category, PlanStep, ToolView}; + +pub use args::{invalid, parse as parse_args}; +pub(crate) use shell::{hide_window, similar}; +pub use shell::{run as run_command, shell_command}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Toolset { + Core, + Git, +} + +pub struct Spec { + pub name: &'static str, + pub title: &'static str, + pub summary: &'static str, + pub aliases: &'static [&'static str], + pub toolset: Toolset, + pub category: Category, + pub active: &'static str, + pub done: &'static str, + pub parallel: bool, + pub description: &'static str, + pub guide: &'static str, +} + +pub trait Host: Sync { + fn output(&self, chunk: &str); + fn plan(&self, steps: Vec, explanation: Option); + fn ask(&self, question: &str, options: &[String]) -> Option; +} + +pub struct Ctx<'a> { + pub root: &'a Path, + pub limits: &'a Limits, + pub cancel: &'a AtomicBool, + pub host: &'a dyn Host, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct Output { + pub ok: bool, + pub text: String, + pub diffs: Vec, + pub image: Option, +} + +impl Output { + pub fn ok(text: impl Into) -> Output { + Output { ok: true, text: text.into(), diffs: Vec::new(), image: None } + } + + pub fn fail(text: impl Into) -> Output { + Output { ok: false, text: text.into(), diffs: Vec::new(), image: None } + } + + pub fn settle(result: Result) -> Output { + match result { + Ok(text) => Output::ok(text), + Err(error) => Output::fail(error), + } + } +} + +pub type Action = Box) -> Output + Send>; + +pub struct Prepared { + pub effect: Effect, + pub subject: String, + pub approval: Approval, + pub action: Action, +} + +impl Prepared { + pub fn new(effect: Effect, subject: impl Into, title: &str, action: Action) -> Prepared { + let subject = subject.into(); + Prepared { + effect, + approval: Approval { title: title.into(), subject: subject.clone(), diffs: Vec::new(), similar: None }, + subject, + action, + } + } + + pub fn read(action: Action) -> Prepared { + Prepared::new(Effect::Read, "", "", action) + } +} + +pub trait Tool: Send + Sync { + fn spec(&self) -> &'static Spec; + fn parameters(&self) -> Value; + fn target(&self, args: &Value) -> String; + fn prepare(&self, args: &Value, ctx: &Ctx<'_>) -> Result; +} + +pub fn all() -> Vec> { + vec![ + Box::new(fs::ListDir), + Box::new(fs::FindFiles), + Box::new(fs::Grep), + Box::new(fs::ReadFile), + Box::new(fs::WriteFile), + Box::new(fs::EditFile), + Box::new(patch::ApplyPatch), + Box::new(shell::ShellTool), + Box::new(plan::UpdatePlan), + Box::new(plan::AskUser), + Box::new(git::CommitChanges), + Box::new(git::OpenPullRequest), + ] +} + +pub fn enabled(toolsets: Toolsets, limits: &Limits) -> Vec> { + all() + .into_iter() + .filter(|tool| { + let spec = tool.spec(); + let on = match spec.toolset { + Toolset::Core => true, + Toolset::Git => toolsets.git, + }; + on && !limits.disabled_tools.iter().any(|name| name == spec.name) + }) + .collect() +} + +fn normalize(name: &str) -> String { + name.trim().to_ascii_lowercase().replace(['-', ' '], "_") +} + +pub fn find<'a>(tools: &'a [Box], name: &str) -> Option<&'a dyn Tool> { + let name = normalize(name); + let name = name.rsplit('.').next().unwrap_or(&name); + tools.iter().map(|tool| tool.as_ref()).find(|tool| { + let spec = tool.spec(); + spec.name == name || spec.aliases.contains(&name) + }) +} + +pub fn spec_for(tool: &dyn Tool) -> ToolSpec { + let spec = tool.spec(); + ToolSpec { name: spec.name.into(), description: spec.description.into(), parameters: tool.parameters() } +} + +pub fn view(tool: &dyn Tool, id: &str, args: &Value) -> ToolView { + let spec = tool.spec(); + ToolView { + id: id.into(), + tool: spec.name.into(), + category: spec.category, + active: spec.active.into(), + done: spec.done.into(), + target: tool.target(args), + } +} + +pub fn unknown_view(id: &str, name: &str) -> ToolView { + ToolView { + id: id.into(), + tool: name.into(), + category: Category::Other, + active: "Calling".into(), + done: "Called".into(), + target: name.into(), + } +} + +pub fn title(name: &str) -> String { + all().iter().find(|tool| tool.spec().name == name).map_or_else(|| name.replace('_', " "), |tool| tool.spec().title.to_string()) +} + +pub fn names(tools: &[Box]) -> String { + tools.iter().map(|tool| tool.spec().name).collect::>().join(", ") +} + +pub fn legacy(kind: &str) -> ToolView { + let name = match kind { + "List" => "list_dir", + "Read" => "read_file", + "Search" => "grep", + "Write" => "write_file", + "Edit" => "edit_file", + "Run" => "shell", + "Commit" => "commit_changes", + "PullRequest" => "open_pull_request", + other => other, + }; + match all().iter().find(|tool| tool.spec().name == name) { + Some(tool) => view(tool.as_ref(), "", &Value::Null), + None => unknown_view("", name), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn names_and_aliases_resolve() { + let tools = all(); + assert_eq!(find(&tools, "bash").map(|t| t.spec().name), Some("shell")); + assert_eq!(find(&tools, "str_replace").map(|t| t.spec().name), Some("edit_file")); + assert_eq!(find(&tools, "Read-File").map(|t| t.spec().name), Some("read_file")); + assert_eq!(find(&tools, "functions.grep").map(|t| t.spec().name), Some("grep")); + assert!(find(&tools, "teleport").is_none()); + } + + #[test] + fn toolsets_and_disabled_tools_filter_the_list() { + let without_git = enabled(Toolsets { git: false }, &Limits::default()); + assert!(find(&without_git, "commit_changes").is_none()); + let limits = Limits { disabled_tools: vec!["shell".into()], ..Limits::default() }; + assert!(find(&enabled(Toolsets::default(), &limits), "shell").is_none()); + } + + #[test] + fn every_name_and_alias_is_unique() { + let tools = all(); + let mut seen = Vec::new(); + for tool in &tools { + for name in std::iter::once(&tool.spec().name).chain(tool.spec().aliases) { + assert!(!seen.contains(name), "{name} appears twice"); + seen.push(*name); + } + } + } + + #[test] + fn old_tool_kinds_map_to_new_tools() { + assert_eq!(legacy("Run").tool, "shell"); + assert_eq!(legacy("Search").category, Category::Explore); + assert_eq!(legacy("Mystery").category, Category::Other); + } +} \ No newline at end of file diff --git a/crates/quill-core/src/tools/patch.rs b/crates/quill-core/src/tools/patch.rs new file mode 100644 index 0000000..21a371c --- /dev/null +++ b/crates/quill-core/src/tools/patch.rs @@ -0,0 +1,348 @@ +use std::fs; +use std::path::PathBuf; + +use serde_json::{Value, json}; + +use super::args::{self, PATCH}; +use super::fs::write; +use super::paths::{display, resolve}; +use super::{Ctx, Output, Prepared, Spec, Tool, Toolset}; +use crate::diff::{FileDiff, diff_text}; +use crate::policy::Effect; +use crate::protocol::Category; + +#[derive(Debug, PartialEq)] +enum FileOp { + Add { path: String, content: String }, + Delete { path: String }, + Update { path: String, to: Option, chunks: Vec }, +} + +#[derive(Debug, Default, PartialEq)] +struct Chunk { + anchor: Option, + old: Vec, + new: Vec, + eof: bool, +} + +fn header<'a>(line: &'a str, prefix: &str) -> Option<&'a str> { + line.strip_prefix(prefix).map(str::trim).filter(|path| !path.is_empty()) +} + +fn is_file_header(line: &str) -> bool { + ["*** Add File:", "*** Delete File:", "*** Update File:", "*** End Patch"].iter().any(|h| line.starts_with(h)) +} + +fn parse(text: &str) -> Result, String> { + let lines: Vec<&str> = text.lines().map(|line| line.trim_end_matches('\r')).collect(); + let mut ops = Vec::new(); + let mut i = 0; + while i < lines.len() { + let line = lines[i]; + i += 1; + if let Some(path) = header(line, "*** Add File:") { + let mut content = Vec::new(); + while i < lines.len() && !lines[i].starts_with("***") { + content.push(lines[i].strip_prefix('+').unwrap_or(lines[i])); + i += 1; + } + let content = if content.is_empty() { String::new() } else { format!("{}\n", content.join("\n")) }; + ops.push(FileOp::Add { path: path.to_string(), content }); + } else if let Some(path) = header(line, "*** Delete File:") { + ops.push(FileOp::Delete { path: path.to_string() }); + } else if let Some(path) = header(line, "*** Update File:") { + let to = lines.get(i).and_then(|next| header(next, "*** Move to:")).map(str::to_string); + if to.is_some() { + i += 1; + } + let mut chunks: Vec = Vec::new(); + while i < lines.len() && !is_file_header(lines[i]) { + let line = lines[i]; + i += 1; + if let Some(anchor) = line.strip_prefix("@@") { + let anchor = anchor.trim().trim_end_matches("@@").trim(); + chunks.push(Chunk { anchor: (!anchor.is_empty()).then(|| anchor.to_string()), ..Chunk::default() }); + continue; + } + if chunks.is_empty() { + chunks.push(Chunk::default()); + } + let chunk = chunks.last_mut().expect("a chunk was just added"); + if line == "*** End of File" { + chunk.eof = true; + } else if let Some(removed) = line.strip_prefix('-') { + chunk.old.push(removed.to_string()); + } else if let Some(added) = line.strip_prefix('+') { + chunk.new.push(added.to_string()); + } else { + let context = line.strip_prefix(' ').unwrap_or(line).to_string(); + chunk.old.push(context.clone()); + chunk.new.push(context); + } + } + chunks.retain(|chunk| !chunk.old.is_empty() || !chunk.new.is_empty()); + ops.push(FileOp::Update { path: path.to_string(), to, chunks }); + } + } + if ops.is_empty() { + return Err("The patch has no file changes. Wrap it in *** Begin Patch and *** End Patch, with *** Add File:, *** Update File: or *** Delete File: sections.".into()); + } + Ok(ops) +} + +fn find_block(lines: &[String], from: usize, block: &[String], eof: bool) -> Option { + if block.len() > lines.len() { + return None; + } + let last = lines.len() - block.len(); + for pass in 0..3 { + let same = |a: &str, b: &str| match pass { + 0 => a == b, + 1 => a.trim_end() == b.trim_end(), + _ => a.trim() == b.trim(), + }; + let fits = |at: usize| block.iter().enumerate().all(|(k, line)| same(&lines[at + k], line)); + if eof && last >= from && fits(last) { + return Some(last); + } + if let Some(at) = (from.min(last + 1)..=last).find(|at| fits(*at)) { + return Some(at); + } + } + None +} + +fn apply_chunks(label: &str, original: &str, chunks: &[Chunk]) -> Result { + let crlf = original.contains("\r\n"); + let mut lines: Vec = original.lines().map(str::to_string).collect(); + let mut cursor = 0; + for (index, chunk) in chunks.iter().enumerate() { + if let Some(anchor) = &chunk.anchor + && let Some(found) = (cursor..lines.len()).find(|at| lines[*at].trim() == anchor.trim()) + { + cursor = found + 1; + } + if chunk.old.is_empty() { + let at = if chunk.eof { lines.len() } else { cursor.min(lines.len()) }; + lines.splice(at..at, chunk.new.iter().cloned()); + cursor = at + chunk.new.len(); + continue; + } + let at = + find_block(&lines, cursor, &chunk.old, chunk.eof).or_else(|| find_block(&lines, 0, &chunk.old, chunk.eof)).ok_or(format!( + "{label}: the lines in change {} were not found. Read the file again and copy the context and removed lines exactly.", + index + 1 + ))?; + lines.splice(at..at + chunk.old.len(), chunk.new.iter().cloned()); + cursor = at + chunk.new.len(); + } + let sep = if crlf { "\r\n" } else { "\n" }; + let mut out = lines.join(sep); + if !lines.is_empty() && (original.ends_with('\n') || original.is_empty()) { + out.push_str(sep); + } + Ok(out) +} + +struct Planned { + writes: Vec<(PathBuf, Option)>, + diffs: Vec, +} + +fn plan(root: &std::path::Path, ops: Vec) -> Result { + let mut planned = Planned { writes: Vec::new(), diffs: Vec::new() }; + let read = |path: &PathBuf, label: &str| { + fs::read_to_string(path).map_err(|_| format!("{label} does not exist. Use *** Add File: to create it.")) + }; + for op in ops { + match op { + FileOp::Add { path, content } => { + let target = resolve(root, &path)?; + let before = fs::read_to_string(&target).ok(); + planned.diffs.push(diff_text(&display(root, &target), before.as_deref(), &content)); + planned.writes.push((target, Some(content))); + } + FileOp::Delete { path } => { + let target = resolve(root, &path)?; + let before = read(&target, &path)?; + planned.diffs.push(diff_text(&display(root, &target), Some(&before), "")); + planned.writes.push((target, None)); + } + FileOp::Update { path, to, chunks } => { + let source = resolve(root, &path)?; + let before = read(&source, &path)?; + let after = apply_chunks(&path, &before, &chunks)?; + let target = match &to { + Some(to) => resolve(root, to)?, + None => source.clone(), + }; + planned.diffs.push(diff_text(&display(root, &target), Some(&before), &after)); + if target != source { + planned.writes.push((source, None)); + } + planned.writes.push((target, Some(after))); + } + } + } + Ok(planned) +} + +pub struct ApplyPatch; + +const PATCH_SPEC: Spec = Spec { + name: "apply_patch", + title: "Apply patches", + summary: "Changes several places or files in one step.", + aliases: &["patch", "applypatch", "apply_diff"], + toolset: Toolset::Core, + category: Category::Edit, + active: "Patching", + done: "Patched", + parallel: false, + description: "Apply a patch that adds, updates, moves or deletes files, all at once. Format:\n*** Begin Patch\n*** Update File: src/app.py\n@@ def greet():\n- print(\"hi\")\n+ print(\"hello\")\n*** Add File: notes.txt\n+first line\n*** Delete File: old.txt\n*** End Patch\nIn an update, lines starting with a space are unchanged context, - removes a line and + adds one. Give about three lines of context around each change. @@ followed by a line such as a function header narrows where the change goes. *** Move to: new/path after an Update File line renames the file.", + guide: "apply_patch changes one or more files in one step using the *** Begin Patch format. Prefer it for edits that touch several places or files.", +}; + +impl Tool for ApplyPatch { + fn spec(&self) -> &'static Spec { + &PATCH_SPEC + } + + fn parameters(&self) -> Value { + json!({ + "type": "object", + "properties": { + "patch": { "type": "string", "description": "The whole patch, from *** Begin Patch to *** End Patch." } + }, + "required": ["patch"] + }) + } + + fn target(&self, args: &Value) -> String { + let patch = args::text(args, &PATCH).unwrap_or_default(); + let paths: Vec<&str> = patch + .lines() + .filter_map(|line| ["*** Add File:", "*** Update File:", "*** Delete File:"].iter().find_map(|h| header(line, h))) + .collect(); + match paths.as_slice() { + [] => String::new(), + [one] => one.replace('\\', "/"), + [first, rest @ ..] => format!("{} and {} more", first.replace('\\', "/"), rest.len()), + } + } + + fn prepare(&self, args: &Value, ctx: &Ctx<'_>) -> Result { + let patch = args::text(args, &PATCH).ok_or("apply_patch needs a \"patch\".")?; + let planned = plan(ctx.root, parse(patch)?)?; + let subject = match planned.diffs.as_slice() { + [one] => one.path.clone(), + many => format!("{} files", many.len()), + }; + let diffs = planned.diffs.clone(); + let mut prepared = Prepared::new( + Effect::Write, + subject, + "Wants to apply a patch", + Box::new(move |_: &Ctx<'_>| { + for (path, content) in &planned.writes { + let result = match content { + Some(text) => write(path, text), + None => fs::remove_file(path).map_err(|e| e.to_string()), + }; + if let Err(error) = result { + return Output::fail(format!("{}: {error}", path.display())); + } + } + let summary: Vec = planned + .diffs + .iter() + .map(|diff| { + let verb = if diff.created { + "Added" + } else if diff.added == 0 && diff.removed > 0 { + "Changed" + } else { + "Updated" + }; + format!("{verb} {} (+{} -{})", diff.path, diff.added, diff.removed) + }) + .collect(); + Output { diffs: planned.diffs.clone(), ..Output::ok(summary.join("\n")) } + }), + ); + prepared.approval.diffs = diffs; + Ok(prepared) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn lines(text: &[&str]) -> Vec { + text.iter().map(|s| s.to_string()).collect() + } + + #[test] + fn patches_are_parsed_into_file_operations() { + let patch = "*** Begin Patch\n*** Add File: a.txt\n+one\n+two\n*** Update File: b.py\n*** Move to: c.py\n@@ def f():\n- x = 1\n+ x = 2\n return x\n*** Delete File: d.txt\n*** End Patch"; + let ops = parse(patch).unwrap(); + assert_eq!(ops[0], FileOp::Add { path: "a.txt".into(), content: "one\ntwo\n".into() }); + assert_eq!( + ops[1], + FileOp::Update { + path: "b.py".into(), + to: Some("c.py".into()), + chunks: vec![Chunk { + anchor: Some("def f():".into()), + old: lines(&[" x = 1", " return x"]), + new: lines(&[" x = 2", " return x"]), + eof: false + }] + } + ); + assert_eq!(ops[2], FileOp::Delete { path: "d.txt".into() }); + assert!(parse("nothing here").is_err()); + } + + #[test] + fn chunks_apply_with_lenient_matching() { + let original = "fn a() {\n one();\n}\n\nfn b() {\n one();\n}\n"; + let chunks = vec![Chunk { anchor: Some("fn b() {".into()), old: lines(&[" one();"]), new: lines(&[" two();"]), eof: false }]; + assert_eq!(apply_chunks("x", original, &chunks).unwrap(), "fn a() {\n one();\n}\n\nfn b() {\n two();\n}\n"); + let loose = vec![Chunk { anchor: None, old: lines(&["fn a() { "]), new: lines(&["fn first() {"]), eof: false }]; + assert!(apply_chunks("x", original, &loose).unwrap().starts_with("fn first() {\n")); + let missing = vec![Chunk { anchor: None, old: lines(&["nope"]), new: Vec::new(), eof: false }]; + assert!(apply_chunks("x", original, &missing).unwrap_err().contains("change 1")); + } + + #[test] + fn line_endings_and_appends_are_kept() { + let chunks = vec![Chunk { anchor: None, old: Vec::new(), new: lines(&["three"]), eof: true }]; + assert_eq!(apply_chunks("x", "one\r\ntwo\r\n", &chunks).unwrap(), "one\r\ntwo\r\nthree\r\n"); + } + + #[test] + fn a_whole_patch_changes_files_together() { + let root = std::env::temp_dir().join(format!("quill-patch-{}", std::process::id())); + let _ = fs::remove_dir_all(&root); + fs::create_dir_all(&root).unwrap(); + fs::write(root.join("keep.txt"), "a\nb\nc\n").unwrap(); + fs::write(root.join("gone.txt"), "bye\n").unwrap(); + let patch = "*** Begin Patch\n*** Update File: keep.txt\n a\n-b\n+B\n c\n*** Add File: new/n.txt\n+hello\n*** Delete File: gone.txt\n*** End Patch"; + let planned = plan(&root, parse(patch).unwrap()).unwrap(); + assert_eq!(planned.diffs.len(), 3); + for (path, content) in &planned.writes { + match content { + Some(text) => write(path, text).unwrap(), + None => fs::remove_file(path).unwrap(), + } + } + assert_eq!(fs::read_to_string(root.join("keep.txt")).unwrap(), "a\nB\nc\n"); + assert_eq!(fs::read_to_string(root.join("new/n.txt")).unwrap(), "hello\n"); + assert!(!root.join("gone.txt").exists()); + assert!(plan(&root, parse("*** Update File: missing.txt\n-x\n+y").unwrap()).is_err()); + fs::remove_dir_all(&root).unwrap(); + } +} \ No newline at end of file diff --git a/crates/quill-core/src/tools/paths.rs b/crates/quill-core/src/tools/paths.rs new file mode 100644 index 0000000..36c3c73 --- /dev/null +++ b/crates/quill-core/src/tools/paths.rs @@ -0,0 +1,62 @@ +use std::path::{Component, Path, PathBuf}; + +pub fn normalize(root: &Path, rel: &str) -> Result { + let rel = rel.trim().trim_matches('"'); + let candidate = Path::new(rel); + let joined = if candidate.is_absolute() { candidate.to_path_buf() } else { root.join(candidate) }; + let mut out = PathBuf::new(); + for component in joined.components() { + match component { + Component::ParentDir => { + if !out.pop() { + return Err(outside()); + } + } + Component::CurDir => {} + other => out.push(other), + } + } + Ok(out) +} + +pub fn inside(path: &Path, root: &Path) -> bool { + let path = path.to_string_lossy().to_lowercase().replace('/', "\\"); + let root = root.to_string_lossy().to_lowercase().replace('/', "\\"); + let root = root.trim_end_matches('\\'); + path == root || path.starts_with(&format!("{root}\\")) +} + +pub fn resolve(root: &Path, rel: &str) -> Result { + let path = normalize(root, rel)?; + if inside(&path, root) { Ok(path) } else { Err(outside()) } +} + +fn outside() -> String { + "That path is outside the project. Use a path relative to the project root, such as \"src/main.rs\".".into() +} + +pub fn display(root: &Path, path: &Path) -> String { + path.strip_prefix(root).map(|rel| rel.to_string_lossy().replace('\\', "/")).unwrap_or_else(|_| path.to_string_lossy().into_owned()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn paths_cannot_leave_the_project() { + let root = PathBuf::from(r"C:\work\proj"); + assert!(resolve(&root, "src/main.rs").is_ok()); + assert!(resolve(&root, "../other").is_err()); + assert!(resolve(&root, r"C:\Windows\System32").is_err()); + assert!(resolve(&root, r"c:\WORK\proj\a.txt").is_ok()); + assert!(resolve(&root, r"C:\work\project2\a.txt").is_err()); + assert!(normalize(&root, r"C:\Windows\win.ini").is_ok()); + } + + #[test] + fn display_paths_are_relative() { + let root = PathBuf::from(r"C:\work\proj"); + assert_eq!(display(&root, &root.join("src").join("a.rs")), "src/a.rs"); + } +} \ No newline at end of file diff --git a/crates/quill-core/src/tools/plan.rs b/crates/quill-core/src/tools/plan.rs new file mode 100644 index 0000000..9683e95 --- /dev/null +++ b/crates/quill-core/src/tools/plan.rs @@ -0,0 +1,158 @@ +use serde_json::{Value, json}; + +use super::args; +use super::{Ctx, Output, Prepared, Spec, Tool, Toolset}; +use crate::protocol::{Category, PlanStep, StepStatus}; + +pub struct UpdatePlan; + +const PLAN: Spec = Spec { + name: "update_plan", + title: "Plan", + summary: "Shows a checklist of the work and keeps it current.", + aliases: &["plan", "todo", "todo_write", "todowrite", "set_plan", "update_todos", "write_todos"], + toolset: Toolset::Core, + category: Category::Plan, + active: "Planning", + done: "Updated the plan", + parallel: false, + description: "Show the user your plan as a short checklist and keep it current. Send the whole list each time, with each step pending, in_progress or completed. Keep exactly one step in_progress while you work.", + guide: "update_plan shows your plan as a checklist. For work with several steps, set a plan first and update it as each step finishes.", +}; + +fn status(value: &str) -> StepStatus { + match value.trim().to_ascii_lowercase().as_str() { + "in_progress" | "in-progress" | "active" | "doing" | "current" | "started" => StepStatus::Active, + "completed" | "complete" | "done" | "finished" => StepStatus::Done, + _ => StepStatus::Pending, + } +} + +fn steps(args: &Value) -> Vec { + let list = ["plan", "steps", "items", "todos"].iter().find_map(|key| args.get(*key).and_then(Value::as_array)); + list.map(|items| { + items + .iter() + .filter_map(|item| match item { + Value::String(text) => Some(PlanStep { text: text.trim().to_string(), status: StepStatus::Pending }), + _ => { + let text = args::trimmed(item, &["step", "text", "content", "title", "task"])?; + let state = args::text(item, &["status", "state"]).map_or(StepStatus::Pending, status); + Some(PlanStep { text: text.to_string(), status: state }) + } + }) + .collect() + }) + .unwrap_or_default() +} + +impl Tool for UpdatePlan { + fn spec(&self) -> &'static Spec { + &PLAN + } + + fn parameters(&self) -> Value { + json!({ + "type": "object", + "properties": { + "explanation": { "type": "string", "description": "Optional note on what changed." }, + "plan": { + "type": "array", + "items": { + "type": "object", + "properties": { + "step": { "type": "string" }, + "status": { "type": "string", "enum": ["pending", "in_progress", "completed"] } + }, + "required": ["step", "status"] + } + } + }, + "required": ["plan"] + }) + } + + fn target(&self, args: &Value) -> String { + let steps = steps(args); + let done = steps.iter().filter(|step| step.status == StepStatus::Done).count(); + if steps.is_empty() { String::new() } else { format!("{done} of {} done", steps.len()) } + } + + fn prepare(&self, args: &Value, _: &Ctx<'_>) -> Result { + let steps = steps(args); + if steps.is_empty() { + return Err("update_plan needs \"plan\": a list of {step, status} items.".into()); + } + let explanation = args::trimmed(args, &["explanation", "note"]).map(str::to_string); + Ok(Prepared::read(Box::new(move |ctx: &Ctx<'_>| { + ctx.host.plan(steps, explanation); + Output::ok("Plan updated.") + }))) + } +} + +pub struct AskUser; + +const ASK: Spec = Spec { + name: "ask_user", + title: "Ask you", + summary: "Asks you a question and waits for the answer.", + aliases: &["ask", "ask_question", "question", "ask_followup_question", "request_user_input"], + toolset: Toolset::Core, + category: Category::Question, + active: "Asking", + done: "Asked", + parallel: false, + description: "Ask the user a question and wait for the answer. Use it only when you cannot continue without a decision from them. Offer short options when there are clear choices.", + guide: "ask_user asks the user a question and waits. Use it only when you are blocked on a decision that is theirs to make.", +}; + +impl Tool for AskUser { + fn spec(&self) -> &'static Spec { + &ASK + } + + fn parameters(&self) -> Value { + json!({ + "type": "object", + "properties": { + "question": { "type": "string", "description": "The question to ask." }, + "options": { "type": "array", "items": { "type": "string" }, "description": "Optional short answers to choose from." } + }, + "required": ["question"] + }) + } + + fn target(&self, args: &Value) -> String { + args::trimmed(args, &["question", "text", "prompt"]).unwrap_or_default().to_string() + } + + fn prepare(&self, args: &Value, _: &Ctx<'_>) -> Result { + let question = args::trimmed(args, &["question", "text", "prompt"]).ok_or("ask_user needs a \"question\".")?.to_string(); + let options: Vec = ["options", "choices"] + .iter() + .find_map(|key| args.get(*key).and_then(Value::as_array)) + .map(|items| items.iter().filter_map(Value::as_str).map(|s| s.trim().to_string()).filter(|s| !s.is_empty()).collect()) + .unwrap_or_default(); + Ok(Prepared::read(Box::new(move |ctx: &Ctx<'_>| match ctx.host.ask(&question, &options) { + Some(answer) => Output::ok(format!("The user answered: {answer}")), + None => Output::fail("The user did not answer."), + }))) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn plans_accept_many_shapes() { + let codex = json!({ "plan": [{ "step": "Read", "status": "completed" }, { "step": "Fix", "status": "in_progress" }, { "step": "Test", "status": "pending" }] }); + let parsed = steps(&codex); + assert_eq!(parsed.iter().map(|s| s.status).collect::>(), vec![StepStatus::Done, StepStatus::Active, StepStatus::Pending]); + assert_eq!(UpdatePlan.target(&codex), "1 of 3 done"); + let loose = json!({ "todos": ["one", { "content": "two", "state": "done" }] }); + assert_eq!(steps(&loose).len(), 2); + assert_eq!(steps(&loose)[1].status, StepStatus::Done); + } +} \ No newline at end of file diff --git a/crates/quill-core/src/tools/shell.rs b/crates/quill-core/src/tools/shell.rs new file mode 100644 index 0000000..e7351fd --- /dev/null +++ b/crates/quill-core/src/tools/shell.rs @@ -0,0 +1,277 @@ +use std::io::{BufRead, BufReader, Read}; +use std::path::{Path, PathBuf}; +use std::process::{Command, Stdio}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::mpsc::{RecvTimeoutError, channel}; +use std::time::{Duration, Instant}; + +use serde_json::{Value, json}; + +use super::args::{self, COMMAND}; +use super::paths::resolve; +use super::{Ctx, Output, Prepared, Spec, Tool, Toolset}; +use crate::options::Shell; +use crate::policy::Effect; +use crate::protocol::Category; + +pub fn shell_command(shell: Shell, command: &str) -> Command { + let mut cmd = match shell { + Shell::PowerShell | Shell::Pwsh => { + let mut cmd = Command::new(if shell == Shell::Pwsh { "pwsh" } else { "powershell" }); + cmd.args([ + "-NoLogo", + "-NoProfile", + "-NonInteractive", + "-ExecutionPolicy", + "Bypass", + "-Command", + &format!("[Console]::OutputEncoding=[Text.Encoding]::UTF8; $ProgressPreference='SilentlyContinue'; {command}"), + ]); + cmd + } + Shell::Cmd => { + let mut cmd = Command::new("cmd"); + cmd.args(["/D", "/S", "/C", command]); + cmd + } + Shell::Bash => { + let mut cmd = Command::new(git_bash().unwrap_or_else(|| PathBuf::from("bash"))); + cmd.args(["-c", command]); + cmd + } + Shell::Sh => { + let mut cmd = Command::new("sh"); + cmd.args(["-c", command]); + cmd + } + }; + hide_window(&mut cmd); + cmd +} + +fn git_bash() -> Option { + let program_files = std::env::var_os("ProgramFiles")?; + let path = PathBuf::from(program_files).join("Git").join("bin").join("bash.exe"); + path.is_file().then_some(path) +} + +#[cfg(windows)] +pub(crate) fn hide_window(cmd: &mut Command) { + use std::os::windows::process::CommandExt; + cmd.creation_flags(0x0800_0000); +} + +#[cfg(not(windows))] +pub(crate) fn hide_window(_: &mut Command) {} + +fn cap(text: String, max: usize) -> String { + if text.len() <= max { + return text; + } + let mut head = max * 2 / 3; + while !text.is_char_boundary(head) { + head -= 1; + } + let mut tail = text.len() - max / 3; + while !text.is_char_boundary(tail) { + tail += 1; + } + format!("{}\n... [output cut] ...\n{}", &text[..head], &text[tail..]) +} + +fn pump(stream: Option, tx: std::sync::mpsc::Sender) { + let Some(stream) = stream else { return }; + std::thread::spawn(move || { + let mut reader = BufReader::new(stream); + let mut buf = Vec::new(); + while reader.read_until(b'\n', &mut buf).is_ok_and(|n| n > 0) { + if tx.send(String::from_utf8_lossy(&buf).into_owned()).is_err() { + break; + } + buf.clear(); + } + }); +} + +pub fn run( + shell: Shell, + dir: &Path, + command: &str, + timeout: Duration, + cancel: &AtomicBool, + max_output: usize, + on_chunk: &dyn Fn(&str), +) -> (bool, String) { + let spawned = shell_command(shell, command).current_dir(dir).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn(); + let mut child = match spawned { + Ok(child) => child, + Err(e) => return (false, format!("The command could not start: {e}")), + }; + let (tx, rx) = channel(); + pump(child.stdout.take(), tx.clone()); + pump(child.stderr.take(), tx); + let started = Instant::now(); + let mut text = String::new(); + let mut ended: Option = None; + let mut outcome = None; + loop { + match rx.recv_timeout(Duration::from_millis(40)) { + Ok(chunk) => { + on_chunk(&chunk); + if text.len() < max_output * 4 { + text.push_str(&chunk); + } + } + Err(RecvTimeoutError::Disconnected) if outcome.is_some() => break, + Err(_) => {} + } + if outcome.is_none() { + match child.try_wait() { + Ok(Some(status)) => outcome = Some((Some(status), None)), + Ok(None) if cancel.load(Ordering::Relaxed) => { + let _ = child.kill(); + outcome = Some((None, Some("Stopped by the user.".to_string()))); + } + Ok(None) if started.elapsed() > timeout => { + let _ = child.kill(); + outcome = Some((None, Some(format!("Stopped after {} seconds without finishing.", timeout.as_secs())))); + } + Ok(None) => {} + Err(e) => outcome = Some((None, Some(e.to_string()))), + } + if outcome.is_some() { + ended = Some(Instant::now()); + } + } else if ended.is_some_and(|at| at.elapsed() > Duration::from_millis(800)) { + break; + } + } + let _ = child.wait(); + let (status, note) = outcome.unwrap_or((None, None)); + let ok = status.is_some_and(|s| s.success()); + let mut report = match (status.and_then(|s| s.code()), note) { + (_, Some(note)) => note, + (Some(code), None) => format!("Exit code {code}"), + (None, None) => "Exited".into(), + }; + let body = text.trim_end(); + if !body.is_empty() { + report.push('\n'); + report.push_str(body); + } + (ok, cap(report, max_output)) +} + +pub struct ShellTool; + +const SHELL: Spec = Spec { + name: "shell", + title: "Run commands", + summary: "Runs commands in the project folder: builds, tests, installs.", + aliases: &[ + "run_command", + "run", + "bash", + "powershell", + "exec", + "execute_command", + "terminal", + "cmd", + "run_shell_command", + "shell_command", + ], + toolset: Toolset::Core, + category: Category::Command, + active: "Running", + done: "Ran", + parallel: false, + description: "Run a shell command in the project folder and return its output and exit code. Use it to build, test, install and run code. The command must finish on its own.", + guide: "shell runs a command in the project folder and returns its output and exit code.", +}; + +impl Tool for ShellTool { + fn spec(&self) -> &'static Spec { + &SHELL + } + + fn parameters(&self) -> Value { + json!({ + "type": "object", + "properties": { + "command": { "type": "string", "description": "The command to run." }, + "timeout_seconds": { "type": "integer", "description": "How long to wait before stopping it. Default 120." }, + "workdir": { "type": "string", "description": "Optional folder to run in, relative to the project root." } + }, + "required": ["command"] + }) + } + + fn target(&self, args: &Value) -> String { + args::text(args, &COMMAND).unwrap_or_default().trim().to_string() + } + + fn prepare(&self, args: &Value, ctx: &Ctx<'_>) -> Result { + let command = args::trimmed(args, &COMMAND).ok_or("shell needs a \"command\".")?.to_string(); + let dir = match args::trimmed(args, &["workdir", "cwd", "dir", "directory"]) { + Some(rel) => resolve(ctx.root, rel)?, + None => ctx.root.to_path_buf(), + }; + let limits = ctx.limits; + let seconds = + args::number(args, &["timeout_seconds", "timeout"]).unwrap_or(limits.command_timeout).clamp(1, limits.max_command_timeout); + let mut prepared = Prepared::new( + Effect::Execute, + command.clone(), + "Wants to run a command", + Box::new(move |ctx: &Ctx<'_>| { + let (ok, text) = + run(ctx.limits.shell, &dir, &command, Duration::from_secs(seconds), ctx.cancel, ctx.limits.max_output, &|chunk| { + ctx.host.output(chunk) + }); + Output { ok, ..Output::ok(text) } + }), + ); + prepared.approval.similar = similar(&prepared.subject); + Ok(prepared) + } +} + +pub(crate) fn similar(command: &str) -> Option { + let words: Vec<&str> = command.split_whitespace().take_while(|word| !word.starts_with('-')).take(2).collect(); + (!words.is_empty()).then(|| words.join(" ")) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn commands_report_exit_codes_and_stream() { + let dir = std::env::temp_dir(); + let cancel = AtomicBool::new(false); + let seen = std::sync::Mutex::new(String::new()); + let (ok, output) = run(Shell::default(), &dir, "echo quill", Duration::from_secs(60), &cancel, 30_000, &|chunk| { + seen.lock().unwrap().push_str(chunk) + }); + assert!(ok, "{output}"); + assert!(output.starts_with("Exit code 0") && output.contains("quill")); + assert!(seen.lock().unwrap().contains("quill")); + let (ok, output) = run(Shell::default(), &dir, "exit 3", Duration::from_secs(60), &cancel, 30_000, &|_| {}); + assert!(!ok); + assert!(output.starts_with("Exit code 3")); + } + + #[test] + fn long_output_keeps_head_and_tail() { + let text = format!("{}{}", "a".repeat(100), "z".repeat(100)); + let capped = cap(text, 60); + assert!(capped.starts_with("aaaa") && capped.ends_with("zzzz") && capped.contains("[output cut]")); + } + + #[test] + fn similar_commands_use_the_leading_words() { + assert_eq!(similar("npm test -- --watch").as_deref(), Some("npm test")); + assert_eq!(similar("cargo build --release").as_deref(), Some("cargo build")); + assert_eq!(similar("ls").as_deref(), Some("ls")); + } +} \ No newline at end of file diff --git a/crates/quill-core/src/turn.rs b/crates/quill-core/src/turn.rs new file mode 100644 index 0000000..d316bee --- /dev/null +++ b/crates/quill-core/src/turn.rs @@ -0,0 +1,542 @@ +use std::sync::Mutex; +use std::sync::atomic::{AtomicBool, Ordering}; + +use quill_providers::{ChatRequest, Error, Event as Stream, Message, Provider, StopReason, ToolCall, ToolSpec}; +use serde_json::Value; + +use crate::context; +use crate::policy::{self, Access, Effect, Rule, Verdict}; +use crate::prompt::{PromptContext, system_prompt}; +use crate::protocol::{Approval, Decision, Event, Outcome, PlanStep}; +use crate::session::{Inbox, Input, Session, Sink, TurnContext}; +use crate::tools::{self, Ctx, Host, Output, Prepared, Tool}; + +pub(crate) const STOPPED: &str = "Stopped by the user before this ran."; +const REFUSED: &str = "The model declined to continue with this request. Try rephrasing it, or pick another model."; + +#[derive(Default)] +struct Reply { + text: String, + reasoning: String, + calls: Vec, + stop: Option, + native: Option, +} + +#[derive(Default)] +struct PendingCall { + id: Option, + name: String, + arguments: String, +} + +struct CallHost<'a> { + sink: &'a Sink, + inbox: &'a Mutex, + turn: usize, + id: String, + cancel: &'a AtomicBool, +} + +impl Host for CallHost<'_> { + fn output(&self, chunk: &str) { + (self.sink)(Event::ToolOutput { turn: self.turn, id: self.id.clone(), chunk: chunk.to_string() }); + } + + fn plan(&self, steps: Vec, explanation: Option) { + (self.sink)(Event::PlanUpdated { turn: self.turn, steps, explanation }); + } + + fn ask(&self, question: &str, options: &[String]) -> Option { + (self.sink)(Event::QuestionAsked { + turn: self.turn, + id: self.id.clone(), + question: question.to_string(), + options: options.to_vec(), + }); + self.inbox.lock().expect("inbox lock").answer(&self.id, self.cancel) + } +} + +pub(crate) fn run( + session: &mut Session, + turn: usize, + input: Input, + ctx: &TurnContext, + provider: &dyn Provider, + cancel: &AtomicBool, +) -> Outcome { + let tools = if ctx.root.is_some() { tools::enabled(ctx.toolsets, &ctx.limits) } else { Vec::new() }; + let system = system_prompt(&PromptContext { + model: &ctx.model, + root: ctx.root.as_deref(), + tools: &tools, + shell: ctx.limits.shell, + personal: &ctx.personal, + instructions: &ctx.instructions, + }); + let specs: Vec = tools.iter().map(|tool| tools::spec_for(tool.as_ref())).collect(); + session.take_steers(); + session.push(Message::user_with_images(input.text, input.images)); + for _ in 0..ctx.limits.max_steps { + if cancel.load(Ordering::Relaxed) { + return Outcome::Stopped; + } + session.take_steers(); + let used = session.used.unwrap_or_else(|| context::estimate(&session.history)); + if !ctx.server_compaction && context::over(used, ctx.context_window, ctx.limits.compact_at) { + let _ = session.compact(ctx, cancel); + } + let reply = match step(session, turn, ctx, provider, &system, &specs, cancel) { + Ok(reply) => reply, + Err(error) => return Outcome::Failed(error.0), + }; + if cancel.load(Ordering::Relaxed) { + if !reply.text.trim().is_empty() { + session.push(Message::assistant(reply.text, Vec::new())); + } + return Outcome::Stopped; + } + let truncated = reply.stop == Some(StopReason::MaxTokens); + let refused = reply.stop == Some(StopReason::Refusal); + let calls = if truncated || refused { Vec::new() } else { reply.calls }; + let content = if calls.is_empty() && reply.text.trim().is_empty() { reply.reasoning.trim().to_string() } else { reply.text }; + let native = if refused { None } else { reply.native }; + session.push(Message { native, ..Message::assistant(content, calls.clone()) }); + if calls.is_empty() { + if session.take_steers() { + continue; + } + if refused { + return Outcome::Failed(REFUSED.into()); + } + if truncated { + return Outcome::Failed( + "The reply hit the model's output limit before it finished. Ask it to continue, or raise the limit on the server." + .into(), + ); + } + return Outcome::Done; + } + run_calls(session, turn, ctx, &tools, &calls, cancel); + } + Outcome::Failed(format!("Stopped after {} steps. Send a follow-up to let the agent continue.", ctx.limits.max_steps)) +} + +fn step( + session: &mut Session, + turn: usize, + ctx: &TurnContext, + provider: &dyn Provider, + system: &str, + specs: &[ToolSpec], + cancel: &AtomicBool, +) -> Result { + let mut messages = Vec::with_capacity(session.history.len() + 1); + messages.push(Message::system(system)); + messages.extend(session.history.iter().cloned()); + let request = ChatRequest { + model: ctx.model.clone(), + messages, + thinking: ctx.thinking, + effort: ctx.effort, + max_tokens: ctx.max_output, + server_compaction: ctx.server_compaction, + tools: specs.to_vec(), + }; + let sink = session.sink.clone(); + let mut reply = Reply::default(); + let mut pending: Vec = Vec::new(); + let mut used = None; + provider.stream(&request, cancel, &mut |event| match event { + Stream::Reasoning(text) => { + reply.reasoning.push_str(&text); + sink(Event::Reasoning { turn, text }); + } + Stream::Content(text) => { + reply.text.push_str(&text); + sink(Event::Text { turn, text }); + } + Stream::ToolCall { index, id, name, arguments } => { + if pending.len() <= index { + pending.resize_with(index + 1, PendingCall::default); + } + let call = &mut pending[index]; + if id.is_some() { + call.id = id; + } + if let Some(name) = name { + call.name.push_str(&name); + } + call.arguments.push_str(&arguments); + } + Stream::Usage(tokens) => { + used = Some(tokens.total()); + sink(Event::Usage { turn, tokens }); + } + Stream::Native(native) => reply.native = Some(native), + Stream::Stop(reason) => reply.stop = Some(reason), + })?; + if used.is_some() { + session.used = used; + } + let base = session.history.len(); + reply.calls = pending + .into_iter() + .enumerate() + .filter(|(_, call)| !call.name.trim().is_empty()) + .map(|(index, call)| { + ToolCall::new(call.id.filter(|id| !id.is_empty()).unwrap_or_else(|| format!("call_{base}_{index}")), call.name, call.arguments) + }) + .collect(); + Ok(reply) +} + +fn run_calls(session: &mut Session, turn: usize, ctx: &TurnContext, tools: &[Box], calls: &[ToolCall], cancel: &AtomicBool) { + let mut index = 0; + while index < calls.len() { + if cancel.load(Ordering::Relaxed) { + for call in &calls[index..] { + session.push(Message::tool(call.id.clone(), STOPPED)); + } + return; + } + let batch = if ctx.limits.parallel_tools { + calls[index..] + .iter() + .take_while(|call| tools::find(tools, &call.function.name).is_some_and(|tool| tool.spec().parallel)) + .count() + } else { + 0 + }; + let end = index + batch.max(1); + let outputs = run_batch(session, turn, ctx, tools, &calls[index..end], cancel); + for (call, output) in calls[index..end].iter().zip(outputs) { + finish(session, turn, call, output); + } + index = end; + } +} + +fn run_batch( + session: &Session, + turn: usize, + ctx: &TurnContext, + tools: &[Box], + calls: &[ToolCall], + cancel: &AtomicBool, +) -> Vec { + let hosts: Vec> = + calls.iter().map(|call| CallHost { sink: &session.sink, inbox: &session.inbox, turn, id: call.id.clone(), cancel }).collect(); + let admitted: Vec> = + calls.iter().zip(&hosts).map(|(call, host)| admit(session, turn, ctx, tools, call, host, cancel)).collect(); + let Some(root) = ctx.root.as_deref() else { + return admitted.into_iter().map(|entry| entry.err().unwrap_or_else(|| Output::fail(STOPPED))).collect(); + }; + let run = |prepared: Prepared, host: &CallHost<'_>| { + if cancel.load(Ordering::Relaxed) { + return Output::fail(STOPPED); + } + let cx = Ctx { root, limits: &ctx.limits, cancel, host }; + (prepared.action)(&cx) + }; + if admitted.len() == 1 { + let entry = admitted.into_iter().next().expect("one call"); + return vec![entry.map_or_else(|output| output, |prepared| run(prepared, &hosts[0]))]; + } + std::thread::scope(|scope| { + let handles: Vec<_> = admitted + .into_iter() + .zip(&hosts) + .map(|(entry, host)| match entry { + Ok(prepared) => Ok(scope.spawn(move || run(prepared, host))), + Err(output) => Err(output), + }) + .collect(); + handles + .into_iter() + .map(|handle| match handle { + Ok(handle) => handle.join().unwrap_or_else(|_| Output::fail("The tool stopped unexpectedly.")), + Err(output) => output, + }) + .collect() + }) +} + +fn admit( + session: &Session, + turn: usize, + ctx: &TurnContext, + tools: &[Box], + call: &ToolCall, + host: &CallHost<'_>, + cancel: &AtomicBool, +) -> Result { + let args = tools::parse_args(&call.function.arguments); + let Some(tool) = tools::find(tools, &call.function.name) else { + session.emit(Event::ToolBegin { turn, view: tools::unknown_view(&call.id, &call.function.name) }); + return Err(Output::fail(match ctx.root { + Some(_) => format!("There is no tool called \"{}\". The tools are {}.", call.function.name, tools::names(tools)), + None => "No project is open, so tools are unavailable. Answer directly.".into(), + })); + }; + session.emit(Event::ToolBegin { turn, view: tools::view(tool, &call.id, &args) }); + if let Some(raw) = tools::invalid(&args) { + return Err(Output::fail(format!( + "The arguments were not valid JSON: {raw}. Send a JSON object, for example {{\"path\": \"src/main.rs\"}}." + ))); + } + let root = ctx.root.as_deref().ok_or_else(|| Output::fail("No project is open, so tools are unavailable."))?; + let cx = Ctx { root, limits: &ctx.limits, cancel, host }; + let prepared = tool.prepare(&args, &cx).map_err(Output::fail)?; + let request = + Request { id: &call.id, tool: tool.spec().name, effect: prepared.effect, subject: &prepared.subject, approval: &prepared.approval }; + permit(session, turn, ctx, &request, cancel).map_err(Output::fail)?; + Ok(prepared) +} + +pub(crate) struct Request<'a> { + pub id: &'a str, + pub tool: &'a str, + pub effect: Effect, + pub subject: &'a str, + pub approval: &'a Approval, +} + +pub(crate) fn permit(session: &Session, turn: usize, ctx: &TurnContext, request: &Request<'_>, cancel: &AtomicBool) -> Result<(), String> { + let access = if session.raised.load(Ordering::Relaxed) { Access::Full } else { ctx.access }; + let mut rules: Vec = ctx.rules.clone(); + rules.extend(session.rules.lock().expect("rules lock").iter().cloned()); + let name = request.tool; + match policy::verdict(access, request.effect, name, request.subject, &rules, &ctx.limits.safe_commands) { + Verdict::Allow => Ok(()), + Verdict::Deny(reason) => Err(reason), + Verdict::Ask => { + session.emit(Event::ApprovalRequested { turn, id: request.id.to_string(), approval: request.approval.clone() }); + let decision = session.inbox.lock().expect("inbox lock").decision(request.id, cancel); + if cancel.load(Ordering::Relaxed) { + return Err(STOPPED.into()); + } + match decision { + Decision::Decline => Err("The user declined this. Ask what they would like instead.".into()), + Decision::Approve => Ok(()), + Decision::AllowSimilar => { + let pattern = request.approval.similar.clone().unwrap_or_else(|| request.subject.to_string()); + session.rules.lock().expect("rules lock").push(Rule::allow(name, &pattern)); + Ok(()) + } + Decision::AllowTool => { + session.rules.lock().expect("rules lock").push(Rule::allow(name, "")); + Ok(()) + } + Decision::AllowAll => { + session.raised.store(true, Ordering::Relaxed); + Ok(()) + } + } + } + } +} + +fn finish(session: &mut Session, turn: usize, call: &ToolCall, output: Output) { + session.emit(Event::ToolEnd { + turn, + id: call.id.clone(), + ok: output.ok, + output: output.text.clone(), + diffs: output.diffs, + image: output.image, + }); + let text = if output.ok { output.text } else { format!("Error: {}", output.text) }; + session.push(Message::tool(call.id.clone(), text)); +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::options::{Limits, Toolsets}; + use crate::session::{Op, spawn}; + use quill_providers::{Model, Provider}; + use std::sync::Arc; + use std::sync::mpsc::{Receiver, channel}; + use std::time::Duration; + + struct Script { + replies: Mutex>>, + seen: Mutex>, + } + + impl Script { + fn new(replies: Vec>) -> Arc