mirror of
https://github.com/l0ng-ai/openidea.git
synced 2026-11-25 02:44:03 -10:00
Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
15b145c6dc | ||
|
|
6a5b7e042b |
No files matched your search
@@ -0,0 +1,83 @@
|
||||
---
|
||||
name: eval
|
||||
description: Run the code-intelligence evals (`pnpm eval`), pick the worst failing scenario, diagnose it from the attached timeline, fix it, prove the fix with before / after numbers measured on this machine without regressing other scenarios, and open one PR. Use for "跑 eval", "优化 Java 代码智能", "eval 失败了", an issue labelled `eval`, or any change to Java navigation / usages / gutter markers that needs numbers.
|
||||
---
|
||||
|
||||
# Eval loop: measure → fix → prove
|
||||
|
||||
`pnpm eval` drives the production workbench in Chromium against a release `openidea-server`
|
||||
with real language servers (Java / jdtls for now) and judges every scenario on what the user
|
||||
sees: time to feedback, to the first result, to the final one, and the results themselves vs
|
||||
`evals/<language>/golden/`. One machine, before and after: numbers from different machines or
|
||||
from the nightly host don't judge a fix.
|
||||
|
||||
## 0. Preconditions
|
||||
|
||||
- `jdtls` on PATH and `JAVA_HOME` pointing at a JDK of the pinned `JAVA` version (projects
|
||||
compile against it, and the JDK scenarios' results are in its sources; jdtls itself runs on
|
||||
a newer installed JDK when it needs one). Pinned versions: `.github/tool-versions.env`. A
|
||||
mismatch prints a warning and the report records both: say so in the PR when it applies.
|
||||
- First run builds `cargo build --release -p ide-host --bin openidea-server` and the perf
|
||||
bundle; later iterations of a frontend-only change can use `--no-build` after a
|
||||
`pnpm exec vite build --mode perf --outDir target/eval/dist`, a backend-only one after the
|
||||
cargo build alone.
|
||||
- Run evals one at a time on this machine, with nothing heavy (builds, other evals) beside them.
|
||||
|
||||
## 1. Baseline on the base commit
|
||||
|
||||
```sh
|
||||
git switch --detach origin/main # or the fix branch's merge base
|
||||
pnpm eval --save-baseline # target/eval/baseline.json, this machine only
|
||||
```
|
||||
|
||||
Read `target/eval/report.json`. Each verdict has `status`, `failures` (`kind`: `error`,
|
||||
`timeout`, `degraded`, `correctness`, `budget`, `golden`), `regressions`, `repro` (the command
|
||||
that reruns it) and, for failures, `diagnostics`: every command sent to the server in the
|
||||
slowest run's window (`cmd`, `start`, `ms`, `ok`, `bytes`, `items`), background tasks, server
|
||||
status changes and the server's log tail.
|
||||
|
||||
## 2. Pick one problem
|
||||
|
||||
Worst first: wrong or missing results and silent degradation, then timeouts, then the
|
||||
feedback budget (100 ms), then the slowest `completeMs`. One problem per PR. Say which
|
||||
scenario and metric, with its value vs budget.
|
||||
|
||||
## 3. Diagnose from the timeline
|
||||
|
||||
- Commands in the window ordered by `start`: what ran, what waited on what, what's serial
|
||||
that could overlap, which request returned many `items`/`bytes`, which failed.
|
||||
- `feedbackMs` far above 16 ms with a fast `firstResultMs`: the UI shows nothing while it
|
||||
waits (a hint or popup that only appears after a delay).
|
||||
- A task still running across the window: background work competing with the request.
|
||||
- For the frontend side rerun with `--trace` and open `target/eval/traces/<id>@<cond>.json`
|
||||
in Chrome's Performance panel.
|
||||
- Name the cause at class level (as in `issue-fix`): it usually affects sibling scenarios.
|
||||
|
||||
## 4. Fix, then rerun that scenario until it passes
|
||||
|
||||
```sh
|
||||
pnpm eval --only <scenario> --condition <warm|cold> # the verdict's `repro`
|
||||
```
|
||||
|
||||
Correctness is enforced, so a faster answer that drops, truncates or serves stale results
|
||||
fails. Don't trade a budget miss for a degraded answer.
|
||||
|
||||
## 5. Full suite, then PR
|
||||
|
||||
```sh
|
||||
pnpm eval # vs the baseline from step 1: no new failures or regressions
|
||||
```
|
||||
|
||||
PR per `issue-fix` §6, plus in **How it was verified** the before / after table from
|
||||
`target/eval/report.md` (both on this machine, commits named) and the tool versions line.
|
||||
|
||||
## Guard rails
|
||||
|
||||
- Goldens (`evals/*/golden/`) and budgets (`evals/budgets.json`) are human-owned. Don't edit
|
||||
them, and don't run `--update-golden`, to make a scenario pass. When a golden looks wrong
|
||||
(a tool bump, a deliberate behaviour change), stop and say so: a PR that touches them gets
|
||||
`needs-decision`.
|
||||
- Don't weaken a scenario's checks or timeouts in `evals/<language>/scenarios.ts` to pass.
|
||||
Adding a scenario (for a case the sweep or a user found) is fine; record its golden with
|
||||
`--update-golden --only <id>` and ask a person to review the file.
|
||||
- A flaky timing (passes on rerun) is not a regression: rerun once before acting on one.
|
||||
@@ -0,0 +1,91 @@
|
||||
---
|
||||
name: issue-fix
|
||||
description: Triage and fix a GitHub issue (or a user-reported bug) end to end — reproduce, find the root cause, generalise it to every sibling case, fix the class rather than the instance, verify, and open one PR. Use when given an issue URL/number or asked to fix a reported bug and open a PR ("看看这个 issue", "修一下这个 bug", "提 pr").
|
||||
---
|
||||
|
||||
# Fix an issue: from one case to the whole class
|
||||
|
||||
The reported case is one sample of a defect class. A fix that only makes the
|
||||
screenshot go away is not done: the next question is always "does this break for other
|
||||
languages / platforms / entry points too?". Answer that before anyone asks.
|
||||
|
||||
## 1. Read and reproduce
|
||||
|
||||
- `gh issue view <n> --comments` (repo `l0ng-ai/openidea`). Read attached logs/screenshots
|
||||
closely: OS, language, toolchain versions, exact error text.
|
||||
- Locate the code path and confirm the claim in code, with `file:line` evidence.
|
||||
Say plainly whether it is a real bug, a missing feature, or user environment.
|
||||
- Reproduce locally when possible (`fixtures/` projects, `/verify` for runtime). If the
|
||||
reporter's platform (often Windows/Linux) can't be reproduced here, say so up front.
|
||||
- Do not ask for a generic environment/log checklist before trying the flow and inspecting the code.
|
||||
Record the attempt and result; ask only for a fact that actually blocks the next diagnostic step.
|
||||
Missing fields, limited time, or unavailable automation are not by themselves reasons to ask the reporter.
|
||||
- Treat a maintainer-confirmed bug as an investigation task even if local reproduction fails. Distinguish
|
||||
“not reproduced here” from “not a bug”, and do not require the reporter to prove its existence again.
|
||||
|
||||
## 2. Name the root cause as a class
|
||||
|
||||
Write one sentence of the form "<mechanism> is missing/wrong, so any <X> hits it",
|
||||
not "<this button> is broken". Typical classes in this codebase:
|
||||
|
||||
- Per-language config handled for one language only (`languages/*.toml`, `ide-sdk`).
|
||||
- Platform gaps: paths, executables, shells, `.cmd`/`.exe`, separators — macOS-only code.
|
||||
- Toolchain/version discovery: one probe location, no version check, no rescan.
|
||||
- Two features each implementing half a flow and never joined (feature isolation →
|
||||
should go through an action/service).
|
||||
- State not reset on project switch / window reuse; events not scoped per window.
|
||||
- Failure surfaced as raw stderr/stack trace or retried until "crashed" instead of a
|
||||
clear status with an action.
|
||||
- UI: same primitive styled differently in N places.
|
||||
|
||||
## 3. Sweep for siblings
|
||||
|
||||
Search systematically, not by memory:
|
||||
|
||||
- Same pattern elsewhere: `git grep` the function, the config key, the error string,
|
||||
the hard-coded path/flag. Check every `languages/*.toml` entry and every platform branch.
|
||||
- Same flow for other languages/runtimes (Java ↔ Kotlin/Gradle, Python ↔ venv/uv,
|
||||
Node ↔ Deno/Bun, Go, Rust …): would they fail the same way?
|
||||
- Other callers/entry points of the same flow (menu, context menu, gutter, shortcut, CLI arg).
|
||||
- Neighbouring failure modes of the same mechanism (not installed / wrong version /
|
||||
installed but crashes / slow start / installed mid-session).
|
||||
For broad sweeps spawn one Explore agent with the class description, not the instance.
|
||||
|
||||
## 4. Decide the fix at the right altitude
|
||||
|
||||
- Fix the mechanism once (shared helper, action, config hook) so siblings are fixed
|
||||
by construction; don't patch each call site.
|
||||
- Respect `AGENTS.md` rules (crate boundaries, no cross-feature imports, `IdeResult`,
|
||||
UTF-16). If the right fix breaks a rule, pick the rule-respecting design and say why.
|
||||
- Compare with how established IDEs solve it when relevant; prefer the established answer.
|
||||
- Present: root cause, sibling table, proposed fix, what's deferred. When the user leaves
|
||||
the choice to you, go ahead without asking again.
|
||||
|
||||
## 5. Implement and test the class
|
||||
|
||||
- Tests cover the class: table-driven over languages/platforms/states, not just the
|
||||
reported input. Include the reporter's case verbatim.
|
||||
- Run the scoped checks (`pnpm vitest run <path>`, `cargo nextest run -p <crate>`), then
|
||||
`/verify` in the app for UI or runtime behaviour.
|
||||
|
||||
## 6. PR
|
||||
|
||||
- One branch `fix/<slug>`, one PR unless the user asks otherwise; `Fixes #<n>` in the body.
|
||||
- Don't stage untracked IDE-state dirs (`.ideal/`, `.openidea/`) or screenshots.
|
||||
- PR body follows `.github/pull_request_template.md`: `Closes #<n>`, then
|
||||
**What and why** (user-visible change + root cause at class level, 2–4 sentences),
|
||||
**How it was verified** (commands run and results, siblings fixed/deferred, what could break and how
|
||||
it was checked, what was not verified, e.g. "Windows not tested"; for UI changes the before/after
|
||||
screenshot paths from `/verify`), **Review focus** (optional). Short and plain.
|
||||
|
||||
## Report format
|
||||
|
||||
Reply in the user's language:
|
||||
|
||||
```
|
||||
Root cause: <one sentence, class level>
|
||||
Sibling sweep:
|
||||
| Location / case | Affected? | Action |
|
||||
Fixed / not covered (why) / not verified (platform)
|
||||
PR: <url>
|
||||
```
|
||||
@@ -0,0 +1,57 @@
|
||||
---
|
||||
name: verify
|
||||
description: Build, launch and drive the OpenIDEA desktop app through the Tauri MCP bridge to verify a change at runtime.
|
||||
---
|
||||
|
||||
# Verify OpenIDEA in the running app
|
||||
|
||||
## Launch
|
||||
|
||||
- Run the app from the worktree that holds the change: `pnpm tauri dev` in the background, logging
|
||||
into your task's scratch subdirectory. Use `pnpm dev:app` instead when your checks call
|
||||
`window.__TAURI__` from `execute_js`. The wrapper gives each worktree its own app identity, data,
|
||||
settings and Vite port, so other worktrees and the installed app don't interfere. If it reports a
|
||||
session already running for this worktree, reuse that one.
|
||||
- Once the app is up, `pnpm dev:status` lists this worktree's MCP bridges. Pass the reported
|
||||
`appIdentifier` (the port) on every `mcp__tauri__*` call. The MCP server is shared between
|
||||
sessions: never `driver_session stop` without an `appIdentifier`, and re-check `document.title` /
|
||||
`location.href` before acting if anything looks off.
|
||||
- Make sure the binary contains the change: a session already running for this worktree may be an
|
||||
older build. Restart it after Rust changes; frontend changes reload through Vite.
|
||||
- After the app restarts, `driver_session start` again for your port (a stale session says "Already connected").
|
||||
- If the `pnpm tauri dev` process exits while the app window stays open, Vite is gone and any webview
|
||||
reload shows an empty `#root`. Stop that app and start the session again.
|
||||
- Stop everything you started when done and nothing else; never use process-name kills.
|
||||
|
||||
## Driving
|
||||
|
||||
- `manage_window focus` before screenshots / timing-sensitive steps: a background window throttles timers
|
||||
(debounced LSP / VCS refreshes stall, `setTimeout` promises in `execute_js` time out) and native
|
||||
screenshots come back black.
|
||||
- Settings is a separate native window `settings-main`; pass `windowId`, focus it before screenshotting.
|
||||
- CodeMirror / xterm ignore MCP `type`. Focus the element, then `document.execCommand('insertText', false, text)`.
|
||||
For xterm Enter, dispatch a `keydown` (`key: 'Enter', keyCode: 13`) on `.xterm-helper-textarea`.
|
||||
- MCP clicks arrive with `event.detail === 0`; CodeMirror treats them as line-select clicks. Set the caret
|
||||
through the view instead: `document.querySelector('.cm-content').cmTile.view`.
|
||||
- MCP `text` strategy can resolve to a hidden node; prefer coordinates (CSS px = image px × 0.9) or CSS selectors.
|
||||
- CSS-module edits often trigger a full page reload in dev: dialogs close, Run sessions and terminal
|
||||
scrollback reset, and each reload spawns a fresh shell. Re-open what you were testing.
|
||||
|
||||
## Evidence
|
||||
|
||||
- For UI or interaction changes, capture `before.png` (on `main` or with the fix reverted) and
|
||||
`after.png` at the same state and window size, into your task's scratch subdirectory. Multi-step
|
||||
flows: a numbered series (`after-1.png`, `after-2.png`, ...).
|
||||
- Report the absolute paths; they go into the PR's **How it was verified** section and the triage
|
||||
acceptance entry. Never commit screenshots to the feature branch.
|
||||
|
||||
## Fixture
|
||||
|
||||
`fixtures/` has sample projects (go-app, rust-app, ts-app, kotlin-gradle, polyglot). Copy one into
|
||||
your scratch directory before editing it, and don't commit the IDE state it creates (`.openidea/`).
|
||||
|
||||
## Flows worth driving
|
||||
|
||||
⌘⇧O Goto File · ⌘⇧F Find in Files (preview scroll + highlight) · ⌘⇧A Find Action · editor edit/undo/autosave ·
|
||||
Terminal (Unicode, venv) · Commit view at the default narrow width · Problems · Run → Stop · Project view
|
||||
New / Delete (nested `a/b.txt` names) · ⌘, Settings search (+ Keymap filter) · Git Log on a repo without commits.
|
||||
Symlink
+1
@@ -0,0 +1 @@
|
||||
../../.agents/skills/eval
|
||||
Symlink
+1
@@ -0,0 +1 @@
|
||||
../../.agents/skills/issue-fix
|
||||
Symlink
+1
@@ -0,0 +1 @@
|
||||
../../.agents/skills/verify
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 160 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 169 KiB |
+32
-95
@@ -28,9 +28,7 @@ jobs:
|
||||
# shared runners to others. Pushes, the merge queue and manual runs always run everything.
|
||||
changes:
|
||||
name: Changes
|
||||
# Self-hosted runners (scripts/selfhost-runner) only for trusted events, and only while the
|
||||
# SELFHOSTED_RUNNERS repository variable is 'true': runs-on cannot fall back when none is online.
|
||||
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
permissions:
|
||||
pull-requests: read
|
||||
@@ -67,9 +65,8 @@ jobs:
|
||||
plugin_web='^plugins/official/[^/]+/web-src/'
|
||||
# Paths the frontend checks never read...
|
||||
backend='^(crates/|src-tauri/|sdk/|wit/|java/|fixtures/|Cargo\.(toml|lock)$|deny\.toml$|rustfmt\.toml$|rust-toolchain(\.toml)?$|\.cargo/)'
|
||||
# ...except these, which frontend tests and e2e fixtures load (the crate manifests:
|
||||
# scripts/smoke-paths.test.ts, through cargo metadata).
|
||||
read_by_web='^(fixtures/(folding|django-app)/|(crates/[^/]+/)?Cargo\.toml$|crates/ide-plugin/tests/fixtures/|crates/ide-db/(src|tests/fixtures)/snowflake/|src-tauri/(icons|capabilities)/|src-tauri/tauri\.conf\.json$)'
|
||||
# ...except these, which frontend tests and e2e fixtures load.
|
||||
read_by_web='^(fixtures/(folding|django-app)/|crates/ide-plugin/tests/fixtures/|crates/ide-db/(src|tests/fixtures)/snowflake/|src-tauri/(icons|capabilities)/|src-tauri/tauri\.conf\.json$)'
|
||||
# What the browser app and its e2e tests are built from.
|
||||
app='^(src/|e2e/|public/|index\.html$|vite\.config\.ts$|tsconfig\.json$|playwright\.config\.ts$|package\.json$|pnpm-(lock|workspace)\.yaml$|crates/ide-plugin/tests/fixtures/|src-tauri/(icons|capabilities)/|src-tauri/tauri\.conf\.json$)'
|
||||
# The plugin workspaces: the SDK, the plugins, their interface and the host's fixture plugins.
|
||||
@@ -104,50 +101,30 @@ jobs:
|
||||
name: Rust (${{ matrix.os }})
|
||||
needs: changes
|
||||
if: needs.changes.outputs.rust == 'true'
|
||||
permissions:
|
||||
contents: read
|
||||
timeout-minutes: 60
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
os: [macos-latest, ubuntu-latest, windows-latest]
|
||||
# Self-hosted runners (scripts/selfhost-runner) only for trusted events, and only while the
|
||||
# SELFHOSTED_RUNNERS repository variable is 'true': runs-on cannot fall back when none is online.
|
||||
runs-on: ${{ matrix.os == 'ubuntu-latest' && vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || matrix.os }}
|
||||
os: [macos-latest, ubuntu-22.04, windows-latest]
|
||||
runs-on: ${{ matrix.os }}
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: pnpm/action-setup@v5
|
||||
with: { version: 11 }
|
||||
- uses: actions/setup-node@v5
|
||||
with:
|
||||
node-version: 22
|
||||
cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }}
|
||||
package-manager-cache: ${{ runner.environment != 'self-hosted' }}
|
||||
with: { node-version: 22, cache: pnpm }
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
with: { components: "clippy, rustfmt" }
|
||||
# Self-hosted runners keep persistent local Cargo caches; GitHub-hosted runners use Actions cache
|
||||
# (only main saves it because saving takes minutes on Windows; PRs restore main's).
|
||||
# Only main saves the cache (saving takes minutes on Windows); PRs restore main's.
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
if: runner.environment != 'self-hosted'
|
||||
with:
|
||||
save-if: ${{ github.ref == 'refs/heads/main' }}
|
||||
# The persistent target dir makes incremental builds pay off; cap its size so it can't fill the disk.
|
||||
- name: Persistent Cargo target dir
|
||||
if: runner.environment == 'self-hosted'
|
||||
shell: bash
|
||||
run: |
|
||||
echo "CARGO_INCREMENTAL=1" >> "$GITHUB_ENV"
|
||||
size=$(du -sm "$CARGO_TARGET_DIR" 2>/dev/null | cut -f1 || true)
|
||||
if [ "${size:-0}" -gt 40000 ]; then
|
||||
echo "$CARGO_TARGET_DIR is ${size} MB; clearing it"
|
||||
rm -rf "$CARGO_TARGET_DIR"
|
||||
fi
|
||||
- uses: taiki-e/install-action@nextest
|
||||
- name: Linux deps
|
||||
if: runner.os == 'Linux'
|
||||
run: |
|
||||
pkgs=(libwebkit2gtk-4.1-dev libayatana-appindicator3-dev librsvg2-dev libxdo-dev libssl-dev patchelf)
|
||||
dpkg -s "${pkgs[@]}" >/dev/null 2>&1 || { sudo apt-get update && sudo apt-get install -y "${pkgs[@]}"; }
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y libwebkit2gtk-4.1-dev libayatana-appindicator3-dev librsvg2-dev libxdo-dev libssl-dev patchelf
|
||||
# tauri-build checks that frontendDist exists.
|
||||
- run: pnpm install --frozen-lockfile && mkdir -p dist
|
||||
shell: bash
|
||||
@@ -157,13 +134,6 @@ jobs:
|
||||
# Test fixtures write LF files; keep Git from converting them on checkout.
|
||||
- run: git config --global core.autocrlf false
|
||||
- run: cargo nextest run --workspace --no-fail-fast
|
||||
- name: Remote backend with Docker Compose
|
||||
# Self-hosted runner containers do not mount /var/run/docker.sock (scripts/selfhost-runner/README.md).
|
||||
if: runner.os == 'Linux' && runner.environment != 'self-hosted'
|
||||
run: |
|
||||
docker pull busybox:latest
|
||||
cargo nextest run -p ide-host --test remote_daemon --run-ignored only \
|
||||
-E 'test(=compose_service_survives_disconnect_and_is_removed_on_stop)'
|
||||
# nextest skips doctests; ide-command's are its compile-fail tests.
|
||||
- if: runner.os == 'Linux'
|
||||
run: cargo test --doc -p ide-command
|
||||
@@ -178,7 +148,7 @@ jobs:
|
||||
name: Rust checks
|
||||
needs: [changes, rust]
|
||||
if: always()
|
||||
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
steps:
|
||||
- env:
|
||||
@@ -195,27 +165,16 @@ jobs:
|
||||
needs: changes
|
||||
if: needs.changes.outputs.server == 'true'
|
||||
timeout-minutes: 40
|
||||
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
|
||||
runs-on: ubuntu-22.04
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
with: { targets: x86_64-unknown-linux-musl }
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
if: runner.environment != 'self-hosted'
|
||||
with: { key: server-musl }
|
||||
- name: Persistent Cargo target dir
|
||||
if: runner.environment == 'self-hosted'
|
||||
shell: bash
|
||||
run: |
|
||||
echo "CARGO_INCREMENTAL=1" >> "$GITHUB_ENV"
|
||||
size=$(du -sm "$CARGO_TARGET_DIR" 2>/dev/null | cut -f1 || true)
|
||||
if [ "${size:-0}" -gt 40000 ]; then
|
||||
echo "$CARGO_TARGET_DIR is ${size} MB; clearing it"
|
||||
rm -rf "$CARGO_TARGET_DIR"
|
||||
fi
|
||||
- run: dpkg -s musl-tools >/dev/null 2>&1 || { sudo apt-get update && sudo apt-get install -y musl-tools; }
|
||||
- run: sudo apt-get update && sudo apt-get install -y musl-tools
|
||||
- run: cargo build --locked -p ide-host --bin openidea-server --target x86_64-unknown-linux-musl
|
||||
- run: '"${CARGO_TARGET_DIR:-target}/x86_64-unknown-linux-musl/debug/openidea-server" --version'
|
||||
- run: target/x86_64-unknown-linux-musl/debug/openidea-server --version
|
||||
|
||||
# The plugin SDK, the official plugins and the test fixtures build in their
|
||||
# own workspaces (the root excludes them), so the jobs above don't see them.
|
||||
@@ -224,31 +183,18 @@ jobs:
|
||||
needs: changes
|
||||
if: needs.changes.outputs.plugins == 'true'
|
||||
timeout-minutes: 30
|
||||
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
|
||||
runs-on: ubuntu-22.04
|
||||
env:
|
||||
CARGO_TARGET_DIR: ${{ github.workspace }}/target-plugins
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
with: { targets: wasm32-wasip2, components: "clippy, rustfmt" }
|
||||
- if: runner.environment != 'self-hosted'
|
||||
shell: bash
|
||||
run: echo "CARGO_TARGET_DIR=$GITHUB_WORKSPACE/target-plugins" >> "$GITHUB_ENV"
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
if: runner.environment != 'self-hosted'
|
||||
with:
|
||||
key: plugins
|
||||
cache-directories: target-plugins
|
||||
save-if: ${{ github.ref == 'refs/heads/main' }}
|
||||
- name: Persistent Cargo target dir
|
||||
if: runner.environment == 'self-hosted'
|
||||
shell: bash
|
||||
run: |
|
||||
echo "CARGO_INCREMENTAL=1" >> "$GITHUB_ENV"
|
||||
size=$(du -sm "$CARGO_TARGET_DIR" 2>/dev/null | cut -f1 || true)
|
||||
if [ "${size:-0}" -gt 40000 ]; then
|
||||
echo "$CARGO_TARGET_DIR is ${size} MB; clearing it"
|
||||
rm -rf "$CARGO_TARGET_DIR"
|
||||
fi
|
||||
echo "CARGO_TARGET_DIR=$CARGO_TARGET_DIR/plugins" >> "$GITHUB_ENV"
|
||||
- name: Format, lint (host and wasm) and test each crate
|
||||
shell: bash
|
||||
run: |
|
||||
@@ -265,7 +211,7 @@ jobs:
|
||||
- uses: pnpm/action-setup@v5
|
||||
with: { version: 11 }
|
||||
- uses: actions/setup-node@v5
|
||||
with: { node-version: 22, package-manager-cache: false }
|
||||
with: { node-version: 22 }
|
||||
# Plugin web pages (`web-src/`, their own pnpm projects): typecheck and test.
|
||||
- name: Web pages typecheck and test
|
||||
shell: bash
|
||||
@@ -289,7 +235,7 @@ jobs:
|
||||
needs: changes
|
||||
if: needs.changes.outputs.deny == 'true'
|
||||
timeout-minutes: 15
|
||||
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
@@ -301,19 +247,13 @@ jobs:
|
||||
needs: changes
|
||||
if: needs.changes.outputs.frontend == 'true'
|
||||
timeout-minutes: 30
|
||||
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
|
||||
runs-on: ubuntu-22.04
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
# scripts/smoke-paths.test.ts runs `cargo metadata`, which is not preinstalled in the runner container.
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
if: runner.environment == 'self-hosted'
|
||||
- uses: pnpm/action-setup@v5
|
||||
with: { version: 11 }
|
||||
- uses: actions/setup-node@v5
|
||||
with:
|
||||
node-version: 22
|
||||
cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }}
|
||||
package-manager-cache: ${{ runner.environment != 'self-hosted' }}
|
||||
with: { node-version: 22, cache: pnpm }
|
||||
- run: pnpm install --frozen-lockfile
|
||||
- run: pnpm typecheck
|
||||
- run: pnpm lint
|
||||
@@ -328,41 +268,38 @@ jobs:
|
||||
needs: changes
|
||||
if: needs.changes.outputs.catalog == 'true'
|
||||
timeout-minutes: 15
|
||||
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: pnpm/action-setup@v5
|
||||
with: { version: 11 }
|
||||
- uses: actions/setup-node@v5
|
||||
with:
|
||||
node-version: 22
|
||||
cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }}
|
||||
package-manager-cache: ${{ runner.environment != 'self-hosted' }}
|
||||
with: { node-version: 22, cache: pnpm }
|
||||
- run: pnpm install --frozen-lockfile
|
||||
- run: pnpm vitest run src/platform/locales/textCatalog.test.ts
|
||||
|
||||
e2e:
|
||||
name: E2E (${{ matrix.shard }}/4)
|
||||
name: E2E (${{ matrix.shard }}/2)
|
||||
needs: changes
|
||||
if: needs.changes.outputs.e2e == 'true'
|
||||
timeout-minutes: 45
|
||||
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
|
||||
timeout-minutes: 30
|
||||
runs-on: ubuntu-24.04
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
shard: [1, 2, 3, 4]
|
||||
shard: [1, 2]
|
||||
# Browsers and their system libraries are preinstalled; keep the tag in step with @playwright/test.
|
||||
container: mcr.microsoft.com/playwright:v1.64.1-noble
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: pnpm/action-setup@v5
|
||||
with: { version: 11 }
|
||||
- uses: actions/setup-node@v5
|
||||
with:
|
||||
node-version: 22
|
||||
cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }}
|
||||
package-manager-cache: ${{ runner.environment != 'self-hosted' }}
|
||||
with: { node-version: 22, cache: pnpm }
|
||||
- run: pnpm install --frozen-lockfile
|
||||
- run: pnpm exec playwright install --with-deps chromium
|
||||
- run: pnpm e2e --shard=${{ matrix.shard }}/4
|
||||
- run: pnpm e2e --shard=${{ matrix.shard }}/2
|
||||
env:
|
||||
HOME: /root
|
||||
- uses: actions/upload-artifact@v6
|
||||
if: failure()
|
||||
with:
|
||||
|
||||
@@ -8,9 +8,6 @@ name: Language smoke
|
||||
# (Run, Run tests, the test tree, Rerun Failed Tests): smoke/run.test.ts; and debugging its
|
||||
# entry point with the debugger the IDE installs (breakpoint, frames, variables, evaluate,
|
||||
# Step Over, Resume): smoke/debug.test.ts.
|
||||
# The paths below and the Changes step's patterns must cover every file the smoke loads and
|
||||
# every crate it runs: scripts/smoke-paths.test.ts checks them (`node scripts/smoke-paths.ts
|
||||
# [file…]` lists what they miss, or the languages a change runs).
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
@@ -23,33 +20,10 @@ on:
|
||||
- "Cargo.lock"
|
||||
- "src/features/run/**"
|
||||
- "src/features/debugger/**"
|
||||
- "src/features/build/**"
|
||||
- "src/features/build-tools/**"
|
||||
- "src/platform/**"
|
||||
- "src/workbench/**"
|
||||
- "src/ui/**"
|
||||
- "src/editor/api.ts"
|
||||
- "src/editor/navigationProviders.ts"
|
||||
- "src/editor/relatedProviders.ts"
|
||||
- "src/editor/core/cm/cornerInset.ts"
|
||||
- "src/editor/core/cm/iconArea.ts"
|
||||
- "src/editor/lsp/availability.ts"
|
||||
- "src/editor/lsp/diagnostics.ts"
|
||||
- "src/editor/lsp/files.ts"
|
||||
- "src/editor/lsp/hint.ts"
|
||||
- "src/editor/lsp/lsp.ts"
|
||||
- "src/editor/lsp/positions.ts"
|
||||
- "src/bindings.ts"
|
||||
- "src/styles/tokens.css"
|
||||
- "src/test/setup.ts"
|
||||
- "src-tauri/icons/128x128.png"
|
||||
- "smoke/**"
|
||||
- "vite.config.ts"
|
||||
- "tsconfig.json"
|
||||
- "package.json"
|
||||
- "pnpm-lock.yaml"
|
||||
- "pnpm-workspace.yaml"
|
||||
- "patches/**"
|
||||
- ".github/workflows/language-smoke.yml"
|
||||
- ".github/tool-versions.env"
|
||||
pull_request:
|
||||
@@ -58,9 +32,6 @@ on:
|
||||
paths: *paths
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: language-smoke-${{ github.ref }}
|
||||
# A new push supersedes a PR's run; on main every merge runs to the end (and saves the cache).
|
||||
@@ -76,9 +47,7 @@ jobs:
|
||||
# run none; anything else runs them all. Pushes and manual runs always run them all.
|
||||
changes:
|
||||
name: Changes
|
||||
# Self-hosted runners (scripts/selfhost-runner) only for trusted events, and only while the
|
||||
# SELFHOSTED_RUNNERS repository variable is 'true': runs-on cannot fall back when none is online.
|
||||
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
permissions:
|
||||
pull-requests: read
|
||||
@@ -101,12 +70,10 @@ jobs:
|
||||
--jq '.[] | .filename, (.previous_filename // empty)' > files.txt
|
||||
cat files.txt
|
||||
# Crates outside what the smoke runs (language servers, debuggers, run configurations,
|
||||
# SDKs, build tools, the project model, Find Usages candidates, debug stream traces):
|
||||
# cargo metadata, ide-host's direct deps ide-search/ide-streams and the deps of
|
||||
# ide-lsp/dap/run/sdk/tools.
|
||||
unused='^crates/(ide-agent|ide-analysis|ide-android|ide-cli|ide-clipboard|ide-coverage|ide-db|ide-docker|ide-fonts|ide-github|ide-http|ide-mcp|ide-notebook|ide-profiler|ide-scaffold|ide-spell|ide-ssh|ide-vcs|ide-web)/'
|
||||
# SDKs, build tools and the project model): cargo metadata, deps of ide-lsp/dap/run/sdk/tools.
|
||||
unused='^crates/(ide-agent|ide-analysis|ide-android|ide-cli|ide-clipboard|ide-coverage|ide-db|ide-docker|ide-fonts|ide-github|ide-http|ide-mcp|ide-notebook|ide-profiler|ide-scaffold|ide-search|ide-spell|ide-ssh|ide-streams|ide-vcs|ide-web)/'
|
||||
# The workflow's paths, less those handled per language below.
|
||||
smoke='^(crates/|Cargo\.(toml|lock)$|src/features/(run|debugger|build|build-tools)/|src/platform/|src/workbench/|src/ui/|src/editor/(api|navigationProviders|relatedProviders|core/cm/(cornerInset|iconArea)|lsp/(availability|diagnostics|files|hint|lsp|positions))\.ts$|src/bindings\.ts$|src/styles/tokens\.css$|src/test/setup\.ts$|src-tauri/icons/128x128\.png$|smoke/|vite\.config\.ts$|tsconfig\.json$|package\.json$|pnpm-(lock|workspace)\.yaml$|patches/|\.github/workflows/language-smoke\.yml$|\.github/tool-versions\.env$)'
|
||||
smoke='^(crates/|Cargo\.(toml|lock)$|src/features/(run|debugger)/|src/platform/|smoke/|package\.json$|pnpm-lock\.yaml$|\.github/workflows/language-smoke\.yml$|\.github/tool-versions\.env$)'
|
||||
langs=""
|
||||
while read -r f; do
|
||||
case "$f" in
|
||||
@@ -138,105 +105,41 @@ jobs:
|
||||
done < files.txt
|
||||
echo "languages=$(emit "$langs")" | tee -a "$GITHUB_OUTPUT"
|
||||
|
||||
# Builds the smoke test binaries and openidea-server once for every language below.
|
||||
build:
|
||||
name: Build
|
||||
needs: changes
|
||||
if: needs.changes.outputs.languages != '[]'
|
||||
# Self-hosted runners (scripts/selfhost-runner) only for trusted events, and only while the
|
||||
# SELFHOSTED_RUNNERS repository variable is 'true': runs-on cannot fall back when none is online.
|
||||
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
|
||||
timeout-minutes: 30
|
||||
env:
|
||||
# Line tables keep test backtraces readable and the binaries handed on small without
|
||||
# stripping local-variable debuginfo from fixtures debugged in the smoke job (CodeLLDB).
|
||||
CARGO_PROFILE_DEV_DEBUG: line-tables-only
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
if: runner.environment != 'self-hosted'
|
||||
with:
|
||||
shared-key: language-smoke
|
||||
save-if: ${{ github.ref == 'refs/heads/main' }}
|
||||
- name: Persistent Cargo target dir
|
||||
if: runner.environment == 'self-hosted'
|
||||
shell: bash
|
||||
run: |
|
||||
echo "CARGO_INCREMENTAL=1" >> "$GITHUB_ENV"
|
||||
size=$(du -sm "$CARGO_TARGET_DIR" 2>/dev/null | cut -f1 || true)
|
||||
if [ "${size:-0}" -gt 40000 ]; then
|
||||
echo "$CARGO_TARGET_DIR is ${size} MB; clearing it"
|
||||
rm -rf "$CARGO_TARGET_DIR"
|
||||
fi
|
||||
- run: |
|
||||
set -euo pipefail
|
||||
mkdir -p smoke-bin
|
||||
cargo test --locked -p ide-host --test language_smoke --test project_smoke --no-run --message-format=json \
|
||||
| jq -r 'select(.reason == "compiler-artifact" and .executable != null and .target.kind == ["test"]) | "\(.target.name) \(.executable)"' \
|
||||
| while read -r name exe; do cp "$exe" "smoke-bin/$name"; done
|
||||
cargo build --locked -p ide-host --bin openidea-server
|
||||
cp "${CARGO_TARGET_DIR:-target}/debug/openidea-server" smoke-bin/
|
||||
ls -l smoke-bin
|
||||
test -x smoke-bin/language_smoke && test -x smoke-bin/project_smoke
|
||||
# A tar keeps the executable bits, which artifacts drop.
|
||||
tar -cf smoke-bin.tar smoke-bin
|
||||
- uses: actions/upload-artifact@v6
|
||||
with: { name: smoke-bin, path: smoke-bin.tar, retention-days: 1 }
|
||||
|
||||
smoke:
|
||||
name: Language smoke (${{ matrix.language }})
|
||||
needs: [changes, build]
|
||||
needs: changes
|
||||
if: needs.changes.outputs.languages != '[]'
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
language: ${{ fromJSON(needs.changes.outputs.languages) }}
|
||||
# Self-hosted runners (scripts/selfhost-runner) only for trusted events, and only while the
|
||||
# SELFHOSTED_RUNNERS repository variable is 'true': runs-on cannot fall back when none is online.
|
||||
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
|
||||
# C/C++ debug with GDB, whose DAP interpreter needs 14+: 22.04 ships 12.1, 24.04 ships 15.
|
||||
runs-on: ${{ (matrix.language == 'c' || matrix.language == 'cpp') && 'ubuntu-24.04' || 'ubuntu-22.04' }}
|
||||
timeout-minutes: 40
|
||||
# Self-hosted runner slots have distinct checkout paths (/persist/slot-<N>/work/...); override
|
||||
# the compiled-in CARGO_MANIFEST_DIR so binaries from the Build job find this slot's fixtures.
|
||||
env:
|
||||
CARGO_MANIFEST_DIR: ${{ github.workspace }}/crates/ide-host
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/checkout@v4
|
||||
# Tool versions, shared with the evals (pnpm eval).
|
||||
- run: grep -E '^[A-Z0-9_]+=' .github/tool-versions.env >> "$GITHUB_ENV"
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
with: { components: "rust-analyzer, rustfmt" }
|
||||
- uses: actions/download-artifact@v6
|
||||
with: { name: smoke-bin }
|
||||
- run: |
|
||||
tar -xf smoke-bin.tar && rm smoke-bin.tar
|
||||
mkdir -p target/debug && mv smoke-bin/openidea-server target/debug/
|
||||
|
||||
- uses: pnpm/action-setup@v5
|
||||
with: { version: 11 }
|
||||
- uses: actions/setup-node@v5
|
||||
# One build cache for every language; main saves it.
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
with:
|
||||
node-version: 22
|
||||
cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }}
|
||||
package-manager-cache: ${{ runner.environment != 'self-hosted' }}
|
||||
shared-key: language-smoke
|
||||
save-if: ${{ github.ref == 'refs/heads/main' && matrix.language == 'rust' }}
|
||||
|
||||
- uses: pnpm/action-setup@v4
|
||||
with: { version: 11 }
|
||||
- uses: actions/setup-node@v4
|
||||
with: { node-version: 22, cache: pnpm }
|
||||
- if: matrix.language == 'typescript'
|
||||
run: npm install --global "@vtsls/language-server@$VTSLS" "typescript@$TYPESCRIPT"
|
||||
|
||||
# The smoke checks C/C++ with clangd and debugs c-app with GDB's own DAP interpreter (GDB 14+).
|
||||
# The smoke builds the c-app fixture and debugs it with GDB's own DAP interpreter.
|
||||
- if: matrix.language == 'c' || matrix.language == 'cpp'
|
||||
shell: bash
|
||||
run: |
|
||||
pkgs=()
|
||||
command -v clangd >/dev/null || pkgs+=(clangd)
|
||||
command -v gdb >/dev/null || pkgs+=(gdb)
|
||||
if [ "${#pkgs[@]}" -gt 0 ]; then
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y "${pkgs[@]}"
|
||||
fi
|
||||
major=$(gdb --version | head -n1 | grep -Eo '[0-9]+\.[0-9]+' | head -n1 | cut -d. -f1)
|
||||
if [ "${major:-0}" -lt 14 ]; then
|
||||
echo "::error::GDB 14+ is required for its DAP interpreter; recreate the runner from scripts/selfhost-runner (Ubuntu 24.04)."
|
||||
exit 1
|
||||
fi
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y gdb
|
||||
|
||||
- if: matrix.language == 'python'
|
||||
uses: actions/setup-python@v5
|
||||
@@ -255,7 +158,6 @@ jobs:
|
||||
with: { distribution: temurin, java-version: "${{ env.JAVA }}" }
|
||||
- if: matrix.language == 'java'
|
||||
run: |
|
||||
command -v mvn >/dev/null || { sudo apt-get update && sudo apt-get install -y maven; }
|
||||
mkdir -p "$RUNNER_TEMP/jdtls"
|
||||
curl -fsSL "https://download.eclipse.org/jdtls/milestones/${JDTLS%-*}/jdt-language-server-$JDTLS.tar.gz" \
|
||||
| tar xz -C "$RUNNER_TEMP/jdtls"
|
||||
@@ -280,20 +182,17 @@ jobs:
|
||||
- if: matrix.language == 'php'
|
||||
run: npm install --global "intelephense@$INTELEPHENSE"
|
||||
|
||||
# The binaries from the build job, run from the crate directory as `cargo test` does.
|
||||
- working-directory: crates/ide-host
|
||||
run: ../../smoke-bin/language_smoke --ignored --exact ${{ matrix.language }}
|
||||
- run: cargo test --locked -p ide-host --test language_smoke --no-run
|
||||
- run: cargo test --locked -p ide-host --test language_smoke -- --ignored --exact ${{ matrix.language }}
|
||||
- if: matrix.language == 'java'
|
||||
working-directory: crates/ide-host
|
||||
run: ../../smoke-bin/project_smoke --ignored --exact maven_sync jdk maven_launch_classpath_uses_the_runner_jdk_classifier
|
||||
run: cargo test --locked -p ide-host --test project_smoke -- --ignored --exact maven_sync jdk maven_launch_classpath_uses_the_runner_jdk_classifier
|
||||
- if: matrix.language == 'kotlin'
|
||||
working-directory: crates/ide-host
|
||||
run: ../../smoke-bin/project_smoke --ignored --exact gradle_sync
|
||||
run: cargo test --locked -p ide-host --test project_smoke -- --ignored --exact gradle_sync
|
||||
- if: matrix.language == 'python'
|
||||
working-directory: crates/ide-host
|
||||
run: ../../smoke-bin/project_smoke --ignored --exact python_venv
|
||||
run: cargo test --locked -p ide-host --test project_smoke -- --ignored --exact python_venv
|
||||
|
||||
- run: pnpm install --frozen-lockfile
|
||||
- run: cargo build --locked -p ide-host --bin openidea-server
|
||||
- run: pnpm smoke smoke/run.test.ts -t "^${{ matrix.language }}$"
|
||||
- run: pnpm smoke smoke/debug.test.ts -t "^${{ matrix.language }}$"
|
||||
# The IDE installs the debugger from GitHub releases: authenticated, against rate limits.
|
||||
|
||||
+7
-5
@@ -33,12 +33,14 @@ target/
|
||||
test-results/
|
||||
playwright-report/
|
||||
|
||||
# Local AI agent files
|
||||
AGENTS.md
|
||||
CLAUDE.md
|
||||
# Local AI agent files. Shared skills live in .agents/skills; .claude/skills links to them.
|
||||
CLAUDE.local.md
|
||||
.agents/
|
||||
.claude/
|
||||
.claude/*
|
||||
!.claude/skills/
|
||||
.claude/skills/*
|
||||
!.claude/skills/verify
|
||||
!.claude/skills/issue-fix
|
||||
!.claude/skills/eval
|
||||
|
||||
# Local reference screenshots
|
||||
pycharm-screenshots/
|
||||
@@ -1,15 +0,0 @@
|
||||
{
|
||||
"detector": {
|
||||
"ignoreRules": [],
|
||||
"ignoreFiles": [],
|
||||
"ignoreValues": [
|
||||
{
|
||||
"rule": "gradient-text",
|
||||
"value": "*",
|
||||
"files": ["src/features/agents/Session.module.css"],
|
||||
"createdAt": "2026-11-24T14:58:12.514Z",
|
||||
"reason": "agent: .shimmer is an animated in-progress sweep on running-step labels (commit 18b286e7e, comment documents intent), not decorative gradient text"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -1,557 +0,0 @@
|
||||
{
|
||||
"schemaVersion": 2,
|
||||
"generatedAt": "2026-11-24T15:06:05+00:00",
|
||||
"title": "Design System: OpenIDEA",
|
||||
"extensions": {
|
||||
"colorMeta": {
|
||||
"workbench-blue": {
|
||||
"role": "primary",
|
||||
"displayName": "Workbench Blue",
|
||||
"canonical": "#3871e1",
|
||||
"tonalRamp": [
|
||||
"oklch(15% 0.073 262)",
|
||||
"oklch(25% 0.121 262)",
|
||||
"oklch(35% 0.17 262)",
|
||||
"oklch(48% 0.17 262)",
|
||||
"oklch(60% 0.17 262)",
|
||||
"oklch(72% 0.136 262)",
|
||||
"oklch(84% 0.078 262)",
|
||||
"oklch(95% 0.024 262)"
|
||||
]
|
||||
},
|
||||
"link-blue": {
|
||||
"role": "primary",
|
||||
"displayName": "Link Blue",
|
||||
"canonical": "#2f5eb9",
|
||||
"tonalRamp": [
|
||||
"oklch(15% 0.064 262)",
|
||||
"oklch(25% 0.107 262)",
|
||||
"oklch(35% 0.15 262)",
|
||||
"oklch(48% 0.15 262)",
|
||||
"oklch(60% 0.15 262)",
|
||||
"oklch(72% 0.12 262)",
|
||||
"oklch(84% 0.069 262)",
|
||||
"oklch(95% 0.021 262)"
|
||||
]
|
||||
},
|
||||
"selection-wash": {
|
||||
"role": "primary",
|
||||
"displayName": "Selection Wash",
|
||||
"canonical": "#d0dffe",
|
||||
"tonalRamp": [
|
||||
"oklch(15% 0.034 262)",
|
||||
"oklch(25% 0.057 262)",
|
||||
"oklch(35% 0.08 262)",
|
||||
"oklch(48% 0.08 262)",
|
||||
"oklch(60% 0.08 262)",
|
||||
"oklch(72% 0.064 262)",
|
||||
"oklch(84% 0.037 262)",
|
||||
"oklch(95% 0.011 262)"
|
||||
]
|
||||
},
|
||||
"tab-wash": {
|
||||
"role": "primary",
|
||||
"displayName": "Tab Wash",
|
||||
"canonical": "#e3ebfe",
|
||||
"tonalRamp": [
|
||||
"oklch(15% 0.026 262)",
|
||||
"oklch(25% 0.043 262)",
|
||||
"oklch(35% 0.06 262)",
|
||||
"oklch(48% 0.06 262)",
|
||||
"oklch(60% 0.06 262)",
|
||||
"oklch(72% 0.048 262)",
|
||||
"oklch(84% 0.027 262)",
|
||||
"oklch(95% 0.009 262)"
|
||||
]
|
||||
},
|
||||
"danger": {
|
||||
"role": "status",
|
||||
"displayName": "Danger",
|
||||
"canonical": "#c54e58",
|
||||
"tonalRamp": [
|
||||
"oklch(15% 0.064 18)",
|
||||
"oklch(25% 0.107 18)",
|
||||
"oklch(35% 0.15 18)",
|
||||
"oklch(48% 0.15 18)",
|
||||
"oklch(60% 0.15 18)",
|
||||
"oklch(72% 0.12 18)",
|
||||
"oklch(84% 0.069 18)",
|
||||
"oklch(95% 0.021 18)"
|
||||
]
|
||||
},
|
||||
"warning": {
|
||||
"role": "status",
|
||||
"displayName": "Warning",
|
||||
"canonical": "#a56906",
|
||||
"tonalRamp": [
|
||||
"oklch(15% 0.056 70)",
|
||||
"oklch(25% 0.093 70)",
|
||||
"oklch(35% 0.13 70)",
|
||||
"oklch(48% 0.13 70)",
|
||||
"oklch(60% 0.13 70)",
|
||||
"oklch(72% 0.104 70)",
|
||||
"oklch(84% 0.059 70)",
|
||||
"oklch(95% 0.019 70)"
|
||||
]
|
||||
},
|
||||
"success": {
|
||||
"role": "status",
|
||||
"displayName": "Success",
|
||||
"canonical": "#338555",
|
||||
"tonalRamp": [
|
||||
"oklch(15% 0.047 152)",
|
||||
"oklch(25% 0.079 152)",
|
||||
"oklch(35% 0.11 152)",
|
||||
"oklch(48% 0.11 152)",
|
||||
"oklch(60% 0.11 152)",
|
||||
"oklch(72% 0.088 152)",
|
||||
"oklch(84% 0.05 152)",
|
||||
"oklch(95% 0.016 152)"
|
||||
]
|
||||
},
|
||||
"frame-grey": {
|
||||
"role": "neutral",
|
||||
"displayName": "Frame Grey",
|
||||
"tonalRamp": [
|
||||
"oklch(15% 0.005 265)",
|
||||
"oklch(25% 0.009 265)",
|
||||
"oklch(35% 0.012 265)",
|
||||
"oklch(48% 0.012 265)",
|
||||
"oklch(60% 0.012 265)",
|
||||
"oklch(72% 0.01 265)",
|
||||
"oklch(84% 0.005 265)",
|
||||
"oklch(95% 0.002 265)"
|
||||
]
|
||||
},
|
||||
"island-white": {
|
||||
"role": "neutral",
|
||||
"displayName": "Island White",
|
||||
"tonalRamp": [
|
||||
"oklch(15% 0.005 265)",
|
||||
"oklch(25% 0.009 265)",
|
||||
"oklch(35% 0.012 265)",
|
||||
"oklch(48% 0.012 265)",
|
||||
"oklch(60% 0.012 265)",
|
||||
"oklch(72% 0.01 265)",
|
||||
"oklch(84% 0.005 265)",
|
||||
"oklch(95% 0.002 265)"
|
||||
]
|
||||
},
|
||||
"raised-paper": {
|
||||
"role": "neutral",
|
||||
"displayName": "Raised Paper",
|
||||
"tonalRamp": [
|
||||
"oklch(15% 0.005 265)",
|
||||
"oklch(25% 0.009 265)",
|
||||
"oklch(35% 0.012 265)",
|
||||
"oklch(48% 0.012 265)",
|
||||
"oklch(60% 0.012 265)",
|
||||
"oklch(72% 0.01 265)",
|
||||
"oklch(84% 0.005 265)",
|
||||
"oklch(95% 0.002 265)"
|
||||
]
|
||||
},
|
||||
"ink": {
|
||||
"role": "neutral",
|
||||
"displayName": "Ink",
|
||||
"tonalRamp": [
|
||||
"oklch(15% 0.005 265)",
|
||||
"oklch(25% 0.009 265)",
|
||||
"oklch(35% 0.012 265)",
|
||||
"oklch(48% 0.012 265)",
|
||||
"oklch(60% 0.012 265)",
|
||||
"oklch(72% 0.01 265)",
|
||||
"oklch(84% 0.005 265)",
|
||||
"oklch(95% 0.002 265)"
|
||||
]
|
||||
},
|
||||
"ink-secondary": {
|
||||
"role": "neutral",
|
||||
"displayName": "Ink Secondary",
|
||||
"tonalRamp": [
|
||||
"oklch(15% 0.005 265)",
|
||||
"oklch(25% 0.009 265)",
|
||||
"oklch(35% 0.012 265)",
|
||||
"oklch(48% 0.012 265)",
|
||||
"oklch(60% 0.012 265)",
|
||||
"oklch(72% 0.01 265)",
|
||||
"oklch(84% 0.005 265)",
|
||||
"oklch(95% 0.002 265)"
|
||||
]
|
||||
},
|
||||
"ink-muted": {
|
||||
"role": "neutral",
|
||||
"displayName": "Ink Muted",
|
||||
"tonalRamp": [
|
||||
"oklch(15% 0.005 265)",
|
||||
"oklch(25% 0.009 265)",
|
||||
"oklch(35% 0.012 265)",
|
||||
"oklch(48% 0.012 265)",
|
||||
"oklch(60% 0.012 265)",
|
||||
"oklch(72% 0.01 265)",
|
||||
"oklch(84% 0.005 265)",
|
||||
"oklch(95% 0.002 265)"
|
||||
]
|
||||
},
|
||||
"ink-faint": {
|
||||
"role": "neutral",
|
||||
"displayName": "Ink Faint",
|
||||
"tonalRamp": [
|
||||
"oklch(15% 0.005 265)",
|
||||
"oklch(25% 0.009 265)",
|
||||
"oklch(35% 0.012 265)",
|
||||
"oklch(48% 0.012 265)",
|
||||
"oklch(60% 0.012 265)",
|
||||
"oklch(72% 0.01 265)",
|
||||
"oklch(84% 0.005 265)",
|
||||
"oklch(95% 0.002 265)"
|
||||
]
|
||||
},
|
||||
"hairline": {
|
||||
"role": "neutral",
|
||||
"displayName": "Hairline",
|
||||
"tonalRamp": [
|
||||
"oklch(15% 0.005 265)",
|
||||
"oklch(25% 0.009 265)",
|
||||
"oklch(35% 0.012 265)",
|
||||
"oklch(48% 0.012 265)",
|
||||
"oklch(60% 0.012 265)",
|
||||
"oklch(72% 0.01 265)",
|
||||
"oklch(84% 0.005 265)",
|
||||
"oklch(95% 0.002 265)"
|
||||
]
|
||||
},
|
||||
"control-edge": {
|
||||
"role": "neutral",
|
||||
"displayName": "Control Edge",
|
||||
"tonalRamp": [
|
||||
"oklch(15% 0.005 265)",
|
||||
"oklch(25% 0.009 265)",
|
||||
"oklch(35% 0.012 265)",
|
||||
"oklch(48% 0.012 265)",
|
||||
"oklch(60% 0.012 265)",
|
||||
"oklch(72% 0.01 265)",
|
||||
"oklch(84% 0.005 265)",
|
||||
"oklch(95% 0.002 265)"
|
||||
]
|
||||
},
|
||||
"frame-grey-dark": {
|
||||
"role": "neutral",
|
||||
"displayName": "Frame Grey (Dark)",
|
||||
"tonalRamp": [
|
||||
"oklch(15% 0.005 265)",
|
||||
"oklch(25% 0.009 265)",
|
||||
"oklch(35% 0.012 265)",
|
||||
"oklch(48% 0.012 265)",
|
||||
"oklch(60% 0.012 265)",
|
||||
"oklch(72% 0.01 265)",
|
||||
"oklch(84% 0.005 265)",
|
||||
"oklch(95% 0.002 265)"
|
||||
]
|
||||
},
|
||||
"island-dark": {
|
||||
"role": "neutral",
|
||||
"displayName": "Island (Dark)",
|
||||
"tonalRamp": [
|
||||
"oklch(15% 0.005 265)",
|
||||
"oklch(25% 0.009 265)",
|
||||
"oklch(35% 0.012 265)",
|
||||
"oklch(48% 0.012 265)",
|
||||
"oklch(60% 0.012 265)",
|
||||
"oklch(72% 0.01 265)",
|
||||
"oklch(84% 0.005 265)",
|
||||
"oklch(95% 0.002 265)"
|
||||
]
|
||||
},
|
||||
"ink-dark": {
|
||||
"role": "neutral",
|
||||
"displayName": "Ink (Dark)",
|
||||
"tonalRamp": [
|
||||
"oklch(15% 0.005 265)",
|
||||
"oklch(25% 0.009 265)",
|
||||
"oklch(35% 0.012 265)",
|
||||
"oklch(48% 0.012 265)",
|
||||
"oklch(60% 0.012 265)",
|
||||
"oklch(72% 0.01 265)",
|
||||
"oklch(84% 0.005 265)",
|
||||
"oklch(95% 0.002 265)"
|
||||
]
|
||||
},
|
||||
"ink-strong-dark": {
|
||||
"role": "neutral",
|
||||
"displayName": "Ink Strong (Dark)",
|
||||
"tonalRamp": [
|
||||
"oklch(15% 0.005 265)",
|
||||
"oklch(25% 0.009 265)",
|
||||
"oklch(35% 0.012 265)",
|
||||
"oklch(48% 0.012 265)",
|
||||
"oklch(60% 0.012 265)",
|
||||
"oklch(72% 0.01 265)",
|
||||
"oklch(84% 0.005 265)",
|
||||
"oklch(95% 0.002 265)"
|
||||
]
|
||||
},
|
||||
"ink-muted-dark": {
|
||||
"role": "neutral",
|
||||
"displayName": "Ink Muted (Dark)",
|
||||
"tonalRamp": [
|
||||
"oklch(15% 0.005 265)",
|
||||
"oklch(25% 0.009 265)",
|
||||
"oklch(35% 0.012 265)",
|
||||
"oklch(48% 0.012 265)",
|
||||
"oklch(60% 0.012 265)",
|
||||
"oklch(72% 0.01 265)",
|
||||
"oklch(84% 0.005 265)",
|
||||
"oklch(95% 0.002 265)"
|
||||
]
|
||||
},
|
||||
"control-edge-dark": {
|
||||
"role": "neutral",
|
||||
"displayName": "Control Edge (Dark)",
|
||||
"tonalRamp": [
|
||||
"oklch(15% 0.005 265)",
|
||||
"oklch(25% 0.009 265)",
|
||||
"oklch(35% 0.012 265)",
|
||||
"oklch(48% 0.012 265)",
|
||||
"oklch(60% 0.012 265)",
|
||||
"oklch(72% 0.01 265)",
|
||||
"oklch(84% 0.005 265)",
|
||||
"oklch(95% 0.002 265)"
|
||||
]
|
||||
},
|
||||
"selection-wash-dark": {
|
||||
"role": "primary",
|
||||
"displayName": "Selection Wash (Dark)",
|
||||
"canonical": "#2a4371",
|
||||
"tonalRamp": [
|
||||
"oklch(15% 0.034 262)",
|
||||
"oklch(25% 0.057 262)",
|
||||
"oklch(35% 0.08 262)",
|
||||
"oklch(48% 0.08 262)",
|
||||
"oklch(60% 0.08 262)",
|
||||
"oklch(72% 0.064 262)",
|
||||
"oklch(84% 0.037 262)",
|
||||
"oklch(95% 0.011 262)"
|
||||
]
|
||||
}
|
||||
},
|
||||
"typographyMeta": {
|
||||
"title": {
|
||||
"displayName": "Title",
|
||||
"purpose": "Tool window titles, section headers, dialog titles; weight 600 is the main emphasis."
|
||||
},
|
||||
"body": {
|
||||
"displayName": "Body",
|
||||
"purpose": "Default UI text, menus, rows, buttons."
|
||||
},
|
||||
"label": {
|
||||
"displayName": "Label",
|
||||
"purpose": "Secondary metadata, chips, status bar, table cells; the most-used size."
|
||||
},
|
||||
"label-tiny": {
|
||||
"displayName": "Label Tiny",
|
||||
"purpose": "Stripe labels, counters, badges."
|
||||
},
|
||||
"input-large": {
|
||||
"displayName": "Input Large",
|
||||
"purpose": "Search Everywhere and other large query fields."
|
||||
},
|
||||
"code": {
|
||||
"displayName": "Code",
|
||||
"purpose": "Editor, console, terminal and every monospace preview; size and weights are user settings."
|
||||
}
|
||||
},
|
||||
"shadows": [
|
||||
{
|
||||
"name": "shadow-popup",
|
||||
"value": "0 6px 20px rgba(0, 0, 0, 0.12)",
|
||||
"purpose": "Popups, menus, completion, floating toolbar (Light; Dark uses 0.45 alpha)."
|
||||
},
|
||||
{
|
||||
"name": "shadow-dialog",
|
||||
"value": "0 0 0 0.5px rgba(0, 0, 0, 0.1), 0 10px 24px rgba(0, 0, 0, 0.1), 0 24px 72px rgba(0, 0, 0, 0.2)",
|
||||
"purpose": "Window-style shadow for dialogs (Light)."
|
||||
},
|
||||
{
|
||||
"name": "shadow-tooltip",
|
||||
"value": "0 4px 12px rgba(0, 0, 0, 0.12)",
|
||||
"purpose": "Hover tooltips (Light)."
|
||||
},
|
||||
{
|
||||
"name": "shadow-balloon",
|
||||
"value": "0 8px 24px rgba(0, 0, 0, 0.14)",
|
||||
"purpose": "Notification balloons (Light)."
|
||||
}
|
||||
],
|
||||
"motion": [
|
||||
{
|
||||
"name": "ease",
|
||||
"value": "cubic-bezier(0.2, 0, 0, 1)",
|
||||
"purpose": "Default easing for every state transition."
|
||||
},
|
||||
{
|
||||
"name": "dur-fast",
|
||||
"value": "80ms",
|
||||
"purpose": "Hover, press and focus changes on controls."
|
||||
},
|
||||
{
|
||||
"name": "dur",
|
||||
"value": "140ms",
|
||||
"purpose": "Standard transitions such as popup fades."
|
||||
},
|
||||
{
|
||||
"name": "dur-slow",
|
||||
"value": "220ms",
|
||||
"purpose": "Upper bound for any state transition."
|
||||
}
|
||||
],
|
||||
"density": [
|
||||
{
|
||||
"name": "default",
|
||||
"value": "rows 24px, fields/buttons 28px, titlebar 40px, tab bar 38px, status bar 30px, island gap 6px, island radius 10px"
|
||||
},
|
||||
{
|
||||
"name": "compact",
|
||||
"value": "rows 22px, fields/buttons 24px, titlebar/headers 32px, tab bar 32px, status bar 24px, island gap 4px, island radius 8px, chrome text -1px"
|
||||
}
|
||||
]
|
||||
},
|
||||
"components": [
|
||||
{
|
||||
"name": "Primary Button",
|
||||
"kind": "button",
|
||||
"refersTo": "button-primary",
|
||||
"description": "The one default action in a dialog or form.",
|
||||
"html": "<button class=\"ds-btn ds-btn-primary\">OK</button>",
|
||||
"css": ".ds-btn { display:inline-flex; align-items:center; justify-content:center; height:var(--h-button,28px); min-width:72px; padding:0 16px; border:0; border-radius:var(--radius-control,4px); font-family:var(--font-ui); font-size:var(--fs-ui,13px); line-height:1; cursor:default; transition:background var(--dur-fast,80ms) var(--ease), color var(--dur-fast,80ms) var(--ease), box-shadow var(--dur-fast,80ms) var(--ease); } .ds-btn:focus-visible { outline:2px solid var(--focus-ring,#3871e1); outline-offset:1px; } .ds-btn-primary { background:var(--bg-button-primary,#3871e1); color:var(--fg-button-primary,#fff); } .ds-btn-primary:hover { background:var(--bg-button-primary-hover,#3366cc); }"
|
||||
},
|
||||
{
|
||||
"name": "Secondary Button",
|
||||
"kind": "button",
|
||||
"refersTo": "button-secondary",
|
||||
"description": "Every other dialog action: Cancel, Apply, Browse.",
|
||||
"html": "<button class=\"ds-btn ds-btn-secondary\">Cancel</button>",
|
||||
"css": ".ds-btn { display:inline-flex; align-items:center; justify-content:center; height:var(--h-button,28px); min-width:72px; padding:0 16px; border:0; border-radius:var(--radius-control,4px); font-family:var(--font-ui); font-size:var(--fs-ui,13px); line-height:1; cursor:default; transition:background var(--dur-fast,80ms) var(--ease), box-shadow var(--dur-fast,80ms) var(--ease); } .ds-btn:focus-visible { outline:2px solid var(--focus-ring,#3871e1); outline-offset:1px; } .ds-btn-secondary { background:var(--bg-button,#fff); color:var(--fg-strong,#000); box-shadow:inset 0 0 0 1px var(--border-button,#d1d3d9); } .ds-btn-secondary:hover { background:color-mix(in srgb, var(--bg-button,#fff) 94%, var(--fg-strong,#000)); }"
|
||||
},
|
||||
{
|
||||
"name": "Ghost Button",
|
||||
"kind": "button",
|
||||
"refersTo": "button-ghost",
|
||||
"description": "Low-emphasis text actions in headers and inline rows.",
|
||||
"html": "<button class=\"ds-btn-ghost\">Show all</button>",
|
||||
"css": ".ds-btn-ghost { display:inline-flex; align-items:center; height:var(--h-button,28px); padding:0 8px; border:0; background:transparent; border-radius:var(--radius-control,4px); color:var(--fg-secondary,#5f6269); font-family:var(--font-ui); font-size:var(--fs-ui,13px); cursor:default; transition:background var(--dur-fast,80ms) var(--ease), color var(--dur-fast,80ms) var(--ease); } .ds-btn-ghost:hover { background:var(--bg-toolbar-hover,#00000012); color:var(--fg-strong,#000); } .ds-btn-ghost:active { background:var(--bg-toolbar-pressed,#00000020); } .ds-btn-ghost:focus-visible { outline:2px solid var(--focus-ring,#3871e1); outline-offset:1px; }"
|
||||
},
|
||||
{
|
||||
"name": "Toolbar Icon Button",
|
||||
"kind": "button",
|
||||
"refersTo": "icon-button",
|
||||
"description": "Toolbar and tool window header actions; frameless at rest, toggles show Selection Wash.",
|
||||
"html": "<div class=\"ds-iconbar\"><button class=\"ds-icon-btn\" aria-label=\"Refresh\"><svg width=\"16\" height=\"16\" viewBox=\"0 0 16 16\" fill=\"none\"><path d=\"M13 8a5 5 0 1 1-1.46-3.54M13 3v2.5h-2.5\" stroke=\"currentColor\" stroke-width=\"1.2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/></svg></button><button class=\"ds-icon-btn\" aria-label=\"Show options\" aria-pressed=\"true\"><svg width=\"16\" height=\"16\" viewBox=\"0 0 16 16\" fill=\"none\"><path d=\"M2.5 4.5h11M2.5 8h11M2.5 11.5h11\" stroke=\"currentColor\" stroke-width=\"1.2\" stroke-linecap=\"round\"/></svg></button></div>",
|
||||
"css": ".ds-iconbar { display:flex; gap:2px; } .ds-icon-btn { display:inline-flex; align-items:center; justify-content:center; width:24px; height:24px; padding:0; border:0; background:transparent; border-radius:var(--radius-toolbar-button,6px); color:var(--fg-muted,#6c707e); cursor:default; transition:background var(--dur-fast,80ms) var(--ease), color var(--dur-fast,80ms) var(--ease); } .ds-icon-btn:hover { background:var(--bg-toolbar-hover,#00000012); color:var(--fg-strong,#000); } .ds-icon-btn:active { background:var(--bg-toolbar-pressed,#00000020); } .ds-icon-btn[aria-pressed=\"true\"] { background:var(--bg-toolbar-selected,#d0dffe); color:var(--fg-strong,#000); } .ds-icon-btn:focus-visible { outline:2px solid var(--focus-ring,#3871e1); outline-offset:-2px; }"
|
||||
},
|
||||
{
|
||||
"name": "Text Field",
|
||||
"kind": "input",
|
||||
"refersTo": "input",
|
||||
"description": "Framed text field; the frame doubles in Workbench Blue on focus.",
|
||||
"html": "<input class=\"ds-input\" placeholder=\"Project name\" />",
|
||||
"css": ".ds-input { height:var(--h-field,28px); padding:0 8px; border:0; appearance:none; border-radius:var(--radius-control,4px); background:var(--bg-field,#fff); color:var(--fg-strong,#000); font-family:var(--font-ui); font-size:var(--fs-ui,13px); outline:none; box-shadow:inset 0 0 0 1px var(--border-button,#d1d3d9); transition:box-shadow var(--dur-fast,80ms) var(--ease); } .ds-input::placeholder { color:var(--fg-faint,#9fa2a8); } .ds-input:focus { box-shadow:inset 0 0 0 1px var(--focus-ring,#3871e1), 0 0 0 1px var(--focus-ring,#3871e1); }"
|
||||
},
|
||||
{
|
||||
"name": "Chip",
|
||||
"kind": "chip",
|
||||
"refersTo": "chip",
|
||||
"description": "Flat read-only fact or picker trigger, sized like the toolbar widgets.",
|
||||
"html": "<button class=\"ds-chip\"><svg width=\"14\" height=\"14\" viewBox=\"0 0 16 16\" fill=\"none\"><circle cx=\"5\" cy=\"4\" r=\"1.5\" stroke=\"currentColor\"/><circle cx=\"5\" cy=\"12\" r=\"1.5\" stroke=\"currentColor\"/><circle cx=\"11\" cy=\"6\" r=\"1.5\" stroke=\"currentColor\"/><path d=\"M5 5.5v5M11 7.5c0 2-2 2.5-6 3\" stroke=\"currentColor\"/></svg><span>main</span></button>",
|
||||
"css": ".ds-chip { display:inline-flex; align-items:center; gap:var(--space-1,4px); height:22px; padding:0 6px; border:0; background:transparent; border-radius:var(--radius-toolbar-button,6px); color:var(--fg-secondary,#5f6269); font-family:var(--font-ui); font-size:var(--fs-small,12px); line-height:1; cursor:default; transition:background var(--dur-fast,80ms) var(--ease); } .ds-chip svg { color:var(--fg-muted,#6c707e); } .ds-chip:hover { background:var(--bg-toolbar-hover,#00000012); } .ds-chip:focus-visible { outline:2px solid var(--focus-ring,#3871e1); outline-offset:-2px; }"
|
||||
},
|
||||
{
|
||||
"name": "Tree Rows",
|
||||
"kind": "custom",
|
||||
"refersTo": "list-row-selected",
|
||||
"description": "24px rows with an inset rounded selection wash; unfocused selection turns neutral.",
|
||||
"html": "<div class=\"ds-tree\" tabindex=\"0\"><div class=\"ds-row\">src</div><div class=\"ds-row ds-row-sel\">main.tsx</div><div class=\"ds-row\">workbench</div></div>",
|
||||
"css": ".ds-tree { width:220px; padding:4px var(--tree-inset,6px); background:var(--bg-island,#fff); border-radius:var(--island-radius,10px); font-family:var(--font-ui); font-size:var(--fs-ui,13px); color:var(--fg,#000); outline:none; } .ds-row { height:var(--h-row,24px); display:flex; align-items:center; padding:0 8px; border-radius:var(--radius-row,4px); } .ds-row:hover { background:var(--bg-tree-hover,#0000000a); } .ds-row-sel, .ds-row-sel:hover { background:var(--bg-tree-selected-inactive,#e9eaee); } .ds-tree:focus .ds-row-sel { background:var(--bg-tree-selected,#d0dffe); }"
|
||||
},
|
||||
{
|
||||
"name": "Island on Frame",
|
||||
"kind": "card",
|
||||
"description": "The signature layout unit: rounded islands 6px apart on the grey frame, flat at rest.",
|
||||
"html": "<div class=\"ds-frame\"><div class=\"ds-island ds-side\"><div class=\"ds-head\">Project</div></div><div class=\"ds-island ds-main\"><code>fn main() {}</code></div></div>",
|
||||
"css": ".ds-frame { display:flex; gap:var(--island-gap,6px); padding:var(--island-gap,6px); background:var(--bg-frame,#e9eaee); height:160px; } .ds-island { background:var(--bg-island,#fff); border-radius:var(--island-radius,10px); } .ds-side { width:140px; } .ds-main { flex:1; padding:12px; font-family:var(--font-mono); font-size:var(--fs-code,13px); color:var(--fg-editor,#080808); } .ds-head { height:40px; display:flex; align-items:center; padding:0 12px; font-family:var(--font-ui); font-size:var(--fs-ui,13px); font-weight:600; color:var(--fg-strong,#000); }"
|
||||
},
|
||||
{
|
||||
"name": "Tooltip",
|
||||
"kind": "custom",
|
||||
"refersTo": "tooltip",
|
||||
"description": "Floating hover help: one of the few surfaces allowed a shadow.",
|
||||
"html": "<div class=\"ds-tooltip\">Run 'main' <span class=\"ds-kbd\">⌃R</span></div>",
|
||||
"css": ".ds-tooltip { display:inline-flex; gap:8px; align-items:center; padding:6px 10px; border-radius:var(--radius-tooltip,6px); background:var(--bg-tooltip,#fff); color:var(--fg-tooltip,#000); border:1px solid var(--border-tooltip,#d1d3d9); box-shadow:var(--shadow-tooltip,0 4px 12px rgba(0,0,0,.12)); font-family:var(--font-ui); font-size:var(--fs-ui,13px); } .ds-kbd { font-family:var(--font-keys); color:var(--fg-muted,#6c707e); }"
|
||||
}
|
||||
],
|
||||
"narrative": {
|
||||
"northStar": "The Quiet Workbench",
|
||||
"overview": "The interface is a workbench, not a showroom. Code, trees, logs and diffs are the work. The chrome around them stays quiet, so the eye goes to the content and a long session stays calm.\n\nThe visual language is the JetBrains new UI in its **Islands** form, and this document records it rather than inventing one. The tokens in `src/styles/tokens.css` take their values from the Islands Light and Islands Dark theme JSON and editor schemes, at 100% zoom. Component metrics follow the matching IntelliJ theme keys (a Swing `arc` is a diameter, so the CSS radius is half of it), and component CSS names the key it follows. Behaviour follows IDEA as well, from focus and selection to dialogs and drag and drop. Users bring their JetBrains muscle memory, so a layout, metric or state that looks or behaves differently from IDEA counts as a bug, not a style choice.\n\nEvery panel sits on a grey frame as a rounded island (10px corners, 6px gaps). Depth comes from that tonal step, not from decoration. The density is that of a professional desktop tool: 13px UI text, 24px rows, 28px controls, with a compact mode that tightens all of them.\n\nThe tokens are a theming contract, not one palette. The built-in themes are Islands Light (the default), Islands Dark, High Contrast, Solarized Light and Solarized Dark. Users can also change the accent colour, give tool windows a different background from the editor, set a background image, use contrast scrollbars, or adjust colours for red-green vision deficiency. Imported IntelliJ themes and plugin themes set the same tokens at runtime. A component that looks right only in Islands Light is broken.\n\nExpression is kept to precise details: one blue accent, controls with no frame until they're hovered, hairline frames on fields and secondary buttons, and fast state transitions. Three things are rejected outright. It must not look like a web app: no big rounded cards, airy marketing whitespace, decorative gradients or illustrations. It has no second accent colour. And it has no eye-catching animation.",
|
||||
"keyCharacteristics": [
|
||||
"JetBrains new UI (Islands): metrics and behaviour follow IntelliJ's theme keys.",
|
||||
"Grey frame, rounded content islands, tonal layering only.",
|
||||
"A single accent (Workbench Blue) for primary actions, focus, selection and the active tool window.",
|
||||
"High density on a 4px grid. Compact mode is a first-class variant.",
|
||||
"Controls are quiet at rest: toolbar buttons and chips have no frame until hover.",
|
||||
"Semantic colour (status, VCS, diff, syntax) carries meaning and is never decoration.",
|
||||
"Every colour and metric is a token in `src/styles/tokens.css`. Tokens are the public theme API for plugins."
|
||||
],
|
||||
"rules": [
|
||||
{
|
||||
"name": "The IDEA Reference Rule",
|
||||
"body": "When tokens and this document don't answer a question, the answer is what IntelliJ IDEA does in the Islands theme, with the same metric and the same state behaviour. Take the value from the theme key, add it as a token, and name the key in a CSS comment.",
|
||||
"section": "overview"
|
||||
},
|
||||
{
|
||||
"name": "The One Accent Rule",
|
||||
"body": "Workbench Blue is the only accent. Every other hue in the UI belongs to a functional vocabulary (status, VCS, diff, syntax, charts) and means something specific. If a new colour has no meaning to carry, it doesn't ship.",
|
||||
"section": "colors"
|
||||
},
|
||||
{
|
||||
"name": "The Token Only Rule",
|
||||
"body": "Components never contain hex, `rgb()` or named colour literals. A new colour is a new token with a value in every theme variant, named for its purpose. Run `pnpm gen:theme-docs` afterwards.",
|
||||
"section": "colors"
|
||||
},
|
||||
{
|
||||
"name": "The Flat Scale Rule",
|
||||
"body": "The UI uses 11, 12, 13 and 15px, and nothing in between. Emphasis is weight 600 or a stronger ink colour, not a bigger size.",
|
||||
"section": "typography"
|
||||
},
|
||||
{
|
||||
"name": "The User Owns Size Rule",
|
||||
"body": "Sizes are tokens because users change them (UI font size, editor font, compact mode's -1px chrome offset). Never hard-code a font size.",
|
||||
"section": "typography"
|
||||
},
|
||||
{
|
||||
"name": "The Flat at Rest Rule",
|
||||
"body": "No docked panel, island, row or control gets a shadow. A shadow means \"this floats over the workbench and will go away\". Depth inside the layout is only ever a tonal step.",
|
||||
"section": "elevation"
|
||||
}
|
||||
],
|
||||
"dos": [
|
||||
"**Do** match IntelliJ IDEA's Islands theme for any metric or state that isn't tokenized yet. Take the value from the theme key and name the key in a CSS comment (for example `Button.arc 8 (radius 4)`).",
|
||||
"**Do** take every colour and metric from `src/styles/tokens.css`, and add a token for every theme variant when you need a new one.",
|
||||
"**Do** separate regions with a tonal step (frame against island) or a 1px hairline, never with a shadow.",
|
||||
"**Do** keep toolbar buttons and chips without a frame at rest, with the toolbar hover wash over the full hit target.",
|
||||
"**Do** draw frames and focus rings as inset box-shadows (1px at rest, doubled on focus), and keep the 2px Workbench Blue focus outline visible.",
|
||||
"**Do** check every surface in Islands Light and Islands Dark at least, as the contribution guidelines require. Check High Contrast and compact density whenever a change touches colour or metrics.",
|
||||
"**Do** keep transitions to state changes: 80ms (`--dur-fast`), 140ms (`--dur`) or at most 220ms (`--dur-slow`) with `--ease`, and none under reduced motion.",
|
||||
"**Do** use icons from the `src/ui/icons.tsx` registry, drawn in `currentColor`."
|
||||
],
|
||||
"donts": [
|
||||
"**Don't** make it look like a web app: no large rounded cards, airy marketing whitespace, decorative gradients, hero illustrations or corners above 10px. The project wash is the one gradient in the chrome. Progress shimmer counts as activity, not decoration.",
|
||||
"**Don't** invent a look or behaviour where IDEA already has one. A custom variant of an IDEA pattern breaks muscle memory.",
|
||||
"**Don't** add a second accent. Any hue other than Workbench Blue must carry status, VCS, diff, syntax or chart meaning.",
|
||||
"**Don't** add attention-seeking animation: no bounces, no staggered entrances, and no state transition over 220ms. Looping animation is only for activity that is really happening (spinners, progress, loading shimmer, a running pulse, the caret), never decoration.",
|
||||
"**Don't** put shadows on docked panels, islands, rows or controls.",
|
||||
"**Don't** use sizes off the 11/12/13/15px scale, or hard-code a font size users can change.",
|
||||
"**Don't** use hex, `rgb()` or named colours in component CSS or inline styles.",
|
||||
"**Don't** use emoji as icons or decoration, or inline ad-hoc SVG in a feature."
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -147,32 +147,6 @@
|
||||
"prefer-rest-params": "error",
|
||||
"prefer-spread": "error"
|
||||
}
|
||||
},
|
||||
{
|
||||
"files": [
|
||||
"evals/**/*.ts",
|
||||
"perf/**/*.ts",
|
||||
"smoke/**/*.ts",
|
||||
"src/features/vcs/**/*.ts",
|
||||
"src/features/vcs/**/*.tsx",
|
||||
"src/features/run/**/*.ts",
|
||||
"src/features/run/**/*.tsx",
|
||||
"src/features/database/**/*.ts",
|
||||
"src/features/database/**/*.tsx",
|
||||
"src/features/analysis/**/*.ts",
|
||||
"src/features/analysis/**/*.tsx",
|
||||
"src/features/project-tree/**/*.ts",
|
||||
"src/features/project-tree/**/*.tsx",
|
||||
"src/features/http-client/**/*.ts",
|
||||
"src/features/http-client/**/*.tsx",
|
||||
"src/platform/**/*.ts",
|
||||
"src/platform/**/*.tsx",
|
||||
"src/features/debugger/**/*.ts",
|
||||
"src/features/debugger/**/*.tsx"
|
||||
],
|
||||
"rules": {
|
||||
"no-await-in-loop": "error"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
# OpenIDEA — contributor guide
|
||||
|
||||
Rust + Tauri 2 desktop IDE with full-featured, multi-language code intelligence.
|
||||
Visual style: dark, low-contrast greys, one cool accent
|
||||
(`src/styles/tokens.css` is the source of truth for colours and metrics).
|
||||
|
||||
## Layout
|
||||
|
||||
- `crates/ide-*` — backend crates; one domain each. Depend on `ide-core` for shared
|
||||
types; never reach into another crate's internals.
|
||||
- `src-tauri/` — glue only: `state.rs` (AppState / Project), `commands/<domain>.rs`
|
||||
(desktop-only commands; the adapters of `ide-host` commands are derived), `events.rs`.
|
||||
No domain logic here.
|
||||
- `src/bindings.ts` — generated by tauri-specta (`pnpm gen:bindings`). Never edit.
|
||||
- `src/platform/` — ipc (`call`, `onIdeEvent`, `nextRequestId`), actions registry,
|
||||
keymap + dispatcher, context keys / `when` clauses, project store.
|
||||
- `src/workbench/contributions.ts` — extension points (tool windows, status items,
|
||||
overlays, editor kinds) and cross-feature services (editor, tool windows, notifications).
|
||||
- `src/ui/` — design-system primitives. `src/features/<name>/` — one feature each,
|
||||
exporting `activate()` registered in `src/features/index.ts`.
|
||||
- `languages/<id>.toml` — language definitions (detection, comments, LSP, DAP).
|
||||
- `crates/ide-host` — the `openidea-server` binary for remote development and the
|
||||
`openidea-plugin` CLI (plugin starter templates live in its `templates.rs`).
|
||||
- `wit/` — plugin interface definitions; `plugins/` — sample and bundled plugins.
|
||||
Plugin docs: `plugins/README.md`, `plugins/themes.md`.
|
||||
- `java/` — JDT LS extension bundles (`java-usages`, `kotlin-bridge`) and the patched
|
||||
Lombok agent, embedded into the app by `ide-sdk` / `ide-tools`.
|
||||
- `e2e/` — Playwright UI tests (`pnpm e2e`). `evals/` — code-intelligence evals (`pnpm eval`).
|
||||
`fixtures/` — sample projects per language for manual and automated testing.
|
||||
- `docs/` — the Mintlify documentation site (`docs.json` navigation, `en/` and `zh/` pages);
|
||||
preview with `npx mint dev` in `docs/`.
|
||||
|
||||
## Rules
|
||||
|
||||
- IPC coordinates: 0-based lines, **UTF-16** columns/offsets everywhere (`ide-core::text`).
|
||||
- Every command returns `IdeResult<T>`; convert internal errors at the crate edge.
|
||||
- Declare a command once, on its implementation: `#[command(trust = …)]` in `ide-host::ops`
|
||||
plus its module's `domain!` list (Tauri adapter, server handler and bindings are derived);
|
||||
desktop-only commands use `#[desktop_command(trust = …)]` and `desktop_domain!`.
|
||||
- Streaming → `tauri::ipc::Channel<T>`; cancellable → UI-allocated `RequestId` +
|
||||
`cancel_request`. Backend → UI notifications → `IdeEvent` via `EventSink`.
|
||||
- Long work never blocks the UI thread or a Tauri command thread: use
|
||||
`spawn_blocking`/rayon, honour `CancellationToken`.
|
||||
- Frontend features never import each other; communicate via actions, contributions
|
||||
and services. All user-invocable behaviour is an action with a stable id; default
|
||||
shortcuts live in `src/platform/keymaps/`.
|
||||
- Styling: CSS Modules + tokens only (no hex literals in components). Inline SVG
|
||||
icons from `src/ui/icons.tsx`, never emoji. Real `<button>`/`<input>`; `aria-label` on icon buttons.
|
||||
`gap` uses the `--space-*` scale (`src/styles/tokens.css`, 4px grid) where a value is on it.
|
||||
- User-visible text goes through the text catalog: add every new string to both
|
||||
`src/platform/locales/text/en.json` and `zh.json` (`textCatalog.test.ts` enforces it).
|
||||
Other locales may lack entries; their UI shows the English text until a translator adds it.
|
||||
- Keep comments sparse and purposeful; match surrounding style.
|
||||
- For GUI verification, prefer Tauri MCP; use Computer Use only when Tauri MCP is
|
||||
unavailable or cannot cover the required checks.
|
||||
|
||||
## Issues & PRs
|
||||
|
||||
Follow `CONTRIBUTING.md` and `.github/pull_request_template.md`: one problem per PR
|
||||
(`Closes #<n>` when it resolves an issue), reproduce first, keep the diff focused, short plain description, and a
|
||||
**How it was verified** section with commands run, results and, when the change alters what users
|
||||
see, before/after screenshots (not for UI removed along with a feature, copy-only or non-visual changes).
|
||||
Unclear product decisions → `needs-decision` and stop.
|
||||
|
||||
## Skills
|
||||
|
||||
Do not use Impeccable or its related skills in this repository, including globally installed copies.
|
||||
|
||||
Shared agent skills live in `.agents/skills/` (`.claude/skills/` links to them):
|
||||
`verify` drives the running app through Tauri MCP and captures screenshot evidence;
|
||||
`issue-fix` takes an issue from reproduction to one PR;
|
||||
`eval` takes a failing code-intelligence eval to a fix with before / after numbers.
|
||||
|
||||
## Commands
|
||||
|
||||
- `pnpm tauri dev` — run the app with worktree isolation (Node 22.18+).
|
||||
`pnpm dev:app` also enables the global Tauri API. `pnpm dev:status` reports
|
||||
this worktree's running MCP bridges and actual ports.
|
||||
- `pnpm build` — typecheck + bundle frontend.
|
||||
- `cargo nextest run --workspace` (or `cargo test`), `cargo clippy --workspace --all-targets -- -D warnings`, `cargo fmt --all`.
|
||||
- `cargo test -p ide-host --test language_smoke -- --ignored --exact <language>` — code intelligence
|
||||
on `fixtures/` with that language's real server installed (CI: `Language smoke`, pinned versions).
|
||||
- `pnpm smoke smoke/run.test.ts -t <language>` — run and test that language's fixture through the
|
||||
run store and a real `openidea-server` (build it first: `cargo build -p ide-host --bin openidea-server`).
|
||||
- `pnpm smoke smoke/debug.test.ts -t <language>` — debug that fixture's entry point the same way, with
|
||||
the debugger the IDE installs (on macOS, CodeLLDB and Delve may need Developer Mode:
|
||||
`sudo DevToolsSecurity -enable`).
|
||||
- `pnpm test`, `pnpm e2e`, `pnpm lint`, `pnpm format:check`, `pnpm knip`, `pnpm typecheck`,
|
||||
`pnpm gen:bindings`.
|
||||
- `pnpm perf` (UI interaction latency / frames / leaks), `pnpm perf:rust` (criterion
|
||||
benches vs budgets). Budgets: `perf/budgets.json`.
|
||||
- `pnpm eval [--only <id>] [--runs n] [--save-baseline]` — Java code intelligence (navigation,
|
||||
usages, gutter markers) in the production workbench against a release `openidea-server` and
|
||||
jdtls: time to feedback / first result / complete, results vs `evals/<language>/golden/`.
|
||||
Report: `target/eval/report.json`. Goldens and `evals/budgets.json` are changed by people only.
|
||||
Tool versions: `.github/tool-versions.env` (shared with Language smoke).
|
||||
- `pnpm release:prepare <version>` — the release commit's changes: app version everywhere,
|
||||
`Cargo.lock`, and the plugin API snapshot when `wit/` moved to a new version.
|
||||
|
||||
## Before opening a PR
|
||||
|
||||
Run what CI runs for the parts you touched:
|
||||
|
||||
- Rust: `cargo fmt --all --check`, `cargo clippy --workspace --all-targets -- -D warnings`,
|
||||
`cargo nextest run --workspace`. After changing IPC types, run `pnpm gen:bindings` and
|
||||
commit `src/bindings.ts`; CI fails if it differs.
|
||||
- Frontend: `pnpm typecheck`, `pnpm lint`, `pnpm format:check`, `pnpm knip`, `pnpm test`,
|
||||
`pnpm build`, and `pnpm e2e` for UI flows.
|
||||
- UI or runtime behaviour: verify in the running app (`.agents/skills/verify`).
|
||||
|
||||
## Pitfalls
|
||||
|
||||
- Run a subset of frontend tests with `pnpm vitest run <path>`. `pnpm test -- <path>` ignores
|
||||
the filter and runs the whole suite, which takes several minutes.
|
||||
- Don't run clippy while iterating: `pnpm tauri dev` compiles anyway. Run
|
||||
`cargo fmt --all` + `cargo clippy -p <crate> --all-targets -- -D warnings` once, right
|
||||
before committing. A cold build cache can take around 5 minutes. Run long checks one at
|
||||
a time, not chained in one shell call that may hit the 10-minute tool timeout.
|
||||
- `pnpm tauri dev` does a full debug build. Clippy only checks the code, so a passing clippy
|
||||
doesn't make the first launch fast.
|
||||
|
||||
## Parallel worktrees
|
||||
|
||||
Several worktrees can be developed and run side by side.
|
||||
|
||||
- Create one per task: `git worktree add ../<name> -b <branch> origin/main`, then
|
||||
`pnpm install` in it.
|
||||
- Launch with `pnpm tauri dev` / `pnpm dev:app`, not the raw `pnpm exec tauri dev` CLI. The
|
||||
wrapper starts Vite on a worktree-derived port (advancing if occupied), passes its actual
|
||||
URL to Tauri, and reports an existing launcher instead of starting another for the same
|
||||
worktree. HMR uses the Vite port.
|
||||
- Debug app identity, data, settings, logs and single-instance scope follow the canonical
|
||||
worktree path captured at build time, independent of launch cwd. Launching the same debug
|
||||
binary again focuses its existing instance and forwards its path argument. Different
|
||||
worktrees and the installed release can coexist. `--release` uses normal release identity
|
||||
and bypasses the development wrapper.
|
||||
- MCP bridge ports are dynamic (9223–9322). Use `pnpm dev:status`, connect to the reported
|
||||
port, verify identifier/cwd, and pass `appIdentifier: <port>` explicitly. Do not assume the
|
||||
default MCP session belongs to this worktree.
|
||||
- Keep each worktree's Cargo output directory separate; do not point `CARGO_TARGET_DIR` or
|
||||
`target` symlinks at a shared directory.
|
||||
- Each worktree's first build is cold (several minutes) and `cargo build` output takes
|
||||
around 9 GB; tests, clippy and incremental builds add more. Avoid running several heavy builds on one machine at the same time.
|
||||
- Stop only processes started for the current worktree/session. Never use broad
|
||||
process-name kills such as `pkill openidea`.
|
||||
- When done: stop that worktree's app and dev session, delete its build output, then
|
||||
`git worktree remove ../<name>`.
|
||||
@@ -1,6 +1,7 @@
|
||||
# Contributing to OpenIDEA
|
||||
|
||||
These rules apply to everyone, and to any coding agent working on their behalf.
|
||||
Project layout, coding rules, commands and checks are in [AGENTS.md](AGENTS.md).
|
||||
|
||||
## Issues
|
||||
|
||||
|
||||
Generated
+150
-156
File diff suppressed because it is too large.
Load diff
+3
-2
@@ -5,7 +5,7 @@ members = ["crates/*", "src-tauri"]
|
||||
exclude = ["sdk", "plugins"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.1.51"
|
||||
version = "0.1.49"
|
||||
edition = "2024"
|
||||
rust-version = "1.96"
|
||||
license = "Apache-2.0"
|
||||
@@ -38,7 +38,6 @@ ide-web = { path = "crates/ide-web" }
|
||||
ide-spell = { path = "crates/ide-spell" }
|
||||
ide-agent = { path = "crates/ide-agent" }
|
||||
ide-clipboard = { path = "crates/ide-clipboard" }
|
||||
ide-drag-out = { path = "crates/ide-drag-out" }
|
||||
ide-fonts = { path = "crates/ide-fonts" }
|
||||
ide-ssh = { path = "crates/ide-ssh" }
|
||||
ide-remote = { path = "crates/ide-remote" }
|
||||
@@ -69,11 +68,13 @@ tokio = { version = "1", features = ["rt-multi-thread", "macros", "sync", "time"
|
||||
tokio-util = { version = "0.7", features = ["rt"] }
|
||||
parking_lot = "0.12"
|
||||
rayon = "1"
|
||||
dashmap = "6"
|
||||
futures = "0.3"
|
||||
tokio-tungstenite = { version = "0.28", default-features = false, features = ["connect", "__rustls-tls"] }
|
||||
|
||||
# errors & diagnostics
|
||||
thiserror = "2"
|
||||
anyhow = "1"
|
||||
tracing = "0.1"
|
||||
tracing-subscriber = { version = "0.3", features = ["env-filter", "fmt"] }
|
||||
|
||||
|
||||
@@ -1,323 +0,0 @@
|
||||
---
|
||||
name: OpenIDEA
|
||||
description: The IDE you know, rebuilt in Rust.
|
||||
colors:
|
||||
workbench-blue: "#3871e1"
|
||||
link-blue: "#2f5eb9"
|
||||
frame-grey: "#e9eaee"
|
||||
island-white: "#ffffff"
|
||||
raised-paper: "#f7f8f9"
|
||||
ink: "#000000"
|
||||
ink-secondary: "#5f6269"
|
||||
ink-muted: "#6c707e"
|
||||
ink-faint: "#9fa2a8"
|
||||
hairline: "#e9eaee"
|
||||
control-edge: "#d1d3d9"
|
||||
selection-wash: "#d0dffe"
|
||||
tab-wash: "#e3ebfe"
|
||||
danger: "#c54e58"
|
||||
warning: "#a56906"
|
||||
success: "#338555"
|
||||
frame-grey-dark: "#26282c"
|
||||
island-dark: "#191a1c"
|
||||
ink-dark: "#d1d3d9"
|
||||
ink-strong-dark: "#dfe1e5"
|
||||
ink-muted-dark: "#8c8f95"
|
||||
control-edge-dark: "#40434a"
|
||||
selection-wash-dark: "#2a4371"
|
||||
typography:
|
||||
title:
|
||||
fontFamily: "Inter Variable, Inter, system-ui, -apple-system, sans-serif"
|
||||
fontSize: "13px"
|
||||
fontWeight: 600
|
||||
lineHeight: 1.4
|
||||
body:
|
||||
fontFamily: "Inter Variable, Inter, system-ui, -apple-system, sans-serif"
|
||||
fontSize: "13px"
|
||||
fontWeight: 400
|
||||
lineHeight: 1.4
|
||||
label:
|
||||
fontFamily: "Inter Variable, Inter, system-ui, -apple-system, sans-serif"
|
||||
fontSize: "12px"
|
||||
fontWeight: 400
|
||||
lineHeight: 1.4
|
||||
label-tiny:
|
||||
fontFamily: "Inter Variable, Inter, system-ui, -apple-system, sans-serif"
|
||||
fontSize: "11px"
|
||||
fontWeight: 400
|
||||
lineHeight: 1.4
|
||||
input-large:
|
||||
fontFamily: "Inter Variable, Inter, system-ui, -apple-system, sans-serif"
|
||||
fontSize: "15px"
|
||||
fontWeight: 400
|
||||
code:
|
||||
fontFamily: "JetBrains Mono, JetBrains Mono Variable, ui-monospace, Menlo, monospace"
|
||||
fontSize: "13px"
|
||||
fontWeight: 400
|
||||
lineHeight: "22px"
|
||||
fontFeature: "\"liga\" 0"
|
||||
rounded:
|
||||
small: "4px"
|
||||
control: "4px"
|
||||
row: "4px"
|
||||
selection: "5px"
|
||||
tab: "6px"
|
||||
toolbar-button: "6px"
|
||||
tooltip: "6px"
|
||||
popup: "8px"
|
||||
island: "10px"
|
||||
popup-large: "10px"
|
||||
dialog: "10px"
|
||||
spacing:
|
||||
space-0-5: "2px"
|
||||
space-1: "4px"
|
||||
space-1-5: "6px"
|
||||
space-2: "8px"
|
||||
space-3: "12px"
|
||||
space-4: "16px"
|
||||
components:
|
||||
button-primary:
|
||||
backgroundColor: "{colors.workbench-blue}"
|
||||
textColor: "{colors.island-white}"
|
||||
typography: "{typography.body}"
|
||||
rounded: "{rounded.control}"
|
||||
padding: "0 16px"
|
||||
height: "28px"
|
||||
button-secondary:
|
||||
backgroundColor: "{colors.island-white}"
|
||||
textColor: "{colors.ink}"
|
||||
typography: "{typography.body}"
|
||||
rounded: "{rounded.control}"
|
||||
padding: "0 16px"
|
||||
height: "28px"
|
||||
button-ghost:
|
||||
textColor: "{colors.ink-secondary}"
|
||||
typography: "{typography.body}"
|
||||
rounded: "{rounded.control}"
|
||||
padding: "0 8px"
|
||||
height: "28px"
|
||||
icon-button:
|
||||
textColor: "{colors.ink-muted}"
|
||||
rounded: "{rounded.toolbar-button}"
|
||||
size: "24px"
|
||||
icon-button-selected:
|
||||
backgroundColor: "{colors.selection-wash}"
|
||||
textColor: "{colors.ink}"
|
||||
rounded: "{rounded.toolbar-button}"
|
||||
size: "24px"
|
||||
input:
|
||||
backgroundColor: "{colors.island-white}"
|
||||
textColor: "{colors.ink}"
|
||||
typography: "{typography.body}"
|
||||
rounded: "{rounded.control}"
|
||||
padding: "0 8px"
|
||||
height: "28px"
|
||||
chip:
|
||||
textColor: "{colors.ink-secondary}"
|
||||
typography: "{typography.label}"
|
||||
rounded: "{rounded.toolbar-button}"
|
||||
padding: "0 6px"
|
||||
height: "22px"
|
||||
tooltip:
|
||||
backgroundColor: "{colors.island-white}"
|
||||
textColor: "{colors.ink}"
|
||||
typography: "{typography.body}"
|
||||
rounded: "{rounded.tooltip}"
|
||||
padding: "6px 10px"
|
||||
list-row-selected:
|
||||
backgroundColor: "{colors.selection-wash}"
|
||||
textColor: "{colors.ink}"
|
||||
rounded: "{rounded.row}"
|
||||
height: "24px"
|
||||
---
|
||||
|
||||
# Design System: OpenIDEA
|
||||
|
||||
## Overview
|
||||
|
||||
**Creative North Star: "The Quiet Workbench"**
|
||||
|
||||
The interface is a workbench, not a showroom. Code, trees, logs and diffs are the work. The chrome around them stays quiet, so the eye goes to the content and a long session stays calm.
|
||||
|
||||
The visual language is the JetBrains new UI in its **Islands** form, and this document records it rather than inventing one. The tokens in `src/styles/tokens.css` take their values from the Islands Light and Islands Dark theme JSON and editor schemes, at 100% zoom. Component metrics follow the matching IntelliJ theme keys (a Swing `arc` is a diameter, so the CSS radius is half of it), and component CSS names the key it follows. Behaviour follows IDEA as well, from focus and selection to dialogs and drag and drop. Users bring their JetBrains muscle memory, so a layout, metric or state that looks or behaves differently from IDEA counts as a bug, not a style choice.
|
||||
|
||||
Every panel sits on a grey frame as a rounded island (10px corners, 6px gaps). Depth comes from that tonal step, not from decoration. The density is that of a professional desktop tool: 13px UI text, 24px rows, 28px controls, with a compact mode that tightens all of them.
|
||||
|
||||
The tokens are a theming contract, not one palette. The built-in themes are Islands Light (the default), Islands Dark, High Contrast, Solarized Light and Solarized Dark. Users can also change the accent colour, give tool windows a different background from the editor, set a background image, use contrast scrollbars, or adjust colours for red-green vision deficiency. Imported IntelliJ themes and plugin themes set the same tokens at runtime. A component that looks right only in Islands Light is broken.
|
||||
|
||||
Expression is kept to precise details: one blue accent, controls with no frame until they're hovered, hairline frames on fields and secondary buttons, and fast state transitions. Three things are rejected outright. It must not look like a web app: no big rounded cards, airy marketing whitespace, decorative gradients or illustrations. It has no second accent colour. And it has no eye-catching animation.
|
||||
|
||||
### Named Rules
|
||||
|
||||
**The IDEA Reference Rule.** When tokens and this document don't answer a question, the answer is what IntelliJ IDEA does in the Islands theme, with the same metric and the same state behaviour. Take the value from the theme key, add it as a token, and name the key in a CSS comment.
|
||||
|
||||
**Key Characteristics:**
|
||||
|
||||
- JetBrains new UI (Islands): metrics and behaviour follow IntelliJ's theme keys.
|
||||
- Grey frame, rounded content islands, tonal layering only.
|
||||
- A single accent (Workbench Blue) for primary actions, focus, selection and the active tool window.
|
||||
- High density on a 4px grid. Compact mode is a first-class variant.
|
||||
- Controls are quiet at rest: toolbar buttons and chips have no frame until hover.
|
||||
- Semantic colour (status, VCS, diff, syntax) carries meaning and is never decoration.
|
||||
- Every colour and metric is a token in `src/styles/tokens.css`. Tokens are the public theme API for plugins.
|
||||
|
||||
## Colors
|
||||
|
||||
A near-neutral grey ramp with one cool blue accent. Status, VCS and syntax colours are functional vocabularies with fixed meanings. Values in the frontmatter are Islands Light (the default), and `-dark` keys are the Islands Dark counterparts. High Contrast, the Solarized themes, imported IntelliJ themes and plugin themes override the same tokens, so the names describe roles, not hexes.
|
||||
|
||||
### Project colour
|
||||
|
||||
- **Project wash** (`--project-color`): a radial tint of the project's colour (22% strength, 600 × 300px) that fades in from the frame's top-left corner, as the IDEA project gradient does. It identifies the project window. It is the one gradient in the chrome.
|
||||
|
||||
### Primary
|
||||
|
||||
- **Workbench Blue** (`--accent`): primary buttons, the focus ring, the selected-and-active stripe button, and search-match emphasis. The appearance setting can override it, so components reference `--accent`, never the hex.
|
||||
- **Link Blue** (`--link`): inline links. In Dark it lightens to stay readable on the dark islands.
|
||||
|
||||
### Neutral
|
||||
|
||||
- **Frame Grey** (`--bg-frame`): the window frame behind the islands, and the stripes (the tool window button bars).
|
||||
- **Island White** (`--bg-island`, `--bg-app`): editor and tool window surfaces. This is where the work lives.
|
||||
- **Raised Paper** (`--bg-elev`, `--bg-dialog`): dialog bodies and inline popups, one tonal step off the island.
|
||||
- **Ink** (`--fg`, `--fg-strong`): primary text. **Ink Secondary / Muted / Faint** (`--fg-secondary`, `--fg-muted`, `--fg-faint`): metadata, icons and placeholders, then disabled text.
|
||||
- **Hairline** (`--border`): dividers between regions inside an island. **Control Edge** (`--border-button`, `--border-strong`): the 1px inset frame of fields and secondary buttons.
|
||||
- **Selection Wash** (`--bg-tree-selected`, `--bg-selected`, `--bg-toolbar-selected`): the selected row in focused trees and lists, and pressed-on toolbar toggles. When the tree loses focus, the selection drops to the neutral `--bg-tree-selected-inactive`.
|
||||
|
||||
### Functional vocabularies
|
||||
|
||||
- **Status:** `--danger`, `--warning`, `--success` and `--info`, each with `--bg-feedback-*` and `--border-feedback-*` pairs for banners.
|
||||
- **VCS and diff:** `--vcs-*` for file status in trees and tabs, `--gutter-*` for gutter marks, and `--diff-*` for diff fills and their error-stripe marks.
|
||||
- **Syntax:** `--syn-*`, from the editor colour scheme. Users and plugins replace these per scheme.
|
||||
|
||||
### Named Rules
|
||||
|
||||
**The One Accent Rule.** Workbench Blue is the only accent. Every other hue in the UI belongs to a functional vocabulary (status, VCS, diff, syntax, charts) and means something specific. If a new colour has no meaning to carry, it doesn't ship.
|
||||
|
||||
**The Token Only Rule.** Components never contain hex, `rgb()` or named colour literals. A new colour is a new token with a value in every theme variant, named for its purpose. Run `pnpm gen:theme-docs` afterwards.
|
||||
|
||||
## Typography
|
||||
|
||||
**UI Font:** Inter Variable (with system-ui and -apple-system fallbacks)
|
||||
**Code Font:** JetBrains Mono (with ui-monospace and Menlo fallbacks)
|
||||
**Key Glyph Font:** the system UI font (`--font-keys`), so shortcut glyphs such as ⌘⇧⌥⌃↵ render as they do in native menus
|
||||
|
||||
**Character:** a neutral sans for chrome and a coding mono for content. Neither performs. Hierarchy comes from weight and colour, not size.
|
||||
|
||||
### Hierarchy
|
||||
|
||||
- **Title** (600, 13px, 1.4): tool window titles, section headers, dialog titles and emphasised names. Weight 600 is the system's main emphasis.
|
||||
- **Body** (400, 13px, 1.4): default UI text, menus, tree and list rows, and buttons.
|
||||
- **Label** (400, 12px): the most common size. It covers secondary metadata, chips, status bar items, table cells and hints.
|
||||
- **Label Tiny** (400, 11px): stripe labels, counters and badges.
|
||||
- **Input Large** (400, 15px): Search Everywhere and similar large query fields.
|
||||
- **Code** (400, 13px, 22px line height): the editor, console, terminal and every monospace preview. Ligatures are off by default and follow the `editor.ligatures` setting. Users set the weights (`--fw-code`, `--fw-code-bold`) and the size.
|
||||
|
||||
### Named Rules
|
||||
|
||||
**The Flat Scale Rule.** The UI uses 11, 12, 13 and 15px, and nothing in between. Emphasis is weight 600 or a stronger ink colour, not a bigger size.
|
||||
|
||||
**The User Owns Size Rule.** Sizes are tokens because users change them (UI font size, editor font, compact mode's -1px chrome offset). Never hard-code a font size.
|
||||
|
||||
## Layout
|
||||
|
||||
The window is a grey frame holding docked islands: the editor in the centre, tool windows around it, stripes of tool window buttons on the edges (58px wide), a titlebar with the main toolbar (40px), and a status bar (30px). The status bar sits directly on the frame with no divider. Islands sit 6px apart and have 10px corners. Trees are inset 6px inside their island.
|
||||
|
||||
Spacing follows a 4px grid (`--space-0-5` to `--space-4`, 2–16px). It is used for gaps, with component heights doing most of the rhythm work: rows 24px, fields and buttons 28px, small controls 24px or 20px, tabs 28px in a 38px tab bar, and tool window headers 40px.
|
||||
|
||||
**Compact mode** (`data-compact`) is a full variant, not an afterthought. Rows drop to 22px, fields and buttons to 24px, the titlebar and headers to 32px, the status bar to 24px, the island gap to 4px and island corners to 8px, and chrome text gets 1px smaller. Every layout must hold in both modes.
|
||||
|
||||
The app is a desktop window. It is never a scrolling page: the document never scrolls, and every scroll region is its own scroller inside an island. Dialogs open about 10vh from the top and below the titlebar. Wide reading surfaces, such as an agent conversation, cap their width (900px) inside the island.
|
||||
|
||||
## Elevation & Depth
|
||||
|
||||
Static layout is flat and layered by tone. The grey frame sits under white islands (in Dark, a lighter frame under darker islands). Shadows exist only on surfaces that float above the layout: popups, menus, dialogs, tooltips, balloons, undocked tool windows and drag ghosts. Dialogs use a window-style shadow, because they are separate windows in spirit.
|
||||
|
||||
### Shadow Vocabulary
|
||||
|
||||
- **Popup** (`--shadow-popup`; Light `0 6px 20px rgba(0,0,0,0.12)`): popups, menus, completion and the floating editor toolbar.
|
||||
- **Dialog** (`--shadow-dialog`): a hairline ring plus two soft drops, like a native window shadow.
|
||||
- **Tooltip** (`--shadow-tooltip`) and **Balloon** (`--shadow-balloon`): small and medium drops for hover help and notifications.
|
||||
|
||||
### Named Rules
|
||||
|
||||
**The Flat at Rest Rule.** No docked panel, island, row or control gets a shadow. A shadow means "this floats over the workbench and will go away". Depth inside the layout is only ever a tonal step.
|
||||
|
||||
## Shapes
|
||||
|
||||
Corners scale with the size of the surface. Small controls get 4px (buttons, fields, combos, rows, small icon buttons). Toolbar buttons, chips, tabs and tooltips get 6px, and selection highlights get 5px. Popups get 8–10px, and islands and dialogs get 10px. Compact mode tightens island corners to 8px and combo corners to 2px. Frames are drawn as 1px inset box-shadows rather than borders, so they never shift layout and can double on focus. There are no pills, circles (apart from macOS window buttons and status dots), or rounding beyond 10px.
|
||||
|
||||
## Components
|
||||
|
||||
Quiet and dependable. Components don't call attention to themselves, they behave the same everywhere, and they come from `src/ui/` primitives before anything custom.
|
||||
|
||||
### Buttons
|
||||
|
||||
- **Shape:** gently rounded (4px). Minimum width 72px, 28px tall, 16px horizontal padding. The small variant is 24px tall with 10px padding.
|
||||
- **Primary:** Workbench Blue fill with white text. Hover mixes it toward the strong ink colour (`--accent-hover`). Use it for one default action per dialog.
|
||||
- **Secondary:** island-coloured with a 1px Control Edge inset frame. Hover darkens the fill by about 6%.
|
||||
- **Ghost:** no fill or frame, secondary ink colour, 8px padding. Hover shows the toolbar hover wash and strong ink. Pressed is a stronger wash.
|
||||
- **Focus:** a 2px Workbench Blue outline, 1px outside the button. **Disabled:** transparent fill, faint text and a hairline frame.
|
||||
- **Motion:** background, colour and frame change over 80ms (`--dur-fast`) with `--ease`. There are no transitions under `prefers-reduced-motion`, and forced-colours mode gets a real border.
|
||||
|
||||
### Icon Buttons (toolbar actions)
|
||||
|
||||
- 20, 24 or 28px square, with 6px corners (4px at 20px). The icon is muted at rest.
|
||||
- Hover shows the toolbar hover wash (`--bg-toolbar-hover`, a translucent ink) across the full hit target, and the icon turns strong ink. Pressed shows `--bg-toolbar-pressed`.
|
||||
- A toggled-on button (`aria-pressed`) shows Selection Wash. The focus ring is drawn 2px inside the button.
|
||||
- Tone variants (`danger`, `accent`) recolour only the icon.
|
||||
|
||||
### Chips
|
||||
|
||||
- **Style:** flat, like the main toolbar's project and branch widgets. They are 22px tall with 6px corners, have no fill or frame at rest, and use 12px secondary ink with a muted icon.
|
||||
- **State:** a chip that opens a picker gets the toolbar hover wash. A read-only chip never changes on hover.
|
||||
|
||||
### Inputs / Fields
|
||||
|
||||
- **Style:** 28px tall with 8px horizontal padding and 4px corners. Island fill with a 1px Control Edge inset frame. Placeholders use the faint ink.
|
||||
- **Focus:** the frame turns Workbench Blue and doubles with a 1px outer ring, drawn entirely with box-shadow.
|
||||
- **Error:** the same doubled ring in `--danger`. **Disabled:** transparent fill, faint text and a hairline frame.
|
||||
- Search fields have a muted leading icon. Monospace fields use the code font.
|
||||
|
||||
### Lists and Trees
|
||||
|
||||
- Rows are 24px (22px compact). The selection is a 4–5px rounded wash inset from the island edge, not a full-bleed bar.
|
||||
- A focused selection uses Selection Wash, and an unfocused one drops to a neutral grey. Hover is a faint translucent wash. Search matches use `--bg-search-match`.
|
||||
|
||||
### Popups, Menus and Dialogs
|
||||
|
||||
- **Popups and menus:** `--bg-popup` with a 1px popup frame, 10px corners (`--radius-popup-large`) and the popup shadow.
|
||||
- **Dialogs:** Raised Paper body with 10px corners and the dialog shadow. They behave like IDEA's dialogs, which are separate windows: the modal layer blocks the workbench but never dims it. The footer actions are right-aligned buttons. Focus returns to wherever it came from when the dialog closes.
|
||||
|
||||
### Tabs
|
||||
|
||||
- 28px tabs (24px compact) in a 38px bar, with 6px corners and 8px horizontal padding.
|
||||
- As in IDEA, only the part holding focus accents its selected tab (`--bg-tab-selected` with `--border-tab-selected`). Elsewhere the selected tab drops to the neutral inactive pair.
|
||||
- **Tooltips:** 6px corners with 6px × 10px padding, using `--bg-tooltip` (white in Light, dark grey in Dark) and the tooltip shadow.
|
||||
|
||||
### Tool Window Stripes (signature)
|
||||
|
||||
The edge bars of tool window buttons are 58px wide on Frame Grey, with icons over 11px labels. Hover and selected states are translucent ink washes. The selected button of the active tool window fills with Workbench Blue and white content. This is the one place the accent fills a large shape in the chrome, and it marks the active tool window.
|
||||
|
||||
## Do's and Don'ts
|
||||
|
||||
### Do:
|
||||
|
||||
- **Do** match IntelliJ IDEA's Islands theme for any metric or state that isn't tokenized yet. Take the value from the theme key and name the key in a CSS comment (for example `Button.arc 8 (radius 4)`).
|
||||
- **Do** take every colour and metric from `src/styles/tokens.css`, and add a token for every theme variant when you need a new one.
|
||||
- **Do** separate regions with a tonal step (frame against island) or a 1px hairline, never with a shadow.
|
||||
- **Do** keep toolbar buttons and chips without a frame at rest, with the toolbar hover wash over the full hit target.
|
||||
- **Do** draw frames and focus rings as inset box-shadows (1px at rest, doubled on focus), and keep the 2px Workbench Blue focus outline visible.
|
||||
- **Do** check every surface in Islands Light and Islands Dark at least, as the contribution guidelines require. Check High Contrast and compact density whenever a change touches colour or metrics.
|
||||
- **Do** keep transitions to state changes: 80ms (`--dur-fast`), 140ms (`--dur`) or at most 220ms (`--dur-slow`) with `--ease`, and none under reduced motion.
|
||||
- **Do** use icons from the `src/ui/icons.tsx` registry, drawn in `currentColor`.
|
||||
|
||||
### Don't:
|
||||
|
||||
- **Don't** make it look like a web app: no large rounded cards, airy marketing whitespace, decorative gradients, hero illustrations or corners above 10px. The project wash is the one gradient in the chrome. Progress shimmer counts as activity, not decoration.
|
||||
- **Don't** invent a look or behaviour where IDEA already has one. A custom variant of an IDEA pattern breaks muscle memory.
|
||||
- **Don't** add a second accent. Any hue other than Workbench Blue must carry status, VCS, diff, syntax or chart meaning.
|
||||
- **Don't** add attention-seeking animation: no bounces, no staggered entrances, and no state transition over 220ms. Looping animation is only for activity that is really happening (spinners, progress, loading shimmer, a running pulse, the caret), never decoration.
|
||||
- **Don't** put shadows on docked panels, islands, rows or controls.
|
||||
- **Don't** use sizes off the 11/12/13/15px scale, or hard-code a font size users can change.
|
||||
- **Don't** use hex, `rgb()` or named colours in component CSS or inline styles.
|
||||
- **Don't** use emoji as icons or decoration, or inline ad-hoc SVG in a feature.
|
||||
-73
@@ -1,73 +0,0 @@
|
||||
# Product
|
||||
|
||||
<!-- impeccable:product-schema 1 -->
|
||||
|
||||
## Platform
|
||||
|
||||
web
|
||||
|
||||
The IDE is a Tauri desktop app for macOS, Windows and Linux. Its UI is a web frontend (React, CSS Modules) inside the system webview, with its own design language rather than each operating system's native one. Scope: this record covers the IDE application only. The openidea.sh docs site and home page (`docs/`) are out of scope.
|
||||
|
||||
## Users
|
||||
|
||||
- **Primary: JetBrains users who want something lighter.** They already know the IntelliJ IDEA keymap, tool windows and search-everything habits, and find IDEA heavy and slow. They do everyday multi-language development on the desktop: editing, navigating, refactoring, running and debugging, Git, terminal, database and HTTP clients.
|
||||
- **Primary: developers working with AI coding agents.** They run CLI agents (Claude Code, Codex, Gemini CLI, Copilot, Cursor and others over ACP) inside the IDE as tasks, often several at once, each in its own Git worktree or in the checkout. They review the agents' diffs, answer their permission requests, and give agents the IDE's own tools through the built-in MCP server.
|
||||
- **Secondary: people moving from VS Code or Eclipse.** Their keymaps are built in.
|
||||
|
||||
## Product Purpose
|
||||
|
||||
OpenIDEA brings the IntelliJ IDEA way of working to a native app with a Rust core: editor, code insight, debugger, Git, terminal, database and HTTP clients for 60+ languages. Success means people who know the IDEA way of working can switch without relearning anything, and it opens, responds and quits much faster while using a fraction of the memory.
|
||||
|
||||
## Positioning
|
||||
|
||||
"The IDE you know, rebuilt in Rust." The habits are familiar (keymap, tool windows, Search Everywhere, Alt+Enter), the app is open source (Apache 2.0), and performance is measured: on the published benchmark, the window opens in 0.9 s against 3.1 s and the app uses 169 MB against 2011 MB. Coding agents are part of the IDE (tasks, worktrees, diffs and the IDE's tools over MCP) rather than a separate chat app.
|
||||
|
||||
## Operating Context
|
||||
|
||||
- Long sessions in one desktop window: the editor in the middle, tool windows docked around it, and keyboard-first navigation (Search Everywhere, Find Action, Go to Class/File/Symbol).
|
||||
- Local projects, and remote development over SSH or in dev containers through the `openidea-server` backend.
|
||||
- Agent tasks running alongside the developer's own work, with diff review and permission prompts.
|
||||
- Built-in themes: Islands Light (the default), Islands Dark, High Contrast, Solarized Light and Solarized Dark, with an option to follow the OS's light or dark mode. Users can import IntelliJ themes and `.icls` colour schemes, and plugins add more themes.
|
||||
|
||||
## Capabilities and Constraints
|
||||
|
||||
Hard constraints future work must preserve:
|
||||
|
||||
1. The default keymap and interaction habits stay the same as IDEA's.
|
||||
2. All user-visible text is written in English and must also have a Chinese translation, through the text catalog (`T`, translated `aria-label`).
|
||||
3. WebKit floor is Safari 15.4 (macOS 12). No regex lookbehind or `v` flag, no import attributes, and no newer runtime APIs in startup code. `scripts/check-webkit.ts` enforces this.
|
||||
4. Design tokens in `src/styles/tokens.css` are the public theme API for plugins. Components use tokens only and never colour literals. A new token needs a value for every theme variant, and the docs must be regenerated with `pnpm gen:theme-docs`.
|
||||
5. Every user operation is an action with a stable id, reachable from the keyboard and Find Action, not only by mouse.
|
||||
6. No emoji as icons or decoration, in the UI or in user-visible text. Icons come from the `src/ui/icons.tsx` registry.
|
||||
7. Performance (startup, memory, idle CPU) is the core selling point. UI work must not slow it down.
|
||||
|
||||
Other facts:
|
||||
|
||||
- Plugins are sandboxed WebAssembly components that add actions, completion, quick fixes, tool windows, custom editors, themes, file icons and languages. The plugin API is still a preview.
|
||||
- UI is built from the primitives in `src/ui/` (Button, Dialog, Popup, Menu, List, Tree, Tabs and others). Workbench pieces come from contributions, not custom layout.
|
||||
|
||||
## Brand Commitments
|
||||
|
||||
- Name: OpenIDEA. Wordmarks are in `src-tauri/icons/source/` (`openidea-wordmark.svg` and `openidea-wordmark-dark.svg`).
|
||||
- Not affiliated with JetBrains. IntelliJ IDEA is a trademark of JetBrains s.r.o.
|
||||
- Voice is plain, short and factual. It states measurements with their conditions rather than superlatives.
|
||||
|
||||
## Evidence on Hand
|
||||
|
||||
- Benchmark table and method: `README.md`, `perf/compare`. The conditions are stated with it: freqtrade, warm caches, median of 5 runs, Windows 11, 32-core AMD.
|
||||
- Demo video linked from `README.md`.
|
||||
- No testimonials, customer logos or user counts exist. Do not fabricate them.
|
||||
|
||||
## Product Principles
|
||||
|
||||
1. **Familiar first.** Existing IDEA habits must keep working. New behaviour must not break that muscle memory.
|
||||
2. **Speed is a feature.** Every surface is judged by how much it costs in startup time, memory and responsiveness.
|
||||
3. **Keyboard reachable.** If something can be done, it is an action that can be found and bound.
|
||||
4. **Agents work inside the IDE.** Agent work is reviewed and controlled with the IDE's own tools: diffs, worktrees and permissions.
|
||||
5. **Themeable by contract.** Visual decisions go through tokens that themes and plugins can rely on.
|
||||
|
||||
## Accessibility & Inclusion
|
||||
|
||||
- Use real `<button>` and `<input>` elements or the primitives that render them. Every icon-only button has a translated `aria-label`.
|
||||
- Keep focus visible and predictable. Dialogs and popups return focus to where it came from.
|
||||
- A dark high-contrast theme (`dark-hc`) ships and must be kept working.
|
||||
@@ -68,7 +68,7 @@ the [official plugins](plugins/official). The plugin API is still a preview.
|
||||
- [Discord](https://discord.gg/2Zy4yn7gP) — questions, feedback and release news.
|
||||
- WeChat group — scan to join:
|
||||
|
||||
<img src=".github/assets/wechat-group-4.png" alt="WeChat group QR code" width="200">
|
||||
<img src=".github/assets/wechat-group-3.png" alt="WeChat group QR code" width="200">
|
||||
|
||||
- Contributing: see [CONTRIBUTING.md](CONTRIBUTING.md) and the [contributor docs](https://openidea.sh/en/contribute/setup).
|
||||
|
||||
|
||||
+1
-1
@@ -68,7 +68,7 @@ Eklentileri Ayarlar › Eklentiler (Settings › Plugins) bölümünden kur ya d
|
||||
- [Discord](https://discord.gg/2Zy4yn7gP): sorular, geri bildirim ve sürüm haberleri.
|
||||
- WeChat grubu, katılmak için kodu okut:
|
||||
|
||||
<img src=".github/assets/wechat-group-4.png" alt="WeChat grubu QR kodu" width="200">
|
||||
<img src=".github/assets/wechat-group-3.png" alt="WeChat grubu QR kodu" width="200">
|
||||
|
||||
- Katkıda bulunmak için: [CONTRIBUTING.md](CONTRIBUTING.md) ve [katkıcı belgeleri](https://openidea.sh/en/contribute/setup).
|
||||
|
||||
|
||||
+1
-1
@@ -66,7 +66,7 @@ WebAssembly 组件运行;主题、图标主题和语言无需编写代码。
|
||||
- [Discord](https://discord.gg/2Zy4yn7gP):提问、反馈和版本发布消息。
|
||||
- 微信群,扫码加入:
|
||||
|
||||
<img src=".github/assets/wechat-group-4.png" alt="微信群二维码" width="200">
|
||||
<img src=".github/assets/wechat-group-3.png" alt="微信群二维码" width="200">
|
||||
|
||||
- 参与贡献:参见 [CONTRIBUTING.md](CONTRIBUTING.md) 和[贡献者文档](https://openidea.sh/zh/contribute/setup)。
|
||||
|
||||
|
||||
+2
-10
@@ -6,13 +6,6 @@
|
||||
[Simple Icons](https://github.com/simple-icons/simple-icons), retrieved through
|
||||
Iconify (`simple-icons:angular`, `simple-icons:astro`, `simple-icons:cplusplus`, `simple-icons:dart`, `simple-icons:deepseek`, `simple-icons:django`, `simple-icons:dotnet`, `simple-icons:elixir`, `simple-icons:express`, `simple-icons:fastapi`, `simple-icons:flask`, `simple-icons:flutter`, `simple-icons:go`, `simple-icons:haskell`, `simple-icons:html5`, `simple-icons:kotlin`, `simple-icons:ktor`, `simple-icons:laravel`, `simple-icons:nestjs`, `simple-icons:nextdotjs`, `simple-icons:nodedotjs`, `simple-icons:nuxt`, `simple-icons:openjdk`, `simple-icons:phoenixframework`, `simple-icons:php`, `simple-icons:python`, `simple-icons:quarkus`, `simple-icons:ruby`, `simple-icons:rubyonrails`, `simple-icons:rust`, `simple-icons:scala`, `simple-icons:springboot`, `simple-icons:svelte`, `simple-icons:swift`, `simple-icons:symfony`, `simple-icons:vite`, `simple-icons:zig`) and filled with the brand colors (the standard icon grey for black logos). Licensed under [CC0 1.0 Universal](https://github.com/simple-icons/simple-icons/blob/develop/LICENSE.md).
|
||||
|
||||
## Microsoft ConPTY
|
||||
|
||||
`crates/ide-core/resources/conpty/` contains the unmodified Microsoft Windows Console
|
||||
ConPTY runtime 1.25.260930003, embedded in Windows builds. Copyright (c) Microsoft
|
||||
Corporation. Licensed under MIT; see its [license](crates/ide-core/resources/conpty/LICENSE)
|
||||
and [package provenance](crates/ide-core/resources/conpty/README.md).
|
||||
|
||||
## Project Lombok
|
||||
|
||||
`java/lombok/lombok-1.18.48-openidea.3.jar` contains Project Lombok v1.18.48 with the Equinox
|
||||
@@ -42,8 +35,7 @@ icon set, copied unmodified (some renamed) from JetBrains' open-source repositor
|
||||
→ `maven/`); `plugins/gradle` (`icons/expui/gradle` → `toolwindows/gradle`,
|
||||
`icons/expui/gradleLoadChanges` → `build/gradleLoadChanges`,
|
||||
`icons/expui/gradle`, `icons/gradleSubproject` → `gradle/`);
|
||||
`platform/external-system-impl` (`icons/newui/task` → `externalSystem/task`);
|
||||
`platform/dvcs-impl` (`icons/new/cherryPick` → `vcs/cherryPick`).
|
||||
`platform/external-system-impl` (`icons/newui/task` → `externalSystem/task`).
|
||||
Copyright 2000-2026 JetBrains s.r.o. and contributors. Apache License 2.0 (below).
|
||||
- [intellij-plugins](https://github.com/JetBrains/intellij-plugins) (each plugin
|
||||
carries its own licence): `protobuf/protoeditor-core` (`newui/protoFile` →
|
||||
@@ -73,7 +65,7 @@ At render time `src/ui/icons.tsx` may recolour monochrome icons to `currentColor
|
||||
These icons of [flutter-intellij](https://github.com/flutter/flutter-intellij) (commit `d02813ad5890`) are used
|
||||
under the BSD 3-Clause License:
|
||||
|
||||
- `src/ui/expui/flutter/*.svg`: the Flutter tool window icons, copied unmodified from
|
||||
- `src/ui/expui/flutter/*.svg`: the DevTools tool window icons, copied unmodified from
|
||||
`resources/icons/expui/`.
|
||||
- `src/ui/expui/flutter/[email protected]` and `[email protected]`: the Flutter outline's widget
|
||||
icons, `resources/icons/custom/[email protected]` and `[email protected]`, renamed, content unmodified.
|
||||
|
||||
@@ -7,7 +7,6 @@ license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
encoding_rs.workspace = true
|
||||
base64.workspace = true
|
||||
blake3.workspace = true
|
||||
ide-vfs.workspace = true
|
||||
ide-core.workspace = true
|
||||
@@ -26,10 +25,6 @@ dunce.workspace = true
|
||||
uuid.workspace = true
|
||||
tempfile.workspace = true
|
||||
which = "8"
|
||||
semver = "1"
|
||||
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
rustix = { version = "1", features = ["fs"] }
|
||||
|
||||
[dev-dependencies]
|
||||
tokio = { workspace = true, features = ["test-util"] }
|
||||
@@ -51,7 +51,7 @@ async fn run_once(
|
||||
move || launch.resolve_for_launch_with_copilot_env(&root, strip_ambient)
|
||||
})
|
||||
.await
|
||||
.map_err(|e| e.to_string())??;
|
||||
.map_err(|e| e.to_string())?;
|
||||
let cwd = dunce::canonicalize(&root).unwrap_or(root);
|
||||
let updates = Arc::new(DiscoveryUpdates { provider: spec.id.clone(), ..Default::default() });
|
||||
let client = Dialect::wrap(updates.clone());
|
||||
@@ -196,11 +196,11 @@ fn levels_for_model_from_slice(options: &[AgentConfigOption]) -> Vec<AgentConfig
|
||||
.filter(|o| config::is_per_model_option(o))
|
||||
.cloned()
|
||||
.map(|mut o| {
|
||||
if config::is_context_option(&o.id) || config::is_fast_option(&o.id) {
|
||||
if config::is_context_option(&o.id) {
|
||||
if o.category.is_none() {
|
||||
o.category = Some("model_config".into());
|
||||
}
|
||||
} else if o.category.is_none() {
|
||||
} else if o.category.as_deref() != Some("thought_level") {
|
||||
o.category = Some("thought_level".into());
|
||||
}
|
||||
o
|
||||
|
||||
@@ -168,12 +168,11 @@ async fn discovery_reads_effort_and_fast_from_session_new_then_stops_the_agent()
|
||||
assert_eq!(calls.iter().map(|(m, _)| m.as_str()).collect::<Vec<_>>(), ["initialize", "session/new"]);
|
||||
assert_eq!(calls[1].1["mcpServers"], json!([]));
|
||||
let cursor = mgr.providers().into_iter().find(|p| p.id == "cursor").unwrap();
|
||||
// Per-model options (`effort`, `fast`, `context`) belong to the session's model, not provider-wide config.
|
||||
assert!(!cursor.config.iter().any(|o| o.id == "fast"));
|
||||
assert_eq!(cursor.thought_levels.keys().collect::<Vec<_>>(), ["m1"]);
|
||||
let fast = cursor.thought_levels["m1"].iter().find(|o| o.id == "fast").expect("fast option");
|
||||
let fast = cursor.config.iter().find(|o| o.id == "fast").expect("fast option");
|
||||
assert_eq!(fast.category.as_deref(), Some("model_config"));
|
||||
assert_eq!(fast.current.as_deref(), Some("false"));
|
||||
// The effort option belongs to the session's model; m2 may offer other levels.
|
||||
assert_eq!(cursor.thought_levels.keys().collect::<Vec<_>>(), ["m1"]);
|
||||
assert!(cursor.thought_levels["m1"].iter().any(|o| o.category.as_deref() == Some("thought_level")));
|
||||
}
|
||||
|
||||
|
||||
@@ -15,8 +15,6 @@ use tokio::time::Instant;
|
||||
|
||||
const FRESH_FOR: Duration = Duration::from_secs(15 * 60);
|
||||
const COOLDOWN: Duration = Duration::from_secs(30);
|
||||
/// Persisted catalog layout version; bump when option classification changes so stale per-model entries re-discover.
|
||||
const CATALOG_SCHEMA: u8 = 2;
|
||||
|
||||
type Store = Arc<Mutex<HashMap<String, Known>>>;
|
||||
type Key = (PathBuf, PathBuf, String);
|
||||
@@ -82,8 +80,6 @@ impl CatalogData {
|
||||
pub(crate) struct SavedCatalog {
|
||||
/// An opaque cryptographic digest, never raw launch arguments or credentials.
|
||||
fingerprint: String,
|
||||
#[serde(default)]
|
||||
schema: u8,
|
||||
#[serde(flatten)]
|
||||
catalog: CatalogData,
|
||||
}
|
||||
@@ -115,7 +111,7 @@ impl LaunchContext {
|
||||
hash.update(&(value.len() as u64).to_le_bytes());
|
||||
hash.update(value);
|
||||
}
|
||||
field(&mut hash, b"openidea-model-catalog-v2");
|
||||
field(&mut hash, b"openidea-model-catalog-v1");
|
||||
field(
|
||||
&mut hash,
|
||||
match self.spec.driver {
|
||||
@@ -198,21 +194,14 @@ impl AgentCatalogs {
|
||||
(shared.paths.models_file.clone(), shared.paths.project_root.clone(), provider.to_owned())
|
||||
}
|
||||
|
||||
/// The catalog saved for this project, for before this run looked anything up.
|
||||
fn saved(shared: &Shared, provider: &str) -> CatalogData {
|
||||
fn fallback(shared: &Shared, provider: &str) -> CatalogData {
|
||||
let cache = shared.known.lock();
|
||||
cache
|
||||
.get(provider)
|
||||
.and_then(|known| known.catalogs.get(&shared.root_key()))
|
||||
.map(|saved| {
|
||||
let mut catalog = saved.catalog.clone();
|
||||
if saved.schema < CATALOG_SCHEMA {
|
||||
catalog.refreshed_at_ms = None;
|
||||
catalog.thought_levels.clear();
|
||||
}
|
||||
catalog
|
||||
})
|
||||
.unwrap_or_default()
|
||||
let Some(known) = cache.get(provider) else { return CatalogData::default() };
|
||||
known.catalogs.get(&shared.root_key()).map(|saved| saved.catalog.clone()).unwrap_or_else(|| CatalogData {
|
||||
config: known.config.clone(),
|
||||
thought_levels: known.thought_levels.clone(),
|
||||
refreshed_at_ms: None,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn cached(&self, shared: &Shared, provider: &str) -> CatalogData {
|
||||
@@ -221,14 +210,32 @@ impl AgentCatalogs {
|
||||
.entries
|
||||
.get(&Self::key(shared, provider))
|
||||
.and_then(|e| e.catalog.clone())
|
||||
.unwrap_or_else(|| Self::saved(shared, provider))
|
||||
.unwrap_or_else(|| Self::fallback(shared, provider))
|
||||
}
|
||||
|
||||
/// The entry a chat may switch to: exactly what the picker offers from the cached catalog,
|
||||
/// however long ago it was read. Refreshing keeps that catalog current; a listed model is
|
||||
/// never refused because the catalog aged.
|
||||
pub(super) fn listed_model(&self, shared: &Shared, provider: &str, model: &str) -> Option<crate::AgentConfigValue> {
|
||||
self.cached(shared, provider).model_option()?.values.iter().find(|value| value.value == model).cloned()
|
||||
/// Availability for an explicit session switch must come from a recent discovery for this
|
||||
/// launch, not from the display fallback or a different project's session report.
|
||||
pub(super) fn fresh_model(
|
||||
&self,
|
||||
shared: &Shared,
|
||||
spec: &provider::ProviderSpec,
|
||||
model: &str,
|
||||
) -> Option<crate::AgentConfigValue> {
|
||||
let context = LaunchContext::new(spec.clone(), &shared.paths.project_root);
|
||||
let select = |catalog: &CatalogData| {
|
||||
let age = self.epoch_ms() - catalog.refreshed_at_ms?;
|
||||
if !(0.0..FRESH_FOR.as_millis() as f64).contains(&age) {
|
||||
return None;
|
||||
}
|
||||
catalog.model_option()?.values.iter().find(|value| value.value == model).cloned()
|
||||
};
|
||||
let state = self.state.lock();
|
||||
if let Some(entry) = state.entries.get(&Self::key(shared, &spec.id)) {
|
||||
return select(entry.catalog.as_ref().filter(|_| entry.context == context)?);
|
||||
}
|
||||
let cache = shared.known.lock();
|
||||
let saved = cache.get(&spec.id)?.catalogs.get(&shared.root_key())?;
|
||||
(saved.fingerprint == context.fingerprint()).then(|| select(&saved.catalog)).flatten()
|
||||
}
|
||||
|
||||
pub(crate) fn levels(&self, shared: &Shared, provider: &str, model: &str) -> Option<Vec<AgentConfigOption>> {
|
||||
@@ -239,8 +246,14 @@ impl AgentCatalogs {
|
||||
}
|
||||
drop(state);
|
||||
let cache = shared.known.lock();
|
||||
let saved = cache.get(provider)?.catalogs.get(&shared.root_key())?;
|
||||
(saved.schema >= CATALOG_SCHEMA).then(|| saved.catalog.thought_levels.get(model).cloned()).flatten()
|
||||
let known = cache.get(provider)?;
|
||||
known
|
||||
.catalogs
|
||||
.get(&shared.root_key())
|
||||
.map(|saved| &saved.catalog.thought_levels)
|
||||
.unwrap_or(&known.thought_levels)
|
||||
.get(model)
|
||||
.cloned()
|
||||
}
|
||||
|
||||
pub(super) async fn load_levels(
|
||||
@@ -284,7 +297,7 @@ impl AgentCatalogs {
|
||||
}
|
||||
|
||||
fn snapshot(&self, shared: &Shared, provider: &str, entry: &Entry) -> AgentModelCatalog {
|
||||
let catalog = entry.catalog.clone().unwrap_or_default();
|
||||
let catalog = entry.catalog.clone().unwrap_or_else(|| Self::fallback(shared, provider));
|
||||
let model_failure = entry.requested_model.as_ref().and_then(|model| entry.model_failures.get(model));
|
||||
let unknown_model = entry
|
||||
.requested_model
|
||||
@@ -293,7 +306,7 @@ impl AgentCatalogs {
|
||||
AgentModelCatalog {
|
||||
provider: provider.to_owned(),
|
||||
config: shared.config_for_new_task(catalog.config, provider),
|
||||
thought_levels: shared.thought_levels_for_new_task(catalog.thought_levels, provider),
|
||||
thought_levels: catalog.thought_levels,
|
||||
refreshing: entry.flight.is_some(),
|
||||
refreshed_at_ms: catalog.refreshed_at_ms,
|
||||
retry_at_ms: model_failure
|
||||
@@ -330,9 +343,7 @@ impl AgentCatalogs {
|
||||
let generation = state.generation;
|
||||
let saved =
|
||||
shared.known.lock().get(&spec.id).and_then(|known| known.catalogs.get(&shared.root_key())).cloned();
|
||||
let matching = saved
|
||||
.as_ref()
|
||||
.is_some_and(|saved| saved.schema >= CATALOG_SCHEMA && saved.fingerprint == context.fingerprint());
|
||||
let matching = saved.as_ref().is_some_and(|saved| saved.fingerprint == context.fingerprint());
|
||||
let age = saved
|
||||
.as_ref()
|
||||
.filter(|_| matching)
|
||||
@@ -371,11 +382,12 @@ impl AgentCatalogs {
|
||||
},
|
||||
);
|
||||
}
|
||||
let fallback =
|
||||
state.entries.get(&key).filter(|entry| entry.catalog.is_none()).map(|_| Self::fallback(shared, &spec.id));
|
||||
state.generation += 1;
|
||||
let generation = state.generation;
|
||||
let entry = state.entries.get_mut(&key).expect("catalog entry");
|
||||
let empty = CatalogData::default();
|
||||
let catalog = entry.catalog.as_ref().unwrap_or(&empty);
|
||||
let catalog = entry.catalog.as_ref().or(fallback.as_ref()).expect("cached catalog");
|
||||
let fresh = entry.successful.is_some_and(|at| now.duration_since(at) < FRESH_FOR);
|
||||
let target = model
|
||||
.filter(|model| {
|
||||
@@ -484,7 +496,7 @@ impl AgentCatalogs {
|
||||
entry.flight_model = None;
|
||||
let success = match result {
|
||||
Ok(found) => {
|
||||
let previous = entry.catalog.take().unwrap_or_default();
|
||||
let previous = entry.catalog.take().unwrap_or_else(|| Self::fallback(shared, &key.2));
|
||||
let mut cache = shared.known.lock();
|
||||
let known = cache.entry(key.2.clone()).or_default();
|
||||
let mut catalog = CatalogData {
|
||||
@@ -498,16 +510,16 @@ impl AgentCatalogs {
|
||||
catalog.thought_levels.insert(model, levels);
|
||||
}
|
||||
}
|
||||
known.config = catalog.config.clone();
|
||||
known.thought_levels = catalog.thought_levels.clone();
|
||||
if let Some(commands) = found.commands {
|
||||
known.commands.insert(shared.root_key(), commands);
|
||||
}
|
||||
known.authoritative = true;
|
||||
known.refreshed_at_ms = catalog.refreshed_at_ms;
|
||||
known.catalogs.insert(
|
||||
shared.root_key(),
|
||||
SavedCatalog {
|
||||
fingerprint: entry.context.fingerprint(),
|
||||
schema: CATALOG_SCHEMA,
|
||||
catalog: catalog.clone(),
|
||||
},
|
||||
SavedCatalog { fingerprint: entry.context.fingerprint(), catalog: catalog.clone() },
|
||||
);
|
||||
entry.catalog = Some(catalog);
|
||||
shared.persist_known(&cache);
|
||||
|
||||
@@ -169,12 +169,9 @@ fn make_manager_at(root: &Path, models_file: &Path, catalogs: Arc<AgentCatalogs>
|
||||
|
||||
fn events(manager: &AgentManager) -> mpsc::UnboundedReceiver<AgentEvent> {
|
||||
let (tx, rx) = mpsc::unbounded_channel();
|
||||
manager.subscribe_as(
|
||||
"",
|
||||
Arc::new(move |event| {
|
||||
let _ = tx.send(event);
|
||||
}),
|
||||
);
|
||||
manager.subscribe(Arc::new(move |event| {
|
||||
let _ = tx.send(event);
|
||||
}));
|
||||
rx
|
||||
}
|
||||
|
||||
@@ -233,9 +230,11 @@ async fn successful_refresh_replaces_models_and_efforts_and_old_sessions_cannot_
|
||||
let manager = make_manager(tmp.path(), catalogs.clone(), &harness);
|
||||
let mut events = events(&manager);
|
||||
let old = config::options_of(&response(&["old", "retained"], &["low", "high"]));
|
||||
manager.shared.remember(PROVIDER, Some(&old), None, Some("old"));
|
||||
let cached = manager.refresh_models(PROVIDER, false, None).unwrap();
|
||||
assert!(cached.refreshing);
|
||||
assert!(model_values(&cached).is_empty(), "nothing is offered before the first discovery");
|
||||
assert_eq!(model_values(&cached), ["old", "retained"]);
|
||||
assert!(cached.refreshed_at_ms.is_none(), "session reports are not fresh discovery");
|
||||
let pending = harness.next().await;
|
||||
assert_eq!(pending.params["mcpServers"], json!([]));
|
||||
pending.reply.send(Ok(response(&["retained", "new"], &["medium"]))).unwrap();
|
||||
@@ -259,10 +258,7 @@ async fn successful_refresh_replaces_models_and_efforts_and_old_sessions_cannot_
|
||||
assert_eq!(provider.config, fresh.config);
|
||||
restored.shared.remember(PROVIDER, Some(&old), None, Some("old"));
|
||||
assert_eq!(restored.shared.known_config(PROVIDER), fresh.config);
|
||||
assert_eq!(
|
||||
restored.shared.paths.catalogs.cached(&restored.shared, PROVIDER).refreshed_at_ms,
|
||||
fresh.refreshed_at_ms
|
||||
);
|
||||
assert_eq!(restored.shared.known.lock()[PROVIDER].refreshed_at_ms, fresh.refreshed_at_ms);
|
||||
assert!(!tmp.path().join("store").exists(), "refresh never creates tasks");
|
||||
}
|
||||
|
||||
@@ -312,11 +308,6 @@ async fn discovered_model_reloads_the_same_session_on_the_next_message() {
|
||||
switch_chat_model(ChatSwitch::Resume).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn discovered_model_from_an_aged_catalog_can_still_be_selected() {
|
||||
switch_chat_model(ChatSwitch::Aged).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn discovered_model_leaves_the_original_session_intact_after_resume_failure() {
|
||||
switch_chat_model(ChatSwitch::ResumeFails).await;
|
||||
@@ -365,7 +356,6 @@ async fn discovered_model_lookup_does_not_overwrite_a_newer_selection() {
|
||||
#[derive(Clone, Copy)]
|
||||
enum ChatSwitch {
|
||||
Live,
|
||||
Aged,
|
||||
Resume,
|
||||
ResumeFails,
|
||||
Unavailable,
|
||||
@@ -386,8 +376,7 @@ async fn switch_chat_model(scenario: ChatSwitch) {
|
||||
let mut harness = Harness::with_initialize(json!({
|
||||
"protocolVersion": 1, "agentCapabilities": { "loadSession": true }
|
||||
}));
|
||||
let catalogs = Arc::new(AgentCatalogs::default());
|
||||
let mut manager = make_manager(tmp.path(), catalogs.clone(), &harness);
|
||||
let mut manager = make_manager(tmp.path(), Arc::default(), &harness);
|
||||
let task = manager
|
||||
.create(NewAgentTask {
|
||||
prompt: AgentPrompt { text: "first".into(), ..Default::default() },
|
||||
@@ -454,11 +443,7 @@ async fn switch_chat_model(scenario: ChatSwitch) {
|
||||
}
|
||||
assert_eq!(manager.task(&task.id).unwrap().state.lock().task.config, before_config);
|
||||
|
||||
let live = matches!(scenario, ChatSwitch::Live | ChatSwitch::Aged);
|
||||
if matches!(scenario, ChatSwitch::Aged) {
|
||||
// The catalog stays what the picker offers however long ago it was read.
|
||||
advance(&catalogs, 20 * 60);
|
||||
}
|
||||
let live = matches!(scenario, ChatSwitch::Live);
|
||||
let resumed_launch = if missing_settings { 3 } else { 2 };
|
||||
let load_fails = matches!(scenario, ChatSwitch::ResumeFails);
|
||||
let unavailable = matches!(scenario, ChatSwitch::Unavailable);
|
||||
@@ -492,7 +477,7 @@ async fn switch_chat_model(scenario: ChatSwitch) {
|
||||
set.reply.send(Err("Sign in required".into())).unwrap();
|
||||
let error = switching.await.unwrap_err().to_string();
|
||||
assert!(error.contains("Sign in required"), "{error}");
|
||||
assert_eq!(manager.subscribe_as("", Arc::new(|_| {})).remove(0).config, before_config);
|
||||
assert_eq!(manager.subscribe(Arc::new(|_| {})).remove(0).config, before_config);
|
||||
assert!(harness.pending.try_recv().is_err());
|
||||
manager.shutdown();
|
||||
return;
|
||||
@@ -501,7 +486,7 @@ async fn switch_chat_model(scenario: ChatSwitch) {
|
||||
manager.set_config(&task.id, "model", "old".into()).await.unwrap();
|
||||
set.reply.send(Ok(response(&["new", "old"], &["quick", "thorough"]))).unwrap();
|
||||
switching.await.unwrap();
|
||||
let task = manager.subscribe_as("", Arc::new(|_| {})).remove(0);
|
||||
let task = manager.subscribe(Arc::new(|_| {})).remove(0);
|
||||
assert_eq!(task.config.iter().find(|o| o.id == "model").unwrap().current.as_deref(), Some("old"));
|
||||
assert_eq!(task.config.iter().find(|o| o.id == "effort").unwrap().current.as_deref(), Some("low"));
|
||||
assert!(harness.pending.try_recv().is_err());
|
||||
@@ -532,7 +517,7 @@ async fn switch_chat_model(scenario: ChatSwitch) {
|
||||
let effort = update.config.iter().find(|o| o.id == "effort").unwrap();
|
||||
assert_eq!(effort.values.iter().map(|v| v.value.as_str()).collect::<Vec<_>>(), ["quick", "thorough"]);
|
||||
}
|
||||
let snapshot = |manager: &AgentManager| manager.subscribe_as("", Arc::new(|_| {})).remove(0);
|
||||
let snapshot = |manager: &AgentManager| manager.subscribe(Arc::new(|_| {})).remove(0);
|
||||
let current = snapshot(&manager);
|
||||
assert_eq!(current.config.iter().find(|o| o.id == "model").unwrap().current.as_deref(), Some("new"));
|
||||
assert_eq!(current.model.as_deref(), Some(if live { "new" } else { "old" }));
|
||||
@@ -699,7 +684,7 @@ async fn next_chat_request(
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_cache_from_before_project_catalogs_offers_nothing_until_discovery_succeeds() {
|
||||
async fn legacy_cache_loads_without_claiming_authoritative_freshness() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
configure(tmp.path(), "one");
|
||||
let options = config::options_of(&response(&["legacy"], &["low"]));
|
||||
@@ -715,11 +700,12 @@ async fn a_cache_from_before_project_catalogs_offers_nothing_until_discovery_suc
|
||||
let manager = make_manager(tmp.path(), Arc::default(), &harness);
|
||||
let mut events = events(&manager);
|
||||
let cached = manager.refresh_models(PROVIDER, false, None).unwrap();
|
||||
assert!(model_values(&cached).is_empty());
|
||||
assert_eq!(model_values(&cached), ["legacy"]);
|
||||
assert!(cached.refreshing && cached.refreshed_at_ms.is_none());
|
||||
harness.next().await.reply.send(Ok(response(&["current"], &["low"]))).unwrap();
|
||||
let found = completed(&mut events).await;
|
||||
assert_eq!(model_values(&found), ["current"]);
|
||||
harness.next().await.reply.send(Err("Sign in required".into())).unwrap();
|
||||
let failed = completed(&mut events).await;
|
||||
assert_eq!(failed.config, cached.config);
|
||||
assert!(failed.error.as_deref().unwrap().contains("Sign in required"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
|
||||
@@ -1,395 +0,0 @@
|
||||
//! Checks and updates only the global npm installation selected by the agent launcher.
|
||||
use crate::{AgentManager, AgentSource, provider};
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult, error::ErrorKind};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
use specta::Type;
|
||||
use std::{
|
||||
fs, io,
|
||||
path::{Path, PathBuf},
|
||||
process::Command,
|
||||
};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
pub struct AgentCliOffer {
|
||||
pub current: String,
|
||||
pub latest: String,
|
||||
pub prefix: PathBuf,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(tag = "status", rename_all = "camelCase")]
|
||||
pub enum AgentCliUpdateResult {
|
||||
Available(AgentCliOffer),
|
||||
Permission(AgentCliOffer),
|
||||
Current { current: String },
|
||||
Channel { current: String },
|
||||
Updated { current: String },
|
||||
Unmanaged,
|
||||
Error { code: String },
|
||||
}
|
||||
|
||||
pub(crate) fn package(id: &str) -> Option<&'static str> {
|
||||
Some(match id {
|
||||
"claude" => "@anthropic-ai/claude-code",
|
||||
"codex" => "@openai/codex",
|
||||
"gemini" => "@google/gemini-cli",
|
||||
"opencode" => "opencode-ai",
|
||||
"copilot" => "@github/copilot",
|
||||
"qwen" => "@qwen-code/qwen-code",
|
||||
"auggie" => "@augmentcode/auggie",
|
||||
"qoder" => "@qoder-ai/qodercli",
|
||||
"omp" => "@oh-my-pi/pi-coding-agent",
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
impl AgentManager {
|
||||
pub fn cli_update(
|
||||
&self,
|
||||
id: &str,
|
||||
offer: Option<&AgentCliOffer>,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<AgentCliUpdateResult> {
|
||||
let spec = self.shared.spec(id).ok_or_else(|| IdeError::invalid(format!("unknown agent {id}")))?;
|
||||
let (Some(pkg), Some(builtin)) = (package(id), provider::builtin_spec(id)) else {
|
||||
return Ok(AgentCliUpdateResult::Unmanaged);
|
||||
};
|
||||
if spec.source != AgentSource::Builtin {
|
||||
return Ok(AgentCliUpdateResult::Unmanaged);
|
||||
}
|
||||
let Ok(npm) = which::which("npm") else { return Ok(AgentCliUpdateResult::Unmanaged) };
|
||||
let program = spec.resolve_for_launch(&self.shared.paths.project_root).command;
|
||||
match maintain(&npm, Path::new(&program), &builtin.command, pkg, offer, cancel) {
|
||||
Err(e) if e.kind == ErrorKind::Unavailable => Ok(AgentCliUpdateResult::Error { code: e.message }),
|
||||
result => result,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct Installation {
|
||||
modules: PathBuf,
|
||||
folder: PathBuf,
|
||||
link: PathBuf,
|
||||
}
|
||||
|
||||
impl Installation {
|
||||
fn at(prefix: &Path, pkg: &str, bin: &str) -> Self {
|
||||
let modules = prefix.join(if cfg!(windows) { "node_modules" } else { "lib/node_modules" });
|
||||
let link = if cfg!(windows) { prefix.join(format!("{bin}.cmd")) } else { prefix.join("bin").join(bin) };
|
||||
Self { folder: modules.join(pkg), modules, link }
|
||||
}
|
||||
|
||||
fn version(&self, program: &Path, pkg: &str, bin: &str) -> IdeResult<Option<String>> {
|
||||
if !program.is_absolute() || !self.folder.try_exists()? || !self.link.try_exists()? || !program.try_exists()? {
|
||||
return Ok(None);
|
||||
}
|
||||
let folder = dunce::canonicalize(&self.folder)?;
|
||||
if fs::symlink_metadata(&self.folder)?.is_symlink()
|
||||
|| dunce::canonicalize(program)? != dunce::canonicalize(&self.link)?
|
||||
{
|
||||
return Ok(None);
|
||||
}
|
||||
let manifest = self.folder.join("package.json");
|
||||
if !manifest.try_exists()? {
|
||||
return Ok(None);
|
||||
}
|
||||
let manifest: Value = serde_json::from_slice(&fs::read(manifest)?)
|
||||
.map_err(|_| IdeError::invalid("Invalid npm package manifest"))?;
|
||||
let entry = manifest["bin"].as_str().or_else(|| manifest["bin"][bin].as_str());
|
||||
let Some(entry) = entry.filter(|_| manifest["name"] == pkg) else { return Ok(None) };
|
||||
let Some(version) = manifest["version"].as_str() else {
|
||||
return Err(IdeError::invalid("Missing npm package version"));
|
||||
};
|
||||
let entry = folder.join(entry);
|
||||
if !entry.try_exists()? {
|
||||
return Ok(None);
|
||||
}
|
||||
let entry = dunce::canonicalize(entry)?;
|
||||
if !entry.starts_with(&folder) {
|
||||
return Ok(None);
|
||||
}
|
||||
#[cfg(unix)]
|
||||
let owns = fs::symlink_metadata(&self.link)?.is_symlink() && dunce::canonicalize(&self.link)? == entry;
|
||||
#[cfg(windows)]
|
||||
let owns = {
|
||||
let prefix = dunce::canonicalize(self.link.parent().unwrap())?;
|
||||
let Ok(target) = entry.strip_prefix(prefix) else { return Ok(None) };
|
||||
let needle = format!("%dp0%\\{}\"", target.display()).to_lowercase();
|
||||
fs::read_to_string(&self.link)?.replace('/', "\\").to_lowercase().contains(&needle)
|
||||
};
|
||||
Ok(owns.then(|| version.to_owned()))
|
||||
}
|
||||
|
||||
fn writable(&self) -> io::Result<bool> {
|
||||
for dir in [&*self.folder, self.folder.parent().unwrap(), &self.modules, self.link.parent().unwrap()] {
|
||||
#[cfg(unix)]
|
||||
let access: io::Result<()> =
|
||||
rustix::fs::accessat(rustix::fs::CWD, dir, rustix::fs::Access::WRITE_OK, rustix::fs::AtFlags::empty())
|
||||
.map_err(Into::into);
|
||||
#[cfg(windows)]
|
||||
let access = tempfile::tempfile_in(dir).map(drop);
|
||||
match access {
|
||||
Err(e) if matches!(e.kind(), io::ErrorKind::PermissionDenied | io::ErrorKind::ReadOnlyFilesystem) => {
|
||||
return Ok(false);
|
||||
}
|
||||
other => other?,
|
||||
}
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
}
|
||||
|
||||
fn stable(version: &str) -> Option<semver::Version> {
|
||||
semver::Version::parse(version).ok().filter(|v| v.pre.is_empty() && v.build.is_empty())
|
||||
}
|
||||
|
||||
fn maintain(
|
||||
npm: &Path,
|
||||
program: &Path,
|
||||
bin: &str,
|
||||
pkg: &str,
|
||||
approved: Option<&AgentCliOffer>,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<AgentCliUpdateResult> {
|
||||
use AgentCliUpdateResult::*;
|
||||
let run = |args: &[&str]| {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
let mut cmd = Command::new(npm);
|
||||
cmd.args(args)
|
||||
.current_dir(npm.parent().unwrap())
|
||||
.env("NPM_CONFIG_UPDATE_NOTIFIER", "false")
|
||||
.env("NPM_CONFIG_LOGLEVEL", "error");
|
||||
ide_tools::run_streamed(cmd, cancel, &|_| {}).map_err(|e| {
|
||||
if e.kind == ErrorKind::Cancelled {
|
||||
return e;
|
||||
}
|
||||
// npm diagnostics can contain private registry URLs; expose only known codes.
|
||||
let code = e
|
||||
.message
|
||||
.split(|c: char| !c.is_ascii_alphanumeric() && c != '_')
|
||||
.find(|w| {
|
||||
matches!(
|
||||
*w,
|
||||
"EACCES"
|
||||
| "EPERM"
|
||||
| "EROFS"
|
||||
| "ENOTFOUND"
|
||||
| "EAI_AGAIN"
|
||||
| "ETIMEDOUT"
|
||||
| "E404"
|
||||
| "E401"
|
||||
| "E403"
|
||||
)
|
||||
})
|
||||
.unwrap_or("npm");
|
||||
IdeError::unavailable(code)
|
||||
})
|
||||
};
|
||||
let output = run(&["prefix", "-g"])?;
|
||||
let prefix = Path::new(output.trim_end());
|
||||
if !prefix.is_absolute() {
|
||||
return Err(IdeError::invalid("Invalid npm global prefix"));
|
||||
}
|
||||
let installation = Installation::at(prefix, pkg, bin);
|
||||
let Some(current) = installation.version(program, pkg, bin)? else { return Ok(Unmanaged) };
|
||||
let latest: String = serde_json::from_str(&run(&["view", &format!("{pkg}@latest"), "version", "--json"])?)
|
||||
.map_err(|_| IdeError::invalid("Invalid npm version response"))?;
|
||||
let (Some(before), Some(after)) = (stable(¤t), stable(&latest)) else {
|
||||
return Ok(Channel { current });
|
||||
};
|
||||
if before >= after {
|
||||
return Ok(Current { current });
|
||||
}
|
||||
let offer = AgentCliOffer { current, latest, prefix: prefix.to_owned() };
|
||||
if !installation.writable()? {
|
||||
return Ok(Permission(offer));
|
||||
}
|
||||
if approved != Some(&offer) {
|
||||
return Ok(Available(offer));
|
||||
}
|
||||
run(&[
|
||||
"install",
|
||||
"-g",
|
||||
"--prefix",
|
||||
prefix.to_str().unwrap(),
|
||||
"--no-audit",
|
||||
"--no-fund",
|
||||
&format!("{pkg}@{}", offer.latest),
|
||||
])?;
|
||||
if installation.version(program, pkg, bin)?.as_ref() != Some(&offer.latest) {
|
||||
return Err(IdeError::invalid("npm installation verification failed"));
|
||||
}
|
||||
Ok(Updated { current: offer.latest })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
use tempfile::TempDir;
|
||||
|
||||
const PKG: &str = "@anthropic-ai/claude-code";
|
||||
|
||||
struct Fixture {
|
||||
root: TempDir,
|
||||
install: Installation,
|
||||
}
|
||||
|
||||
impl Fixture {
|
||||
fn new() -> Self {
|
||||
let root = tempfile::Builder::new().prefix("全局 prefix ").tempdir().unwrap();
|
||||
let install = Installation::at(root.path(), PKG, "claude");
|
||||
fs::create_dir_all(&install.folder).unwrap();
|
||||
fs::create_dir_all(install.link.parent().unwrap()).unwrap();
|
||||
fs::write(install.folder.join("entry.js"), "").unwrap();
|
||||
#[cfg(unix)]
|
||||
std::os::unix::fs::symlink(install.folder.join("entry.js"), &install.link).unwrap();
|
||||
#[cfg(windows)]
|
||||
fs::write(&install.link, r#"@"%dp0%\node_modules\@anthropic-ai\claude-code\entry.js""#).unwrap();
|
||||
let fixture = Self { root, install };
|
||||
fixture.manifest(PKG, "2.1.9");
|
||||
fixture
|
||||
}
|
||||
|
||||
fn manifest(&self, name: &str, version: &str) {
|
||||
fs::write(
|
||||
self.install.folder.join("package.json"),
|
||||
json!({"name":name,"version":version,"bin":{"claude":"entry.js"}}).to_string(),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
fn version(&self) -> Option<String> {
|
||||
self.install.version(&self.install.link, PKG, "claude").unwrap()
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn npm(&self, script: &str) -> PathBuf {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let path = self.root.path().join("npm");
|
||||
fs::write(&path, format!("#!/bin/sh\nset -eu\n{script}\n")).unwrap();
|
||||
fs::set_permissions(&path, fs::Permissions::from_mode(0o755)).unwrap();
|
||||
path
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn requires_the_selected_install_and_its_exact_package_entry() {
|
||||
let f = Fixture::new();
|
||||
assert_eq!(f.version().as_deref(), Some("2.1.9"));
|
||||
let other = f.root.path().join("other");
|
||||
fs::write(&other, "").unwrap();
|
||||
assert_eq!(f.install.version(&other, PKG, "claude").unwrap(), None);
|
||||
f.manifest("other-package", "2.1.9");
|
||||
assert_eq!(f.version(), None);
|
||||
f.manifest(PKG, "2.1.9");
|
||||
fs::remove_file(&f.install.link).unwrap();
|
||||
#[cfg(unix)]
|
||||
std::os::unix::fs::symlink(&other, &f.install.link).unwrap();
|
||||
#[cfg(windows)]
|
||||
fs::write(&f.install.link, r#"@"%dp0%\other""#).unwrap();
|
||||
assert_eq!(f.version(), None);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
const NPM: &str = r#"case "$1" in
|
||||
prefix) pwd -P ;;
|
||||
view) cat latest ;;
|
||||
install)
|
||||
test "$2" = "-g" && test "$3" = "--prefix" && test "$4" = "$(pwd -P)"
|
||||
test "$7" = "@anthropic-ai/[email protected]"
|
||||
cp updated.json "$4/lib/node_modules/@anthropic-ai/claude-code/package.json"
|
||||
touch installed ;;
|
||||
*) exit 2 ;;
|
||||
esac"#;
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn installs_only_the_confirmed_offer_and_rechecks_ownership() {
|
||||
use AgentCliUpdateResult::*;
|
||||
let f = Fixture::new();
|
||||
let npm = f.npm(NPM);
|
||||
let cancel = CancellationToken::new();
|
||||
let run =
|
||||
|offer: Option<&AgentCliOffer>| maintain(&npm, &f.install.link, "claude", PKG, offer, &cancel).unwrap();
|
||||
let latest = f.root.path().join("latest");
|
||||
fs::write(&latest, r#""2.1.12""#).unwrap();
|
||||
let Available(offer) = run(None) else { panic!("expected an offer") };
|
||||
for different in [
|
||||
AgentCliOffer { prefix: PathBuf::from("/other"), ..offer.clone() },
|
||||
AgentCliOffer { current: "2.0.0".into(), ..offer.clone() },
|
||||
] {
|
||||
assert_eq!(run(Some(&different)), Available(offer.clone()));
|
||||
}
|
||||
fs::write(&latest, r#""2.2.0""#).unwrap();
|
||||
assert!(matches!(run(Some(&offer)), Available(new) if new.latest == "2.2.0"));
|
||||
fs::write(&latest, r#""2.0.0""#).unwrap();
|
||||
assert!(matches!(run(Some(&offer)), Current { .. }));
|
||||
fs::write(&latest, r#""2.2.0-beta.1""#).unwrap();
|
||||
assert!(matches!(run(Some(&offer)), Channel { .. }));
|
||||
fs::write(&latest, r#""2.1.12""#).unwrap();
|
||||
f.manifest("other-package", "2.1.9");
|
||||
assert_eq!(run(Some(&offer)), Unmanaged);
|
||||
assert!(!f.root.path().join("installed").exists());
|
||||
f.manifest(PKG, "2.1.12");
|
||||
fs::copy(f.install.folder.join("package.json"), f.root.path().join("updated.json")).unwrap();
|
||||
f.manifest(PKG, "2.1.9");
|
||||
assert_eq!(run(Some(&offer)), Updated { current: "2.1.12".into() });
|
||||
assert!(f.root.path().join("installed").exists());
|
||||
assert_eq!(run(None), Current { current: "2.1.12".into() });
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn permission_failure_never_starts_an_install() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let f = Fixture::new();
|
||||
let npm = f.npm(NPM);
|
||||
fs::write(f.root.path().join("latest"), r#""2.1.12""#).unwrap();
|
||||
let run = |offer: Option<&AgentCliOffer>| {
|
||||
maintain(&npm, &f.install.link, "claude", PKG, offer, &CancellationToken::new()).unwrap()
|
||||
};
|
||||
let AgentCliUpdateResult::Available(offer) = run(None) else { panic!("expected an offer") };
|
||||
fs::set_permissions(&f.install.folder, fs::Permissions::from_mode(0o555)).unwrap();
|
||||
// root can write even when no mode bit grants write permission.
|
||||
if tempfile::tempfile_in(&f.install.folder).is_err() {
|
||||
assert_eq!(run(Some(&offer)), AgentCliUpdateResult::Permission(offer));
|
||||
}
|
||||
fs::set_permissions(&f.install.folder, fs::Permissions::from_mode(0o755)).unwrap();
|
||||
assert!(!f.root.path().join("installed").exists());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn cancellation_stops_a_running_npm_process() {
|
||||
use std::time::{Duration, Instant};
|
||||
let f = Fixture::new();
|
||||
let npm = f.npm(
|
||||
r#"case "$1" in
|
||||
prefix) pwd -P ;;
|
||||
view) echo '"2.1.12"' ;;
|
||||
install) touch started; exec sleep 30 ;;
|
||||
esac"#,
|
||||
);
|
||||
let cancel = CancellationToken::new();
|
||||
let AgentCliUpdateResult::Available(offer) =
|
||||
maintain(&npm, &f.install.link, "claude", PKG, None, &cancel).unwrap()
|
||||
else {
|
||||
panic!("expected an offer")
|
||||
};
|
||||
let started = f.root.path().join("started");
|
||||
std::thread::scope(|s| {
|
||||
let op = s.spawn(|| maintain(&npm, &f.install.link, "claude", PKG, Some(&offer), &cancel));
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
while !started.exists() && Instant::now() < deadline {
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
cancel.cancel();
|
||||
assert!(started.exists());
|
||||
assert_eq!(op.join().unwrap().unwrap_err().kind, ErrorKind::Cancelled);
|
||||
});
|
||||
assert_eq!(f.version().as_deref(), Some("2.1.9"));
|
||||
}
|
||||
}
|
||||
+28
-121
@@ -3,7 +3,7 @@
|
||||
|
||||
use crate::model::{
|
||||
AgentCommand, AgentCommandSource, AgentConfigOption, AgentConfigValue, AgentConfigVia, AgentCost, AgentLimit,
|
||||
AgentModelPricing, AgentTokens, AgentUsage,
|
||||
AgentModelPricing, AgentUsage,
|
||||
};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
@@ -65,7 +65,7 @@ fn bypass_value(category: &str) -> Option<fn(&str) -> bool> {
|
||||
}
|
||||
|
||||
/// Moves options that approve everything without asking to a value that asks: the agent's
|
||||
/// own default (when it asks), else `default` or `ask`, else its first one that asks.
|
||||
/// default or ask mode, else its first one that asks.
|
||||
pub(crate) fn ask_for_approvals(config: &mut [AgentConfigOption]) {
|
||||
for option in config {
|
||||
let Some(bypass) = option.category.as_deref().and_then(bypass_value) else { continue };
|
||||
@@ -73,15 +73,9 @@ pub(crate) fn ask_for_approvals(config: &mut [AgentConfigOption]) {
|
||||
continue;
|
||||
}
|
||||
let asks = |v: &&AgentConfigValue| !bypass(&v.value);
|
||||
let value = option
|
||||
.default_value
|
||||
.as_deref()
|
||||
.and_then(|def| option.values.iter().filter(asks).find(|v| v.value == def))
|
||||
.or_else(|| {
|
||||
["default", "ask"]
|
||||
.iter()
|
||||
.find_map(|preferred| option.values.iter().filter(asks).find(|v| v.value == *preferred))
|
||||
})
|
||||
let value = ["default", "ask"]
|
||||
.iter()
|
||||
.find_map(|preferred| option.values.iter().filter(asks).find(|v| v.value == *preferred))
|
||||
.or_else(|| option.values.iter().find(asks));
|
||||
if let Some(value) = value {
|
||||
option.current = Some(value.value.clone());
|
||||
@@ -89,26 +83,11 @@ pub(crate) fn ask_for_approvals(config: &mut [AgentConfigOption]) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Moves approval-bearing options (`mode`, `permissions`, `approval`) to their approving value.
|
||||
pub(crate) fn apply_bypass_approvals(config: &mut [AgentConfigOption]) {
|
||||
for option in config {
|
||||
let Some(bypass) = option.category.as_deref().and_then(bypass_value) else { continue };
|
||||
if let Some(value) = option.values.iter().find(|v| bypass(&v.value)) {
|
||||
option.current = Some(value.value.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Applies provider-specific defaults to per-model options for new tasks without altering `default_value`.
|
||||
pub(crate) fn apply_model_defaults(provider: &str, options: &mut [AgentConfigOption]) {
|
||||
if provider != "cursor" {
|
||||
return;
|
||||
}
|
||||
if let Some(fast) = options.iter_mut().find(|o| is_fast_option(&o.id))
|
||||
&& fast.values.iter().any(|v| v.value == "false")
|
||||
{
|
||||
fast.current = Some("false".into());
|
||||
}
|
||||
/// The mode that approves everything without asking (`bypassPermissions`, `yolo`, `full-access`…), if the agent has one.
|
||||
pub(crate) fn bypass_mode(options: &[AgentConfigOption]) -> Option<(&AgentConfigOption, &AgentConfigValue)> {
|
||||
let option = options.iter().find(|o| o.category.as_deref() == Some("mode"))?;
|
||||
let value = option.values.iter().find(|v| is_bypass_mode(&v.value))?;
|
||||
Some((option, value))
|
||||
}
|
||||
|
||||
fn is_bypass_mode(mode: &str) -> bool {
|
||||
@@ -147,20 +126,14 @@ pub(crate) fn options_of(result: &Value) -> Vec<AgentConfigOption> {
|
||||
}
|
||||
|
||||
pub(crate) fn is_context_option(id: &str) -> bool {
|
||||
matches!(id, "context" | "context_tier" | "contextTier")
|
||||
}
|
||||
|
||||
pub(crate) fn is_fast_option(id: &str) -> bool {
|
||||
id == "fast"
|
||||
matches!(id, "context_tier" | "contextTier")
|
||||
}
|
||||
|
||||
/// Whether an option's available values and default belong to the selected model
|
||||
/// (`thought_level`, `context_tier`, and `model_config` options like `context` and `fast`)
|
||||
/// rather than the provider as a whole.
|
||||
/// (`thought_level` and model context-tier options) rather than the provider as a whole.
|
||||
pub(crate) fn is_per_model_option(o: &AgentConfigOption) -> bool {
|
||||
matches!(o.category.as_deref(), Some("thought_level" | "context_tier" | "model_config"))
|
||||
matches!(o.category.as_deref(), Some("thought_level" | "context_tier"))
|
||||
|| matches!(o.id.as_str(), "effort" | "reasoning_effort" | "thinking" | "reasoning")
|
||||
|| is_fast_option(&o.id)
|
||||
|| is_context_option(&o.id)
|
||||
}
|
||||
|
||||
@@ -191,7 +164,7 @@ pub(crate) fn parse_options(options: &Value) -> Vec<AgentConfigOption> {
|
||||
matches!(id.as_str(), "effort" | "reasoning_effort" | "thinking" | "reasoning")
|
||||
.then(|| "thought_level".into())
|
||||
})
|
||||
.or_else(|| (is_fast_option(&id) || is_context_option(&id)).then(|| "model_config".into()))
|
||||
.or_else(|| (id == "fast" || is_context_option(&id)).then(|| "model_config".into()))
|
||||
}),
|
||||
current,
|
||||
default_value,
|
||||
@@ -299,18 +272,6 @@ pub(crate) fn usage_of(update: &Value) -> Option<AgentUsage> {
|
||||
Some(AgentUsage { used: tokens("used")?, size: tokens("size").filter(|s| *s > 0)?, cost })
|
||||
}
|
||||
|
||||
/// The `usage` of a `session/prompt` result: `{ inputTokens, cachedReadTokens, outputTokens }`.
|
||||
pub(crate) fn tokens_of(result: &Value) -> Option<AgentTokens> {
|
||||
let usage = result.get("usage")?;
|
||||
let tokens = |key: &str| usage.get(key).and_then(Value::as_u64).map_or(0, |n| u32::try_from(n).unwrap_or(u32::MAX));
|
||||
let tokens = AgentTokens {
|
||||
input: tokens("inputTokens"),
|
||||
cached: tokens("cachedReadTokens"),
|
||||
output: tokens("outputTokens"),
|
||||
};
|
||||
(tokens != AgentTokens::default()).then_some(tokens)
|
||||
}
|
||||
|
||||
/// The usage-limit windows a [`crate::LIMITS_UPDATE`] carries; malformed entries are skipped.
|
||||
pub(crate) fn limits_of(update: &Value) -> Vec<AgentLimit> {
|
||||
let limits = update.get("limits").and_then(Value::as_array).into_iter().flatten();
|
||||
@@ -364,11 +325,6 @@ fn legacy(
|
||||
}
|
||||
}
|
||||
|
||||
fn clean_label(s: String, fallback: &str) -> String {
|
||||
let trimmed = s.trim_matches(|c: char| c.is_whitespace() || matches!(c, '\u{200B}'..='\u{200D}' | '\u{FEFF}'));
|
||||
if trimmed.is_empty() { fallback.to_owned() } else { trimmed.to_owned() }
|
||||
}
|
||||
|
||||
fn value_of(v: &Value) -> Option<AgentConfigValue> {
|
||||
let value = v.get("value")?.as_str()?.to_owned();
|
||||
let meta = v.get("_meta");
|
||||
@@ -384,7 +340,7 @@ fn value_of(v: &Value) -> Option<AgentConfigValue> {
|
||||
.filter(|s| !s.is_empty())
|
||||
.map(str::to_owned);
|
||||
Some(AgentConfigValue {
|
||||
name: str_of(v, "name").map(|n| clean_label(n, &value)).unwrap_or_else(|| value.clone()),
|
||||
name: str_of(v, "name").unwrap_or_else(|| value.clone()),
|
||||
description: str_of(v, "description"),
|
||||
cost_category,
|
||||
usage_multiplier,
|
||||
@@ -412,15 +368,6 @@ mod tests {
|
||||
c.iter().map(|o| (o.id.as_str(), o.current.as_deref())).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_hermes_prompt_result_reports_the_turns_tokens() {
|
||||
let result = json!({"stopReason": "end_turn", "usage": {"cachedReadTokens": 51306, "inputTokens": 77284,
|
||||
"outputTokens": 509, "thoughtTokens": 0, "totalTokens": 77793}});
|
||||
assert_eq!(tokens_of(&result), Some(AgentTokens { input: 77284, cached: 51306, output: 509 }));
|
||||
assert_eq!(tokens_of(&json!({"stopReason": "end_turn"})), None);
|
||||
assert_eq!(tokens_of(&json!({"usage": {}})), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn config_options_win_over_the_older_fields() {
|
||||
let r = json!({
|
||||
@@ -466,16 +413,19 @@ mod tests {
|
||||
]}
|
||||
}));
|
||||
assert!(bypass_approvals(&full_access));
|
||||
assert_eq!(bypass_mode(&full_access).map(|(_, v)| v.value.as_str()), Some("full-access"));
|
||||
|
||||
let mut asking = options_of(&json!({
|
||||
let asking = options_of(&json!({
|
||||
"modes": {"currentModeId": "ask", "availableModes": [
|
||||
{"id": "ask", "name": "Ask"}, {"id": "full-access", "name": "Full Access"}
|
||||
]}
|
||||
}));
|
||||
assert!(!bypass_approvals(&asking));
|
||||
apply_bypass_approvals(&mut asking);
|
||||
assert_eq!(asking[0].current.as_deref(), Some("full-access"));
|
||||
assert!(bypass_approvals(&asking));
|
||||
assert_eq!(
|
||||
bypass_mode(&asking).map(|(_, v)| v.value.as_str()),
|
||||
Some("full-access"),
|
||||
"the offered bypass mode stays available"
|
||||
);
|
||||
|
||||
let permissions = |current: &str| {
|
||||
options_of(&json!({"configOptions": [{
|
||||
@@ -532,7 +482,7 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn effort_context_and_fast_are_per_model_options() {
|
||||
fn effort_and_fast_categories_are_inferred_from_ids() {
|
||||
let mut c = options_of(&json!({
|
||||
"configOptions": [
|
||||
{"id": "model", "type": "select", "currentValue": "gemini-4-carbon",
|
||||
@@ -541,39 +491,19 @@ mod tests {
|
||||
"_meta": {"copilotPriceCategory": "Medium", "copilotUsage": "1x"}}]},
|
||||
{"id": "effort", "type": "select", "currentValue": "medium",
|
||||
"options": [{"value": "low"}, {"value": "medium"}, {"value": "high"}]},
|
||||
{"id": "context", "type": "select", "currentValue": "256k",
|
||||
"options": [{"value": "256k", "name": "256K"}, {"value": "500k", "name": "500K"}]},
|
||||
{"id": "contextTier", "type": "select", "currentValue": "default",
|
||||
"options": [{"value": "default", "name": "200K"}, {"value": "long_context", "name": "1M"}]},
|
||||
{"id": "fast", "type": "select", "currentValue": "true",
|
||||
"options": [{"value": "false", "name": "Off"}, {"value": "true", "name": "Fast\u{200b}\u{200b}"}]}
|
||||
{"id": "fast", "type": "select", "currentValue": "false",
|
||||
"options": [{"value": "false", "name": "Off"}, {"value": "true", "name": "On"}]}
|
||||
]
|
||||
}));
|
||||
assert_eq!(c.len(), 5);
|
||||
assert_eq!(c.len(), 4);
|
||||
assert_eq!(c[0].values[0].cost_category.as_deref(), Some("medium"));
|
||||
assert_eq!(c[0].values[0].usage_multiplier.as_deref(), Some("1x"));
|
||||
assert_eq!(c[1].category.as_deref(), Some("thought_level"));
|
||||
assert_eq!(c[1].default_value.as_deref(), Some("medium"));
|
||||
assert_eq!(c[2].category.as_deref(), Some("model_config"));
|
||||
assert_eq!(c[3].category.as_deref(), Some("model_config"));
|
||||
assert_eq!(c[4].category.as_deref(), Some("model_config"));
|
||||
assert_eq!(c[4].values[1].name, "Fast");
|
||||
assert!(
|
||||
is_per_model_option(&c[1])
|
||||
&& is_per_model_option(&c[2])
|
||||
&& is_per_model_option(&c[3])
|
||||
&& is_per_model_option(&c[4])
|
||||
);
|
||||
assert!(!is_per_model_option(&c[0]));
|
||||
|
||||
// Cursor defaults fast off for new tasks while preserving the agent's own default_value.
|
||||
let mut cursor_opts = c.clone();
|
||||
apply_model_defaults("cursor", &mut cursor_opts);
|
||||
let fast = cursor_opts.iter().find(|o| o.id == "fast").unwrap();
|
||||
assert_eq!((fast.current.as_deref(), fast.default_value.as_deref()), (Some("false"), Some("true")));
|
||||
let mut other_opts = c.clone();
|
||||
apply_model_defaults("claude", &mut other_opts);
|
||||
assert_eq!(other_opts.iter().find(|o| o.id == "fast").unwrap().current.as_deref(), Some("true"));
|
||||
assert!(is_per_model_option(&c[1]) && is_per_model_option(&c[2]) && !is_per_model_option(&c[3]));
|
||||
|
||||
// Editing effort on the same model preserves its initial `default_value` for Reset.
|
||||
merge_update(
|
||||
@@ -595,34 +525,11 @@ mod tests {
|
||||
{"id": "model", "type": "select", "currentValue": "gpt-6-sol",
|
||||
"options": [{"value": "gemini-4-carbon"}, {"value": "gpt-6-sol"}]},
|
||||
{"id": "effort", "type": "select", "currentValue": "low",
|
||||
"options": [{"value": "low"}, {"value": "medium"}, {"value": "high"}]},
|
||||
{"id": "context", "type": "select", "currentValue": "1m",
|
||||
"options": [{"value": "300k", "name": "300K"}, {"value": "1m", "name": "1M"}]}
|
||||
"options": [{"value": "low"}, {"value": "medium"}, {"value": "high"}]}
|
||||
]),
|
||||
);
|
||||
let effort = c.iter().find(|o| o.id == "effort").unwrap();
|
||||
assert_eq!((effort.current.as_deref(), effort.default_value.as_deref()), (Some("low"), Some("low")));
|
||||
let context = c.iter().find(|o| o.id == "context").unwrap();
|
||||
assert_eq!((context.current.as_deref(), context.default_value.as_deref()), (Some("1m"), Some("1m")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn apply_bypass_approvals_covers_mode_permissions_and_approval() {
|
||||
let mut c = options_of(&json!({"configOptions": [
|
||||
{"id": "mode", "category": "mode", "type": "select", "currentValue": "ask",
|
||||
"options": [{"value": "ask"}, {"value": "full-access"}]},
|
||||
{"id": "allow_all", "category": "permissions", "type": "select", "currentValue": "off",
|
||||
"options": [{"value": "off"}, {"value": "on"}]},
|
||||
{"id": "approval", "category": "approval", "type": "select", "currentValue": "ask",
|
||||
"options": [{"value": "ask"}, {"value": "bypass"}]}
|
||||
]}));
|
||||
apply_bypass_approvals(&mut c);
|
||||
assert_eq!(ids(&c), [("mode", Some("full-access")), ("allow_all", Some("on")), ("approval", Some("bypass"))]);
|
||||
// Original agent default_values stay intact.
|
||||
assert_eq!(
|
||||
c.iter().map(|o| o.default_value.as_deref()).collect::<Vec<_>>(),
|
||||
[Some("ask"), Some("off"), Some("ask")]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -1,111 +0,0 @@
|
||||
//! Hermes Agent profiles on disk: `default` is the Hermes home itself, the others are
|
||||
//! `<home>/profiles/<name>` directories holding one of Hermes' identity files.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use serde::Serialize;
|
||||
use specta::Type;
|
||||
|
||||
const PROFILE_FILES: &[&str] = &["config.yaml", ".env", "SOUL.md", "profile.yaml", "auth.json", "state.db"];
|
||||
|
||||
/// Hermes' home directory (`~/.hermes`; `%LOCALAPPDATA%\hermes` on Windows).
|
||||
pub fn root(home: Option<&Path>) -> Option<PathBuf> {
|
||||
#[cfg(windows)]
|
||||
if let Some(local) = std::env::var_os("LOCALAPPDATA") {
|
||||
return Some(PathBuf::from(local).join("hermes"));
|
||||
}
|
||||
home.map(|h| h.join(".hermes"))
|
||||
}
|
||||
|
||||
/// The profile names under `root`: `default` first, then the others by name; none without `root`.
|
||||
pub fn profiles(root: &Path) -> Vec<String> {
|
||||
if !root.is_dir() {
|
||||
return Vec::new();
|
||||
}
|
||||
let mut named: Vec<String> = std::fs::read_dir(root.join("profiles"))
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.flatten()
|
||||
.filter(|e| PROFILE_FILES.iter().any(|f| e.path().join(f).exists()))
|
||||
.filter_map(|e| e.file_name().to_str().map(str::to_owned))
|
||||
.filter(|name| name != "default")
|
||||
.collect();
|
||||
named.sort();
|
||||
std::iter::once("default".to_owned()).chain(named).collect()
|
||||
}
|
||||
|
||||
/// A profile and the name Hermes shows for it (`hermes profile list`).
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Type)]
|
||||
pub struct HermesProfile {
|
||||
/// What `hermes -p` takes; `default` is the Hermes home itself.
|
||||
pub name: String,
|
||||
/// `display_name` from the profile's `profile.yaml`, else the name.
|
||||
pub label: String,
|
||||
}
|
||||
|
||||
/// [`profiles`] with the names Hermes shows for them.
|
||||
pub fn labeled_profiles(root: &Path) -> Vec<HermesProfile> {
|
||||
profiles(root)
|
||||
.into_iter()
|
||||
.map(|name| {
|
||||
let home = if name == "default" { root.to_path_buf() } else { root.join("profiles").join(&name) };
|
||||
let label = display_name(&home).unwrap_or_else(|| name.clone());
|
||||
HermesProfile { name, label }
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The top-level `display_name:` of `<home>/profile.yaml`, the only key read (no YAML parser).
|
||||
fn display_name(home: &Path) -> Option<String> {
|
||||
let text = std::fs::read_to_string(home.join("profile.yaml")).ok()?;
|
||||
let value = text.lines().find_map(|l| l.strip_prefix("display_name:"))?;
|
||||
let value = value.trim().trim_matches(['"', '\'']).trim();
|
||||
(!value.is_empty()).then(|| value.to_owned())
|
||||
}
|
||||
|
||||
/// The home of the profile an agent id stands for: `hermes` and `hermes-default` are the
|
||||
/// default profile, `hermes-<slug>` the profile whose name slugifies to `<slug>`.
|
||||
pub fn profile_home(root: &Path, provider: &str) -> Option<PathBuf> {
|
||||
let slug = match provider {
|
||||
"hermes" | "hermes-default" => return Some(root.to_path_buf()),
|
||||
_ => provider.strip_prefix("hermes-")?,
|
||||
};
|
||||
profiles(root).into_iter().find(|p| crate::provider::slugify_id(p) == slug).map(|p| root.join("profiles").join(p))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn lists_default_and_profiles_with_an_identity_file() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
assert!(profiles(&dir.path().join("missing")).is_empty());
|
||||
let root = dir.path().join(".hermes");
|
||||
std::fs::create_dir_all(root.join("profiles/empty")).unwrap();
|
||||
assert_eq!(profiles(&root), ["default"]);
|
||||
for (name, file) in [("work", "config.yaml"), ("Dom 2", "SOUL.md"), ("db", "state.db")] {
|
||||
std::fs::create_dir_all(root.join("profiles").join(name)).unwrap();
|
||||
std::fs::write(root.join("profiles").join(name).join(file), "").unwrap();
|
||||
}
|
||||
std::fs::write(root.join("profiles/stray.yaml"), "").unwrap();
|
||||
assert_eq!(profiles(&root), ["default", "Dom 2", "db", "work"]);
|
||||
assert_eq!(profile_home(&root, "hermes"), Some(root.clone()));
|
||||
assert_eq!(profile_home(&root, "hermes-dom-2"), Some(root.join("profiles/Dom 2")));
|
||||
assert_eq!(profile_home(&root, "hermes-empty"), None);
|
||||
assert_eq!(profile_home(&root, "claude"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn labels_profiles_with_their_display_name() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path().join(".hermes");
|
||||
std::fs::create_dir_all(root.join("profiles/work")).unwrap();
|
||||
std::fs::write(root.join("profile.yaml"), "description: mine\ndisplay_name: \"qb\"\n").unwrap();
|
||||
std::fs::write(root.join("profiles/work/profile.yaml"), "ui_meta:\n display_name: nested\n").unwrap();
|
||||
let label = |name: &str, label: &str| HermesProfile { name: name.into(), label: label.into() };
|
||||
assert_eq!(labeled_profiles(&root), [label("default", "qb"), label("work", "work")]);
|
||||
std::fs::remove_file(root.join("profile.yaml")).unwrap();
|
||||
assert_eq!(labeled_profiles(&root)[0], label("default", "default"));
|
||||
}
|
||||
}
|
||||
@@ -1,143 +0,0 @@
|
||||
//! Images in agent content: ACP content blocks, `data:` URLs and image files on disk.
|
||||
|
||||
use crate::model::AgentImage;
|
||||
use base64::Engine;
|
||||
use serde_json::{Value, json};
|
||||
use std::path::Path;
|
||||
|
||||
/// Image files larger than this are not inlined into the conversation.
|
||||
const MAX_FILE_BYTES: u64 = 10 * 1024 * 1024;
|
||||
|
||||
/// The image an ACP content block shows: an `image` (inline or by URI), a `resource` with an
|
||||
/// image blob, or a `resource_link` to an image file.
|
||||
pub(crate) fn from_content(content: &Value) -> Option<AgentImage> {
|
||||
match str_of(content, "type")? {
|
||||
"image" => {
|
||||
if let (Some(data), Some(mime)) = (str_of(content, "data"), str_of(content, "mimeType"))
|
||||
&& mime.starts_with("image/")
|
||||
{
|
||||
return Some(AgentImage { mime_type: mime.into(), data: data.into(), name: None });
|
||||
}
|
||||
from_uri(str_of(content, "uri")?)
|
||||
}
|
||||
"resource" => {
|
||||
let resource = content.get("resource")?;
|
||||
let (data, mime) = (str_of(resource, "blob")?, str_of(resource, "mimeType")?);
|
||||
mime.starts_with("image/").then(|| AgentImage { mime_type: mime.into(), data: data.into(), name: None })
|
||||
}
|
||||
"resource_link" => {
|
||||
let uri = str_of(content, "uri")?;
|
||||
let declared = str_of(content, "mimeType").is_some_and(|m| m.starts_with("image/"));
|
||||
if !declared && mime_of(Path::new(&uri_path(uri))).is_none() {
|
||||
return None;
|
||||
}
|
||||
let mut image = from_uri(uri)?;
|
||||
image.name = str_of(content, "name").map(str::to_owned);
|
||||
Some(image)
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn str_of<'a>(v: &'a Value, key: &str) -> Option<&'a str> {
|
||||
v.get(key).and_then(Value::as_str).filter(|s| !s.is_empty())
|
||||
}
|
||||
|
||||
/// The image at a `data:` URL or a `file://` URI.
|
||||
pub(crate) fn from_uri(uri: &str) -> Option<AgentImage> {
|
||||
if let Some(rest) = uri.strip_prefix("data:") {
|
||||
let (mime, data) = rest.split_once(";base64,")?;
|
||||
return (mime.starts_with("image/") && !data.is_empty()).then(|| AgentImage {
|
||||
mime_type: mime.into(),
|
||||
data: data.into(),
|
||||
name: None,
|
||||
});
|
||||
}
|
||||
uri.starts_with("file://").then(|| from_file(Path::new(&uri_path(uri))))?
|
||||
}
|
||||
|
||||
/// The image file at `path`, when it has an image extension and isn't too large.
|
||||
pub(crate) fn from_file(path: &Path) -> Option<AgentImage> {
|
||||
let mime = mime_of(path)?;
|
||||
if std::fs::metadata(path).ok()?.len() > MAX_FILE_BYTES {
|
||||
return None;
|
||||
}
|
||||
let bytes = std::fs::read(path).ok()?;
|
||||
(!bytes.is_empty()).then(|| AgentImage {
|
||||
mime_type: mime.into(),
|
||||
data: base64::engine::general_purpose::STANDARD.encode(bytes),
|
||||
name: path.file_name().and_then(|n| n.to_str()).map(str::to_owned),
|
||||
})
|
||||
}
|
||||
|
||||
/// `image` as an ACP image content block.
|
||||
pub(crate) fn content(image: &AgentImage) -> Value {
|
||||
json!({ "type": "image", "mimeType": image.media_type(), "data": image.data })
|
||||
}
|
||||
|
||||
fn mime_of(path: &Path) -> Option<&'static str> {
|
||||
let ext = path.extension()?.to_str()?.to_ascii_lowercase();
|
||||
Some(match ext.as_str() {
|
||||
"png" => "image/png",
|
||||
"jpg" | "jpeg" => "image/jpeg",
|
||||
"gif" => "image/gif",
|
||||
"webp" => "image/webp",
|
||||
"bmp" => "image/bmp",
|
||||
"svg" => "image/svg+xml",
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// The path of a `file://` URI (percent-decoded); other URIs as they are.
|
||||
pub(crate) fn uri_path(uri: &str) -> String {
|
||||
let Some(rest) = uri.strip_prefix("file://") else { return uri.to_owned() };
|
||||
let bytes = rest.as_bytes();
|
||||
let mut out = Vec::with_capacity(bytes.len());
|
||||
let mut i = 0;
|
||||
while i < bytes.len() {
|
||||
if bytes[i] == b'%'
|
||||
&& let Some(b) = rest.get(i + 1..i + 3).and_then(|h| u8::from_str_radix(h, 16).ok())
|
||||
{
|
||||
out.push(b);
|
||||
i += 3;
|
||||
} else {
|
||||
out.push(bytes[i]);
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
let path = String::from_utf8_lossy(&out).into_owned();
|
||||
// `file:///C:/x` on Windows.
|
||||
match path.as_bytes() {
|
||||
[b'/', drive, b':', ..] if drive.is_ascii_alphabetic() => path[1..].to_owned(),
|
||||
_ => path,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn content_blocks_inline_data_urls_blobs_and_image_files() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let file = dir.path().join("shot 1.png");
|
||||
std::fs::write(&file, b"\x89PNG\r\n").unwrap();
|
||||
std::fs::write(dir.path().join("notes.txt"), b"hi").unwrap();
|
||||
let uri = crate::file_uri(&file);
|
||||
let inline = json!({"type": "image", "mimeType": "image/png", "data": "aW1n"});
|
||||
assert_eq!(from_content(&inline).unwrap().data, "aW1n");
|
||||
let by_url = json!({"type": "image", "uri": "data:image/jpeg;base64,AAA"});
|
||||
assert_eq!(from_content(&by_url).unwrap().mime_type, "image/jpeg");
|
||||
let by_file = from_content(&json!({"type": "image", "uri": uri})).unwrap();
|
||||
assert_eq!(by_file.data, base64::engine::general_purpose::STANDARD.encode(b"\x89PNG\r\n"));
|
||||
let blob = json!({"type": "resource", "resource": {"uri": "x", "mimeType": "image/gif", "blob": "R0lG"}});
|
||||
assert_eq!(from_content(&blob).unwrap().mime_type, "image/gif");
|
||||
let link = from_content(&json!({"type": "resource_link", "uri": uri, "name": "shot"})).unwrap();
|
||||
assert_eq!((link.mime_type.as_str(), link.name.as_deref()), ("image/png", Some("shot")));
|
||||
let text = crate::file_uri(&dir.path().join("notes.txt"));
|
||||
assert!(from_content(&json!({"type": "resource_link", "uri": text, "name": "notes"})).is_none());
|
||||
assert!(from_content(&json!({"type": "resource", "resource": {"uri": "x", "text": "t"}})).is_none());
|
||||
assert!(from_content(&json!({"type": "image", "uri": "https://example.com/a.png"})).is_none());
|
||||
assert!(from_file(&dir.path().join("missing.png")).is_none());
|
||||
}
|
||||
}
|
||||
+254
-1009
File diff suppressed because it is too large.
Load diff
@@ -941,10 +941,107 @@ fn normalize_agents_list(agents: Vec<String>) -> Vec<String> {
|
||||
out
|
||||
}
|
||||
|
||||
/// Strips `//` line comments, `/* ... */` block comments, and trailing commas before `}` or `]`
|
||||
/// outside JSON string literals so JSONC config files parse cleanly with `serde_json`.
|
||||
pub(crate) fn strip_jsonc(input: &str) -> String {
|
||||
let bytes = input.as_bytes();
|
||||
let mut out = String::with_capacity(input.len());
|
||||
let mut i = 0;
|
||||
let mut in_str = false;
|
||||
while i < bytes.len() {
|
||||
if in_str {
|
||||
let ch = input[i..].chars().next().unwrap();
|
||||
out.push(ch);
|
||||
i += ch.len_utf8();
|
||||
if ch == '\\' && i < bytes.len() {
|
||||
let next = input[i..].chars().next().unwrap();
|
||||
out.push(next);
|
||||
i += next.len_utf8();
|
||||
} else if ch == '"' {
|
||||
in_str = false;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if bytes[i] == b'"' {
|
||||
in_str = true;
|
||||
out.push('"');
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if bytes[i] == b'/' && i + 1 < bytes.len() && bytes[i + 1] == b'/' {
|
||||
i += 2;
|
||||
while i < bytes.len() && bytes[i] != b'\n' {
|
||||
i += 1;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if bytes[i] == b'/' && i + 1 < bytes.len() && bytes[i + 1] == b'*' {
|
||||
i += 2;
|
||||
while i + 1 < bytes.len() && !(bytes[i] == b'*' && bytes[i + 1] == b'/') {
|
||||
if bytes[i] == b'\n' {
|
||||
out.push('\n');
|
||||
i += 1;
|
||||
} else {
|
||||
let ch = input[i..].chars().next().unwrap();
|
||||
i += ch.len_utf8();
|
||||
}
|
||||
}
|
||||
i = (i + 2).min(bytes.len());
|
||||
continue;
|
||||
}
|
||||
let ch = input[i..].chars().next().unwrap();
|
||||
out.push(ch);
|
||||
i += ch.len_utf8();
|
||||
}
|
||||
remove_trailing_commas(&out)
|
||||
}
|
||||
|
||||
fn remove_trailing_commas(input: &str) -> String {
|
||||
let bytes = input.as_bytes();
|
||||
let mut out = String::with_capacity(input.len());
|
||||
let mut i = 0;
|
||||
let mut in_str = false;
|
||||
while i < bytes.len() {
|
||||
if in_str {
|
||||
let ch = input[i..].chars().next().unwrap();
|
||||
out.push(ch);
|
||||
i += ch.len_utf8();
|
||||
if ch == '\\' && i < bytes.len() {
|
||||
let next = input[i..].chars().next().unwrap();
|
||||
out.push(next);
|
||||
i += next.len_utf8();
|
||||
} else if ch == '"' {
|
||||
in_str = false;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if bytes[i] == b'"' {
|
||||
in_str = true;
|
||||
out.push('"');
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if bytes[i] == b',' {
|
||||
let mut j = i + 1;
|
||||
while j < bytes.len() && bytes[j].is_ascii_whitespace() {
|
||||
j += 1;
|
||||
}
|
||||
if j < bytes.len() && (bytes[j] == b'}' || bytes[j] == b']') {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
let ch = input[i..].chars().next().unwrap();
|
||||
out.push(ch);
|
||||
i += ch.len_utf8();
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn parse_jsonc_value(raw: &str) -> Result<Value, String> {
|
||||
let trimmed = raw.trim().trim_start_matches('\u{feff}');
|
||||
serde_json::from_str::<Value>(trimmed)
|
||||
.or_else(|_| serde_json::from_str::<Value>(&ide_core::jsonc::strip(trimmed)))
|
||||
.or_else(|_| serde_json::from_str::<Value>(&strip_jsonc(trimmed)))
|
||||
.map_err(|e| format!("Invalid JSON: {e}"))
|
||||
}
|
||||
|
||||
|
||||
@@ -45,8 +45,6 @@ pub struct AgentCapabilities {
|
||||
pub steer: bool,
|
||||
/// It reports its background tasks and stops them one by one.
|
||||
pub background_tasks: bool,
|
||||
/// The connected agent can report a breakdown of its context window.
|
||||
pub context_usage: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
@@ -110,32 +108,6 @@ pub struct AgentTask {
|
||||
/// Per-session MCP server enable/disable overrides (`server_name` -> `enabled`), including `"openidea"`.
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub mcp_overrides: BTreeMap<String, bool>,
|
||||
/// Per-session skill modes (`skill name` -> mode), on top of the settings' policies.
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub skill_overrides: BTreeMap<String, AgentSkillMode>,
|
||||
/// Token counts of the last turn and context compressions, when the agent reports them.
|
||||
// Boxed so that `AgentEvent::Task` stays within clippy's `large_enum_variant` bound on Windows.
|
||||
#[serde(default)]
|
||||
pub stats: Box<AgentSessionStats>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentSessionStats {
|
||||
/// The last turn's tokens (`session/prompt` result `usage`).
|
||||
#[serde(default)]
|
||||
pub tokens: Option<AgentTokens>,
|
||||
/// How many times the agent compressed the conversation (Hermes `compressionDepth`).
|
||||
#[serde(default)]
|
||||
pub compressions: u32,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentTokens {
|
||||
pub input: u32,
|
||||
pub cached: u32,
|
||||
pub output: u32,
|
||||
}
|
||||
|
||||
/// A task the agent runs in the background while the conversation goes on.
|
||||
@@ -280,24 +252,6 @@ pub struct AgentUsage {
|
||||
pub cost: Option<Box<AgentCost>>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentContextUsage {
|
||||
pub categories: Vec<AgentContextCategory>,
|
||||
pub total_tokens: u32,
|
||||
pub max_tokens: u32,
|
||||
pub model: String,
|
||||
pub is_auto_compact_enabled: Option<bool>,
|
||||
pub auto_compact_threshold: Option<u32>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
pub struct AgentContextCategory {
|
||||
pub name: String,
|
||||
pub tokens: u32,
|
||||
pub kind: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentCost {
|
||||
@@ -525,9 +479,6 @@ pub enum AgentEntry {
|
||||
},
|
||||
Thought {
|
||||
text: String,
|
||||
/// When the reasoning started (ms since the epoch); `None` in tasks saved before.
|
||||
#[serde(default)]
|
||||
started_ms: Option<f64>,
|
||||
},
|
||||
Tool {
|
||||
id: String,
|
||||
@@ -536,17 +487,9 @@ pub enum AgentEntry {
|
||||
kind: String,
|
||||
status: AgentToolStatus,
|
||||
locations: Vec<IpcPath>,
|
||||
/// Images returned by the tool, kept separately from its truncated text.
|
||||
#[serde(default)]
|
||||
images: Vec<AgentImage>,
|
||||
/// Text the tool reported (command output…), truncated.
|
||||
output: Option<String>,
|
||||
diffs: Vec<AgentToolDiff>,
|
||||
/// When the call started and ended (ms since the epoch); `None` in tasks saved before.
|
||||
#[serde(default)]
|
||||
started_ms: Option<f64>,
|
||||
#[serde(default)]
|
||||
ended_ms: Option<f64>,
|
||||
},
|
||||
Plan {
|
||||
items: Vec<AgentPlanItem>,
|
||||
@@ -620,9 +563,6 @@ pub struct AgentProvider {
|
||||
pub command_read_only_reason: Option<AgentCommandReadOnlyReason>,
|
||||
/// Whether the command was found (on `PATH`).
|
||||
pub installed: bool,
|
||||
/// The built-in command can be owned by a global npm package.
|
||||
#[serde(default)]
|
||||
pub can_check_cli_update: bool,
|
||||
/// Environment variables it starts with (from its agent file).
|
||||
pub env: BTreeMap<String, String>,
|
||||
/// Settings (models, modes…) the agent offered last time it ran; empty before its first session.
|
||||
@@ -693,9 +633,6 @@ pub struct NewAgentTask {
|
||||
/// Per-session MCP server enable/disable overrides (`server_name` -> `enabled`).
|
||||
#[serde(default)]
|
||||
pub mcp_overrides: BTreeMap<String, bool>,
|
||||
/// Per-session skill modes (`skill name` -> mode).
|
||||
#[serde(default)]
|
||||
pub skill_overrides: BTreeMap<String, AgentSkillMode>,
|
||||
/// Creates the task without sending `prompt` (it only names the task): the composer's
|
||||
/// `!` command runs in it first.
|
||||
#[serde(default)]
|
||||
@@ -714,8 +651,6 @@ pub struct AgentChange {
|
||||
pub removed: u32,
|
||||
/// Path before a rename; the left side of its diff reads this path.
|
||||
pub old_path: Option<String>,
|
||||
/// The repository the file is in, when the task's project holds nested repositories.
|
||||
pub repo: Option<IpcPath>,
|
||||
}
|
||||
|
||||
/// A commit made while the task ran, with the files it changed against its first parent.
|
||||
@@ -769,7 +704,7 @@ pub struct AgentModelCatalog {
|
||||
pub error: Option<String>,
|
||||
}
|
||||
|
||||
/// Streamed to the window that subscribed (`AgentManager::subscribe_as`).
|
||||
/// Streamed to the window that subscribed (`AgentManager::subscribe`).
|
||||
#[derive(Clone, Debug, Serialize, Type)]
|
||||
#[serde(tag = "type", rename_all = "camelCase", rename_all_fields = "camelCase")]
|
||||
pub enum AgentEvent {
|
||||
@@ -801,16 +736,6 @@ pub enum AgentEvent {
|
||||
from: u32,
|
||||
text: String,
|
||||
},
|
||||
/// Text was appended to the output of tool entry `index`: it read the first `from` UTF-16
|
||||
/// units of its output when the previous event for it was sent. Any other change of the
|
||||
/// tool (status, title, diffs…) arrives as an `Entry`.
|
||||
ToolOutput {
|
||||
task: String,
|
||||
subagent: Option<String>,
|
||||
index: u32,
|
||||
from: u32,
|
||||
text: String,
|
||||
},
|
||||
/// An agent reported the usage limits of its account (shared by every task of `provider`).
|
||||
Limits {
|
||||
provider: String,
|
||||
@@ -900,104 +825,6 @@ fn default_true() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
pub use ide_core::settings::{AgentSkillMode, AgentSkillPolicy};
|
||||
|
||||
/// Which CLI's own folders a skill was discovered in (Settings › Agents › Skills groups by it).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum AgentSkillSource {
|
||||
/// The project's `.agents/skills` and `.openidea/skills`.
|
||||
#[default]
|
||||
Workspace,
|
||||
/// The user's `~/.agents/skills` (what `npx skills add` fills).
|
||||
User,
|
||||
/// Contributed by an enabled OpenIDEA plugin (`[[contributes.skills]]`).
|
||||
Plugin,
|
||||
/// The project's `.claude/skills`.
|
||||
ClaudeWorkspace,
|
||||
/// `~/.claude/skills`.
|
||||
ClaudeUser,
|
||||
/// The project's `.github/skills` (Copilot's repository skills).
|
||||
GithubWorkspace,
|
||||
/// `~/.copilot/skills` and `~/.copilot/installed-plugins/*`.
|
||||
CopilotUser,
|
||||
/// The project's `.codex/skills`.
|
||||
CodexWorkspace,
|
||||
/// `~/.codex/skills`.
|
||||
CodexUser,
|
||||
/// The project's `.cursor/skills`.
|
||||
CursorWorkspace,
|
||||
/// `~/.cursor/skills`.
|
||||
CursorUser,
|
||||
}
|
||||
|
||||
impl AgentSkillSource {
|
||||
/// Whether skills of this source are only read, never delivered by OpenIDEA: the CLI
|
||||
/// discovers them itself, so "off" holds only where the CLI supports a native disable.
|
||||
pub fn discovered(&self) -> bool {
|
||||
!matches!(self, Self::Workspace | Self::User | Self::Plugin)
|
||||
}
|
||||
}
|
||||
|
||||
/// One discovered skill: a folder with a `SKILL.md`.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentSkill {
|
||||
/// The frontmatter `name`, else the folder's name.
|
||||
pub name: String,
|
||||
pub description: String,
|
||||
/// Optional `argument-hint` from frontmatter, completed in the `/` menu.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub hint: Option<String>,
|
||||
/// Canonical folder holding `SKILL.md` (symlinks resolved, so duplicates collapse).
|
||||
pub path: IpcPath,
|
||||
pub source: AgentSkillSource,
|
||||
/// Other skill roots whose symlinked entry resolved to this same canonical `path`.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub also_in: Vec<AgentSkillSource>,
|
||||
/// False when frontmatter sets `user-invocable: false` (omitted from `/` completion).
|
||||
#[serde(default = "default_true")]
|
||||
pub user_invocable: bool,
|
||||
/// True when frontmatter sets `disable-model-invocation: true` (defaults to `slashOnly`).
|
||||
#[serde(default)]
|
||||
pub disable_model_invocation: bool,
|
||||
/// True when frontmatter sets `context: fork` (passed through natively to supporting CLIs).
|
||||
#[serde(default)]
|
||||
pub context_fork: bool,
|
||||
/// Optional `paths` / `globs` patterns from frontmatter (passed through natively to supporting CLIs).
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub paths: Vec<String>,
|
||||
/// The `SKILL.md` passes validation (`name` matches its folder, `description` present).
|
||||
pub valid: bool,
|
||||
/// What validation found (`name` mismatch, missing or over-long description…).
|
||||
pub warnings: Vec<String>,
|
||||
}
|
||||
|
||||
/// A skill as Settings › Agents › Skills shows it: discovery plus the effective mode and
|
||||
/// which layer decided it.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentSkillState {
|
||||
pub skill: AgentSkill,
|
||||
pub mode: AgentSkillMode,
|
||||
/// What set `mode`: a session override, the workspace, the user's settings, workspace
|
||||
/// trust, or nothing (the default `auto`).
|
||||
pub origin: AgentSkillOrigin,
|
||||
}
|
||||
|
||||
/// Which layer decided a skill's [`AgentSkillState::mode`].
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum AgentSkillOrigin {
|
||||
#[default]
|
||||
None,
|
||||
Session,
|
||||
Workspace,
|
||||
User,
|
||||
/// An untrusted workspace's skills and policies may only turn skills off.
|
||||
Trust,
|
||||
}
|
||||
|
||||
/// An external MCP configuration file discovered on disk (user CLI config or workspace file).
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
|
||||
@@ -172,12 +172,6 @@ struct Session {
|
||||
mcp_config: Option<tempfile::TempPath>,
|
||||
/// MCP servers switched off for this session (`--disallowedTools`), its own config's too.
|
||||
mcp_off: Vec<String>,
|
||||
/// The staged skills folder passed as `--add-dir` (its `.claude/skills` holds the copies).
|
||||
skills_add_dir: Option<PathBuf>,
|
||||
/// The workspace's other roots, each passed as `--add-dir`.
|
||||
additional_dirs: Vec<String>,
|
||||
/// The staged skills' `--settings` JSON (`skillOverrides` for the native ones too).
|
||||
skills_settings: Option<String>,
|
||||
shim: Weak<Shim>,
|
||||
st: Mutex<State>,
|
||||
/// Serializes (re)starting the process.
|
||||
@@ -362,14 +356,10 @@ impl Shim {
|
||||
None
|
||||
}
|
||||
});
|
||||
let skills = params.pointer("/_meta/openidea/skills");
|
||||
let session = Arc::new(Session {
|
||||
id: id.to_owned(),
|
||||
mcp_config,
|
||||
mcp_off,
|
||||
skills_add_dir: skills.and_then(|s| s.get("claudeAddDir")).and_then(Value::as_str).map(PathBuf::from),
|
||||
additional_dirs: additional_dirs(params),
|
||||
skills_settings: skills.and_then(|s| s.get("claudeSettings")).and_then(Value::as_str).map(str::to_owned),
|
||||
shim: Arc::downgrade(self),
|
||||
st: Mutex::new(State {
|
||||
proc: None,
|
||||
@@ -415,9 +405,9 @@ impl Shim {
|
||||
"agentCapabilities": {
|
||||
"loadSession": true,
|
||||
"promptCapabilities": { "image": true, "embeddedContext": true },
|
||||
"sessionCapabilities": { "fork": {}, "additionalDirectories": {} },
|
||||
"sessionCapabilities": { "fork": {} },
|
||||
"mcpCapabilities": { "stdio": true, "http": true, "sse": true },
|
||||
"_meta": { "openidea": { "rollback": true, "steer": true, "backgroundTasks": true, "contextUsage": true } },
|
||||
"_meta": { "openidea": { "rollback": true, "steer": true, "backgroundTasks": true } },
|
||||
},
|
||||
"agentInfo": { "name": "claude", "title": "Claude Code", "version": self.version() },
|
||||
"authMethods": [],
|
||||
@@ -502,11 +492,6 @@ impl Shim {
|
||||
session.steer(params.get("prompt").cloned().unwrap_or_default()).map_err(invalid)?;
|
||||
Ok(json!({}))
|
||||
}
|
||||
"_openidea/context_usage" => {
|
||||
let session = self.session(¶ms)?;
|
||||
let proc = session.st.lock().proc.clone().ok_or_else(|| internal("Claude Code is not running"))?;
|
||||
rt.block_on(proc.control(json!({ "subtype": "get_context_usage" }))).map_err(internal)
|
||||
}
|
||||
"_openidea/stop_task" => {
|
||||
let session = self.session(¶ms)?;
|
||||
let task = params.get("taskId").and_then(Value::as_str).ok_or_else(|| invalid("no taskId"))?;
|
||||
@@ -683,17 +668,6 @@ impl Session {
|
||||
if !self.mcp_off.is_empty() {
|
||||
args.extend(["--disallowedTools".to_owned(), self.mcp_off.join(",")]);
|
||||
}
|
||||
// The staged skills: `.claude/skills` of the added directory is discovered like the
|
||||
// project's own, and the settings hold the modes of the skills it sees natively too.
|
||||
if let Some(dir) = &self.skills_add_dir {
|
||||
args.extend(["--add-dir".to_owned(), dir.to_string_lossy().into_owned()]);
|
||||
}
|
||||
for dir in &self.additional_dirs {
|
||||
args.extend(["--add-dir".to_owned(), dir.clone()]);
|
||||
}
|
||||
if let Some(settings) = &self.skills_settings {
|
||||
args.extend(["--settings".to_owned(), settings.clone()]);
|
||||
}
|
||||
args.extend(start.args());
|
||||
let launch =
|
||||
Launch { program: shim.config.program.clone(), args, cwd: self.cwd.clone(), env: shim.config.env.clone() };
|
||||
@@ -1007,16 +981,11 @@ impl Session {
|
||||
let mut updates = Vec::new();
|
||||
let mut finished = None;
|
||||
let mut read_title = false;
|
||||
let mut refresh_usage = false;
|
||||
{
|
||||
let mut st = self.st.lock();
|
||||
let st = &mut *st;
|
||||
match kind {
|
||||
"system" => match msg.get("subtype").and_then(Value::as_str) {
|
||||
Some("compact_boundary") => {
|
||||
refresh_usage = msg.pointer("/compact_metadata/post_tokens").is_none_or(Value::is_null);
|
||||
updates.extend(st.tr.on_message(&msg));
|
||||
}
|
||||
Some("init") => {
|
||||
st.terminal_only = strings(msg.get("terminal_slash_commands"));
|
||||
}
|
||||
@@ -1120,31 +1089,6 @@ impl Session {
|
||||
if read_title {
|
||||
self.read_title();
|
||||
}
|
||||
if refresh_usage {
|
||||
self.refresh_usage();
|
||||
}
|
||||
}
|
||||
|
||||
/// Sends what the context holds after a compaction that didn't report it, as Claude Code
|
||||
/// counts it (`get_context_usage`); until then the meter would show the count from before.
|
||||
fn refresh_usage(self: &Arc<Self>) {
|
||||
let me = self.clone();
|
||||
tokio::spawn(async move {
|
||||
let Some(proc) = me.st.lock().proc.clone() else { return };
|
||||
let usage = match proc.control(json!({ "subtype": "get_context_usage" })).await {
|
||||
Ok(usage) => usage,
|
||||
Err(e) => {
|
||||
tracing::debug!("reading claude context usage after compaction: {e}");
|
||||
return;
|
||||
}
|
||||
};
|
||||
let n = |k: &str| usage.get(k).and_then(Value::as_u64);
|
||||
let (Some(used), Some(size)) = (n("totalTokens"), n("maxTokens").filter(|m| *m > 0)) else { return };
|
||||
let update = me.st.lock().tr.on_context_usage(used, size);
|
||||
if let Some(shim) = me.shim() {
|
||||
shim.notify(vec![update]);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Sends the session's title once it has one: the one in its transcript, or else one
|
||||
@@ -1558,12 +1502,6 @@ fn write_mcp_config(json: &str) -> std::io::Result<tempfile::TempPath> {
|
||||
/// The servers switched off for the session (`_meta.openidea.mcpServersOff`) as Claude Code
|
||||
/// permission rules that deny all of a server's tools (`mcp__<server>`), so a server of
|
||||
/// Claude Code's own configuration stays off too.
|
||||
/// The session's `additionalDirectories`: the workspace's other roots.
|
||||
fn additional_dirs(params: &Value) -> Vec<String> {
|
||||
let dirs = params.get("additionalDirectories").and_then(Value::as_array);
|
||||
dirs.into_iter().flatten().filter_map(Value::as_str).map(str::to_owned).collect()
|
||||
}
|
||||
|
||||
fn mcp_off(params: &Value) -> Vec<String> {
|
||||
params
|
||||
.pointer("/_meta/openidea/mcpServersOff")
|
||||
|
||||
@@ -531,38 +531,6 @@ async fn sessions_without_a_title_get_one_generated() {
|
||||
assert_eq!(request["request"]["persist"], true);
|
||||
}
|
||||
|
||||
/// A compaction that doesn't report what the context holds now (no `post_tokens`): the
|
||||
/// driver asks Claude Code, and the meter shows that instead of the count from before.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_compaction_without_its_token_count_reads_the_context_usage() {
|
||||
let mut processes = load_fixture("simple");
|
||||
processes[0].extend([
|
||||
Frame::Cli(json!({"type": "system", "subtype": "compact_boundary",
|
||||
"compact_metadata": {"trigger": "manual", "pre_tokens": 120000}})),
|
||||
Frame::Shim(json!({"type": "control_request", "request_id": "req_3",
|
||||
"request": {"subtype": "get_context_usage"}})),
|
||||
Frame::Cli(json!({"type": "control_response", "response": {"subtype": "success", "request_id": "req_3",
|
||||
"response": {"categories": [], "totalTokens": 4200, "maxTokens": 200000, "model": "claude"}}})),
|
||||
]);
|
||||
let cli = replay_cli(processes);
|
||||
let (config, cwd) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
|
||||
let cwd_path = std::fs::canonicalize(cwd.path()).unwrap();
|
||||
let h =
|
||||
Harness::connect(cli.clone(), config.path().into(), config.path().join("pending"), cwd_path, Vec::new()).await;
|
||||
let session = h.new_session().await;
|
||||
h.prompt(&session, "Reply with exactly: hello there").await.unwrap();
|
||||
let mut usage = Vec::new();
|
||||
for _ in 0..100 {
|
||||
usage = h.updates(&session, "usage_update");
|
||||
if usage.last().is_some_and(|u| u["used"] == 4200) {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
}
|
||||
assert!(cli.errors.lock().is_empty(), "{:?}", cli.errors.lock());
|
||||
assert_eq!(usage.last().map(|u| (u["used"].clone(), u["size"].clone())), Some((json!(4200), json!(200000))));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn replay_multi_turn() {
|
||||
let r = replay("multi_turn").await;
|
||||
@@ -1130,24 +1098,6 @@ fn streamed_text_is_not_sent_twice() {
|
||||
assert_eq!(usage[0].update, json!({"sessionUpdate": "usage_update", "used": 15, "size": 1000}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_compaction_replaces_the_context_usage() {
|
||||
let mut t = Translator::new("s", PathBuf::from("/w"), true);
|
||||
let assistant = json!({"type": "assistant", "parent_tool_use_id": null,
|
||||
"message": {"id": "m1", "model": "x", "content": [], "usage": {"input_tokens": 900, "output_tokens": 50}}});
|
||||
t.on_message(&assistant);
|
||||
let result = json!({"modelUsage": {"x": {"contextWindow": 1000}}});
|
||||
assert_eq!(t.on_result(&result)[0].update["used"], 950);
|
||||
let boundary = |meta: Value| json!({"type": "system", "subtype": "compact_boundary", "compact_metadata": meta});
|
||||
let out = t.on_message(&boundary(json!({"trigger": "manual", "pre_tokens": 950, "post_tokens": 120})));
|
||||
assert_eq!(out[0].update, json!({"sessionUpdate": "usage_update", "used": 120, "size": 1000}));
|
||||
// The `/compact` turn's result reports what compaction left, not the count from before.
|
||||
assert_eq!(t.on_result(&result)[0].update["used"], 120);
|
||||
// Without `post_tokens` nothing is known yet (the driver asks): the stale count stays out.
|
||||
assert!(t.on_message(&boundary(json!({"trigger": "auto", "pre_tokens": 950}))).is_empty());
|
||||
assert!(t.on_result(&result).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rate_limits_and_cost() {
|
||||
let mut t = Translator::new("s", PathBuf::from("/w"), false);
|
||||
@@ -1325,10 +1275,3 @@ fn mcp_servers_become_an_mcp_config() {
|
||||
drop(path);
|
||||
assert!(!kept.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn additional_directories_are_read_from_the_session_params() {
|
||||
let params = json!({ "cwd": "/w/api", "additionalDirectories": ["/w/web", 3, "/w/docs"] });
|
||||
assert_eq!(additional_dirs(¶ms), ["/w/web", "/w/docs"]);
|
||||
assert!(additional_dirs(&json!({ "cwd": "/w/api" })).is_empty());
|
||||
}
|
||||
@@ -144,22 +144,6 @@ pub(super) fn result_fields(name: &str, input: &Value, block: &Value, structured
|
||||
content.push(text(&t));
|
||||
}
|
||||
}
|
||||
if let Some(blocks) = block.get("content").and_then(Value::as_array) {
|
||||
for block in blocks {
|
||||
if block.get("type").and_then(Value::as_str) != Some("image") {
|
||||
continue;
|
||||
}
|
||||
let Some(source) = block.get("source") else { continue };
|
||||
if source.get("type").and_then(Value::as_str) != Some("base64") {
|
||||
continue;
|
||||
}
|
||||
let data = source.get("data").and_then(Value::as_str).unwrap_or_default();
|
||||
let mime = source.get("media_type").and_then(Value::as_str).unwrap_or_default();
|
||||
if !data.is_empty() && mime.starts_with("image/") {
|
||||
content.push(json!({"type": "content", "content": {"type": "image", "mimeType": mime, "data": data}}));
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut out = json!({ "status": if failed { "failed" } else { "completed" } });
|
||||
if !content.is_empty() {
|
||||
out["content"] = Value::Array(content);
|
||||
@@ -246,43 +230,6 @@ mod tests {
|
||||
assert_eq!(call_fields("WebSearch", &json!({"query": "q"}), cwd)["kind"], "fetch");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn image_tool_results_keep_text_and_inline_images() {
|
||||
let result = result_fields(
|
||||
"Read",
|
||||
&json!({"file_path": "/w/preview.png"}),
|
||||
&json!({"content": [
|
||||
{"type": "text", "text": "Preview ready"},
|
||||
{"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": "aW1hZ2U="}}
|
||||
]}),
|
||||
None,
|
||||
);
|
||||
assert_eq!(result["status"], "completed");
|
||||
assert_eq!(
|
||||
result["content"],
|
||||
json!([
|
||||
text("Preview ready"),
|
||||
{"type": "content", "content": {"type": "image", "mimeType": "image/png", "data": "aW1hZ2U="}}
|
||||
])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_shell_tool_images_keep_fallback_error_text() {
|
||||
let result = result_fields(
|
||||
"Bash",
|
||||
&json!({}),
|
||||
&json!({"is_error": true, "content": [
|
||||
{"type": "text", "text": "Preview command failed"},
|
||||
{"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": "aW1hZ2U="}}
|
||||
]}),
|
||||
Some(&json!({"stdout": "", "stderr": ""})),
|
||||
);
|
||||
assert_eq!(result["status"], "failed");
|
||||
assert_eq!(result["content"][0], text("Preview command failed"));
|
||||
assert_eq!(result["content"][1]["content"]["type"], "image");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn results() {
|
||||
let input = json!({"file_path": "/w/n.txt", "content": "two"});
|
||||
|
||||
@@ -458,13 +458,6 @@ impl Translator {
|
||||
let last = self.children.get(&tool_use).map(|c| c.last_text.clone()).filter(|t| !t.is_empty());
|
||||
self.finish_child(&tool_use, stop, last.or(summary))
|
||||
}
|
||||
// Compaction replaced the conversation with its summary: the context now holds
|
||||
// `post_tokens`. Without it the stale count must not come back with the result;
|
||||
// the driver asks Claude Code instead (`Session::refresh_usage`).
|
||||
Some("compact_boundary") => {
|
||||
self.used = msg.pointer("/compact_metadata/post_tokens").and_then(Value::as_u64);
|
||||
self.usage_update().into_iter().collect()
|
||||
}
|
||||
// A turn's background tasks (`run_in_background`) outlive it: the task keeps
|
||||
// the list and stays up while it isn't empty (see `Task::release_when_idle`).
|
||||
Some("background_tasks_changed") => {
|
||||
@@ -568,16 +561,6 @@ impl Translator {
|
||||
self.usage_update().into_iter().collect()
|
||||
}
|
||||
|
||||
/// The context usage Claude Code reports (`get_context_usage`), as a usage update.
|
||||
pub fn on_context_usage(&mut self, used: u64, size: u64) -> Update {
|
||||
self.used = Some(used);
|
||||
let mut update = json!({ "sessionUpdate": "usage_update", "used": used, "size": size });
|
||||
if let Some(amount) = self.cost_usd {
|
||||
update["cost"] = json!({ "amount": amount, "currency": "USD" });
|
||||
}
|
||||
Update { session: self.root.clone(), update }
|
||||
}
|
||||
|
||||
fn usage_update(&self) -> Option<Update> {
|
||||
let used = self.used?;
|
||||
let size = self
|
||||
|
||||
@@ -334,38 +334,6 @@ fn str_param<'a>(params: &'a Value, key: &str) -> Result<&'a str, ResponseError>
|
||||
params.get(key).and_then(Value::as_str).ok_or_else(|| invalid(format!("missing {key}")))
|
||||
}
|
||||
|
||||
/// Fills a `thread/start`/`thread/resume`/`thread/fork` request's `config` with the session's
|
||||
/// MCP servers and its staged skills: the off ones, by path (`skills.config` entries with
|
||||
/// `enabled = false`, which the CLI honors for the copies it discovers natively too).
|
||||
fn apply_thread_config(params: &Value, request: &mut Value) {
|
||||
let mut config = translate::mcp_config(params).unwrap_or_else(|| json!({}));
|
||||
let off: Vec<Value> = params
|
||||
.pointer("/_meta/openidea/skills/codexOff")
|
||||
.and_then(Value::as_array)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|entry| {
|
||||
let path = entry.get(1)?.as_str()?;
|
||||
Some(json!({ "path": path, "enabled": false }))
|
||||
})
|
||||
.collect();
|
||||
if !off.is_empty()
|
||||
&& let Some(map) = config.as_object_mut()
|
||||
{
|
||||
map.insert("skills".into(), json!({ "config": off }));
|
||||
}
|
||||
if !config.as_object().is_some_and(|m| m.is_empty()) {
|
||||
request["config"] = config;
|
||||
}
|
||||
// The workspace's other roots join the thread's own: they are where `workspace-write`
|
||||
// may write and what the model is told the workspace holds.
|
||||
if let Some(extra) = params.get("additionalDirectories").and_then(Value::as_array).filter(|a| !a.is_empty())
|
||||
&& let Some(cwd) = params.get("cwd").filter(|c| c.is_string())
|
||||
{
|
||||
request["runtimeWorkspaceRoots"] = std::iter::once(cwd).chain(extra).cloned().collect();
|
||||
}
|
||||
}
|
||||
|
||||
impl CodexShim {
|
||||
fn codex(&self) -> &Peer {
|
||||
self.codex.get().expect("attached before any message")
|
||||
@@ -413,7 +381,7 @@ impl CodexShim {
|
||||
"loadSession": true,
|
||||
"promptCapabilities": { "image": true, "audio": false, "embeddedContext": true },
|
||||
"mcpCapabilities": { "http": false, "sse": false, "stdio": true },
|
||||
"sessionCapabilities": { "fork": {}, "close": {}, "additionalDirectories": {} },
|
||||
"sessionCapabilities": { "fork": {}, "close": {} },
|
||||
"_meta": { "openidea": { "rollback": true, "steer": true } },
|
||||
},
|
||||
"agentInfo": { "name": "codex", "title": "Codex", "version": version },
|
||||
@@ -446,31 +414,6 @@ impl CodexShim {
|
||||
}
|
||||
}
|
||||
|
||||
/// Hands the session's staged skills to the app-server: the farm's `codex` tree joins
|
||||
/// its discovery roots. Best-effort: a CLI version without `skills/extraRoots/set`
|
||||
/// (the method arrived later than some pinned installs) runs without the farm, as
|
||||
/// before.
|
||||
async fn apply_skill_roots(&self, session: &str, params: &Value) {
|
||||
let roots = params
|
||||
.pointer("/_meta/openidea/skills/codexExtraRoots")
|
||||
.and_then(Value::as_array)
|
||||
.map(|a| a.iter().filter_map(Value::as_str).collect::<Vec<_>>())
|
||||
.unwrap_or_default();
|
||||
if roots.is_empty() {
|
||||
return;
|
||||
}
|
||||
let set = tokio::time::timeout(
|
||||
Duration::from_secs(5),
|
||||
self.call("skills/extraRoots/set", json!({ "extraRoots": roots })),
|
||||
)
|
||||
.await;
|
||||
match set {
|
||||
Ok(Ok(_)) => {}
|
||||
Ok(Err(e)) => tracing::info!("codex session {session}: could not set the extra skill roots: {}", e.message),
|
||||
Err(e) => tracing::info!("codex session {session}: could not set the extra skill roots: {e}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Registers a thread codex opened for a session of its own; returns its `configOptions`.
|
||||
fn open_thread(&self, result: &Value, models: &[ModelInfo], settings: Option<Settings>) -> (String, Value) {
|
||||
let thread = result.get("thread").unwrap_or(&Value::Null);
|
||||
@@ -491,13 +434,14 @@ impl CodexShim {
|
||||
let models = self.models().await?;
|
||||
self.prepare_project_trust(params).await;
|
||||
let mut request = json!({ "cwd": params.get("cwd") });
|
||||
apply_thread_config(params, &mut request);
|
||||
if let Some(config) = translate::mcp_config(params) {
|
||||
request["config"] = config;
|
||||
}
|
||||
let result = self.call("thread/start", request).await?;
|
||||
let (id, options) = self.open_thread(&result, &models, None);
|
||||
if id.is_empty() {
|
||||
return Err(error(codes::INTERNAL_ERROR, "codex started no thread"));
|
||||
}
|
||||
self.apply_skill_roots(&id, params).await;
|
||||
self.publish_skills(&id).await;
|
||||
Ok(json!({ "sessionId": id, "configOptions": options }))
|
||||
}
|
||||
@@ -508,7 +452,9 @@ impl CodexShim {
|
||||
let models = self.models().await?;
|
||||
self.prepare_project_trust(params).await;
|
||||
let mut request = json!({ "threadId": id, "cwd": params.get("cwd") });
|
||||
apply_thread_config(params, &mut request);
|
||||
if let Some(config) = translate::mcp_config(params) {
|
||||
request["config"] = config;
|
||||
}
|
||||
let result = self.call("thread/resume", request).await?;
|
||||
let (_, options) = self.open_thread(&result, &models, None);
|
||||
let cwd = self.state.lock().threads.get(id).and_then(|t| t.cwd.clone());
|
||||
@@ -516,7 +462,6 @@ impl CodexShim {
|
||||
for update in translate::history(thread, cwd.as_deref()) {
|
||||
self.emit(id, update);
|
||||
}
|
||||
self.apply_skill_roots(id, params).await;
|
||||
self.publish_skills(id).await;
|
||||
Ok(json!({ "configOptions": options }))
|
||||
}
|
||||
@@ -527,7 +472,9 @@ impl CodexShim {
|
||||
self.prepare_project_trust(params).await;
|
||||
let settings = self.state.lock().threads.get(source).and_then(|t| t.settings.clone());
|
||||
let mut request = json!({ "threadId": source, "cwd": params.get("cwd") });
|
||||
apply_thread_config(params, &mut request);
|
||||
if let Some(config) = translate::mcp_config(params) {
|
||||
request["config"] = config;
|
||||
}
|
||||
if let Some(s) = &settings {
|
||||
request["model"] = json!(s.model_slug(&models));
|
||||
request["approvalPolicy"] = json!(s.mode.approval_policy());
|
||||
@@ -535,7 +482,6 @@ impl CodexShim {
|
||||
}
|
||||
let result = self.call("thread/fork", request).await?;
|
||||
let (id, options) = self.open_thread(&result, &models, settings);
|
||||
self.apply_skill_roots(&id, params).await;
|
||||
self.publish_skills(&id).await;
|
||||
Ok(json!({ "sessionId": id, "configOptions": options }))
|
||||
}
|
||||
|
||||
@@ -473,39 +473,6 @@ fn history_replays_turns() {
|
||||
assert_eq!(updates[4]["status"], "completed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn viewed_generated_and_attached_images_carry_their_pixels() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let png = dir.path().join("shot.png");
|
||||
std::fs::write(&png, b"\x89PNG\r\n").unwrap();
|
||||
let png_path = png.to_str().unwrap();
|
||||
let encoded = "iVBORw0K";
|
||||
let view = json!({"id": "v", "type": "imageView", "path": png_path});
|
||||
assert!(tool_call(&view, false, None, None).unwrap().get("content").is_none());
|
||||
let image = &tool_call(&view, true, None, None).unwrap()["content"][0]["content"];
|
||||
assert_eq!((image["type"].as_str(), image["data"].as_str()), (Some("image"), Some(encoded)));
|
||||
let missing = json!({"id": "v", "type": "imageView", "path": dir.path().join("gone.png")});
|
||||
assert!(tool_call(&missing, true, None, None).unwrap().get("content").is_none());
|
||||
let inline = json!({"id": "g", "type": "imageGeneration", "status": "completed", "result": encoded});
|
||||
let image = &tool_call(&inline, true, None, None).unwrap()["content"][0]["content"];
|
||||
assert_eq!((image["mimeType"].as_str(), image["data"].as_str()), (Some("image/png"), Some(encoded)));
|
||||
let saved =
|
||||
json!({"id": "g", "type": "imageGeneration", "status": "completed", "fileId": "f", "savedPath": png_path});
|
||||
assert_eq!(tool_call(&saved, true, None, None).unwrap()["content"][0]["content"]["data"], encoded);
|
||||
|
||||
let thread = json!({"turns": [{"items": [{"type": "userMessage", "id": "u", "content": [
|
||||
{"type": "image", "url": "data:image/jpeg;base64,/9j/"},
|
||||
{"type": "image", "url": "https://example.com/a.png"},
|
||||
{"type": "localImage", "path": png_path},
|
||||
{"type": "localImage", "path": "/gone.png"}
|
||||
]}]}]});
|
||||
let contents: Vec<Value> = history(&thread, None).into_iter().map(|u| u["content"].clone()).collect();
|
||||
assert_eq!(contents[0], json!({"type": "image", "mimeType": "image/jpeg", "data": "/9j/"}));
|
||||
assert_eq!(contents[1]["type"], "resource_link");
|
||||
assert_eq!(contents[2], json!({"type": "image", "mimeType": "image/png", "data": encoded}));
|
||||
assert_eq!(contents[3], json!({"type": "text", "text": "/gone.png"}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn history_preserves_async_questions_with_stable_answer_ids() {
|
||||
let updates = history(
|
||||
@@ -1880,14 +1847,3 @@ fn skills_become_commands_with_their_invocation_names() {
|
||||
assert!(skill_commands(&json!({"data": []})).unwrap()["availableCommands"].as_array().unwrap().is_empty());
|
||||
assert!(skill_commands(&json!({})).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn workspace_roots_join_the_thread_roots() {
|
||||
let params = json!({ "cwd": "/w/api", "mcpServers": [], "additionalDirectories": ["/w/web"] });
|
||||
let mut request = json!({});
|
||||
apply_thread_config(¶ms, &mut request);
|
||||
assert_eq!(request["runtimeWorkspaceRoots"], json!(["/w/api", "/w/web"]));
|
||||
let mut request = json!({});
|
||||
apply_thread_config(&json!({ "cwd": "/w/api", "mcpServers": [] }), &mut request);
|
||||
assert!(request.get("runtimeWorkspaceRoots").is_none());
|
||||
}
|
||||
@@ -348,18 +348,36 @@ pub(super) fn user_input(prompt: &Value) -> Vec<Value> {
|
||||
}
|
||||
"resource" => {
|
||||
let r = b.get("resource")?;
|
||||
let path = crate::images::uri_path(r.get("uri").and_then(Value::as_str).unwrap_or_default());
|
||||
let path = uri_path(r.get("uri").and_then(Value::as_str).unwrap_or_default());
|
||||
let text = r.get("text").and_then(Value::as_str)?;
|
||||
Some(json!({ "type": "text", "text": format!("<file path=\"{path}\">\n{text}\n</file>") }))
|
||||
}
|
||||
"resource_link" => {
|
||||
Some(json!({ "type": "text", "text": crate::images::uri_path(b.get("uri")?.as_str()?) }))
|
||||
}
|
||||
"resource_link" => Some(json!({ "type": "text", "text": uri_path(b.get("uri")?.as_str()?) })),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The path of a `file://` URI (percent-decoded); other URIs as they are.
|
||||
fn uri_path(uri: &str) -> String {
|
||||
let Some(rest) = uri.strip_prefix("file://") else { return uri.to_owned() };
|
||||
let bytes = rest.as_bytes();
|
||||
let mut out = Vec::with_capacity(bytes.len());
|
||||
let mut i = 0;
|
||||
while i < bytes.len() {
|
||||
if bytes[i] == b'%'
|
||||
&& let Some(b) = rest.get(i + 1..i + 3).and_then(|h| u8::from_str_radix(h, 16).ok())
|
||||
{
|
||||
out.push(b);
|
||||
i += 3;
|
||||
} else {
|
||||
out.push(bytes[i]);
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
String::from_utf8_lossy(&out).into_owned()
|
||||
}
|
||||
|
||||
/// A `session/update` notification's `update` for content.
|
||||
pub(super) fn chunk(kind: &str, text: &str) -> Value {
|
||||
json!({ "sessionUpdate": kind, "content": { "type": "text", "text": text } })
|
||||
@@ -449,9 +467,6 @@ pub(super) fn tool_call(item: &Value, done: bool, cwd: Option<&str>, output: Opt
|
||||
"imageView" => {
|
||||
let path = item.get("path").and_then(Value::as_str).unwrap_or_default();
|
||||
call.insert("locations".into(), json!([{ "path": path }]));
|
||||
if done && let Some(image) = crate::images::from_file(std::path::Path::new(path)) {
|
||||
call.insert("content".into(), json!([image_content(&image)]));
|
||||
}
|
||||
(format!("View {}", display_path(path, cwd)), "read")
|
||||
}
|
||||
"collabAgentToolCall" => {
|
||||
@@ -467,12 +482,7 @@ pub(super) fn tool_call(item: &Value, done: bool, cwd: Option<&str>, output: Opt
|
||||
}
|
||||
"contextCompaction" => ("Compact the conversation".to_owned(), "other"),
|
||||
"sleep" => ("Wait".to_owned(), "other"),
|
||||
"imageGeneration" => {
|
||||
if done && let Some(image) = generated_image(item) {
|
||||
call.insert("content".into(), json!([image_content(&image)]));
|
||||
}
|
||||
("Generate an image".to_owned(), "other")
|
||||
}
|
||||
"imageGeneration" => ("Generate an image".to_owned(), "other"),
|
||||
_ => return None,
|
||||
};
|
||||
call.insert("sessionUpdate".into(), json!(if done { "tool_call_update" } else { "tool_call" }));
|
||||
@@ -483,19 +493,6 @@ pub(super) fn tool_call(item: &Value, done: bool, cwd: Option<&str>, output: Opt
|
||||
Some(Value::Object(call))
|
||||
}
|
||||
|
||||
fn image_content(image: &crate::model::AgentImage) -> Value {
|
||||
json!({ "type": "content", "content": crate::images::content(image) })
|
||||
}
|
||||
|
||||
/// A generated image: inline (base64 PNG) or, when codex saved it, the file.
|
||||
fn generated_image(item: &Value) -> Option<crate::model::AgentImage> {
|
||||
if let Some(data) = item.get("result").and_then(Value::as_str).filter(|d| !d.is_empty()) {
|
||||
let image = crate::model::AgentImage { mime_type: "image/png".into(), data: data.into(), name: None };
|
||||
return Some(crate::model::AgentImage { mime_type: image.media_type().into(), ..image });
|
||||
}
|
||||
crate::images::from_file(std::path::Path::new(item.get("savedPath")?.as_str()?))
|
||||
}
|
||||
|
||||
/// The output of a running command, as a `tool_call_update`.
|
||||
pub(super) fn command_output(id: &str, output: &str) -> Value {
|
||||
json!({ "sessionUpdate": "tool_call_update", "toolCallId": id, "content": [text_content(&tail(output))] })
|
||||
@@ -859,23 +856,9 @@ pub(super) fn history(thread: &Value, cwd: Option<&str>) -> Vec<Value> {
|
||||
"user_message_chunk",
|
||||
c.get("text").and_then(Value::as_str).unwrap_or_default(),
|
||||
)),
|
||||
Some("image") => {
|
||||
let url = c.get("url").and_then(Value::as_str).unwrap_or_default();
|
||||
let content = crate::images::from_uri(url).map_or_else(
|
||||
|| json!({ "type": "resource_link", "uri": url, "name": "image" }),
|
||||
|image| crate::images::content(&image),
|
||||
);
|
||||
out.push(json!({ "sessionUpdate": "user_message_chunk", "content": content }));
|
||||
}
|
||||
Some("localImage") => {
|
||||
let path = c.get("path").and_then(Value::as_str).unwrap_or_default();
|
||||
out.push(match crate::images::from_file(std::path::Path::new(path)) {
|
||||
Some(image) => json!({ "sessionUpdate": "user_message_chunk",
|
||||
"content": crate::images::content(&image) }),
|
||||
None => chunk("user_message_chunk", path),
|
||||
});
|
||||
}
|
||||
Some("mention" | "skill") => {
|
||||
Some("image") => out.push(json!({ "sessionUpdate": "user_message_chunk",
|
||||
"content": { "type": "resource_link", "uri": c.get("url"), "name": "image" } })),
|
||||
Some("localImage" | "mention" | "skill") => {
|
||||
let path = c.get("path").and_then(Value::as_str).unwrap_or_default();
|
||||
out.push(chunk("user_message_chunk", path));
|
||||
}
|
||||
|
||||
@@ -144,8 +144,7 @@ async fn discover_once(spec: ProviderSpec, cwd: PathBuf, strip_ambient: bool) ->
|
||||
move || spec.resolve_for_launch_with_copilot_env(&cwd, strip_ambient)
|
||||
})
|
||||
.await
|
||||
.map_err(|e| DiscoverError { message: e.to_string(), allow_acp_fallback: false })?
|
||||
.map_err(|e| DiscoverError { message: e, allow_acp_fallback: false })?;
|
||||
.map_err(|e| DiscoverError { message: e.to_string(), allow_acp_fallback: false })?;
|
||||
let cwd = dunce::canonicalize(&cwd).unwrap_or(cwd);
|
||||
let args = headless_args(&launch.args);
|
||||
let peer = Peer::spawn_framed(
|
||||
@@ -372,24 +371,6 @@ fn error(code: i64, message: impl Into<String>) -> ResponseError {
|
||||
ResponseError { code, message: message.into(), data: None }
|
||||
}
|
||||
|
||||
/// Adds the session's staged skills to a `session.create`/`session.resume` request:
|
||||
/// `skillDirectories` (the farm's `copilot` tree) and `disabledSkills` (the off and
|
||||
/// slash-only ones; Copilot invokes skills with the model only, so a slash-only skill has
|
||||
/// no other switch here).
|
||||
fn apply_skills(params: &Value, req: &mut Value) {
|
||||
let skills = params.pointer("/_meta/openidea/skills");
|
||||
if let Some(dirs) = skills.and_then(|s| s.get("copilotSkillDirectories")).and_then(Value::as_array)
|
||||
&& !dirs.is_empty()
|
||||
{
|
||||
req["skillDirectories"] = json!(dirs.iter().filter_map(Value::as_str).collect::<Vec<_>>());
|
||||
}
|
||||
if let Some(disabled) = skills.and_then(|s| s.get("copilotDisabledSkills")).and_then(Value::as_array)
|
||||
&& !disabled.is_empty()
|
||||
{
|
||||
req["disabledSkills"] = json!(disabled.iter().filter_map(Value::as_str).collect::<Vec<_>>());
|
||||
}
|
||||
}
|
||||
|
||||
fn invalid(message: impl Into<String>) -> ResponseError {
|
||||
error(codes::INVALID_PARAMS, message)
|
||||
}
|
||||
@@ -514,7 +495,6 @@ impl CopilotShim {
|
||||
if let Some(disabled) = translate::wire_disabled_mcp_servers(params) {
|
||||
req["disabledMcpServers"] = disabled;
|
||||
}
|
||||
apply_skills(params, &mut req);
|
||||
|
||||
let created = self.call("session.create", req).await?;
|
||||
let session_id = created
|
||||
@@ -565,7 +545,6 @@ impl CopilotShim {
|
||||
if let Some(disabled) = translate::wire_disabled_mcp_servers(params) {
|
||||
req["disabledMcpServers"] = disabled;
|
||||
}
|
||||
apply_skills(params, &mut req);
|
||||
|
||||
let resumed = self.call("session.resume", req).await?;
|
||||
if let Ok(current) = self.call("session.model.getCurrent", json!({ "sessionId": session_id })).await {
|
||||
|
||||
@@ -312,7 +312,7 @@ impl Settings {
|
||||
}
|
||||
|
||||
/// Parses `models.list` + optional `models.listTokenPriceUnits` into catalog entries,
|
||||
/// prepending `"auto"` when direct models are present or Copilot advertises an enabled Auto tier.
|
||||
/// prepending `"auto"` when not already in the list.
|
||||
pub(super) fn parse_catalog(list: &Value, price_units: Option<&Value>) -> Vec<ModelEntry> {
|
||||
let units = parse_price_units(price_units);
|
||||
let raw = list
|
||||
@@ -322,7 +322,7 @@ pub(super) fn parse_catalog(list: &Value, price_units: Option<&Value>) -> Vec<Mo
|
||||
.map(Vec::as_slice)
|
||||
.unwrap_or_default();
|
||||
let mut out = Vec::new();
|
||||
if !raw.iter().any(|m| str_of(m, "id") == Some("auto")) && (!raw.is_empty() || auto_model_available(list)) {
|
||||
if !raw.iter().any(|m| str_of(m, "id") == Some("auto")) && !raw.is_empty() {
|
||||
out.push(ModelEntry {
|
||||
id: "auto".into(),
|
||||
name: "Auto".into(),
|
||||
@@ -344,18 +344,6 @@ pub(super) fn parse_catalog(list: &Value, price_units: Option<&Value>) -> Vec<Mo
|
||||
out
|
||||
}
|
||||
|
||||
fn auto_model_available(list: &Value) -> bool {
|
||||
let Some(auto) = list.get("auto") else { return false };
|
||||
if auto.get("enabled").or_else(|| auto.pointer("/status/enabled")).and_then(Value::as_bool) == Some(false) {
|
||||
return false;
|
||||
}
|
||||
let Some(tiers) = auto.get("tiers").and_then(Value::as_array) else { return auto.is_object() };
|
||||
tiers.is_empty()
|
||||
|| tiers.iter().any(|tier| {
|
||||
tier.get("enabled").or_else(|| tier.pointer("/status/enabled")).and_then(Value::as_bool) != Some(false)
|
||||
})
|
||||
}
|
||||
|
||||
fn parse_model(m: &Value, units: &HashMap<String, PriceUnit>) -> Option<ModelEntry> {
|
||||
let id = str_of(m, "id")?.to_owned();
|
||||
if m.get("model_picker_enabled").and_then(Value::as_bool) == Some(false)
|
||||
|
||||
@@ -110,72 +110,6 @@ fn sample_price_units() -> Value {
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_an_enabled_auto_only_catalog() {
|
||||
let list = json!({
|
||||
"models": [],
|
||||
"auto": {
|
||||
"defaultTier": "balance",
|
||||
"tiers": [
|
||||
{
|
||||
"id": "balance",
|
||||
"displayName": "Standard",
|
||||
"type": "auto",
|
||||
"fusionTier": "standard",
|
||||
"status": { "enabled": true, "pickerVisible": true }
|
||||
},
|
||||
{
|
||||
"id": "hydrafusion",
|
||||
"displayName": "High",
|
||||
"type": "fusion",
|
||||
"fusionTier": "high",
|
||||
"status": {
|
||||
"enabled": false,
|
||||
"pickerVisible": true,
|
||||
"reason": "user_not_eligible"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "fast",
|
||||
"displayName": "Fast",
|
||||
"type": "auto",
|
||||
"status": { "enabled": true, "pickerVisible": false }
|
||||
}
|
||||
],
|
||||
"providerId": "copilot"
|
||||
},
|
||||
"imageModels": []
|
||||
});
|
||||
|
||||
let catalog = models::parse_catalog(&list, None);
|
||||
assert_eq!(catalog.iter().map(|m| m.id.as_str()).collect::<Vec<_>>(), ["auto"]);
|
||||
assert_eq!(Settings::new(&catalog, &UserDefaults::default()).model, "auto");
|
||||
|
||||
let options =
|
||||
config::parse_options(&models::config_options(&catalog, &Settings::new(&catalog, &UserDefaults::default())));
|
||||
let model = options.iter().find(|option| option.id == MODEL).unwrap();
|
||||
assert_eq!(model.current.as_deref(), Some("auto"));
|
||||
assert_eq!(model.values.iter().map(|value| value.value.as_str()).collect::<Vec<_>>(), ["auto"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_an_auto_only_catalog_when_every_tier_is_disabled() {
|
||||
let list = json!({
|
||||
"models": [],
|
||||
"auto": {
|
||||
"defaultTier": "balance",
|
||||
"tiers": [
|
||||
{
|
||||
"id": "balance",
|
||||
"status": { "enabled": false, "pickerVisible": true }
|
||||
}
|
||||
]
|
||||
}
|
||||
});
|
||||
|
||||
assert!(models::parse_catalog(&list, None).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_tiered_context_windows_pricing_and_uses_copilots_own_defaults() {
|
||||
let catalog = models::parse_catalog(&sample_models_list(), Some(&sample_price_units()));
|
||||
|
||||
@@ -9,8 +9,6 @@ use serde_json::Value;
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
pub(crate) const COPILOT_GITHUB_ACCOUNT_ENV: &str = "OPENIDEA_COPILOT_GITHUB_ACCOUNT";
|
||||
|
||||
/// The protocol an agent speaks. Native ones run behind an in-process ACP endpoint
|
||||
/// (`native`), so tasks see every agent as ACP and read features from its capabilities.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
@@ -84,7 +82,6 @@ const BUILTIN: &[(&str, &str, Driver, &[&str], &str)] = &[
|
||||
("kiro", "Kiro", Driver::Acp, &["kiro-cli", "acp"], "Run `kiro-cli login` in a terminal."),
|
||||
("vibe", "Mistral Vibe", Driver::Acp, &["vibe-acp"], "Run `vibe` in a terminal and sign in."),
|
||||
("omp", "OMP", Driver::Acp, &["omp", "acp"], "Run `omp` in a terminal and sign in."),
|
||||
("hermes", "Hermes Agent", Driver::Acp, &["hermes", "acp"], "Run `hermes model` in a terminal."),
|
||||
];
|
||||
|
||||
fn builtins() -> Vec<ProviderSpec> {
|
||||
@@ -140,31 +137,15 @@ impl ProviderSpec {
|
||||
/// Resolve once before connecting, so authentication guidance names that same install.
|
||||
pub(crate) fn resolve_for_launch(self, cwd: &Path) -> Self {
|
||||
let strip = prefer_stored_copilot_auth();
|
||||
self.resolve_for_launch_base(cwd, strip)
|
||||
self.resolve_for_launch_with_copilot_env(cwd, strip)
|
||||
}
|
||||
|
||||
pub(crate) fn resolve_for_launch_with_copilot_env(
|
||||
self,
|
||||
cwd: &Path,
|
||||
strip_ambient_tokens: bool,
|
||||
) -> Result<Self, String> {
|
||||
let account = is_copilot_provider(&self.id).then(|| copilot_github_account(&self.env)).flatten();
|
||||
let mut resolved = self.resolve_for_launch_base(cwd, strip_ambient_tokens || account.is_some());
|
||||
if let Some(account) = account {
|
||||
let token = github_token_for_account(&account)?;
|
||||
resolved.env.retain(|(name, _)| !AMBIENT_COPILOT_AUTH_VARS.contains(&name.as_str()));
|
||||
resolved.env.push(("COPILOT_GITHUB_TOKEN".into(), token));
|
||||
}
|
||||
Ok(resolved)
|
||||
}
|
||||
|
||||
fn resolve_for_launch_base(mut self, cwd: &Path, strip_ambient_tokens: bool) -> Self {
|
||||
pub(crate) fn resolve_for_launch_with_copilot_env(mut self, cwd: &Path, strip_ambient_tokens: bool) -> Self {
|
||||
if self.driver != Driver::Acp {
|
||||
self.command = crate::native::newest_install(&self.command);
|
||||
}
|
||||
if is_copilot_provider(&self.id) {
|
||||
self.env = sanitized_copilot_env(&self.env, strip_ambient_tokens);
|
||||
self.env.retain(|(name, _)| name != COPILOT_GITHUB_ACCOUNT_ENV);
|
||||
}
|
||||
let program = ide_jsonrpc::resolve_spawn_program(&self.command, &self.env);
|
||||
self.command =
|
||||
@@ -182,50 +163,6 @@ pub(crate) fn is_copilot_provider(id: &str) -> bool {
|
||||
id == "copilot" || id.starts_with("copilot-")
|
||||
}
|
||||
|
||||
pub(crate) fn copilot_github_account(env: &[(String, String)]) -> Option<String> {
|
||||
env.iter()
|
||||
.rev()
|
||||
.find(|(name, _)| name == COPILOT_GITHUB_ACCOUNT_ENV)
|
||||
.map(|(_, value)| value.trim())
|
||||
.filter(|value| !value.is_empty())
|
||||
.map(str::to_owned)
|
||||
}
|
||||
|
||||
fn github_token_for_account(account: &str) -> Result<String, String> {
|
||||
let path = ide_core::process::shell_env()
|
||||
.find(|(name, _)| name == "PATH")
|
||||
.map(|(_, value)| value)
|
||||
.or_else(|| ide_core::process::host_var_os("PATH"));
|
||||
let program = path
|
||||
.as_deref()
|
||||
.and_then(|path| ide_core::process::find_executable("gh", path))
|
||||
.ok_or_else(|| "GitHub CLI (`gh`) is required to select a Copilot GitHub account".to_owned())?;
|
||||
let mut command = std::process::Command::new(program);
|
||||
command.args(["auth", "token", "--hostname", "github.com", "--user", account]).envs(ide_core::process::shell_env());
|
||||
for name in AMBIENT_COPILOT_AUTH_VARS {
|
||||
command.env_remove(name);
|
||||
}
|
||||
let output = command
|
||||
.output()
|
||||
.map_err(|error| format!("Couldn't read GitHub authentication for account {account}: {error}"))?;
|
||||
if !output.status.success() {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
let detail = stderr.trim();
|
||||
return Err(if detail.is_empty() {
|
||||
format!("GitHub CLI has no authenticated account named {account}")
|
||||
} else {
|
||||
format!("Couldn't use GitHub account {account}: {detail}")
|
||||
});
|
||||
}
|
||||
let token = String::from_utf8(output.stdout)
|
||||
.map_err(|_| format!("GitHub CLI returned a non-text token for account {account}"))?;
|
||||
let token = token.trim();
|
||||
if token.is_empty() {
|
||||
return Err(format!("GitHub CLI returned no token for account {account}"));
|
||||
}
|
||||
Ok(token.to_owned())
|
||||
}
|
||||
|
||||
pub(crate) fn prefer_stored_copilot_auth() -> bool {
|
||||
PREFER_STORED_COPILOT_AUTH.load(std::sync::atomic::Ordering::Acquire)
|
||||
}
|
||||
@@ -373,7 +310,6 @@ pub(crate) fn describe(spec: &ProviderSpec) -> AgentProvider {
|
||||
command_editable: reason.is_none(),
|
||||
command_read_only_reason: reason,
|
||||
installed: installed(&spec.command),
|
||||
can_check_cli_update: spec.source == AgentSource::Builtin && crate::cli_update::package(&spec.id).is_some(),
|
||||
env: spec.env.iter().cloned().collect(),
|
||||
config: vec![],
|
||||
thought_levels: BTreeMap::new(),
|
||||
@@ -402,31 +338,6 @@ pub(crate) fn set_builtin_env(
|
||||
id: &str,
|
||||
env: BTreeMap<String, String>,
|
||||
) -> IdeResult<()> {
|
||||
if id == "copilot" {
|
||||
let file = custom_dir.join("copilot.toml");
|
||||
if file.try_exists()?
|
||||
&& let mut agent = CustomAgent::read_with(&file, id, secrets).map_err(IdeError::invalid)?
|
||||
&& agent.registry.is_some()
|
||||
{
|
||||
let existing = agent.env.clone();
|
||||
let mut existing_launch_env = existing.clone();
|
||||
let mut next_launch_env = env.clone();
|
||||
existing_launch_env.remove(COPILOT_GITHUB_ACCOUNT_ENV);
|
||||
next_launch_env.remove(COPILOT_GITHUB_ACCOUNT_ENV);
|
||||
if existing_launch_env != next_launch_env {
|
||||
return Err(IdeError::invalid(format!("{id} is installed from the ACP Registry")));
|
||||
}
|
||||
match env.get(COPILOT_GITHUB_ACCOUNT_ENV).filter(|value| !value.trim().is_empty()) {
|
||||
Some(account) => {
|
||||
agent.env.insert(COPILOT_GITHUB_ACCOUNT_ENV.into(), account.trim().into());
|
||||
}
|
||||
None => {
|
||||
agent.env.remove(COPILOT_GITHUB_ACCOUNT_ENV);
|
||||
}
|
||||
}
|
||||
return agent.write(&file).map_err(Into::into);
|
||||
}
|
||||
}
|
||||
update_builtin(custom_dir, secrets, id, |agent, _| agent.env = env)
|
||||
}
|
||||
|
||||
@@ -592,7 +503,7 @@ fn validated_custom_id(id: &str) -> IdeResult<String> {
|
||||
}
|
||||
|
||||
/// Turns an `acp.json` server name into a file-stem id (`"My Agent!"` → `"my-agent"`).
|
||||
pub(crate) fn slugify_id(name: &str) -> String {
|
||||
fn slugify_id(name: &str) -> String {
|
||||
let mut id = String::with_capacity(name.len());
|
||||
for c in name.chars() {
|
||||
if c.is_ascii_alphanumeric() {
|
||||
@@ -805,15 +716,6 @@ mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn hermes_is_built_in_over_acp() {
|
||||
let spec = builtin_spec("hermes").unwrap();
|
||||
assert_eq!(spec.driver, Driver::Acp);
|
||||
let info = describe(&spec);
|
||||
assert_eq!((info.name.as_str(), info.command.as_str()), ("Hermes Agent", "hermes acp"));
|
||||
assert_eq!(info.login_hint.as_deref(), Some("Run `hermes model` in a terminal."));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qoder_global_and_cn_editions_are_both_built_in() {
|
||||
let info = |id: &str| describe(&load(None, None).into_iter().find(|s| s.id == id).unwrap());
|
||||
@@ -1043,46 +945,6 @@ mod tests {
|
||||
set_builtin_env(dir.path(), None, "not-a-builtin", env).unwrap_err();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn registry_copilot_allows_only_the_github_account_override() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let file = dir.path().join("copilot.toml");
|
||||
CustomAgent {
|
||||
name: Some("GitHub Copilot".into()),
|
||||
driver: Driver::Acp,
|
||||
command: "/tools/copilot".into(),
|
||||
args: vec!["--acp".into()],
|
||||
env: BTreeMap::from([("REGISTRY_SETTING".into(), "kept".into())]),
|
||||
registry: Some(RegistryRef { id: "copilot".into(), version: "1.0.0".into() }),
|
||||
}
|
||||
.write(&file)
|
||||
.unwrap();
|
||||
|
||||
set_builtin_env(
|
||||
dir.path(),
|
||||
None,
|
||||
"copilot",
|
||||
BTreeMap::from([
|
||||
("REGISTRY_SETTING".into(), "kept".into()),
|
||||
(COPILOT_GITHUB_ACCOUNT_ENV.into(), "dengliu_microsoft".into()),
|
||||
]),
|
||||
)
|
||||
.unwrap();
|
||||
let spec = load(Some(dir.path()), None).into_iter().find(|spec| spec.id == "copilot").unwrap();
|
||||
assert_eq!(copilot_github_account(&spec.env).as_deref(), Some("dengliu_microsoft"));
|
||||
|
||||
set_builtin_env(dir.path(), None, "copilot", BTreeMap::from([("REGISTRY_SETTING".into(), "changed".into())]))
|
||||
.unwrap_err();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn launch_metadata_never_passes_the_github_account_control_to_copilot() {
|
||||
let mut spec = builtin_spec("copilot").unwrap();
|
||||
spec.env.push((COPILOT_GITHUB_ACCOUNT_ENV.into(), "dengliu_microsoft".into()));
|
||||
let resolved = spec.resolve_for_launch(Path::new("."));
|
||||
assert!(resolved.env.iter().all(|(name, _)| name != COPILOT_GITHUB_ACCOUNT_ENV));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn acp_adapters_of_native_agents_are_unlisted_until_customized() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -537,14 +537,6 @@ fn install_entry_with(
|
||||
return Err(e);
|
||||
}
|
||||
};
|
||||
let github_account = (entry.id == "copilot")
|
||||
.then(|| CustomAgent::read(&file).ok())
|
||||
.flatten()
|
||||
.and_then(|agent| agent.env.get(provider::COPILOT_GITHUB_ACCOUNT_ENV).cloned());
|
||||
let mut env = env;
|
||||
if let Some(account) = github_account {
|
||||
env.insert(provider::COPILOT_GITHUB_ACCOUNT_ENV.into(), account);
|
||||
}
|
||||
let agent = CustomAgent {
|
||||
name: Some(entry.name.clone()),
|
||||
driver: Driver::Acp,
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
+14
-1235
File diff suppressed because it is too large.
Load diff
+278
-1406
File diff suppressed because it is too large.
Load diff
@@ -1,6 +1,6 @@
|
||||
//! Folds ACP `session/update` notifications into a task's entries.
|
||||
|
||||
use crate::model::{AgentEntry, AgentImage, AgentPlanItem, AgentSubagentStatus, AgentToolDiff, AgentToolStatus};
|
||||
use crate::model::{AgentEntry, AgentPlanItem, AgentSubagentStatus, AgentToolDiff, AgentToolStatus};
|
||||
use ide_core::IpcPath;
|
||||
use serde_json::Value;
|
||||
use std::collections::HashMap;
|
||||
@@ -8,9 +8,6 @@ use std::collections::HashMap;
|
||||
/// Tool output kept per call; longer output keeps its tail.
|
||||
const MAX_OUTPUT: usize = 64 * 1024;
|
||||
|
||||
/// Image files a read tool names that are shown when it reports none itself.
|
||||
const MAX_READ_IMAGES: usize = 4;
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Timeline {
|
||||
pub entries: Vec<AgentEntry>,
|
||||
@@ -87,10 +84,7 @@ impl Timeline {
|
||||
status: tool_status(update.get("status")).unwrap_or(AgentToolStatus::Pending),
|
||||
locations: locations(update.get("locations")),
|
||||
output: None,
|
||||
images: Vec::new(),
|
||||
diffs: Vec::new(),
|
||||
started_ms: Some(crate::now_ms()),
|
||||
ended_ms: None,
|
||||
};
|
||||
let index = match self.tools.get(&id) {
|
||||
Some(&i) => {
|
||||
@@ -140,22 +134,17 @@ impl Timeline {
|
||||
fn append_text(&mut self, thought: bool, text: &str) -> usize {
|
||||
match self.entries.last_mut() {
|
||||
Some(AgentEntry::Agent { text: t }) if !thought => t.push_str(text),
|
||||
Some(AgentEntry::Thought { text: t, .. }) if thought => t.push_str(text),
|
||||
Some(AgentEntry::Thought { text: t }) if thought => t.push_str(text),
|
||||
_ => {
|
||||
let text = text.to_owned();
|
||||
return self.push(if thought {
|
||||
AgentEntry::Thought { text, started_ms: Some(crate::now_ms()) }
|
||||
} else {
|
||||
AgentEntry::Agent { text }
|
||||
});
|
||||
return self.push(if thought { AgentEntry::Thought { text } } else { AgentEntry::Agent { text } });
|
||||
}
|
||||
}
|
||||
self.entries.len() - 1
|
||||
}
|
||||
|
||||
fn merge_tool(&mut self, index: usize, update: &Value) {
|
||||
let AgentEntry::Tool { title, kind, status, locations: locs, output, images, diffs, ended_ms, .. } =
|
||||
&mut self.entries[index]
|
||||
let AgentEntry::Tool { title, kind, status, locations: locs, output, diffs, .. } = &mut self.entries[index]
|
||||
else {
|
||||
return;
|
||||
};
|
||||
@@ -167,24 +156,37 @@ impl Timeline {
|
||||
}
|
||||
if let Some(s) = tool_status(update.get("status")) {
|
||||
*status = s;
|
||||
if matches!(s, AgentToolStatus::Completed | AgentToolStatus::Failed) && ended_ms.is_none() {
|
||||
*ended_ms = Some(crate::now_ms());
|
||||
}
|
||||
}
|
||||
if update.get("locations").is_some_and(Value::is_array) {
|
||||
*locs = locations(update.get("locations"));
|
||||
}
|
||||
if let Some(content) = update.get("content").and_then(Value::as_array) {
|
||||
merge_content(content, output, images, diffs);
|
||||
let Some(content) = update.get("content").and_then(Value::as_array) else { return };
|
||||
let mut text = String::new();
|
||||
let mut new_diffs = Vec::new();
|
||||
for item in content {
|
||||
match item.get("type").and_then(Value::as_str) {
|
||||
Some("content") => {
|
||||
if let Some(t) = content_text(item.get("content")) {
|
||||
if !text.is_empty() {
|
||||
text.push('\n');
|
||||
}
|
||||
text.push_str(&t);
|
||||
}
|
||||
}
|
||||
Some("diff") => {
|
||||
let old = item.get("oldText").and_then(Value::as_str).unwrap_or_default();
|
||||
let new = item.get("newText").and_then(Value::as_str).unwrap_or_default();
|
||||
let (added, removed) = line_stats(old, new);
|
||||
new_diffs.push(AgentToolDiff { path: IpcPath(str_field(item, "path").into()), added, removed });
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
// Agents that only name the image a read tool opened (Cursor): show the file itself.
|
||||
if *status == AgentToolStatus::Completed && kind == "read" && images.is_empty() {
|
||||
images.extend(
|
||||
locs.iter()
|
||||
.filter(|p| p.0.is_absolute())
|
||||
.take(MAX_READ_IMAGES)
|
||||
.filter_map(|p| crate::images::from_file(&p.0)),
|
||||
);
|
||||
if !text.is_empty() {
|
||||
*output = Some(tail(text));
|
||||
}
|
||||
if !new_diffs.is_empty() {
|
||||
*diffs = new_diffs;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -351,54 +353,6 @@ fn subagent_status(state: &Value) -> Option<(AgentSubagentStatus, Option<String>
|
||||
})
|
||||
}
|
||||
|
||||
/// Folds a tool update's content into its output, diffs and images.
|
||||
fn merge_content(
|
||||
content: &[Value],
|
||||
output: &mut Option<String>,
|
||||
images: &mut Vec<AgentImage>,
|
||||
diffs: &mut Vec<AgentToolDiff>,
|
||||
) {
|
||||
let mut text = String::new();
|
||||
let mut new_diffs = Vec::new();
|
||||
let mut new_images = Vec::new();
|
||||
for item in content {
|
||||
match item.get("type").and_then(Value::as_str) {
|
||||
Some("content") => {
|
||||
let content = item.get("content");
|
||||
if let Some(image) = content.and_then(crate::images::from_content) {
|
||||
new_images.push(image);
|
||||
} else if let Some(t) = content_text(content) {
|
||||
if !text.is_empty() {
|
||||
text.push('\n');
|
||||
}
|
||||
text.push_str(&t);
|
||||
}
|
||||
}
|
||||
Some("diff") => {
|
||||
let old = item.get("oldText").and_then(Value::as_str).unwrap_or_default();
|
||||
let new = item.get("newText").and_then(Value::as_str).unwrap_or_default();
|
||||
let (added, removed) = line_stats(old, new);
|
||||
new_diffs.push(AgentToolDiff { path: IpcPath(str_field(item, "path").into()), added, removed });
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if !text.is_empty() {
|
||||
// The command a call announced (`$ cmd`) stays above the result that replaces it.
|
||||
let command = output.as_deref().and_then(|o| o.lines().next()).filter(|l| l.starts_with("$ "));
|
||||
if let Some(command) = command.filter(|c| !text.starts_with(c)) {
|
||||
text = format!("{command}\n{text}");
|
||||
}
|
||||
*output = Some(tail(text));
|
||||
}
|
||||
if !new_diffs.is_empty() {
|
||||
*diffs = new_diffs;
|
||||
}
|
||||
if !new_images.is_empty() {
|
||||
*images = new_images;
|
||||
}
|
||||
}
|
||||
|
||||
/// The text of a list of content blocks, one per line.
|
||||
pub(crate) fn blocks_text(content: Option<&Value>) -> String {
|
||||
let blocks = content.and_then(Value::as_array).map(Vec::as_slice).unwrap_or_default();
|
||||
@@ -449,7 +403,6 @@ fn tail(mut text: String) -> String {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::model::AgentImage;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
@@ -471,72 +424,6 @@ mod tests {
|
||||
assert!(matches!(&t.entries[0], AgentEntry::Question { chosen: Some(answer), .. } if answer == "One"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tool_images_survive_updates_text_truncation_and_serialization() {
|
||||
use base64::Engine;
|
||||
let mut t = Timeline::default();
|
||||
t.apply(&json!({"sessionUpdate": "tool_call", "toolCallId": "preview", "title": "Render", "kind": "execute"}));
|
||||
let mut old = serde_json::to_value(&t.entries[0]).unwrap();
|
||||
old.as_object_mut().unwrap().remove("images");
|
||||
let legacy: AgentEntry = serde_json::from_value(old).unwrap();
|
||||
assert!(matches!(legacy, AgentEntry::Tool { images, .. } if images.is_empty()));
|
||||
let data = base64::engine::general_purpose::STANDARD.encode(vec![0; MAX_OUTPUT]);
|
||||
let update = json!({"sessionUpdate": "tool_call_update", "toolCallId": "preview", "content": [
|
||||
{"type": "content", "content": {"type": "text", "text": "x".repeat(MAX_OUTPUT + 100)}},
|
||||
{"type": "content", "content": {"type": "image", "mimeType": "image/png", "data": data}}
|
||||
]});
|
||||
t.apply(&update);
|
||||
t.apply(&update);
|
||||
t.apply(&json!({"sessionUpdate": "tool_call_update", "toolCallId": "preview", "status": "completed"}));
|
||||
let AgentEntry::Tool { images, output, status, .. } = &t.entries[0] else { panic!() };
|
||||
assert_eq!(images, &vec![AgentImage { mime_type: "image/png".into(), data, name: None }]);
|
||||
assert!(output.as_ref().unwrap().len() < MAX_OUTPUT + 100);
|
||||
assert_eq!(*status, AgentToolStatus::Completed);
|
||||
let saved = serde_json::to_string(&t.entries[0]).unwrap();
|
||||
assert_eq!(serde_json::from_str::<AgentEntry>(&saved).unwrap(), t.entries[0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tool_images_come_from_linked_files_and_resource_blobs() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let png = dir.path().join("out.png");
|
||||
std::fs::write(&png, b"\x89PNG\r\n").unwrap();
|
||||
let mut t = Timeline::default();
|
||||
t.apply(&json!({"sessionUpdate": "tool_call", "toolCallId": "r", "title": "Read", "kind": "read"}));
|
||||
t.apply(&json!({"sessionUpdate": "tool_call_update", "toolCallId": "r", "content": [
|
||||
{"type": "content", "content": {"type": "text", "text": "Read the image"}},
|
||||
{"type": "content", "content": {"type": "resource_link", "uri": crate::file_uri(&png), "name": "out.png"}},
|
||||
{"type": "content", "content": {"type": "resource", "resource": {"uri": "mem:1", "mimeType": "image/gif", "blob": "R0lG"}}}
|
||||
]}));
|
||||
let AgentEntry::Tool { images, output, .. } = &t.entries[0] else { panic!() };
|
||||
let types: Vec<&str> = images.iter().map(|i| i.mime_type.as_str()).collect();
|
||||
assert_eq!(types, ["image/png", "image/gif"]);
|
||||
assert_eq!(output.as_deref(), Some("Read the image"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_completed_read_shows_the_image_file_it_names() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let png = dir.path().join("icon.png");
|
||||
std::fs::write(&png, b"\x89PNG\r\n").unwrap();
|
||||
let text = dir.path().join("a.rs");
|
||||
std::fs::write(&text, b"fn main() {}").unwrap();
|
||||
let mut t = Timeline::default();
|
||||
for (id, path) in [("img", &png), ("src", &text)] {
|
||||
t.apply(&json!({"sessionUpdate": "tool_call", "toolCallId": id, "title": "Read", "kind": "read",
|
||||
"locations": [{"path": path}]}));
|
||||
}
|
||||
let images = |t: &Timeline, i: usize| match &t.entries[i] {
|
||||
AgentEntry::Tool { images, .. } => images.len(),
|
||||
_ => panic!(),
|
||||
};
|
||||
assert_eq!(images(&t, 0), 0, "not before the read completes");
|
||||
for id in ["img", "src"] {
|
||||
t.apply(&json!({"sessionUpdate": "tool_call_update", "toolCallId": id, "status": "completed"}));
|
||||
}
|
||||
assert_eq!((images(&t, 0), images(&t, 1)), (1, 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chunks_merge_into_one_message_until_another_entry_comes() {
|
||||
let mut t = Timeline::default();
|
||||
@@ -545,14 +432,11 @@ mod tests {
|
||||
assert_eq!(t.apply(&chunk("lo")).changed, vec![0]);
|
||||
t.apply(&json!({"sessionUpdate": "agent_thought_chunk", "content": {"type": "text", "text": "hmm"}}));
|
||||
t.apply(&chunk("again"));
|
||||
// The thought's start is the clock's: it is there, and the rest compares exactly.
|
||||
let AgentEntry::Thought { started_ms, .. } = &mut t.entries[1] else { panic!("{:?}", t.entries) };
|
||||
assert!(started_ms.take().is_some());
|
||||
assert_eq!(
|
||||
t.entries,
|
||||
vec![
|
||||
AgentEntry::Agent { text: "Hello".into() },
|
||||
AgentEntry::Thought { text: "hmm".into(), started_ms: None },
|
||||
AgentEntry::Thought { text: "hmm".into() },
|
||||
AgentEntry::Agent { text: "again".into() },
|
||||
]
|
||||
);
|
||||
@@ -644,25 +528,6 @@ mod tests {
|
||||
assert!(matches!(t.entries[2], AgentEntry::User { done_ms: None, .. }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_hermes_terminal_call_keeps_its_command_and_times() {
|
||||
let text = |t: &str| serde_json::json!([{"type": "content", "content": {"type": "text", "text": t}}]);
|
||||
let mut t = Timeline::default();
|
||||
t.apply(&serde_json::json!({"sessionUpdate": "tool_call", "toolCallId": "tc-0b98b5e30a28",
|
||||
"kind": "execute", "title": "terminal: echo ok + 2 commands", "locations": [],
|
||||
"content": text("$ echo ok >> notes.txt && wc -l notes.txt")}));
|
||||
let AgentEntry::Tool { started_ms, ended_ms, .. } = &t.entries[0] else { panic!() };
|
||||
assert!(started_ms.is_some() && ended_ms.is_none());
|
||||
t.apply(&serde_json::json!({"sessionUpdate": "tool_call_update", "toolCallId": "tc-0b98b5e30a28",
|
||||
"kind": "execute", "status": "completed",
|
||||
"content": text("terminal result\n- **output:** 3 notes.txt\n- **exit_code:** 0")}));
|
||||
let AgentEntry::Tool { output, status, ended_ms, .. } = &t.entries[0] else { panic!() };
|
||||
assert_eq!(*status, AgentToolStatus::Completed);
|
||||
assert!(ended_ms.is_some());
|
||||
let expected = "$ echo ok >> notes.txt && wc -l notes.txt\nterminal result\n- **output:** 3 notes.txt\n";
|
||||
assert_eq!(output.as_deref(), Some(format!("{expected}- **exit_code:** 0").as_str()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn long_output_keeps_its_tail() {
|
||||
let s = tail("é".repeat(MAX_OUTPUT));
|
||||
|
||||
@@ -25,116 +25,6 @@ fn discover(path: &Path) -> IdeResult<Option<Repo>> {
|
||||
Ok(repo)
|
||||
}
|
||||
|
||||
/// The repositories of a project with nested ones (an own `.git` under the project root, not a
|
||||
/// submodule), with the folder their files are named from: the root of the repository holding
|
||||
/// `cwd`, else `cwd`. `None` when only the repository holding `cwd` (if any) is there.
|
||||
fn nested_repos(cwd: &Path) -> IdeResult<Option<(PathBuf, Vec<Repo>)>> {
|
||||
let Ok(cwd) = dunce::canonicalize(cwd) else { return Ok(None) };
|
||||
let found = ide_vcs::Repos::discover(&cwd, &|_| false)?;
|
||||
if found.all().iter().all(|r| cwd.starts_with(r.root())) {
|
||||
return Ok(None);
|
||||
}
|
||||
let base = found.all().iter().map(|r| r.root()).filter(|r| cwd.starts_with(r)).max().unwrap_or(&cwd).to_path_buf();
|
||||
let mut repos = Vec::new();
|
||||
for r in found.all() {
|
||||
repos.extend(discover(r.root())?);
|
||||
}
|
||||
Ok(Some((base, repos)))
|
||||
}
|
||||
|
||||
/// Whether the project at `cwd` holds repositories nested in it: its changes are each one's.
|
||||
pub(crate) fn spans_repos(cwd: &Path) -> bool {
|
||||
nested_repos(cwd).is_ok_and(|r| r.is_some())
|
||||
}
|
||||
|
||||
/// The repositories a turn's files are in, and the folder those files are named from.
|
||||
struct TurnRepos {
|
||||
base: PathBuf,
|
||||
repos: Vec<Repo>,
|
||||
/// The project holds nested repositories: each one's `HEAD` is recorded on its own.
|
||||
nested: bool,
|
||||
}
|
||||
|
||||
impl TurnRepos {
|
||||
fn of(cwd: &Path) -> IdeResult<Option<Self>> {
|
||||
if let Some((base, repos)) = nested_repos(cwd)? {
|
||||
return Ok(Some(Self { base, repos, nested: true }));
|
||||
}
|
||||
Ok(discover(cwd)?.map(|repo| Self { base: repo.root().to_path_buf(), repos: vec![repo], nested: false }))
|
||||
}
|
||||
|
||||
/// The innermost repository holding `path`.
|
||||
fn owner(&self, path: &Path) -> Option<&Repo> {
|
||||
owning_repo(&self.repos, path)
|
||||
}
|
||||
|
||||
/// `repo`'s `HEAD` as the turn `start` began.
|
||||
fn head_then<'a>(&self, start: &'a TurnStart, repo: &Repo) -> Option<&'a str> {
|
||||
if self.nested { start.heads.get(&root_key(repo.root())) } else { start.head.as_ref() }.map(String::as_str)
|
||||
}
|
||||
}
|
||||
|
||||
fn root_key(root: &Path) -> String {
|
||||
root.to_string_lossy().into_owned()
|
||||
}
|
||||
|
||||
fn owning_repo<'a>(repos: &'a [Repo], path: &Path) -> Option<&'a Repo> {
|
||||
repos.iter().filter(|r| path.starts_with(r.root())).max_by_key(|r| r.root().as_os_str().len())
|
||||
}
|
||||
|
||||
/// `path` as a task in `base` names it, if it is not in a repository nested below `repo` (that
|
||||
/// one lists it itself; to `repo` its folder is untracked).
|
||||
fn nested_rel(base: &Path, repo: &Repo, roots: &[PathBuf], path: &Path) -> Option<String> {
|
||||
let rel = path.strip_prefix(base).ok()?;
|
||||
if path.is_dir()
|
||||
|| roots.iter().any(|n| n.as_path() != repo.root() && n.starts_with(repo.root()) && path.starts_with(n))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
Some(rel.to_string_lossy().replace('\\', "/"))
|
||||
}
|
||||
|
||||
/// The uncommitted changes in every repository of the project, against each one's `HEAD`.
|
||||
fn nested_changes(base: &Path, repos: &[Repo], touched: Option<&BTreeSet<String>>) -> IdeResult<Vec<AgentChange>> {
|
||||
let roots: Vec<PathBuf> = repos.iter().map(|r| r.root().to_path_buf()).collect();
|
||||
// Match deletions too: find the owner by path components, not by opening the file.
|
||||
// Display paths use slash separators and lossy Unicode (see nested_rel). If a checkout's
|
||||
// name cannot round-trip from that representation, keep the full-read fallback.
|
||||
let owners = touched
|
||||
.filter(|_| {
|
||||
roots.iter().all(|root| {
|
||||
root.strip_prefix(base).is_ok_and(|rel| base.join(rel.to_string_lossy().replace('\\', "/")) == *root)
|
||||
})
|
||||
})
|
||||
.map(|paths| {
|
||||
paths.iter().filter_map(|rel| owning_repo(repos, &base.join(rel)).map(Repo::root)).collect::<BTreeSet<_>>()
|
||||
});
|
||||
let mut out: Vec<AgentChange> = Vec::new();
|
||||
for repo in repos {
|
||||
if owners.as_ref().is_some_and(|owners| !owners.contains(repo.root())) {
|
||||
continue;
|
||||
}
|
||||
let listed = match repo.head()?.1 {
|
||||
Some(head) => changes(repo.root(), &head)?,
|
||||
None => {
|
||||
repo.status()?.into_iter().filter(|s| s.path.is_file()).map(|s| added(s.path, s.rel_path)).collect()
|
||||
}
|
||||
};
|
||||
for mut c in listed {
|
||||
let Some(rel) = nested_rel(base, repo, &roots, &c.path.0) else { continue };
|
||||
if out.iter().any(|o| o.path == c.path) {
|
||||
continue;
|
||||
}
|
||||
c.rel_path = rel;
|
||||
c.old_path = None;
|
||||
c.repo = Some(IpcPath(repo.root().to_path_buf()));
|
||||
out.push(c);
|
||||
}
|
||||
}
|
||||
out.sort_by(|a, b| a.rel_path.cmp(&b.rel_path));
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn repo_at(path: &Path) -> IdeResult<Repo> {
|
||||
discover(path)?.ok_or_else(|| IdeError::unavailable(format!("{} is not in a git repository", path.display())))
|
||||
}
|
||||
@@ -148,9 +38,6 @@ pub(crate) fn head_of(path: &Path) -> IdeResult<(String, String)> {
|
||||
|
||||
/// `HEAD`'s commit in `cwd`, `None` outside a repository or before its first commit.
|
||||
pub(crate) fn head_commit(cwd: &Path) -> IdeResult<Option<String>> {
|
||||
if spans_repos(cwd) {
|
||||
return Ok(Some("HEAD".to_owned()));
|
||||
}
|
||||
match discover(cwd)? {
|
||||
Some(repo) => Ok(repo.head()?.1),
|
||||
None => Ok(None),
|
||||
@@ -240,7 +127,6 @@ pub(crate) fn changes(cwd: &Path, base: &str) -> IdeResult<Vec<AgentChange>> {
|
||||
added,
|
||||
removed,
|
||||
old_path: f.old_path,
|
||||
repo: None,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
@@ -257,9 +143,6 @@ pub(crate) fn changes(cwd: &Path, base: &str) -> IdeResult<Vec<AgentChange>> {
|
||||
/// Files renamed since `rev`, by their new repository-relative path: the old path, as a deletion
|
||||
/// to roll back along with the rename.
|
||||
pub(crate) fn rename_sources(cwd: &Path, rev: &str) -> IdeResult<BTreeMap<String, AgentChange>> {
|
||||
if spans_repos(cwd) {
|
||||
return Ok(BTreeMap::new());
|
||||
}
|
||||
let Some(repo) = discover(cwd)? else { return Ok(BTreeMap::new()) };
|
||||
let root = repo.root().to_path_buf();
|
||||
Ok(repo
|
||||
@@ -274,7 +157,6 @@ pub(crate) fn rename_sources(cwd: &Path, rev: &str) -> IdeResult<BTreeMap<String
|
||||
added: 0,
|
||||
removed: 0,
|
||||
old_path: None,
|
||||
repo: None,
|
||||
};
|
||||
Some((f.path, source))
|
||||
})
|
||||
@@ -283,7 +165,7 @@ pub(crate) fn rename_sources(cwd: &Path, rev: &str) -> IdeResult<BTreeMap<String
|
||||
|
||||
fn added(path: IpcPath, rel_path: String) -> AgentChange {
|
||||
let added = std::fs::read_to_string(&*path).map_or(0, |t| t.lines().count() as u32);
|
||||
AgentChange { path, rel_path, kind: ChangeKind::Added, added, removed: 0, old_path: None, repo: None }
|
||||
AgentChange { path, rel_path, kind: ChangeKind::Added, added, removed: 0, old_path: None }
|
||||
}
|
||||
|
||||
/// The commits from `base` (exclusive) to `head` (inclusive) in `cwd`, newest first, each
|
||||
@@ -319,7 +201,6 @@ pub(crate) fn commits(cwd: &Path, base: &str, head: &str) -> IdeResult<Vec<Agent
|
||||
added,
|
||||
removed,
|
||||
old_path: f.old_path,
|
||||
repo: None,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
@@ -382,30 +263,10 @@ impl TaskBase {
|
||||
}
|
||||
|
||||
/// The files the task changed, less those changed before it started and untouched since.
|
||||
pub(crate) fn changes(
|
||||
&self,
|
||||
before: &BTreeMap<String, Stamp>,
|
||||
touched: Option<&BTreeSet<String>>,
|
||||
) -> IdeResult<Vec<AgentChange>> {
|
||||
if touched.is_some_and(BTreeSet::is_empty) {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
Ok(made_by_task(self.read_changes(before, touched)?, touched))
|
||||
}
|
||||
|
||||
fn read_changes(
|
||||
&self,
|
||||
before: &BTreeMap<String, Stamp>,
|
||||
touched: Option<&BTreeSet<String>>,
|
||||
) -> IdeResult<Vec<AgentChange>> {
|
||||
pub(crate) fn changes(&self, before: &BTreeMap<String, Stamp>) -> IdeResult<Vec<AgentChange>> {
|
||||
let (cwd, start) = match self {
|
||||
Self::Worktree { cwd, base } => return Ok(without_untouched(changes(cwd, base)?, before)),
|
||||
Self::Local { cwd, start } => {
|
||||
if let Some((base, repos)) = nested_repos(cwd)? {
|
||||
return Ok(without_untouched(nested_changes(&base, &repos, touched)?, before));
|
||||
}
|
||||
(cwd, start.as_deref())
|
||||
}
|
||||
Self::Local { cwd, start } => (cwd, start.as_deref()),
|
||||
};
|
||||
let Some(repo) = discover(cwd)? else { return Ok(Vec::new()) };
|
||||
// What is uncommitted, as the Commit tool window lists it: commits made since the task
|
||||
@@ -463,9 +324,6 @@ impl TaskBase {
|
||||
/// reads cannot put a file in both lists.
|
||||
pub(crate) fn grouped_changes(&self, before: &BTreeMap<String, Stamp>) -> IdeResult<AgentChanges> {
|
||||
let cwd = self.cwd();
|
||||
if spans_repos(cwd) {
|
||||
return Ok(AgentChanges { uncommitted: self.changes(before, None)?, commits: Vec::new() });
|
||||
}
|
||||
let Some(repo) = discover(cwd)? else { return Ok(AgentChanges::default()) };
|
||||
let head = repo.head()?.1;
|
||||
let uncommitted = match &head {
|
||||
@@ -495,8 +353,6 @@ impl TaskBase {
|
||||
pub(crate) fn rev(&self) -> IdeResult<Option<String>> {
|
||||
let (cwd, start) = match self {
|
||||
Self::Worktree { base, .. } => return Ok(Some(base.clone())),
|
||||
// Each repository goes back to its own `HEAD`.
|
||||
Self::Local { cwd, .. } if spans_repos(cwd) => return Ok(Some("HEAD".to_owned())),
|
||||
Self::Local { cwd, start } => (cwd, start.as_deref()),
|
||||
};
|
||||
let Some(repo) = discover(cwd)? else { return Ok(None) };
|
||||
@@ -689,32 +545,8 @@ pub(crate) fn stamp(path: &Path) -> Stamp {
|
||||
pub(crate) fn snapshot(cwd: &Path) -> IdeResult<BTreeMap<String, Stamp>> {
|
||||
// Paths and stamps only: no diff and no line counts, which read every untracked file
|
||||
// and held up starting a task in a checkout with many of them.
|
||||
if let Some((base, repos)) = nested_repos(cwd)? {
|
||||
let roots: Vec<PathBuf> = repos.iter().map(|r| r.root().to_path_buf()).collect();
|
||||
let mut out = BTreeMap::new();
|
||||
for repo in &repos {
|
||||
for s in repo.status()? {
|
||||
if let Some(rel) = nested_rel(&base, repo, &roots, &s.path) {
|
||||
out.insert(rel, stamp(&s.path));
|
||||
}
|
||||
if let Some(old) = &s.renamed_from
|
||||
&& let Some(rel) = nested_rel(&base, repo, &roots, &repo.root().join(old))
|
||||
{
|
||||
out.entry(rel).or_insert(None);
|
||||
}
|
||||
}
|
||||
}
|
||||
return Ok(out);
|
||||
}
|
||||
let Some(repo) = Repo::discover(cwd)? else { return Ok(BTreeMap::new()) };
|
||||
let mut out = BTreeMap::new();
|
||||
for s in repo.status()? {
|
||||
out.insert(s.rel_path, stamp(&s.path));
|
||||
if let Some(old) = s.renamed_from {
|
||||
out.entry(old).or_insert(None);
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
Ok(repo.status()?.into_iter().map(|s| (s.rel_path, stamp(&s.path))).collect())
|
||||
}
|
||||
|
||||
/// The files whose state changed between two snapshots of a checkout: edited, new, deleted,
|
||||
@@ -755,16 +587,10 @@ fn saved_name(rel: &str) -> String {
|
||||
/// into `dir`, so rolling back the task's changes to them restores the user's own edits.
|
||||
/// Whether anything was saved.
|
||||
pub(crate) fn save_before(cwd: &Path, before: &BTreeMap<String, Stamp>, dir: &Path) -> IdeResult<bool> {
|
||||
let root = match nested_repos(cwd)? {
|
||||
Some((base, _)) => base,
|
||||
None => match Repo::discover(cwd)? {
|
||||
Some(repo) => repo.root().to_path_buf(),
|
||||
None => return Ok(false),
|
||||
},
|
||||
};
|
||||
let Some(repo) = Repo::discover(cwd)? else { return Ok(false) };
|
||||
let mut saved = false;
|
||||
for (rel, stamp) in before {
|
||||
let path = root.join(rel);
|
||||
let path = repo.root().join(rel);
|
||||
if stamp.is_none() || !std::fs::metadata(&path).is_ok_and(|m| m.is_file() && m.len() <= SAVED_MAX) {
|
||||
continue;
|
||||
}
|
||||
@@ -775,36 +601,6 @@ pub(crate) fn save_before(cwd: &Path, before: &BTreeMap<String, Stamp>, dir: &Pa
|
||||
Ok(saved)
|
||||
}
|
||||
|
||||
fn restore_content(
|
||||
cwd: &Path,
|
||||
rev: Option<&str>,
|
||||
change: &AgentChange,
|
||||
before: &BTreeMap<String, Stamp>,
|
||||
saved: Option<&Path>,
|
||||
) -> IdeResult<Option<Vec<u8>>> {
|
||||
match before.get(&change.rel_path) {
|
||||
Some(None) => Ok(None),
|
||||
Some(Some(_)) => {
|
||||
let copy =
|
||||
saved.map(|d| d.join(saved_name(&change.rel_path))).filter(|p| p.is_file()).ok_or_else(|| {
|
||||
IdeError::invalid(format!(
|
||||
"{} had changes of yours when the task started that weren't saved; roll it back in Git instead",
|
||||
change.rel_path
|
||||
))
|
||||
})?;
|
||||
Ok(Some(std::fs::read(copy)?))
|
||||
}
|
||||
None => match rev {
|
||||
Some(rev) => {
|
||||
let at = change.repo.as_ref().map_or(cwd, |r| r.0.as_path());
|
||||
let repo = Repo::discover(at)?.ok_or_else(|| IdeError::invalid("not in a git repository"))?;
|
||||
repo.file_bytes_at(&change.path.0, Some(rev))
|
||||
}
|
||||
None => Ok(None),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Rolls `change` back: to the copy saved when the task started when the file had changes
|
||||
/// then (`before`, `saved` holding the copies), otherwise to `rev` (removed when `rev` lacks
|
||||
/// it, or when there is no `rev`: the repository had no commits).
|
||||
@@ -815,35 +611,27 @@ pub(crate) fn restore(
|
||||
before: &BTreeMap<String, Stamp>,
|
||||
saved: Option<&Path>,
|
||||
) -> IdeResult<()> {
|
||||
put(&change.path.0, restore_content(cwd, rev, change, before, saved)?)
|
||||
}
|
||||
|
||||
/// The files the task changed since it started, with what to put back. Fails, changing
|
||||
/// nothing, when one can't be put back.
|
||||
pub(crate) fn plan_restore(
|
||||
at: &TaskBase,
|
||||
before: &BTreeMap<String, Stamp>,
|
||||
saved: Option<&Path>,
|
||||
touched: Option<&BTreeSet<String>>,
|
||||
) -> IdeResult<Vec<PutBack>> {
|
||||
let changes = made_by_task(at.changes(before, None)?, touched);
|
||||
let rev = at.rev()?;
|
||||
let sources = match rev.as_deref() {
|
||||
Some(rev) => rename_sources(at.cwd(), rev)?,
|
||||
None => Default::default(),
|
||||
};
|
||||
let mut seen = BTreeSet::new();
|
||||
let mut out = Vec::new();
|
||||
for change in &changes {
|
||||
for change in std::iter::once(change).chain(sources.get(&change.rel_path)) {
|
||||
if !seen.insert(change.rel_path.clone()) {
|
||||
continue;
|
||||
}
|
||||
let content = restore_content(at.cwd(), rev.as_deref(), change, before, saved)?;
|
||||
out.push(PutBack { rel: change.rel_path.clone(), path: change.path.0.clone(), content });
|
||||
let content = match before.get(&change.rel_path) {
|
||||
Some(None) => None,
|
||||
Some(Some(_)) => {
|
||||
let copy =
|
||||
saved.map(|d| d.join(saved_name(&change.rel_path))).filter(|p| p.is_file()).ok_or_else(|| {
|
||||
IdeError::invalid(format!(
|
||||
"{} had changes of yours when the task started that weren't saved; roll it back in Git instead",
|
||||
change.rel_path
|
||||
))
|
||||
})?;
|
||||
Some(std::fs::read(copy)?)
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
None => match rev {
|
||||
Some(rev) => {
|
||||
let repo = Repo::discover(cwd)?.ok_or_else(|| IdeError::invalid("not in a git repository"))?;
|
||||
repo.file_bytes_at(&change.path.0, Some(rev))?
|
||||
}
|
||||
None => None,
|
||||
},
|
||||
};
|
||||
put(&change.path.0, content)
|
||||
}
|
||||
|
||||
/// Writes `content` to `path`, or removes the file when there is none.
|
||||
@@ -868,7 +656,7 @@ pub(crate) fn saved_copy(dir: &Path, rel: &str) -> Option<Vec<u8>> {
|
||||
std::fs::read(dir.join(saved_name(rel))).ok()
|
||||
}
|
||||
|
||||
/// The checkout as one of the task's turns started: what that turn's changes are compared with
|
||||
/// The checkout as the task's last turn started: what that turn's changes are compared with
|
||||
/// and rolled back to. Recorded like the task's own start: `HEAD`, the files already changed,
|
||||
/// and copies of those.
|
||||
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
|
||||
@@ -877,9 +665,6 @@ pub(crate) struct TurnStart {
|
||||
/// `HEAD` then (`None` outside a repository or before its first commit).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub head: Option<String>,
|
||||
/// With nested repositories, each one's `HEAD` then, by its root.
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub heads: BTreeMap<String, String>,
|
||||
/// The files already changed then, stamped.
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub before: BTreeMap<String, Stamp>,
|
||||
@@ -889,146 +674,48 @@ pub(crate) struct TurnStart {
|
||||
/// The files that changed while the turn ran, recorded as it ended (`None` while it runs).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub changed: Option<BTreeSet<String>>,
|
||||
/// The copies are named by file and stamp, so the turns share them; the turn recorded
|
||||
/// before that named them by file alone.
|
||||
#[serde(default, skip_serializing_if = "is_false")]
|
||||
pub stamped: bool,
|
||||
}
|
||||
|
||||
fn is_false(b: &bool) -> bool {
|
||||
!*b
|
||||
}
|
||||
|
||||
/// The name of the copy of `rel` as stamped `stamp`: the same while the file is unchanged.
|
||||
fn turn_copy_name(rel: &str, stamp: &Stamp) -> String {
|
||||
let mut hasher = blake3::Hasher::new();
|
||||
hasher.update(rel.as_bytes());
|
||||
hasher.update(&[0]);
|
||||
if let Some((len, modified)) = stamp {
|
||||
hasher.update(&[1]);
|
||||
hasher.update(&len.to_le_bytes());
|
||||
hasher.update(&modified.to_le_bytes());
|
||||
}
|
||||
let hex = hasher.finalize().to_hex();
|
||||
format!("t{}", &hex[..16])
|
||||
}
|
||||
|
||||
impl TurnStart {
|
||||
/// The name of the copy saved of `rel` as the turn began.
|
||||
fn copy_name(&self, rel: &str) -> Option<String> {
|
||||
if !self.stamped {
|
||||
return Some(saved_name(rel));
|
||||
}
|
||||
Some(turn_copy_name(rel, self.before.get(rel)?))
|
||||
}
|
||||
}
|
||||
|
||||
/// Records the checkout at `cwd` as a turn starts, with copies of its changed files in `dir`.
|
||||
/// A copy an earlier turn saved of a file unchanged since is used rather than made again, so
|
||||
/// The copies `previous` saved of files unchanged since are kept rather than made again, so
|
||||
/// starting a turn copies little more than what the turn before it changed.
|
||||
pub(crate) fn start_turn(cwd: &Path, dir: &Path) -> IdeResult<TurnStart> {
|
||||
let Some(at) = TurnRepos::of(cwd)? else { return Ok(TurnStart { stamped: true, ..Default::default() }) };
|
||||
let mut heads = BTreeMap::new();
|
||||
let head = if at.nested {
|
||||
for repo in &at.repos {
|
||||
heads.extend(repo.head()?.1.map(|h| (root_key(repo.root()), h)));
|
||||
}
|
||||
None
|
||||
} else {
|
||||
at.repos[0].head()?.1
|
||||
};
|
||||
pub(crate) fn start_turn(cwd: &Path, dir: &Path, previous: Option<&TurnStart>) -> IdeResult<TurnStart> {
|
||||
let Some(repo) = discover(cwd)? else { return Ok(TurnStart::default()) };
|
||||
let head = repo.head()?.1;
|
||||
// As the turn's end is read, so the two compare.
|
||||
let before = snapshot(cwd)?;
|
||||
let mut saved = BTreeSet::new();
|
||||
for (rel, stamp) in &before {
|
||||
let path = at.base.join(rel);
|
||||
if stamp.is_none() || !std::fs::metadata(&path).is_ok_and(|m| m.is_file() && m.len() <= SAVED_MAX) {
|
||||
continue;
|
||||
match previous {
|
||||
Some(previous) => {
|
||||
for rel in &previous.saved {
|
||||
let unchanged =
|
||||
before.get(rel).is_some_and(|now| now.is_some() && previous.before.get(rel) == Some(now));
|
||||
if unchanged {
|
||||
saved.insert(rel.clone());
|
||||
} else {
|
||||
let _ = std::fs::remove_file(dir.join(saved_name(rel)));
|
||||
}
|
||||
}
|
||||
}
|
||||
let copy = dir.join(turn_copy_name(rel, stamp));
|
||||
if copy.is_file() {
|
||||
saved.insert(rel.clone());
|
||||
None => {
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
}
|
||||
for (rel, stamp) in &before {
|
||||
let path = repo.root().join(rel);
|
||||
if stamp.is_none()
|
||||
|| saved.contains(rel)
|
||||
|| !std::fs::metadata(&path).is_ok_and(|m| m.is_file() && m.len() <= SAVED_MAX)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
std::fs::create_dir_all(dir)?;
|
||||
// One that can't be copied is listed but can't be rolled back, as a large one.
|
||||
if std::fs::copy(&path, ©).is_ok() {
|
||||
if std::fs::copy(&path, dir.join(saved_name(rel))).is_ok() {
|
||||
saved.insert(rel.clone());
|
||||
}
|
||||
}
|
||||
Ok(TurnStart { head, heads, before, saved, changed: None, stamped: true })
|
||||
}
|
||||
|
||||
/// Removes the copies in `dir` that none of `turns` uses any more.
|
||||
pub(crate) fn prune_turn_copies<'a>(dir: &Path, turns: impl IntoIterator<Item = &'a TurnStart>) {
|
||||
let used: BTreeSet<String> =
|
||||
turns.into_iter().flat_map(|t| t.saved.iter().filter_map(move |rel| t.copy_name(rel))).collect();
|
||||
let Ok(read) = std::fs::read_dir(dir) else { return };
|
||||
for entry in read.flatten() {
|
||||
if !used.contains(&*entry.file_name().to_string_lossy()) {
|
||||
let _ = std::fs::remove_file(entry.path());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A file to put back as it was.
|
||||
pub(crate) struct PutBack {
|
||||
/// Relative to the checkout, as the task names it.
|
||||
pub rel: String,
|
||||
pub path: PathBuf,
|
||||
/// `None`: there was no file.
|
||||
pub content: Option<Vec<u8>>,
|
||||
}
|
||||
|
||||
/// The files among `rels` that differ from how they were as the turn `start` began, with what
|
||||
/// to put back. Fails, changing nothing, when one can't be put back.
|
||||
pub(crate) fn rewind(cwd: &Path, start: &TurnStart, dir: &Path, rels: &BTreeSet<String>) -> IdeResult<Vec<PutBack>> {
|
||||
let Some(at) = TurnRepos::of(cwd)? else { return Ok(Vec::new()) };
|
||||
let mut lower_counts: BTreeMap<String, usize> = BTreeMap::new();
|
||||
for rel in rels {
|
||||
*lower_counts.entry(rel.to_lowercase()).or_default() += 1;
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
for rel in rels {
|
||||
let path = at.base.join(rel);
|
||||
// A folder (a submodule, say) has nothing to put back.
|
||||
if path.is_dir() {
|
||||
continue;
|
||||
}
|
||||
let then = at_turn_start(&at, rel, start, dir)?;
|
||||
// On a case-insensitive disk, `existing(&path)` can read a case-only rename's new name;
|
||||
// keep the write so `put_back` deletes the new name and recreates the old one.
|
||||
let case_collision = lower_counts.get(&rel.to_lowercase()).is_some_and(|&n| n > 1);
|
||||
if !case_collision && existing(&path).is_some_and(|now| now == then) {
|
||||
continue;
|
||||
}
|
||||
out.push(PutBack { rel: rel.clone(), path, content: then });
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Writes what `rewind` or `plan_restore` planned, returning the files back to their saved
|
||||
/// pre-task copy so `before` can be restamped.
|
||||
pub(crate) fn put_back(
|
||||
mut planned: Vec<PutBack>,
|
||||
before: &BTreeMap<String, Stamp>,
|
||||
saved: Option<&Path>,
|
||||
) -> IdeResult<Vec<(String, Stamp)>> {
|
||||
// Removals first so a case-only rename on a case-insensitive disk ends at its old name.
|
||||
planned.sort_by_key(|f| f.content.is_some());
|
||||
let mut restamped = Vec::new();
|
||||
for file in planned {
|
||||
let should_restamp = matches!(before.get(&file.rel), Some(Some(_)))
|
||||
&& file
|
||||
.content
|
||||
.as_deref()
|
||||
.is_some_and(|bytes| saved.and_then(|d| saved_copy(d, &file.rel)).as_deref() == Some(bytes));
|
||||
put(&file.path, file.content)?;
|
||||
if should_restamp {
|
||||
restamped.push((file.rel, stamp(&file.path)));
|
||||
}
|
||||
}
|
||||
Ok(restamped)
|
||||
Ok(TurnStart { head, before, saved, changed: None })
|
||||
}
|
||||
|
||||
/// The files that changed in `cwd` since the turn `start` began: in the working tree (as
|
||||
@@ -1037,45 +724,32 @@ pub(crate) fn changed_in_turn(cwd: &Path, start: &TurnStart) -> IdeResult<(Vec<S
|
||||
let end = snapshot(cwd)?;
|
||||
let worktree = changed_between(&start.before, &end);
|
||||
let mut all: BTreeSet<String> = worktree.iter().cloned().collect();
|
||||
let Some(at) = TurnRepos::of(cwd)? else { return Ok((worktree, all)) };
|
||||
for repo in &at.repos {
|
||||
let (Some(from), Some(to)) = (at.head_then(start, repo), repo.head()?.1) else { continue };
|
||||
if from == to {
|
||||
continue;
|
||||
}
|
||||
// Named from the base, as the working tree's files are.
|
||||
let prefix = rel_in(&at.base, repo.root())?;
|
||||
let named = |rel: String| if prefix.is_empty() { rel } else { format!("{prefix}/{rel}") };
|
||||
if let Some(repo) = discover(cwd)?
|
||||
&& let (Some(from), Some(to)) = (&start.head, repo.head()?.1)
|
||||
&& *from != to
|
||||
{
|
||||
for f in repo.diff_revisions(from, &to)? {
|
||||
all.extend(f.old_path.map(named));
|
||||
all.insert(named(f.path));
|
||||
all.extend(f.old_path);
|
||||
all.insert(f.path);
|
||||
}
|
||||
}
|
||||
Ok((worktree, all))
|
||||
}
|
||||
|
||||
/// The content of `rel` as the turn `start` began (`None`: no file), its copies in `dir`.
|
||||
fn at_turn_start(at: &TurnRepos, rel: &str, start: &TurnStart, dir: &Path) -> IdeResult<Option<Vec<u8>>> {
|
||||
fn at_turn_start(repo: &Repo, rel: &str, start: &TurnStart, dir: &Path) -> IdeResult<Option<Vec<u8>>> {
|
||||
match start.before.get(rel) {
|
||||
Some(None) => Ok(None),
|
||||
Some(Some(_)) => match start
|
||||
.saved
|
||||
.contains(rel)
|
||||
.then(|| start.copy_name(rel).and_then(|name| std::fs::read(dir.join(name)).ok()))
|
||||
.flatten()
|
||||
{
|
||||
Some(Some(_)) => match start.saved.contains(rel).then(|| saved_copy(dir, rel)).flatten() {
|
||||
Some(bytes) => Ok(Some(bytes)),
|
||||
None => Err(IdeError::invalid(format!(
|
||||
"{rel} had changes when the turn started that weren't saved; roll it back in Git instead"
|
||||
))),
|
||||
},
|
||||
None => {
|
||||
let path = at.base.join(rel);
|
||||
match at.owner(&path).and_then(|repo| Some((repo, at.head_then(start, repo)?))) {
|
||||
Some((repo, head)) => repo.file_bytes_at(&path, Some(head)),
|
||||
None => Ok(None),
|
||||
}
|
||||
}
|
||||
None => match &start.head {
|
||||
Some(head) => repo.file_bytes_at(&repo.root().join(rel), Some(head)),
|
||||
None => Ok(None),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1097,13 +771,13 @@ pub(crate) fn turn_changes(
|
||||
dir: &Path,
|
||||
changed: &BTreeSet<String>,
|
||||
) -> IdeResult<Vec<AgentChange>> {
|
||||
let Some(at) = TurnRepos::of(cwd)? else { return Ok(Vec::new()) };
|
||||
let Some(repo) = discover(cwd)? else { return Ok(Vec::new()) };
|
||||
let mut out = Vec::new();
|
||||
for rel in changed {
|
||||
let path = at.base.join(rel);
|
||||
let path = repo.root().join(rel);
|
||||
// A folder (a submodule, say) or a file that can't be read has nothing to compare.
|
||||
let Some(now) = existing(&path) else { continue };
|
||||
let (kind, (added, removed)) = match at_turn_start(&at, rel, start, dir) {
|
||||
let (kind, (added, removed)) = match at_turn_start(&repo, rel, start, dir) {
|
||||
Ok(then) if then == now => continue,
|
||||
Ok(then) => {
|
||||
let kind = match (&then, &now) {
|
||||
@@ -1116,29 +790,19 @@ pub(crate) fn turn_changes(
|
||||
// Its start wasn't saved: listed, without counts.
|
||||
Err(_) => (ChangeKind::Modified, (0, 0)),
|
||||
};
|
||||
out.push(AgentChange {
|
||||
rel_path: rel.clone(),
|
||||
kind,
|
||||
added,
|
||||
removed,
|
||||
old_path: None,
|
||||
repo: at.nested.then(|| at.owner(&path).map(|r| IpcPath(r.root().to_path_buf()))).flatten(),
|
||||
path: IpcPath(path),
|
||||
});
|
||||
out.push(AgentChange { path: IpcPath(path), rel_path: rel.clone(), kind, added, removed, old_path: None });
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The text of `path` as the turn `start` began, `None` when there was no file.
|
||||
pub(crate) fn turn_text(cwd: &Path, path: &Path, start: &TurnStart, dir: &Path) -> IdeResult<Option<String>> {
|
||||
let Some(at) = TurnRepos::of(cwd)? else { return Ok(None) };
|
||||
let rel = rel_in(&at.base, path)?;
|
||||
if !start.before.contains_key(&rel)
|
||||
&& let Some(head) = at.owner(&at.base.join(&rel)).and_then(|repo| at.head_then(start, repo))
|
||||
{
|
||||
let Some(repo) = discover(cwd)? else { return Ok(None) };
|
||||
let rel = rel_in(repo.root(), path)?;
|
||||
if let (None, Some(head)) = (start.before.get(&rel), &start.head) {
|
||||
return file_at(cwd, path, head);
|
||||
}
|
||||
let Some(bytes) = at_turn_start(&at, &rel, start, dir)? else { return Ok(None) };
|
||||
let Some(bytes) = at_turn_start(&repo, &rel, start, dir)? else { return Ok(None) };
|
||||
let encoding = match ide_vfs::load_text(path) {
|
||||
Ok(loaded) => encoding_rs::Encoding::for_label(loaded.encoding.as_bytes()).unwrap_or(encoding_rs::UTF_8),
|
||||
Err(_) => ide_vfs::detect_encoding(&bytes, None),
|
||||
@@ -1164,15 +828,12 @@ fn rel_in(root: &Path, path: &Path) -> IdeResult<String> {
|
||||
|
||||
/// Puts `change` back as it was when the turn `start` began.
|
||||
pub(crate) fn restore_turn(cwd: &Path, start: &TurnStart, dir: &Path, change: &AgentChange) -> IdeResult<()> {
|
||||
let at = TurnRepos::of(cwd)?
|
||||
.ok_or_else(|| IdeError::unavailable(format!("{} is not in a git repository", cwd.display())))?;
|
||||
put(&change.path.0, at_turn_start(&at, &change.rel_path, start, dir)?)
|
||||
let repo = repo_at(cwd)?;
|
||||
put(&change.path.0, at_turn_start(&repo, &change.rel_path, start, dir)?)
|
||||
}
|
||||
|
||||
pub(crate) fn file_at(cwd: &Path, path: &Path, rev: &str) -> IdeResult<Option<String>> {
|
||||
// With nested repositories, the file's own one.
|
||||
let at = if spans_repos(cwd) { path.parent().unwrap_or(cwd) } else { cwd };
|
||||
let Some(repo) = discover(at)? else { return Ok(None) };
|
||||
let Some(repo) = discover(cwd)? else { return Ok(None) };
|
||||
let encoding = match ide_vfs::load_text(path) {
|
||||
Ok(loaded) => encoding_rs::Encoding::for_label(loaded.encoding.as_bytes()).unwrap_or(encoding_rs::UTF_8),
|
||||
Err(_) => ide_vfs::detect_encoding(&repo.file_bytes_at(path, Some(rev))?.unwrap_or_default(), None),
|
||||
@@ -1301,111 +962,6 @@ mod tests {
|
||||
assert!(ok, "git {args:?}");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn attributed_changes_only_diff_the_owning_checkout() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap().join("project");
|
||||
for n in 0..15 {
|
||||
let repo = root.join(format!("repo{n:02}"));
|
||||
std::fs::create_dir_all(&repo).unwrap();
|
||||
git(&repo, &["init", "-q", "-b", "main"]);
|
||||
std::fs::write(repo.join("a.txt"), "one\n").unwrap();
|
||||
git(&repo, &["add", "a.txt"]);
|
||||
git(&repo, &["commit", "-q", "-m", "initial"]);
|
||||
std::fs::write(repo.join("a.txt"), "two\n").unwrap();
|
||||
}
|
||||
// Count real Git diff processes, not walks to discover the topology.
|
||||
let git = tmp.path().join("count-git");
|
||||
let log = tmp.path().join("count-git.log");
|
||||
std::fs::write(
|
||||
&git,
|
||||
"#!/bin/sh\nfor arg do\nif [ \"$arg\" = diff ]; then pwd >> \"$0.log\"; break; fi\ndone\nexec git \"$@\"\n",
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::set_permissions(&git, std::fs::Permissions::from_mode(0o700)).unwrap();
|
||||
let at = TaskBase::Local { cwd: root, start: None };
|
||||
let before = BTreeMap::new();
|
||||
let one = BTreeSet::from(["repo07/a.txt".to_owned()]);
|
||||
let read = |touched: Option<&BTreeSet<String>>| {
|
||||
std::fs::write(&log, "").unwrap();
|
||||
let start = std::time::Instant::now();
|
||||
let changes = ide_vcs::with_git_executable(Some(&git), || at.changes(&before, touched).unwrap());
|
||||
let elapsed = start.elapsed();
|
||||
let calls = std::fs::read_to_string(&log).unwrap();
|
||||
eprintln!("change read: touched={:?} elapsed={elapsed:?}", touched.map(BTreeSet::len));
|
||||
(changes, calls.lines().count())
|
||||
};
|
||||
let (all, full_calls) = read(None);
|
||||
let (selected, selected_calls) = read(Some(&one));
|
||||
let (empty, empty_calls) = read(Some(&BTreeSet::new()));
|
||||
assert_eq!(all.len(), 15);
|
||||
assert_eq!(
|
||||
serde_json::to_value(selected).unwrap(),
|
||||
serde_json::to_value(made_by_task(all, Some(&one))).unwrap()
|
||||
);
|
||||
assert!(empty.is_empty());
|
||||
eprintln!("git diff children: full {full_calls}, one touched {selected_calls}, none touched {empty_calls}");
|
||||
assert!(selected_calls > 0);
|
||||
assert_eq!(selected_calls * 15, full_calls);
|
||||
assert_eq!(empty_calls, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_project_with_nested_repositories_sees_changes_in_each_one() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let (nested, deeper) = (root.join("libs/validation"), root.join("libs/validation/pkg/sdk"));
|
||||
for repo in [&root, &nested, &deeper] {
|
||||
std::fs::create_dir_all(repo).unwrap();
|
||||
git(repo, &["init", "-q", "-b", "main"]);
|
||||
std::fs::write(repo.join("a.txt"), "one\n").unwrap();
|
||||
git(repo, &["add", "a.txt"]);
|
||||
git(repo, &["commit", "-q", "-m", "init"]);
|
||||
}
|
||||
assert!(spans_repos(&root));
|
||||
std::fs::write(root.join("mine.txt"), "the user's\n").unwrap();
|
||||
let before = snapshot(&root).unwrap();
|
||||
assert_eq!(before.keys().collect::<Vec<_>>(), ["mine.txt"]);
|
||||
|
||||
std::fs::write(root.join("a.txt"), "two\n").unwrap();
|
||||
std::fs::write(nested.join("a.txt"), "two\n").unwrap();
|
||||
std::fs::write(nested.join("b.txt"), "new\n").unwrap();
|
||||
std::fs::write(deeper.join("a.txt"), "two\n").unwrap();
|
||||
let at = TaskBase::Local { cwd: root.clone(), start: None };
|
||||
let changed = at.changes(&before, None).unwrap();
|
||||
let listed: Vec<(&str, &Path)> =
|
||||
changed.iter().map(|c| (c.rel_path.as_str(), c.repo.as_ref().unwrap().0.as_path())).collect();
|
||||
assert_eq!(
|
||||
listed,
|
||||
[
|
||||
("a.txt", root.as_path()),
|
||||
("libs/validation/a.txt", nested.as_path()),
|
||||
("libs/validation/b.txt", nested.as_path()),
|
||||
("libs/validation/pkg/sdk/a.txt", deeper.as_path()),
|
||||
]
|
||||
);
|
||||
assert_eq!(at.grouped_changes(&before).unwrap().uncommitted.len(), 4);
|
||||
assert_eq!(file_at(&root, &nested.join("a.txt"), "HEAD").unwrap().as_deref(), Some("one\n"));
|
||||
|
||||
let rev = at.rev().unwrap();
|
||||
for change in &changed {
|
||||
restore(&root, rev.as_deref(), change, &before, None).unwrap();
|
||||
}
|
||||
for repo in [&root, &nested, &deeper] {
|
||||
assert_eq!(std::fs::read_to_string(repo.join("a.txt")).unwrap(), "one\n");
|
||||
}
|
||||
assert!(!nested.join("b.txt").exists());
|
||||
assert!(root.join("mine.txt").exists(), "the user's own change stays");
|
||||
// A deleted file cannot be canonicalized, but still belongs to its innermost repo.
|
||||
std::fs::remove_file(deeper.join("a.txt")).unwrap();
|
||||
let removed = at.changes(&before, Some(&BTreeSet::from(["libs/validation/pkg/sdk/a.txt".into()]))).unwrap();
|
||||
assert_eq!(removed.len(), 1);
|
||||
assert_eq!(removed[0].repo.as_ref().unwrap().0, deeper);
|
||||
assert_eq!(removed[0].kind, ChangeKind::Deleted);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn worktree_changes_are_listed_against_the_base() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
@@ -1456,64 +1012,30 @@ mod tests {
|
||||
git(&repo, &["commit", "-q", "-m", "init"]);
|
||||
let dir = tmp.path().join("turn");
|
||||
let set = |names: &[&str]| names.iter().map(|n| (*n).to_owned()).collect::<BTreeSet<_>>();
|
||||
let copy = |turn: &TurnStart, rel: &str| std::fs::read(dir.join(turn.copy_name(rel).unwrap())).ok();
|
||||
let at = |turn: &TurnStart, rel: &str| {
|
||||
at_turn_start(&TurnRepos::of(&repo).unwrap().unwrap(), rel, turn, &dir).unwrap()
|
||||
};
|
||||
|
||||
std::fs::write(repo.join("a.txt"), "turn 1\n").unwrap();
|
||||
std::fs::write(repo.join("b.txt"), "b\n").unwrap();
|
||||
let first = start_turn(&repo, &dir).unwrap();
|
||||
let first = start_turn(&repo, &dir, None).unwrap();
|
||||
assert_eq!(first.saved, set(&["a.txt", "b.txt"]));
|
||||
// A copy made again would replace this mark.
|
||||
std::fs::write(dir.join(first.copy_name("b.txt").unwrap()), "kept\n").unwrap();
|
||||
std::fs::write(dir.join(saved_name("b.txt")), "kept\n").unwrap();
|
||||
|
||||
std::thread::sleep(std::time::Duration::from_millis(10));
|
||||
std::fs::write(repo.join("a.txt"), "turn two\n").unwrap();
|
||||
let second = start_turn(&repo, &dir).unwrap();
|
||||
let second = start_turn(&repo, &dir, Some(&first)).unwrap();
|
||||
assert_eq!(second.saved, set(&["a.txt", "b.txt"]));
|
||||
assert_eq!(copy(&second, "a.txt").as_deref(), Some(&b"turn two\n"[..]));
|
||||
assert_eq!(copy(&second, "b.txt").as_deref(), Some(&b"kept\n"[..]));
|
||||
// The first turn keeps its own copy of the file changed since.
|
||||
assert_eq!(at(&first, "a.txt").as_deref(), Some(&b"turn 1\n"[..]));
|
||||
assert_eq!(saved_copy(&dir, "a.txt").as_deref(), Some(&b"turn two\n"[..]));
|
||||
assert_eq!(saved_copy(&dir, "b.txt").as_deref(), Some(&b"kept\n"[..]));
|
||||
|
||||
// Back as committed: nothing to keep a copy of, and the committed text is the start.
|
||||
// Back as committed: nothing to keep a copy of.
|
||||
git(&repo, &["checkout", "--", "a.txt"]);
|
||||
let third = start_turn(&repo, &dir).unwrap();
|
||||
let third = start_turn(&repo, &dir, Some(&second)).unwrap();
|
||||
assert_eq!(third.saved, set(&["b.txt"]));
|
||||
assert_eq!(at(&third, "a.txt").as_deref(), Some(&b"base\n"[..]));
|
||||
|
||||
// Dropping the earlier turns drops the copies only they used.
|
||||
prune_turn_copies(&dir, [&third]);
|
||||
assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 1);
|
||||
assert_eq!(copy(&third, "b.txt").as_deref(), Some(&b"kept\n"[..]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn put_back_removes_new_name_before_writing_old_name_for_case_only_rename() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let repo = tmp.path().join("repo");
|
||||
std::fs::create_dir(&repo).unwrap();
|
||||
git(&repo, &["init", "-q", "-b", "main"]);
|
||||
std::fs::write(repo.join("A.txt"), "upper\n").unwrap();
|
||||
git(&repo, &["add", "."]);
|
||||
git(&repo, &["commit", "-q", "-m", "init"]);
|
||||
|
||||
let dir = tmp.path().join("turn");
|
||||
let start = start_turn(&repo, &dir).unwrap();
|
||||
git(&repo, &["mv", "A.txt", "a.txt"]);
|
||||
let changed = changed_in_turn(&repo, &start).unwrap().1;
|
||||
let planned = rewind(&repo, &start, &dir, &changed).unwrap();
|
||||
put_back(planned, &BTreeMap::new(), None).unwrap();
|
||||
|
||||
assert_eq!(std::fs::read_to_string(repo.join("A.txt")).unwrap(), "upper\n");
|
||||
let entries: Vec<String> = std::fs::read_dir(&repo)
|
||||
.unwrap()
|
||||
.filter_map(|e| e.ok())
|
||||
.map(|e| e.file_name().to_string_lossy().into_owned())
|
||||
.filter(|n| n != ".git")
|
||||
.collect();
|
||||
assert_eq!(entries, ["A.txt"]);
|
||||
assert_eq!(saved_copy(&dir, "a.txt"), None);
|
||||
// Without a record of the last turn (a task from before), every copy is made afresh.
|
||||
let fresh = start_turn(&repo, &dir, None).unwrap();
|
||||
assert_eq!(fresh.saved, set(&["b.txt"]));
|
||||
assert_eq!(saved_copy(&dir, "b.txt").as_deref(), Some(&b"b\n"[..]));
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
@@ -1528,7 +1050,7 @@ mod tests {
|
||||
git(&repo, &["commit", "-q", "-m", "init"]);
|
||||
std::fs::write(repo.join("a.txt"), "turn 1\n").unwrap();
|
||||
let dir = tmp.path().join("turn");
|
||||
let start = start_turn(&repo, &dir).unwrap();
|
||||
let start = start_turn(&repo, &dir, None).unwrap();
|
||||
std::fs::write(repo.join("a.txt"), "turn 2\n").unwrap();
|
||||
std::fs::write(repo.join("new.txt"), "new\n").unwrap();
|
||||
let link = tmp.path().join("link");
|
||||
|
||||
@@ -10,6 +10,8 @@ ide-core.workspace = true
|
||||
ide-language.workspace = true
|
||||
serde.workspace = true
|
||||
specta.workspace = true
|
||||
tree-sitter.workspace = true
|
||||
rayon.workspace = true
|
||||
tracing.workspace = true
|
||||
# Pinned: 0.40.2+ moves to tree-sitter 0.26, the workspace is on 0.25.
|
||||
ast-grep-core = "=0.40.1"
|
||||
@@ -12,12 +12,11 @@ mod process;
|
||||
|
||||
pub use model::*;
|
||||
|
||||
use ide_core::process::{own_group, prepare};
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Stdio};
|
||||
use std::process::Command;
|
||||
use std::sync::OnceLock;
|
||||
use std::time::{Duration, Instant};
|
||||
use std::time::Duration;
|
||||
|
||||
/// `adb devices` is quick unless it starts the daemon, which can take a moment.
|
||||
const DEVICES: Duration = Duration::from_secs(20);
|
||||
@@ -29,8 +28,6 @@ const TAIL_LINES: u32 = 200;
|
||||
/// while `IDLE` makes sure a quiet stream still shows its last line promptly.
|
||||
const BATCH_IDLE: Duration = Duration::from_millis(60);
|
||||
const BATCH_MAX: usize = 300;
|
||||
/// How long a started emulator gets to fail: a locked or broken AVD exits within it.
|
||||
const EMULATOR_STARTUP: Duration = Duration::from_secs(3);
|
||||
|
||||
fn exe(name: &str) -> String {
|
||||
if cfg!(windows) { format!("{name}.exe") } else { name.to_owned() }
|
||||
@@ -94,49 +91,10 @@ fn executable() -> IdeResult<PathBuf> {
|
||||
})
|
||||
}
|
||||
|
||||
/// The SDK's `emulator` executable, which starts AVDs.
|
||||
pub fn emulator_executable() -> Option<PathBuf> {
|
||||
let name = exe("emulator");
|
||||
sdk_roots().into_iter().map(|root| root.join("emulator").join(&name)).find(|p| p.is_file())
|
||||
}
|
||||
|
||||
/// Starts AVD `avd` in its own process group, so it
|
||||
/// outlives whoever asked: a restarted `flutter daemon`, a closed project, the IDE. Fails when
|
||||
/// the emulator exits within its first seconds, with what it printed.
|
||||
pub fn launch_emulator(avd: &str) -> IdeResult<()> {
|
||||
let emulator = emulator_executable().ok_or_else(|| {
|
||||
IdeError::unavailable(
|
||||
"the Android emulator was not found: install it with the Android SDK Manager, or set ANDROID_HOME",
|
||||
)
|
||||
})?;
|
||||
start_emulator(&emulator, avd)
|
||||
}
|
||||
|
||||
fn start_emulator(emulator: &Path, avd: &str) -> IdeResult<()> {
|
||||
let name: String = avd.chars().map(|c| if c.is_ascii_alphanumeric() { c } else { '_' }).collect();
|
||||
let log_path = std::env::temp_dir().join(format!("openidea-emulator-{name}.log"));
|
||||
let log = std::fs::File::create(&log_path)?;
|
||||
let mut cmd = Command::new(emulator);
|
||||
cmd.arg("-avd").arg(avd);
|
||||
cmd.stdin(Stdio::null()).stdout(log.try_clone()?).stderr(log);
|
||||
let mut child = prepare(own_group(&mut cmd)).spawn()?;
|
||||
let deadline = Instant::now() + EMULATOR_STARTUP;
|
||||
while Instant::now() < deadline {
|
||||
if let Some(status) = child.try_wait()? {
|
||||
let output = std::fs::read_to_string(&log_path).unwrap_or_default();
|
||||
let tail: Vec<&str> = output.lines().filter(|l| !l.trim().is_empty()).collect();
|
||||
let tail = tail[tail.len().saturating_sub(8)..].join("\n");
|
||||
return Err(IdeError::unavailable(if tail.is_empty() {
|
||||
format!("the emulator exited ({status})")
|
||||
} else {
|
||||
tail
|
||||
}));
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(100));
|
||||
}
|
||||
// Reaps it whenever it ends.
|
||||
std::thread::spawn(move || child.wait());
|
||||
Ok(())
|
||||
/// The directory holding adb, for command lines that expect `adb` on `PATH`.
|
||||
pub fn platform_tools_dir() -> Option<&'static Path> {
|
||||
static DIR: OnceLock<Option<PathBuf>> = OnceLock::new();
|
||||
DIR.get_or_init(|| adb_executable().as_deref().and_then(Path::parent).map(Path::to_path_buf)).as_deref()
|
||||
}
|
||||
|
||||
/// Connected devices, online ones first; starting the adb daemon when needed.
|
||||
@@ -254,30 +212,6 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn an_emulator_that_fails_at_once_says_why_and_one_that_runs_is_left_running() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let script = |name: &str, body: &str| {
|
||||
let path = dir.path().join(name);
|
||||
std::fs::write(&path, format!("#!/bin/sh\n{body}")).unwrap();
|
||||
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
path
|
||||
};
|
||||
let broken = script("broken", "echo \"PANIC: Missing emulator engine for $2\" >&2\nexit 1\n");
|
||||
let e = start_emulator(&broken, "Pixel_9").unwrap_err();
|
||||
assert_eq!(e.message, "PANIC: Missing emulator engine for Pixel_9");
|
||||
|
||||
let args = dir.path().join("args");
|
||||
let running =
|
||||
script("running", &format!("echo $$ > '{0}.pid'\necho \"$@\" > '{0}'\nexec sleep 30\n", args.display()));
|
||||
start_emulator(&running, "Pixel_9").unwrap();
|
||||
assert_eq!(std::fs::read_to_string(&args).unwrap().trim(), "-avd Pixel_9");
|
||||
let pid = std::fs::read_to_string(dir.path().join("args.pid")).unwrap();
|
||||
assert!(Command::new("kill").arg(pid.trim()).status().unwrap().success(), "still running");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn executable_is_absolute_when_found() {
|
||||
if let Some(adb) = adb_executable() {
|
||||
|
||||
+134
-216
@@ -1,18 +1,101 @@
|
||||
//! The `adb` CLI as a child process: bounded runs, and cancellable line streams
|
||||
//! Child processes of the `adb` CLI: bounded runs, and cancellable line streams
|
||||
//! that are handed over in batches (logcat is far too chatty for one message a line).
|
||||
|
||||
pub(crate) use ide_core::cli_process::Output;
|
||||
use ide_core::cli_process::{CarriageReturn, CliTool, Decoding, Poll, Stream, keep_stderr_line};
|
||||
use ide_core::{CancellationToken, IdeResult};
|
||||
use std::process::Command;
|
||||
use ide_core::process::terminate_tree;
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult};
|
||||
use std::io::Read;
|
||||
use std::process::{Child, Command, Stdio};
|
||||
use std::sync::mpsc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
const ADB: CliTool = CliTool::new("adb", Decoding::ToolOutput);
|
||||
/// How long a cancelled child gets to exit on `SIGTERM` (and flush) before `SIGKILL`.
|
||||
const KILL_GRACE: Duration = Duration::from_millis(20);
|
||||
|
||||
pub(crate) struct Output {
|
||||
pub stdout: String,
|
||||
pub stderr: String,
|
||||
pub success: bool,
|
||||
}
|
||||
|
||||
fn prepare(cmd: &mut Command) {
|
||||
cmd.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped());
|
||||
ide_core::process::prepare(ide_core::process::own_group(cmd));
|
||||
}
|
||||
|
||||
fn spawn(cmd: &mut Command) -> IdeResult<Child> {
|
||||
cmd.spawn().map_err(|e| IdeError::unavailable(format!("could not run adb: {e}")))
|
||||
}
|
||||
|
||||
fn read_all(mut pipe: impl Read + Send + 'static) -> std::thread::JoinHandle<String> {
|
||||
std::thread::spawn(move || {
|
||||
let mut buf = Vec::new();
|
||||
let _ = pipe.read_to_end(&mut buf);
|
||||
ide_core::output_encoding::decode_tool_output(&buf)
|
||||
})
|
||||
}
|
||||
|
||||
/// Runs `cmd` to completion. Fails when it outlives `timeout` or `cancel` fires;
|
||||
/// a non-zero exit is reported in [`Output::success`], not as an error.
|
||||
pub(crate) fn run(cmd: Command, timeout: Duration, cancel: Option<&CancellationToken>) -> IdeResult<Output> {
|
||||
ADB.run(cmd, timeout, cancel)
|
||||
pub(crate) fn run(mut cmd: Command, timeout: Duration, cancel: Option<&CancellationToken>) -> IdeResult<Output> {
|
||||
prepare(&mut cmd);
|
||||
let mut child = spawn(&mut cmd)?;
|
||||
let out = child.stdout.take().map(read_all);
|
||||
let err = child.stderr.take().map(read_all);
|
||||
let deadline = Instant::now() + timeout;
|
||||
let status = loop {
|
||||
if let Some(status) = child.try_wait()? {
|
||||
break status;
|
||||
}
|
||||
if cancel.is_some_and(CancellationToken::is_cancelled) {
|
||||
terminate_tree(&mut child, KILL_GRACE);
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
if Instant::now() >= deadline {
|
||||
terminate_tree(&mut child, KILL_GRACE);
|
||||
return Err(IdeError::unavailable("adb did not respond in time"));
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
};
|
||||
Ok(Output {
|
||||
stdout: out.map(|t| t.join().unwrap_or_default()).unwrap_or_default(),
|
||||
stderr: err.map(|t| t.join().unwrap_or_default()).unwrap_or_default(),
|
||||
success: status.success(),
|
||||
})
|
||||
}
|
||||
|
||||
enum Event {
|
||||
Line(bool, String),
|
||||
Closed,
|
||||
}
|
||||
|
||||
fn spawn_reader(mut pipe: impl Read + Send + 'static, tx: mpsc::Sender<Event>, stdout: bool) {
|
||||
std::thread::spawn(move || {
|
||||
let mut buf = [0u8; 8192];
|
||||
let mut pending: Vec<u8> = Vec::new();
|
||||
let flush = |pending: &mut Vec<u8>| {
|
||||
if !pending.is_empty() {
|
||||
let line = ide_core::output_encoding::decode_tool_output(pending);
|
||||
pending.clear();
|
||||
let _ = tx.send(Event::Line(stdout, line.trim_end().to_string()));
|
||||
}
|
||||
};
|
||||
loop {
|
||||
match pipe.read(&mut buf) {
|
||||
Ok(0) | Err(_) => break,
|
||||
Ok(n) => {
|
||||
for &b in &buf[..n] {
|
||||
if b == b'\n' {
|
||||
flush(&mut pending);
|
||||
} else if b != b'\r' {
|
||||
pending.push(b);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
flush(&mut pending);
|
||||
let _ = tx.send(Event::Closed);
|
||||
});
|
||||
}
|
||||
|
||||
fn flush<T>(batch: &mut Vec<T>, on_batch: &mut dyn FnMut(Vec<T>)) {
|
||||
@@ -26,22 +109,41 @@ fn flush<T>(batch: &mut Vec<T>, on_batch: &mut dyn FnMut(Vec<T>)) {
|
||||
/// old, so neither a quiet nor a steady stream holds lines back. Stderr is kept as a
|
||||
/// tail for the error message. Returns whether the child exited successfully.
|
||||
pub(crate) fn stream_batched<T>(
|
||||
cmd: Command,
|
||||
mut cmd: Command,
|
||||
cancel: &CancellationToken,
|
||||
idle: Duration,
|
||||
max: usize,
|
||||
mut parse: impl FnMut(&str) -> Option<T>,
|
||||
on_batch: &mut dyn FnMut(Vec<T>),
|
||||
) -> IdeResult<(bool, Vec<String>)> {
|
||||
let mut lines = ADB.lines(cmd, cancel, CarriageReturn::Dropped)?;
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
prepare(&mut cmd);
|
||||
let mut child = spawn(&mut cmd)?;
|
||||
let (tx, rx) = mpsc::channel::<Event>();
|
||||
let mut open = 0;
|
||||
if let Some(out) = child.stdout.take() {
|
||||
spawn_reader(out, tx.clone(), true);
|
||||
open += 1;
|
||||
}
|
||||
if let Some(err) = child.stderr.take() {
|
||||
spawn_reader(err, tx.clone(), false);
|
||||
open += 1;
|
||||
}
|
||||
drop(tx);
|
||||
let mut stderr_tail: Vec<String> = Vec::new();
|
||||
let mut batch: Vec<T> = Vec::with_capacity(max);
|
||||
// When the first line of the waiting batch arrived.
|
||||
let mut since = Instant::now();
|
||||
loop {
|
||||
while open > 0 {
|
||||
if cancel.is_cancelled() {
|
||||
terminate_tree(&mut child, KILL_GRACE);
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
let wait = if batch.is_empty() { idle } else { idle.saturating_sub(since.elapsed()) };
|
||||
match lines.poll(cancel, wait)? {
|
||||
Poll::Line(Stream::Stdout, line) => {
|
||||
match rx.recv_timeout(wait) {
|
||||
Ok(Event::Line(true, line)) => {
|
||||
if let Some(item) = parse(&line) {
|
||||
if batch.is_empty() {
|
||||
since = Instant::now();
|
||||
@@ -52,25 +154,36 @@ pub(crate) fn stream_batched<T>(
|
||||
}
|
||||
}
|
||||
}
|
||||
Poll::Line(Stream::Stderr, line) => {
|
||||
Ok(Event::Line(false, line)) => {
|
||||
if !line.trim().is_empty() {
|
||||
keep_stderr_line(&mut stderr_tail, line);
|
||||
stderr_tail.push(line);
|
||||
if stderr_tail.len() > 20 {
|
||||
stderr_tail.remove(0);
|
||||
}
|
||||
}
|
||||
}
|
||||
Poll::Closed => {}
|
||||
Poll::Timeout => flush(&mut batch, on_batch),
|
||||
Poll::Finished => break,
|
||||
Ok(Event::Closed) => open -= 1,
|
||||
Err(mpsc::RecvTimeoutError::Timeout) => flush(&mut batch, on_batch),
|
||||
Err(mpsc::RecvTimeoutError::Disconnected) => break,
|
||||
}
|
||||
}
|
||||
flush(&mut batch, on_batch);
|
||||
Ok((lines.finish(cancel)?, stderr_tail))
|
||||
let status = loop {
|
||||
if let Some(status) = child.try_wait()? {
|
||||
break status;
|
||||
}
|
||||
if cancel.is_cancelled() {
|
||||
terminate_tree(&mut child, KILL_GRACE);
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
};
|
||||
Ok((status.success(), stderr_tail))
|
||||
}
|
||||
|
||||
#[cfg(all(test, unix))]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use ide_core::error::ErrorKind;
|
||||
use ide_core::process::process_alive;
|
||||
|
||||
#[test]
|
||||
fn a_steady_stream_is_handed_over_while_it_runs() {
|
||||
@@ -90,199 +203,4 @@ mod tests {
|
||||
assert_eq!(sizes.iter().sum::<usize>(), 20);
|
||||
assert!(sizes.len() >= 3, "lines arriving every 20 ms waited for the end: {sizes:?}");
|
||||
}
|
||||
|
||||
const LONG: Duration = Duration::from_secs(30);
|
||||
|
||||
fn sh(script: &str) -> Command {
|
||||
let mut cmd = Command::new("sh");
|
||||
cmd.args(["-c", script]);
|
||||
cmd
|
||||
}
|
||||
|
||||
/// A script that records its pid in `name`'s file, then runs `rest`.
|
||||
fn recording_pid(name: &str, rest: &str) -> (Command, std::path::PathBuf) {
|
||||
let file = std::env::temp_dir().join(format!("openidea-process-{}-{name}", std::process::id()));
|
||||
let _ = std::fs::remove_file(&file);
|
||||
(sh(&format!("echo $$ > '{0}.tmp' && mv '{0}.tmp' '{0}'; {rest}", file.display())), file)
|
||||
}
|
||||
|
||||
fn recorded_pid(file: &std::path::Path) -> u32 {
|
||||
let pid = std::fs::read_to_string(file).unwrap().trim().parse().unwrap();
|
||||
let _ = std::fs::remove_file(file);
|
||||
pid
|
||||
}
|
||||
|
||||
/// Cancels `cancel` once the script has recorded its pid.
|
||||
fn cancel_when_recorded(file: &std::path::Path, cancel: &CancellationToken) {
|
||||
let (file, cancel) = (file.to_owned(), cancel.clone());
|
||||
std::thread::spawn(move || {
|
||||
while !file.exists() {
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
}
|
||||
cancel.cancel();
|
||||
});
|
||||
}
|
||||
|
||||
fn assert_gone(pid: u32) {
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
while process_alive(pid) {
|
||||
assert!(Instant::now() < deadline, "process {pid} survived");
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_exit_status_is_reported_not_raised() {
|
||||
assert!(run(sh("exit 0"), LONG, None).unwrap().success);
|
||||
assert!(!run(sh("exit 3"), LONG, None).unwrap().success);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn both_streams_are_captured_separately_and_in_order() {
|
||||
let out = run(sh("printf 'a\\nb\\nc\\n'; printf 'x\\ny\\n' >&2"), LONG, None).unwrap();
|
||||
assert_eq!(out.stdout, "a\nb\nc\n");
|
||||
assert_eq!(out.stderr, "x\ny\n");
|
||||
assert!(out.success);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_utf8_is_replaced_in_collected_output() {
|
||||
let out = run(sh("printf 'ok\\n\\377\\n'; printf 'a\\377b' >&2"), LONG, None).unwrap();
|
||||
assert_eq!(out.stdout, "ok\n\u{FFFD}\n");
|
||||
assert_eq!(out.stderr, "a\u{FFFD}b");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stdin_is_closed() {
|
||||
assert_eq!(run(sh("cat; echo done"), LONG, None).unwrap().stdout, "done\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_missing_program_is_unavailable() {
|
||||
let err = run(Command::new("/nonexistent/openidea-adb"), LONG, None).err().unwrap();
|
||||
assert_eq!(err.kind, ErrorKind::Unavailable);
|
||||
assert_eq!(err.message, "could not run adb: No such file or directory (os error 2)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_run_past_its_timeout_fails_and_the_child_is_killed() {
|
||||
let (cmd, file) = recording_pid("adb-timeout", "exec sleep 30");
|
||||
let err = run(cmd, Duration::from_secs(1), None).err().unwrap();
|
||||
assert_eq!(err.kind, ErrorKind::Unavailable);
|
||||
assert_eq!(err.message, "adb did not respond in time");
|
||||
assert_gone(recorded_pid(&file));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cancelled_run_fails_and_the_child_is_killed() {
|
||||
let (cmd, file) = recording_pid("adb-cancel", "exec sleep 30");
|
||||
let cancel = CancellationToken::new();
|
||||
cancel_when_recorded(&file, &cancel);
|
||||
let err = run(cmd, LONG, Some(&cancel)).err().unwrap();
|
||||
assert_eq!(err.kind, ErrorKind::Cancelled);
|
||||
assert_eq!(err.message, "cancelled");
|
||||
assert_gone(recorded_pid(&file));
|
||||
}
|
||||
|
||||
/// Runs `script` batched by `max` lines (a long `idle`, so only `max` and the end flush),
|
||||
/// parsing stdout lines unless they are `skip`.
|
||||
fn batches(script: &str, max: usize) -> (bool, Vec<Vec<String>>, Vec<String>) {
|
||||
let mut batches = Vec::new();
|
||||
let (ok, tail) = stream_batched(
|
||||
sh(script),
|
||||
&CancellationToken::new(),
|
||||
LONG,
|
||||
max,
|
||||
|line| (line != "skip").then(|| line.to_owned()),
|
||||
&mut |batch| batches.push(batch),
|
||||
)
|
||||
.unwrap();
|
||||
(ok, batches, tail)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_batch_is_handed_over_as_soon_as_max_lines_are_ready() {
|
||||
let (ok, batches, _) = batches("printf '1\\n2\\n3\\n4\\n5\\n'", 2);
|
||||
assert!(ok);
|
||||
assert_eq!(batches, [vec!["1", "2"], vec!["3", "4"], vec!["5"]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lines_the_parser_rejects_are_dropped() {
|
||||
let (_, batches, _) = batches("printf '1\\nskip\\n2\\n'", 10);
|
||||
assert_eq!(batches, [vec!["1", "2"]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn carriage_returns_are_dropped_not_split_on_and_line_ends_are_trimmed() {
|
||||
let (_, batches, _) = batches("printf 'a\\r\\nb\\rc \\n\\n\\nd'", 10);
|
||||
assert_eq!(batches, [vec!["a", "bc", "d"]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stream_replaces_invalid_utf8() {
|
||||
let (_, batches, _) = batches("printf 'a\\377b\\n'", 10);
|
||||
assert_eq!(batches, [vec!["a\u{FFFD}b"]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stream_reports_the_exit_status() {
|
||||
assert!(batches("exit 0", 10).0);
|
||||
assert!(!batches("exit 2", 10).0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stderr_is_not_parsed_and_its_last_twenty_non_blank_lines_are_kept() {
|
||||
let (_, batches, tail) =
|
||||
batches("echo ' ' >&2; i=1; while [ $i -le 25 ]; do echo e$i >&2; i=$((i+1)); done; echo out", 10);
|
||||
assert_eq!(batches, [vec!["out"]]);
|
||||
let expected: Vec<String> = (6..=25).map(|i| format!("e{i}")).collect();
|
||||
assert_eq!(tail, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stream_cancelled_before_it_starts_does_not_spawn() {
|
||||
let cancel = CancellationToken::new();
|
||||
cancel.cancel();
|
||||
let err = stream_batched(
|
||||
Command::new("/nonexistent/openidea-adb"),
|
||||
&cancel,
|
||||
LONG,
|
||||
10,
|
||||
|line| Some(line.to_owned()),
|
||||
&mut |_| {},
|
||||
)
|
||||
.err()
|
||||
.unwrap();
|
||||
assert_eq!(err.kind, ErrorKind::Cancelled);
|
||||
assert_eq!(err.message, "cancelled");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stream_cancelled_while_running_fails_and_the_child_is_killed() {
|
||||
let (cmd, file) = recording_pid("adb-stream-cancel", "echo started; exec sleep 30");
|
||||
let cancel = CancellationToken::new();
|
||||
let err = stream_batched(cmd, &cancel, LONG, 1, |line| Some(line.to_owned()), &mut |_| cancel.cancel())
|
||||
.err()
|
||||
.unwrap();
|
||||
assert_eq!(err.kind, ErrorKind::Cancelled);
|
||||
assert_eq!(err.message, "cancelled");
|
||||
assert_gone(recorded_pid(&file));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_missing_program_cannot_be_streamed() {
|
||||
let err = stream_batched(
|
||||
Command::new("/nonexistent/openidea-adb"),
|
||||
&CancellationToken::new(),
|
||||
LONG,
|
||||
10,
|
||||
|line| Some(line.to_owned()),
|
||||
&mut |_| {},
|
||||
)
|
||||
.err()
|
||||
.unwrap();
|
||||
assert_eq!(err.kind, ErrorKind::Unavailable);
|
||||
assert_eq!(err.message, "could not run adb: No such file or directory (os error 2)");
|
||||
}
|
||||
}
|
||||
@@ -17,4 +17,6 @@ serde_json.workspace = true
|
||||
specta.workspace = true
|
||||
tracing.workspace = true
|
||||
dirs.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile.workspace = true
|
||||
@@ -26,10 +26,9 @@ pub fn plan(root: &Path, model: &BuildModel, module: &Path, cache: &Path) -> Ide
|
||||
let module = dunce::canonicalize(root.join(module))?;
|
||||
if let Some(p) = model.maven.as_ref().and_then(|m| m.projects.iter().find(|p| root.join(&p.dir) == module)) {
|
||||
let mut args = p.options.clone();
|
||||
let repo = crate::maven::local_repository_for(&p.options);
|
||||
args.extend([
|
||||
"process-resources".into(),
|
||||
crate::maven::plugin_goal("help:evaluate", repo.as_deref()),
|
||||
"help:evaluate".into(),
|
||||
"-Dexpression=project.build.outputDirectory".into(),
|
||||
format!("-Doutput={}", manifest.display()),
|
||||
]);
|
||||
|
||||
@@ -15,12 +15,12 @@ pub use fingerprint::{LaunchFingerprint, launch_fingerprint, menu_fingerprint};
|
||||
pub use launch_resources::process_launch_resources;
|
||||
pub use modules::record_module_build;
|
||||
pub use single::{
|
||||
SingleFileTarget, compile_file_plan, compile_file_plan_cancellable, find_javac, gradle_compile_file_plan,
|
||||
has_gradle_file_target, javac_step, module_classpath, module_classpaths, single_file_classpath, single_file_target,
|
||||
SingleFileTarget, compile_file_plan, find_javac, javac_step, module_classpath, single_file_classpath,
|
||||
single_file_target,
|
||||
};
|
||||
pub use structure::{
|
||||
StructureJdk, StructureRoots, artifact_file, artifact_output, language_release, structure_compile_file_plan,
|
||||
structure_outputs, structure_plan, structure_war_plan, structure_web_artifacts,
|
||||
StructureJdk, StructureRoots, artifact_file, artifact_output, language_release, structure_outputs, structure_plan,
|
||||
structure_war_plan, structure_web_artifacts,
|
||||
};
|
||||
pub use up_to_date::{menu_up_to_date, record_menu_build};
|
||||
|
||||
@@ -483,6 +483,11 @@ fn go_module_steps(dir: &Path, kind: BuildKind) -> Vec<BuildStep> {
|
||||
vec![s]
|
||||
}
|
||||
|
||||
/// `pnpm` / `yarn` / `bun` / `npm`, from the lock file next to `package.json` or above it.
|
||||
fn package_manager(dir: &Path) -> &'static str {
|
||||
ide_core::project_roots::package_manager(dir)
|
||||
}
|
||||
|
||||
fn has_build_script(dir: &Path) -> bool {
|
||||
std::fs::read(dir.join("package.json"))
|
||||
.ok()
|
||||
@@ -520,12 +525,7 @@ fn dotnet_steps(dir: &Path, kind: BuildKind) -> IdeResult<Vec<BuildStep>> {
|
||||
fn ts_steps(dir: &Path, kind: BuildKind) -> Vec<BuildStep> {
|
||||
let script = has_build_script(dir);
|
||||
if script && (kind == BuildKind::Artifacts || !dir.join("tsconfig.json").is_file()) {
|
||||
return vec![BuildStep::new(
|
||||
ide_core::project_roots::package_manager(dir),
|
||||
&["run", "build"],
|
||||
dir,
|
||||
Format::Tsc,
|
||||
)];
|
||||
return vec![BuildStep::new(package_manager(dir), &["run", "build"], dir, Format::Tsc)];
|
||||
}
|
||||
let local = dir.ancestors().map(|d| d.join("node_modules/.bin/tsc")).find(|p| p.is_file());
|
||||
let program = local.map_or_else(|| "tsc".to_owned(), |p| p.to_string_lossy().into_owned());
|
||||
@@ -916,47 +916,6 @@ fn launch_plan(
|
||||
Ok(plan)
|
||||
}
|
||||
|
||||
/// Directory of the linked Maven reactor that builds the launch module at `module`;
|
||||
/// launches of one reactor can share a build ([`build_for_launches`]).
|
||||
pub fn launch_reactor(root: &Path, model: &BuildModel, module: &Path) -> Option<String> {
|
||||
maven_reactor(model.maven.as_ref()?, &rel_str(root, module)).map(|top| top.dir.clone())
|
||||
}
|
||||
|
||||
/// One Maven step building every module of `modules` (all of one reactor) with what they
|
||||
/// depend on: `-pl a,b -am`, so their shared upstream modules build once (#3971).
|
||||
fn merged_launch_plan(
|
||||
root: &Path,
|
||||
model: &BuildModel,
|
||||
modules: &[PathBuf],
|
||||
test: bool,
|
||||
kind: BuildKind,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<BuildPlan> {
|
||||
let mut plan = launch_plan(root, model, &modules[0], test, kind, cancel)?;
|
||||
if plan.system != BuildSystem::Maven || modules.len() == 1 {
|
||||
return Ok(plan);
|
||||
}
|
||||
let mut selection = Vec::new();
|
||||
for module in modules {
|
||||
let one = launch_plan(root, model, module, test, kind, cancel)?;
|
||||
if one.steps.len() != 1 || one.steps[0].cwd != plan.steps[0].cwd {
|
||||
return Err(IdeError::invalid("launch modules belong to different Maven reactors"));
|
||||
}
|
||||
match one.steps[0].args.iter().position(|a| a == "-pl") {
|
||||
Some(i) => selection.push(one.steps[0].args[i + 1].clone()),
|
||||
// The reactor root itself builds every module.
|
||||
None => return Ok(one),
|
||||
}
|
||||
}
|
||||
selection.sort();
|
||||
selection.dedup();
|
||||
let step = &mut plan.steps[0];
|
||||
if let Some(i) = step.args.iter().position(|a| a == "-pl") {
|
||||
step.args[i + 1] = selection.join(",");
|
||||
}
|
||||
Ok(plan)
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct LaunchBuild {
|
||||
pub class_dirs: Vec<PathBuf>,
|
||||
@@ -965,7 +924,6 @@ pub struct LaunchBuild {
|
||||
|
||||
/// Compiles the module at `module` with its build system before a JVM launch and
|
||||
/// returns the class directories it wrote, to put ahead of the jdtls classpath.
|
||||
/// The build's console, messages and progress stream to `on_event` as it runs.
|
||||
pub fn build_for_launch(
|
||||
root: &Path,
|
||||
model: &BuildModel,
|
||||
@@ -973,25 +931,9 @@ pub fn build_for_launch(
|
||||
test: bool,
|
||||
kind: BuildKind,
|
||||
cancel: &CancellationToken,
|
||||
on_event: &(dyn Fn(BuildEvent) + Sync),
|
||||
) -> IdeResult<LaunchBuild> {
|
||||
let mut built = build_for_launches(root, model, &[module.to_path_buf()], test, kind, cancel, on_event)?;
|
||||
Ok(built.pop().unwrap())
|
||||
}
|
||||
|
||||
/// [`build_for_launch`] of several modules of one Maven reactor in a single Maven run:
|
||||
/// one result per module, in order, sharing the build's failure.
|
||||
pub fn build_for_launches(
|
||||
root: &Path,
|
||||
model: &BuildModel,
|
||||
modules: &[PathBuf],
|
||||
test: bool,
|
||||
kind: BuildKind,
|
||||
cancel: &CancellationToken,
|
||||
on_event: &(dyn Fn(BuildEvent) + Sync),
|
||||
) -> IdeResult<Vec<LaunchBuild>> {
|
||||
let plan = merged_launch_plan(root, model, modules, test, kind, cancel)?;
|
||||
let result = run(root, &plan, cancel, on_event)?;
|
||||
let plan = launch_plan(root, model, module, test, kind, cancel)?;
|
||||
let result = run(root, &plan, cancel, &|_| {})?;
|
||||
let failure = if !result.success {
|
||||
let errors: Vec<String> = result
|
||||
.messages
|
||||
@@ -1007,70 +949,17 @@ pub fn build_for_launches(
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let class_dirs = |module: &Path| {
|
||||
if plan.system == BuildSystem::Maven
|
||||
&& let Some(m) = &model.maven
|
||||
{
|
||||
maven_launch_output_dirs(root, m, module, test).into_iter().filter(|dir| dir.is_dir()).collect()
|
||||
} else {
|
||||
launch_class_dirs(plan.system, module, test)
|
||||
}
|
||||
let class_dirs = if plan.system == BuildSystem::Maven
|
||||
&& let Some(m) = &model.maven
|
||||
{
|
||||
maven_launch_projects(root, m, module, test)
|
||||
.iter()
|
||||
.flat_map(|p| launch_class_dirs(plan.system, &subdir(root, &p.dir), test && subdir(root, &p.dir) == module))
|
||||
.collect()
|
||||
} else {
|
||||
launch_class_dirs(plan.system, module, test)
|
||||
};
|
||||
Ok(modules.iter().map(|m| LaunchBuild { class_dirs: class_dirs(m), failure: failure.clone() }).collect())
|
||||
}
|
||||
|
||||
/// Maven output directories for a launch, including directories that have yet to be created.
|
||||
pub fn maven_launch_output_dirs(root: &Path, model: &maven::MavenModel, module: &Path, test: bool) -> Vec<PathBuf> {
|
||||
maven_launch_projects(root, model, module, test)
|
||||
.into_iter()
|
||||
.flat_map(|p| {
|
||||
let dir = subdir(root, &p.dir);
|
||||
maven_output_dirs(&dir, test && dir == module)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The class directories of a Maven launch that must hold classes after its build: those of
|
||||
/// the launch projects with sources in a conventional JVM source root. One that is missing
|
||||
/// or holds no class was caught mid-rewrite, e.g. cleaned by a concurrent `mvn` (#5404).
|
||||
pub fn launch_required_class_dirs(root: &Path, model: &BuildModel, module: &Path, test: bool) -> Vec<PathBuf> {
|
||||
fn has_sources(dir: &Path, depth: u32) -> bool {
|
||||
let Ok(entries) = std::fs::read_dir(dir) else { return false };
|
||||
entries.flatten().any(|e| {
|
||||
let p = e.path();
|
||||
if p.is_dir() {
|
||||
depth > 0 && has_sources(&p, depth - 1)
|
||||
} else {
|
||||
// A package-info.java without annotations compiles to nothing.
|
||||
p.file_name() != Some("package-info.java".as_ref())
|
||||
&& p.extension().is_some_and(|x| x == "java" || x == "kt" || x == "groovy" || x == "scala")
|
||||
}
|
||||
})
|
||||
}
|
||||
let compiles = |dir: &Path, set: &str| {
|
||||
["java", "kotlin", "groovy", "scala"].iter().any(|lang| has_sources(&dir.join("src").join(set).join(lang), 32))
|
||||
};
|
||||
let Some(m) = &model.maven else { return Vec::new() };
|
||||
let mut dirs = Vec::new();
|
||||
for p in maven_launch_projects(root, m, module, test) {
|
||||
let dir = subdir(root, &p.dir);
|
||||
if test && dir == module && compiles(&dir, "test") {
|
||||
dirs.push(subdir(&dir, "target/test-classes"));
|
||||
}
|
||||
if compiles(&dir, "main") {
|
||||
dirs.push(subdir(&dir, "target/classes"));
|
||||
}
|
||||
}
|
||||
dirs
|
||||
}
|
||||
|
||||
fn maven_output_dirs(module: &Path, test: bool) -> Vec<PathBuf> {
|
||||
let mut dirs = Vec::new();
|
||||
if test {
|
||||
dirs.push(subdir(module, "target/test-classes"));
|
||||
}
|
||||
dirs.push(subdir(module, "target/classes"));
|
||||
dirs
|
||||
Ok(LaunchBuild { class_dirs, failure })
|
||||
}
|
||||
|
||||
fn launch_class_dirs(system: BuildSystem, module: &Path, test: bool) -> Vec<PathBuf> {
|
||||
@@ -1083,7 +972,8 @@ fn launch_class_dirs(system: BuildSystem, module: &Path, test: bool) -> Vec<Path
|
||||
.map(|d| subdir(module, &format!("build/{d}/{s}")))
|
||||
})
|
||||
.collect(),
|
||||
BuildSystem::Maven => maven_output_dirs(module, test),
|
||||
BuildSystem::Maven if test => vec![subdir(module, "target/test-classes"), subdir(module, "target/classes")],
|
||||
BuildSystem::Maven => vec![subdir(module, "target/classes")],
|
||||
_ => Vec::new(),
|
||||
};
|
||||
dirs.into_iter().filter(|d| d.is_dir()).collect()
|
||||
@@ -1769,46 +1659,6 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn launches_of_one_reactor_merge_into_one_module_selection() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
for dir in ["app", "lib", "unrelated"] {
|
||||
write(root, &format!("{dir}/pom.xml"), "<project/>");
|
||||
}
|
||||
let mut model = reactor_model();
|
||||
let cancel = CancellationToken::new();
|
||||
let modules = |dirs: &[&str]| dirs.iter().map(|d| root.join(d)).collect::<Vec<_>>();
|
||||
let selection = |plan: BuildPlan| {
|
||||
let args = &plan.steps[0].args;
|
||||
args.iter().position(|a| a == "-pl").map(|i| (args[i + 1].clone(), args[i + 2].clone(), args.len()))
|
||||
};
|
||||
assert_eq!(launch_reactor(root, &model, &root.join("lib")).as_deref(), Some(""));
|
||||
let plan = merged_launch_plan(root, &model, &modules(&["lib", "app", "lib"]), false, BuildKind::Build, &cancel)
|
||||
.unwrap();
|
||||
assert_eq!(plan.steps.len(), 1);
|
||||
assert_eq!(plan.steps[0].args.last().unwrap(), "compile");
|
||||
assert_eq!(selection(plan), Some(("app,lib".into(), "-am".into(), 10)));
|
||||
// One module: exactly the single launch's step.
|
||||
let single = merged_launch_plan(root, &model, &modules(&["app"]), true, BuildKind::Rebuild, &cancel).unwrap();
|
||||
let expected = launch_plan(root, &model, &root.join("app"), true, BuildKind::Rebuild, &cancel).unwrap();
|
||||
assert_eq!(single.steps[0].args, expected.steps[0].args);
|
||||
// The reactor root among them builds the whole reactor.
|
||||
model.maven.as_mut().unwrap().projects[0].packaging = "jar".into();
|
||||
let whole = merged_launch_plan(root, &model, &modules(&["app", ""]), false, BuildKind::Build, &cancel).unwrap();
|
||||
assert_eq!(selection(whole), None);
|
||||
// Another linked reactor can't join the step.
|
||||
let m = model.maven.as_mut().unwrap();
|
||||
m.projects[4].aggregated = false;
|
||||
m.projects[4].command = "other".into();
|
||||
m.projects[0].modules.retain(|p| p != "unrelated/pom.xml");
|
||||
assert_eq!(launch_reactor(root, &model, &root.join("unrelated")).as_deref(), Some("unrelated"));
|
||||
assert!(
|
||||
merged_launch_plan(root, &model, &modules(&["app", "unrelated"]), false, BuildKind::Build, &cancel)
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn external_launch_returns_upstream_outputs_and_blocks_failure_or_cancellation() {
|
||||
@@ -1825,16 +1675,8 @@ mod tests {
|
||||
std::fs::set_permissions(&wrapper, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
let mut model = reactor_model();
|
||||
model.maven.as_mut().unwrap().projects[0].command = wrapper.to_string_lossy().into_owned();
|
||||
let dirs = build_for_launch(
|
||||
root,
|
||||
&model,
|
||||
&root.join("app"),
|
||||
true,
|
||||
BuildKind::Build,
|
||||
&CancellationToken::new(),
|
||||
&|_| {},
|
||||
)
|
||||
.unwrap();
|
||||
let dirs = build_for_launch(root, &model, &root.join("app"), true, BuildKind::Build, &CancellationToken::new())
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
dirs.class_dirs,
|
||||
["app/target/test-classes", "app/target/classes", "middle/target/classes", "lib/target/classes"]
|
||||
@@ -1845,25 +1687,16 @@ mod tests {
|
||||
"mvnw",
|
||||
"#!/bin/sh\necho '[ERROR] Kotlin compilation failed: unresolved reference broken' >&2\nexit 1\n",
|
||||
);
|
||||
let error = build_for_launch(
|
||||
root,
|
||||
&model,
|
||||
&root.join("app"),
|
||||
false,
|
||||
BuildKind::Build,
|
||||
&CancellationToken::new(),
|
||||
&|_| {},
|
||||
)
|
||||
.unwrap()
|
||||
.failure
|
||||
.unwrap();
|
||||
let error =
|
||||
build_for_launch(root, &model, &root.join("app"), false, BuildKind::Build, &CancellationToken::new())
|
||||
.unwrap()
|
||||
.failure
|
||||
.unwrap();
|
||||
assert!(error.contains("Kotlin compilation failed"), "{error}");
|
||||
let cancel = CancellationToken::new();
|
||||
cancel.cancel();
|
||||
assert_eq!(
|
||||
build_for_launch(root, &model, &root.join("app"), false, BuildKind::Build, &cancel, &|_| {})
|
||||
.unwrap_err()
|
||||
.kind,
|
||||
build_for_launch(root, &model, &root.join("app"), false, BuildKind::Build, &cancel).unwrap_err().kind,
|
||||
ide_core::error::ErrorKind::Cancelled
|
||||
);
|
||||
}
|
||||
|
||||
@@ -200,22 +200,19 @@ fn kotlin_line(line: &str) -> Option<RawMessage> {
|
||||
kotlin_location(rest, severity)
|
||||
}
|
||||
|
||||
/// javac: `A.java:12: error: msg` / `A.java:12: warning: [deprecation] msg`
|
||||
/// (and localized javac prefixes such as Chinese/Japanese `错误:` / `錯誤:` / `エラー:` / `警告:`).
|
||||
/// javac: `A.java:12: error: msg` / `A.java:12: warning: [deprecation] msg`.
|
||||
fn javac_header(line: &str) -> Option<RawMessage> {
|
||||
let (path, ln, col, rest) = path_line_col(line)?;
|
||||
if !looks_like_source_path(path) {
|
||||
return None;
|
||||
}
|
||||
let rest = rest.trim_start_matches(':').trim_start();
|
||||
let (severity, msg) = ["error:", "错误:", "錯誤:", "エラー:"]
|
||||
.into_iter()
|
||||
.find_map(|prefix| rest.strip_prefix(prefix).map(|m| (Severity::Error, m)))
|
||||
.or_else(|| {
|
||||
["warning:", "警告:"]
|
||||
.into_iter()
|
||||
.find_map(|prefix| rest.strip_prefix(prefix).map(|m| (Severity::Warning, m)))
|
||||
})?;
|
||||
let (severity, msg) = if let Some(m) = rest.strip_prefix("error:") {
|
||||
(Severity::Error, m)
|
||||
} else {
|
||||
let m = rest.strip_prefix("warning:")?;
|
||||
(Severity::Warning, m)
|
||||
};
|
||||
Some(RawMessage::new(severity, msg.trim(), ColUnit::Char).at(path, ln, col))
|
||||
}
|
||||
|
||||
@@ -558,31 +555,6 @@ mod tests {
|
||||
assert_eq!(out[1].text, "[removal] finalize() has been deprecated");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn localized_javac_errors_and_warnings() {
|
||||
let out = parse(
|
||||
Format::Gradle,
|
||||
"/p/src/A.java:12: 错误: 找不到符号\n\
|
||||
\x20 Foo foo = new Foo();\n\
|
||||
\x20 ^\n\
|
||||
\x20 符号: 类 Foo\n\
|
||||
\x20 位置: 类 A\n\
|
||||
/p/src/B.java:5: 錯誤: 需要 ';'\n\
|
||||
\x20 int x = 1\n\
|
||||
\x20 ^\n\
|
||||
/p/src/C.java:8: 警告: [deprecation] old() 已过时\n\
|
||||
\x20 old();\n\
|
||||
\x20 ^\n",
|
||||
);
|
||||
assert_eq!(out.len(), 3, "{out:?}");
|
||||
assert_eq!(pos(&out[0]), (Severity::Error, "/p/src/A.java", 12, Some(9)));
|
||||
assert_eq!(out[0].text, "找不到符号\n符号: 类 Foo\n位置: 类 A");
|
||||
assert_eq!(pos(&out[1]), (Severity::Error, "/p/src/B.java", 5, Some(14)));
|
||||
assert_eq!(out[1].text, "需要 ';'");
|
||||
assert_eq!(pos(&out[2]), (Severity::Warning, "/p/src/C.java", 8, Some(5)));
|
||||
assert_eq!(out[2].text, "[deprecation] old() 已过时");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gradle_kotlin() {
|
||||
let out = parse(
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! Single-file Java compilation with `javac` for the Recompile action (#2476).
|
||||
//! Single-file Java compilation with `javac` for the Compile File action (#2476).
|
||||
//!
|
||||
//! A module build (`-pl … -am`) still walks every upstream module, and packaging
|
||||
//! walks the whole reactor; compiling one file only needs that file's module
|
||||
@@ -6,93 +6,12 @@
|
||||
use super::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::fs;
|
||||
use std::process::Command as ProcCommand;
|
||||
|
||||
/// Output file of the `dependency:build-classpath` probe, relative to each module.
|
||||
const CP_FILE: &str = "target/ide-compile-cp.txt";
|
||||
// Older records include undeclared reactor test outputs even in runtime classpaths.
|
||||
const CLASSPATH_CACHE_VERSION: u32 = 1;
|
||||
const GRADLE_COMPILE_CP_INIT_SCRIPT: &str = include_str!("../gradle-compile-cp.init.gradle");
|
||||
|
||||
pub(super) fn is_java_file(file: &Path) -> IdeResult<String> {
|
||||
if file.extension().is_none_or(|ext| !ext.eq_ignore_ascii_case("java")) {
|
||||
return Err(IdeError::invalid("only Java sources can be compiled as a single file"));
|
||||
}
|
||||
if !file.is_file() {
|
||||
return Err(IdeError::not_found("no Java source found for single-file compilation"));
|
||||
}
|
||||
Ok(file.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default())
|
||||
}
|
||||
|
||||
pub(super) fn is_test_source(rel: &str) -> bool {
|
||||
let parts: Vec<&str> = rel.split(['/', '\\']).collect();
|
||||
parts.windows(2).any(|w| w == ["src", "test"])
|
||||
}
|
||||
|
||||
pub(super) fn java_home_major(env: &BTreeMap<String, String>) -> Option<u32> {
|
||||
let home = env.get("JAVA_HOME").filter(|h| !h.trim().is_empty())?;
|
||||
let release = fs::read_to_string(Path::new(home).join("release")).ok()?;
|
||||
let value = release.lines().find_map(|l| l.trim().strip_prefix("JAVA_VERSION="))?;
|
||||
let value = value.trim().trim_matches(['"', '\'']);
|
||||
language_release(value)
|
||||
}
|
||||
|
||||
/// `--release N` from JDK 9 on; older compilers only know `-source` / `-target`.
|
||||
pub(super) fn release_args(level: Option<u32>, jdk_major: Option<u32>) -> Vec<String> {
|
||||
let Some(level) = level else { return Vec::new() };
|
||||
if jdk_major.is_none_or(|m| m >= 9) {
|
||||
vec!["--release".into(), level.to_string()]
|
||||
} else {
|
||||
vec!["-source".into(), format!("1.{level}"), "-target".into(), format!("1.{level}")]
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn join_classpath(entries: impl IntoIterator<Item = String>) -> String {
|
||||
let separator = if cfg!(windows) { ";" } else { ":" };
|
||||
let mut seen = HashSet::new();
|
||||
let mut out = Vec::new();
|
||||
for entry in entries {
|
||||
if !entry.is_empty() && seen.insert(entry.clone()) {
|
||||
out.push(entry);
|
||||
}
|
||||
}
|
||||
out.join(separator)
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(super) fn build_javac_step(
|
||||
javac: &str,
|
||||
cwd: &Path,
|
||||
out_dir: &Path,
|
||||
classpath: &str,
|
||||
sources: &[PathBuf],
|
||||
release: Vec<String>,
|
||||
file: &Path,
|
||||
env: BTreeMap<String, String>,
|
||||
) -> IdeResult<BuildStep> {
|
||||
fs::create_dir_all(out_dir)
|
||||
.map_err(|e| IdeError::internal(format!("cannot create {} ({e})", out_dir.display())))?;
|
||||
// Raw `javac` prints `path:line: error: …`, the same form Gradle forwards.
|
||||
let mut step = BuildStep::new(javac, &[], cwd, Format::Gradle);
|
||||
step.args.extend(["-encoding".into(), "UTF-8".into(), "-g".into()]);
|
||||
step.args.extend(["-d".into(), out_dir.to_string_lossy().into_owned()]);
|
||||
if !classpath.is_empty() {
|
||||
step.args.extend(["-cp".into(), classpath.to_owned()]);
|
||||
}
|
||||
// Classes of the module that were never built (or are older than their source) are read
|
||||
// from its sources; only `file` is written, so a test compile never puts main classes
|
||||
// into test-classes.
|
||||
if !sources.is_empty() {
|
||||
let separator = if cfg!(windows) { ";" } else { ":" };
|
||||
step.args.push("-sourcepath".into());
|
||||
step.args.push(sources.iter().map(|p| p.to_string_lossy()).collect::<Vec<_>>().join(separator));
|
||||
step.args.push("-implicit:none".into());
|
||||
}
|
||||
step.args.extend(release);
|
||||
step.args.push(file.to_string_lossy().into_owned());
|
||||
step.env = env;
|
||||
step.mkdirs = vec![out_dir.to_path_buf()];
|
||||
Ok(step)
|
||||
}
|
||||
|
||||
/// The resolved dependency classpath for one module and scope, tied to the same
|
||||
/// inputs as its launch build so POM, JDK, settings and profile changes invalidate it.
|
||||
@@ -122,7 +41,12 @@ pub struct SingleFileTarget {
|
||||
|
||||
/// Locates the linked Maven module owning a `.java` source file.
|
||||
pub fn single_file_target(root: &Path, model: &BuildModel, file: &Path) -> IdeResult<SingleFileTarget> {
|
||||
is_java_file(file)?;
|
||||
if file.extension().is_none_or(|ext| ext != "java") {
|
||||
return Err(IdeError::invalid("only Java sources can be compiled as a single file"));
|
||||
}
|
||||
if !file.is_file() {
|
||||
return Err(IdeError::not_found("no Java source found for single-file compilation"));
|
||||
}
|
||||
let Some(m) = &model.maven else {
|
||||
return Err(IdeError::not_found("no linked Maven project found for module"));
|
||||
};
|
||||
@@ -146,7 +70,8 @@ pub fn single_file_target(root: &Path, model: &BuildModel, file: &Path) -> IdeRe
|
||||
let top_dir = subdir(root, &top.dir);
|
||||
let pl = module.strip_prefix(&top_dir).map(|r| r.to_string_lossy().replace('\\', "/")).unwrap_or_default();
|
||||
// Test sources see the test classpath and compile into test classes.
|
||||
let test = is_test_source(&rel);
|
||||
let parts: Vec<&str> = rel.split('/').collect();
|
||||
let test = parts.windows(2).any(|w| w == ["src", "test"]);
|
||||
let out_dir = module.join("target").join(if test { "test-classes" } else { "classes" });
|
||||
Ok(SingleFileTarget { module, test, out_dir, top: top.clone(), pl, java_version: project.java_version })
|
||||
}
|
||||
@@ -187,17 +112,7 @@ pub fn find_javac(env: &BTreeMap<String, String>) -> String {
|
||||
/// `mvn dependency:build-classpath` (which resolves without compiling anything,
|
||||
/// so `-am` stays cheap). Entries are platform-separated (`;` on Windows).
|
||||
pub fn single_file_classpath(root: &Path, model: &BuildModel, target: &SingleFileTarget) -> IdeResult<String> {
|
||||
single_file_classpath_cancellable(root, model, target, &CancellationToken::new())
|
||||
}
|
||||
|
||||
fn single_file_classpath_cancellable(
|
||||
root: &Path,
|
||||
model: &BuildModel,
|
||||
target: &SingleFileTarget,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<String> {
|
||||
let scope = if target.test { "test" } else { "compile" };
|
||||
classpath(root, model, target, scope, false, cancel)
|
||||
classpath(root, model, target, "test", false)
|
||||
}
|
||||
|
||||
/// Runtime (or test) dependency classpath for a launch module.
|
||||
@@ -214,75 +129,31 @@ pub fn module_classpath(
|
||||
cache: &Path,
|
||||
cancel: &ide_core::CancellationToken,
|
||||
) -> IdeResult<String> {
|
||||
module_classpaths(root, model, &[module.to_path_buf()], test, local_repo, cache, cancel)
|
||||
}
|
||||
|
||||
/// [`module_classpath`] of `modules[0]`. The other modules, launched together with it
|
||||
/// (#3971), share its Maven probe when they have no cached classpath, which leaves
|
||||
/// theirs cached for their own launches.
|
||||
pub fn module_classpaths(
|
||||
root: &Path,
|
||||
model: &BuildModel,
|
||||
modules: &[PathBuf],
|
||||
test: bool,
|
||||
local_repo: Option<PathBuf>,
|
||||
cache: &Path,
|
||||
cancel: &ide_core::CancellationToken,
|
||||
) -> IdeResult<String> {
|
||||
let mut probes: Vec<Probe> = Vec::new();
|
||||
for (i, module) in modules.iter().enumerate() {
|
||||
let target = match module_target(root, model, module, test) {
|
||||
Ok(target) => target,
|
||||
Err(e) if i == 0 => return Err(e),
|
||||
Err(_) => continue,
|
||||
};
|
||||
if i > 0 && (target.top.dir != probes[0].0.top.dir || probes.iter().any(|p| p.0.module == target.module)) {
|
||||
continue;
|
||||
}
|
||||
let fingerprint = launch_fingerprint(root, model, &target.module, test, local_repo.clone(), cancel)?;
|
||||
let cache_path = classpath_cache_path(root, cache, &target.module, test);
|
||||
if let (Some(fingerprint), Some(path)) = (&fingerprint, &cache_path)
|
||||
&& let Ok(bytes) = fs::read(path)
|
||||
&& let Ok(cached) = serde_json::from_slice::<CachedClasspath>(&bytes)
|
||||
&& cached.version == CLASSPATH_CACHE_VERSION
|
||||
&& cached.fingerprint == *fingerprint
|
||||
&& classpath_entries_exist(root, &cached.classpath)
|
||||
{
|
||||
if i == 0 {
|
||||
return Ok(cached.classpath);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
probes.push(Probe(target, fingerprint, cache_path));
|
||||
let target = module_target(root, model, module, test)?;
|
||||
let fingerprint = launch_fingerprint(root, model, &target.module, test, local_repo, cancel)?;
|
||||
let cache_path = classpath_cache_path(root, cache, &target.module, test);
|
||||
if let (Some(fingerprint), Some(path)) = (&fingerprint, &cache_path)
|
||||
&& let Ok(bytes) = fs::read(path)
|
||||
&& let Ok(cached) = serde_json::from_slice::<CachedClasspath>(&bytes)
|
||||
&& cached.version == CLASSPATH_CACHE_VERSION
|
||||
&& cached.fingerprint == *fingerprint
|
||||
&& classpath_entries_exist(root, &cached.classpath)
|
||||
{
|
||||
return Ok(cached.classpath);
|
||||
}
|
||||
let scope = if test { "test" } else { "runtime" };
|
||||
let targets: Vec<&SingleFileTarget> = probes.iter().map(|p| &p.0).collect();
|
||||
let classpaths = match classpaths(root, model, &targets, scope, true, cancel) {
|
||||
Ok(classpaths) => classpaths,
|
||||
// Another module's failure must not cost this launch its own probe.
|
||||
Err(_) if targets.len() > 1 && !cancel.is_cancelled() => {
|
||||
classpaths(root, model, &targets[..1], scope, true, cancel)?
|
||||
}
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
let classpath = classpath(root, model, &target, if test { "test" } else { "runtime" }, true)?;
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
for (Probe(_, fingerprint, cache_path), classpath) in probes.into_iter().zip(&classpaths) {
|
||||
if let (Some(fingerprint), Some(path)) = (fingerprint, cache_path) {
|
||||
let cached =
|
||||
CachedClasspath { version: CLASSPATH_CACHE_VERSION, fingerprint, classpath: classpath.clone() };
|
||||
if let Err(error) = cache_classpath(&path, &cached) {
|
||||
tracing::debug!(path = %path.display(), %error, "Cannot cache the Java launch classpath");
|
||||
}
|
||||
if let (Some(fingerprint), Some(path)) = (fingerprint, cache_path) {
|
||||
let cached = CachedClasspath { version: CLASSPATH_CACHE_VERSION, fingerprint, classpath: classpath.clone() };
|
||||
if let Err(error) = cache_classpath(&path, &cached) {
|
||||
tracing::debug!(path = %path.display(), %error, "Cannot cache the Java launch classpath");
|
||||
}
|
||||
}
|
||||
Ok(classpaths.into_iter().next().unwrap())
|
||||
Ok(classpath)
|
||||
}
|
||||
|
||||
/// A module whose classpath the Maven probe resolves, with its cache key and file.
|
||||
struct Probe(SingleFileTarget, Option<LaunchFingerprint>, Option<PathBuf>);
|
||||
|
||||
/// One cache file per module and scope. Mirroring the module path keeps nested
|
||||
/// modules and their different dependency scopes from overwriting each other.
|
||||
fn classpath_cache_path(root: &Path, cache: &Path, module: &Path, test: bool) -> Option<PathBuf> {
|
||||
@@ -323,68 +194,7 @@ fn classpath(
|
||||
target: &SingleFileTarget,
|
||||
scope: &str,
|
||||
compile_first: bool,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<String> {
|
||||
Ok(classpaths(root, model, &[target], scope, compile_first, cancel)?.pop().unwrap())
|
||||
}
|
||||
|
||||
/// The classpath of each of `targets` (modules of one reactor) from one Maven probe.
|
||||
fn classpaths(
|
||||
root: &Path,
|
||||
model: &BuildModel,
|
||||
targets: &[&SingleFileTarget],
|
||||
scope: &str,
|
||||
compile_first: bool,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<Vec<String>> {
|
||||
let top = &targets[0].top;
|
||||
let probe = CP_FILE;
|
||||
let mut args = vec!["-B", "-Dstyle.color=never", maven::LOCAL_REPO_TRACKING_ARG];
|
||||
args.extend(top.options.iter().map(String::as_str));
|
||||
// The reactor root among them builds every module.
|
||||
let selection = if targets.iter().any(|t| t.pl.is_empty()) {
|
||||
String::new()
|
||||
} else {
|
||||
let mut pl: Vec<&str> = targets.iter().map(|t| t.pl.as_str()).collect();
|
||||
pl.sort();
|
||||
pl.dedup();
|
||||
pl.join(",")
|
||||
};
|
||||
if !selection.is_empty() {
|
||||
args.extend(["-pl", selection.as_str(), "-am"]);
|
||||
}
|
||||
let output_arg = format!("-Dmdep.outputFile={probe}");
|
||||
let scope_arg = format!("-Dmdep.includeScope={scope}");
|
||||
// A launch build may only have reached `compile`. Running `compile` in this
|
||||
// same Maven session lets the dependency plugin resolve Reactor siblings from
|
||||
// their target/classes without paying for package-phase plugins.
|
||||
if compile_first {
|
||||
args.push("compile");
|
||||
}
|
||||
let build_classpath =
|
||||
maven::plugin_goal("dependency:build-classpath", maven::local_repository_for(&top.options).as_deref());
|
||||
args.extend([build_classpath.as_str(), output_arg.as_str(), scope_arg.as_str(), "-q"]);
|
||||
let top_dir = subdir(root, &top.dir);
|
||||
let owned_args: Vec<String> = args.into_iter().map(str::to_owned).collect();
|
||||
let out = process::run_bounded(&top.command, &owned_args, &top_dir, &top.env, cancel, |_, _| {}).map_err(|e| {
|
||||
if e.kind == ide_core::error::ErrorKind::Cancelled {
|
||||
e
|
||||
} else {
|
||||
IdeError::internal(format!("cannot resolve the compile classpath: {}", e.message))
|
||||
}
|
||||
})?;
|
||||
if !out.success {
|
||||
// Maven reports reactor/dependency failures on stdout, not only stderr.
|
||||
let tail: Vec<&str> = out.text.lines().filter(|l| !l.trim().is_empty()).collect();
|
||||
let tail = tail.iter().rev().take(5).rev().cloned().collect::<Vec<_>>().join("\n");
|
||||
return Err(IdeError::internal(format!("cannot resolve the compile classpath:\n{tail}")));
|
||||
}
|
||||
targets.iter().map(|target| target_classpath(root, model, target)).collect()
|
||||
}
|
||||
|
||||
/// The classpath of `target` after a probe: its reactor class directories, then
|
||||
/// the dependencies Maven wrote to the module's probe file.
|
||||
fn target_classpath(root: &Path, model: &BuildModel, target: &SingleFileTarget) -> IdeResult<String> {
|
||||
let mut entries: Vec<String> = Vec::new();
|
||||
// The module's own classes first: the file almost always uses classes next to it.
|
||||
let own: &[&str] = if target.test { &["target/test-classes", "target/classes"] } else { &["target/classes"] };
|
||||
@@ -410,21 +220,76 @@ fn target_classpath(root: &Path, model: &BuildModel, target: &SingleFileTarget)
|
||||
}
|
||||
}
|
||||
}
|
||||
let probe = CP_FILE;
|
||||
let mut args = vec!["-B", "-Dstyle.color=never", maven::LOCAL_REPO_TRACKING_ARG];
|
||||
args.extend(target.top.options.iter().map(String::as_str));
|
||||
if !target.pl.is_empty() {
|
||||
args.extend(["-pl", target.pl.as_str(), "-am"]);
|
||||
}
|
||||
let output_arg = format!("-Dmdep.outputFile={probe}");
|
||||
let scope_arg = format!("-Dmdep.includeScope={scope}");
|
||||
// A launch build may only have reached `compile`. Running `compile` in this
|
||||
// same Maven session lets the dependency plugin resolve Reactor siblings from
|
||||
// their target/classes without paying for package-phase plugins.
|
||||
if compile_first {
|
||||
args.push("compile");
|
||||
}
|
||||
args.extend(["dependency:build-classpath", output_arg.as_str(), scope_arg.as_str(), "-q"]);
|
||||
let top_dir = subdir(root, &target.top.dir);
|
||||
let status = ProcCommand::new(&target.top.command)
|
||||
.args(&args)
|
||||
.envs(&target.top.env)
|
||||
.current_dir(&top_dir)
|
||||
.output()
|
||||
.map_err(|e| IdeError::internal(format!("cannot resolve the compile classpath: {e}")))?;
|
||||
if !status.status.success() {
|
||||
let stdout = String::from_utf8_lossy(&status.stdout);
|
||||
let stderr = String::from_utf8_lossy(&status.stderr);
|
||||
// Maven reports reactor/dependency failures on stdout, not only stderr.
|
||||
let tail: Vec<&str> = stdout.lines().chain(stderr.lines()).filter(|l| !l.trim().is_empty()).collect();
|
||||
let tail = tail.iter().rev().take(5).rev().cloned().collect::<Vec<_>>().join("\n");
|
||||
return Err(IdeError::internal(format!("cannot resolve the compile classpath:\n{tail}")));
|
||||
}
|
||||
// With `-am` every visited module writes its own file; only this module's counts.
|
||||
let cp_file = target.module.join(CP_FILE);
|
||||
let cp_file = target.module.join(probe);
|
||||
let content = fs::read_to_string(&cp_file).map_err(|e| {
|
||||
IdeError::internal(format!("cannot resolve the compile classpath: {} ({e})", cp_file.display()))
|
||||
})?;
|
||||
let separator = if cfg!(windows) { ';' } else { ':' };
|
||||
entries.extend(content.split([separator, '\n', '\r']).map(str::trim).filter(|e| !e.is_empty()).map(str::to_owned));
|
||||
Ok(join_classpath(entries))
|
||||
entries.dedup();
|
||||
Ok(entries.join(&separator.to_string()))
|
||||
}
|
||||
|
||||
/// The `javac` step compiling `file` into `target`'s output directory.
|
||||
pub fn javac_step(target: &SingleFileTarget, file: &Path, classpath: &str, javac: &str) -> IdeResult<BuildStep> {
|
||||
fs::create_dir_all(&target.out_dir)
|
||||
.map_err(|e| IdeError::internal(format!("cannot create {} ({e})", target.out_dir.display())))?;
|
||||
let mut step = BuildStep::new(javac, &[], &target.module, Format::Gradle);
|
||||
// Raw `javac` prints `path:line: error: …`, the same form Gradle forwards.
|
||||
step.args.push("-encoding".into());
|
||||
step.args.push("UTF-8".into());
|
||||
step.args.push("-d".into());
|
||||
step.args.push(target.out_dir.to_string_lossy().into_owned());
|
||||
step.args.push("-cp".into());
|
||||
step.args.push(classpath.to_owned());
|
||||
// Classes of the module that were never built (or are older than their source) are read
|
||||
// from its sources; only `file` is written, so a test compile never puts main classes
|
||||
// into test-classes.
|
||||
let sources = source_roots(target);
|
||||
let release = release_args(target.java_version, java_home_major(&target.top.env));
|
||||
build_javac_step(javac, &target.module, &target.out_dir, classpath, &sources, release, file, target.top.env.clone())
|
||||
if !sources.is_empty() {
|
||||
let separator = if cfg!(windows) { ";" } else { ":" };
|
||||
step.args.push("-sourcepath".into());
|
||||
step.args.push(sources.iter().map(|p| p.to_string_lossy()).collect::<Vec<_>>().join(separator));
|
||||
step.args.push("-implicit:none".into());
|
||||
}
|
||||
if let Some(version) = target.java_version {
|
||||
step.args.push("--release".into());
|
||||
step.args.push(version.to_string());
|
||||
}
|
||||
step.args.push(file.to_string_lossy().into_owned());
|
||||
step.env = target.top.env.clone();
|
||||
Ok(step)
|
||||
}
|
||||
|
||||
/// The module's Java source folders that exist, generated ones included; test sources see
|
||||
@@ -450,18 +315,8 @@ fn source_roots(target: &SingleFileTarget) -> Vec<PathBuf> {
|
||||
|
||||
/// Resolves the classpath and plans the `javac` invocation for one Java source.
|
||||
pub fn compile_file_plan(root: &Path, model: &BuildModel, file: &Path) -> IdeResult<BuildPlan> {
|
||||
compile_file_plan_cancellable(root, model, file, &CancellationToken::new())
|
||||
}
|
||||
|
||||
/// Cancellable [`compile_file_plan`].
|
||||
pub fn compile_file_plan_cancellable(
|
||||
root: &Path,
|
||||
model: &BuildModel,
|
||||
file: &Path,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<BuildPlan> {
|
||||
let target = single_file_target(root, model, file)?;
|
||||
let classpath = single_file_classpath_cancellable(root, model, &target, cancel)?;
|
||||
let classpath = single_file_classpath(root, model, &target)?;
|
||||
let javac = find_javac(&target.top.env);
|
||||
let name = file.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
Ok(BuildPlan {
|
||||
@@ -471,140 +326,6 @@ pub fn compile_file_plan_cancellable(
|
||||
})
|
||||
}
|
||||
|
||||
fn gradle_for_file<'a>(
|
||||
root: &Path,
|
||||
model: &'a BuildModel,
|
||||
file: &Path,
|
||||
) -> Option<(&'a crate::GradleModel, &'a crate::GradleProject, PathBuf)> {
|
||||
let file = normalize(file);
|
||||
let file_ref = &file;
|
||||
model
|
||||
.gradle
|
||||
.iter()
|
||||
.flat_map(|g| {
|
||||
let g_dir = normalize(&subdir(root, &g.dir));
|
||||
let g_depth = g_dir.components().count();
|
||||
g.projects.iter().filter_map(move |p| {
|
||||
let p_dir = normalize(&subdir(root, &p.dir));
|
||||
file_ref.starts_with(&p_dir).then_some((g, p, p_dir, g_depth))
|
||||
})
|
||||
})
|
||||
.max_by_key(|(_, _, p_dir, g_depth)| (p_dir.components().count(), *g_depth))
|
||||
.map(|(g, p, p_dir, _)| (g, p, p_dir))
|
||||
}
|
||||
|
||||
/// Whether `file` lies inside a linked Gradle project of `model`.
|
||||
pub fn has_gradle_file_target(root: &Path, model: &BuildModel, file: &Path) -> bool {
|
||||
gradle_for_file(root, model, file).is_some()
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct GradleCompileCp {
|
||||
out_dir: Option<String>,
|
||||
#[serde(default)]
|
||||
classpath: Vec<String>,
|
||||
#[serde(default)]
|
||||
src_dirs: Vec<String>,
|
||||
release: Option<u32>,
|
||||
}
|
||||
|
||||
/// Resolves the compile classpath from Gradle and plans a single-file `javac` step.
|
||||
pub fn gradle_compile_file_plan(
|
||||
root: &Path,
|
||||
model: &BuildModel,
|
||||
file: &Path,
|
||||
cache: &Path,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<BuildPlan> {
|
||||
let name = is_java_file(file)?;
|
||||
let (gradle, project, module_dir) = gradle_for_file(root, model, file)
|
||||
.ok_or_else(|| IdeError::not_found("no linked Gradle project found for file"))?;
|
||||
let rel = rel_str(&module_dir, file);
|
||||
let test = is_test_source(&rel);
|
||||
let scope = if test { "test" } else { "main" };
|
||||
|
||||
fs::create_dir_all(cache)?;
|
||||
let init_script = cache.join("gradle-compile-cp.init.gradle");
|
||||
fs::write(&init_script, GRADLE_COMPILE_CP_INIT_SCRIPT)?;
|
||||
let args = vec![
|
||||
"--console=plain".into(),
|
||||
"-q".into(),
|
||||
"-Dorg.gradle.configuration-cache=false".into(),
|
||||
"--init-script".into(),
|
||||
init_script.to_string_lossy().into_owned(),
|
||||
format!("-Popenidea.target={}", project.path),
|
||||
format!("-Popenidea.scope={scope}"),
|
||||
"help".into(),
|
||||
];
|
||||
let gradle_dir = subdir(root, &gradle.dir);
|
||||
let mut reported: Option<String> = None;
|
||||
let out = process::run_bounded(&gradle.command, &args, &gradle_dir, &gradle.env, cancel, |_, line| {
|
||||
if let Some(json) = line.strip_prefix("@openidea-compile-cp\t") {
|
||||
reported = Some(json.to_owned());
|
||||
}
|
||||
})
|
||||
.map_err(|e| {
|
||||
if e.kind == ide_core::error::ErrorKind::Cancelled {
|
||||
e
|
||||
} else {
|
||||
IdeError::internal(format!("cannot resolve the compile classpath: {}", e.message))
|
||||
}
|
||||
})?;
|
||||
if !out.success {
|
||||
let tail: Vec<&str> = out.text.lines().filter(|l| !l.trim().is_empty()).collect();
|
||||
let tail = tail.iter().rev().take(5).rev().cloned().collect::<Vec<_>>().join("\n");
|
||||
return Err(IdeError::internal(format!("cannot resolve the compile classpath:\n{tail}")));
|
||||
}
|
||||
let json = reported.ok_or_else(|| {
|
||||
IdeError::internal(format!(
|
||||
"cannot resolve the compile classpath: Gradle did not report source set '{scope}' for {}",
|
||||
project.path
|
||||
))
|
||||
})?;
|
||||
let cp: GradleCompileCp = serde_json::from_str(&json)
|
||||
.map_err(|e| IdeError::internal(format!("cannot parse Gradle compile classpath: {e}")))?;
|
||||
|
||||
let out_dir = cp
|
||||
.out_dir
|
||||
.filter(|d| !d.trim().is_empty())
|
||||
.map(PathBuf::from)
|
||||
.unwrap_or_else(|| module_dir.join("build/classes/java").join(scope));
|
||||
let mut cp_entries: Vec<String> = Vec::new();
|
||||
if out_dir.is_dir() {
|
||||
cp_entries.push(out_dir.to_string_lossy().into_owned());
|
||||
}
|
||||
if test {
|
||||
let main_out = module_dir.join("build/classes/java/main");
|
||||
if main_out.is_dir() {
|
||||
cp_entries.push(main_out.to_string_lossy().into_owned());
|
||||
}
|
||||
}
|
||||
for sibling in &gradle.projects {
|
||||
let sibling_dir = subdir(root, &sibling.dir);
|
||||
if sibling_dir == module_dir {
|
||||
continue;
|
||||
}
|
||||
let classes = sibling_dir.join("build/classes/java/main");
|
||||
if classes.is_dir() {
|
||||
cp_entries.push(classes.to_string_lossy().into_owned());
|
||||
}
|
||||
}
|
||||
cp_entries.extend(cp.classpath);
|
||||
let classpath = join_classpath(cp_entries);
|
||||
|
||||
let mut sources: Vec<PathBuf> = cp.src_dirs.into_iter().map(PathBuf::from).filter(|p| p.is_dir()).collect();
|
||||
if sources.is_empty() {
|
||||
let fallback: &[&str] = if test { &["src/test/java", "src/main/java"] } else { &["src/main/java"] };
|
||||
sources.extend(fallback.iter().map(|s| module_dir.join(s)).filter(|p| p.is_dir()));
|
||||
}
|
||||
let javac = find_javac(&gradle.env);
|
||||
let release = release_args(cp.release.or(gradle.java_version), java_home_major(&gradle.env));
|
||||
let step =
|
||||
build_javac_step(&javac, &module_dir, &out_dir, &classpath, &sources, release, file, gradle.env.clone())?;
|
||||
Ok(BuildPlan { system: BuildSystem::Gradle, title: format!("Compile {name}"), steps: vec![step] })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -650,8 +371,7 @@ mod tests {
|
||||
#[test]
|
||||
fn target_finds_the_owning_module_and_the_test_scope() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root_buf = dunce::canonicalize(dir.path()).unwrap();
|
||||
let root = root_buf.as_path();
|
||||
let root = dir.path();
|
||||
let model = fixture(root);
|
||||
let main = single_file_target(root, &model, &root.join("app/src/main/java/demo/Main.java")).unwrap();
|
||||
assert_eq!(main.module, root.join("app"));
|
||||
@@ -665,8 +385,7 @@ mod tests {
|
||||
#[test]
|
||||
fn target_rejects_non_java_missing_and_unlinked_files() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root_buf = dunce::canonicalize(dir.path()).unwrap();
|
||||
let root = root_buf.as_path();
|
||||
let root = dir.path();
|
||||
let model = fixture(root);
|
||||
write(root, "app/pom.xml", "<project/>");
|
||||
assert!(single_file_target(root, &model, &root.join("app/pom.xml")).is_err());
|
||||
@@ -678,8 +397,7 @@ mod tests {
|
||||
#[test]
|
||||
fn javac_prefers_the_module_jdk_and_scopes_test_sources() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root_buf = dunce::canonicalize(dir.path()).unwrap();
|
||||
let root = root_buf.as_path();
|
||||
let root = dir.path();
|
||||
let model = fixture(root);
|
||||
let file = root.join("app/src/test/java/demo/MainTest.java");
|
||||
let target = single_file_target(root, &model, &file).unwrap();
|
||||
@@ -715,8 +433,7 @@ mod tests {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root_buf = dunce::canonicalize(dir.path()).unwrap();
|
||||
let root = root_buf.as_path();
|
||||
let root = dir.path();
|
||||
fixture(root);
|
||||
let script = root.join("mvnw");
|
||||
fs::write(
|
||||
@@ -747,7 +464,6 @@ mod tests {
|
||||
assert!(cp.split(separator).count() >= 3, "{cp}");
|
||||
let args = fs::read_to_string(root.join("args.txt")).unwrap();
|
||||
assert!(!args.lines().any(|a| a == "compile" || a == "package"), "{args}");
|
||||
assert!(args.lines().any(|a| a == "-Dmdep.includeScope=compile"), "{args}");
|
||||
fs::create_dir_all(root.join("app/target/test-classes")).unwrap();
|
||||
let target = single_file_target(root, &model, &root.join("app/src/test/java/demo/MainTest.java")).unwrap();
|
||||
let cp = single_file_classpath(root, &model, &target).unwrap();
|
||||
@@ -755,8 +471,6 @@ mod tests {
|
||||
assert_eq!(paths[0], root.join("app/target/test-classes"));
|
||||
assert!(paths.contains(&root.join("app/target/classes")), "{cp}");
|
||||
assert!(!paths.contains(&root.join("lib/target/test-classes")), "{cp}");
|
||||
let args = fs::read_to_string(root.join("args.txt")).unwrap();
|
||||
assert!(args.lines().any(|a| a == "-Dmdep.includeScope=test"), "{args}");
|
||||
}
|
||||
|
||||
/// Launches request Maven's matching scope without adding reactor test outputs.
|
||||
@@ -766,8 +480,7 @@ mod tests {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root_buf = dunce::canonicalize(dir.path()).unwrap();
|
||||
let root = root_buf.as_path();
|
||||
let root = dir.path();
|
||||
fixture(root);
|
||||
let script = root.join("mvnw");
|
||||
fs::write(
|
||||
@@ -816,48 +529,6 @@ mod tests {
|
||||
assert!(args.lines().any(|a| a == "-Dmdep.includeScope=test"), "{args}");
|
||||
}
|
||||
|
||||
/// Modules launched together resolve their classpaths in one Maven probe and leave
|
||||
/// the others' cached; a probe another module breaks still resolves the first one.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn launch_modules_share_one_classpath_probe() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root_buf = dunce::canonicalize(dir.path()).unwrap();
|
||||
let root = root_buf.as_path();
|
||||
fixture(root);
|
||||
write(root, "lib/src/main/java/demo/Lib.java", "class Lib {}");
|
||||
let script = root.join("mvnw");
|
||||
fs::write(
|
||||
&script,
|
||||
"#!/bin/sh\necho \"$@\" >> calls.txt\npl='.'\nwhile [ $# -gt 0 ]; do\nif [ \"$1\" = \"-pl\" ]; then pl=\"$2\"; shift 2; else shift; fi\ndone\ncase \"$pl\" in *lib*) [ -f lib/broken ] && exit 1;; esac\nfor m in $(echo \"$pl\" | tr ',' ' '); do mkdir -p \"$m/target\" repo; touch \"repo/$m.jar\"; printf \"$PWD/repo/$m.jar\" > \"$m/target/ide-compile-cp.txt\"; done\n",
|
||||
)
|
||||
.unwrap();
|
||||
fs::set_permissions(&script, fs::Permissions::from_mode(0o755)).unwrap();
|
||||
let model = crate::load(root, &root.join("cache"), None);
|
||||
let cache = root.join("cache");
|
||||
let cancel = CancellationToken::new();
|
||||
let calls = || fs::read_to_string(root.join("calls.txt")).unwrap_or_default().lines().count();
|
||||
let modules = [root.join("app"), root.join("lib"), root.join("app")];
|
||||
let app = module_classpaths(root, &model, &modules, false, None, &cache, &cancel).unwrap();
|
||||
assert!(app.contains("/repo/app.jar") && !app.contains("repo/lib.jar"), "{app}");
|
||||
assert_eq!(calls(), 1);
|
||||
assert!(fs::read_to_string(root.join("calls.txt")).unwrap().contains("-pl app,lib -am compile"));
|
||||
let lib = module_classpath(root, &model, &root.join("lib"), false, None, &cache, &cancel).unwrap();
|
||||
assert!(lib.contains("/repo/lib.jar"), "{lib}");
|
||||
assert_eq!(calls(), 1, "lib's classpath came from the shared probe");
|
||||
// A probe another module breaks is retried for the first module alone.
|
||||
write(root, "lib/src/main/java/demo/Lib.java", "class Lib { int changed; }");
|
||||
write(root, "lib/broken", "");
|
||||
let app = module_classpaths(root, &model, &[root.join("app"), root.join("lib")], false, None, &cache, &cancel)
|
||||
.unwrap();
|
||||
assert!(app.contains("/repo/app.jar"), "{app}");
|
||||
assert_eq!(calls(), 3, "the shared probe failed, then app was probed alone");
|
||||
// The first module's own failure stays its failure.
|
||||
assert!(module_classpath(root, &model, &root.join("lib"), false, None, &cache, &cancel).is_err());
|
||||
}
|
||||
|
||||
/// The launch classpath follows the Maven runner JDK and is reused until that
|
||||
/// build input changes; the probe does not run packaging plugins.
|
||||
#[cfg(unix)]
|
||||
@@ -866,8 +537,7 @@ mod tests {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root_buf = dunce::canonicalize(dir.path()).unwrap();
|
||||
let root = root_buf.as_path();
|
||||
let root = dir.path();
|
||||
fixture(root);
|
||||
let script = root.join("mvnw");
|
||||
// `dependency:build-classpath` reports reactor outputs as absolute paths. Keep
|
||||
@@ -933,79 +603,4 @@ mod tests {
|
||||
calls.push('x');
|
||||
assert_eq!(fs::read_to_string(root.join("calls.txt")).unwrap(), calls);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn javac_step_omits_empty_classpath_and_uses_source_target_on_jdk_8() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root_buf = dunce::canonicalize(dir.path()).unwrap();
|
||||
let root = root_buf.as_path();
|
||||
let mut model = fixture(root);
|
||||
let file = root.join("app/src/main/java/demo/Main.java");
|
||||
let jdk8 = root.join("jdk8");
|
||||
fs::create_dir_all(jdk8.join("bin")).unwrap();
|
||||
fs::write(jdk8.join("release"), "JAVA_VERSION=\"1.8.0_372\"\n").unwrap();
|
||||
let project = model.maven.as_mut().unwrap().projects.iter_mut().find(|p| p.dir == "app").unwrap();
|
||||
project.java_version = Some(8);
|
||||
let mut target = single_file_target(root, &model, &file).unwrap();
|
||||
target.top.env.insert("JAVA_HOME".into(), jdk8.to_string_lossy().into_owned());
|
||||
let step = javac_step(&target, &file, "", "javac").unwrap();
|
||||
assert!(!step.args.iter().any(|a| a == "-cp"), "{:?}", step.args);
|
||||
assert!(step.args.iter().any(|a| a == "-g"), "{:?}", step.args);
|
||||
assert!(step.args.windows(4).any(|w| w == ["-source", "1.8", "-target", "1.8"]), "{:?}", step.args);
|
||||
assert!(!step.args.iter().any(|a| a == "--release"), "{:?}", step.args);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn gradle_single_file_compiles_with_source_set_classpath_and_siblings() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root_buf = dunce::canonicalize(dir.path()).unwrap();
|
||||
let root = root_buf.as_path();
|
||||
write(root, "settings.gradle", "include ':lib', ':app'");
|
||||
write(root, "lib/build.gradle", "plugins { id 'java' }");
|
||||
write(root, "app/build.gradle", "plugins { id 'java' }");
|
||||
write(root, "app/src/main/java/demo/App.java", "package demo; class App {}");
|
||||
write(root, "app/src/test/java/demo/AppTest.java", "package demo; class AppTest {}");
|
||||
fs::create_dir_all(root.join("lib/build/classes/java/main")).unwrap();
|
||||
fs::create_dir_all(root.join("app/build/classes/java/main")).unwrap();
|
||||
let wrapper = root.join("gradlew");
|
||||
fs::write(
|
||||
&wrapper,
|
||||
"#!/bin/sh\nprintf '%s\\n' \"$@\" > gradle_args.txt\nscope='main'\nfor a in \"$@\"; do\ncase \"$a\" in -Popenidea.scope=*) scope=\"${a#-Popenidea.scope=}\" ;; esac\ndone\nprintf '@openidea-compile-cp\\t{\"outDir\":\"%s/app/build/classes/java/%s\",\"classpath\":[\"%s/deps/guava.jar\"],\"srcDirs\":[\"%s/app/src/%s/java\"],\"release\":17}\\n' \"$PWD\" \"$scope\" \"$PWD\" \"$PWD\" \"$scope\"\n",
|
||||
)
|
||||
.unwrap();
|
||||
fs::set_permissions(&wrapper, fs::Permissions::from_mode(0o755)).unwrap();
|
||||
|
||||
let model = crate::load(root, &root.join("cache"), None);
|
||||
let cache = root.join("cache");
|
||||
let cancel = CancellationToken::new();
|
||||
|
||||
let main_file = root.join("app/src/main/java/demo/App.java");
|
||||
let main_plan = gradle_compile_file_plan(root, &model, &main_file, &cache, &cancel).unwrap();
|
||||
assert_eq!(main_plan.system, BuildSystem::Gradle);
|
||||
assert_eq!(main_plan.title, "Compile App.java");
|
||||
let step = &main_plan.steps[0];
|
||||
let args = fs::read_to_string(root.join("gradle_args.txt")).unwrap();
|
||||
assert!(args.lines().any(|a| a == "-Popenidea.target=:app"), "{args}");
|
||||
assert!(args.lines().any(|a| a == "-Popenidea.scope=main"), "{args}");
|
||||
let cp = &step.args[step.args.iter().position(|a| a == "-cp").unwrap() + 1];
|
||||
let paths: Vec<_> = std::env::split_paths(cp).collect();
|
||||
assert!(paths.contains(&root.join("app/build/classes/java/main")), "{cp}");
|
||||
assert!(paths.contains(&root.join("lib/build/classes/java/main")), "{cp}");
|
||||
assert!(paths.contains(&root.join("deps/guava.jar")), "{cp}");
|
||||
assert!(step.args.windows(2).any(|w| w == ["--release", "17"]), "{:?}", step.args);
|
||||
assert!(step.args.iter().any(|a| a == "-implicit:none"), "{:?}", step.args);
|
||||
|
||||
let test_file = root.join("app/src/test/java/demo/AppTest.java");
|
||||
let test_plan = gradle_compile_file_plan(root, &model, &test_file, &cache, &cancel).unwrap();
|
||||
assert_eq!(test_plan.title, "Compile AppTest.java");
|
||||
let test_step = &test_plan.steps[0];
|
||||
let args = fs::read_to_string(root.join("gradle_args.txt")).unwrap();
|
||||
assert!(args.lines().any(|a| a == "-Popenidea.scope=test"), "{args}");
|
||||
assert!(
|
||||
test_step.args.windows(2).any(|w| w == ["-d", &root.join("app/build/classes/java/test").to_string_lossy()])
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -162,6 +162,16 @@ fn classpath(entries: &[String]) -> String {
|
||||
entries.join(if cfg!(windows) { ";" } else { ":" })
|
||||
}
|
||||
|
||||
/// `--release N` from JDK 9 on; older compilers only know `-source` / `-target`.
|
||||
fn release_args(level: Option<u32>, jdk: Option<&StructureJdk>) -> Vec<String> {
|
||||
let Some(level) = level else { return Vec::new() };
|
||||
if jdk.is_none_or(|j| j.major >= 9) {
|
||||
vec!["--release".into(), level.to_string()]
|
||||
} else {
|
||||
vec!["-source".into(), format!("1.{level}"), "-target".into(), format!("1.{level}")]
|
||||
}
|
||||
}
|
||||
|
||||
/// `"17"`, `"1.8"`, `"JDK_17"` → the release number.
|
||||
pub fn language_release(level: &str) -> Option<u32> {
|
||||
let digits = level.trim().trim_start_matches("JDK_").trim_start_matches("jdk").replace('_', ".");
|
||||
@@ -169,25 +179,6 @@ pub fn language_release(level: &str) -> Option<u32> {
|
||||
digits.split(['.', ' ']).next()?.parse().ok().filter(|n| *n > 0)
|
||||
}
|
||||
|
||||
fn structure_compiler(
|
||||
root: &Path,
|
||||
ps: &ProjectStructureSettings,
|
||||
jdk: Option<&StructureJdk>,
|
||||
language_level: &str,
|
||||
) -> (Option<u32>, BTreeMap<String, String>, String) {
|
||||
let module = root_module(root, ps);
|
||||
let level = module
|
||||
.map(|m| m.language_level.as_str())
|
||||
.filter(|l| !l.trim().is_empty())
|
||||
.or(Some(language_level))
|
||||
.and_then(language_release);
|
||||
let env: BTreeMap<String, String> = jdk
|
||||
.map(|j| BTreeMap::from([("JAVA_HOME".to_owned(), j.home.to_string_lossy().into_owned())]))
|
||||
.unwrap_or_default();
|
||||
let javac = find_javac(&env);
|
||||
(level, env, javac)
|
||||
}
|
||||
|
||||
/// The Build / Rebuild plan of a project without a build tool, or `None` when it has no
|
||||
/// Java sources under its source roots. `language_level`: the project's, unless the module
|
||||
/// overrides it. Writes the javac argument files below `cache`.
|
||||
@@ -212,7 +203,16 @@ pub fn structure_plan(
|
||||
return Ok(None);
|
||||
}
|
||||
let (main_out, test_out) = structure_outputs(root, ps);
|
||||
let (level, env, javac) = structure_compiler(root, ps, jdk, language_level);
|
||||
let module = root_module(root, ps);
|
||||
let level = module
|
||||
.map(|m| m.language_level.as_str())
|
||||
.filter(|l| !l.trim().is_empty())
|
||||
.or(Some(language_level))
|
||||
.and_then(language_release);
|
||||
let env: BTreeMap<String, String> = jdk
|
||||
.map(|j| BTreeMap::from([("JAVA_HOME".to_owned(), j.home.to_string_lossy().into_owned())]))
|
||||
.unwrap_or_default();
|
||||
let javac = find_javac(&env);
|
||||
let args_dir = cache.join("javac");
|
||||
fs::create_dir_all(&args_dir)
|
||||
.map_err(|e| IdeError::internal(format!("cannot create {} ({e})", args_dir.display())))?;
|
||||
@@ -241,7 +241,7 @@ pub fn structure_plan(
|
||||
if !cp.is_empty() {
|
||||
step.args.extend(["-cp".into(), classpath(cp)]);
|
||||
}
|
||||
step.args.extend(single::release_args(level, jdk.map(|j| j.major)));
|
||||
step.args.extend(release_args(level, jdk));
|
||||
step.args.push(format!("@{}", args_file.to_string_lossy()));
|
||||
step.env = env.clone();
|
||||
step.mkdirs = vec![out.to_path_buf()];
|
||||
@@ -281,47 +281,6 @@ pub fn structure_plan(
|
||||
Ok(Some(BuildPlan { system: BuildSystem::Javac, title: module_name(root), steps }))
|
||||
}
|
||||
|
||||
/// Single-file `javac` plan for a Java project without a build tool (Project Structure).
|
||||
pub fn structure_compile_file_plan(
|
||||
root: &Path,
|
||||
ps: &ProjectStructureSettings,
|
||||
roots: &StructureRoots,
|
||||
jdk: Option<&StructureJdk>,
|
||||
language_level: &str,
|
||||
file: &Path,
|
||||
) -> IdeResult<BuildPlan> {
|
||||
let name = single::is_java_file(file)?;
|
||||
let rel = rel_str(root, file);
|
||||
let test = if roots.tests.is_empty() {
|
||||
single::is_test_source(&rel)
|
||||
} else {
|
||||
let file_norm = normalize(file);
|
||||
roots.tests.iter().any(|t| file_norm.starts_with(normalize(t)))
|
||||
};
|
||||
let (main_out, test_out) = structure_outputs(root, ps);
|
||||
let out_dir = if test { &test_out } else { &main_out };
|
||||
let mut cp: Vec<String> = Vec::new();
|
||||
if test && test_out.is_dir() {
|
||||
cp.push(test_out.to_string_lossy().into_owned());
|
||||
}
|
||||
if main_out.is_dir() {
|
||||
cp.push(main_out.to_string_lossy().into_owned());
|
||||
}
|
||||
cp.extend(library_entries(root, ps, test));
|
||||
let cp = single::join_classpath(cp);
|
||||
|
||||
let mut src_roots: Vec<PathBuf> = Vec::new();
|
||||
if test {
|
||||
src_roots.extend(roots.tests.iter().filter(|p| p.is_dir()).cloned());
|
||||
}
|
||||
src_roots.extend(roots.sources.iter().filter(|p| p.is_dir()).cloned());
|
||||
|
||||
let (level, env, javac) = structure_compiler(root, ps, jdk, language_level);
|
||||
let release = single::release_args(level, jdk.map(|j| j.major));
|
||||
let step = single::build_javac_step(&javac, root, out_dir, &cp, &src_roots, release, file, env)?;
|
||||
Ok(BuildPlan { system: BuildSystem::Javac, title: format!("Compile {name}"), steps: vec![step] })
|
||||
}
|
||||
|
||||
/// Where an artifact goes: its output folder, else `out/artifacts/<name>`.
|
||||
pub fn artifact_output(root: &Path, artifact: &ArtifactConfig) -> PathBuf {
|
||||
resolve_dir(root, &artifact.output_directory)
|
||||
@@ -1049,99 +1008,4 @@ mod tests {
|
||||
layout(&["a.jar"]).run(&CancellationToken::new()).unwrap();
|
||||
assert!(project.join("c.jar").is_file());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plans_single_file_javac_for_main_test_and_jdk8() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path().join("shop");
|
||||
write(&root.join("src/com/a/Main.java"), "package com.a; class Main {}");
|
||||
write(&root.join("test/com/a/MainTest.java"), "package com.a; class MainTest {}");
|
||||
write(&root.join("out/production/shop/com/a/Helper.class"), "");
|
||||
let ps = ProjectStructureSettings {
|
||||
libraries: vec![
|
||||
ProjectLibrary { name: "core".into(), classes: vec!["lib/core.jar".into()], ..Default::default() },
|
||||
ProjectLibrary {
|
||||
name: "junit".into(),
|
||||
classes: vec!["lib/junit.jar".into()],
|
||||
scope: DependencyScope::Test,
|
||||
..Default::default()
|
||||
},
|
||||
],
|
||||
..Default::default()
|
||||
};
|
||||
let roots =
|
||||
StructureRoots { sources: vec![root.join("src")], tests: vec![root.join("test")], ..Default::default() };
|
||||
|
||||
let jdk21 = StructureJdk { home: PathBuf::from("/jdk21"), major: 21 };
|
||||
let main_plan =
|
||||
structure_compile_file_plan(&root, &ps, &roots, Some(&jdk21), "17", &root.join("src/com/a/Main.java"))
|
||||
.unwrap();
|
||||
assert_eq!(main_plan.system, BuildSystem::Javac);
|
||||
assert_eq!(main_plan.title, "Compile Main.java");
|
||||
let main_step = &main_plan.steps[0];
|
||||
let cp = &main_step.args[main_step.args.iter().position(|a| a == "-cp").unwrap() + 1];
|
||||
assert!(cp.contains("core.jar") && !cp.contains("junit.jar"), "{cp}");
|
||||
assert!(main_step.args.windows(2).any(|w| w == ["--release", "17"]));
|
||||
assert!(main_step.args.iter().any(|a| a == "-implicit:none"));
|
||||
|
||||
let jdk8 = StructureJdk { home: PathBuf::from("/jdk8"), major: 8 };
|
||||
let test_plan =
|
||||
structure_compile_file_plan(&root, &ps, &roots, Some(&jdk8), "8", &root.join("test/com/a/MainTest.java"))
|
||||
.unwrap();
|
||||
let test_step = &test_plan.steps[0];
|
||||
let test_cp = &test_step.args[test_step.args.iter().position(|a| a == "-cp").unwrap() + 1];
|
||||
assert!(test_cp.contains("out/production/shop") || test_cp.contains("out\\production\\shop"), "{test_cp}");
|
||||
assert!(test_cp.contains("junit.jar"), "{test_cp}");
|
||||
assert!(test_step.args.windows(4).any(|w| w == ["-source", "1.8", "-target", "1.8"]));
|
||||
assert!(test_step.args.windows(2).any(|w| w[0] == "-d" && Path::new(&w[1]).ends_with("out/test/shop")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compiles_only_the_target_java_file_and_reports_errors() {
|
||||
let exe = if cfg!(windows) { "javac.exe" } else { "javac" };
|
||||
if !std::process::Command::new(exe).arg("-version").output().is_ok_and(|o| o.status.success()) {
|
||||
return;
|
||||
}
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap().join("demo");
|
||||
let good = root.join("src/p/Good.java");
|
||||
let broken_sibling = root.join("src/p/BrokenSibling.java");
|
||||
let bad_target = root.join("src/p/BadTarget.java");
|
||||
write(&good, "package p;\npublic class Good { public static int ok() { return 1; } }\n");
|
||||
write(&broken_sibling, "package p;\npublic class BrokenSibling { MissingType field; }\n");
|
||||
write(&bad_target, "package p;\npublic class BadTarget {\n UnknownSymbol field;\n}\n");
|
||||
|
||||
let ps = ProjectStructureSettings::default();
|
||||
let roots = StructureRoots { sources: vec![root.join("src")], ..Default::default() };
|
||||
let cancel = CancellationToken::new();
|
||||
|
||||
// 1. Valid file compiles cleanly without touching or failing on BrokenSibling.java.
|
||||
let plan = structure_compile_file_plan(&root, &ps, &roots, None, "", &good).unwrap();
|
||||
let events = std::sync::Mutex::new(Vec::new());
|
||||
let result = run(&root, &plan, &cancel, &|e| events.lock().unwrap().push(e)).unwrap();
|
||||
assert!(result.success, "expected single-file compile to succeed: {:?}", result.messages);
|
||||
assert_eq!(result.errors, 0);
|
||||
assert!(root.join("out/production/demo/p/Good.class").is_file());
|
||||
assert!(!root.join("out/production/demo/p/BrokenSibling.class").exists());
|
||||
|
||||
// 2. Broken target fails, streams raw compiler output, and produces structured diagnostics.
|
||||
let plan = structure_compile_file_plan(&root, &ps, &roots, None, "", &bad_target).unwrap();
|
||||
let bad_events = std::sync::Mutex::new(Vec::new());
|
||||
let bad_result = run(&root, &plan, &cancel, &|e| bad_events.lock().unwrap().push(e)).unwrap();
|
||||
assert!(!bad_result.success);
|
||||
assert!(bad_result.errors >= 1, "{bad_result:?}");
|
||||
assert!(
|
||||
bad_events.lock().unwrap().iter().any(|e| matches!(e, BuildEvent::Output { .. })),
|
||||
"expected streamed output"
|
||||
);
|
||||
assert!(
|
||||
bad_result.messages.iter().any(|m| {
|
||||
m.severity == Severity::Error
|
||||
&& m.path.as_ref().is_some_and(|p| <ide_core::IpcPath as AsRef<Path>>::as_ref(p) == bad_target)
|
||||
&& m.range.is_some_and(|r| r.start.line == 2)
|
||||
}),
|
||||
"messages={:?}",
|
||||
bad_result.messages
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,58 +0,0 @@
|
||||
// OpenIDEA single-file javac classpath probe for Gradle projects.
|
||||
// Prints the target source set's output directory, compile classpath, source dirs and release version.
|
||||
import groovy.json.JsonOutput
|
||||
|
||||
def identity = { Project p -> try { p.identityPath.toString() } catch (ignored) { p.path } }
|
||||
|
||||
gradle.projectsEvaluated { g ->
|
||||
def wantedTarget = g.rootProject.findProperty('openidea.target')?.toString() ?: ':'
|
||||
def scope = g.rootProject.findProperty('openidea.scope')?.toString() ?: 'main'
|
||||
def project = g.rootProject.allprojects.find { identity(it) == wantedTarget }
|
||||
if (project == null && g.parent == null) {
|
||||
project = g.rootProject.allprojects.find { it.path == wantedTarget }
|
||||
}
|
||||
if (project == null) return
|
||||
|
||||
def sets = project.extensions.findByName('sourceSets') ?: project.findProperty('sourceSets')
|
||||
def ss = sets?.findByName(scope)
|
||||
if (ss == null) return
|
||||
|
||||
def outDir = null
|
||||
try { outDir = ss.java.destinationDirectory.get().asFile.canonicalPath } catch (ignored) {}
|
||||
if (outDir == null) {
|
||||
try { outDir = ss.output.classesDirs.files.iterator().next().canonicalPath } catch (ignored) {}
|
||||
}
|
||||
|
||||
def cp = []
|
||||
if (scope == 'test') {
|
||||
def mainSet = sets.findByName('main')
|
||||
try { mainSet?.output?.classesDirs?.files?.each { cp << it.canonicalPath } } catch (ignored) {}
|
||||
}
|
||||
try { ss.compileClasspath.files.each { cp << it.canonicalPath } } catch (ignored) {}
|
||||
cp = cp.unique()
|
||||
|
||||
def srcDirs = []
|
||||
try { ss.java.srcDirs.each { srcDirs << it.canonicalPath } } catch (ignored) {}
|
||||
if (scope == 'test') {
|
||||
def mainSet = sets.findByName('main')
|
||||
try { mainSet?.java?.srcDirs?.each { srcDirs << it.canonicalPath } } catch (ignored) {}
|
||||
}
|
||||
srcDirs = srcDirs.unique()
|
||||
|
||||
def release = null
|
||||
try {
|
||||
def compileTask = project.tasks.findByName(ss.compileJavaTaskName)
|
||||
release = compileTask?.options?.release?.getOrNull()
|
||||
} catch (ignored) {}
|
||||
if (release == null) {
|
||||
try {
|
||||
def java = project.extensions.findByName('java')
|
||||
def lv = null
|
||||
try { lv = java?.toolchain?.languageVersion?.getOrNull() } catch (ignored) {}
|
||||
def target = java != null ? java.targetCompatibility : project.findProperty('targetCompatibility')
|
||||
release = lv != null ? lv.asInt() : (target?.majorVersion as Integer)
|
||||
} catch (ignored) {}
|
||||
}
|
||||
|
||||
println '@openidea-compile-cp\t' + JsonOutput.toJson([outDir: outDir, classpath: cp, srcDirs: srcDirs, release: release])
|
||||
}
|
||||
@@ -16,7 +16,6 @@ mod process;
|
||||
#[cfg(test)]
|
||||
mod process_numbers;
|
||||
pub mod sbt;
|
||||
pub mod surefire;
|
||||
mod sync;
|
||||
pub mod web;
|
||||
mod xml;
|
||||
@@ -83,23 +82,11 @@ pub fn load_linked(
|
||||
maven_repo: Option<PathBuf>,
|
||||
settings: &ide_core::settings::MavenSettings,
|
||||
gradle_settings: &ide_core::settings::GradleSettings,
|
||||
) -> BuildModel {
|
||||
load_linked_with_jdk(root, cache_dir, maven_repo, settings, gradle_settings, None)
|
||||
}
|
||||
|
||||
/// [`load_linked`] with the JDK Maven runs on, for JDK-activated Maven profiles.
|
||||
pub fn load_linked_with_jdk(
|
||||
root: &Path,
|
||||
cache_dir: &Path,
|
||||
maven_repo: Option<PathBuf>,
|
||||
settings: &ide_core::settings::MavenSettings,
|
||||
gradle_settings: &ide_core::settings::GradleSettings,
|
||||
maven_jdk_version: Option<u32>,
|
||||
) -> BuildModel {
|
||||
let maven = maven::has_projects(root, settings).then(|| {
|
||||
let profiles = settings.profiles(&sync::maven_profiles(cache_dir));
|
||||
let repo = maven_repo.or_else(maven::default_local_repo);
|
||||
let mut m = maven::load_with_linked_jdk(root, repo, &profiles, maven_jdk_version, &settings.linked_projects);
|
||||
let mut m = maven::load_with_linked(root, repo, &profiles, &settings.linked_projects);
|
||||
maven::UnlinkedProjects::from_model(&m, settings).filter(&mut m);
|
||||
// The user settings' profiles can be chosen too (`-P` applies to them as well).
|
||||
for p in maven::user_settings_file(root, settings).map(|f| maven::settings_profiles(&f)).unwrap_or_default() {
|
||||
|
||||
+112
-1047
File diff suppressed because it is too large.
Load diff
@@ -3,13 +3,7 @@
|
||||
use super::MavenProject;
|
||||
use crate::process;
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult};
|
||||
use std::collections::HashSet;
|
||||
use std::fs::{self, File};
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
use std::time::SystemTime;
|
||||
|
||||
const DEPENDENCY_PLUGIN: &str = "org.apache.maven.plugins:maven-dependency-plugin:3.8.1";
|
||||
const SOURCE_REFRESH_WORKERS: usize = 4;
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub struct Artifact {
|
||||
@@ -17,29 +11,6 @@ pub struct Artifact {
|
||||
pub name: String,
|
||||
pub version: String,
|
||||
pub sources: PathBuf,
|
||||
binary: PathBuf,
|
||||
}
|
||||
|
||||
fn valid_part(part: &str) -> bool {
|
||||
!part.is_empty()
|
||||
&& part != "."
|
||||
&& part != ".."
|
||||
&& part.chars().all(|c| c.is_ascii_alphanumeric() || "_.-".contains(c))
|
||||
}
|
||||
|
||||
fn modified_file(path: &Path) -> Option<SystemTime> {
|
||||
let metadata = fs::metadata(path).ok()?;
|
||||
if metadata.is_file() { metadata.modified().ok() } else { None }
|
||||
}
|
||||
|
||||
impl Artifact {
|
||||
fn stale_binary(&self) -> Option<SystemTime> {
|
||||
if !self.version.ends_with("-SNAPSHOT") {
|
||||
return None;
|
||||
}
|
||||
let binary = modified_file(&self.binary)?;
|
||||
(modified_file(&self.sources)? < binary).then_some(binary)
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolve only jars inside the selected local repository, including custom repositories.
|
||||
@@ -57,14 +28,16 @@ pub fn artifact(jar: &Path, repository: &Path) -> Option<Artifact> {
|
||||
}
|
||||
let n = parts.len();
|
||||
let (name, version, file) = (parts[n - 3], parts[n - 2], parts[n - 1]);
|
||||
if !parts[..n - 1].iter().all(|s| valid_part(s)) || file != format!("{name}-{version}.jar") {
|
||||
let valid = |s: &str| {
|
||||
!s.is_empty() && s != "." && s != ".." && s.chars().all(|c| c.is_ascii_alphanumeric() || "_.-".contains(c))
|
||||
};
|
||||
if !parts[..n - 1].iter().all(|s| valid(s)) || file != format!("{name}-{version}.jar") {
|
||||
return None;
|
||||
}
|
||||
Some(Artifact {
|
||||
group: parts[..n - 3].join("."),
|
||||
name: name.into(),
|
||||
version: version.into(),
|
||||
binary: jar.to_owned(),
|
||||
sources: jar.with_file_name(format!("{name}-{version}-sources.jar")),
|
||||
})
|
||||
}
|
||||
@@ -75,58 +48,26 @@ pub fn download(
|
||||
artifact: &Artifact,
|
||||
repository: &Path,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<Option<PathBuf>> {
|
||||
resolve(root, project, artifact, repository, &[], artifact.stale_binary(), cancel)
|
||||
}
|
||||
|
||||
fn resolve(
|
||||
root: &Path,
|
||||
project: &MavenProject,
|
||||
artifact: &Artifact,
|
||||
repository: &Path,
|
||||
profile_args: &[String],
|
||||
stale: Option<SystemTime>,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<Option<PathBuf>> {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
if stale.is_none() && artifact.sources.is_file() {
|
||||
if artifact.sources.is_file() {
|
||||
return Ok(Some(artifact.sources.clone()));
|
||||
}
|
||||
let mut args = vec!["-B".into(), "-N".into(), "-Dstyle.color=never".into()];
|
||||
args.extend(project.options.iter().cloned());
|
||||
args.extend(profile_args.iter().cloned());
|
||||
args.push(format!("-Dmaven.repo.local={}", repository.display()));
|
||||
let coordinate = format!("-Dartifact={}:{}:{}:jar:sources", artifact.group, artifact.name, artifact.version);
|
||||
let stage = if let Some(binary) = stale {
|
||||
// Keep the existing attachment readable while Maven resolves the timestamped snapshot.
|
||||
// Disable Resolver's in-place copy to the base -SNAPSHOT filename.
|
||||
let stage =
|
||||
tempfile::Builder::new().prefix(".openidea-sources-").tempdir_in(artifact.sources.parent().unwrap())?;
|
||||
args.extend([
|
||||
"-U".into(),
|
||||
"-Daether.artifactResolver.snapshotNormalization=false".into(),
|
||||
format!("{DEPENDENCY_PLUGIN}:copy"),
|
||||
coordinate,
|
||||
"-Dmdep.useBaseVersion=true".into(),
|
||||
format!("-DoutputDirectory={}", stage.path().display()),
|
||||
]);
|
||||
Some((stage, binary))
|
||||
} else {
|
||||
args.extend([format!("{DEPENDENCY_PLUGIN}:get"), coordinate, "-Dtransitive=false".into()]);
|
||||
None
|
||||
};
|
||||
args.extend(project.options.clone());
|
||||
args.extend([
|
||||
format!("-Dmaven.repo.local={}", repository.display()),
|
||||
"org.apache.maven.plugins:maven-dependency-plugin:3.8.1:get".into(),
|
||||
format!("-Dartifact={}:{}:{}:jar:sources", artifact.group, artifact.name, artifact.version),
|
||||
"-Dtransitive=false".into(),
|
||||
]);
|
||||
let output = process::run(&project.command, &args, &root.join(&project.dir), &project.env, cancel, |_, _| {})?;
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
if let Some((stage, binary)) = stage {
|
||||
let resolved = stage.path().join(artifact.sources.file_name().unwrap());
|
||||
if output.success && resolved.is_file() {
|
||||
return replace_stale_sources(artifact, &resolved, binary, cancel);
|
||||
}
|
||||
} else if artifact.sources.is_file() {
|
||||
if artifact.sources.is_file() {
|
||||
return Ok(Some(artifact.sources.clone()));
|
||||
}
|
||||
let coordinate = format!("{}:{}:jar:sources:{}", artifact.group, artifact.name, artifact.version);
|
||||
@@ -142,115 +83,6 @@ fn resolve(
|
||||
))
|
||||
}
|
||||
|
||||
fn replace_stale_sources(
|
||||
artifact: &Artifact,
|
||||
resolved: &Path,
|
||||
binary: SystemTime,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<Option<PathBuf>> {
|
||||
// Maven can fall back to a locally installed snapshot. Keep its timestamp if it returned
|
||||
// the same bytes so a later reload can retry when newer sources are available.
|
||||
let hash = |path| -> std::io::Result<_> { Ok(blake3::Hasher::new().update_reader(File::open(path)?)?.finalize()) };
|
||||
if hash(resolved)? == hash(&artifact.sources)? {
|
||||
return Ok(None);
|
||||
}
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
match artifact.stale_binary() {
|
||||
Some(current) if current == binary => {
|
||||
File::options().write(true).open(resolved)?.set_modified(SystemTime::now().max(binary))?;
|
||||
fs::rename(resolved, &artifact.sources)?;
|
||||
Ok(Some(artifact.sources.clone()))
|
||||
}
|
||||
None if artifact.sources.is_file() => Ok(Some(artifact.sources.clone())),
|
||||
_ => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolved Maven dependencies with an existing attachment. Binaries may still be
|
||||
/// updating during import, so freshness is checked when the refresh runs.
|
||||
pub fn cached_snapshots<'a>(
|
||||
repository: &Path,
|
||||
projects: impl Iterator<Item = (usize, &'a MavenProject)>,
|
||||
) -> Vec<(usize, Artifact)> {
|
||||
let mut seen = HashSet::new();
|
||||
let mut candidates = Vec::new();
|
||||
for (owner, project) in projects {
|
||||
let mut dependencies: Vec<_> = project.dependencies.iter().collect();
|
||||
while let Some(dep) = dependencies.pop() {
|
||||
if !dep.resolved() {
|
||||
continue;
|
||||
}
|
||||
dependencies.extend(&dep.children);
|
||||
let Some(version) = dep.version.as_deref().filter(|v| v.ends_with("-SNAPSHOT") && valid_part(v)) else {
|
||||
continue;
|
||||
};
|
||||
if dep.scope == "system"
|
||||
|| dep.classifier.is_some()
|
||||
|| !matches!(dep.kind.as_str(), "jar" | "bundle" | "maven-plugin" | "ejb")
|
||||
|| !valid_part(&dep.artifact_id)
|
||||
|| !dep.group_id.split('.').all(valid_part)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let name = &dep.artifact_id;
|
||||
let jar = repository
|
||||
.join(dep.group_id.replace('.', "/"))
|
||||
.join(name)
|
||||
.join(version)
|
||||
.join(format!("{name}-{version}.jar"));
|
||||
if let Some(artifact) = artifact(&jar, repository)
|
||||
&& artifact.sources.is_file()
|
||||
&& seen.insert(jar)
|
||||
{
|
||||
candidates.push((owner, artifact));
|
||||
}
|
||||
}
|
||||
}
|
||||
candidates
|
||||
}
|
||||
|
||||
/// Refresh only previously attached snapshots. Maven subprocesses are bounded
|
||||
/// and share the build reload's cancellation token.
|
||||
pub fn refresh_snapshots(
|
||||
root: &Path,
|
||||
projects: &[MavenProject],
|
||||
repository: &Path,
|
||||
candidates: &[(usize, Artifact)],
|
||||
profiles: &[String],
|
||||
cancel: &CancellationToken,
|
||||
) -> Vec<PathBuf> {
|
||||
let profile_args = if profiles.is_empty() { vec![] } else { vec![format!("-P{}", profiles.join(","))] };
|
||||
let profile_args = &profile_args;
|
||||
let stale: Vec<_> = candidates.iter().filter(|(_, artifact)| artifact.stale_binary().is_some()).collect();
|
||||
let batch_size = stale.len().div_ceil(SOURCE_REFRESH_WORKERS).max(1);
|
||||
std::thread::scope(|scope| {
|
||||
let workers: Vec<_> = stale
|
||||
.chunks(batch_size)
|
||||
.map(|batch| {
|
||||
scope.spawn(move || {
|
||||
let mut refreshed = Vec::new();
|
||||
for (owner, artifact) in batch.iter().copied() {
|
||||
if cancel.is_cancelled() {
|
||||
break;
|
||||
}
|
||||
let Some(binary) = artifact.stale_binary() else { continue };
|
||||
match resolve(root, &projects[*owner], artifact, repository, profile_args, Some(binary), cancel)
|
||||
{
|
||||
Ok(Some(_)) => refreshed.push(artifact.binary.clone()),
|
||||
Ok(None) => {}
|
||||
Err(e) => tracing::debug!(path = %artifact.sources.display(), "Maven sources refresh: {e}"),
|
||||
}
|
||||
}
|
||||
refreshed
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
workers.into_iter().flat_map(|worker| worker.join().expect("Maven sources worker")).collect()
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -289,86 +121,4 @@ mod tests {
|
||||
assert_eq!(artifact(Path::new(path), repository), None, "{path}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selects_existing_snapshot_attachments_from_the_resolved_tree() {
|
||||
use crate::maven::{MavenDependency, Omission};
|
||||
|
||||
let repo = tempfile::tempdir().unwrap();
|
||||
let dependency = |name: &str, version: &str, cached: bool| {
|
||||
if cached {
|
||||
let dir = repo.path().join("example").join(name).join(version);
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
fs::write(dir.join(format!("{name}-{version}-sources.jar")), b"cached").unwrap();
|
||||
}
|
||||
MavenDependency {
|
||||
group_id: "example".into(),
|
||||
artifact_id: name.into(),
|
||||
version: Some(version.into()),
|
||||
kind: "jar".into(),
|
||||
..Default::default()
|
||||
}
|
||||
};
|
||||
let transitive = dependency("transitive", "1-SNAPSHOT", true);
|
||||
let direct = MavenDependency { children: vec![transitive.clone()], ..dependency("direct", "1-SNAPSHOT", true) };
|
||||
let omitted =
|
||||
MavenDependency { omitted: Some(Omission::Conflict), ..dependency("omitted", "1-SNAPSHOT", true) };
|
||||
let projects = [
|
||||
MavenProject {
|
||||
dependencies: vec![
|
||||
direct,
|
||||
omitted,
|
||||
dependency("missing", "1-SNAPSHOT", false),
|
||||
dependency("release", "1", true),
|
||||
],
|
||||
..Default::default()
|
||||
},
|
||||
MavenProject { dependencies: vec![transitive], ..Default::default() },
|
||||
];
|
||||
let mut found: Vec<_> = cached_snapshots(repo.path(), projects.iter().enumerate())
|
||||
.into_iter()
|
||||
.map(|(owner, artifact)| (owner, artifact.name))
|
||||
.collect();
|
||||
found.sort();
|
||||
assert_eq!(found, [(0, "direct".into()), (0, "transitive".into())]);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn downloads_sources_again_when_the_snapshot_binary_is_newer() {
|
||||
use std::fs::FileTimes;
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
use std::time::Duration;
|
||||
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let repository = dir.path().join("repository");
|
||||
let jar = repository.join("example/lib/1-SNAPSHOT/lib-1-SNAPSHOT.jar");
|
||||
fs::create_dir_all(jar.parent().unwrap()).unwrap();
|
||||
fs::write(&jar, b"new binary").unwrap();
|
||||
let artifact = artifact(&jar, &repository).unwrap();
|
||||
fs::write(&artifact.sources, b"old sources").unwrap();
|
||||
File::open(&artifact.sources)
|
||||
.unwrap()
|
||||
.set_times(FileTimes::new().set_modified(SystemTime::now() - Duration::from_secs(60)))
|
||||
.unwrap();
|
||||
let launcher = dir.path().join("mvn");
|
||||
fs::write(
|
||||
&launcher,
|
||||
"#!/bin/sh\nfor arg do\n case \"$arg\" in\n -DoutputDirectory=*) out=\"${arg#*=}\" ;;\n esac\ndone\nprintf 'new sources' > \"$out/lib-1-SNAPSHOT-sources.jar\"\n",
|
||||
)
|
||||
.unwrap();
|
||||
fs::set_permissions(&launcher, fs::Permissions::from_mode(0o755)).unwrap();
|
||||
let cancel = CancellationToken::new();
|
||||
cancel.cancel();
|
||||
assert!(download(dir.path(), &MavenProject::default(), &artifact, &repository, &cancel).is_err());
|
||||
assert_eq!(fs::read(&artifact.sources).unwrap(), b"old sources");
|
||||
let project = MavenProject { command: launcher.to_string_lossy().into_owned(), ..Default::default() };
|
||||
let cancel = CancellationToken::new();
|
||||
let path = download(dir.path(), &project, &artifact, &repository, &cancel).unwrap().unwrap();
|
||||
assert_eq!(fs::read(&path).unwrap(), b"new sources");
|
||||
assert_eq!(
|
||||
download(dir.path(), &MavenProject::default(), &artifact, &repository, &CancellationToken::new()).unwrap(),
|
||||
Some(path)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -24,21 +24,6 @@ pub(crate) const MAX_LINE_BYTES: usize = 1024 * 1024;
|
||||
/// `Output::text` stops growing past this while the pipes keep draining: a chatty build can
|
||||
/// print far more than is ever parsed back out of the retained copy.
|
||||
pub(crate) const MAX_TEXT_BYTES: usize = 32 * 1024 * 1024;
|
||||
/// Lines the pipe readers may queue ahead of the consumer. A build printing faster than
|
||||
/// `on_line` takes its lines waits on its full pipe, as it would on a terminal, instead of
|
||||
/// the lines piling up in memory (a line is at most [`MAX_LINE_BYTES`] in [`run_bounded`]).
|
||||
const LINE_QUEUE: usize = 64;
|
||||
/// What [`pump_bounded`] reads from a pipe at a time.
|
||||
const PUMP_CHUNK: usize = 64 * 1024;
|
||||
|
||||
/// One line of a child's output, with the stream it came from.
|
||||
type Line = (Stream, String);
|
||||
|
||||
/// The queue from the pipe readers to the consumer: bounded, so the readers wait while the
|
||||
/// consumer is behind.
|
||||
fn line_queue() -> (mpsc::SyncSender<Line>, mpsc::Receiver<Line>) {
|
||||
mpsc::sync_channel(LINE_QUEUE)
|
||||
}
|
||||
|
||||
pub(crate) struct Output {
|
||||
pub success: bool,
|
||||
@@ -48,20 +33,20 @@ pub(crate) struct Output {
|
||||
pub truncated: bool,
|
||||
}
|
||||
|
||||
/// Bounded pump for callers that stream every line and only summarize errors: reads
|
||||
/// [`PUMP_CHUNK`] chunks, splits newline-free runs at a UTF-8 char boundary at the line cap,
|
||||
/// and never grows one line buffer without bound.
|
||||
fn pump_bounded(stream: Box<dyn Read + Send>, kind: Stream, tx: &mpsc::SyncSender<Line>) {
|
||||
/// Bounded pump for callers that stream every line and only summarize errors: reads fixed
|
||||
/// 64 KiB chunks, splits newline-free runs at a UTF-8 char boundary at the line cap, and
|
||||
/// never grows one line buffer without bound.
|
||||
fn pump_bounded(stream: Box<dyn Read + Send>, kind: Stream, tx: &mpsc::Sender<(Stream, String)>) {
|
||||
let mut reader = BufReader::new(stream);
|
||||
// `terminated`: the buffer ends in the stream's newline. A segment cut from a
|
||||
// newline-free run at the line cap must keep a trailing `\r` — it is data.
|
||||
let send = |buf: &mut Vec<u8>, terminated: bool, tx: &mpsc::SyncSender<Line>| {
|
||||
let send = |buf: &mut Vec<u8>, terminated: bool, tx: &mpsc::Sender<(Stream, String)>| {
|
||||
let line = ide_core::output_encoding::decode_tool_output(buf);
|
||||
let line = if terminated { line.trim_end_matches(['\n', '\r']).to_owned() } else { line };
|
||||
buf.clear();
|
||||
tx.send((kind, line)).is_ok()
|
||||
};
|
||||
let mut chunk = vec![0u8; PUMP_CHUNK];
|
||||
let mut chunk = vec![0u8; 64 * 1024];
|
||||
let mut line: Vec<u8> = Vec::with_capacity(256);
|
||||
'read: loop {
|
||||
let n = match reader.read(&mut chunk) {
|
||||
@@ -194,8 +179,8 @@ fn run_with_env_capture(
|
||||
}
|
||||
let mut child =
|
||||
command.spawn().map_err(|e| IdeError::unavailable(format!("cannot start {}: {e}", program.display())))?;
|
||||
let (tx, rx) = line_queue();
|
||||
let pump = |stream: Box<dyn Read + Send>, kind: Stream, tx: mpsc::SyncSender<Line>| {
|
||||
let (tx, rx) = mpsc::channel::<(Stream, String)>();
|
||||
let pump = |stream: Box<dyn Read + Send>, kind: Stream, tx: mpsc::Sender<(Stream, String)>| {
|
||||
std::thread::spawn(move || {
|
||||
if bounded {
|
||||
pump_bounded(stream, kind, &tx);
|
||||
@@ -227,8 +212,7 @@ fn run_with_env_capture(
|
||||
// Retained copy of the output: the first half of the cap, then — once output overflows —
|
||||
// a rolling tail instead of the middle. Error summaries read the end of the output, while
|
||||
// listings parsed out of a successful run read from the start. The pipes keep draining
|
||||
// either way: `on_line` still sees every line, and the child waits on its pipe only
|
||||
// while `on_line` is behind, never because the retained copy is full.
|
||||
// either way: `on_line` still sees every line, so the child never blocks on a full pipe.
|
||||
let cap = MAX_TEXT_BYTES / 2;
|
||||
let mut head = String::new();
|
||||
let mut tail: std::collections::VecDeque<Vec<u8>> = Default::default();
|
||||
@@ -311,9 +295,6 @@ fn run_with_env_capture(
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::time::Instant;
|
||||
|
||||
#[test]
|
||||
fn a_model_line_over_one_mebibyte_is_kept_whole_for_the_parsers() {
|
||||
@@ -519,124 +500,4 @@ mod tests {
|
||||
assert!(out.text.starts_with("pad\n"));
|
||||
assert!(out.text.ends_with("FATAL: the real error\n"));
|
||||
}
|
||||
|
||||
/// Numbered lines of `LINE_LEN` bytes each, counting the bytes taken: a pipe stand-in that
|
||||
/// reports when it is dropped, which is when the pump owning it ends.
|
||||
const LINE_LEN: usize = 100;
|
||||
|
||||
struct NumberedLines {
|
||||
next: usize,
|
||||
lines: usize,
|
||||
taken: Arc<AtomicUsize>,
|
||||
gone: mpsc::Sender<()>,
|
||||
}
|
||||
|
||||
fn numbered(n: usize) -> String {
|
||||
format!("{n:0width$}", width = LINE_LEN - 1)
|
||||
}
|
||||
|
||||
impl Read for NumberedLines {
|
||||
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
|
||||
let mut n = 0;
|
||||
while self.next < self.lines && n + LINE_LEN <= buf.len() {
|
||||
buf[n..n + LINE_LEN - 1].copy_from_slice(numbered(self.next).as_bytes());
|
||||
buf[n + LINE_LEN - 1] = b'\n';
|
||||
self.next += 1;
|
||||
n += LINE_LEN;
|
||||
}
|
||||
self.taken.fetch_add(n, Ordering::SeqCst);
|
||||
Ok(n)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for NumberedLines {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.gone.send(());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_slow_consumer_holds_the_pump_back_instead_of_queueing_every_line() {
|
||||
const LINES: usize = 50_000;
|
||||
let taken = Arc::new(AtomicUsize::new(0));
|
||||
let (gone, _) = mpsc::channel();
|
||||
let pipe = NumberedLines { next: 0, lines: LINES, taken: taken.clone(), gone };
|
||||
let (tx, rx) = line_queue();
|
||||
let pump = std::thread::spawn(move || pump_bounded(Box::new(pipe), Stream::Stdout, &tx));
|
||||
let (mut count, mut peak) = (0usize, 0usize);
|
||||
loop {
|
||||
match rx.recv_timeout(Duration::from_secs(60)) {
|
||||
Ok((stream, line)) => {
|
||||
assert_eq!(stream, Stream::Stdout);
|
||||
assert_eq!(line, numbered(count), "a line arrived out of order or damaged");
|
||||
// Read from the pipe but not yet handed over: the rest of the chunk the pump
|
||||
// is cutting into lines, and the queue.
|
||||
peak = peak.max(taken.load(Ordering::SeqCst) - count * LINE_LEN);
|
||||
count += 1;
|
||||
// A consumer that cannot keep up with the process.
|
||||
if count.is_multiple_of(LINE_QUEUE) {
|
||||
std::thread::sleep(Duration::from_millis(1));
|
||||
}
|
||||
}
|
||||
Err(mpsc::RecvTimeoutError::Disconnected) => break,
|
||||
Err(mpsc::RecvTimeoutError::Timeout) => panic!("the pump stalled"),
|
||||
}
|
||||
}
|
||||
pump.join().unwrap();
|
||||
assert_eq!(count, LINES);
|
||||
let bound = PUMP_CHUNK + (LINE_QUEUE + 2) * LINE_LEN;
|
||||
assert!(peak <= bound, "{peak} bytes read ahead of the consumer, more than {bound}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pump_blocked_on_a_full_queue_ends_when_the_consumer_is_gone() {
|
||||
let taken = Arc::new(AtomicUsize::new(0));
|
||||
let (gone_tx, gone) = mpsc::channel();
|
||||
// Far more than the queue and a few chunks hold.
|
||||
let pipe = NumberedLines { next: 0, lines: 100_000, taken: taken.clone(), gone: gone_tx };
|
||||
let (tx, rx) = line_queue();
|
||||
let pump = std::thread::spawn(move || pump_bounded(Box::new(pipe), Stream::Stdout, &tx));
|
||||
// A consumer that takes nothing: the queue fills, with the pump inside its first chunk.
|
||||
let deadline = Instant::now() + Duration::from_secs(30);
|
||||
while taken.load(Ordering::SeqCst) == 0 {
|
||||
assert!(Instant::now() < deadline, "the pump never read");
|
||||
std::thread::sleep(Duration::from_millis(1));
|
||||
}
|
||||
// Time for a pump that does not wait to run ahead.
|
||||
std::thread::sleep(Duration::from_millis(100));
|
||||
assert!(taken.load(Ordering::SeqCst) <= PUMP_CHUNK, "the pump read past a full queue");
|
||||
assert!(gone.try_recv().is_err(), "the pump ended while its consumer was still there");
|
||||
drop(rx);
|
||||
gone.recv_timeout(Duration::from_secs(30)).expect("the pump stayed blocked after the consumer was gone");
|
||||
pump.join().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_slow_on_line_still_sees_every_line_in_order_and_the_exit_status() {
|
||||
if cfg!(windows) {
|
||||
return;
|
||||
}
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let args = ["-c".into(), "awk 'BEGIN{for(i=1;i<=300000;i++)print i}'; exit 4".into()];
|
||||
for bounded in [false, true] {
|
||||
let mut next = 1usize;
|
||||
let on_line = |stream: Stream, line: &str| {
|
||||
assert_eq!(stream, Stream::Stdout);
|
||||
assert_eq!(line, next.to_string());
|
||||
next += 1;
|
||||
if next.is_multiple_of(1000) {
|
||||
std::thread::sleep(Duration::from_millis(1));
|
||||
}
|
||||
};
|
||||
let cancel = CancellationToken::new();
|
||||
let out = if bounded {
|
||||
run_bounded("sh", &args, tmp.path(), &BTreeMap::new(), &cancel, on_line)
|
||||
} else {
|
||||
run("sh", &args, tmp.path(), &BTreeMap::new(), &cancel, on_line)
|
||||
}
|
||||
.unwrap();
|
||||
assert!(!out.success);
|
||||
assert_eq!(next, 300_001, "lines were lost");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,216 +0,0 @@
|
||||
//! A Maven module's Surefire configuration, for test runs OpenIDEA starts itself instead of
|
||||
//! Surefire (IDEA's `MavenJUnitPatcher`): what the forked test JVM would get from the POM.
|
||||
//!
|
||||
//! Read from the effective POM the last sync cached (Maven merged parents, profiles and
|
||||
//! `pluginManagement` there), else from the module's own `pom.xml` and its `<properties>`.
|
||||
|
||||
use crate::maven::{MavenModel, interpolate};
|
||||
use crate::xml::{self, Element};
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::path::Path;
|
||||
|
||||
const SUREFIRE: &str = "maven-surefire-plugin";
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct SurefireConfig {
|
||||
/// `<argLine>`, split into JVM options.
|
||||
pub arg_line: Vec<String>,
|
||||
/// `<systemPropertyVariables>` and the older `<systemProperties>`.
|
||||
pub system_properties: BTreeMap<String, String>,
|
||||
/// `<environmentVariables>`.
|
||||
pub environment: BTreeMap<String, String>,
|
||||
pub working_directory: Option<String>,
|
||||
/// `<additionalClasspathElements>`.
|
||||
pub additional_classpath: Vec<String>,
|
||||
/// `<classpathDependencyExcludes>`: `groupId:artifactId`.
|
||||
pub classpath_excludes: Vec<String>,
|
||||
}
|
||||
|
||||
/// The Surefire configuration of the Maven module at `module` (absolute), if it is one.
|
||||
pub fn surefire_config(root: &Path, cache_dir: &Path, model: &MavenModel, module: &Path) -> Option<SurefireConfig> {
|
||||
let same = |a: &Path, b: &Path| dunce::canonicalize(a).ok() == dunce::canonicalize(b).ok();
|
||||
let project = model.projects.iter().find(|p| same(&root.join(&p.dir), module))?;
|
||||
let pom = root.join(&project.pom);
|
||||
let modified = |p: &Path| std::fs::metadata(p).and_then(|m| m.modified()).ok();
|
||||
// A cache written before the POM last changed would apply an old configuration.
|
||||
let effective = std::fs::read_dir(cache_dir).ok()?.flatten().map(|e| e.path()).find_map(|path| {
|
||||
let name = path.file_name()?.to_str()?;
|
||||
if !(name.starts_with("effective-pom-") && name.ends_with(".xml")) || modified(&path) < modified(&pom) {
|
||||
return None;
|
||||
}
|
||||
let root = xml::parse(&xml::read_text(&path)?)?;
|
||||
let projects: Vec<Element> = if root.name == "projects" {
|
||||
root.children.into_iter().filter(|p| p.name == "project").collect()
|
||||
} else {
|
||||
vec![root]
|
||||
};
|
||||
projects.into_iter().find(|p| {
|
||||
let group = p.text_of("groupId").or_else(|| p.at("parent/groupId").map(|g| g.text.trim().to_owned()));
|
||||
group.as_deref() == Some(project.group_id.as_str())
|
||||
&& p.text_of("artifactId").as_deref() == Some(&project.artifact_id)
|
||||
})
|
||||
});
|
||||
let (element, own) = match effective {
|
||||
Some(e) => (e, false),
|
||||
// ponytail: without a sync, inherited configuration and parent properties are missing; Reload adds them.
|
||||
None => (xml::parse(&xml::read_text(&pom)?)?, true),
|
||||
};
|
||||
let mut props: HashMap<String, String> = element
|
||||
.child("properties")
|
||||
.map(|p| p.children.iter().map(|c| (c.name.clone(), c.text.trim().to_owned())).collect())
|
||||
.unwrap_or_default();
|
||||
let dir = module.to_string_lossy().into_owned();
|
||||
for (key, value) in [
|
||||
("basedir", dir.clone()),
|
||||
("project.basedir", dir.clone()),
|
||||
("project.build.directory", format!("{dir}/target")),
|
||||
("project.groupId", project.group_id.clone()),
|
||||
("project.artifactId", project.artifact_id.clone()),
|
||||
("project.version", project.version.clone()),
|
||||
] {
|
||||
props.entry(key.into()).or_insert(value);
|
||||
}
|
||||
Some(read(&element, &props, own))
|
||||
}
|
||||
|
||||
/// `<build><plugins>` Surefire's configuration, then its `default-test` execution's.
|
||||
fn read(project: &Element, props: &HashMap<String, String>, own: bool) -> SurefireConfig {
|
||||
let is_surefire = |p: &&Element| p.text_of("artifactId").as_deref() == Some(SUREFIRE);
|
||||
let mut plugins: Vec<&Element> = project.list("build/plugins", "plugin").into_iter().filter(is_surefire).collect();
|
||||
if own && plugins.is_empty() {
|
||||
plugins = project.list("build/pluginManagement/plugins", "plugin").into_iter().filter(is_surefire).collect();
|
||||
}
|
||||
let mut configurations: Vec<&Element> = Vec::new();
|
||||
for plugin in plugins {
|
||||
configurations.extend(plugin.child("configuration"));
|
||||
let default_test = plugin
|
||||
.list("executions", "execution")
|
||||
.into_iter()
|
||||
.find(|e| e.text_of("id").as_deref() == Some("default-test"));
|
||||
configurations.extend(default_test.and_then(|e| e.child("configuration")));
|
||||
}
|
||||
let value = |text: &str| resolve(text.trim(), props);
|
||||
let mut config = SurefireConfig::default();
|
||||
for c in configurations {
|
||||
if let Some(arg_line) = c.child("argLine") {
|
||||
config.arg_line = split_arg_line(&value(&arg_line.text));
|
||||
}
|
||||
for p in c.child("systemPropertyVariables").map_or(&[][..], |p| &p.children) {
|
||||
config.system_properties.insert(p.name.clone(), value(&p.text));
|
||||
}
|
||||
// `<systemProperties>`: `<property><name/><value/></property>` (deprecated, still honoured).
|
||||
for p in c.list("systemProperties", "property") {
|
||||
if let Some(name) = p.text_of("name") {
|
||||
config.system_properties.insert(name, value(&p.text_of("value").unwrap_or_default()));
|
||||
}
|
||||
}
|
||||
for e in c.child("environmentVariables").map_or(&[][..], |e| &e.children) {
|
||||
config.environment.insert(e.name.clone(), value(&e.text));
|
||||
}
|
||||
if let Some(dir) = c.text_of("workingDirectory").map(|d| value(&d)).filter(|d| !d.is_empty()) {
|
||||
config.working_directory = Some(dir);
|
||||
}
|
||||
let texts = |list: &str, item: &str| -> Vec<String> {
|
||||
c.list(list, item).into_iter().map(|e| value(&e.text)).filter(|t| !t.is_empty()).collect()
|
||||
};
|
||||
config.additional_classpath.extend(texts("additionalClasspathElements", "additionalClasspathElement"));
|
||||
config.classpath_excludes.extend(texts("classpathDependencyExcludes", "classpathDependencyExclude"));
|
||||
}
|
||||
config
|
||||
}
|
||||
|
||||
/// `${…}` from the POM's properties, then Surefire's late replacement `@{…}` (a property a plugin
|
||||
/// sets during the build, such as JaCoCo's `argLine`, is unknown here and left out, as in IDEA).
|
||||
fn resolve(text: &str, props: &HashMap<String, String>) -> String {
|
||||
let mut out = interpolate(text, props);
|
||||
for open in ["@{", "${"] {
|
||||
while let Some(start) = out.find(open) {
|
||||
let Some(len) = out[start..].find('}') else { break };
|
||||
let key = &out[start + 2..start + len];
|
||||
let replacement = if open == "@{" { props.get(key).cloned().unwrap_or_default() } else { String::new() };
|
||||
out.replace_range(start..=start + len, &replacement);
|
||||
}
|
||||
}
|
||||
out.trim().to_owned()
|
||||
}
|
||||
|
||||
/// Splits `argLine` as Surefire does (plexus `CommandLineUtils`): whitespace, `"…"` and `'…'`, no escapes.
|
||||
fn split_arg_line(line: &str) -> Vec<String> {
|
||||
let mut out = Vec::new();
|
||||
let mut current: Option<String> = None;
|
||||
let mut quote: Option<char> = None;
|
||||
for c in line.chars() {
|
||||
match quote {
|
||||
Some(q) if c == q => quote = None,
|
||||
Some(_) => current.get_or_insert_default().push(c),
|
||||
None if c == '"' || c == '\'' => {
|
||||
quote = Some(c);
|
||||
current.get_or_insert_default();
|
||||
}
|
||||
None if c.is_whitespace() => out.extend(current.take()),
|
||||
None => current.get_or_insert_default().push(c),
|
||||
}
|
||||
}
|
||||
out.extend(current);
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const POM: &str = r#"<project>
|
||||
<groupId>com.example</groupId><artifactId>orders</artifactId><version>1</version>
|
||||
<properties><openideaFail>true</openideaFail><mockito>/m2/mockito.jar</mockito></properties>
|
||||
<build><plugins><plugin>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<configuration>
|
||||
<argLine>@{argLine} @{jacoco} -javaagent:${mockito} --add-opens "java.base/java.lang=ALL-UNNAMED" -Dx=${undefined}</argLine>
|
||||
<systemPropertyVariables><openidea.fail>${openideaFail}</openidea.fail><dir>${project.build.directory}</dir></systemPropertyVariables>
|
||||
<systemProperties><property><name>old</name><value>style</value></property></systemProperties>
|
||||
<environmentVariables><TZ>UTC</TZ></environmentVariables>
|
||||
<additionalClasspathElements><additionalClasspathElement>${basedir}/extra</additionalClasspathElement></additionalClasspathElements>
|
||||
<classpathDependencyExcludes><classpathDependencyExclude>org.slf4j:slf4j-simple</classpathDependencyExclude></classpathDependencyExcludes>
|
||||
</configuration>
|
||||
<executions><execution><id>default-test</id><configuration><workingDirectory>${basedir}/work</workingDirectory></configuration></execution></executions>
|
||||
</plugin></plugins></build>
|
||||
</project>"#;
|
||||
|
||||
fn model(dir: &Path) -> MavenModel {
|
||||
crate::maven::load(dir)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_the_module_pom_and_the_effective_pom_the_sync_cached() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
std::fs::write(root.join("pom.xml"), POM).unwrap();
|
||||
let cache = root.join("cache");
|
||||
std::fs::create_dir_all(&cache).unwrap();
|
||||
let config = surefire_config(root, &cache, &model(root), root).unwrap();
|
||||
let d = root.to_string_lossy();
|
||||
assert_eq!(
|
||||
config.arg_line,
|
||||
["-javaagent:/m2/mockito.jar", "--add-opens", "java.base/java.lang=ALL-UNNAMED", "-Dx="]
|
||||
);
|
||||
assert_eq!(config.system_properties["openidea.fail"], "true");
|
||||
assert_eq!(config.system_properties["dir"], format!("{d}/target"));
|
||||
assert_eq!(config.system_properties["old"], "style");
|
||||
assert_eq!(config.environment["TZ"], "UTC");
|
||||
assert_eq!(config.working_directory, Some(format!("{d}/work")));
|
||||
assert_eq!(config.additional_classpath, [format!("{d}/extra")]);
|
||||
assert_eq!(config.classpath_excludes, ["org.slf4j:slf4j-simple"]);
|
||||
|
||||
// A sync's effective POM wins: it has what the module inherits.
|
||||
let effective = POM.replace("<argLine>", "<argLine>-Xmx1g ").replace("<TZ>UTC</TZ>", "<TZ>Asia/Tokyo</TZ>");
|
||||
std::fs::write(cache.join("effective-pom-0.xml"), format!("<projects>{effective}</projects>")).unwrap();
|
||||
let config = surefire_config(root, &cache, &model(root), root).unwrap();
|
||||
assert_eq!(config.arg_line[0], "-Xmx1g");
|
||||
assert_eq!(config.environment["TZ"], "Asia/Tokyo");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn splits_arg_line_like_surefire() {
|
||||
assert_eq!(split_arg_line(r#" -a "b c" 'd "e"' C:\x\y "" "#), ["-a", "b c", r#"d "e""#, r"C:\x\y", ""]);
|
||||
}
|
||||
}
|
||||
@@ -86,37 +86,22 @@ const MAVEN_CACHE_VERSION: u32 = 1;
|
||||
|
||||
/// `dependency:tree` of a plugin version whose `-Dverbose` lists the occurrences Maven
|
||||
/// omitted (conflicts, duplicates): verbose output was dropped in 3.0 and is back since 3.2.
|
||||
/// Offline, it is used only when an earlier sync downloaded it; otherwise the newest version
|
||||
/// in the local repository is.
|
||||
/// Offline, it is used only when an earlier sync downloaded it; otherwise the project's own
|
||||
/// plugin version is, which may be cached instead.
|
||||
const DEPENDENCY_TREE: &str = "org.apache.maven.plugins:maven-dependency-plugin:3.8.1:tree";
|
||||
const DEPENDENCY_TREE_JAR: &str =
|
||||
"org/apache/maven/plugins/maven-dependency-plugin/3.8.1/maven-dependency-plugin-3.8.1.jar";
|
||||
|
||||
/// The goals that read the effective POM into `effective` and the verbose dependency trees;
|
||||
/// `repo` is the local repository the build resolves from. Both goals name their plugin by
|
||||
/// coordinates: offline, a prefix resolves only from group metadata the repository may lack.
|
||||
/// Offline without a cached 3.x `maven-help-plugin`, `effective-pom` is skipped so `mvn -o`
|
||||
/// still resolves the dependency tree instead of failing to download the help plugin.
|
||||
/// `repo` is the local repository the build resolves from.
|
||||
fn maven_sync_goals(effective: &Path, offline: bool, repo: Option<&Path>) -> Vec<String> {
|
||||
let pinned = !offline || repo.is_some_and(|repo| repo.join(DEPENDENCY_TREE_JAR).is_file());
|
||||
let tree = if pinned {
|
||||
DEPENDENCY_TREE.to_owned()
|
||||
} else {
|
||||
repo.and_then(|repo| maven::newest_local_plugin(repo, "maven-dependency-plugin", 2)).map_or_else(
|
||||
|| "dependency:tree".to_owned(),
|
||||
|v| format!("org.apache.maven.plugins:maven-dependency-plugin:{v}:tree"),
|
||||
)
|
||||
};
|
||||
let has_help =
|
||||
!offline || repo.is_some_and(|repo| maven::newest_local_plugin(repo, "maven-help-plugin", 3).is_some());
|
||||
let mut goals = Vec::with_capacity(4);
|
||||
if has_help {
|
||||
goals.push(maven::plugin_goal("help:effective-pom", repo));
|
||||
goals.push(format!("-Doutput={}", effective.to_string_lossy()));
|
||||
}
|
||||
goals.push(tree);
|
||||
goals.push("-Dverbose".into());
|
||||
goals
|
||||
vec![
|
||||
"help:effective-pom".into(),
|
||||
format!("-Doutput={}", effective.to_string_lossy()),
|
||||
if pinned { DEPENDENCY_TREE.into() } else { "dependency:tree".into() },
|
||||
"-Dverbose".into(),
|
||||
]
|
||||
}
|
||||
|
||||
/// The settings' Maven options for the sync runs: the thread count (`-T`, also
|
||||
@@ -382,8 +367,25 @@ pub fn sync_maven(
|
||||
verbose: true,
|
||||
..MavenCache::default()
|
||||
};
|
||||
// Where the build resolves its jars, and therefore where the plugin goals are read from.
|
||||
let repo = maven::local_repository_for(&options.maven_options);
|
||||
// Where the build resolves its jars, and therefore where the plugin goals are read
|
||||
// from: `-Dmaven.repo.local=` first, then `<localRepository>` of the `-s` settings,
|
||||
// then the user's default repository (which `plugin()` resolves itself).
|
||||
let local_repo: Option<PathBuf> =
|
||||
options.maven_options.iter().find_map(|a| a.strip_prefix("-Dmaven.repo.local=")).map(PathBuf::from).or_else(
|
||||
|| {
|
||||
let mut args = options.maven_options.iter();
|
||||
while let Some(arg) = args.next() {
|
||||
let path = match arg.as_str() {
|
||||
"-s" | "--settings" => args.next().map(String::as_str),
|
||||
_ => arg.strip_prefix("-s=").or_else(|| arg.strip_prefix("--settings=")),
|
||||
};
|
||||
if let Some(path) = path {
|
||||
return maven::local_repository_of(Path::new(path));
|
||||
}
|
||||
}
|
||||
None
|
||||
},
|
||||
);
|
||||
let mut errors: Vec<String> = Vec::new();
|
||||
for (n, top) in model.projects.iter().filter(|p| !p.aggregated).enumerate() {
|
||||
let effective = cache_dir.join(format!("effective-pom-{n}.xml"));
|
||||
@@ -405,6 +407,7 @@ pub fn sync_maven(
|
||||
if !options.profiles.is_empty() {
|
||||
args.push(format!("-P{}", options.profiles.join(",")));
|
||||
}
|
||||
let repo = local_repo.clone().or_else(maven::default_local_repo);
|
||||
args.extend(maven_sync_goals(&effective, options.offline, repo.as_deref()));
|
||||
progress(SyncProgress { message: format!("Reading {}", top.display_name), fraction: None });
|
||||
let command = options.maven_command.as_deref().unwrap_or(&top.command);
|
||||
@@ -422,7 +425,7 @@ pub fn sync_maven(
|
||||
}
|
||||
})?;
|
||||
let effective_projects = std::fs::read_to_string(&effective)
|
||||
.map(|t| maven::parse_effective_pom_in(&t, repo.as_deref()))
|
||||
.map(|t| maven::parse_effective_pom_in(&t, local_repo.as_deref()))
|
||||
.unwrap_or_default();
|
||||
let trees = maven::parse_dependency_tree(&out.text);
|
||||
for (key, plugins, deps) in effective_projects {
|
||||
@@ -950,32 +953,11 @@ mod tests {
|
||||
#[test]
|
||||
fn sync_reads_verbose_trees_with_a_pinned_plugin_unless_offline_without_it() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let help = "org.apache.maven.plugins:maven-help-plugin:3.5.1:effective-pom";
|
||||
let online = maven_sync_goals(Path::new("e.xml"), false, Some(tmp.path()));
|
||||
assert_eq!(online, [help, "-Doutput=e.xml", DEPENDENCY_TREE, "-Dverbose"]);
|
||||
// Offline with neither plugin cached: `effective-pom` is skipped so `mvn -o` does not fail
|
||||
// on an uncached `maven-help-plugin`, and the tree falls back to the project's own version.
|
||||
let online = maven_sync_goals(Path::new("e.xml"), false, None);
|
||||
assert_eq!(online, ["help:effective-pom", "-Doutput=e.xml", DEPENDENCY_TREE, "-Dverbose"]);
|
||||
let offline = maven_sync_goals(Path::new("e.xml"), true, Some(tmp.path()));
|
||||
assert_eq!(offline, ["dependency:tree", "-Dverbose"]);
|
||||
// #5757 / #5844: offline, plugins in the local repository are named by their coordinates,
|
||||
// since the prefix needs group metadata a repository filled from a private mirror may lack;
|
||||
// a repository with `maven-dependency-plugin` but no 3.x `maven-help-plugin` runs only the tree.
|
||||
for (artifact, version) in [("maven-help-plugin", "2.2"), ("maven-dependency-plugin", "3.6.1")] {
|
||||
let jar =
|
||||
tmp.path().join(format!("org/apache/maven/plugins/{artifact}/{version}/{artifact}-{version}.jar"));
|
||||
std::fs::create_dir_all(jar.parent().unwrap()).unwrap();
|
||||
std::fs::write(&jar, "").unwrap();
|
||||
}
|
||||
let offline = maven_sync_goals(Path::new("e.xml"), true, Some(tmp.path()));
|
||||
assert_eq!(offline, ["org.apache.maven.plugins:maven-dependency-plugin:3.6.1:tree", "-Dverbose"]);
|
||||
let help_jar = tmp.path().join("org/apache/maven/plugins/maven-help-plugin/3.4.0/maven-help-plugin-3.4.0.jar");
|
||||
std::fs::create_dir_all(help_jar.parent().unwrap()).unwrap();
|
||||
std::fs::write(&help_jar, "").unwrap();
|
||||
// A version folder without its jar (only the POM was fetched) doesn't count.
|
||||
std::fs::create_dir_all(tmp.path().join("org/apache/maven/plugins/maven-help-plugin/3.10.0")).unwrap();
|
||||
let offline = maven_sync_goals(Path::new("e.xml"), true, Some(tmp.path()));
|
||||
assert_eq!(offline[0], "org.apache.maven.plugins:maven-help-plugin:3.4.0:effective-pom");
|
||||
assert_eq!(offline[2], "org.apache.maven.plugins:maven-dependency-plugin:3.6.1:tree");
|
||||
assert_eq!(offline[2], "dependency:tree");
|
||||
assert!(offline.contains(&"-Dverbose".to_owned()));
|
||||
// Downloaded by an online sync: offline keeps using it, the project's version may be missing.
|
||||
let jar = tmp.path().join(DEPENDENCY_TREE_JAR);
|
||||
std::fs::create_dir_all(jar.parent().unwrap()).unwrap();
|
||||
@@ -1047,7 +1029,7 @@ mod tests {
|
||||
let cache = tmp.path().join("cache");
|
||||
sync_maven(&root, &cache, &SyncOptions::default(), &CancellationToken::new(), &|_| {}).unwrap();
|
||||
let args = std::fs::read_to_string(root.join("mvnw-args")).unwrap();
|
||||
assert!(args.contains("maven-help-plugin:"), "args: {args}");
|
||||
assert!(args.contains("help:effective-pom"), "args: {args}");
|
||||
let loaded = crate::load_linked(&root, &cache, None, &Default::default(), &Default::default());
|
||||
let maven = loaded.maven.unwrap();
|
||||
assert!(maven.synced_at.is_some() && maven.sync_error.is_none(), "{:?}", maven.sync_error);
|
||||
@@ -1072,6 +1054,6 @@ mod tests {
|
||||
let args = std::fs::read_to_string(root.join("mvnd-args")).unwrap();
|
||||
// `-T1` pins the daemon serial so the dependency trees stay parseable.
|
||||
assert!(args.contains("-T1"), "args: {args}");
|
||||
assert!(args.contains("maven-help-plugin:"), "args: {args}");
|
||||
assert!(args.contains("help:effective-pom"), "args: {args}");
|
||||
}
|
||||
}
|
||||
@@ -137,16 +137,19 @@ pub fn build(root: &Path, model: &BuildModel, id: &str, cache: &Path) -> IdeResu
|
||||
// POM's effective identity first; profiles and -D options can change its GAV.
|
||||
let output = cache.join("artifact-project.txt");
|
||||
let mut probe = top.options.clone();
|
||||
let evaluate =
|
||||
crate::maven::plugin_goal("help:evaluate", crate::maven::local_repository_for(&top.options).as_deref());
|
||||
probe.extend([
|
||||
"-f".into(),
|
||||
root.join(&p.pom).to_string_lossy().into_owned(),
|
||||
evaluate.clone(),
|
||||
"help:evaluate".into(),
|
||||
"-Dexpression=project.id".into(),
|
||||
format!("-Doutput={}", output.display()),
|
||||
]);
|
||||
args.extend(["-DskipTests".into(), "package".into(), evaluate, format!("-Doutput={}", manifest.display())]);
|
||||
args.extend([
|
||||
"-DskipTests".into(),
|
||||
"package".into(),
|
||||
"help:evaluate".into(),
|
||||
format!("-Doutput={}", manifest.display()),
|
||||
]);
|
||||
return Ok(WebBuild {
|
||||
command: top.command.clone(),
|
||||
args,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "ide-clipboard"
|
||||
description = "The OS clipboard's file list (file manager <-> project view) and pasted images: Windows CF_HDROP / PNG / CF_DIB, macOS NSPasteboard, Linux text/uri-list via GTK"
|
||||
description = "The OS clipboard's file list (Explorer <-> project view) and pasted images: Windows CF_HDROP / PNG / CF_DIB or macOS NSPasteboard, no window or message loop"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
@@ -1,85 +0,0 @@
|
||||
use std::io::{Cursor, Error, ErrorKind, Result};
|
||||
|
||||
/// A top-down BITMAPV5HEADER and BGRA pixels. The alpha mask lets native paste targets
|
||||
/// retain transparency; the PNG flavor is also written for browsers and image editors.
|
||||
pub(crate) fn png_to_dib(png: &[u8]) -> Result<Vec<u8>> {
|
||||
let invalid = |error| Error::new(ErrorKind::InvalidData, error);
|
||||
let mut decoder = png::Decoder::new(Cursor::new(png));
|
||||
decoder.set_transformations(png::Transformations::normalize_to_color8());
|
||||
let mut reader = decoder.read_info().map_err(invalid)?;
|
||||
let rgba_size = (reader.info().width as usize)
|
||||
.checked_mul(reader.info().height as usize)
|
||||
.and_then(|pixels| pixels.checked_mul(4))
|
||||
.filter(|size| *size <= 64 * 1024 * 1024)
|
||||
.ok_or_else(|| Error::new(ErrorKind::InvalidData, "Clipboard image is too large"))?;
|
||||
let size = reader
|
||||
.output_buffer_size()
|
||||
.filter(|size| *size <= 64 * 1024 * 1024)
|
||||
.ok_or_else(|| Error::new(ErrorKind::InvalidData, "Clipboard image is too large"))?;
|
||||
let mut pixels = vec![0; size];
|
||||
let info = reader.next_frame(&mut pixels).map_err(invalid)?;
|
||||
let mut dib = vec![0; 124];
|
||||
dib[0..4].copy_from_slice(&124u32.to_le_bytes());
|
||||
dib[4..8].copy_from_slice(&info.width.to_le_bytes());
|
||||
dib[8..12].copy_from_slice(&(-(info.height as i32)).to_le_bytes());
|
||||
dib[12..14].copy_from_slice(&1u16.to_le_bytes());
|
||||
dib[14..16].copy_from_slice(&32u16.to_le_bytes());
|
||||
dib[16..20].copy_from_slice(&3u32.to_le_bytes()); // BI_BITFIELDS
|
||||
dib[20..24].copy_from_slice(&(rgba_size as u32).to_le_bytes());
|
||||
for (at, value) in [(40, 0x00ff0000u32), (44, 0x0000ff00), (48, 0x000000ff), (52, 0xff000000), (56, 0x73524742)] {
|
||||
dib[at..at + 4].copy_from_slice(&value.to_le_bytes());
|
||||
}
|
||||
dib[108..112].copy_from_slice(&4u32.to_le_bytes()); // LCS_GM_IMAGES
|
||||
for pixel in pixels[..info.buffer_size()].chunks_exact(info.color_type.samples()) {
|
||||
let rgba = match info.color_type {
|
||||
png::ColorType::Rgba => [pixel[0], pixel[1], pixel[2], pixel[3]],
|
||||
png::ColorType::Rgb => [pixel[0], pixel[1], pixel[2], 255],
|
||||
png::ColorType::Grayscale => [pixel[0], pixel[0], pixel[0], 255],
|
||||
png::ColorType::GrayscaleAlpha => [pixel[0], pixel[0], pixel[0], pixel[1]],
|
||||
png::ColorType::Indexed => unreachable!("palette expansion requested"),
|
||||
};
|
||||
dib.extend_from_slice(&[rgba[2], rgba[1], rgba[0], rgba[3]]);
|
||||
}
|
||||
Ok(dib)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn encode(color: png::ColorType, pixels: &[u8]) -> Vec<u8> {
|
||||
let mut png = Vec::new();
|
||||
{
|
||||
let mut encoder = png::Encoder::new(&mut png, 1, 2);
|
||||
encoder.set_color(color);
|
||||
encoder.set_depth(png::BitDepth::Eight);
|
||||
encoder.write_header().unwrap().write_image_data(pixels).unwrap();
|
||||
}
|
||||
png
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_rgba_colors_alpha_and_top_down_row_order() {
|
||||
let png = encode(png::ColorType::Rgba, &[255, 0, 0, 128, 0, 255, 0, 255]);
|
||||
let dib = png_to_dib(&png).unwrap();
|
||||
assert_eq!(i32::from_le_bytes(dib[8..12].try_into().unwrap()), -2);
|
||||
assert_eq!(&dib[124..], &[0, 0, 255, 128, 0, 255, 0, 255]);
|
||||
let round_trip = crate::dib_to_png(&dib).unwrap();
|
||||
let mut reader = png::Decoder::new(Cursor::new(round_trip)).read_info().unwrap();
|
||||
let mut pixels = vec![0; reader.output_buffer_size().unwrap()];
|
||||
reader.next_frame(&mut pixels).unwrap();
|
||||
assert_eq!(pixels, [255, 0, 0, 128, 0, 255, 0, 255]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn supports_rgb_and_grayscale_without_assuming_an_alpha_channel() {
|
||||
for (color, pixels, expected) in [
|
||||
(png::ColorType::Rgb, vec![255, 0, 0, 0, 255, 0], vec![0, 0, 255, 255, 0, 255, 0, 255]),
|
||||
(png::ColorType::Grayscale, vec![20, 200], vec![20, 20, 20, 255, 200, 200, 200, 255]),
|
||||
(png::ColorType::GrayscaleAlpha, vec![20, 10, 200, 250], vec![20, 20, 20, 10, 200, 200, 200, 250]),
|
||||
] {
|
||||
assert_eq!(&png_to_dib(&encode(color, &pixels)).unwrap()[124..], expected);
|
||||
}
|
||||
assert!(png_to_dib(b"not a PNG").is_err());
|
||||
}
|
||||
}
|
||||
@@ -16,12 +16,8 @@
|
||||
//! thread: AppKit and WebKit also access the general pasteboard there, and its
|
||||
//! mutable type cache cannot be protected by a mutex in this crate.
|
||||
//!
|
||||
//! Linux keeps it as `text/uri-list` (Dolphin, Nautilus and most file
|
||||
//! managers) or GNOME's `x-special/gnome-copied-files` (`copy` or `cut`, then
|
||||
//! one URI per line), read and written through the GTK clipboard on X11 and
|
||||
//! Wayland alike; [`request_files`] reads it without blocking the main loop.
|
||||
//! Other platforms are not wired up: [`files`] is empty and [`set_files`]
|
||||
//! fails there.
|
||||
//! Other platforms (`text/uri-list` on X11) are not wired up: [`files`] is
|
||||
//! empty and [`set_files`] fails there.
|
||||
//!
|
||||
//! [`png`] reads an image (a screenshot) for the project view's Paste, which
|
||||
//! saves it as a file: `public.png` or `public.tiff` on macOS, the registered
|
||||
@@ -29,29 +25,6 @@
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[cfg(any(windows, test))]
|
||||
mod image;
|
||||
|
||||
/// Writes a PNG as a native image, independently of WebView clipboard permissions.
|
||||
/// Call on the main thread on macOS and Linux; `owner` is a window handle on Windows.
|
||||
pub fn set_png(png: &[u8], owner: usize) -> std::io::Result<()> {
|
||||
if png.get(..8) != Some(b"\x89PNG\r\n\x1a\n") || png.get(12..16) != Some(b"IHDR") || png.len() < 24 {
|
||||
return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "Invalid clipboard image"));
|
||||
}
|
||||
let width = u32::from_be_bytes(png[16..20].try_into().unwrap()) as usize;
|
||||
let height = u32::from_be_bytes(png[20..24].try_into().unwrap()) as usize;
|
||||
if width == 0
|
||||
|| height == 0
|
||||
|| !width
|
||||
.checked_mul(height)
|
||||
.and_then(|pixels| pixels.checked_mul(4))
|
||||
.is_some_and(|size| size <= 64 * 1024 * 1024)
|
||||
{
|
||||
return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "Clipboard image is too large"));
|
||||
}
|
||||
imp::set_png(png, owner)
|
||||
}
|
||||
|
||||
/// Replaces every clipboard flavor with plain text. `owner` is the calling window
|
||||
/// handle on Windows, ignored elsewhere. Call on the main thread on macOS and Linux.
|
||||
pub fn set_text(text: &str, owner: usize) -> std::io::Result<()> {
|
||||
@@ -83,7 +56,6 @@ const HEADER: usize = 20;
|
||||
|
||||
/// The absolute paths on the clipboard, empty when it holds no file list.
|
||||
/// Read failures remain errors so callers can retain an internal copy.
|
||||
/// Empty on Linux, where [`request_files`] reads it.
|
||||
pub fn files() -> std::io::Result<Vec<PathBuf>> {
|
||||
imp::files()
|
||||
}
|
||||
@@ -106,7 +78,7 @@ pub fn set_files(paths: &[PathBuf]) -> bool {
|
||||
/// line. An editor paste inserts names, not the absolute paths the file list
|
||||
/// keeps for Explorer (#1878; IDEA's text flavor is names too). A path with no
|
||||
/// file name (a root like `C:\`) keeps its whole path.
|
||||
#[cfg(any(windows, target_os = "macos", target_os = "linux", test))]
|
||||
#[cfg(any(windows, target_os = "macos", test))]
|
||||
fn names_text(paths: &[PathBuf], separator: &str) -> String {
|
||||
paths
|
||||
.iter()
|
||||
@@ -117,82 +89,6 @@ fn names_text(paths: &[PathBuf], separator: &str) -> String {
|
||||
.join(separator)
|
||||
}
|
||||
|
||||
/// The `file://` URIs in a `text/uri-list` or `x-special/gnome-copied-files`
|
||||
/// payload as local paths: comments, the `copy`/`cut` line and URIs for other
|
||||
/// hosts or schemes are skipped.
|
||||
#[cfg(any(target_os = "linux", all(test, unix)))]
|
||||
fn uri_list_paths(text: &str) -> Vec<PathBuf> {
|
||||
text.lines().map(str::trim).filter(|line| !line.starts_with('#')).filter_map(uri_to_path).collect()
|
||||
}
|
||||
|
||||
/// A local `file://` URI (`file:///a%20b` or `file://localhost/a%20b`) as a
|
||||
/// path; its percent-escapes are raw bytes, as GLib writes them.
|
||||
#[cfg(any(target_os = "linux", all(test, unix)))]
|
||||
fn uri_to_path(uri: &str) -> Option<PathBuf> {
|
||||
use std::os::unix::ffi::OsStringExt;
|
||||
let rest = uri.strip_prefix("file://")?;
|
||||
let path = if rest.starts_with('/') { rest } else { rest.strip_prefix("localhost")? };
|
||||
let path = path.split(['?', '#']).next()?;
|
||||
if !path.starts_with('/') {
|
||||
return None;
|
||||
}
|
||||
let hex = |b: u8| (b as char).to_digit(16).map(|d| d as u8);
|
||||
let bytes = path.as_bytes();
|
||||
let mut out = Vec::with_capacity(bytes.len());
|
||||
let mut i = 0;
|
||||
while i < bytes.len() {
|
||||
let escaped =
|
||||
(bytes[i] == b'%').then(|| Some((hex(*bytes.get(i + 1)?)? << 4) | hex(*bytes.get(i + 2)?)?)).flatten();
|
||||
match escaped {
|
||||
Some(b) => {
|
||||
out.push(b);
|
||||
i += 3;
|
||||
}
|
||||
None => {
|
||||
out.push(bytes[i]);
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(PathBuf::from(std::ffi::OsString::from_vec(out)))
|
||||
}
|
||||
|
||||
/// `path` as a `file://` URI, every byte outside the unreserved set and `/`
|
||||
/// percent-escaped.
|
||||
#[cfg(any(target_os = "linux", all(test, unix)))]
|
||||
fn file_uri(path: &std::path::Path) -> String {
|
||||
use std::fmt::Write;
|
||||
use std::os::unix::ffi::OsStrExt;
|
||||
let mut uri = String::from("file://");
|
||||
for &b in path.as_os_str().as_bytes() {
|
||||
if b.is_ascii_alphanumeric() || b"/-._~".contains(&b) {
|
||||
uri.push(b as char);
|
||||
} else {
|
||||
let _ = write!(uri, "%{b:02X}");
|
||||
}
|
||||
}
|
||||
uri
|
||||
}
|
||||
|
||||
/// Reads the clipboard's file list without blocking: `text/uri-list` first,
|
||||
/// then GNOME's list, and calls `done` with the paths (empty without a list).
|
||||
/// Call on the main thread; `done` runs there later.
|
||||
#[cfg(target_os = "linux")]
|
||||
pub fn request_files(done: impl FnOnce(Vec<PathBuf>) + 'static) {
|
||||
use gtk::gdk::{Atom, SELECTION_CLIPBOARD};
|
||||
fn paths_in(data: >k::SelectionData) -> Vec<PathBuf> {
|
||||
// A failed request has a negative length and no data.
|
||||
if data.length() <= 0 { Vec::new() } else { uri_list_paths(&String::from_utf8_lossy(&data.data())) }
|
||||
}
|
||||
gtk::Clipboard::get(&SELECTION_CLIPBOARD).request_contents(&Atom::intern(imp::URI_LIST), move |board, data| {
|
||||
let paths = paths_in(data);
|
||||
if !paths.is_empty() {
|
||||
return done(paths);
|
||||
}
|
||||
board.request_contents(&Atom::intern(imp::GNOME_COPIED), move |_, data| done(paths_in(data)));
|
||||
});
|
||||
}
|
||||
|
||||
/// `DROPFILES` for `paths`, in the wide form so names outside the ANSI code
|
||||
/// page survive. Empty paths are skipped.
|
||||
pub fn encode(paths: &[PathBuf]) -> Vec<u8> {
|
||||
@@ -344,7 +240,6 @@ mod imp {
|
||||
/// `CF_DIB`: Windows synthesizes it from `CF_BITMAP` and `CF_DIBV5`, so every
|
||||
/// bitmap on the clipboard reads as one.
|
||||
const CF_DIB: u32 = 8;
|
||||
const CF_DIBV5: u32 = 17;
|
||||
|
||||
/// The `PNG` format browsers and the Snipping Tool add beside the bitmap; it
|
||||
/// keeps transparency, so it is read first.
|
||||
@@ -527,48 +422,6 @@ mod imp {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_png(png: &[u8], owner: usize) -> std::io::Result<()> {
|
||||
let dib = super::image::png_to_dib(png)?;
|
||||
let format = png_format();
|
||||
if format == 0 {
|
||||
return Err(std::io::Error::last_os_error());
|
||||
}
|
||||
let formats = [(format, png), (CF_DIBV5, dib.as_slice())];
|
||||
// SAFETY: allocations remain ours until SetClipboardData accepts them. Prepare both
|
||||
// before replacing the clipboard; free only allocations the OS did not take.
|
||||
unsafe {
|
||||
let mut blocks: Vec<_> = formats.iter().map(|(_, bytes)| global_bytes(bytes)).collect();
|
||||
if blocks.iter().any(|memory| memory.is_null()) || !open_for(owner as Handle) {
|
||||
let error = std::io::Error::last_os_error();
|
||||
for memory in blocks {
|
||||
if !memory.is_null() {
|
||||
GlobalFree(memory);
|
||||
}
|
||||
}
|
||||
return Err(error);
|
||||
}
|
||||
let mut result = Ok(());
|
||||
if EmptyClipboard() == 0 {
|
||||
result = Err(std::io::Error::last_os_error());
|
||||
} else {
|
||||
for ((format, _), memory) in formats.iter().zip(&mut blocks) {
|
||||
if SetClipboardData(*format, *memory).is_null() {
|
||||
result = Err(std::io::Error::last_os_error());
|
||||
break;
|
||||
}
|
||||
*memory = ptr::null_mut();
|
||||
}
|
||||
}
|
||||
CloseClipboard();
|
||||
for memory in blocks {
|
||||
if !memory.is_null() {
|
||||
GlobalFree(memory);
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_files(paths: &[PathBuf]) -> bool {
|
||||
let bytes = encode(paths);
|
||||
if bytes.len() <= HEADER {
|
||||
@@ -636,7 +489,7 @@ mod imp {
|
||||
NSBitmapImageFileType, NSBitmapImageRep, NSPasteboard, NSPasteboardReadingOptionKey, NSPasteboardTypePNG,
|
||||
NSPasteboardTypeString, NSPasteboardTypeTIFF, NSPasteboardURLReadingFileURLsOnlyKey, NSPasteboardWriting,
|
||||
};
|
||||
use objc2_foundation::{NSArray, NSData, NSDictionary, NSNumber, NSString, NSURL};
|
||||
use objc2_foundation::{NSArray, NSDictionary, NSNumber, NSString, NSURL};
|
||||
use std::path::PathBuf;
|
||||
|
||||
use super::names_text;
|
||||
@@ -734,23 +587,6 @@ mod imp {
|
||||
})
|
||||
}
|
||||
|
||||
pub fn set_png(png: &[u8], _owner: usize) -> std::io::Result<()> {
|
||||
debug_assert!(MainThreadMarker::new().is_some(), "NSPasteboard access requires the main thread");
|
||||
autoreleasepool(|_| {
|
||||
let data = NSData::with_bytes(png);
|
||||
if NSBitmapImageRep::imageRepWithData(&data).is_none() {
|
||||
return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "Invalid clipboard image"));
|
||||
}
|
||||
let board = NSPasteboard::generalPasteboard();
|
||||
board.clearContents();
|
||||
if board.setData_forType(Some(&data), unsafe { NSPasteboardTypePNG }) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(std::io::Error::other("Cannot write clipboard image"))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
pub fn set_files(paths: &[PathBuf]) -> bool {
|
||||
debug_assert!(MainThreadMarker::new().is_some(), "NSPasteboard access requires the main thread");
|
||||
autoreleasepool(|_| {
|
||||
@@ -781,21 +617,6 @@ mod imp {
|
||||
mod imp {
|
||||
use std::path::PathBuf;
|
||||
|
||||
pub fn set_png(png: &[u8], _owner: usize) -> std::io::Result<()> {
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
let image = gtk::gdk_pixbuf::Pixbuf::from_read(std::io::Cursor::new(png.to_vec()))
|
||||
.map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error.to_string()))?;
|
||||
gtk::Clipboard::get(>k::gdk::SELECTION_CLIPBOARD).set_image(&image);
|
||||
Ok(())
|
||||
}
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
{
|
||||
let _ = png;
|
||||
Err(std::io::Error::other("Clipboard images are unavailable on this platform"))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_text(text: &str, _owner: usize) -> std::io::Result<()> {
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
@@ -809,25 +630,8 @@ mod imp {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
pub const URI_LIST: &str = "text/uri-list";
|
||||
#[cfg(target_os = "linux")]
|
||||
pub const GNOME_COPIED: &str = "x-special/gnome-copied-files";
|
||||
|
||||
pub fn has_files() -> bool {
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
gtk::Clipboard::get(>k::gdk::SELECTION_CLIPBOARD).wait_for_targets().is_some_and(|targets| {
|
||||
targets.into_iter().any(|target| {
|
||||
let name = target.name();
|
||||
name == URI_LIST || name == GNOME_COPIED
|
||||
})
|
||||
})
|
||||
}
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
{
|
||||
false
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
pub fn has_image() -> bool {
|
||||
@@ -845,33 +649,6 @@ mod imp {
|
||||
Ok(Vec::new())
|
||||
}
|
||||
|
||||
/// Offers `paths` as `text/uri-list` (KDE and most file managers), GNOME's
|
||||
/// list (Nautilus, Thunar) and their names as text, rendered on request.
|
||||
#[cfg(target_os = "linux")]
|
||||
pub fn set_files(paths: &[PathBuf]) -> bool {
|
||||
use gtk::{TargetEntry, TargetFlags};
|
||||
let uris: Vec<String> = paths.iter().map(|p| super::file_uri(p)).collect();
|
||||
let uri_list: String = uris.iter().map(|uri| format!("{uri}\r\n")).collect();
|
||||
let gnome = format!("copy\n{}", uris.join("\n"));
|
||||
let names = super::names_text(paths, "\n");
|
||||
let entry = |name: &str, info: u32| TargetEntry::new(name, TargetFlags::empty(), info);
|
||||
let targets = [
|
||||
entry(URI_LIST, 0),
|
||||
entry(GNOME_COPIED, 1),
|
||||
entry("UTF8_STRING", 2),
|
||||
entry("text/plain;charset=utf-8", 2),
|
||||
entry("text/plain", 2),
|
||||
];
|
||||
gtk::Clipboard::get(>k::gdk::SELECTION_CLIPBOARD).set_with_data(&targets, move |_, data, info| match info {
|
||||
0 => data.set(&data.target(), 8, uri_list.as_bytes()),
|
||||
1 => data.set(&data.target(), 8, gnome.as_bytes()),
|
||||
_ => {
|
||||
let _ = data.set_text(&names);
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
pub fn set_files(_paths: &[PathBuf]) -> bool {
|
||||
false
|
||||
}
|
||||
@@ -881,41 +658,10 @@ mod imp {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn invalid_or_oversized_images_are_rejected_before_accessing_the_clipboard() {
|
||||
assert!(set_png(b"not a PNG", 0).is_err());
|
||||
let mut header = b"\x89PNG\r\n\x1a\n\0\0\0\rIHDR".to_vec();
|
||||
header.extend_from_slice(&100_000u32.to_be_bytes());
|
||||
header.extend_from_slice(&100_000u32.to_be_bytes());
|
||||
assert!(set_png(&header, 0).is_err());
|
||||
}
|
||||
|
||||
fn paths(list: &[&str]) -> Vec<PathBuf> {
|
||||
list.iter().map(PathBuf::from).collect()
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn file_manager_uri_lists_become_paths() {
|
||||
// Dolphin: CRLF-separated `text/uri-list`, with a comment line.
|
||||
let kde = "# copied\r\nfile:///home/u/a%20b.txt\r\nfile://localhost/home/u/%E6%A1%8C%E9%9D%A2\r\n";
|
||||
assert_eq!(uri_list_paths(kde), paths(&["/home/u/a b.txt", "/home/u/桌面"]));
|
||||
// Nautilus/Thunar: `copy` or `cut`, then one URI per line.
|
||||
assert_eq!(uri_list_paths("cut\nfile:///tmp/x\nfile:///tmp/y"), paths(&["/tmp/x", "/tmp/y"]));
|
||||
// Other hosts and schemes are not local files.
|
||||
assert!(uri_list_paths("file://server/share/x\nhttps://example.com/x\nsmb:///x").is_empty());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn written_uris_read_back_as_the_same_paths() {
|
||||
let list = paths(&["/home/u/a b#1%.txt", "/home/u/桌面/项目", "/tmp/plain-name_1.~"]);
|
||||
let uris: Vec<String> = list.iter().map(|p| file_uri(p)).collect();
|
||||
assert_eq!(uris[0], "file:///home/u/a%20b%231%25.txt");
|
||||
assert_eq!(uris[2], "file:///tmp/plain-name_1.~");
|
||||
assert_eq!(uri_list_paths(&uris.join("\r\n")), list);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_written_list_reads_back_unchanged() {
|
||||
let list = paths(&["C:/work/project/a.txt", "C:/work/project/sub"]);
|
||||
|
||||
@@ -6,7 +6,6 @@ edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
base64.workspace = true
|
||||
dunce.workspace = true
|
||||
encoding_rs.workspace = true
|
||||
serde.workspace = true
|
||||
@@ -15,16 +14,12 @@ specta.workspace = true
|
||||
specta-typescript.workspace = true
|
||||
thiserror.workspace = true
|
||||
tokio-util.workspace = true
|
||||
portable-pty.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
sha2 = "0.10"
|
||||
tempfile.workspace = true
|
||||
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
libc = "0.2"
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
dirs.workspace = true
|
||||
tracing.workspace = true
|
||||
windows-sys = { version = "0.61", features = ["Wdk_System_SystemServices", "Win32_Foundation", "Win32_Globalization", "Win32_Security", "Win32_System_Console", "Win32_System_Diagnostics_ToolHelp", "Win32_System_IO", "Win32_System_JobObjects", "Win32_System_LibraryLoader", "Win32_System_Registry", "Win32_System_SystemInformation", "Win32_System_Threading"] }
|
||||
windows-sys = { version = "0.61", features = ["Wdk_System_SystemServices", "Win32_Foundation", "Win32_Globalization", "Win32_Security", "Win32_System_Diagnostics_ToolHelp", "Win32_System_IO", "Win32_System_JobObjects", "Win32_System_Registry", "Win32_System_SystemInformation", "Win32_System_Threading"] }
|
||||
@@ -1,21 +0,0 @@
|
||||
Copyright (c) Microsoft Corporation. All rights reserved.
|
||||
|
||||
MIT License
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -1,39 +0,0 @@
|
||||
# Bundled Windows console host
|
||||
|
||||
Unmodified files from Microsoft's MIT-licensed
|
||||
[Microsoft.Windows.Console.ConPTY 1.25.260930003](https://www.nuget.org/packages/Microsoft.Windows.Console.ConPTY/1.25.260930003).
|
||||
The system ConPTY on Windows 10 build 19045 consumes alternate-screen transitions; xterm then
|
||||
puts full-screen applications' redraws in normal scrollback. A current console host
|
||||
preserves those transitions, including while resizing and updating a running TUI.
|
||||
|
||||
The package is pinned, checked in and embedded by `ide-core`, so desktop, server,
|
||||
Run and debugger builds work offline and do not depend on another installed IDE.
|
||||
Only the target architecture is embedded, along with its MIT license. `src/pty.rs`
|
||||
extracts them atomically to a versioned user cache and preloads the DLL's absolute
|
||||
path before portable-pty initializes.
|
||||
Windows reuses that module when portable-pty loads `conpty.dll` by name. Loading
|
||||
failure is logged and falls back to the system backend. Windows builds before
|
||||
19041 also retain the system backend.
|
||||
|
||||
Source archive:
|
||||
`https://api.nuget.org/v3-flatcontainer/microsoft.windows.console.conpty/1.25.260930003/microsoft.windows.console.conpty.1.25.260930003.nupkg`
|
||||
|
||||
Archive SHA-256: `02b07b349af66d801159bdf9e440d4a1ce78bb951f37fc8609731665afdae7ee`
|
||||
|
||||
For each architecture, `conpty.dll` comes from
|
||||
`runtimes/win-<arch>/native/conpty.dll`, and `OpenConsole.exe` from
|
||||
`build/native/runtimes/<arch>/OpenConsole.exe` in that archive. Preserve the pair and
|
||||
the license when updating; update `VERSION` in `src/pty.rs` and these checksums too.
|
||||
|
||||
| File | SHA-256 |
|
||||
| --------------------- | ------------------------------------------------------------------ |
|
||||
| arm64/conpty.dll | `151a02355227710c20c9f8f1eaf68ac4668aa09cdc921adc7ec661804d8eb1bf` |
|
||||
| arm64/OpenConsole.exe | `4313825a3ba634d113cc6ed3bc8ce735e3c19d360cecd985794787479469f91f` |
|
||||
| x64/conpty.dll | `feeef341d891643c62d30b6b07800bc70f0bc148f44cb8c3bee84aa557ae805a` |
|
||||
| x64/OpenConsole.exe | `3d66b23d0a71bb8eed2b77edc8b9df9bf54ce6c8fb74c863a30e760997f80586` |
|
||||
| x86/conpty.dll | `d145f621bf64a9da3b7395587ddef9831ca404805d8987ec8c9903d0c4603d93` |
|
||||
| x86/OpenConsole.exe | `e3e475547d57da0689dc9fc5e0101d10390e2a4719a6eb5dcad569f6cb33c1a3` |
|
||||
|
||||
Verification: `cargo test -p ide-core pty::`. `pty::checksums` checks the embedded files against the table above on every platform. The native PTY test launches a child
|
||||
console application and requires alternate-screen entry and exit to reach the
|
||||
reader; a system ConPTY that consumes them fails this check.
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -1,319 +0,0 @@
|
||||
//! Runs a tool's CLI (`docker`, `gh`, `adb`) as a child process: bounded runs that collect
|
||||
//! its output, and cancellable streams that hand over its output line by line.
|
||||
//!
|
||||
//! Every child leads its own process group ([`own_group`]), so cancelling or timing out
|
||||
//! reaches what it started in turn (`gh` → `git`, `docker` → CLI plugins such as compose).
|
||||
//! They get [`KILL_GRACE`] to exit on `SIGTERM` and clean up (git removes its lock files)
|
||||
//! before `SIGKILL`.
|
||||
|
||||
use crate::process::{own_group, prepare, terminate_tree};
|
||||
use crate::{CancellationToken, IdeError, IdeResult};
|
||||
use std::borrow::Cow;
|
||||
use std::io::{Read, Write};
|
||||
use std::process::{Child, Command, Stdio};
|
||||
use std::sync::mpsc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// How long a cancelled or timed-out child's process group gets to exit on `SIGTERM`
|
||||
/// before `SIGKILL`.
|
||||
const KILL_GRACE: Duration = Duration::from_millis(20);
|
||||
|
||||
/// How many of a streamed child's last non-blank stderr lines are kept for its error message.
|
||||
const STDERR_TAIL: usize = 20;
|
||||
|
||||
/// How a tool's output bytes become text.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Decoding {
|
||||
/// [`decode_tool_output`](crate::output_encoding::decode_tool_output): UTF-8, and on
|
||||
/// Windows the system code page for what is not.
|
||||
ToolOutput,
|
||||
/// UTF-8, invalid bytes replaced by U+FFFD.
|
||||
Utf8Lossy,
|
||||
}
|
||||
|
||||
impl Decoding {
|
||||
fn decode(self, bytes: &[u8]) -> Cow<'_, str> {
|
||||
match self {
|
||||
Decoding::ToolOutput => Cow::Owned(crate::output_encoding::decode_tool_output(bytes)),
|
||||
Decoding::Utf8Lossy => String::from_utf8_lossy(bytes),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What a child's stdin is fed with, and how.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Input<'a> {
|
||||
/// Written before the output is read, then closed: only for input small enough
|
||||
/// (a password) to fit the pipe, as a full pipe blocks the caller.
|
||||
Inline(&'a str),
|
||||
/// Written by a thread of its own, then closed: a large body must not block on a full
|
||||
/// pipe while the child is not reading yet.
|
||||
Threaded(&'a str),
|
||||
}
|
||||
|
||||
/// How a streamed child's `\r` is read.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum CarriageReturn {
|
||||
/// Ends a line like `\n`: progress output rewrites its line in place.
|
||||
EndsLine,
|
||||
/// Is dropped; only `\n` ends a line.
|
||||
Dropped,
|
||||
}
|
||||
|
||||
/// What a bounded run collected.
|
||||
pub struct Output {
|
||||
pub stdout: String,
|
||||
pub stderr: String,
|
||||
pub success: bool,
|
||||
}
|
||||
|
||||
/// Which pipe a streamed line came from.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Stream {
|
||||
Stdout,
|
||||
Stderr,
|
||||
}
|
||||
|
||||
/// One tool's CLI: its name for error messages and how its output is decoded.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct CliTool {
|
||||
name: &'static str,
|
||||
decoding: Decoding,
|
||||
}
|
||||
|
||||
impl CliTool {
|
||||
pub const fn new(name: &'static str, decoding: Decoding) -> Self {
|
||||
Self { name, decoding }
|
||||
}
|
||||
|
||||
fn spawn(self, cmd: &mut Command) -> IdeResult<Child> {
|
||||
cmd.spawn().map_err(|e| IdeError::unavailable(format!("could not run {}: {e}", self.name)))
|
||||
}
|
||||
|
||||
/// Pipes stdout and stderr, closes stdin and starts the child in its own process group.
|
||||
fn configure(cmd: &mut Command) {
|
||||
cmd.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped());
|
||||
prepare(own_group(cmd));
|
||||
}
|
||||
|
||||
/// Runs `cmd` to completion. Fails when it outlives `timeout` or `cancel` fires;
|
||||
/// a non-zero exit is reported in [`Output::success`], not as an error.
|
||||
pub fn run(self, cmd: Command, timeout: Duration, cancel: Option<&CancellationToken>) -> IdeResult<Output> {
|
||||
self.run_with_input(cmd, None, timeout, cancel)
|
||||
}
|
||||
|
||||
/// [`run`](Self::run) with `input` written to the child's stdin and then closed.
|
||||
pub fn run_with_input(
|
||||
self,
|
||||
mut cmd: Command,
|
||||
input: Option<Input>,
|
||||
timeout: Duration,
|
||||
cancel: Option<&CancellationToken>,
|
||||
) -> IdeResult<Output> {
|
||||
Self::configure(&mut cmd);
|
||||
if input.is_some() {
|
||||
cmd.stdin(Stdio::piped());
|
||||
}
|
||||
let mut child = self.spawn(&mut cmd)?;
|
||||
match (input, child.stdin.take()) {
|
||||
(Some(Input::Inline(text)), Some(mut stdin)) => {
|
||||
// Dropping `stdin` afterwards closes it, so the CLI sees EOF.
|
||||
let _ = stdin.write_all(text.as_bytes());
|
||||
}
|
||||
(Some(Input::Threaded(text)), Some(mut stdin)) => {
|
||||
let text = text.to_owned();
|
||||
std::thread::spawn(move || {
|
||||
let _ = stdin.write_all(text.as_bytes());
|
||||
});
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
let decoding = self.decoding;
|
||||
let out = child.stdout.take().map(|pipe| read_all(pipe, decoding));
|
||||
let err = child.stderr.take().map(|pipe| read_all(pipe, decoding));
|
||||
let deadline = Instant::now() + timeout;
|
||||
let status = loop {
|
||||
if let Some(status) = child.try_wait()? {
|
||||
break status;
|
||||
}
|
||||
if cancel.is_some_and(CancellationToken::is_cancelled) {
|
||||
terminate_tree(&mut child, KILL_GRACE);
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
if Instant::now() >= deadline {
|
||||
terminate_tree(&mut child, KILL_GRACE);
|
||||
return Err(IdeError::unavailable(format!("{} did not respond in time", self.name)));
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
};
|
||||
Ok(Output {
|
||||
stdout: out.map(|t| t.join().unwrap_or_default()).unwrap_or_default(),
|
||||
stderr: err.map(|t| t.join().unwrap_or_default()).unwrap_or_default(),
|
||||
success: status.success(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Runs `cmd`, handing every output line to `on_line` until it exits or `cancel`
|
||||
/// fires. Returns whether it exited successfully plus the last stderr lines.
|
||||
pub fn stream(
|
||||
self,
|
||||
cmd: Command,
|
||||
cancel: &CancellationToken,
|
||||
on_line: &mut dyn FnMut(Stream, String),
|
||||
) -> IdeResult<(bool, Vec<String>)> {
|
||||
let mut lines = self.lines(cmd, cancel, CarriageReturn::EndsLine)?;
|
||||
let mut stderr_tail: Vec<String> = Vec::new();
|
||||
loop {
|
||||
match lines.poll(cancel, Duration::from_millis(50))? {
|
||||
Poll::Line(stream, line) => {
|
||||
if stream == Stream::Stderr && !line.trim().is_empty() {
|
||||
keep_stderr_line(&mut stderr_tail, line.clone());
|
||||
}
|
||||
on_line(stream, line);
|
||||
}
|
||||
Poll::Closed | Poll::Timeout => {}
|
||||
Poll::Finished => break,
|
||||
}
|
||||
}
|
||||
Ok((lines.finish(cancel)?, stderr_tail))
|
||||
}
|
||||
|
||||
/// Starts `cmd` with a reader thread per pipe, for a caller that drives the loop itself
|
||||
/// (see [`Lines::poll`]). Fails when `cancel` has already fired, without starting it.
|
||||
pub fn lines(self, mut cmd: Command, cancel: &CancellationToken, cr: CarriageReturn) -> IdeResult<Lines> {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
Self::configure(&mut cmd);
|
||||
let mut child = self.spawn(&mut cmd)?;
|
||||
let (tx, rx) = mpsc::channel::<Event>();
|
||||
let mut open = 0;
|
||||
if let Some(out) = child.stdout.take() {
|
||||
spawn_reader(out, tx.clone(), Stream::Stdout, self.decoding, cr);
|
||||
open += 1;
|
||||
}
|
||||
if let Some(err) = child.stderr.take() {
|
||||
spawn_reader(err, tx.clone(), Stream::Stderr, self.decoding, cr);
|
||||
open += 1;
|
||||
}
|
||||
drop(tx);
|
||||
Ok(Lines { child, rx, open })
|
||||
}
|
||||
}
|
||||
|
||||
/// Appends a stderr line to `tail`, which keeps only the last [`STDERR_TAIL`].
|
||||
pub fn keep_stderr_line(tail: &mut Vec<String>, line: String) {
|
||||
tail.push(line);
|
||||
if tail.len() > STDERR_TAIL {
|
||||
tail.remove(0);
|
||||
}
|
||||
}
|
||||
|
||||
fn read_all(mut pipe: impl Read + Send + 'static, decoding: Decoding) -> std::thread::JoinHandle<String> {
|
||||
std::thread::spawn(move || {
|
||||
let mut buf = Vec::new();
|
||||
let _ = pipe.read_to_end(&mut buf);
|
||||
decoding.decode(&buf).into_owned()
|
||||
})
|
||||
}
|
||||
|
||||
enum Event {
|
||||
Line(Stream, String),
|
||||
Closed,
|
||||
}
|
||||
|
||||
fn spawn_reader(
|
||||
mut pipe: impl Read + Send + 'static,
|
||||
tx: mpsc::Sender<Event>,
|
||||
stream: Stream,
|
||||
decoding: Decoding,
|
||||
cr: CarriageReturn,
|
||||
) {
|
||||
std::thread::spawn(move || {
|
||||
let mut buf = [0u8; 8192];
|
||||
let mut pending: Vec<u8> = Vec::new();
|
||||
let flush = |pending: &mut Vec<u8>| {
|
||||
if !pending.is_empty() {
|
||||
let line = decoding.decode(pending).trim_end().to_string();
|
||||
pending.clear();
|
||||
let _ = tx.send(Event::Line(stream, line));
|
||||
}
|
||||
};
|
||||
loop {
|
||||
match pipe.read(&mut buf) {
|
||||
Ok(0) | Err(_) => break,
|
||||
Ok(n) => {
|
||||
for &b in &buf[..n] {
|
||||
if b == b'\n' || (b == b'\r' && cr == CarriageReturn::EndsLine) {
|
||||
flush(&mut pending);
|
||||
} else if b != b'\r' {
|
||||
pending.push(b);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
flush(&mut pending);
|
||||
let _ = tx.send(Event::Closed);
|
||||
});
|
||||
}
|
||||
|
||||
/// A running child whose output lines are read by threads: see [`CliTool::lines`].
|
||||
pub struct Lines {
|
||||
child: Child,
|
||||
rx: mpsc::Receiver<Event>,
|
||||
/// Pipes whose reader has not reported its end yet.
|
||||
open: usize,
|
||||
}
|
||||
|
||||
/// What [`Lines::poll`] saw.
|
||||
pub enum Poll {
|
||||
Line(Stream, String),
|
||||
/// A pipe reached its end.
|
||||
Closed,
|
||||
/// Nothing arrived within the wait.
|
||||
Timeout,
|
||||
/// Every pipe is at its end.
|
||||
Finished,
|
||||
}
|
||||
|
||||
impl Lines {
|
||||
/// Waits up to `wait` for the next line. Fails, after killing the child, when `cancel` has fired.
|
||||
pub fn poll(&mut self, cancel: &CancellationToken, wait: Duration) -> IdeResult<Poll> {
|
||||
if self.open == 0 {
|
||||
return Ok(Poll::Finished);
|
||||
}
|
||||
if cancel.is_cancelled() {
|
||||
terminate_tree(&mut self.child, KILL_GRACE);
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
match self.rx.recv_timeout(wait) {
|
||||
Ok(Event::Line(stream, line)) => Ok(Poll::Line(stream, line)),
|
||||
Ok(Event::Closed) => {
|
||||
self.open -= 1;
|
||||
Ok(Poll::Closed)
|
||||
}
|
||||
Err(mpsc::RecvTimeoutError::Timeout) => Ok(Poll::Timeout),
|
||||
Err(mpsc::RecvTimeoutError::Disconnected) => {
|
||||
self.open = 0;
|
||||
Ok(Poll::Finished)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Waits for the child to exit and returns whether it did so successfully. Fails, after
|
||||
/// killing it, when `cancel` fires first.
|
||||
pub fn finish(mut self, cancel: &CancellationToken) -> IdeResult<bool> {
|
||||
let status = loop {
|
||||
if let Some(status) = self.child.try_wait()? {
|
||||
break status;
|
||||
}
|
||||
if cancel.is_cancelled() {
|
||||
terminate_tree(&mut self.child, KILL_GRACE);
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
};
|
||||
Ok(status.success())
|
||||
}
|
||||
}
|
||||
@@ -197,34 +197,17 @@ pub enum ImportsOnPaste {
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct FoldingSettings {
|
||||
pub show_outline: bool,
|
||||
pub outline_visibility: FoldingOutlineVisibility,
|
||||
pub file_header: bool,
|
||||
pub imports: bool,
|
||||
pub doc_comments: bool,
|
||||
pub go_short_blocks: bool,
|
||||
}
|
||||
|
||||
impl Default for FoldingSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
show_outline: true,
|
||||
outline_visibility: FoldingOutlineVisibility::Hover,
|
||||
file_header: true,
|
||||
imports: true,
|
||||
doc_comments: false,
|
||||
go_short_blocks: true,
|
||||
}
|
||||
Self { show_outline: true, file_header: true, imports: true, doc_comments: false }
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum FoldingOutlineVisibility {
|
||||
#[default]
|
||||
Hover,
|
||||
Always,
|
||||
}
|
||||
|
||||
/// Editor › General › Editor Tabs.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
@@ -290,8 +273,6 @@ pub struct SmartKeysSettings {
|
||||
pub pair_quotes: bool,
|
||||
pub surround_selection: bool,
|
||||
pub tab_out_of_pair: bool,
|
||||
/// A `;` typed before the closing `)` of a statement goes to the end of the statement.
|
||||
pub semicolon_at_statement_end: bool,
|
||||
/// Simultaneous `<tag></tag>` editing: renaming a tag renames its matching tag.
|
||||
pub simultaneous_tag_editing: bool,
|
||||
/// Reformat on paste: `none` | `indentBlock` | `indentEachLine`.
|
||||
@@ -313,7 +294,6 @@ impl Default for SmartKeysSettings {
|
||||
pair_quotes: true,
|
||||
surround_selection: true,
|
||||
tab_out_of_pair: true,
|
||||
semicolon_at_statement_end: true,
|
||||
simultaneous_tag_editing: true,
|
||||
reformat_on_paste: "indentEachLine".into(),
|
||||
escape_on_paste: true,
|
||||
@@ -338,7 +318,6 @@ pub struct CodeEditingSettings {
|
||||
/// Next / previous error goes to errors only (skips warnings).
|
||||
pub next_error_errors_only: bool,
|
||||
pub sticky_lines_max: u32,
|
||||
pub sticky_lines_disabled_languages: Vec<String>,
|
||||
}
|
||||
|
||||
impl Default for CodeEditingSettings {
|
||||
@@ -351,7 +330,6 @@ impl Default for CodeEditingSettings {
|
||||
quick_doc_delay: 500,
|
||||
next_error_errors_only: true,
|
||||
sticky_lines_max: 5,
|
||||
sticky_lines_disabled_languages: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -364,8 +342,6 @@ pub struct InlayHintsSettings {
|
||||
pub parameters: bool,
|
||||
/// Hints of other kinds (chaining, closing labels…).
|
||||
pub other: bool,
|
||||
/// The Dart server's closing labels (`// Column` after a widget's closing bracket).
|
||||
pub closing_labels: bool,
|
||||
pub disabled_languages: Vec<String>,
|
||||
/// Code vision as a whole (usages, author and language-server lenses); the switches below apply while it is on.
|
||||
pub code_vision: bool,
|
||||
@@ -398,7 +374,6 @@ impl Default for InlayHintsSettings {
|
||||
types: true,
|
||||
parameters: true,
|
||||
other: true,
|
||||
closing_labels: true,
|
||||
disabled_languages: Vec::new(),
|
||||
code_vision: true,
|
||||
code_vision_usages: true,
|
||||
@@ -445,9 +420,6 @@ pub struct TextAttributesOverride {
|
||||
pub effect: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub effect_color: Option<String>,
|
||||
/// IDEA's `ERROR_STRIPE_COLOR`: the diff overview-lane marker of a change type.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub error_stripe_color: Option<String>,
|
||||
}
|
||||
|
||||
/// Editor › Code Style › <Language> › Tabs and Indents (unset fields inherit).
|
||||
@@ -480,12 +452,6 @@ pub struct LanguageCodeStyle {
|
||||
/// PHP: align `=` of consecutive assignment statements after formatting.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub align_consecutive_assignments: Option<bool>,
|
||||
/// SQL › Case › Keywords: `upper` | `lower` | `keep` (other languages ignore it).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub keyword_case: Option<String>,
|
||||
/// SQL › Case › Identifiers (unquoted names): `upper` | `lower` | `keep`.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub identifier_case: Option<String>,
|
||||
}
|
||||
|
||||
/// Editor › Code Style (General tab + per-language overrides).
|
||||
@@ -577,41 +543,3 @@ mod auto_import_tests {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod folding_tests {
|
||||
use super::{FoldingOutlineVisibility, FoldingSettings};
|
||||
|
||||
#[test]
|
||||
fn folding_outline_defaults_to_hover_for_existing_settings() {
|
||||
let settings: FoldingSettings = serde_json::from_str(r#"{"showOutline":false}"#).unwrap();
|
||||
assert!(!settings.show_outline);
|
||||
assert_eq!(settings.outline_visibility, FoldingOutlineVisibility::Hover);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn folding_outline_visibility_round_trips() {
|
||||
for mode in ["hover", "always"] {
|
||||
let json = serde_json::json!({ "outlineVisibility": mode });
|
||||
let settings: FoldingSettings = serde_json::from_value(json).unwrap();
|
||||
assert_eq!(serde_json::to_value(settings).unwrap()["outlineVisibility"], mode);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod sticky_lines_tests {
|
||||
use super::CodeEditingSettings;
|
||||
|
||||
#[test]
|
||||
fn sticky_lines_language_exclusions_round_trip_and_default_to_empty() {
|
||||
let old: CodeEditingSettings = serde_json::from_value(serde_json::json!({"stickyLinesMax": 3})).unwrap();
|
||||
assert_eq!(old.sticky_lines_max, 3);
|
||||
assert!(old.sticky_lines_disabled_languages.is_empty());
|
||||
let json = serde_json::json!(["markdown", "rust"]);
|
||||
let saved: CodeEditingSettings =
|
||||
serde_json::from_value(serde_json::json!({"stickyLinesDisabledLanguages": json})).unwrap();
|
||||
assert_eq!(saved.sticky_lines_disabled_languages, ["markdown", "rust"]);
|
||||
assert_eq!(serde_json::to_value(saved).unwrap()["stickyLinesDisabledLanguages"], json);
|
||||
}
|
||||
}
|
||||
@@ -20,77 +20,7 @@ pub struct IdeError {
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(tag = "type", rename_all = "camelCase")]
|
||||
pub enum ErrorData {
|
||||
Tool {
|
||||
tool: String,
|
||||
missing: bool,
|
||||
},
|
||||
/// A non-fast-forward push from the current branch to its configured upstream.
|
||||
PushRejected {
|
||||
source: String,
|
||||
upstream: String,
|
||||
divergence: Option<Box<PushDivergence>>,
|
||||
/// Other refs may already have been published in the same push.
|
||||
#[specta(optional)]
|
||||
report: Option<Box<PushReport>>,
|
||||
},
|
||||
/// Git updated some refs before a later ref or push URL failed.
|
||||
PushPartiallyApplied {
|
||||
report: Box<PushReport>,
|
||||
},
|
||||
/// A conflicted history replay left an amend commit ready to keep separately.
|
||||
AmendConflict {
|
||||
commit: String,
|
||||
},
|
||||
/// jdtls could not set a module up as a Java project: the errors on its build files and
|
||||
/// the builds enclosing it (`path: message`, the path relative to the project), nearest first.
|
||||
JavaBuildProblems {
|
||||
problems: Vec<String>,
|
||||
},
|
||||
}
|
||||
|
||||
/// Git's reported result for each destination ref. A remote with several push URLs can
|
||||
/// report more than one result for the same ref.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
pub struct PushReport {
|
||||
pub remote: Option<String>,
|
||||
pub refs: Vec<PushRefResult>,
|
||||
}
|
||||
|
||||
impl PushReport {
|
||||
pub fn new(remote: Option<String>) -> Self {
|
||||
Self { remote, refs: Vec::new() }
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
pub struct PushRefResult {
|
||||
pub reference: String,
|
||||
pub status: PushRefStatus,
|
||||
/// The number of commits between the tips Git reports for a fast-forward.
|
||||
pub commits: Option<u32>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum PushRefStatus {
|
||||
FastForward,
|
||||
Forced,
|
||||
Created,
|
||||
UpToDate,
|
||||
Deleted,
|
||||
}
|
||||
|
||||
/// The two tips shown in the rejected-push dialog. A retry must use this lease
|
||||
/// even if a fetch advances the remote-tracking branch while the dialog is open.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PushDivergence {
|
||||
pub source: String,
|
||||
pub remote: String,
|
||||
pub target: String,
|
||||
pub local_tip: String,
|
||||
pub remote_tip: String,
|
||||
pub remote_commits: u32,
|
||||
Tool { tool: String, missing: bool },
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
@@ -100,7 +30,7 @@ pub enum ErrorKind {
|
||||
AlreadyExists,
|
||||
PermissionDenied,
|
||||
InvalidInput,
|
||||
/// The requested state is stale; the UI must use the current snapshot.
|
||||
/// Document version mismatch; the UI must resync the full text.
|
||||
OutOfSync,
|
||||
Cancelled,
|
||||
TimedOut,
|
||||
@@ -185,13 +115,4 @@ mod tests {
|
||||
serde_json::json!({"kind":"unavailable","message":"no server","data":null})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn older_tracked_push_rejections_need_no_report() {
|
||||
let data: ErrorData = serde_json::from_str(
|
||||
r#"{"type":"pushRejected","source":"main","upstream":"origin/main","divergence":null}"#,
|
||||
)
|
||||
.unwrap();
|
||||
assert!(matches!(data, ErrorData::PushRejected { report: None, .. }));
|
||||
}
|
||||
}
|
||||
@@ -36,15 +36,12 @@ pub enum IdeEvent {
|
||||
},
|
||||
/// Project window membership or selection changed.
|
||||
WindowGroupsChanged,
|
||||
/// A project was loaded or unloaded for the MCP server without a window of its own.
|
||||
McpBackgroundProjectsChanged,
|
||||
/// A window entered or left full screen, itself or as a member of a full-screen window group.
|
||||
WindowFullscreenChanged,
|
||||
/// This remote window's connection ended or another window took over the session.
|
||||
/// This remote window's connection to its host ended on its own (network loss, the host or
|
||||
/// its server went away); the window's project is unreachable until it reconnects.
|
||||
RemoteConnectionLost {
|
||||
host: String,
|
||||
#[serde(default)]
|
||||
taken_over: bool,
|
||||
},
|
||||
ProjectTrustChanged {
|
||||
root: crate::IpcPath,
|
||||
@@ -90,21 +87,11 @@ pub enum IdeEvent {
|
||||
DocDirty {
|
||||
doc: DocId,
|
||||
dirty: bool,
|
||||
/// Text version when this transition occurred, including when it was saved.
|
||||
version: u32,
|
||||
},
|
||||
/// An open document's file changed on disk while the buffer had unsaved changes. The buffer
|
||||
/// keeps them (autosave leaves the file alone); the UI offers to load the disk version.
|
||||
DocDiskConflict {
|
||||
doc: DocId,
|
||||
path: String,
|
||||
},
|
||||
/// A complete workspace edit can be undone as one operation.
|
||||
WorkspaceEditApplied {
|
||||
id: u32,
|
||||
paths: Vec<crate::IpcPath>,
|
||||
/// Files the edit renamed, as the edit named them: editors open on them follow.
|
||||
moves: Vec<crate::FileMove>,
|
||||
/// Made by an agent through the MCP server's tools: undoable like a refactoring, but
|
||||
/// not announced as one.
|
||||
by_agent: bool,
|
||||
@@ -264,20 +251,6 @@ pub struct FlutterDevice {
|
||||
pub emulator: bool,
|
||||
/// The adb state keeping it from being used (`unauthorized`, `offline`, …).
|
||||
pub unavailable: Option<String>,
|
||||
/// The [`FlutterEmulator`] it runs on: an AVD name, or `apple_ios_simulator`.
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub emulator_id: Option<String>,
|
||||
}
|
||||
|
||||
/// An Android emulator (AVD) or the iOS Simulator that `flutter emulators --launch` can start.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct FlutterEmulator {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
/// `android` or `ios`.
|
||||
pub platform_type: Option<String>,
|
||||
}
|
||||
|
||||
/// See [`FlutterDeviceList`].
|
||||
@@ -303,10 +276,6 @@ pub enum FlutterDaemonStatus {
|
||||
pub struct FlutterDeviceList {
|
||||
pub status: FlutterDaemonStatus,
|
||||
pub devices: Vec<FlutterDevice>,
|
||||
/// The emulators that no listed device runs on.
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub emulators: Vec<FlutterEmulator>,
|
||||
}
|
||||
|
||||
/// See [`IdeEvent::Direnv`].
|
||||
@@ -343,8 +312,6 @@ pub enum LspRefreshKind {
|
||||
InlayHints,
|
||||
SemanticTokens,
|
||||
CodeLens,
|
||||
/// An import or classpath update may have changed inheritance search results.
|
||||
Inheritance,
|
||||
/// The Dart server published a document's Flutter outline.
|
||||
FlutterOutline,
|
||||
}
|
||||
|
||||
@@ -71,11 +71,6 @@ pub struct SpellingSettings {
|
||||
pub project_words: Vec<String>,
|
||||
/// Custom dictionaries: plain word lists or Hunspell `.dic` files.
|
||||
pub custom_dictionaries: Vec<String>,
|
||||
/// Where "Save '…' to dictionary" writes: `project`, `application`, or a
|
||||
/// `spelling.customDictionaries` entry verbatim; empty (the default) is
|
||||
/// project when one is open, application otherwise.
|
||||
#[specta(optional)]
|
||||
pub default_dictionary: Option<String>,
|
||||
}
|
||||
|
||||
/// Changes to one inspection; absent fields keep the inspection's defaults.
|
||||
|
||||
@@ -1,122 +0,0 @@
|
||||
//! Binary arguments of IPC commands travel as base64 text: [`IpcBytes`] is a `Vec<u8>` that
|
||||
//! serializes as a standard padded base64 string and is a plain `string` in the generated
|
||||
//! bindings.
|
||||
//!
|
||||
//! A plain `Vec<u8>` is a JSON array of numbers, 3.6 times the size of the bytes, and parsing it
|
||||
//! into a `serde_json::Value` (the remote protocol and Tauri both do) takes about 50 times the
|
||||
//! bytes in memory: 20 MB become about 1 GB. Base64 is 1.33 times the size and one string.
|
||||
|
||||
use base64::Engine;
|
||||
use base64::engine::general_purpose::STANDARD;
|
||||
use serde::de::{self, Visitor};
|
||||
use serde::{Deserialize, Deserializer, Serialize, Serializer};
|
||||
use std::fmt;
|
||||
use std::ops::Deref;
|
||||
|
||||
/// A binary argument or result of an IPC command.
|
||||
#[derive(Clone, Default, PartialEq, Eq, specta::Type)]
|
||||
#[specta(transparent)]
|
||||
pub struct IpcBytes(#[specta(type = String)] pub Vec<u8>);
|
||||
|
||||
impl IpcBytes {
|
||||
pub fn into_vec(self) -> Vec<u8> {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for IpcBytes {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "IpcBytes({} bytes)", self.0.len())
|
||||
}
|
||||
}
|
||||
|
||||
impl Serialize for IpcBytes {
|
||||
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
|
||||
s.serialize_str(&STANDARD.encode(&self.0))
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for IpcBytes {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
struct Base64;
|
||||
impl Visitor<'_> for Base64 {
|
||||
type Value = IpcBytes;
|
||||
|
||||
fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str("a base64 string")
|
||||
}
|
||||
|
||||
fn visit_str<E: de::Error>(self, v: &str) -> Result<IpcBytes, E> {
|
||||
STANDARD.decode(v).map(IpcBytes).map_err(|e| E::custom(format!("invalid base64: {e}")))
|
||||
}
|
||||
}
|
||||
d.deserialize_str(Base64)
|
||||
}
|
||||
}
|
||||
|
||||
impl Deref for IpcBytes {
|
||||
type Target = [u8];
|
||||
fn deref(&self) -> &[u8] {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Vec<u8>> for IpcBytes {
|
||||
fn from(bytes: Vec<u8>) -> Self {
|
||||
Self(bytes)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
fn round_trip(bytes: Vec<u8>) {
|
||||
let value = serde_json::to_value(IpcBytes(bytes.clone())).unwrap();
|
||||
let text = value.as_str().expect("serializes as a string");
|
||||
assert_eq!(text.len(), bytes.len().div_ceil(3) * 4);
|
||||
assert_eq!(serde_json::from_value::<IpcBytes>(value).unwrap().into_vec(), bytes);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn round_trips_empty_every_byte_and_large_input() {
|
||||
round_trip(Vec::new());
|
||||
round_trip((0..=255).collect());
|
||||
round_trip((0..=255).rev().cycle().take(5 * 1024 * 1024 + 1).collect());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn round_trips_through_a_json_document() {
|
||||
let bytes: Vec<u8> = (0..=255).collect();
|
||||
let text = serde_json::to_string(&json!({ "data": IpcBytes(bytes.clone()) })).unwrap();
|
||||
#[derive(Deserialize)]
|
||||
struct Args {
|
||||
data: IpcBytes,
|
||||
}
|
||||
assert_eq!(serde_json::from_str::<Args>(&text).unwrap().data.into_vec(), bytes);
|
||||
}
|
||||
|
||||
/// The old wire form of a `Vec<u8>`: 3.6 times the bytes. The string must stay near 4/3.
|
||||
#[test]
|
||||
fn serialized_form_is_a_string_about_a_third_larger_than_the_bytes() {
|
||||
let bytes: Vec<u8> = (0..=255).cycle().take(1_000_000).collect();
|
||||
let json = serde_json::to_string(&IpcBytes(bytes.clone())).unwrap();
|
||||
assert!(json.starts_with('"') && json.ends_with('"'));
|
||||
assert!(json.len() <= bytes.len().div_ceil(3) * 4 + 2, "{} bytes for {}", json.len(), bytes.len());
|
||||
let as_array = serde_json::to_string(&bytes).unwrap();
|
||||
assert!(json.len() * 2 < as_array.len(), "{} vs {}", json.len(), as_array.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_what_is_not_base64() {
|
||||
for bad in [json!([1, 2, 3]), json!(7), Value::Null, json!("not base64!"), json!("QQ"), json!("QQ=a")] {
|
||||
assert!(serde_json::from_value::<IpcBytes>(bad.clone()).is_err(), "{bad}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn debug_does_not_print_the_bytes() {
|
||||
assert_eq!(format!("{:?}", IpcBytes(vec![0; 3])), "IpcBytes(3 bytes)");
|
||||
}
|
||||
}
|
||||
@@ -40,10 +40,6 @@ pub fn strip(src: &str) -> String {
|
||||
if prev == '*' && n == '/' {
|
||||
break;
|
||||
}
|
||||
// Keep the comment's line breaks so parse errors report the original line.
|
||||
if n == '\n' {
|
||||
out.push('\n');
|
||||
}
|
||||
prev = n;
|
||||
}
|
||||
}
|
||||
@@ -69,7 +65,7 @@ pub fn strip(src: &str) -> String {
|
||||
in_str = true;
|
||||
cleaned.push(c);
|
||||
} else if c == ',' {
|
||||
let next = bytes[i + 1..].iter().find(|ch| !ch.is_ascii_whitespace());
|
||||
let next = bytes[i + 1..].iter().find(|ch| !ch.is_whitespace());
|
||||
if !matches!(next, Some('}') | Some(']')) {
|
||||
cleaned.push(c);
|
||||
}
|
||||
@@ -99,53 +95,4 @@ mod tests {
|
||||
let v: serde_json::Value = serde_json::from_str(&strip("\u{feff}{ \"a\": 1 }")).unwrap();
|
||||
assert_eq!(v["a"], 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_line_breaks_of_block_comments_so_errors_report_the_original_line() {
|
||||
assert_eq!(strip("{\"a\"/*\n\n*/:x}"), "{\"a\"\n\n:x}");
|
||||
let err = serde_json::from_str::<serde_json::Value>(&strip("{\"a\"/*\n\n*/:x}")).unwrap_err();
|
||||
assert_eq!(err.line(), 3);
|
||||
// A comment is whitespace, not a join: `1 2` stays invalid.
|
||||
assert!(serde_json::from_str::<serde_json::Value>(&strip("1/*\n*/2")).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn line_comments_keep_their_line_break_and_may_end_the_input() {
|
||||
assert_eq!(strip("{\"a\":1} // tail"), "{\"a\":1} ");
|
||||
assert_eq!(strip("// a\r\n{\"a\":1}"), "\n{\"a\":1}");
|
||||
assert_eq!(strip("[1, // c\n2]"), "[1, \n2]");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unterminated_block_comment_drops_the_rest() {
|
||||
assert_eq!(strip("{\"a\":1}/* open"), "{\"a\":1}");
|
||||
assert_eq!(strip("/*"), "");
|
||||
assert_eq!(strip("/*/ x"), "");
|
||||
assert_eq!(strip("/**/{}"), "{}");
|
||||
assert_eq!(strip("/***/{}"), "{}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn comment_markers_inside_strings_survive_including_after_escapes() {
|
||||
let src = "{\"a\":\"\\\\\",\"b\":\"//x\",\"c\":\"/*y*/\",\"d\":\"é,\u{1F600}\"} // é";
|
||||
let v: serde_json::Value = serde_json::from_str(&strip(src)).unwrap();
|
||||
assert_eq!(v, serde_json::json!({"a": "\\", "b": "//x", "c": "/*y*/", "d": "é,\u{1F600}"}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trailing_commas_are_dropped_across_whitespace_and_comments_only_before_a_closer() {
|
||||
assert_eq!(strip("[1,2, ]"), "[1,2 ]");
|
||||
assert_eq!(strip("[1,\r\n]"), "[1\r\n]");
|
||||
assert_eq!(strip("[1,/*c*/]"), "[1]");
|
||||
assert_eq!(strip("[1,//c\n]"), "[1\n]");
|
||||
assert_eq!(strip("[1,/*c*/ ,]"), "[1, ]");
|
||||
assert_eq!(strip("{\"a\":\"x,}\"}"), "{\"a\":\"x,}\"}");
|
||||
assert_eq!(strip("[1,2]"), "[1,2]");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_json_whitespace_may_separate_a_trailing_comma_from_its_closer() {
|
||||
// U+00A0 is not JSON whitespace: the comma stays and serde_json reports it.
|
||||
assert_eq!(strip("[1,\u{a0}]"), "[1,\u{a0}]");
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,6 @@
|
||||
//! feature crates depend on `ide-core` and never on each other's internals.
|
||||
//! All IPC-facing types derive `specta::Type`, which generates `src/bindings.ts`.
|
||||
|
||||
pub mod cli_process;
|
||||
pub mod editor_settings;
|
||||
pub mod error;
|
||||
pub mod event;
|
||||
@@ -13,11 +12,9 @@ pub mod ids;
|
||||
pub mod ignored;
|
||||
pub mod input;
|
||||
pub mod inspection_settings;
|
||||
pub mod ipc_bytes;
|
||||
pub mod ipc_path;
|
||||
pub mod java_runtime;
|
||||
pub mod jsonc;
|
||||
pub mod memory;
|
||||
pub mod output_encoding;
|
||||
pub mod platform;
|
||||
pub mod process;
|
||||
@@ -25,7 +22,6 @@ pub mod project_dir;
|
||||
pub mod project_env;
|
||||
pub mod project_roots;
|
||||
pub mod proxy_settings;
|
||||
pub mod pty;
|
||||
pub mod real_path;
|
||||
pub mod remote_settings;
|
||||
pub mod settings;
|
||||
@@ -33,7 +29,6 @@ pub mod task;
|
||||
pub mod text;
|
||||
pub mod tool_path;
|
||||
pub mod updates;
|
||||
pub mod utf8;
|
||||
pub mod version_managers;
|
||||
pub mod workflow_settings;
|
||||
pub mod wsl;
|
||||
@@ -41,7 +36,6 @@ pub mod wsl;
|
||||
pub use error::{IdeError, IdeResult};
|
||||
pub use event::{EventSink, IdeEvent, NullSink, SharedSink};
|
||||
pub use ids::*;
|
||||
pub use ipc_bytes::IpcBytes;
|
||||
pub use ipc_path::IpcPath;
|
||||
pub use text::*;
|
||||
pub use tokio_util::sync::CancellationToken;
|
||||
@@ -1,20 +0,0 @@
|
||||
//! Returning freed heap pages to the OS.
|
||||
|
||||
/// Hands pages the allocator has freed but kept back to the OS. Call after a burst of
|
||||
/// short-lived allocations (a full index scan); until then they still count towards the
|
||||
/// process's memory footprint.
|
||||
pub fn release_free_pages() {
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
unsafe extern "C" {
|
||||
fn malloc_zone_pressure_relief(zone: *mut std::ffi::c_void, goal: usize) -> usize;
|
||||
}
|
||||
// SAFETY: a null zone covers every zone; a zero goal releases as much as possible.
|
||||
unsafe { malloc_zone_pressure_relief(std::ptr::null_mut(), 0) };
|
||||
}
|
||||
#[cfg(all(target_os = "linux", target_env = "gnu"))]
|
||||
// SAFETY: malloc_trim only returns free memory to the OS.
|
||||
unsafe {
|
||||
libc::malloc_trim(0);
|
||||
}
|
||||
}
|
||||
@@ -72,16 +72,6 @@ impl WindowButtonLayout {
|
||||
let right = side(parts.next());
|
||||
(!left.is_empty() || !right.is_empty()).then_some(Self { left, right })
|
||||
}
|
||||
|
||||
/// The layout on Linux: the desktop's `gtk-decoration-layout` when a desktop session is running.
|
||||
/// Without one (WSLg, a bare compositor) GTK reports its built-in fallback, close only, which
|
||||
/// leaves no way to minimise or maximise the frameless window, so the default applies.
|
||||
pub fn for_linux(gtk_layout: Option<&str>, var: impl Fn(&str) -> Option<String>) -> Self {
|
||||
let desktop = ["XDG_CURRENT_DESKTOP", "XDG_SESSION_DESKTOP", "DESKTOP_SESSION"]
|
||||
.iter()
|
||||
.any(|key| var(key).is_some_and(|value| !value.trim().is_empty()));
|
||||
gtk_layout.filter(|_| desktop).and_then(Self::from_gtk_decoration_layout).unwrap_or_default()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -128,25 +118,6 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn linux_layout_needs_a_desktop_session() {
|
||||
let env = |vars: &'static [(&'static str, &'static str)]| {
|
||||
move |key: &str| vars.iter().find(|(k, _)| *k == key).map(|(_, v)| v.to_string())
|
||||
};
|
||||
let gnome = env(&[("XDG_CURRENT_DESKTOP", "ubuntu:GNOME")]);
|
||||
assert_eq!(WindowButtonLayout::for_linux(Some("appmenu:close"), gnome), layout(&[], &[Close]).unwrap());
|
||||
let kde = env(&[("DESKTOP_SESSION", "plasma")]);
|
||||
assert_eq!(
|
||||
WindowButtonLayout::for_linux(Some("close,maximize,minimize:icon"), kde),
|
||||
layout(&[Close, Maximize, Minimize], &[]).unwrap()
|
||||
);
|
||||
// WSLg: no desktop session, GTK's fallback layout.
|
||||
let wslg = env(&[("WAYLAND_DISPLAY", "wayland-0"), ("XDG_CURRENT_DESKTOP", " ")]);
|
||||
assert_eq!(WindowButtonLayout::for_linux(Some("menu:close"), wslg), WindowButtonLayout::default());
|
||||
let gnome = env(&[("XDG_SESSION_DESKTOP", "gnome")]);
|
||||
assert_eq!(WindowButtonLayout::for_linux(None, gnome), WindowButtonLayout::default());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_layout_is_on_the_right() {
|
||||
assert_eq!(WindowButtonLayout::default(), layout(&[], &[Minimize, Maximize, Close]).unwrap());
|
||||
|
||||
@@ -5,10 +5,6 @@ use std::path::Path;
|
||||
#[cfg(windows)]
|
||||
use std::process::Stdio;
|
||||
use std::process::{Child, Command};
|
||||
|
||||
pub const ASKPASS_PORT_ENV: &str = "OPENIDEA_ASKPASS_PORT";
|
||||
/// The IDE's askpass helper may answer with saved credentials only.
|
||||
pub const ASKPASS_SILENT_ENV: &str = "OPENIDEA_ASKPASS_SILENT";
|
||||
use std::sync::{Arc, RwLock};
|
||||
use std::time::Duration;
|
||||
|
||||
@@ -402,14 +398,12 @@ mod windows_job {
|
||||
use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle, RawHandle};
|
||||
use windows_sys::Win32::Foundation::{ERROR_MORE_DATA, INVALID_HANDLE_VALUE};
|
||||
use windows_sys::Win32::System::JobObjects::{
|
||||
AssignProcessToJobObject, CreateJobObjectW, IsProcessInJob, JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,
|
||||
AssignProcessToJobObject, CreateJobObjectW, JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,
|
||||
JOBOBJECT_BASIC_LIMIT_INFORMATION, JOBOBJECT_BASIC_PROCESS_ID_LIST, JOBOBJECT_EXTENDED_LIMIT_INFORMATION,
|
||||
JobObjectBasicProcessIdList, JobObjectExtendedLimitInformation, QueryInformationJobObject,
|
||||
SetInformationJobObject, TerminateJobObject,
|
||||
};
|
||||
use windows_sys::Win32::System::Threading::{
|
||||
IO_COUNTERS, OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION, PROCESS_SET_QUOTA, PROCESS_TERMINATE,
|
||||
};
|
||||
use windows_sys::Win32::System::Threading::{IO_COUNTERS, OpenProcess, PROCESS_SET_QUOTA, PROCESS_TERMINATE};
|
||||
|
||||
/// A job object holding one launch's processes. The handle is kept open for the
|
||||
/// launch's lifetime: `KILL_ON_JOB_CLOSE` ends anything still in the job when the
|
||||
@@ -512,21 +506,6 @@ mod windows_job {
|
||||
ok != 0
|
||||
}
|
||||
|
||||
/// Whether the running process belongs to this specific launch's job.
|
||||
pub fn contains_pid(&self, pid: u32) -> bool {
|
||||
// SAFETY: a non-null result is a process handle owned by this call.
|
||||
let handle = unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid) };
|
||||
if handle.is_null() {
|
||||
return false;
|
||||
}
|
||||
// SAFETY: the process handle was just opened above and the job handle is owned here.
|
||||
let handle = unsafe { OwnedHandle::from_raw_handle(handle) };
|
||||
let mut contained = 0;
|
||||
// SAFETY: both handles remain valid and `contained` is a writable BOOL.
|
||||
(unsafe { IsProcessInJob(handle.as_raw_handle(), self.0.as_raw_handle(), &mut contained) }) != 0
|
||||
&& contained != 0
|
||||
}
|
||||
|
||||
/// Terminates every process in the job. `false` when the call failed (the job
|
||||
/// handle is invalid): callers then fall back to `taskkill /T /F`. Termination is
|
||||
/// asynchronous; poll [`Job::is_running`] (bounded by [`TREE_EXIT_WAIT`]) until
|
||||
@@ -1351,45 +1330,6 @@ mod tests {
|
||||
assert_eq!(cmd.get_envs().find(|(k, _)| *k == "PATH").and_then(|(_, v)| v), Some(OsStr::new("/custom")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unix_uses_the_name_as_is() {
|
||||
assert_eq!(executable_names("kotlinc", false, Some(".BAT")), ["kotlinc"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn windows_appends_pathext_extensions() {
|
||||
assert_eq!(
|
||||
executable_names("kotlinc", true, None),
|
||||
["kotlinc.com", "kotlinc.exe", "kotlinc.bat", "kotlinc.cmd"]
|
||||
);
|
||||
assert_eq!(executable_names("npx", true, Some(".EXE;.CMD;;")), ["npx.exe", "npx.cmd"]);
|
||||
assert_eq!(executable_names("npx", true, Some(" ")), executable_names("npx", true, None));
|
||||
// Already has an executable extension (any case): only that file.
|
||||
assert_eq!(executable_names("rustc.EXE", true, None), ["rustc.EXE"]);
|
||||
assert_eq!(executable_names("gradlew.bat", true, None), ["gradlew.bat"]);
|
||||
// A dot that is not an executable extension (`clang++`, `python3.12`).
|
||||
assert_eq!(executable_names("python3.12", true, Some(".EXE")), ["python3.12.exe"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn finds_batch_files_and_skips_extensionless_scripts_on_windows() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let a = dir.path().join("a");
|
||||
let b = dir.path().join("b");
|
||||
std::fs::create_dir_all(&a).unwrap();
|
||||
std::fs::create_dir_all(&b).unwrap();
|
||||
// `node_modules/.bin` style: a POSIX script next to its `.cmd` shim.
|
||||
std::fs::write(a.join("tsx"), "#!/bin/sh\n").unwrap();
|
||||
std::fs::write(b.join("tsx.cmd"), "@echo off\n").unwrap();
|
||||
std::fs::write(b.join("kotlinc.bat"), "@echo off\n").unwrap();
|
||||
let search = std::env::join_paths([&a, &b]).unwrap();
|
||||
assert_eq!(find_executable_in("tsx", &search, true, None), Some(b.join("tsx.cmd")));
|
||||
assert_eq!(find_executable_in("kotlinc", &search, true, None), Some(b.join("kotlinc.bat")));
|
||||
assert_eq!(find_executable_in("tsx", &search, false, None), Some(a.join("tsx")));
|
||||
assert_eq!(find_executable_in("kotlinc", &search, false, None), None);
|
||||
assert_eq!(find_executable_in("nope", &search, true, None), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn find_executable_finds_bare_names_on_the_given_path() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -1,254 +0,0 @@
|
||||
//! The PTY backend shared by terminals, Run consoles and debugger launchers.
|
||||
|
||||
pub fn native_pty_system() -> Box<dyn portable_pty::PtySystem + Send> {
|
||||
#[cfg(windows)]
|
||||
windows::initialize();
|
||||
portable_pty::native_pty_system()
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
mod windows {
|
||||
use std::fs;
|
||||
use std::io::{self, Write};
|
||||
use std::os::windows::ffi::OsStrExt;
|
||||
use std::path::Path;
|
||||
use std::sync::OnceLock;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use windows_sys::Win32::Foundation::FreeLibrary;
|
||||
use windows_sys::Win32::System::LibraryLoader::{
|
||||
GetProcAddress, LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR, LOAD_LIBRARY_SEARCH_SYSTEM32, LoadLibraryExW,
|
||||
};
|
||||
|
||||
const VERSION: &str = "1.25.260930003";
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
const RUNTIME: (&str, &[u8], &[u8]) = (
|
||||
"x64",
|
||||
include_bytes!("../resources/conpty/x64/conpty.dll"),
|
||||
include_bytes!("../resources/conpty/x64/OpenConsole.exe"),
|
||||
);
|
||||
#[cfg(target_arch = "aarch64")]
|
||||
const RUNTIME: (&str, &[u8], &[u8]) = (
|
||||
"arm64",
|
||||
include_bytes!("../resources/conpty/arm64/conpty.dll"),
|
||||
include_bytes!("../resources/conpty/arm64/OpenConsole.exe"),
|
||||
);
|
||||
#[cfg(target_arch = "x86")]
|
||||
const RUNTIME: (&str, &[u8], &[u8]) = (
|
||||
"x86",
|
||||
include_bytes!("../resources/conpty/x86/conpty.dll"),
|
||||
include_bytes!("../resources/conpty/x86/OpenConsole.exe"),
|
||||
);
|
||||
|
||||
pub(super) fn initialize() -> bool {
|
||||
static BUNDLED: OnceLock<bool> = OnceLock::new();
|
||||
*BUNDLED.get_or_init(|| {
|
||||
if !crate::platform::windows_build_number().is_some_and(|build| build >= 19041) {
|
||||
return false;
|
||||
}
|
||||
match load() {
|
||||
Ok(()) => true,
|
||||
Err(error) => {
|
||||
tracing::warn!(%error, "bundled ConPTY unavailable; using the system terminal backend");
|
||||
false
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn load() -> io::Result<()> {
|
||||
let cache = dirs::cache_dir().ok_or_else(|| io::Error::other("no user cache directory"))?;
|
||||
let directory = cache.join("OpenIDEA").join("conpty").join(VERSION).join(RUNTIME.0);
|
||||
fs::create_dir_all(&directory)?;
|
||||
install(&directory.join("LICENSE.txt"), include_bytes!("../resources/conpty/LICENSE"))?;
|
||||
install(&directory.join("OpenConsole.exe"), RUNTIME.2)?;
|
||||
let library = directory.join("conpty.dll");
|
||||
install(&library, RUNTIME.1)?;
|
||||
let wide: Vec<u16> = library.as_os_str().encode_wide().chain(Some(0)).collect();
|
||||
// portable-pty 0.9 opens conpty.dll by name. Preload our verified absolute path:
|
||||
// Windows reuses this module, without adding the project directory to DLL search.
|
||||
// SAFETY: the path is terminated and the module is retained for the process lifetime.
|
||||
let module = unsafe {
|
||||
LoadLibraryExW(
|
||||
wide.as_ptr(),
|
||||
std::ptr::null_mut(),
|
||||
LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_SYSTEM32,
|
||||
)
|
||||
};
|
||||
if module.is_null() {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
for name in [c"CreatePseudoConsole", c"ResizePseudoConsole", c"ClosePseudoConsole"] {
|
||||
// SAFETY: `module` is loaded and each name is a terminated export name.
|
||||
if unsafe { GetProcAddress(module, name.as_ptr().cast()) }.is_none() {
|
||||
// SAFETY: no PTY uses this rejected module yet; release our load reference.
|
||||
unsafe { FreeLibrary(module) };
|
||||
return Err(io::Error::other("bundled ConPTY lacks the portable-pty exports"));
|
||||
}
|
||||
}
|
||||
// Keep this reference for the process lifetime, including between PTY sessions.
|
||||
tracing::info!(path = %library.display(), version = VERSION, "loaded bundled ConPTY");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn install(path: &Path, data: &[u8]) -> io::Result<()> {
|
||||
if fs::read(path).is_ok_and(|existing| existing == data) {
|
||||
return Ok(());
|
||||
}
|
||||
static NEXT: AtomicU64 = AtomicU64::new(0);
|
||||
let pending =
|
||||
path.with_extension(format!("{}-{}.tmp", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
|
||||
let result = (|| {
|
||||
let mut file = fs::OpenOptions::new().write(true).create_new(true).open(&pending)?;
|
||||
file.write_all(data)?;
|
||||
file.sync_all()?;
|
||||
drop(file);
|
||||
match fs::rename(&pending, path) {
|
||||
Ok(()) => Ok(()),
|
||||
Err(_) if fs::read(path).is_ok_and(|existing| existing == data) => Ok(()),
|
||||
Err(error) => Err(error),
|
||||
}
|
||||
})();
|
||||
let _ = fs::remove_file(pending);
|
||||
result
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn installs_atomically_and_repairs_incomplete_files() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("conpty.dll");
|
||||
fs::write(&path, b"partial").unwrap();
|
||||
std::thread::scope(|scope| {
|
||||
for _ in 0..8 {
|
||||
let path = &path;
|
||||
scope.spawn(move || install(path, b"complete runtime").unwrap());
|
||||
}
|
||||
});
|
||||
assert_eq!(fs::read(&path).unwrap(), b"complete runtime");
|
||||
assert_eq!(fs::read_dir(dir.path()).unwrap().count(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn loads_the_bundled_backend() {
|
||||
assert!(initialize());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn conpty_output_child() {
|
||||
if std::env::var_os("OPENIDEA_CONPTY_TEST_CHILD").is_none() {
|
||||
return;
|
||||
}
|
||||
use windows_sys::Win32::System::Console::{
|
||||
ENABLE_VIRTUAL_TERMINAL_PROCESSING, GetConsoleMode, GetStdHandle, STD_OUTPUT_HANDLE, SetConsoleMode,
|
||||
};
|
||||
// SAFETY: the inherited console output handle and a local writable mode word.
|
||||
unsafe {
|
||||
let output = GetStdHandle(STD_OUTPUT_HANDLE);
|
||||
let mut mode = 0;
|
||||
assert_ne!(GetConsoleMode(output, &mut mode), 0);
|
||||
assert_ne!(SetConsoleMode(output, mode | ENABLE_VIRTUAL_TERMINAL_PROCESSING), 0);
|
||||
}
|
||||
std::io::stdout()
|
||||
.write_all(b"\x1b[?1049h\x1b[2J\x1b[HWorking (3m 19s)\x1b[1;1H\x1b[2KWorking (2m 59s)\x1b[?1049l\r\nVT_DONE\r\n")
|
||||
.unwrap();
|
||||
std::io::stdout().flush().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn conpty_preserves_alternate_screen_transitions() {
|
||||
use std::io::Read;
|
||||
use std::sync::mpsc;
|
||||
use std::time::{Duration, Instant};
|
||||
let pair = super::super::native_pty_system().openpty(portable_pty::PtySize::default()).unwrap();
|
||||
let mut reader = pair.master.try_clone_reader().unwrap();
|
||||
let mut writer = pair.master.take_writer().unwrap();
|
||||
let mut command = portable_pty::CommandBuilder::new(std::env::current_exe().unwrap());
|
||||
command.args(["--exact", "pty::windows::tests::conpty_output_child", "--nocapture"]);
|
||||
command.env("OPENIDEA_CONPTY_TEST_CHILD", "1");
|
||||
let mut child = pair.slave.spawn_command(command).unwrap();
|
||||
drop(pair.slave);
|
||||
let (tx, rx) = mpsc::channel();
|
||||
let reading = std::thread::spawn(move || {
|
||||
let mut bytes = [0; 4096];
|
||||
while let Ok(count) = reader.read(&mut bytes) {
|
||||
if count == 0 || tx.send(bytes[..count].to_vec()).is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
let deadline = Instant::now() + Duration::from_secs(10);
|
||||
let mut output = Vec::new();
|
||||
let mut cursor_replied = false;
|
||||
while Instant::now() < deadline {
|
||||
if let Ok(bytes) = rx.recv_timeout(Duration::from_millis(50)) {
|
||||
output.extend_from_slice(&bytes);
|
||||
if !cursor_replied && output.windows(4).any(|s| s == b"\x1b[6n") {
|
||||
writer.write_all(b"\x1b[1;1R").unwrap();
|
||||
cursor_replied = true;
|
||||
}
|
||||
if output.windows(7).any(|s| s == b"VT_DONE") {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
drop(writer);
|
||||
drop(pair.master);
|
||||
reading.join().unwrap();
|
||||
let output = String::from_utf8_lossy(&output);
|
||||
assert!(output.contains("\x1b[?1049h"), "alternate screen entry missing: {output:?}");
|
||||
assert!(output.contains("\x1b[?1049l"), "alternate screen exit missing: {output:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The embedded runtime is the pinned NuGet package's files (`resources/conpty/README.md`).
|
||||
#[cfg(test)]
|
||||
mod checksums {
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
const FILES: [(&str, &[u8], &str); 6] = [
|
||||
(
|
||||
"arm64/conpty.dll",
|
||||
include_bytes!("../resources/conpty/arm64/conpty.dll"),
|
||||
"151a02355227710c20c9f8f1eaf68ac4668aa09cdc921adc7ec661804d8eb1bf",
|
||||
),
|
||||
(
|
||||
"arm64/OpenConsole.exe",
|
||||
include_bytes!("../resources/conpty/arm64/OpenConsole.exe"),
|
||||
"4313825a3ba634d113cc6ed3bc8ce735e3c19d360cecd985794787479469f91f",
|
||||
),
|
||||
(
|
||||
"x64/conpty.dll",
|
||||
include_bytes!("../resources/conpty/x64/conpty.dll"),
|
||||
"feeef341d891643c62d30b6b07800bc70f0bc148f44cb8c3bee84aa557ae805a",
|
||||
),
|
||||
(
|
||||
"x64/OpenConsole.exe",
|
||||
include_bytes!("../resources/conpty/x64/OpenConsole.exe"),
|
||||
"3d66b23d0a71bb8eed2b77edc8b9df9bf54ce6c8fb74c863a30e760997f80586",
|
||||
),
|
||||
(
|
||||
"x86/conpty.dll",
|
||||
include_bytes!("../resources/conpty/x86/conpty.dll"),
|
||||
"d145f621bf64a9da3b7395587ddef9831ca404805d8987ec8c9903d0c4603d93",
|
||||
),
|
||||
(
|
||||
"x86/OpenConsole.exe",
|
||||
include_bytes!("../resources/conpty/x86/OpenConsole.exe"),
|
||||
"e3e475547d57da0689dc9fc5e0101d10390e2a4719a6eb5dcad569f6cb33c1a3",
|
||||
),
|
||||
];
|
||||
|
||||
#[test]
|
||||
fn embedded_runtime_matches_the_pinned_package() {
|
||||
for (name, bytes, expected) in FILES {
|
||||
let actual: String = Sha256::digest(bytes).iter().map(|b| format!("{b:02x}")).collect();
|
||||
assert_eq!(actual, expected, "{name}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,20 +4,6 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
|
||||
/// Tools › Remote Development. This is a user setting on the remote host.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct RemoteDevelopmentSettings {
|
||||
/// Zero disables idle shutdown. Positive values from older configurations keep their meaning.
|
||||
pub idle_timeout_minutes: u16,
|
||||
}
|
||||
|
||||
impl Default for RemoteDevelopmentSettings {
|
||||
fn default() -> Self {
|
||||
Self { idle_timeout_minutes: 180 }
|
||||
}
|
||||
}
|
||||
|
||||
/// How an SSH connection authenticates.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
|
||||
+17
-235
@@ -34,8 +34,6 @@ pub struct Settings {
|
||||
pub project_structure: ProjectStructureSettings,
|
||||
/// Version Control (Git, Commit, Confirmation, Issue Navigation).
|
||||
pub vcs: VcsSettings,
|
||||
/// Build, Execution, Deployment › Compiler (Build tool window).
|
||||
pub build: BuildSettings,
|
||||
/// Build, Execution, Deployment › Console.
|
||||
pub console: ConsoleSettings,
|
||||
pub debugger: DebuggerSettings,
|
||||
@@ -60,7 +58,6 @@ pub struct Settings {
|
||||
pub spelling: SpellingSettings,
|
||||
/// Tools › SSH Configurations.
|
||||
pub ssh: SshSettings,
|
||||
pub remote_development: RemoteDevelopmentSettings,
|
||||
/// Build, Execution, Deployment › Deployment.
|
||||
pub deployment: DeploymentSettings,
|
||||
/// Build, Execution, Deployment › Run Targets.
|
||||
@@ -101,6 +98,16 @@ pub struct AgentSettings {
|
||||
pub smooth_text: bool,
|
||||
/// Conversations and the composer expand to the full width of the pane instead of staying in a centred column.
|
||||
pub fit_window_width: bool,
|
||||
/// While the agent works, playful words fill the pauses in what it reports.
|
||||
pub playful_status: bool,
|
||||
/// Seconds the agent reports nothing new before the playful words take over; 0 shows them
|
||||
/// from the start.
|
||||
pub playful_after_seconds: u32,
|
||||
/// The user's playful words by activity (`working`, `thinking`, `reading`, …), replacing
|
||||
/// the built-in ones of that activity; an empty list keeps its status factual.
|
||||
#[serde(deserialize_with = "or_default")]
|
||||
#[specta(type = BTreeMap<String, Vec<String>>)]
|
||||
pub playful_words: BTreeMap<String, Vec<String>>,
|
||||
#[serde(deserialize_with = "or_default")]
|
||||
#[specta(type = ThinkingDisplay)]
|
||||
pub thinking: ThinkingDisplay,
|
||||
@@ -131,11 +138,6 @@ pub struct AgentSettings {
|
||||
#[serde(deserialize_with = "or_default")]
|
||||
#[specta(type = BTreeMap<String, AgentMcpServer>)]
|
||||
pub mcp_servers: BTreeMap<String, AgentMcpServer>,
|
||||
/// How agent skills may run, keyed by skill name (`[agents.skills.<name>]`); `SKILL.md`
|
||||
/// files on disk are never modified.
|
||||
#[serde(deserialize_with = "or_default")]
|
||||
#[specta(type = BTreeMap<String, AgentSkillPolicy>)]
|
||||
pub skills: BTreeMap<String, AgentSkillPolicy>,
|
||||
}
|
||||
|
||||
impl Default for AgentSettings {
|
||||
@@ -145,9 +147,12 @@ impl Default for AgentSettings {
|
||||
show_work_time: true,
|
||||
show_usage_limits: true,
|
||||
show_cost: false,
|
||||
fold_turns: false,
|
||||
fold_turns: true,
|
||||
smooth_text: true,
|
||||
fit_window_width: false,
|
||||
playful_status: false,
|
||||
playful_after_seconds: 0,
|
||||
playful_words: BTreeMap::new(),
|
||||
thinking: ThinkingDisplay::Auto,
|
||||
tool_calls: ToolCallDisplay::Grouped,
|
||||
expand_tool_output: false,
|
||||
@@ -156,7 +161,6 @@ impl Default for AgentSettings {
|
||||
new_task_approvals: NewTaskApprovals::Bypass,
|
||||
defaults: BTreeMap::new(),
|
||||
mcp_servers: BTreeMap::new(),
|
||||
skills: BTreeMap::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -212,34 +216,6 @@ impl Default for AgentMcpServer {
|
||||
}
|
||||
}
|
||||
|
||||
/// How an agent skill may run (`[agents.skills.<name>] mode = …`).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum AgentSkillMode {
|
||||
/// The model decides when to use it.
|
||||
#[default]
|
||||
Auto,
|
||||
/// Only when the user invokes it with `/name`.
|
||||
SlashOnly,
|
||||
/// Never.
|
||||
Off,
|
||||
}
|
||||
|
||||
/// A skill's policy in Settings › Agents › Skills, stored without touching its `SKILL.md`.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct AgentSkillPolicy {
|
||||
#[serde(deserialize_with = "or_default")]
|
||||
#[specta(type = AgentSkillMode)]
|
||||
pub mode: AgentSkillMode,
|
||||
}
|
||||
|
||||
impl Default for AgentSkillPolicy {
|
||||
fn default() -> Self {
|
||||
Self { mode: AgentSkillMode::Auto }
|
||||
}
|
||||
}
|
||||
|
||||
/// A hand-edited value these settings don't know reads as the default, rather than
|
||||
/// failing the whole settings file.
|
||||
fn or_default<'de, D, T>(d: D) -> Result<T, D::Error>
|
||||
@@ -341,20 +317,6 @@ pub enum NewTaskApprovals {
|
||||
Ask,
|
||||
}
|
||||
|
||||
/// Which folders without an open window the MCP server still serves tools for.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum McpBackgroundProjects {
|
||||
/// Only projects open in a window.
|
||||
#[default]
|
||||
Off,
|
||||
/// Also folders the user trusts: trusted projects, recent projects and the repositories inside
|
||||
/// trusted locations.
|
||||
Trusted,
|
||||
/// Only the folders in [`McpServerSettings::background_project_paths`] (and below them).
|
||||
Listed,
|
||||
}
|
||||
|
||||
/// Agents › MCP Server: agents use the IDE's built-in tools.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
@@ -379,21 +341,6 @@ pub struct McpServerSettings {
|
||||
/// Keep the bearer token across runs (in the app data, readable by this user only) rather than
|
||||
/// make a new one each run.
|
||||
pub fixed_token: bool,
|
||||
/// Serve tools for folders that have no open window (see [`McpBackgroundProjects`]); the
|
||||
/// project loads when an agent first asks for it.
|
||||
#[serde(deserialize_with = "or_default")]
|
||||
#[specta(type = McpBackgroundProjects)]
|
||||
pub background_projects: McpBackgroundProjects,
|
||||
/// The folders [`McpBackgroundProjects::Listed`] serves, and the ones `Trusted` serves even
|
||||
/// when untrusted.
|
||||
#[serde(deserialize_with = "or_default")]
|
||||
#[specta(type = Vec<String>)]
|
||||
pub background_project_paths: Vec<String>,
|
||||
/// Minutes a background project may go without a tool call before it is unloaded, at most
|
||||
/// 1440; 0 keeps it until the IDE quits.
|
||||
pub background_idle_minutes: u32,
|
||||
/// Background projects loaded at once, 1 to 32; the least recently used one makes room.
|
||||
pub background_project_limit: u32,
|
||||
}
|
||||
|
||||
/// The default of [`McpServerSettings::port`].
|
||||
@@ -412,10 +359,6 @@ impl Default for McpServerSettings {
|
||||
fixed_port: true,
|
||||
port: DEFAULT_MCP_PORT,
|
||||
fixed_token: false,
|
||||
background_projects: McpBackgroundProjects::Off,
|
||||
background_project_paths: Vec::new(),
|
||||
background_idle_minutes: 30,
|
||||
background_project_limit: 8,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -565,7 +508,6 @@ impl Default for Settings {
|
||||
languages: LanguagesSettings::default(),
|
||||
project_structure: ProjectStructureSettings::default(),
|
||||
vcs: VcsSettings::default(),
|
||||
build: BuildSettings::default(),
|
||||
console: ConsoleSettings::default(),
|
||||
debugger: DebuggerSettings::default(),
|
||||
run: RunSettings::default(),
|
||||
@@ -579,7 +521,6 @@ impl Default for Settings {
|
||||
inspections: InspectionSettings::default(),
|
||||
spelling: SpellingSettings::default(),
|
||||
ssh: SshSettings::default(),
|
||||
remote_development: RemoteDevelopmentSettings::default(),
|
||||
deployment: DeploymentSettings::default(),
|
||||
run_targets: Vec::new(),
|
||||
cmake: CMakeSettings::default(),
|
||||
@@ -941,8 +882,6 @@ pub struct FileIconThemeOptions {
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct MainToolbarSettings {
|
||||
pub left: Vec<String>,
|
||||
/// Centred in the toolbar (between the other two groups when they leave too little room).
|
||||
pub center: Vec<String>,
|
||||
pub right: Vec<String>,
|
||||
/// Widgets the user removed.
|
||||
pub hidden: Vec<String>,
|
||||
@@ -1210,15 +1149,12 @@ pub struct LanguagesSettings {
|
||||
pub typescript: TypeScriptSettings,
|
||||
pub prettier: ExternalFormatterSettings,
|
||||
pub oxfmt: ExternalFormatterSettings,
|
||||
pub biome: ExternalFormatterSettings,
|
||||
pub ruff: ExternalFormatterSettings,
|
||||
pub black: ExternalFormatterSettings,
|
||||
pub java: JavaSettings,
|
||||
pub ruby: RubySettings,
|
||||
pub markdown: MarkdownSettings,
|
||||
pub arduino: ArduinoSettings,
|
||||
pub zig: ZigSettings,
|
||||
pub flutter: FlutterSettings,
|
||||
}
|
||||
|
||||
impl Default for LanguagesSettings {
|
||||
@@ -1233,24 +1169,15 @@ impl Default for LanguagesSettings {
|
||||
typescript: TypeScriptSettings::default(),
|
||||
prettier: ExternalFormatterSettings::default(),
|
||||
oxfmt: ExternalFormatterSettings::default(),
|
||||
biome: ExternalFormatterSettings {
|
||||
languages: BIOME_LANGUAGES.iter().map(|&l| l.into()).collect(),
|
||||
..ExternalFormatterSettings::default()
|
||||
},
|
||||
ruff: ExternalFormatterSettings {
|
||||
languages: vec!["python".into()],
|
||||
..ExternalFormatterSettings::default()
|
||||
},
|
||||
black: ExternalFormatterSettings {
|
||||
languages: vec!["python".into()],
|
||||
..ExternalFormatterSettings::default()
|
||||
},
|
||||
java: JavaSettings::default(),
|
||||
ruby: RubySettings::default(),
|
||||
markdown: MarkdownSettings::default(),
|
||||
arduino: ArduinoSettings::default(),
|
||||
zig: ZigSettings::default(),
|
||||
flutter: FlutterSettings::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1267,45 +1194,11 @@ pub struct ArduinoSettings {
|
||||
}
|
||||
|
||||
/// Languages & Frameworks › Markdown. Like IDEA's, it is application-level only.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct MarkdownSettings {
|
||||
pub preview_layout: MarkdownPreviewLayout,
|
||||
/// Preview (and notebook Markdown cell) font size in px; unset follows the editor font size.
|
||||
pub preview_font_size: Option<u32>,
|
||||
/// "Detect commands that can be run right from Markdown files": gutter run icons on
|
||||
/// shell code blocks and on command lines in code blocks.
|
||||
pub run_commands: bool,
|
||||
/// Where those commands run; unset asks when the project and the file's folder differ.
|
||||
pub command_directory: Option<MarkdownCommandDirectory>,
|
||||
}
|
||||
|
||||
impl Default for MarkdownSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
preview_layout: MarkdownPreviewLayout::default(),
|
||||
preview_font_size: None,
|
||||
run_commands: true,
|
||||
command_directory: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum MarkdownPreviewLayout {
|
||||
#[default]
|
||||
SideBySide,
|
||||
Stacked,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum MarkdownCommandDirectory {
|
||||
/// The project's root folder.
|
||||
Project,
|
||||
/// The Markdown file's parent folder.
|
||||
File,
|
||||
}
|
||||
|
||||
impl LanguagesSettings {
|
||||
@@ -1313,9 +1206,7 @@ impl LanguagesSettings {
|
||||
match tool {
|
||||
ExternalFormatter::Prettier => &self.prettier,
|
||||
ExternalFormatter::Oxfmt => &self.oxfmt,
|
||||
ExternalFormatter::Biome => &self.biome,
|
||||
ExternalFormatter::Ruff => &self.ruff,
|
||||
ExternalFormatter::Black => &self.black,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1326,9 +1217,7 @@ impl LanguagesSettings {
|
||||
pub enum ExternalFormatter {
|
||||
Prettier,
|
||||
Oxfmt,
|
||||
Biome,
|
||||
Ruff,
|
||||
Black,
|
||||
}
|
||||
|
||||
impl ExternalFormatter {
|
||||
@@ -1337,22 +1226,16 @@ impl ExternalFormatter {
|
||||
match self {
|
||||
Self::Prettier => "prettier",
|
||||
Self::Oxfmt => "oxfmt",
|
||||
Self::Biome => "biome",
|
||||
Self::Ruff => "ruff",
|
||||
Self::Black => "black",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The languages Biome formats (of those Prettier formats).
|
||||
pub const BIOME_LANGUAGES: [&str; 8] =
|
||||
["css", "graphql", "javascript", "javascriptreact", "typescript", "typescriptreact", "json", "jsonc"];
|
||||
|
||||
/// An external formatter (Prettier, oxfmt, Biome, Ruff, Black) and the languages it formats.
|
||||
/// An external formatter (Prettier, oxfmt, Ruff) and the languages it formats.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct ExternalFormatterSettings {
|
||||
/// Empty path: project node_modules (Prettier/oxfmt/Biome), managed installation, then PATH.
|
||||
/// Empty path: project node_modules (Prettier/oxfmt), managed installation, then PATH.
|
||||
pub path: String,
|
||||
/// Ruff only: directory containing its configuration, or a configuration file.
|
||||
pub configuration_directory: String,
|
||||
@@ -1410,9 +1293,6 @@ pub struct PythonSettings {
|
||||
pub hide_other_project_interpreters: bool,
|
||||
/// Show each interpreter's path under its name on the interpreters page.
|
||||
pub show_interpreter_paths: bool,
|
||||
/// Folders the user added to an interpreter's `sys.path` (All Interpreters › Show Paths),
|
||||
/// by interpreter executable; absolute or `~/`.
|
||||
pub interpreter_paths: BTreeMap<String, Vec<String>>,
|
||||
}
|
||||
|
||||
impl Default for PythonSettings {
|
||||
@@ -1424,7 +1304,6 @@ impl Default for PythonSettings {
|
||||
hidden_interpreters: Vec::new(),
|
||||
hide_other_project_interpreters: false,
|
||||
show_interpreter_paths: true,
|
||||
interpreter_paths: BTreeMap::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1517,15 +1396,6 @@ pub struct ZigSettings {
|
||||
pub zig: String,
|
||||
}
|
||||
|
||||
/// The Flutter plugin's "Flutter SDK path".
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct FlutterSettings {
|
||||
/// Flutter SDK root (holding `bin/flutter`); its `flutter` and Dart replace the ones on
|
||||
/// `PATH`. Empty = `PATH`.
|
||||
pub sdk: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct GoSettings {
|
||||
@@ -1668,20 +1538,6 @@ pub struct MavenSettings {
|
||||
/// Always update snapshots (`-U`): Maven checks remote repositories for newer SNAPSHOT
|
||||
/// dependencies on every sync, build and run, and jdtls on import (`java.maven.updateSnapshots`).
|
||||
pub update_snapshots: bool,
|
||||
/// Who runs the JUnit 5 tests of the gutter's Run / Debug.
|
||||
pub run_tests_using: MavenRunTestsUsing,
|
||||
}
|
||||
|
||||
/// Build Tools › Maven › Run tests using. IDEA runs a Maven project's tests itself unless its build
|
||||
/// and run actions are delegated to Maven.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum MavenRunTestsUsing {
|
||||
/// OpenIDEA's JUnit Platform runner on the language server's test classpath (`java/junit-runner`).
|
||||
#[default]
|
||||
Ide,
|
||||
/// Surefire (`mvn test -Dtest=…`).
|
||||
Maven,
|
||||
}
|
||||
|
||||
impl MavenSettings {
|
||||
@@ -1956,20 +1812,6 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn markdown_preview_layout_defaults_and_round_trips() {
|
||||
let old: Settings = serde_json::from_str(r#"{"languages":{"markdown":{"previewFontSize":16}}}"#).unwrap();
|
||||
assert_eq!(old.languages.markdown.preview_layout, MarkdownPreviewLayout::SideBySide);
|
||||
assert_eq!(old.languages.markdown.preview_font_size, Some(16));
|
||||
|
||||
let stacked: Settings =
|
||||
serde_json::from_str(r#"{"languages":{"markdown":{"previewLayout":"stacked"}}}"#).unwrap();
|
||||
assert_eq!(stacked.languages.markdown.preview_layout, MarkdownPreviewLayout::Stacked);
|
||||
let saved = serde_json::to_value(&stacked).unwrap();
|
||||
assert_eq!(saved["languages"]["markdown"]["previewLayout"], "stacked");
|
||||
assert_eq!(serde_json::from_value::<Settings>(saved).unwrap().languages.markdown, stacked.languages.markdown);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cmake_profile_argument_arrays_round_trip() {
|
||||
let mut settings = Settings::default();
|
||||
@@ -2124,10 +1966,8 @@ mod tests {
|
||||
assert!(old.agents.show_cost);
|
||||
assert!(old.agents.show_context_usage && old.agents.show_work_time && old.agents.show_usage_limits);
|
||||
assert!(!old.agents.fit_window_width);
|
||||
assert!(!old.agents.fold_turns);
|
||||
assert!(!Settings::default().agents.show_cost);
|
||||
assert!(!Settings::default().agents.fit_window_width);
|
||||
assert!(!Settings::default().agents.fold_turns);
|
||||
let mut settings = Settings::default();
|
||||
settings.agents.show_usage_limits = false;
|
||||
settings.agents.fit_window_width = true;
|
||||
@@ -2277,63 +2117,6 @@ mod tests {
|
||||
let restored: Settings = serde_json::from_value(value).unwrap();
|
||||
assert_eq!(restored, settings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn background_projects_default_to_off_with_no_paths_30_idle_minutes_and_a_limit_of_8() {
|
||||
for settings in [Settings::default(), serde_json::from_str(r#"{"mcpServer":{"enabled":true}}"#).unwrap()] {
|
||||
let mcp = settings.mcp_server;
|
||||
assert_eq!(mcp.background_projects, McpBackgroundProjects::Off);
|
||||
assert!(mcp.background_project_paths.is_empty());
|
||||
assert_eq!((mcp.background_idle_minutes, mcp.background_project_limit), (30, 8));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bad_background_mode_or_path_list_reads_as_its_default_and_keeps_the_rest() {
|
||||
for (key, bad) in
|
||||
[("backgroundProjects", serde_json::json!("bogus")), ("backgroundProjectPaths", serde_json::json!(5))]
|
||||
{
|
||||
let mut json = serde_json::json!({
|
||||
"appearance": { "theme": "solarized-dark" },
|
||||
"mcpServer": {
|
||||
"enabled": true,
|
||||
"port": 7000,
|
||||
"backgroundProjects": "listed",
|
||||
"backgroundProjectPaths": ["/projects/inventory"],
|
||||
"backgroundIdleMinutes": 10,
|
||||
"backgroundProjectLimit": 3,
|
||||
},
|
||||
});
|
||||
json["mcpServer"][key] = bad;
|
||||
let settings: Settings = serde_json::from_value(json).unwrap_or_else(|e| panic!("{key}: {e}"));
|
||||
let mcp = settings.mcp_server;
|
||||
let (mode, paths) = if key == "backgroundProjects" {
|
||||
(McpBackgroundProjects::Off, vec!["/projects/inventory".to_owned()])
|
||||
} else {
|
||||
(McpBackgroundProjects::Listed, Vec::new())
|
||||
};
|
||||
assert_eq!((mcp.background_projects, mcp.background_project_paths), (mode, paths), "{key}");
|
||||
assert_eq!((mcp.enabled, mcp.port), (true, 7000), "{key}");
|
||||
assert_eq!((mcp.background_idle_minutes, mcp.background_project_limit), (10, 3), "{key}");
|
||||
assert_eq!(settings.appearance.theme, "solarized-dark", "{key}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn background_project_settings_round_trip() {
|
||||
for mode in [McpBackgroundProjects::Off, McpBackgroundProjects::Trusted, McpBackgroundProjects::Listed] {
|
||||
let mut settings = Settings::default();
|
||||
settings.mcp_server.background_projects = mode;
|
||||
settings.mcp_server.background_project_paths =
|
||||
vec!["/projects/inventory".into(), "/projects/billing".into()];
|
||||
settings.mcp_server.background_idle_minutes = 0;
|
||||
settings.mcp_server.background_project_limit = 32;
|
||||
let json = serde_json::to_string(&settings).unwrap();
|
||||
assert!(json.contains(r#""backgroundProjects":""#), "{json}");
|
||||
let restored: Settings = serde_json::from_str(&json).unwrap();
|
||||
assert_eq!(restored.mcp_server, settings.mcp_server);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -2345,7 +2128,6 @@ mod maven_linkage_tests {
|
||||
let old: MavenSettings = serde_json::from_str(r#"{"home":"/opt/maven"}"#).unwrap();
|
||||
assert!(old.runner_jre.is_empty());
|
||||
assert!(!old.delegate_build);
|
||||
assert_eq!(old.run_tests_using, MavenRunTestsUsing::Ide);
|
||||
assert!(MavenSettings::default().runner_jre.is_empty());
|
||||
let settings = MavenSettings { runner_jre: "/opt/jdk-21".into(), delegate_build: true, ..old };
|
||||
let encoded = serde_json::to_string(&settings).unwrap();
|
||||
|
||||
@@ -110,17 +110,6 @@ pub struct WorkspaceEditPrecondition {
|
||||
}
|
||||
|
||||
impl WorkspaceEdit {
|
||||
/// The files and folders the edit renames, in order.
|
||||
pub fn moves(&self) -> Vec<FileMove> {
|
||||
self.files
|
||||
.iter()
|
||||
.filter_map(|f| match f {
|
||||
FileEdit::Rename { from, to } => Some(FileMove { from: from.clone(), to: to.clone() }),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Coalesces aliases of the same file before applying edits against its original text.
|
||||
/// Resource operations separate batches because later edits may use the new contents.
|
||||
pub fn deduplicate(&mut self) {
|
||||
@@ -195,14 +184,6 @@ pub enum FileEdit {
|
||||
},
|
||||
}
|
||||
|
||||
/// One file or folder move.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct FileMove {
|
||||
pub from: crate::IpcPath,
|
||||
pub to: crate::IpcPath,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum Severity {
|
||||
|
||||
@@ -11,9 +11,6 @@ use std::collections::BTreeMap;
|
||||
pub struct VcsSettings {
|
||||
/// Colour folders that contain changed files (project tree, tabs).
|
||||
pub show_dirty_directories: bool,
|
||||
pub create_changelists_automatically: bool,
|
||||
/// Diffs the user opens show in an editor tab; off, in a separate window.
|
||||
pub diff_as_editor_tab: bool,
|
||||
/// Stop file history (Show History) after `history_limit` commits.
|
||||
pub limit_history: bool,
|
||||
pub history_limit: u32,
|
||||
@@ -58,8 +55,6 @@ impl Default for VcsSettings {
|
||||
Self {
|
||||
// IDEA's VcsConfiguration.SHOW_DIRTY_RECURSIVELY is off by default.
|
||||
show_dirty_directories: false,
|
||||
create_changelists_automatically: false,
|
||||
diff_as_editor_tab: true,
|
||||
limit_history: true,
|
||||
history_limit: 1000,
|
||||
git: GitSettings::default(),
|
||||
@@ -72,99 +67,31 @@ impl Default for VcsSettings {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum EmptyCherryPickAction {
|
||||
#[default]
|
||||
Skip,
|
||||
CreateEmpty,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum StashDiffTarget {
|
||||
#[default]
|
||||
Local,
|
||||
Parent,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum GitSaveChangesPolicy {
|
||||
#[default]
|
||||
Shelve,
|
||||
Stash,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum FetchTagsMode {
|
||||
#[default]
|
||||
Auto,
|
||||
Sync,
|
||||
Always,
|
||||
Never,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum GitAnnotateMovement {
|
||||
#[default]
|
||||
None,
|
||||
WithinFile,
|
||||
AcrossFiles,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct GitAnnotateSettings {
|
||||
pub ignore_whitespace: bool,
|
||||
pub movement: GitAnnotateMovement,
|
||||
}
|
||||
|
||||
impl Default for GitAnnotateSettings {
|
||||
fn default() -> Self {
|
||||
Self { ignore_whitespace: true, movement: GitAnnotateMovement::None }
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct GitSettings {
|
||||
pub annotate: GitAnnotateSettings,
|
||||
/// Show blame after the current editor line.
|
||||
pub inline_blame: bool,
|
||||
/// A click (or Enter / Space) on the inline blame label opens its commit; off, the
|
||||
/// label is plain text and a click on it places the caret as past the line end.
|
||||
pub inline_blame_clickable: bool,
|
||||
pub show_branch_in_project_view: bool,
|
||||
/// Branch operations from the branches popup act on every repository of the project.
|
||||
pub sync_branch_operations: bool,
|
||||
/// Path to the git executable; empty = auto-detect.
|
||||
pub executable: String,
|
||||
/// Clone all submodules along with the root repository.
|
||||
pub clone_submodules: bool,
|
||||
/// Default of Update Project: `merge` | `rebase`.
|
||||
pub update_method: String,
|
||||
/// Where Git operations keep local changes temporarily.
|
||||
pub save_changes_policy: GitSaveChangesPolicy,
|
||||
/// Push rejected (non-fast-forward): update the branch and push again.
|
||||
pub auto_update_on_push_rejected: bool,
|
||||
pub warn_crlf: bool,
|
||||
pub warn_detached_head: bool,
|
||||
/// Background check for incoming commits: `auto` | `always` | `check` | `never`.
|
||||
/// Background check for incoming commits: `auto` | `always` | `never`.
|
||||
pub incoming_check: String,
|
||||
/// Minutes between background checks for incoming commits.
|
||||
pub incoming_check_interval: u32,
|
||||
/// How an explicit fetch or project update handles remote tags.
|
||||
pub fetch_tags_mode: FetchTagsMode,
|
||||
/// Branch name globs, `;`/`,`-separated; force push to them is prohibited.
|
||||
pub protected_branches: String,
|
||||
/// Initial state of Commit Options › Sign-off Commit.
|
||||
pub sign_off: bool,
|
||||
/// Add Git's origin line when cherry-picking commits from protected remote branches.
|
||||
pub add_cherry_pick_origin: bool,
|
||||
pub empty_cherry_pick: EmptyCherryPickAction,
|
||||
/// Ask before committing files larger than `large_file_mb`.
|
||||
pub warn_large_files: bool,
|
||||
pub large_file_mb: u32,
|
||||
@@ -176,8 +103,6 @@ pub struct GitSettings {
|
||||
pub push_dialog_only_protected: bool,
|
||||
/// Stashes and shelves share one tab.
|
||||
pub combine_stash_and_shelf: bool,
|
||||
/// What the stash browser compares its saved files against.
|
||||
pub stash_diff_target: StashDiffTarget,
|
||||
/// The non-modal Commit tool window works on the index: Staged / Unstaged groups,
|
||||
/// stage and unstage instead of inclusion checkboxes, and no change lists.
|
||||
pub staging_area: bool,
|
||||
@@ -189,32 +114,24 @@ pub struct GitSettings {
|
||||
impl Default for GitSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
annotate: GitAnnotateSettings::default(),
|
||||
inline_blame: false,
|
||||
inline_blame_clickable: true,
|
||||
show_branch_in_project_view: false,
|
||||
sync_branch_operations: true,
|
||||
executable: String::new(),
|
||||
clone_submodules: true,
|
||||
update_method: "merge".into(),
|
||||
save_changes_policy: GitSaveChangesPolicy::default(),
|
||||
auto_update_on_push_rejected: false,
|
||||
warn_crlf: true,
|
||||
warn_detached_head: true,
|
||||
incoming_check: "auto".into(),
|
||||
incoming_check_interval: 15,
|
||||
fetch_tags_mode: FetchTagsMode::Auto,
|
||||
protected_branches: "master; main".into(),
|
||||
sign_off: false,
|
||||
add_cherry_pick_origin: true,
|
||||
empty_cherry_pick: EmptyCherryPickAction::Skip,
|
||||
warn_large_files: true,
|
||||
large_file_mb: 50,
|
||||
warn_bad_file_names: true,
|
||||
show_push_dialog: true,
|
||||
push_dialog_only_protected: false,
|
||||
combine_stash_and_shelf: false,
|
||||
stash_diff_target: StashDiffTarget::default(),
|
||||
staging_area: false,
|
||||
cli_status: false,
|
||||
}
|
||||
@@ -228,12 +145,9 @@ pub struct CommitSettings {
|
||||
/// Commit from the Commit tool window; off = Local Changes in the Git tool
|
||||
/// window and a Commit dialog.
|
||||
pub non_modal: bool,
|
||||
pub include_changes_by_default: bool,
|
||||
pub commit_all_when_nothing_staged: bool,
|
||||
/// Start with an empty message instead of the last one / the changelist's.
|
||||
pub clear_initial_message: bool,
|
||||
pub analyze_code: bool,
|
||||
pub postpone_slow_checks: bool,
|
||||
pub check_todo: bool,
|
||||
pub reformat: bool,
|
||||
pub optimize_imports: bool,
|
||||
@@ -262,19 +176,14 @@ pub struct CommitSettings {
|
||||
pub agent_model: String,
|
||||
/// That model's thinking level for commit messages; empty keeps the agent's.
|
||||
pub agent_effort: String,
|
||||
/// Show the Generate Commit Message with Agent button above the commit message.
|
||||
pub agent_button: bool,
|
||||
}
|
||||
|
||||
impl Default for CommitSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
non_modal: true,
|
||||
include_changes_by_default: true,
|
||||
commit_all_when_nothing_staged: true,
|
||||
clear_initial_message: false,
|
||||
analyze_code: true,
|
||||
postpone_slow_checks: true,
|
||||
check_todo: true,
|
||||
reformat: false,
|
||||
optimize_imports: false,
|
||||
@@ -292,7 +201,6 @@ impl Default for CommitSettings {
|
||||
agent: String::new(),
|
||||
agent_model: String::new(),
|
||||
agent_effort: String::new(),
|
||||
agent_button: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -409,23 +317,6 @@ pub struct SqlResolutionScope {
|
||||
pub schema: String,
|
||||
}
|
||||
|
||||
/// Build, Execution, Deployment › Compiler (Build tool window behaviour).
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct BuildSettings {
|
||||
/// When to open the Build tool window: `always` | `onError` | `never`.
|
||||
pub open_tool_window: String,
|
||||
/// When to focus the Build tool window: `always` | `onError` | `never`.
|
||||
pub focus_tool_window: String,
|
||||
}
|
||||
|
||||
impl Default for BuildSettings {
|
||||
fn default() -> Self {
|
||||
// Builds open the tool window without taking focus.
|
||||
Self { open_tool_window: "always".into(), focus_tool_window: "never".into() }
|
||||
}
|
||||
}
|
||||
|
||||
/// Build, Execution, Deployment › Console.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
@@ -460,16 +351,6 @@ impl Default for ConsoleSettings {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether compiled classes are reloaded into running Java debug sessions after compilation.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum HotSwapPolicy {
|
||||
#[default]
|
||||
Ask,
|
||||
Always,
|
||||
Never,
|
||||
}
|
||||
|
||||
/// Build, Execution, Deployment › Debugger (+ Data Views, Stepping, Python Debugger).
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
@@ -497,8 +378,6 @@ pub struct DebuggerSettings {
|
||||
pub debug_server_page: bool,
|
||||
/// Flutter: saving a Dart file of a running debug session hot reloads the app.
|
||||
pub flutter_hot_reload_on_save: bool,
|
||||
/// Java: whether to reload changed classes into running debug sessions after compilation.
|
||||
pub hot_swap_after_compile: HotSwapPolicy,
|
||||
pub python: PythonDebuggerSettings,
|
||||
}
|
||||
|
||||
@@ -520,7 +399,6 @@ impl Default for DebuggerSettings {
|
||||
skip_library_code: true,
|
||||
debug_server_page: false,
|
||||
flutter_hot_reload_on_save: true,
|
||||
hot_swap_after_compile: HotSwapPolicy::Ask,
|
||||
python: PythonDebuggerSettings::default(),
|
||||
}
|
||||
}
|
||||
@@ -711,39 +589,3 @@ impl Default for AgentSecuritySettings {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn clone_submodules_defaults_on_and_can_be_disabled() {
|
||||
let missing: GitSettings = serde_json::from_str("{}").unwrap();
|
||||
let off: GitSettings = serde_json::from_str(r#"{"cloneSubmodules":false}"#).unwrap();
|
||||
assert!(missing.clone_submodules);
|
||||
assert!(!off.clone_submodules);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn git_settings_without_sync_key_execute_on_all_repositories() {
|
||||
let missing: GitSettings = serde_json::from_str("{}").unwrap();
|
||||
assert!(missing.sync_branch_operations);
|
||||
let off: GitSettings = serde_json::from_str(r#"{"syncBranchOperations":false}"#).unwrap();
|
||||
assert!(!off.sync_branch_operations);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn debugger_hotswap_after_compile_defaults_to_ask_and_roundtrips() {
|
||||
let missing: DebuggerSettings = serde_json::from_str("{}").unwrap();
|
||||
assert_eq!(missing.hot_swap_after_compile, HotSwapPolicy::Ask);
|
||||
for (raw, expected) in
|
||||
[("ask", HotSwapPolicy::Ask), ("always", HotSwapPolicy::Always), ("never", HotSwapPolicy::Never)]
|
||||
{
|
||||
let parsed: DebuggerSettings =
|
||||
serde_json::from_str(&format!(r#"{{"hotSwapAfterCompile":"{raw}"}}"#)).unwrap();
|
||||
assert_eq!(parsed.hot_swap_after_compile, expected);
|
||||
let serialized = serde_json::to_value(&parsed).unwrap();
|
||||
assert_eq!(serialized["hotSwapAfterCompile"], raw);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,7 @@ quick-xml = "0.42"
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
specta.workspace = true
|
||||
tracing.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile.workspace = true
|
||||
Loaded 100 of 3067 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user