Compare commits

..
Author SHA1 Message Date
l0ng-ai 2aa46f21bf test(settings): include agentButton in the commit settings defaults shape 2026-11-20 13:29:14 +08:00
l0ng-ai 7310d0ab01 feat(vcs): setting to hide the Generate Commit Message with Agent button
Version Control › Commit › Commit Message Generation gets "Show the Generate Commit Message
with Agent button" (on by default). Off, the button above the commit message is hidden in
the Commit tool window and dialog; the action stays available from Find Action and its
shortcut.
2026-11-20 13:21:55 +08:00
2677 changed files with 28666 additions and 238504 deletions

No files matched your search

+83
View File
@@ -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.
+91
View File
@@ -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>
```
+57
View File
@@ -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.
+1
View File
@@ -0,0 +1 @@
../../.agents/skills/eval
+1
View File
@@ -0,0 +1 @@
../../.agents/skills/issue-fix
+1
View File
@@ -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
View File
@@ -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:
+27 -127
View File
@@ -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,32 +20,10 @@ on:
- "Cargo.lock"
- "src/features/run/**"
- "src/features/debugger/**"
- "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:
@@ -57,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).
@@ -75,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
@@ -100,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-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
@@ -137,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
@@ -254,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"
@@ -279,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
View File
@@ -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/
-16
View File
@@ -147,22 +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"
],
"rules": {
"no-await-in-loop": "error"
}
}
]
}
+147
View File
@@ -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>`.
Symlink
+1
View File
@@ -0,0 +1 @@
AGENTS.md
+1
View File
@@ -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
+151 -149
View File
@@ -1104,9 +1104,9 @@ checksum = "3d52eff69cd5e647efe296129160853a42795992097e8af39800e1060caeea9b"
[[package]]
name = "cookie"
version = "0.18.3"
version = "0.18.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d55f2d6c30eeec7d5c6f98bd4395d4abb1895629eab97ee6522d340623615f8a"
checksum = "1a373e3602691c3cdea496d2f0ee5935151e6168fe87739483c463db1b2f2f87"
dependencies = [
"time",
"version_check",
@@ -1203,27 +1203,27 @@ dependencies = [
[[package]]
name = "cranelift-assembler-x64"
version = "0.136.7"
version = "0.136.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c19fba13ee427c4dd29488ea51127e945bf07fd9d79093f14c9cc57f74acf757"
checksum = "aecefa88696b62f833cc0c997d19c93246b0268e2aaf23e0e8692e527f6de088"
dependencies = [
"cranelift-assembler-x64-meta",
]
[[package]]
name = "cranelift-assembler-x64-meta"
version = "0.136.7"
version = "0.136.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dd88c766346fcc14bbadbd68cb11e9bc1e555e99f7e8f6b1f4c27a73ca659bec"
checksum = "1391a2546f5edf06a0ff5e9430d73c2713fd536aefec53200dc21846d1467f53"
dependencies = [
"cranelift-srcgen",
]
[[package]]
name = "cranelift-bforest"
version = "0.136.7"
version = "0.136.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f19d43d75dd963d6b1a653f2e03d4eed4365ca2e598ec57e52c15afdad6c3276"
checksum = "9528915fbc2c950702329e08c6d72aaff8ece9b7ecdbd225742825c09a445227"
dependencies = [
"cranelift-entity",
"wasmtime-internal-core",
@@ -1231,9 +1231,9 @@ dependencies = [
[[package]]
name = "cranelift-bitset"
version = "0.136.7"
version = "0.136.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "45d0b93e50856858c89c61cbe3f6d4b07596da22eb5a03a95b19420e1d08a275"
checksum = "9dd69a6db85c1bcff989809e0e0b3b06506425f32b545c46aeafda5fe7775d6a"
dependencies = [
"serde",
"serde_derive",
@@ -1242,9 +1242,9 @@ dependencies = [
[[package]]
name = "cranelift-codegen"
version = "0.136.7"
version = "0.136.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "efbdff32d3b6b4f33f1ba8a4ac747b97ce569b1d6834c3089c1c0933b94e618c"
checksum = "24c2db6c26cd96393cf785c4b51b900738963cc7422aa0045416a7641ae2f6cd"
dependencies = [
"bumpalo",
"cranelift-assembler-x64",
@@ -1273,9 +1273,9 @@ dependencies = [
[[package]]
name = "cranelift-codegen-meta"
version = "0.136.7"
version = "0.136.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67fd11ff24916a2c1ff852ce4bb664fcf2c2970ed551de44dd5b573321123703"
checksum = "e284270142e7f1dcb73a992a62a8b3716b4062a65a52d8f2732c6ebf6f7f342f"
dependencies = [
"cranelift-assembler-x64-meta",
"cranelift-codegen-shared",
@@ -1286,24 +1286,24 @@ dependencies = [
[[package]]
name = "cranelift-codegen-shared"
version = "0.136.7"
version = "0.136.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ba5d321229c3e00a17d7bb3633529ffdf97a13bcf4962fd2e92f1e0fd39360aa"
checksum = "6595667b7d505cf85d5bdd014e6f57ad6128183238f8e372319d9384782472f5"
[[package]]
name = "cranelift-control"
version = "0.136.7"
version = "0.136.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "71cd63450256d0f80f7a0527e133452f84fa6e1ca73c7db6ca2a9e8cc89d1c18"
checksum = "f26ffdbfcd24c3833d730849e6d132af34a400a2b89b44446015c01eecbea21d"
dependencies = [
"arbitrary",
]
[[package]]
name = "cranelift-entity"
version = "0.136.7"
version = "0.136.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "18d2f259130db1bbb89500d26944971a9beeb410de91ff14039203f055d7f9f0"
checksum = "9ffb08ccd8a77fb31cdbbda2afa2333d8f85299b1bc0d1c194259ba66d160d74"
dependencies = [
"cranelift-bitset",
"serde",
@@ -1313,9 +1313,9 @@ dependencies = [
[[package]]
name = "cranelift-frontend"
version = "0.136.7"
version = "0.136.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf37a38d982d45fe2c065d55e4de76e596b443b6acceb3ca726c2072c8ba6d7b"
checksum = "b447e4f2bb44b1188185a77f478e5a91b7723a40b3b58c3e2d5b26df2ed5a665"
dependencies = [
"cranelift-codegen",
"hashbrown 0.17.1",
@@ -1326,15 +1326,15 @@ dependencies = [
[[package]]
name = "cranelift-isle"
version = "0.136.7"
version = "0.136.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8ce8f84e2d44326879e18016d763457a2cb5d775e4a5822cd7473fc171fca063"
checksum = "2f0989e943f3a9d41989595826bba544df9fda64bcddd4df0c06fb2e26af3cb3"
[[package]]
name = "cranelift-native"
version = "0.136.7"
version = "0.136.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df64a0392edac7b38fb2965ce8e205e7c5e219e4c531ed3cd1929c782f21853d"
checksum = "5fa10df59e776c42dae5b6ba5216ba5321707a2136abd2219e615c54b234fc1b"
dependencies = [
"cranelift-codegen",
"libc",
@@ -1343,9 +1343,9 @@ dependencies = [
[[package]]
name = "cranelift-srcgen"
version = "0.136.7"
version = "0.136.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3748e3c77c0717359cd4c089e1dc057221eb8598a9c18b0b5afccb5685975abb"
checksum = "36508559c8839a8b6ee091f9deaa9cfe620a82f1abb5e358a0a0c65290583622"
[[package]]
name = "crc"
@@ -2154,7 +2154,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
dependencies = [
"libc",
"windows-sys 0.52.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -2361,9 +2361,9 @@ checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b"
[[package]]
name = "form_urlencoded"
version = "1.2.3"
version = "1.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "afa489199eaffb1211795df1c6236ce1ad0d41a6fa45250add73e3b02420f06e"
checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf"
dependencies = [
"percent-encoding",
]
@@ -2386,7 +2386,7 @@ checksum = "94e7099f6313ecacbe1256e8ff9d617b75d1bcb16a6fddef94866d225a01a14a"
dependencies = [
"io-lifetimes 2.0.4",
"rustix",
"windows-sys 0.52.0",
"windows-sys 0.59.0",
]
[[package]]
@@ -4144,9 +4144,8 @@ checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
[[package]]
name = "ide-agent"
version = "0.1.51"
version = "0.1.49"
dependencies = [
"base64 0.22.1",
"blake3",
"dunce",
"encoding_rs",
@@ -4157,8 +4156,6 @@ dependencies = [
"ide-vcs",
"ide-vfs",
"parking_lot",
"rustix",
"semver",
"serde",
"serde_json",
"specta",
@@ -4172,7 +4169,7 @@ dependencies = [
[[package]]
name = "ide-analysis"
version = "0.1.51"
version = "0.1.49"
dependencies = [
"ast-grep-core",
"ide-core",
@@ -4180,21 +4177,24 @@ dependencies = [
"rayon",
"serde",
"specta",
"tracing",
"tree-sitter",
]
[[package]]
name = "ide-android"
version = "0.1.51"
version = "0.1.49"
dependencies = [
"ide-core",
"serde",
"specta",
"tempfile",
"which",
]
[[package]]
name = "ide-build"
version = "0.1.51"
version = "0.1.49"
dependencies = [
"blake3",
"chardetng",
@@ -4212,7 +4212,7 @@ dependencies = [
[[package]]
name = "ide-cli"
version = "0.1.51"
version = "0.1.49"
dependencies = [
"dirs 6.0.0",
"serde",
@@ -4226,7 +4226,7 @@ dependencies = [
[[package]]
name = "ide-clipboard"
version = "0.1.51"
version = "0.1.49"
dependencies = [
"gtk",
"objc2 0.6.5",
@@ -4237,7 +4237,7 @@ dependencies = [
[[package]]
name = "ide-command"
version = "0.1.51"
version = "0.1.49"
dependencies = [
"heck 0.5.0",
"proc-macro2",
@@ -4248,9 +4248,8 @@ dependencies = [
[[package]]
name = "ide-core"
version = "0.1.51"
version = "0.1.49"
dependencies = [
"base64 0.22.1",
"dunce",
"encoding_rs",
"libc",
@@ -4266,7 +4265,7 @@ dependencies = [
[[package]]
name = "ide-coverage"
version = "0.1.51"
version = "0.1.49"
dependencies = [
"ide-core",
"ide-run",
@@ -4275,11 +4274,12 @@ dependencies = [
"serde_json",
"specta",
"tempfile",
"tracing",
]
[[package]]
name = "ide-dap"
version = "0.1.51"
version = "0.1.49"
dependencies = [
"base64 0.22.1",
"futures",
@@ -4308,11 +4308,12 @@ dependencies = [
[[package]]
name = "ide-db"
version = "0.1.51"
version = "0.1.49"
dependencies = [
"base64 0.22.1",
"bb8",
"blake3",
"dirs 6.0.0",
"dunce",
"flate2",
"futures",
@@ -4320,7 +4321,6 @@ dependencies = [
"ide-http",
"ide-sdk",
"ide-ssh",
"libc",
"notify",
"open",
"oracledb",
@@ -4340,14 +4340,13 @@ dependencies = [
"toml_edit 0.25.17+spec-1.1.0",
"tracing",
"uuid",
"windows-sys 0.61.2",
"zeroize",
"zip",
]
[[package]]
name = "ide-docker"
version = "0.1.51"
version = "0.1.49"
dependencies = [
"ide-core",
"serde",
@@ -4358,28 +4357,15 @@ dependencies = [
"which",
]
[[package]]
name = "ide-drag-out"
version = "0.1.51"
dependencies = [
"gtk",
"objc2 0.6.5",
"objc2-app-kit 0.3.2",
"objc2-foundation 0.3.2",
"raw-window-handle",
"tempfile",
"windows",
"windows-core",
]
[[package]]
name = "ide-extension"
version = "0.1.51"
version = "0.1.49"
dependencies = [
"base64 0.22.1",
"blake3",
"dunce",
"ed25519-dalek",
"ide-core",
"parking_lot",
"semver",
"serde",
@@ -4394,7 +4380,7 @@ dependencies = [
[[package]]
name = "ide-flutter"
version = "0.1.51"
version = "0.1.49"
dependencies = [
"ide-android",
"ide-core",
@@ -4405,7 +4391,7 @@ dependencies = [
[[package]]
name = "ide-fonts"
version = "0.1.51"
version = "0.1.49"
dependencies = [
"objc2-core-foundation",
"objc2-core-text",
@@ -4417,7 +4403,7 @@ dependencies = [
[[package]]
name = "ide-github"
version = "0.1.51"
version = "0.1.49"
dependencies = [
"ide-core",
"ide-vcs",
@@ -4430,11 +4416,10 @@ dependencies = [
[[package]]
name = "ide-heap"
version = "0.1.51"
version = "0.1.49"
dependencies = [
"criterion",
"ide-core",
"ide-heap",
"libc",
"memmap2",
"proptest",
@@ -4449,7 +4434,7 @@ dependencies = [
[[package]]
name = "ide-host"
version = "0.1.51"
version = "0.1.49"
dependencies = [
"base64 0.22.1",
"blake3",
@@ -4517,7 +4502,6 @@ dependencies = [
"toml 0.9.12+spec-1.1.0",
"tracing",
"tracing-subscriber",
"url",
"uuid",
"windows-sys 0.61.2",
"zip",
@@ -4525,9 +4509,8 @@ dependencies = [
[[package]]
name = "ide-http"
version = "0.1.51"
version = "0.1.49"
dependencies = [
"hyper-util",
"ide-core",
"ide-vfs",
"parking_lot",
@@ -4539,19 +4522,19 @@ dependencies = [
"specta",
"tempfile",
"tokio",
"tracing",
"uuid",
]
[[package]]
name = "ide-index"
version = "0.1.51"
version = "0.1.49"
dependencies = [
"blake3",
"criterion",
"dunce",
"globset",
"ide-core",
"ide-index",
"ide-language",
"ignore",
"nucleo-matcher",
@@ -4567,7 +4550,7 @@ dependencies = [
[[package]]
name = "ide-jdwp"
version = "0.1.51"
version = "0.1.49"
dependencies = [
"ide-jvm-inspect",
"proptest",
@@ -4579,9 +4562,10 @@ dependencies = [
[[package]]
name = "ide-jsonrpc"
version = "0.1.51"
version = "0.1.49"
dependencies = [
"encoding_rs",
"futures",
"ide-core",
"parking_lot",
"serde",
@@ -4595,7 +4579,7 @@ dependencies = [
[[package]]
name = "ide-jvm-attach"
version = "0.1.51"
version = "0.1.49"
dependencies = [
"libc",
"tempfile",
@@ -4604,7 +4588,7 @@ dependencies = [
[[package]]
name = "ide-jvm-inspect"
version = "0.1.51"
version = "0.1.49"
dependencies = [
"futures",
"serde",
@@ -4615,7 +4599,7 @@ dependencies = [
[[package]]
name = "ide-language"
version = "0.1.51"
version = "0.1.49"
dependencies = [
"blake3",
"criterion",
@@ -4674,7 +4658,7 @@ dependencies = [
[[package]]
name = "ide-lsp"
version = "0.1.51"
version = "0.1.49"
dependencies = [
"criterion",
"dunce",
@@ -4703,7 +4687,7 @@ dependencies = [
[[package]]
name = "ide-mcp"
version = "0.1.51"
version = "0.1.49"
dependencies = [
"bytes",
"dunce",
@@ -4722,8 +4706,9 @@ dependencies = [
[[package]]
name = "ide-notebook"
version = "0.1.51"
version = "0.1.49"
dependencies = [
"futures",
"ide-core",
"ide-vfs",
"jupyter-protocol",
@@ -4736,6 +4721,7 @@ dependencies = [
"specta-typescript",
"tempfile",
"tokio",
"tracing",
"uuid",
"windows-sys 0.61.2",
"zeromq",
@@ -4743,7 +4729,7 @@ dependencies = [
[[package]]
name = "ide-plugin"
version = "0.1.51"
version = "0.1.49"
dependencies = [
"blake3",
"dunce",
@@ -4755,6 +4741,7 @@ dependencies = [
"serde_json",
"specta",
"tempfile",
"thiserror 2.0.21",
"tokio",
"tracing",
"url",
@@ -4765,7 +4752,7 @@ dependencies = [
[[package]]
name = "ide-profiler"
version = "0.1.51"
version = "0.1.49"
dependencies = [
"ide-core",
"ide-jvm-attach",
@@ -4779,7 +4766,7 @@ dependencies = [
[[package]]
name = "ide-remote"
version = "0.1.51"
version = "0.1.49"
dependencies = [
"dunce",
"futures",
@@ -4799,7 +4786,7 @@ dependencies = [
[[package]]
name = "ide-run"
version = "0.1.51"
version = "0.1.49"
dependencies = [
"dunce",
"encoding_rs",
@@ -4823,7 +4810,7 @@ dependencies = [
[[package]]
name = "ide-scaffold"
version = "0.1.51"
version = "0.1.49"
dependencies = [
"ide-core",
"ide-tools",
@@ -4839,10 +4826,8 @@ dependencies = [
[[package]]
name = "ide-sdk"
version = "0.1.51"
version = "0.1.49"
dependencies = [
"base64 0.22.1",
"dirs 6.0.0",
"dunce",
"flate2",
"ide-core",
@@ -4853,7 +4838,6 @@ dependencies = [
"quick-xml 0.42.0",
"serde",
"serde_json",
"sha2 0.10.9",
"specta",
"tar",
"tempfile",
@@ -4865,7 +4849,7 @@ dependencies = [
[[package]]
name = "ide-search"
version = "0.1.51"
version = "0.1.49"
dependencies = [
"criterion",
"encoding_rs",
@@ -4886,7 +4870,7 @@ dependencies = [
[[package]]
name = "ide-spell"
version = "0.1.51"
version = "0.1.49"
dependencies = [
"ide-core",
"parking_lot",
@@ -4899,7 +4883,7 @@ dependencies = [
[[package]]
name = "ide-ssh"
version = "0.1.51"
version = "0.1.49"
dependencies = [
"dirs 6.0.0",
"flate2",
@@ -4924,7 +4908,7 @@ dependencies = [
[[package]]
name = "ide-streams"
version = "0.1.51"
version = "0.1.49"
dependencies = [
"ide-core",
"ide-language",
@@ -4937,7 +4921,7 @@ dependencies = [
[[package]]
name = "ide-syntax"
version = "0.1.51"
version = "0.1.49"
dependencies = [
"ide-core",
"ide-language",
@@ -4952,7 +4936,7 @@ dependencies = [
[[package]]
name = "ide-terminal"
version = "0.1.51"
version = "0.1.49"
dependencies = [
"ide-core",
"libc",
@@ -4966,7 +4950,7 @@ dependencies = [
[[package]]
name = "ide-text"
version = "0.1.51"
version = "0.1.49"
dependencies = [
"criterion",
"ide-core",
@@ -4979,7 +4963,7 @@ dependencies = [
[[package]]
name = "ide-tools"
version = "0.1.51"
version = "0.1.49"
dependencies = [
"flate2",
"hex",
@@ -5000,7 +4984,7 @@ dependencies = [
[[package]]
name = "ide-vcs"
version = "0.1.51"
version = "0.1.49"
dependencies = [
"blake3",
"dunce",
@@ -5009,7 +4993,6 @@ dependencies = [
"ide-core",
"ignore",
"libc",
"notify",
"redb",
"regex-lite",
"serde",
@@ -5022,7 +5005,7 @@ dependencies = [
[[package]]
name = "ide-vfs"
version = "0.1.51"
version = "0.1.49"
dependencies = [
"chardetng",
"dunce",
@@ -5049,7 +5032,7 @@ dependencies = [
[[package]]
name = "ide-web"
version = "0.1.51"
version = "0.1.49"
dependencies = [
"dirs 6.0.0",
"ide-core",
@@ -5065,7 +5048,7 @@ dependencies = [
[[package]]
name = "ide-workspace"
version = "0.1.51"
version = "0.1.49"
dependencies = [
"blake3",
"dunce",
@@ -5227,7 +5210,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "20fd6de4ccfcc187e38bc21cfa543cb5a302cb86a8b114eb7f0bf0dc9f8ac00f"
dependencies = [
"io-lifetimes 3.0.1",
"windows-sys 0.52.0",
"windows-sys 0.60.2",
]
[[package]]
@@ -5265,7 +5248,7 @@ checksum = "3640c1c38b8e4e43584d8df18be5fc6b0aa314ce6ebf51b53313d4306cca8e46"
dependencies = [
"hermit-abi",
"libc",
"windows-sys 0.52.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -6694,7 +6677,7 @@ dependencies = [
[[package]]
name = "openidea"
version = "0.1.51"
version = "0.1.49"
dependencies = [
"base64 0.22.1",
"blake3",
@@ -6703,30 +6686,40 @@ dependencies = [
"dunce",
"gtk",
"ide-agent",
"ide-analysis",
"ide-android",
"ide-build",
"ide-cli",
"ide-clipboard",
"ide-command",
"ide-core",
"ide-coverage",
"ide-dap",
"ide-db",
"ide-docker",
"ide-drag-out",
"ide-extension",
"ide-fonts",
"ide-github",
"ide-host",
"ide-http",
"ide-index",
"ide-jsonrpc",
"ide-language",
"ide-lsp",
"ide-mcp",
"ide-notebook",
"ide-plugin",
"ide-profiler",
"ide-remote",
"ide-run",
"ide-scaffold",
"ide-sdk",
"ide-search",
"ide-spell",
"ide-ssh",
"ide-syntax",
"ide-terminal",
"ide-text",
"ide-tools",
"ide-vcs",
"ide-vfs",
@@ -7413,9 +7406,9 @@ dependencies = [
[[package]]
name = "pulley-interpreter"
version = "49.0.7"
version = "49.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "99ecf828c291348e4066f8e45bf37c35ea6012b07a9201e7911c21f03ad1af3e"
checksum = "335e459f9c7809af04768799880504d014d07e8e2fc6ae682fe2a105d8ced33f"
dependencies = [
"cranelift-bitset",
"log",
@@ -7425,9 +7418,9 @@ dependencies = [
[[package]]
name = "pulley-macros"
version = "49.0.7"
version = "49.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "20e35ece122b2e8bbd7ea9db0709b3d32f20555b73985efc3eaf6afa4ef2ecdf"
checksum = "dd492ac929a6ca0357362d9fa0a09e31290feac5914550ccfb539b21f89c4b9e"
dependencies = [
"proc-macro2",
"quote",
@@ -7957,7 +7950,7 @@ dependencies = [
"errno",
"libc",
"linux-raw-sys",
"windows-sys 0.52.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -8025,7 +8018,7 @@ dependencies = [
"security-framework",
"security-framework-sys",
"webpki-root-certs",
"windows-sys 0.52.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -9772,7 +9765,7 @@ dependencies = [
"getrandom 0.3.4",
"once_cell",
"rustix",
"windows-sys 0.52.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -10813,9 +10806,9 @@ checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"
[[package]]
name = "url"
version = "2.5.9"
version = "2.5.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f00cd2407bb42c0ef17be88d4cf020f5cceffd121665bac9b8b9493a369b3b1a"
checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed"
dependencies = [
"form_urlencoded",
"idna",
@@ -11106,9 +11099,9 @@ dependencies = [
[[package]]
name = "wasmtime"
version = "49.0.7"
version = "49.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "263d6a66a772efff2c98a1aa367e8e61dae32d2ecf95f85f4776733762322aa7"
checksum = "f32390bdc8d7cdb6259a1b855178bfed88226b4004b209fd48fb30e0deb01cd3"
dependencies = [
"addr2line",
"async-trait",
@@ -11148,9 +11141,9 @@ dependencies = [
[[package]]
name = "wasmtime-environ"
version = "49.0.7"
version = "49.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5f2f0898bedc77f110dca6f70394780f89af68a8ca19e12559ee73d4187a6fe9"
checksum = "9c10f8ef1c9ee5e0f125c775fe56a4d07b8525db30a96e6358c61d93bd11dee4"
dependencies = [
"anyhow",
"cpp_demangle",
@@ -11179,9 +11172,9 @@ dependencies = [
[[package]]
name = "wasmtime-internal-component-macro"
version = "49.0.7"
version = "49.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b140c28283bd2255a4bb8834621f7200bbe7581cbca91d803b5ba4adf9119a5e"
checksum = "620c53182ebd26c9fff5b90dd53cf8ec3103c381403fd32f8d395da31a9e4a46"
dependencies = [
"anyhow",
"proc-macro2",
@@ -11194,15 +11187,15 @@ dependencies = [
[[package]]
name = "wasmtime-internal-component-util"
version = "49.0.7"
version = "49.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "853075a197694ba7f0749e7af78b59e12c0956dff5b16dafbfc49c3b90cdbc93"
checksum = "011e31ca343d9ba0ec623153cd94131b6f03973ef1a0ab791161f642e4a16a93"
[[package]]
name = "wasmtime-internal-core"
version = "49.0.7"
version = "49.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6e13ab3aa598d863643ef9ec043d63fde7effca4465270446d5b868936b27a6"
checksum = "ab15e50a060b746493e6e95ef3ce4e6e7ebfdd7cc336a7dff0f0277e01b447ef"
dependencies = [
"hashbrown 0.17.1",
"libm",
@@ -11211,9 +11204,9 @@ dependencies = [
[[package]]
name = "wasmtime-internal-cranelift"
version = "49.0.7"
version = "49.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "660103cff91df46f9f06568f3889b8b59a6ae0f56756abfcc002a0a69974cc9f"
checksum = "dc3d27440a83fba26dd2784a997e13d9acb3606a75fb127c324929b52221c5c5"
dependencies = [
"cranelift-codegen",
"cranelift-control",
@@ -11237,9 +11230,9 @@ dependencies = [
[[package]]
name = "wasmtime-internal-fiber"
version = "49.0.7"
version = "49.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c4d0e958516bdf283b83015283774e11c86b66f2f4bd7d2ea52e9799fa59cddb"
checksum = "6e54b28d0d453ca8932e4504065ae66a78f01fcb22b1a2ee287128d732fa9d6f"
dependencies = [
"cc",
"libc",
@@ -11251,9 +11244,9 @@ dependencies = [
[[package]]
name = "wasmtime-internal-jit-debug"
version = "49.0.7"
version = "49.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ad61b1e661871bb7d11b5543202a05c44ed8682806b438f68ced629a22719463"
checksum = "9293e75a3048b900f7b7c524702abca16d8a2332f970324eefc519f454cd5d69"
dependencies = [
"cc",
"wasmtime-internal-versioned-export-macros",
@@ -11261,9 +11254,9 @@ dependencies = [
[[package]]
name = "wasmtime-internal-jit-icache-coherence"
version = "49.0.7"
version = "49.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "52c641b9e1bab449c7316896f01d4a0c426e2a502a5a8098e1af4a0392053e7a"
checksum = "b852e568831b913d410541bb37edc45a5002e472208fbdbaf844ed801dd4255f"
dependencies = [
"libc",
"wasmtime-internal-core",
@@ -11272,9 +11265,9 @@ dependencies = [
[[package]]
name = "wasmtime-internal-unwinder"
version = "49.0.7"
version = "49.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "03303a9abd333edcbd44fee3b1e0905ad156d3bcec311323d061cdff92e7d1f3"
checksum = "a1f7349c9834a542275ad757340079e6453fccb429efce581454d23f85af92c0"
dependencies = [
"cranelift-codegen",
"log",
@@ -11284,9 +11277,9 @@ dependencies = [
[[package]]
name = "wasmtime-internal-versioned-export-macros"
version = "49.0.7"
version = "49.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8db0c7f417e5ca3ba92d127d17b980529455d01c141be99204e6d309630c42de"
checksum = "30b3e0768a450d9dea3e16b83f2498f0b08db0e32bad695e35564eef017be3f1"
dependencies = [
"proc-macro2",
"quote",
@@ -11295,9 +11288,9 @@ dependencies = [
[[package]]
name = "wasmtime-internal-wit-bindgen"
version = "49.0.7"
version = "49.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6292ee4f797f9befb64aa2b3477ec8576501d6302ec21fd2785a8d3f94cf8717"
checksum = "b9d085c540b95d0ffebf98c266e6f152e1acf96a9f676f224a74307b9d422c15"
dependencies = [
"anyhow",
"bitflags 2.13.2",
@@ -11309,9 +11302,9 @@ dependencies = [
[[package]]
name = "wasmtime-wasi"
version = "49.0.7"
version = "49.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3175ff29e2992269f51ec372f7757941f11f87b265a614761726960d42ef6e4d"
checksum = "17f8ce6b9e77539b5f52d440346f876a84c513ec1b07162845282f8652f7f7f9"
dependencies = [
"async-trait",
"bitflags 2.13.2",
@@ -11333,9 +11326,9 @@ dependencies = [
[[package]]
name = "wasmtime-wasi-io"
version = "49.0.7"
version = "49.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3bb561839e32b61bf0cdd51efe3874fac5de1bd5775a5b7c41bdf70993e367ea"
checksum = "da9f90eb7ce6edbead27dba3a58843398875defa73b8dce4bbc29d0ce3dc9b40"
dependencies = [
"async-trait",
"bytes",
@@ -11609,7 +11602,7 @@ version = "0.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
dependencies = [
"windows-sys 0.52.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -11777,6 +11770,15 @@ dependencies = [
"windows-targets 0.52.6",
]
[[package]]
name = "windows-sys"
version = "0.59.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b"
dependencies = [
"windows-targets 0.52.6",
]
[[package]]
name = "windows-sys"
version = "0.60.2"
@@ -12049,7 +12051,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f3fd376f71958b862e7afb20cfe5a22830e1963462f3a17f49d82a6c1d1f42d"
dependencies = [
"bitflags 2.13.2",
"windows-sys 0.52.0",
"windows-sys 0.59.0",
]
[[package]]
+3 -2
View File
@@ -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 -1
View File
@@ -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
View File
@@ -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
View File
@@ -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)。
+1 -2
View File
@@ -35,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` →
-5
View File
@@ -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"] }
+48 -18
View File
@@ -194,14 +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| saved.catalog.clone())
.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 {
@@ -210,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>> {
@@ -228,7 +246,14 @@ impl AgentCatalogs {
}
drop(state);
let cache = shared.known.lock();
cache.get(provider)?.catalogs.get(&shared.root_key())?.catalog.thought_levels.get(model).cloned()
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(
@@ -272,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
@@ -357,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| {
@@ -470,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 {
@@ -484,9 +510,13 @@ 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(), catalog: catalog.clone() },
+18 -32
View File
@@ -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]
-395
View File
@@ -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(&current), 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"));
}
}
File diff suppressed because it is too large. Load diff
+98 -1
View File
@@ -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}"))
}
+1 -143
View File
@@ -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,9 +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)]
@@ -280,24 +275,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 {
@@ -536,9 +513,6 @@ 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>,
@@ -620,9 +594,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 +664,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 +682,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 +735,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 +767,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 +856,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")]
+2 -64
View File
@@ -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(&params)?;
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(&params)?;
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(&params), ["/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
+10 -64
View File
@@ -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 }))
}
@@ -1847,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(&params, &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());
}
@@ -372,24 +372,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 +496,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 +546,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 {
-1
View File
@@ -373,7 +373,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(),
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+3 -42
View File
@@ -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;
@@ -84,7 +84,6 @@ 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,
@@ -151,7 +150,7 @@ impl Timeline {
}
fn merge_tool(&mut self, index: usize, update: &Value) {
let AgentEntry::Tool { title, kind, status, locations: locs, output, images, diffs, ended_ms, .. } =
let AgentEntry::Tool { title, kind, status, locations: locs, output, diffs, ended_ms, .. } =
&mut self.entries[index]
else {
return;
@@ -174,20 +173,10 @@ impl Timeline {
let Some(content) = update.get("content").and_then(Value::as_array) else { return };
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.filter(|c| c.get("type").and_then(Value::as_str) == Some("image"))
&& let (Some(data), Some(mime)) =
(image.get("data").and_then(Value::as_str), image.get("mimeType").and_then(Value::as_str))
&& !data.is_empty()
&& mime.starts_with("image/")
{
new_images.push(AgentImage { mime_type: mime.into(), data: data.into(), name: None });
}
if let Some(t) = content_text(content) {
if let Some(t) = content_text(item.get("content")) {
if !text.is_empty() {
text.push('\n');
}
@@ -214,9 +203,6 @@ impl Timeline {
if !new_diffs.is_empty() {
*diffs = new_diffs;
}
if !new_images.is_empty() {
*images = new_images;
}
}
/// Adds or updates the card of subagent `id` from its `subagent_update`; returns the
@@ -453,31 +439,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 chunks_merge_into_one_message_until_another_entry_comes() {
let mut t = Timeline::default();
+32 -332
View File
@@ -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,18 +545,6 @@ 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));
}
}
}
return Ok(out);
}
let Some(repo) = Repo::discover(cwd)? else { return Ok(BTreeMap::new()) };
Ok(repo.status()?.into_iter().map(|s| (s.rel_path, stamp(&s.path))).collect())
}
@@ -743,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;
}
@@ -787,8 +625,7 @@ pub(crate) fn restore(
}
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"))?;
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,
@@ -828,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>,
@@ -846,16 +680,8 @@ pub(crate) struct TurnStart {
/// 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, previous: Option<&TurnStart>) -> IdeResult<TurnStart> {
let Some(at) = TurnRepos::of(cwd)? else { return Ok(TurnStart::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
};
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();
@@ -876,7 +702,7 @@ pub(crate) fn start_turn(cwd: &Path, dir: &Path, previous: Option<&TurnStart>) -
}
}
for (rel, stamp) in &before {
let path = at.base.join(rel);
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)
@@ -889,7 +715,7 @@ pub(crate) fn start_turn(cwd: &Path, dir: &Path, previous: Option<&TurnStart>) -
saved.insert(rel.clone());
}
}
Ok(TurnStart { head, heads, before, saved, changed: None })
Ok(TurnStart { head, before, saved, changed: None })
}
/// The files that changed in `cwd` since the turn `start` began: in the working tree (as
@@ -898,25 +724,20 @@ 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(|| saved_copy(dir, rel)).flatten() {
@@ -925,13 +746,10 @@ fn at_turn_start(at: &TurnRepos, rel: &str, start: &TurnStart, dir: &Path) -> Id
"{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),
},
}
}
@@ -953,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) {
@@ -972,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),
@@ -1020,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),
@@ -1157,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();
+2
View File
@@ -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"
+3
View File
@@ -10,3 +10,6 @@ ide-core.workspace = true
serde.workspace = true
specta.workspace = true
which = "8"
[dev-dependencies]
tempfile.workspace = true
+6
View File
@@ -91,6 +91,12 @@ fn executable() -> IdeResult<PathBuf> {
})
}
/// 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.
pub fn devices() -> IdeResult<Vec<AndroidDevice>> {
let adb = executable()?;
+134 -216
View File
@@ -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)");
}
}
+2
View File
@@ -17,4 +17,6 @@ serde_json.workspace = true
specta.workspace = true
tracing.workspace = true
dirs.workspace = true
[dev-dependencies]
tempfile.workspace = true
+23 -170
View File
@@ -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>,
@@ -973,21 +932,7 @@ pub fn build_for_launch(
kind: BuildKind,
cancel: &CancellationToken,
) -> IdeResult<LaunchBuild> {
let mut built = build_for_launches(root, model, &[module.to_path_buf()], test, kind, cancel)?;
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,
) -> IdeResult<Vec<LaunchBuild>> {
let plan = merged_launch_plan(root, model, modules, test, kind, cancel)?;
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
@@ -1004,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> {
@@ -1080,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()
@@ -1766,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() {
+7 -35
View File
@@ -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(
+93 -497
View File
@@ -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,66 +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");
}
args.extend(["dependency:build-classpath", 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"] };
@@ -408,21 +220,75 @@ 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 mut command = ProcCommand::new(&target.top.command);
command.args(&args).envs(&target.top.env).current_dir(&top_dir);
let status = ide_core::process::prepare(&mut command)
.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
@@ -448,18 +314,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 {
@@ -469,140 +325,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::*;
@@ -648,8 +370,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"));
@@ -663,8 +384,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());
@@ -676,8 +396,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();
@@ -713,8 +432,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(
@@ -745,7 +463,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();
@@ -753,8 +470,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.
@@ -764,8 +479,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(
@@ -814,48 +528,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)]
@@ -864,8 +536,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
@@ -931,79 +602,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()])
);
}
}
+21 -157
View File
@@ -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])
}
+1 -13
View File
@@ -82,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() {
File diff suppressed because it is too large. Load diff
+13 -263
View File
@@ -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)
);
}
}
+9 -148
View File
@@ -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
View File
@@ -6,7 +6,6 @@ edition.workspace = true
license.workspace = true
[dependencies]
base64.workspace = true
dunce.workspace = true
encoding_rs.workspace = true
serde.workspace = true
-319
View File
@@ -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())
}
}
+1 -68
View File
@@ -197,7 +197,6 @@ 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,
@@ -205,24 +204,10 @@ pub struct FoldingSettings {
impl Default for FoldingSettings {
fn default() -> Self {
Self {
show_outline: true,
outline_visibility: FoldingOutlineVisibility::Hover,
file_header: true,
imports: true,
doc_comments: false,
}
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")]
@@ -288,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`.
@@ -311,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,
@@ -336,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 {
@@ -349,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(),
}
}
}
@@ -440,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).
@@ -475,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).
@@ -572,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);
}
}
+2 -81
View File
@@ -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, .. }));
}
}
+2 -13
View File
@@ -40,11 +40,10 @@ pub enum IdeEvent {
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,
@@ -93,18 +92,10 @@ pub enum IdeEvent {
/// 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,
@@ -325,8 +316,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.
-122
View File
@@ -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)");
}
}
+1 -54
View File
@@ -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}]");
}
}
-5
View File
@@ -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;
@@ -32,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;
@@ -40,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;
-20
View File
@@ -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);
}
}
-29
View File
@@ -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());
+2 -62
View File
@@ -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();
-14
View File
@@ -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")]
+3 -93
View File
@@ -60,7 +60,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.
@@ -131,11 +130,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 {
@@ -156,7 +150,6 @@ impl Default for AgentSettings {
new_task_approvals: NewTaskApprovals::Bypass,
defaults: BTreeMap::new(),
mcp_servers: BTreeMap::new(),
skills: BTreeMap::new(),
}
}
}
@@ -212,34 +205,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>
@@ -579,7 +544,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 +905,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,9 +1172,7 @@ 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,
@@ -1232,18 +1192,10 @@ 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(),
@@ -1268,7 +1220,6 @@ pub struct ArduinoSettings {
#[derive(Clone, Debug, 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
@@ -1280,23 +1231,10 @@ pub struct MarkdownSettings {
impl Default for MarkdownSettings {
fn default() -> Self {
Self {
preview_layout: MarkdownPreviewLayout::default(),
preview_font_size: None,
run_commands: true,
command_directory: None,
}
Self { 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 {
@@ -1311,9 +1249,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,
}
}
}
@@ -1324,9 +1260,7 @@ impl LanguagesSettings {
pub enum ExternalFormatter {
Prettier,
Oxfmt,
Biome,
Ruff,
Black,
}
impl ExternalFormatter {
@@ -1335,22 +1269,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,
@@ -1408,9 +1336,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 {
@@ -1422,7 +1347,6 @@ impl Default for PythonSettings {
hidden_interpreters: Vec::new(),
hide_other_project_interpreters: false,
show_interpreter_paths: true,
interpreter_paths: BTreeMap::new(),
}
}
}
@@ -1931,20 +1855,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();
-19
View File
@@ -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 {
+1 -139
View File
@@ -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,
@@ -270,11 +184,8 @@ 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,
@@ -460,16 +371,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 +398,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 +419,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 +609,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);
}
}
}
+1
View File
@@ -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
+6 -13
View File
@@ -49,8 +49,6 @@ pub struct AdapterSpec {
pub connect: Option<String>,
/// A plugin language's adapter: start exactly this approved program.
pub pinned: Option<ProgramPin>,
/// See [`DebuggerConfig::resolve_lazy_variables`].
pub resolve_lazy_variables: bool,
}
/// Built-in adapters used when no language definition names `adapter`.
@@ -62,7 +60,6 @@ fn builtin(adapter: &str) -> Option<DebuggerConfig> {
transport: transport.to_owned(),
connect: None,
install_hint: Some(hint.to_owned()),
resolve_lazy_variables: false,
pinned: None,
};
Some(match adapter {
@@ -133,15 +130,12 @@ fn builtin(adapter: &str) -> Option<DebuggerConfig> {
),
"rdbg" => cfg("rdbg", &["-O", "--port", PORT_PLACEHOLDER, "-c"], "tcp", "gem install debug"),
// A jdtls bundle: the session is started through jdtls and reached via `debugServer`.
"java-debug" => DebuggerConfig {
resolve_lazy_variables: true,
..cfg(
"com.microsoft.java.debug.plugin.jar",
&[],
"tcp",
"Install Microsoft java-debug (Settings › Languages & Frameworks › Language Servers)",
)
},
"java-debug" => cfg(
"com.microsoft.java.debug.plugin.jar",
&[],
"tcp",
"Install Microsoft java-debug (Settings › Languages & Frameworks › Language Servers)",
),
// The Java language server's own debugger, for modules jdtls doesn't serve; the host
// runs the executable of the java-analyzer serving the module.
JAVA_ANALYZER => cfg(
@@ -192,7 +186,6 @@ pub fn resolve(config: &DebuggerConfig, cwd: PathBuf) -> AdapterSpec {
server_host: None,
connect: config.connect.clone(),
pinned: config.pinned.clone(),
resolve_lazy_variables: config.resolve_lazy_variables,
}
}
-90
View File
@@ -1,90 +0,0 @@
//! Exception breakpoints on a chosen class. The manager keeps one list; a session given a backend
//! for them at start arms it before `configurationDone`, so a throw in the program's first line
//! stops, and again after each `setExceptionBreakpoints`, which drops them in java-debug.
use crate::session::Session;
use crate::{DebugManager, jvm_memory};
use ide_jvm_inspect::ExceptionClassSpec;
use serde::{Deserialize, Serialize};
use specta::Type;
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct ExceptionClassBreakpoint {
pub id: String,
/// Fully qualified binary name (`com.acme.Outer$Inner`); its subclasses stop too.
pub class_name: String,
pub caught: bool,
pub uncaught: bool,
pub enabled: bool,
/// Patterns (`com.acme.*`, `*Test`, a full name) for the class whose code throws.
pub class_filters: Vec<String>,
pub class_exclusion_filters: Vec<String>,
}
/// What a session's exception class breakpoints can do.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct ExceptionClassSupport {
/// Whose class names the session takes: `java`.
pub family: String,
pub condition: bool,
pub class_filters: bool,
/// Filters on the class whose code catches the exception.
pub catch_filters: bool,
}
/// The JVM backends stop through java-debug's own exception events, which a condition or a
/// catch-location filter cannot veto.
pub(crate) fn support(s: &Session) -> Option<ExceptionClassSupport> {
s.exception_classes.is_some().then(|| ExceptionClassSupport {
family: "java".into(),
condition: false,
class_filters: true,
catch_filters: false,
})
}
fn spec(b: &ExceptionClassBreakpoint) -> ExceptionClassSpec {
ExceptionClassSpec {
id: b.id.clone(),
class_name: b.class_name.clone(),
caught: b.caught,
uncaught: b.uncaught,
enabled: b.enabled,
class_filters: b.class_filters.clone(),
class_exclusion_filters: b.class_exclusion_filters.clone(),
}
}
impl DebugManager {
/// Arms the manager's list in `s`; the caller holds `s.exception_turn`. `clear`: also when the
/// list is empty, to take down what an earlier list armed.
pub(crate) async fn arm_exception_classes(&self, s: &Session, clear: bool) {
let Some(backend) = &s.exception_classes else { return };
let specs: Vec<_> = self.exception_classes.lock().iter().map(spec).collect();
// Without either, no VM is known yet: `configure` arms once it is.
let target = jvm_memory::vm_target(s);
if (specs.is_empty() && !clear) || (target.pid.is_none() && target.attach_port.is_none()) {
return;
}
match backend.set(&target, &specs).await {
Ok(states) => tracing::debug!("exception class breakpoints of session {}: {states:?}", s.id.0),
Err(e) => tracing::debug!("exception class breakpoints of session {} failed: {e}", s.id.0),
}
}
/// Stores exception breakpoints on chosen classes (kept without a session, armed on start)
/// and arms them in every session that takes them. Also in one still starting: one that has
/// armed already would miss the list, and one that has not answers `vmNotFound` until then.
pub async fn set_exception_class_breakpoints(&self, list: Vec<ExceptionClassBreakpoint>) {
*self.exception_classes.lock() = list;
for s in self.live_sessions() {
if s.exception_classes.is_none() || s.conn.is_closed() {
continue;
}
let _turn = s.exception_turn.lock().await;
self.arm_exception_classes(&s, true).await;
}
}
}
+1 -27
View File
@@ -1,6 +1,5 @@
//! Class-table snapshots of a debugged JVM, read over the HotSpot attach listener or, where
//! that is unavailable, counted by the debugger; the JVM's objects through the debugger; and
//! its thread dumps.
//! that is unavailable, counted by the debugger; and the JVM's objects through the debugger.
mod fallback;
mod heap;
@@ -11,7 +10,6 @@ mod snapshot;
pub(crate) mod test_support;
#[cfg(test)]
mod tests;
mod threads;
use crate::session::Session;
use crate::session::Suspension;
@@ -30,8 +28,6 @@ pub(crate) use inspect::{fields, instances, referrers, set_inspector, vm_target,
pub(crate) use scan::watch_for_attached_jvm;
pub(crate) use scan::{JvmFinder, attach_target, find_attached_jvm, find_local_jvm, local_jdwp_port};
use snapshot::{AttachProbe, JdkProbe, take_snapshot};
pub use threads::{JvmThreadDump, JvmThreadsResult, JvmThreadsUnavailable, run_jvm_thread_dump};
pub(crate) use threads::{debugged_run_thread_dump, session_thread_dump};
pub const JVM_MEMORY_ADAPTERS: &[&str] = &["java-debug", crate::kotlin::ADAPTER, crate::kotlin_lsp::ADAPTER];
pub const HISTOGRAM_TIMEOUT: Duration = Duration::from_secs(10);
@@ -194,25 +190,6 @@ fn histogram_pid(session: &Session) -> Result<Option<i32>, JvmMemoryUnavailable>
Ok(None)
}
/// Whether `session` is a JVM session attached to `run` that may hold `pid`: its JVM is `pid` or
/// not located yet.
pub(crate) fn attached_to_run(session: &Session, run: ide_core::RunId, pid: u32) -> bool {
let located = session.jvm_pid.load(Ordering::Acquire);
session.run == Some(run)
&& JVM_MEMORY_ADAPTERS.contains(&session.adapter.as_str())
&& !session.terminated.load(Ordering::Acquire)
&& (located <= 0 || located == i64::from(pid))
}
/// Whether `session` debugs the JVM `pid`: the program it launched or the JVM its attach found.
pub(crate) fn debugs_jvm(session: &Session, pid: u32) -> bool {
let jvm = if session.request == "launch" { launch_pid(session) } else { session.jvm_pid.load(Ordering::Acquire) };
JVM_MEMORY_ADAPTERS.contains(&session.adapter.as_str())
&& !session.terminated.load(Ordering::Acquire)
&& jvm > 0
&& jvm == i64::from(pid)
}
/// The JVM a launch session started: the one the IDE started for an app-launched (Kotlin)
/// session, else the program the adapter reported; 0 when neither is known.
pub(crate) fn launch_pid(session: &Session) -> i64 {
@@ -229,8 +206,6 @@ pub(crate) enum JvmTarget<'a> {
/// The JVM of an attach session. While `pid` is 0 it is looked up by `jdwp_port`, which is
/// `None` for a remote JVM.
Attached { pid: &'a AtomicI64, jdwp_port: Option<u16> },
/// A JVM the session debugs, found from outside it (in a run's process tree).
Known(i32),
/// Known without asking any JVM: no histogram can be taken, for this reason.
Unavailable(JvmMemoryUnavailable),
}
@@ -286,7 +261,6 @@ async fn histogram(
fn lookup(target: JvmTarget<'_>) -> Result<Lookup, JvmMemoryUnavailable> {
match target {
JvmTarget::Launched(pid) => Ok(Lookup::Tree(pid)),
JvmTarget::Known(pid) => Ok(Lookup::Known(pid)),
JvmTarget::Attached { pid, jdwp_port } => match i32::try_from(pid.load(Ordering::Acquire)) {
Ok(p) if p > 0 => Ok(Lookup::Known(p)),
_ => jdwp_port.map(Lookup::Scan).ok_or(JvmMemoryUnavailable::AttachedJvmNotFound),
+1 -19
View File
@@ -15,8 +15,7 @@ use std::time::Duration;
const VERSION_TIMEOUT: Duration = Duration::from_secs(2);
const FLAGS_TIMEOUT: Duration = Duration::from_secs(2);
/// The attach calls a snapshot, a heap dump or a thread dump makes, so tests can stand in for a
/// JVM.
/// The attach calls a snapshot or a heap dump makes, so tests can stand in for a JVM.
pub(crate) trait AttachProbe: Send + Sync {
fn has_listener(&self, pid: u32) -> bool;
/// Asks only the JVMs whose pid `may_query` accepts.
@@ -28,11 +27,6 @@ pub(crate) trait AttachProbe: Send + Sync {
fn heap_dump(&self, pid: u32, path: &Path, timeout: Duration) -> Result<HeapDumpReply, AttachError>;
/// `None` where the free space is not known.
fn free_bytes(&self, dir: &Path) -> Option<u64>;
fn thread_print(&self, pid: u32) -> Result<String, AttachError>;
/// Opens `pid`'s attach listener unless it runs; refuses a process not confirmed HotSpot.
fn ensure_listener(&self, pid: u32) -> Result<(), AttachError>;
/// Confirmed HotSpot and not one of Gradle's own JVMs; asks the JVM nothing.
fn is_application_jvm(&self, pid: u32) -> bool;
}
pub(super) struct JdkProbe {
@@ -79,18 +73,6 @@ impl AttachProbe for JdkProbe {
fn free_bytes(&self, dir: &Path) -> Option<u64> {
ide_heap::free_bytes(dir)
}
fn thread_print(&self, pid: u32) -> Result<String, AttachError> {
ide_jvm_attach::thread_print(pid, ide_jvm_attach::THREAD_DUMP_TIMEOUT)
}
fn ensure_listener(&self, pid: u32) -> Result<(), AttachError> {
ide_jvm_attach::ensure_listener(pid, ide_jvm_attach::LISTENER_START_TIMEOUT)
}
fn is_application_jvm(&self, pid: u32) -> bool {
ide_jvm_attach::is_application_jvm(pid)
}
}
fn alive(pid: u32) -> bool {
@@ -102,7 +102,6 @@ pub(crate) fn bare_session_of(name: &str, request: &str) -> BareSession {
server_host: None,
connect: None,
pinned: None,
resolve_lazy_variables: false,
};
let session = Session::new(
DebugSessionId(1),
-361
View File
@@ -3,7 +3,6 @@ use super::heap::*;
use super::scan::*;
use super::snapshot::*;
use super::test_support::{BareSession, FakeInspector, bare_session, bare_session_of};
use super::threads::*;
use super::*;
use ide_core::CancellationToken;
use ide_jvm_attach::{AttachError, HeapDumpReply, HistogramRow, JavaVersion};
@@ -40,13 +39,6 @@ struct FakeProbe {
free: Option<u64>,
/// Answering this command stops the program: runs the hook.
stops_on: Option<(&'static str, StopHook)>,
thread_dumps: parking_lot::Mutex<VecDeque<Result<String, AttachError>>>,
/// Replies to `ensure_listener`, in order; `Ok` once empty.
listener_starts: parking_lot::Mutex<VecDeque<Result<(), AttachError>>>,
/// Pids `is_application_jvm` confirms.
application_jvms: Vec<u32>,
/// Pids `ensure_listener` was asked for.
ensured: parking_lot::Mutex<Vec<u32>>,
}
type StopHook = Box<dyn Fn() + Send + Sync>;
@@ -105,10 +97,6 @@ impl FakeProbe {
dump_bytes: 64,
free: None,
stops_on: None,
thread_dumps: parking_lot::Mutex::new(VecDeque::new()),
listener_starts: parking_lot::Mutex::new(VecDeque::new()),
application_jvms: Vec::new(),
ensured: parking_lot::Mutex::new(Vec::new()),
}
}
@@ -179,20 +167,6 @@ impl AttachProbe for FakeProbe {
fn free_bytes(&self, _dir: &Path) -> Option<u64> {
self.free
}
fn thread_print(&self, _pid: u32) -> Result<String, AttachError> {
self.enter("thread_print");
std::thread::sleep(self.delay);
self.leave();
self.thread_dumps.lock().pop_front().expect("unexpected thread dump request")
}
fn ensure_listener(&self, pid: u32) -> Result<(), AttachError> {
self.record("ensure_listener");
self.ensured.lock().push(pid);
self.listener_starts.lock().pop_front().unwrap_or(Ok(()))
}
fn is_application_jvm(&self, pid: u32) -> bool {
self.application_jvms.contains(&pid)
}
}
const FLAGS: &str = "-XX:+UseCompressedOops -XX:+StartAttachListener";
@@ -1186,341 +1160,6 @@ async fn jdk11_is_refused_while_the_link_is_suspended_before_dap_stops() {
assert!(!dir.exists());
}
const THREADS: &str = "Full thread dump OpenJDK 64-Bit Server VM (21.0.5+11-LTS mixed mode, sharing):\n\n\"main\" #1 [259] prio=5 os_prio=31 cpu=31.20ms elapsed=1.70s tid=0x1 nid=259 runnable [0x2]\n java.lang.Thread.State: RUNNABLE\n";
fn dumping_threads(listener: u32, dumps: Vec<Result<String, AttachError>>) -> FakeProbe {
let fake = FakeProbe::new(listener, Vec::new());
*fake.thread_dumps.lock() = dumps.into();
fake
}
fn threads_unavailable(r: JvmThreadsResult) -> JvmThreadsUnavailable {
match r {
JvmThreadsResult::Unavailable { reason } => reason,
other => panic!("{other:?}"),
}
}
fn threads_jvm(reason: JvmMemoryUnavailable) -> JvmThreadsUnavailable {
JvmThreadsUnavailable::Jvm { reason }
}
#[test]
fn threads_while_running_start_the_listener() {
let fake = dumping_threads(99, vec![Ok(THREADS.into())]);
let r = dump_threads(&fake, 12, false);
let JvmThreadsResult::Ready { dump } = r else { panic!("{r:?}") };
assert_eq!((dump.text.as_str(), dump.pid, dump.java_version.as_str()), (THREADS, 12, "21.0.5"));
assert!(!dump.taken_while_suspended);
assert_eq!(*fake.commands.lock(), ["ensure_listener", "thread_print"]);
}
#[test]
fn threads_while_suspended_without_listener_do_not_attach() {
let fake = dumping_threads(99, Vec::new());
assert_eq!(
threads_unavailable(dump_threads(&fake, 12, true)),
threads_jvm(JvmMemoryUnavailable::ListenerNotRunning)
);
assert!(fake.commands.lock().is_empty());
}
#[test]
fn threads_while_suspended_on_11_are_refused() {
let mut fake = dumping_threads(12, Vec::new());
fake.version = Some(JavaVersion { major: 11, text: "11.0.25".into() });
assert_eq!(
threads_unavailable(dump_threads(&fake, 12, true)),
threads_jvm(JvmMemoryUnavailable::UnsafeWhileSuspended { java_major: 11 })
);
fake.version = None;
assert_eq!(
threads_unavailable(dump_threads(&fake, 12, true)),
threads_jvm(JvmMemoryUnavailable::UnsafeWhileSuspended { java_major: 0 })
);
assert!(fake.commands.lock().is_empty());
}
#[test]
fn threads_while_suspended_on_17_use_the_running_listener() {
let mut fake = dumping_threads(12, vec![Ok(THREADS.into())]);
fake.version = Some(JavaVersion { major: 17, text: "17.0.13".into() });
let r = dump_threads(&fake, 12, true);
let JvmThreadsResult::Ready { dump } = r else { panic!("{r:?}") };
assert!(dump.taken_while_suspended);
assert_eq!(dump.java_version, "17.0.13");
assert_eq!(*fake.commands.lock(), ["thread_print"]);
}
#[test]
fn threads_of_a_tree_without_a_listener_go_to_its_first_application_jvm() {
// A shell (10) started a Gradle client (11) that started the program's JVM (12).
let mut fake = dumping_threads(99, vec![Ok(THREADS.into())]);
fake.application_jvms = vec![12];
let r = dump_tree(&fake, &[10, 11, 12], false);
let JvmThreadsResult::Ready { dump } = r else { panic!("{r:?}") };
assert_eq!(dump.pid, 12);
assert_eq!(*fake.ensured.lock(), [12]);
// No JVM at all: the reported pid is asked, which tells an exited program from a non-JVM.
let fake = dumping_threads(99, Vec::new());
*fake.listener_starts.lock() = vec![Err(AttachError::NotAJvm)].into();
assert_eq!(
threads_unavailable(dump_tree(&fake, &[10, 11], false)),
threads_jvm(JvmMemoryUnavailable::NoJvmProcess)
);
assert_eq!(*fake.ensured.lock(), [10]);
}
#[cfg(unix)]
#[tokio::test]
async fn launched_thread_dump_without_a_listener_finds_the_jvm_below_the_reported_pid() {
struct Child(std::process::Child);
impl Drop for Child {
fn drop(&mut self) {
let _ = self.0.kill();
let _ = self.0.wait();
}
}
let child = Child(std::process::Command::new("sleep").arg("30").spawn().unwrap());
let jvm = child.0.id();
let state = tokio::sync::Mutex::new(JvmMemoryState::default());
let mut fake = dumping_threads(0, vec![Ok(THREADS.into())]);
fake.application_jvms = vec![jvm];
let fake = Arc::new(fake);
let probe: Arc<dyn AttachProbe> = fake.clone();
let target = JvmTarget::Launched(std::process::id() as i32);
let r = thread_dump(&state, || false, |_| probe, target).await.unwrap();
let JvmThreadsResult::Ready { dump } = r else { panic!("{r:?}") };
assert_eq!(dump.pid, jvm);
assert_eq!(*fake.ensured.lock(), [jvm]);
}
#[tokio::test]
async fn a_session_debugs_the_jvm_it_launched_or_found() {
let attach = bare_session("attach");
attach.session.jvm_pid.store(4242, Ordering::Release);
assert!(debugs_jvm(&attach.session, 4242));
assert!(!debugs_jvm(&attach.session, 4243));
let launch = bare_session("launch");
launch.session.debuggee_pid.store(77, Ordering::Release);
assert!(debugs_jvm(&launch.session, 77));
let python = bare_session_of("debugpy", "attach");
python.session.jvm_pid.store(4242, Ordering::Release);
assert!(!debugs_jvm(&python.session, 4242));
attach.session.terminated.store(true, Ordering::Release);
assert!(!debugs_jvm(&attach.session, 4242));
// An attach whose JVM is not found yet debugs no pid.
assert!(!debugs_jvm(&bare_session("attach").session, 0));
}
#[tokio::test]
async fn a_session_attached_to_a_run_may_hold_its_jvm_before_it_is_located() {
let run = ide_core::RunId(7);
let mut bare = bare_session("attach");
Arc::get_mut(&mut bare.session).unwrap().run = Some(run);
// Gradle bootRun Debug opens no attach listener, so the attach-time scan finds no pid.
assert!(attached_to_run(&bare.session, run, 555));
assert!(!attached_to_run(&bare.session, ide_core::RunId(8), 555));
bare.session.jvm_pid.store(4242, Ordering::Release);
assert!(attached_to_run(&bare.session, run, 4242));
assert!(!attached_to_run(&bare.session, run, 555), "another JVM of the same run");
bare.session.terminated.store(true, Ordering::Release);
assert!(!attached_to_run(&bare.session, run, 4242));
let mut python = bare_session_of("debugpy", "attach");
Arc::get_mut(&mut python.session).unwrap().run = Some(run);
assert!(!attached_to_run(&python.session, run, 555));
assert!(!attached_to_run(&bare_session("attach").session, run, 555), "not linked to a run");
}
#[tokio::test]
async fn run_dump_through_a_linked_session_whose_jvm_is_not_located() {
// Stopped at a breakpoint, no listener: refused with the resume reason, no listener start.
let bare = stopped_attach(0);
let fake = Arc::new(dumping_threads(99, Vec::new()));
let probe: Arc<dyn AttachProbe> = fake.clone();
let r = known_pid_dump(&bare.session, |_| probe, 555).await.unwrap();
assert_eq!(threads_unavailable(r), threads_jvm(JvmMemoryUnavailable::ListenerNotRunning));
assert!(fake.commands.lock().is_empty());
// Running: the run's JVM is dumped under the session's turn.
let bare = bare_session("attach");
let fake = Arc::new(dumping_threads(99, vec![Ok(THREADS.into())]));
let probe: Arc<dyn AttachProbe> = fake.clone();
let r = known_pid_dump(&bare.session, |_| probe, 555).await.unwrap();
let JvmThreadsResult::Ready { dump } = r else { panic!("{r:?}") };
assert_eq!((dump.pid, dump.taken_while_suspended), (555, false));
assert_eq!(*fake.ensured.lock(), [555]);
}
/// A run's JVM held at a breakpoint by a debugger attached to it (Debug of `spring-boot:run`).
fn stopped_attach(pid: u32) -> BareSession {
let bare = bare_session("attach");
bare.session.jvm_pid.store(i64::from(pid), Ordering::Release);
bare.session.suspended.stopped(None, true);
bare
}
#[tokio::test]
async fn run_dump_of_a_suspended_debugged_jvm_takes_the_suspended_path() {
let bare = stopped_attach(4242);
let mut fake = dumping_threads(4242, Vec::new());
fake.version = Some(JavaVersion { major: 11, text: "11.0.25".into() });
let fake = Arc::new(fake);
let probe: Arc<dyn AttachProbe> = fake.clone();
let r = known_pid_dump(&bare.session, |_| probe, 4242).await.unwrap();
assert_eq!(threads_unavailable(r), threads_jvm(JvmMemoryUnavailable::UnsafeWhileSuspended { java_major: 11 }));
assert!(fake.commands.lock().is_empty());
// No listener: none is started, the JVM's Signal Dispatcher being stopped.
let fake = Arc::new(dumping_threads(99, Vec::new()));
let probe: Arc<dyn AttachProbe> = fake.clone();
let r = known_pid_dump(&bare.session, |_| probe, 4242).await.unwrap();
assert_eq!(threads_unavailable(r), threads_jvm(JvmMemoryUnavailable::ListenerNotRunning));
assert!(fake.commands.lock().is_empty());
let mut fake = dumping_threads(4242, vec![Ok(THREADS.into())]);
fake.version = Some(JavaVersion { major: 17, text: "17.0.13".into() });
let probe: Arc<dyn AttachProbe> = Arc::new(fake);
let r = known_pid_dump(&bare.session, |_| probe, 4242).await.unwrap();
let JvmThreadsResult::Ready { dump } = r else { panic!("{r:?}") };
assert!(dump.taken_while_suspended);
assert_eq!(dump.pid, 4242);
}
#[tokio::test]
async fn run_dump_of_a_debugged_jvm_waits_for_the_session_turn() {
let bare = bare_session("attach");
bare.session.jvm_pid.store(4242, Ordering::Release);
let fake = Arc::new(dumping_threads(99, Vec::new()));
let probe: Arc<dyn AttachProbe> = fake.clone();
let histogram = bare.session.jvm_memory.lock().await;
let mut queued = Box::pin(known_pid_dump(&bare.session, |_| probe, 4242));
assert!(tokio::time::timeout(Duration::from_millis(50), &mut queued).await.is_err());
// The program hits a breakpoint while the dump waits behind the session's histogram.
bare.session.suspended.stopped(None, true);
drop(histogram);
assert_eq!(threads_unavailable(queued.await.unwrap()), threads_jvm(JvmMemoryUnavailable::ListenerNotRunning));
assert!(fake.commands.lock().is_empty());
}
#[test]
fn threads_of_an_exited_program() {
let mut fake = dumping_threads(99, Vec::new());
fake.alive = false;
*fake.listener_starts.lock() = vec![Err(AttachError::NoListener)].into();
assert_eq!(threads_unavailable(dump_threads(&fake, 12, false)), threads_jvm(JvmMemoryUnavailable::ProgramExited));
assert_eq!(threads_unavailable(dump_threads(&fake, 12, true)), threads_jvm(JvmMemoryUnavailable::ProgramExited));
}
#[test]
fn thread_dump_errors_map_to_reasons() {
let fake = dumping_threads(12, vec![Err(AttachError::Timeout)]);
assert_eq!(threads_unavailable(dump_threads(&fake, 12, false)), threads_jvm(JvmMemoryUnavailable::TimedOut));
let fake = dumping_threads(99, Vec::new());
*fake.listener_starts.lock() = vec![Err(AttachError::ListenerDidNotStart)].into();
assert_eq!(threads_unavailable(dump_threads(&fake, 12, false)), JvmThreadsUnavailable::ListenerDidNotStart);
assert_eq!(*fake.commands.lock(), ["ensure_listener"]);
let mut fake = dumping_threads(99, Vec::new());
*fake.listener_starts.lock() = vec![Err(AttachError::NotAJvm), Err(AttachError::NotAJvm)].into();
assert_eq!(threads_unavailable(dump_threads(&fake, 12, false)), threads_jvm(JvmMemoryUnavailable::NoJvmProcess));
fake.alive = false;
assert_eq!(threads_unavailable(dump_threads(&fake, 12, false)), threads_jvm(JvmMemoryUnavailable::ProgramExited));
let fake = dumping_threads(12, vec![Err(AttachError::Command { code: 1, message: "no".into() })]);
let JvmThreadsUnavailable::Failed { message } = threads_unavailable(dump_threads(&fake, 12, false)) else {
panic!("not a failure")
};
assert!(message.contains("no"), "{message}");
}
#[test]
fn thread_results_serialize_with_camel_case_tags() {
let r = JvmThreadsResult::Unavailable { reason: threads_jvm(JvmMemoryUnavailable::ListenerNotRunning) };
assert_eq!(
serde_json::to_value(r).unwrap(),
serde_json::json!({"status": "unavailable", "reason": {"kind": "jvm", "reason": {"kind": "listenerNotRunning"}}})
);
let r = JvmThreadsResult::Unavailable { reason: JvmThreadsUnavailable::ListenerDidNotStart };
assert_eq!(
serde_json::to_value(r).unwrap(),
serde_json::json!({"status": "unavailable", "reason": {"kind": "listenerDidNotStart"}})
);
let dump = JvmThreadDump {
text: "t".into(),
pid: 7,
java_version: String::new(),
taken_while_suspended: true,
elapsed_ms: 3,
};
assert_eq!(
serde_json::to_value(JvmThreadsResult::Ready { dump }).unwrap(),
serde_json::json!({
"status": "ready",
"dump": {"text": "t", "pid": 7, "javaVersion": "", "takenWhileSuspended": true, "elapsedMs": 3}
})
);
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn threads_take_the_memory_lock() {
let pid = std::process::id();
let state = tokio::sync::Mutex::new(JvmMemoryState::default());
let mut fake = dumping_threads(pid, vec![Ok(THREADS.into())]);
*fake.histograms.lock() = vec![Ok(HISTOGRAM.into())].into();
fake.delay = Duration::from_millis(100);
let fake = Arc::new(fake);
let probe: Arc<dyn AttachProbe> = fake.clone();
let running = Suspension::default();
let (classes, threads) = tokio::join!(
snapshot(&state, &running, |_| probe.clone(), JvmTarget::Launched(pid as i32), None),
thread_dump(&state, || false, |_| probe.clone(), JvmTarget::Launched(pid as i32))
);
assert!(matches!(classes.unwrap(), JvmMemoryResult::Ready { .. }));
let threads = threads.unwrap();
assert!(matches!(threads, JvmThreadsResult::Ready { .. }), "{threads:?}");
assert_eq!(fake.max_in_flight.load(Ordering::SeqCst), 1);
assert_eq!(*fake.commands.lock(), ["histogram", "ensure_listener", "thread_print"]);
}
#[cfg(unix)]
#[tokio::test]
async fn queued_thread_dump_reads_suspension_under_the_lock() {
let pid = std::process::id();
let state = tokio::sync::Mutex::new(JvmMemoryState::default());
let suspended = Suspension::default();
let fake = Arc::new(dumping_threads(0, Vec::new()));
let probe: Arc<dyn AttachProbe> = fake.clone();
let running = state.lock().await;
let mut queued = Box::pin(thread_dump(&state, || suspended.get(), |_| probe, JvmTarget::Launched(pid as i32)));
assert!(tokio::time::timeout(Duration::from_millis(50), &mut queued).await.is_err());
// The program hits a breakpoint while the dump waits behind a class-table request.
suspended.stopped(None, true);
drop(running);
assert_eq!(threads_unavailable(queued.await.unwrap()), threads_jvm(JvmMemoryUnavailable::ListenerNotRunning));
assert!(fake.commands.lock().is_empty());
}
#[tokio::test]
async fn attached_thread_dump_keeps_the_scanned_jvm() {
let state = tokio::sync::Mutex::new(JvmMemoryState::default());
let jvm_pid = AtomicI64::new(0);
let mut fake = dumping_threads(4242, vec![Ok(THREADS.into())]);
fake.jdwp = Some((5005, 4242));
let probe: Arc<dyn AttachProbe> = Arc::new(fake);
let target = JvmTarget::Attached { pid: &jvm_pid, jdwp_port: Some(5005) };
let r = thread_dump(&state, || false, |_| probe, target).await.unwrap();
let JvmThreadsResult::Ready { dump } = r else { panic!("{r:?}") };
assert_eq!(dump.pid, 4242);
assert_eq!(jvm_pid.load(Ordering::SeqCst), 4242);
}
#[tokio::test]
async fn capability_matches_memory() {
for adapter in JVM_MEMORY_ADAPTERS.iter().copied().chain(["debugpy"]) {
-181
View File
@@ -1,181 +0,0 @@
//! A thread dump (`Thread.print -l`) of a debugged or running JVM.
use super::heap::capture_suspended;
use super::snapshot::{AttachProbe, JdkProbe, attach_failure, gone, pick_jvm_pid};
use super::{
JvmMemoryState, JvmMemoryUnavailable, JvmTarget, histogram_pid, keep_found, lookup, resolve_jvm,
safe_while_suspended, session_target, until_located,
};
use crate::session::Session;
use ide_core::{IdeError, IdeResult};
use ide_jvm_attach::AttachError;
use serde::{Deserialize, Serialize};
use specta::Type;
use std::sync::Arc;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct JvmThreadDump {
pub text: String,
pub pid: u32,
/// Empty when unknown.
pub java_version: String,
pub taken_while_suspended: bool,
/// Wall time of the `Thread.print` request.
pub elapsed_ms: u32,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(tag = "kind", rename_all = "camelCase", rename_all_fields = "camelCase")]
pub enum JvmThreadsUnavailable {
/// The reason a class table could not be read applies to the dump too.
Jvm {
reason: JvmMemoryUnavailable,
},
/// The JVM ignored the request to open its attach listener (`-XX:+DisableAttachMechanism`).
ListenerDidNotStart,
/// A run on a remote host, whose JVM this machine cannot attach to.
RemoteRun,
Failed {
message: String,
},
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(tag = "status", rename_all = "camelCase", rename_all_fields = "camelCase")]
pub enum JvmThreadsResult {
Ready { dump: JvmThreadDump },
Unavailable { reason: JvmThreadsUnavailable },
}
/// A thread dump of `pid`, a JVM no debugger holds. Blocking for up to the listener start and
/// dump timeouts, so callers run it in `spawn_blocking`.
pub fn run_jvm_thread_dump(pid: u32) -> JvmThreadsResult {
dump_threads(&JdkProbe { suspended: false }, pid, false)
}
pub(crate) async fn session_thread_dump(session: Arc<Session>) -> IdeResult<JvmThreadsResult> {
until_located(&session).await;
let launched = histogram_pid(&session);
// Detached, so a caller that gives up cannot release the lock while the JVM is still
// answering and let a class-table request run next to it.
tokio::spawn(async move {
let target = session_target(&session, launched);
let probe = |suspended| -> Arc<dyn AttachProbe> { Arc::new(JdkProbe { suspended }) };
thread_dump(&session.jvm_memory, || capture_suspended(&session), probe, target).await
})
.await
.map_err(|e| IdeError::internal(format!("JVM thread dump failed: {e}")))?
}
/// A thread dump of `pid`, a run's JVM that `session` debugs, taken as the session's own dump
/// is: a JVM the debugger holds suspended is never asked to open a listener.
pub(crate) async fn debugged_run_thread_dump(session: Arc<Session>, pid: u32) -> IdeResult<JvmThreadsResult> {
// Detached for the same reason as `session_thread_dump`.
tokio::spawn(async move {
let probe = |suspended| -> Arc<dyn AttachProbe> { Arc::new(JdkProbe { suspended }) };
known_pid_dump(&session, probe, pid).await
})
.await
.map_err(|e| IdeError::internal(format!("JVM thread dump failed: {e}")))?
}
pub(super) async fn known_pid_dump(
session: &Session,
probe: impl FnOnce(bool) -> Arc<dyn AttachProbe>,
pid: u32,
) -> IdeResult<JvmThreadsResult> {
let target =
i32::try_from(pid).map_or(JvmTarget::Unavailable(JvmMemoryUnavailable::NoJvmProcess), JvmTarget::Known);
thread_dump(&session.jvm_memory, || capture_suspended(session), probe, target).await
}
/// Takes the class-table lock, so a dump never runs beside a histogram or heap dump of the same
/// session; `suspended` and then `probe` are read once it is held.
pub(super) async fn thread_dump(
state: &tokio::sync::Mutex<JvmMemoryState>,
suspended: impl FnOnce() -> bool,
probe: impl FnOnce(bool) -> Arc<dyn AttachProbe>,
target: JvmTarget<'_>,
) -> IdeResult<JvmThreadsResult> {
let _turn = state.lock().await;
let suspended = suspended();
let lookup = match lookup(target) {
Ok(lookup) => lookup,
Err(reason) => return Ok(jvm(reason)),
};
let probe = probe(suspended);
let (found, outcome) = tokio::task::spawn_blocking(move || match resolve_jvm(lookup, &*probe, suspended) {
Ok((tree, found)) => (found, dump_tree(&*probe, &tree, suspended)),
Err(reason) => (None, jvm(reason)),
})
.await
.map_err(|e| IdeError::internal(format!("JVM thread dump failed: {e}")))?;
keep_found(target, found);
Ok(outcome)
}
/// `tree` starts with the session's reported pid, followed by its descendants: the JVM is the
/// first with a listener, else the first application JVM (the reported pid may be a shell or a
/// Gradle client), else the reported pid.
pub(super) fn dump_tree(probe: &dyn AttachProbe, tree: &[i32], suspended: bool) -> JvmThreadsResult {
let jvm_pid = pick_jvm_pid(tree, |p| probe.has_listener(p))
.or_else(|| pick_jvm_pid(tree, |p| probe.is_application_jvm(p)))
.or_else(|| tree.first().and_then(|&p| u32::try_from(p).ok()).filter(|&p| p > 0));
match jvm_pid {
Some(pid) => dump_threads(probe, pid, suspended),
None => jvm(JvmMemoryUnavailable::NoJvmProcess),
}
}
/// Blocking. A JVM a debugger holds suspended cannot open a listener (its Signal Dispatcher is
/// stopped), and one below 17 hangs even with one, so it is asked only when both are ruled out.
pub(crate) fn dump_threads(probe: &dyn AttachProbe, pid: u32, suspended: bool) -> JvmThreadsResult {
if suspended {
if !probe.has_listener(pid) {
return jvm(gone(probe, pid));
}
} else if let Err(e) = probe.ensure_listener(pid) {
return failure(probe, pid, e);
}
let version = probe.version(pid);
if suspended && !safe_while_suspended(version.as_ref()) {
return jvm(JvmMemoryUnavailable::UnsafeWhileSuspended { java_major: version.map_or(0, |v| v.major) });
}
let started = std::time::Instant::now();
let text = match probe.thread_print(pid) {
Ok(text) => text,
Err(e) => return failure(probe, pid, e),
};
let elapsed_ms = u32::try_from(started.elapsed().as_millis()).unwrap_or(u32::MAX);
JvmThreadsResult::Ready {
dump: JvmThreadDump {
text,
pid,
java_version: version.map(|v| v.text).unwrap_or_default(),
taken_while_suspended: suspended,
elapsed_ms,
},
}
}
fn failure(probe: &dyn AttachProbe, pid: u32, error: AttachError) -> JvmThreadsResult {
let reason = match error {
AttachError::ListenerDidNotStart => JvmThreadsUnavailable::ListenerDidNotStart,
// A program that exited leaves no perf-data file, so it fails the HotSpot check too.
AttachError::NotAJvm if probe.alive(pid) => {
JvmThreadsUnavailable::Jvm { reason: JvmMemoryUnavailable::NoJvmProcess }
}
AttachError::NotAJvm => JvmThreadsUnavailable::Jvm { reason: JvmMemoryUnavailable::ProgramExited },
e => match attach_failure(probe, pid, e, "thread dump") {
Ok(reason) => JvmThreadsUnavailable::Jvm { reason },
Err(e) => JvmThreadsUnavailable::Failed { message: e.message },
},
};
JvmThreadsResult::Unavailable { reason }
}
fn jvm(reason: JvmMemoryUnavailable) -> JvmThreadsResult {
JvmThreadsResult::Unavailable { reason: JvmThreadsUnavailable::Jvm { reason } }
}
+28 -150
View File
@@ -12,7 +12,6 @@ pub mod adapter;
pub mod attach;
mod cargo;
pub mod connection;
mod exception_classes;
pub mod jdwp;
mod js_cdp;
mod js_debug;
@@ -25,9 +24,8 @@ pub mod unity;
use adapter::{AdapterLauncher, AdapterSpec, ProcessLauncher};
use connection::{Connection, DapError};
pub use exception_classes::{ExceptionClassBreakpoint, ExceptionClassSupport};
use futures::future::join_all;
use ide_core::{DebugSessionId, IdeError, IdeResult, RunId, SharedSink};
use ide_core::{DebugSessionId, IdeError, IdeResult, SharedSink};
use ide_language::LanguageRegistry;
pub use js_cdp::JsResponseRule;
pub use js_debug::JsResponseBody;
@@ -238,11 +236,6 @@ pub struct Variable {
/// > 0 when expandable.
pub variables_reference: i64,
pub evaluate_name: Option<String>,
/// `value` is not computed yet (DAP `presentationHint.lazy`): the single variable that
/// `variables` returns for `variables_reference` holds the value and its children.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
#[specta(optional)]
pub lazy: bool,
}
/// A completion the adapter offers for an expression (DAP `completions`).
@@ -285,8 +278,6 @@ pub struct SessionExceptionFilters {
pub session: DebugSessionId,
pub adapter: String,
pub filters: Vec<ExceptionFilter>,
/// Set when the session takes exception breakpoints on a chosen class.
pub classes: Option<ExceptionClassSupport>,
}
/// What triggered a hot reload; `flutter debug_adapter` takes it as `reason`.
@@ -340,7 +331,6 @@ pub struct DebugManager {
states: Mutex<HashMap<PathBuf, Vec<BreakpointState>>>,
/// Explicit exception filter choices (filter id → enabled); unset filters use the adapter default.
exception_choices: Mutex<BTreeMap<String, bool>>,
exception_classes: Mutex<Vec<ExceptionClassBreakpoint>>,
function_breakpoints: Mutex<Vec<FunctionBreakpoint>>,
data_breakpoints: Mutex<Vec<DataBreakpoint>>,
/// In-flight stops, by session: a second Stop sets `stop_force`, the waiting one kills.
@@ -460,15 +450,6 @@ fn child_name(configuration: &Value, parent: &str) -> String {
}
}
/// `extra_json` key naming the run whose JVM an attach debugs; IDE-side, never sent to the
/// adapter.
pub const RUN_LINK: &str = "__openideaRun";
fn take_run_link(arguments: &mut Value) -> Option<RunId> {
let run = arguments.as_object_mut()?.remove(RUN_LINK)?;
serde_json::from_value(run).ok()
}
/// Builds the `launch`/`attach` arguments: our fields first, then `extra_json` merged on top.
pub fn launch_arguments(config: &LaunchConfig) -> IdeResult<Value> {
// VS Code puts `type`, `request` and `name` in the arguments; js-debug picks launch
@@ -746,46 +727,9 @@ pub(crate) fn variable_from(v: &Value) -> Variable {
type_name: s("type").filter(|t| !t.is_empty()),
variables_reference: v.get("variablesReference").and_then(Value::as_i64).unwrap_or(0),
evaluate_name: s("evaluateName"),
lazy: v.pointer("/presentationHint/lazy").and_then(Value::as_bool).unwrap_or(false),
}
}
async fn session_variables(session: &Session, reference: i64) -> IdeResult<Vec<Variable>> {
let body =
session.conn.request_timeout("variables", json!({ "variablesReference": reference }), REQUEST_TIMEOUT).await?;
Ok(body
.get("variables")
.and_then(Value::as_array)
.map(|v| v.iter().map(variable_from).collect())
.unwrap_or_default())
}
async fn resolve_in(session: &Session, variable: Variable) -> IdeResult<Variable> {
if !variable.lazy || variable.variables_reference <= 0 {
return Ok(variable);
}
let mut inner = session_variables(session, variable.variables_reference).await?;
Ok(match (inner.pop(), inner.is_empty()) {
(Some(value), true) => Variable {
type_name: value.type_name.or(variable.type_name),
evaluate_name: variable.evaluate_name.or(value.evaluate_name),
name: variable.name,
value: value.value,
variables_reference: value.variables_reference,
lazy: value.lazy,
},
_ => variable,
})
}
/// A value that cannot be computed stays lazy, so the row can still be opened by hand.
async fn resolve_lazy(session: &Session, variable: Variable) -> Variable {
if !variable.lazy {
return variable;
}
resolve_in(session, variable.clone()).await.unwrap_or(variable)
}
impl DebugManager {
pub fn new(languages: Arc<LanguageRegistry>) -> Arc<Self> {
Self::with_launcher(languages, Arc::new(ProcessLauncher))
@@ -802,7 +746,6 @@ impl DebugManager {
breakpoints: Mutex::default(),
states: Mutex::default(),
exception_choices: Mutex::default(),
exception_classes: Mutex::default(),
function_breakpoints: Mutex::default(),
data_breakpoints: Mutex::default(),
stopping: Mutex::default(),
@@ -851,18 +794,6 @@ impl DebugManager {
config: LaunchConfig,
owner: SessionOwner,
custom_command: impl FnOnce(&str) -> Option<String>,
) -> IdeResult<DebugSessionId> {
self.start_with_exception_classes(config, owner, custom_command, None).await
}
/// [`start_with`](Self::start_with), the session arming [`Self::set_exception_class_breakpoints`]
/// through `exception_classes`.
pub async fn start_with_exception_classes(
&self,
config: LaunchConfig,
owner: SessionOwner,
custom_command: impl FnOnce(&str) -> Option<String>,
exception_classes: Option<Arc<dyn ide_jvm_inspect::ExceptionClassBreakpoints>>,
) -> IdeResult<DebugSessionId> {
let mut arguments = launch_arguments(&config)?;
// An IDE-side marker (never sent to the adapter): the session is a Flutter
@@ -1004,19 +935,7 @@ impl DebugManager {
}
}
let port = debug_server.map(|s| s.port);
self.start_session(
id,
owner,
config.name,
config.adapter,
None,
config.request,
arguments,
spec,
port,
exception_classes,
)
.await
self.start_session(id, owner, config.name, config.adapter, None, config.request, arguments, spec, port).await
}
/// `startDebugging` reverse request: a child session on the same adapter.
@@ -1041,7 +960,6 @@ impl DebugManager {
configuration,
parent.spec.clone(),
parent.port,
None,
)
.await
.map(|_| ())
@@ -1056,10 +974,9 @@ impl DebugManager {
adapter_name: String,
parent: Option<DebugSessionId>,
request: String,
mut arguments: Value,
arguments: Value,
spec: AdapterSpec,
reuse_port: Option<u16>,
exception_classes: Option<Arc<dyn ide_jvm_inspect::ExceptionClassBreakpoints>>,
) -> IdeResult<DebugSessionId> {
if request != "launch" && request != "attach" {
return Err(IdeError::invalid(format!("request must be `launch` or `attach`, got `{request}`")));
@@ -1074,10 +991,8 @@ impl DebugManager {
let rdbg_pid = (adapter_name == "rdbg" && request == "launch")
.then(|| io.child.as_ref().and_then(tokio::process::Child::id))
.flatten();
let mut session = Session::new(id, owner, name, adapter_name, parent, request, conn, spec, io.port, io.child);
session.exception_classes = exception_classes;
session.run = take_run_link(&mut arguments);
let session = Arc::new(session);
let session =
Arc::new(Session::new(id, owner, name, adapter_name, parent, request, conn, spec, io.port, io.child));
if let Some(launch_type) = arguments.get("type").and_then(Value::as_str) {
let _ = session.launch_type.set(launch_type.to_owned());
}
@@ -1302,12 +1217,8 @@ impl DebugManager {
tracing::debug!("setDataBreakpoints failed: {e}");
}
let has_filters = s.caps.lock().get("exceptionBreakpointFilters").and_then(Value::as_array).is_some();
{
let _turn = s.exception_turn.lock().await;
if has_filters {
let _ = self.send_exception_breakpoints(s).await;
}
self.arm_exception_classes(s, false).await;
if has_filters {
let _ = self.send_exception_breakpoints(s).await;
}
if s.supports("supportsConfigurationDoneRequest") {
if s.adapter == kotlin::ADAPTER {
@@ -1528,7 +1439,6 @@ impl DebugManager {
session: s.id,
adapter: s.adapter.clone(),
filters: exception_filters_from(&s.caps.lock()),
classes: exception_classes::support(s),
})
.collect()
}
@@ -1544,11 +1454,9 @@ impl DebugManager {
if exception_filters_from(&s.caps.lock()).is_empty() {
continue;
}
let _turn = s.exception_turn.lock().await;
if let Err(e) = self.send_exception_breakpoints(&s).await {
tracing::debug!("setExceptionBreakpoints on session {} failed: {e}", s.id.0);
}
self.arm_exception_classes(&s, false).await;
}
Ok(())
}
@@ -1589,7 +1497,6 @@ impl DebugManager {
type_name: body.get("type").and_then(Value::as_str).filter(|t| !t.is_empty()).map(str::to_owned),
variables_reference: body.get("variablesReference").and_then(Value::as_i64).unwrap_or(0),
evaluate_name: evaluate_name.or(Some(name)),
lazy: false,
})
}
@@ -1660,18 +1567,16 @@ impl DebugManager {
}
pub async fn variables(&self, s: DebugSessionId, reference: i64) -> IdeResult<Vec<Variable>> {
let session = self.session(s)?;
let vars = session_variables(&session, reference).await?;
if !session.spec.resolve_lazy_variables {
return Ok(vars);
}
Ok(join_all(vars.into_iter().map(|v| resolve_lazy(&session, v))).await)
}
/// Computes a lazy variable's value (DAP `presentationHint.lazy`); any other variable, or one
/// whose value the adapter does not give as a single variable, comes back unchanged.
pub async fn resolve_variable(&self, s: DebugSessionId, variable: Variable) -> IdeResult<Variable> {
resolve_in(&*self.session(s)?, variable).await
let body = self
.session(s)?
.conn
.request_timeout("variables", json!({ "variablesReference": reference }), REQUEST_TIMEOUT)
.await?;
Ok(body
.get("variables")
.and_then(Value::as_array)
.map(|v| v.iter().map(variable_from).collect())
.unwrap_or_default())
}
/// Evaluates in the `repl` context.
@@ -1697,18 +1602,13 @@ impl DebugManager {
args["frameId"] = f.into();
}
let body = session.conn.request_timeout("evaluate", args, REQUEST_TIMEOUT).await?;
let result = Variable {
Ok(Variable {
name: expression.clone(),
value: body.get("result").and_then(Value::as_str).unwrap_or_default().to_owned(),
type_name: body.get("type").and_then(Value::as_str).filter(|t| !t.is_empty()).map(str::to_owned),
variables_reference: body.get("variablesReference").and_then(Value::as_i64).unwrap_or(0),
evaluate_name: Some(expression),
lazy: body.pointer("/presentationHint/lazy").and_then(Value::as_bool).unwrap_or(false),
};
if !session.spec.resolve_lazy_variables {
return Ok(result);
}
Ok(resolve_lazy(&session, result).await)
})
}
/// Completions for `text` at `line` / `column` (0-based, UTF-16) in the frame's scope; none
@@ -1762,7 +1662,9 @@ impl DebugManager {
let body = session.conn.request_timeout("continue", json!({ "threadId": thread_id }), REQUEST_TIMEOUT).await?;
// DAP: a response without the flag continued every thread.
let all = body.get("allThreadsContinued").and_then(Value::as_bool).unwrap_or(true);
session.finish_resume(ticket, thread_id, all);
session.suspended.resumed(ticket, thread_id, all);
stream_trace::release_done(&session);
session.emit(ide_core::event::DebugEvent::Continued { thread_id, all_threads_continued: all });
Ok(())
}
@@ -1809,7 +1711,9 @@ impl DebugManager {
let sent = session.conn.request_timeout(command, json!({ "threadId": thread_id }), REQUEST_TIMEOUT).await;
step_settled(&session, sent)?;
// A step runs its thread; other threads stopped by their own events stay stopped.
session.finish_resume(ticket, thread_id, false);
session.suspended.resumed(ticket, thread_id, false);
stream_trace::release_done(&session);
session.emit(ide_core::event::DebugEvent::Continued { thread_id, all_threads_continued: true });
Ok(())
}
@@ -1919,7 +1823,9 @@ impl DebugManager {
.request_timeout("stepIn", json!({ "threadId": thread_id, "targetId": target_id }), REQUEST_TIMEOUT)
.await;
step_settled(&session, sent)?;
session.finish_resume(ticket, thread_id, false);
session.suspended.resumed(ticket, thread_id, false);
stream_trace::release_done(&session);
session.emit(ide_core::event::DebugEvent::Continued { thread_id, all_threads_continued: true });
Ok(())
}
@@ -1977,34 +1883,6 @@ impl DebugManager {
jvm_memory::session_heap_dump(session, dir, cancel).await
}
/// `Thread.print -l` of the session's JVM, taking the session's class-table turn. A JVM the
/// debugger holds suspended is asked only when it is 17 or later and its listener already
/// runs: otherwise the request would hang until the program resumes.
pub async fn jvm_thread_dump(&self, s: DebugSessionId) -> IdeResult<JvmThreadsResult> {
let session = self.session(s)?;
jvm_memory::session_thread_dump(session).await
}
/// `Thread.print -l` of `pid`, the JVM of `run`, when a live session debugs it (a build
/// tool's run started for Debug, Attach to Process): taken as [`Self::jvm_thread_dump`] takes
/// it, under that session's turn and suspension. `None` when no session debugs `pid`.
pub async fn debugged_jvm_thread_dump(&self, run: RunId, pid: u32) -> Option<IdeResult<JvmThreadsResult>> {
let session = self.jvm_session_of(run, pid)?;
Some(jvm_memory::debugged_run_thread_dump(session, pid).await)
}
/// A session attached to `run` first: one whose JVM is not located yet (its attach-time scan
/// found no listener) still holds `pid`.
fn jvm_session_of(&self, run: RunId, pid: u32) -> Option<Arc<Session>> {
let sessions = self.live_sessions();
let linked = || sessions.iter().filter(|s| jvm_memory::attached_to_run(s, run, pid));
linked()
.find(|s| jvm_memory::debugs_jvm(s, pid))
.or_else(|| linked().next())
.or_else(|| sessions.iter().find(|s| jvm_memory::debugs_jvm(s, pid)))
.cloned()
}
/// Gives the session the backend for [`Self::jvm_memory_instances`] and the debugger's class
/// counts; the UI is told to reload the session's capabilities.
pub fn set_jvm_inspector(
+16 -148
View File
@@ -8,7 +8,7 @@ use crate::{Breakpoint, BreakpointState, DataBreakpoint, DebugManager, FunctionB
use ide_core::event::DebugEvent;
#[cfg(unix)]
use ide_core::process::process_tree;
use ide_core::{DebugSessionId, IdeEvent, RunId, TaskId};
use ide_core::{DebugSessionId, IdeEvent, TaskId};
use parking_lot::Mutex;
use serde_json::{Value, json};
use std::collections::{BTreeSet, HashMap};
@@ -117,15 +117,7 @@ pub(crate) struct Session {
pub jvm_located: watch::Sender<bool>,
pub kotlin_mirror: Mutex<Option<crate::kotlin::SourceMirror>>,
pub jvm_memory: tokio::sync::Mutex<crate::JvmMemoryState>,
/// The run whose JVM this session attached to (Debug of a build tool's run, Attach to
/// Process on a run): that run's thread dumps go through this session.
pub run: Option<RunId>,
pub stream_tracer: parking_lot::Mutex<Option<Arc<dyn ide_jvm_inspect::StreamTracer>>>,
/// Given at start: the class breakpoints must be armed before `configurationDone`.
pub(crate) exception_classes: Option<Arc<dyn ide_jvm_inspect::ExceptionClassBreakpoints>>,
/// Held from `setExceptionBreakpoints`, which drops the class breakpoints, until they are
/// armed again, so that the last list armed is the manager's.
pub(crate) exception_turn: tokio::sync::Mutex<()>,
pub(crate) stream_trace: parking_lot::Mutex<Option<crate::stream_trace::ActiveTrace>>,
/// The last trace that finished, until the stop its records were read in ends.
pub(crate) stream_trace_done: parking_lot::Mutex<Option<crate::stream_trace::DoneTrace>>,
@@ -163,36 +155,19 @@ impl Stops {
}
/// Ends the stops taken by ticket `upto` of `thread`, or of every thread.
/// Returns whether any stop was removed.
fn release(&mut self, thread: Option<i64>, every: bool, upto: u64) -> bool {
fn release(&mut self, thread: Option<i64>, every: bool, upto: u64) {
let latest = self.latest();
let before = (self.all, self.threads.len());
if every || thread.is_none() || self.all.is_some_and(|t| t <= upto) {
self.all = self.all.filter(|&t| t > upto);
self.threads.retain(|&(_, t)| t > upto);
} else {
self.threads.retain(|&(id, t)| Some(id) != thread || t > upto);
}
let changed = (self.all, self.threads.len()) != before;
// Back on an earlier thread's stop, as the JDWP link moves to it with a new generation.
let now = self.latest();
if now.is_some() && now != latest {
self.ticket += 1;
}
changed
}
/// Whether a stop taken after `after` would be undone by a synthetic `continued` event for
/// `thread` (or for every thread when `every` is set).
fn superseded(&self, thread: i64, every: bool, after: u64) -> bool {
if self.all.is_some_and(|t| t > after) {
return true;
}
if every {
self.threads.iter().any(|&(_, t)| t > after)
} else {
self.threads.iter().any(|&(id, t)| id == thread && t > after)
}
}
}
@@ -217,27 +192,12 @@ impl Suspension {
}
}
/// Runs `emit` under the suspension lock so a synthetic `continued` from a resume reply cannot
/// be emitted after a `stopped` event once that stop has been recorded.
pub fn emit_synced(&self, emit: impl FnOnce()) {
let _stops = self.0.lock();
emit();
}
/// A `continued` event; `all`: its `allThreadsContinued`. Runs `emit` under the same lock so
/// synthetic `continued` events from resume replies stay ordered against it.
pub fn continued_and_emit(&self, thread: Option<i64>, all: bool, emit: impl FnOnce()) {
let mut stops = self.0.lock();
stops.release(thread, all, u64::MAX);
emit();
}
#[cfg(test)]
/// A `continued` event; `all`: its `allThreadsContinued`.
pub fn continued(&self, thread: Option<i64>, all: bool) {
self.continued_and_emit(thread, all, || {});
self.0.lock().release(thread, all, u64::MAX);
}
/// Take before sending a resume-like request and pass to [`Self::resumed_and_emit`].
/// Take before sending a resume-like request and pass to [`Self::resumed`].
pub fn ticket(&self) -> u64 {
self.0.lock().ticket
}
@@ -250,19 +210,8 @@ impl Suspension {
}
/// After a successful resume-like request for `thread`; `all`: every thread ran.
/// Runs `emit` under the lock only when a prior stop was ended and no newer stop superseded it.
pub fn resumed_and_emit(&self, ticket: u64, thread: i64, all: bool, emit: impl FnOnce()) {
let mut stops = self.0.lock();
let superseded = stops.superseded(thread, all, ticket);
let released = stops.release(Some(thread), all, ticket);
if released && !superseded {
emit();
}
}
#[cfg(test)]
pub fn resumed(&self, ticket: u64, thread: i64, all: bool) {
self.resumed_and_emit(ticket, thread, all, || {});
self.0.lock().release(Some(thread), all, ticket);
}
}
@@ -336,10 +285,7 @@ impl Session {
jvm_located: watch::channel(false).0,
kotlin_mirror: Mutex::new(None),
jvm_memory: tokio::sync::Mutex::default(),
run: None,
stream_tracer: parking_lot::Mutex::new(None),
exception_classes: None,
exception_turn: tokio::sync::Mutex::default(),
stream_trace: parking_lot::Mutex::new(None),
stream_trace_done: parking_lot::Mutex::new(None),
quirks: kotlin_lsp::Quirks::default(),
@@ -363,16 +309,6 @@ impl Session {
self.owner.sink.emit(IdeEvent::Debug { session: self.id, event });
}
/// Completes a successful resume or step reply (`ticket` taken before the request): ends the
/// prior stops and emits a synthetic `continued` event unless an adapter event already ended
/// them or a newer `stopped` event superseded it.
pub(crate) fn finish_resume(&self, ticket: u64, thread_id: i64, all: bool) {
self.suspended.resumed_and_emit(ticket, thread_id, all, || {
self.emit(DebugEvent::Continued { thread_id, all_threads_continued: all });
});
crate::stream_trace::release_done(self);
}
/// `path` as sent to the adapter (resolved for [`RESOLVES_PATHS`] adapters).
pub fn adapter_path(&self, path: &Path) -> PathBuf {
if let Some(path) = self.kotlin_mirror.lock().as_ref().and_then(|m| m.adapter_path(path)) {
@@ -846,26 +782,23 @@ async fn on_event(mgr: &Arc<DebugManager>, s: &Arc<Session>, event: &str, mut bo
reason = quirks.stop_reason(reason);
}
mgr.restore_breakpoints(s).await;
s.suspended.emit_synced(|| {
s.emit(DebugEvent::Stopped {
thread_id: int("threadId").unwrap_or(0),
reason,
description: str_("description").or_else(|| str_("text")),
all_threads_stopped: all,
});
s.emit(DebugEvent::Stopped {
thread_id: int("threadId").unwrap_or(0),
reason,
description: str_("description").or_else(|| str_("text")),
all_threads_stopped: all,
});
}
"continued" => {
let all = body.get("allThreadsContinued").and_then(Value::as_bool);
// DAP: an event without the flag continues its thread alone. The UI keeps treating
// it as all threads; the suspension, which holds only threads that stopped, need not.
s.suspended.continued_and_emit(int("threadId"), all.unwrap_or(false), || {
s.emit(DebugEvent::Continued {
thread_id: int("threadId").unwrap_or(0),
all_threads_continued: all.unwrap_or(true),
});
});
s.suspended.continued(int("threadId"), all.unwrap_or(false));
crate::stream_trace::release_done(s);
s.emit(DebugEvent::Continued {
thread_id: int("threadId").unwrap_or(0),
all_threads_continued: all.unwrap_or(true),
});
}
"output" => {
let category = str_("category").unwrap_or_else(|| "console".into());
@@ -1525,71 +1458,6 @@ mod tests {
assert!(!s.get());
}
#[test]
fn synthetic_continued_is_suppressed_when_a_newer_stop_or_continued_already_landed() {
let emit_if_resumed = |s: &Suspension, ticket, thread, all| {
let mut emitted = false;
s.resumed_and_emit(ticket, thread, all, || emitted = true);
emitted
};
// Normal step without an adapter `continued` event emits a synthetic one.
let s = Suspension::default();
s.stopped(Some(1), true);
assert!(emit_if_resumed(&s, s.ticket(), 1, false));
// Next `stopped` (all-threads or single-thread) overtakes the reply: no synthetic `continued`.
for next_all in [true, false] {
let s = Suspension::default();
s.stopped(Some(1), true);
let ticket = s.ticket();
s.stopped(Some(1), next_all);
assert!(!emit_if_resumed(&s, ticket, 1, false), "next_all={next_all}");
assert!(s.get());
}
// Adapter's own `continued` event already ended the stop: no duplicate synthetic `continued`.
let s = Suspension::default();
s.stopped(Some(1), true);
let ticket = s.ticket();
s.continued(Some(1), true);
assert!(!emit_if_resumed(&s, ticket, 1, true));
// Multi-thread: thread 7 steps while thread 9 stops alone -> thread 7 still emits `continued(all=false)`.
let s = two_threads_stopped();
let ticket = s.ticket();
s.stopped(Some(9), false);
assert!(emit_if_resumed(&s, ticket, 7, false));
assert!(s.get());
// Multi-thread: `continue(all=true)` while thread 9 stops alone -> suppressed so thread 9 stays paused.
let s = two_threads_stopped();
let ticket = s.ticket();
s.stopped(Some(9), false);
assert!(!emit_if_resumed(&s, ticket, 7, true));
assert!(s.get());
}
#[test]
fn concurrent_stop_and_resume_never_emit_continued_after_the_new_stop() {
for _ in 0..200 {
let s = std::sync::Arc::new(Suspension::default());
let log = std::sync::Arc::new(parking_lot::Mutex::new(Vec::<&'static str>::new()));
s.stopped(Some(1), true);
let ticket = s.ticket();
let s2 = s.clone();
let log2 = log.clone();
let stop = std::thread::spawn(move || {
s2.stopped(Some(1), false);
s2.emit_synced(|| log2.lock().push("stopped"));
});
s.resumed_and_emit(ticket, 1, false, || log.lock().push("continued"));
stop.join().unwrap();
let events = log.lock().clone();
assert!(events == ["continued", "stopped"] || events == ["stopped"], "unexpected order: {events:?}");
}
}
#[test]
fn kotlin_launch_starts_attach_listener_first() {
assert_eq!(
+7 -228
View File
@@ -1,6 +1,5 @@
//! Protocol flow against an in-memory fake adapter.
mod exception_classes;
mod jvm_inspect;
mod stream_trace;
@@ -157,11 +156,6 @@ struct Script {
breakpoints_after_continue: usize,
/// The `reason` of the stop a `next` ends with (`step` when unset; kotlin-lsp says `breakpoint`).
step_reason: Option<&'static str>,
/// Send `stopped` before answering `next` / `stepIn` / `stepOut` / `continue` (like php-debug
/// when Xdebug finishes a step before the DAP reply is handled).
stop_before_reply: bool,
/// Send `continued` before answering `next` / `continue`.
continued_before_reply: bool,
/// Refuse `next`, then stop at a breakpoint (one the program hit meanwhile).
refuse_next: bool,
/// Send `invalidated { areas: ["variables"] }` right after the first `stopped` event.
@@ -218,8 +212,6 @@ impl Default for Script {
refuse_continue: false,
breakpoints_after_continue: 0,
step_reason: None,
stop_before_reply: false,
continued_before_reply: false,
refuse_next: false,
invalidated_after_stop: false,
stop_during_threads: false,
@@ -421,19 +413,6 @@ async fn fake_adapter<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(stream
tokio::time::sleep(Duration::from_millis(50)).await;
send!(json!({"type": "event", "event": "stopped", "body": {"reason": "breakpoint", "threadId": 1}}));
}
"next" if script.stop_before_reply => {
let reason = script.step_reason.unwrap_or("step");
send!(json!({"type": "event", "event": "stopped", "body": {"reason": reason, "threadId": 1}}));
tokio::time::sleep(Duration::from_millis(50)).await;
ok!(msg, Value::Null);
}
"next" if script.continued_before_reply => {
send!(
json!({"type": "event", "event": "continued", "body": {"threadId": 1, "allThreadsContinued": false}})
);
tokio::time::sleep(Duration::from_millis(50)).await;
ok!(msg, Value::Null);
}
"next" => {
ok!(msg, Value::Null);
let reason = script.step_reason.unwrap_or("step");
@@ -526,29 +505,13 @@ async fn fake_adapter<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(stream
"scopes" => {
ok!(msg, json!({"scopes": [{"name": "Locals", "variablesReference": 100, "expensive": false}]}))
}
// 200 holds a lazy value (java-debug's toString(), js-debug's getters): asked for, its
// reference answers one nameless child with the value and the reference of its fields.
"variables" => match msg["arguments"]["variablesReference"].as_i64() {
Some(200) => ok!(
msg,
json!({"variables": [
{"name": "order", "value": "Order@7", "type": "Order", "variablesReference": 201,
"evaluateName": "order", "presentationHint": {"lazy": true}},
{"name": "n", "value": "2", "type": "int", "variablesReference": 0, "presentationHint": {"lazy": false}},
]})
),
Some(201) => ok!(
msg,
json!({"variables": [{"name": "", "value": "Order@7 \"Order(1)\"", "variablesReference": 202, "evaluateName": "order"}]})
),
_ => ok!(
msg,
json!({"variables": [
{"name": "x", "value": "1", "type": "int", "variablesReference": 0},
{"name": "req", "value": "{Req}", "type": "Req", "variablesReference": 101, "evaluateName": "req"},
]})
),
},
"variables" => ok!(
msg,
json!({"variables": [
{"name": "x", "value": "1", "type": "int", "variablesReference": 0},
{"name": "req", "value": "{Req}", "type": "Req", "variablesReference": 101, "evaluateName": "req"},
]})
),
"evaluate" => ok!(msg, json!({"result": "42", "type": "int", "variablesReference": 0})),
"completions" => ok!(
msg,
@@ -573,20 +536,6 @@ async fn fake_adapter<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(stream
"stepOut" if script.refuse_step_out => send!(
json!({"type": "response", "request_seq": msg["seq"], "command": "stepOut", "success": false, "message": "Thread is not suspended"})
),
"continue" if script.stop_before_reply => {
send!(
json!({"type": "event", "event": "stopped", "body": {"reason": "breakpoint", "threadId": 1, "allThreadsStopped": true}})
);
tokio::time::sleep(Duration::from_millis(50)).await;
ok!(msg, json!({"allThreadsContinued": true}));
}
"continue" if script.continued_before_reply => {
send!(
json!({"type": "event", "event": "continued", "body": {"threadId": 1, "allThreadsContinued": true}})
);
tokio::time::sleep(Duration::from_millis(50)).await;
ok!(msg, json!({"allThreadsContinued": true}));
}
"continue" if script.stop_after_continue => {
ok!(msg, json!({"allThreadsContinued": true}));
send!(
@@ -609,11 +558,6 @@ async fn fake_adapter<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(stream
send!(json!({"type": "event", "event": "stopped", "body": {"reason": reason, "threadId": thread}}));
}
}
"stepIn" | "stepOut" if script.stop_before_reply => {
send!(json!({"type": "event", "event": "stopped", "body": {"reason": "step", "threadId": 1}}));
tokio::time::sleep(Duration::from_millis(50)).await;
ok!(msg, Value::Null);
}
"stepIn" | "stepOut" | "pause" => ok!(msg, Value::Null),
"hotReload" => {
ok!(msg, Value::Null);
@@ -2076,7 +2020,6 @@ fn godot_registry(port: u16, command: &str, args: &[&str]) -> Arc<LanguageRegist
transport: "tcp".into(),
connect: Some(format!("127.0.0.1:{port}")),
install_hint: Some("Open the project in the Godot editor".into()),
resolve_lazy_variables: false,
pinned: None,
}),
};
@@ -2820,121 +2763,6 @@ async fn step_of_one_thread_keeps_the_others_suspended() {
assert_eq!(session.suspended.ticket(), ticket + 1);
h.manager.step_in_target(id, 7, 1).await.unwrap();
assert!(!session.suspended.get());
// The UI stays on a thread that is still stopped only when told the step ran one thread.
for thread in [7, 8] {
let continued =
h.wait_event(|e| matches!(e, DebugEvent::Continued { thread_id, .. } if *thread_id == thread)).await;
assert!(matches!(continued, DebugEvent::Continued { all_threads_continued: false, .. }), "{continued:?}");
}
}
/// When an adapter emits the next `stopped` event before replying to `next` / `stepIn` / `stepOut`
/// / `continue` (as php-debug / Xdebug can on fast steps), no trailing synthetic `continued` may
/// overwrite the new stop.
#[tokio::test]
async fn stop_before_reply_does_not_emit_trailing_continued() {
let h = harness(Script { stop_before_reply: true, ..Script::default() });
let id = h.start(config()).await.unwrap();
h.wait_event(|e| matches!(e, DebugEvent::Stopped { .. })).await;
let session = h.manager.session(id).unwrap();
let run_events = |from: usize| {
h.events
.lock()
.iter()
.skip(from)
.filter_map(|e| match e {
IdeEvent::Debug { event: DebugEvent::Stopped { reason, .. }, .. } => Some(format!("stopped:{reason}")),
IdeEvent::Debug { event: DebugEvent::Continued { .. }, .. } => Some("continued".into()),
_ => None,
})
.collect::<Vec<_>>()
};
for (label, expected) in [
("over", "stopped:step"),
("into", "stopped:step"),
("out", "stopped:step"),
("target", "stopped:step"),
("resume", "stopped:breakpoint"),
] {
let before = h.events.lock().len();
match label {
"over" => h.manager.step(id, 1, StepKind::Over).await.unwrap(),
"into" => h.manager.step(id, 1, StepKind::Into).await.unwrap(),
"out" => h.manager.step(id, 1, StepKind::Out).await.unwrap(),
"target" => h.manager.step_in_target(id, 1, 1).await.unwrap(),
"resume" => h.manager.resume(id, 1).await.unwrap(),
_ => unreachable!(),
}
assert!(session.suspended.get(), "{label}: session must remain suspended");
assert_eq!(run_events(before), [expected], "{label}: must not emit continued after stopped");
}
}
#[tokio::test]
async fn continued_event_before_reply_does_not_emit_duplicate_continued() {
for is_resume in [false, true] {
let h = harness(Script { continued_before_reply: true, ..Script::default() });
let id = h.start(config()).await.unwrap();
h.wait_event(|e| matches!(e, DebugEvent::Stopped { .. })).await;
let before = h.events.lock().len();
if is_resume {
h.manager.resume(id, 1).await.unwrap();
} else {
h.manager.step(id, 1, StepKind::Over).await.unwrap();
}
let continued = h
.events
.lock()
.iter()
.skip(before)
.filter(|e| matches!(e, IdeEvent::Debug { event: DebugEvent::Continued { .. }, .. }))
.count();
assert_eq!(continued, 1, "is_resume={is_resume}: adapter continued event already reported it");
}
}
#[tokio::test]
async fn lazy_variables_are_resolved_when_the_adapter_declares_them_safe() {
let h = harness(Script::default());
let id = h.start(java_config("launch")).await.unwrap();
h.wait_event(|e| matches!(e, DebugEvent::Stopped { .. })).await;
let vars = h.manager.variables(id, 200).await.unwrap();
let order = &vars[0];
assert_eq!(
(order.name.as_str(), order.value.as_str(), order.type_name.as_deref()),
("order", "Order@7 \"Order(1)\"", Some("Order"))
);
assert_eq!((order.variables_reference, order.lazy), (202, false));
assert_eq!(order.evaluate_name.as_deref(), Some("order"));
assert_eq!((vars[1].name.as_str(), vars[1].lazy), ("n", false));
}
#[tokio::test]
async fn lazy_variables_stay_lazy_for_other_adapters() {
let h = harness(Script::default());
let id = h.start(config()).await.unwrap();
h.wait_event(|e| matches!(e, DebugEvent::Stopped { .. })).await;
let vars = h.manager.variables(id, 200).await.unwrap();
assert_eq!((vars[0].value.as_str(), vars[0].variables_reference, vars[0].lazy), ("Order@7", 201, true));
assert_eq!(requests(&h, "variables").len(), 1, "nothing is computed until asked for");
let order = h.manager.resolve_variable(id, vars[0].clone()).await.unwrap();
assert_eq!((order.name.as_str(), order.value.as_str()), ("order", "Order@7 \"Order(1)\""));
assert_eq!((order.variables_reference, order.lazy), (202, false));
let n = h.manager.resolve_variable(id, vars[1].clone()).await.unwrap();
assert_eq!((n.value.as_str(), requests(&h, "variables").len()), ("2", 2), "only lazy values are computed");
}
#[test]
fn java_debug_declares_its_lazy_variables_safe_to_resolve() {
let languages = LanguageRegistry::load(None).unwrap();
for registry in [&languages, &LanguageRegistry::from_configs(Vec::new())] {
assert!(adapter::find_config(registry, "java-debug").unwrap().resolve_lazy_variables);
assert!(!adapter::find_config(registry, "js-debug").unwrap().resolve_lazy_variables);
}
}
#[tokio::test]
@@ -3074,55 +2902,6 @@ async fn local_attach_finds_its_jvm_before_the_debugger_connects() {
assert_eq!(session.jvm_pid.load(Ordering::Acquire), 4242);
}
/// Gradle bootRun Debug: the JVM has no attach listener, so the session never learns its pid. The
/// run's dump still goes through the session and, the program being stopped, signals nothing.
#[cfg(unix)]
#[tokio::test]
async fn a_run_dump_goes_through_the_session_attached_to_the_run() {
let h = harness(Script::default());
let project = tempfile::tempdir().unwrap();
let mut cfg = remote_attach("java-debug", project.path());
let mut extra: Value = serde_json::from_str(cfg.extra_json.as_deref().unwrap()).unwrap();
extra[RUN_LINK] = json!(7);
cfg.extra_json = Some(extra.to_string());
let id = h.start(cfg).await.unwrap();
h.wait_event(|e| matches!(e, DebugEvent::Stopped { .. })).await;
assert!(h.request("attach")["arguments"].get(RUN_LINK).is_none(), "IDE-side only");
let session = h.manager.session(id).unwrap();
assert_eq!((session.run, session.jvm_pid.load(Ordering::Acquire)), (Some(RunId(7)), 0));
// `sleep` stands in for the JVM: a SIGQUIT would end it.
let mut jvm = std::process::Command::new("sleep").arg("30").spawn().unwrap();
let pid = jvm.id();
assert_eq!(h.manager.jvm_session_of(RunId(7), pid).map(|s| s.id), Some(id));
assert!(h.manager.jvm_session_of(RunId(8), pid).is_none());
let dump = h.manager.debugged_jvm_thread_dump(RunId(7), pid).await.unwrap().unwrap();
let alive = jvm.try_wait().unwrap().is_none();
let _ = jvm.kill();
let _ = jvm.wait();
assert_eq!(
dump,
JvmThreadsResult::Unavailable {
reason: JvmThreadsUnavailable::Jvm { reason: JvmMemoryUnavailable::ListenerNotRunning }
}
);
assert!(alive, "the stopped JVM was signalled");
}
/// A run's Dump Threads reaches the session attached to the run's JVM, not the plain run path.
#[cfg(unix)]
#[tokio::test]
async fn a_run_jvm_is_found_by_the_session_attached_to_it() {
let h = harness(Script::default());
h.manager.set_jvm_finder(Arc::new(|port, _| (port == 5005).then_some(4242)));
let mut cfg = java_config("attach");
cfg.extra_json = Some(json!({"hostName": "127.0.0.1", "port": 5005}).to_string());
let id = h.start(cfg).await.unwrap();
assert_eq!(h.manager.jvm_session_of(RunId(1), 4242).map(|s| s.id), Some(id));
assert!(h.manager.jvm_session_of(RunId(1), 4243).is_none());
assert!(h.manager.debugged_jvm_thread_dump(RunId(1), 4243).await.is_none());
}
#[cfg(unix)]
#[tokio::test]
async fn local_attach_remembers_its_jdwp_port() {
@@ -1,154 +0,0 @@
//! Exception breakpoints on a chosen class, armed through a session's backend.
use super::*;
use ide_jvm_inspect::{ExceptionArmState, ExceptionClassBreakpoints, ExceptionClassSpec, InspectFuture, VmTarget};
/// The target, the list, and the DAP requests sent before it.
type ArmCall = (VmTarget, Vec<ExceptionClassSpec>, Vec<String>);
/// Records each list it is given with the DAP requests sent before it.
struct FakeArmer {
log: Log,
calls: Mutex<Vec<ArmCall>>,
}
impl FakeArmer {
fn new(h: &Harness) -> Arc<Self> {
Arc::new(Self { log: h.log.clone(), calls: Mutex::default() })
}
fn lists(&self) -> Vec<Vec<String>> {
self.calls.lock().iter().map(|(_, specs, _)| specs.iter().map(|s| s.class_name.clone()).collect()).collect()
}
/// The DAP requests sent before each call.
fn before(&self) -> Vec<Vec<String>> {
self.calls.lock().iter().map(|(_, _, sent)| sent.clone()).collect()
}
}
impl ExceptionClassBreakpoints for FakeArmer {
fn set<'a>(
&'a self,
target: &'a VmTarget,
breakpoints: &'a [ExceptionClassSpec],
) -> InspectFuture<'a, Vec<(String, ExceptionArmState)>> {
let sent = self
.log
.lock()
.iter()
.filter(|m| m["type"] == "request")
.map(|m| m["command"].as_str().unwrap().to_owned())
.collect();
self.calls.lock().push((target.clone(), breakpoints.to_vec(), sent));
let states = breakpoints.iter().map(|b| (b.id.clone(), ExceptionArmState::Armed)).collect();
Box::pin(async move { Ok(states) })
}
}
fn class_bp(id: &str, class_name: &str) -> ExceptionClassBreakpoint {
ExceptionClassBreakpoint {
id: id.into(),
class_name: class_name.into(),
caught: true,
uncaught: true,
enabled: true,
class_filters: vec![],
class_exclusion_filters: vec![],
}
}
/// A java-debug attach to a JVM on another machine: the target is known from the request alone.
fn attach() -> LaunchConfig {
LaunchConfig {
extra_json: Some(json!({"hostName": "10.0.0.5", "port": 5005}).to_string()),
..java_config("attach")
}
}
async fn start(h: &Harness, config: LaunchConfig, armer: &Arc<FakeArmer>) -> DebugSessionId {
let backend: Arc<dyn ExceptionClassBreakpoints> = armer.clone();
h.manager.start_with_exception_classes(config, h.owner.clone(), |_| None, Some(backend)).await.unwrap()
}
#[tokio::test]
async fn armed_after_the_exception_filters_and_before_configuration_done() {
let h = harness(Script::default());
let armer = FakeArmer::new(&h);
let filtered = ExceptionClassBreakpoint {
caught: false,
enabled: false,
class_filters: vec!["com.acme.*".into()],
class_exclusion_filters: vec!["*Test".into()],
..class_bp("b", "com.acme.Boom")
};
h.manager.set_exception_class_breakpoints(vec![class_bp("a", "java.lang.IllegalStateException"), filtered]).await;
start(&h, attach(), &armer).await;
assert_eq!(armer.before(), [["initialize", "attach", "setExceptionBreakpoints"]]);
let (target, specs, _) = armer.calls.lock()[0].clone();
assert_eq!((target.pid, target.attach_host.as_deref(), target.attach_port), (None, Some("10.0.0.5"), Some(5005)));
assert_eq!(
specs[1],
ExceptionClassSpec {
id: "b".into(),
class_name: "com.acme.Boom".into(),
caught: false,
uncaught: true,
enabled: false,
class_filters: vec!["com.acme.*".into()],
class_exclusion_filters: vec!["*Test".into()],
}
);
assert!(h.commands().contains(&"configurationDone".to_owned()));
}
#[tokio::test]
async fn armed_again_after_every_set_exception_breakpoints() {
let h = harness(Script::default());
let armer = FakeArmer::new(&h);
h.manager.set_exception_class_breakpoints(vec![class_bp("a", "com.acme.Boom")]).await;
start(&h, attach(), &armer).await;
h.manager.set_exception_breakpoints(BTreeMap::from([("raised".into(), true)])).await.unwrap();
assert_eq!(armer.lists(), [["com.acme.Boom"], ["com.acme.Boom"]]);
let last = armer.before().pop().unwrap();
assert_eq!(last.iter().filter(|c| *c == "setExceptionBreakpoints").count(), 2, "{last:?}");
}
#[tokio::test]
async fn a_new_list_reaches_the_sessions_that_take_it() {
let h = harness(Script::default());
let armer = FakeArmer::new(&h);
start(&h, attach(), &armer).await;
let other = h.start(attach()).await.unwrap();
assert!(armer.lists().is_empty(), "nothing to arm at start");
h.manager.set_exception_class_breakpoints(vec![class_bp("a", "com.acme.Boom")]).await;
h.manager.set_exception_class_breakpoints(vec![]).await;
assert_eq!(armer.lists(), [vec!["com.acme.Boom".to_owned()], vec![]], "an empty list takes them down");
let filters = h.manager.exception_filters(None);
let support = |id| filters.iter().find(|f| f.session == id).unwrap().classes.clone();
assert_eq!(support(other), None);
let java = filters.iter().find(|f| f.session != other).unwrap().session;
assert_eq!(
support(java),
Some(ExceptionClassSupport {
family: "java".into(),
condition: false,
class_filters: true,
catch_filters: false
})
);
}
#[tokio::test]
async fn nothing_is_sent_before_the_jvm_is_known() {
let h = harness(Script::default());
let armer = FakeArmer::new(&h);
h.manager.set_exception_class_breakpoints(vec![class_bp("a", "com.acme.Boom")]).await;
// The fake adapter sends no `process` event before `configurationDone`: no pid to name.
start(&h, java_config("launch"), &armer).await;
assert!(armer.lists().is_empty());
}
+2 -14
View File
@@ -17,7 +17,7 @@ specta.workspace = true
toml.workspace = true
toml_edit.workspace = true
blake3.workspace = true
tokio = { workspace = true, features = ["net"] }
tokio.workspace = true
tracing.workspace = true
parking_lot.workspace = true
notify.workspace = true
@@ -27,6 +27,7 @@ tiberius.workspace = true
oracledb.workspace = true
bb8.workspace = true
tokio-util = { workspace = true, features = ["compat"] }
dirs.workspace = true
ide-ssh.workspace = true
ide-http.workspace = true
reqwest = { workspace = true, features = ["query"] }
@@ -38,19 +39,6 @@ rsa = { version = "0.10.0-rc.18", features = ["sha2", "pkcs5"] }
zeroize = "1"
open = "5"
[target.'cfg(unix)'.dependencies]
libc = "0.2"
[target.'cfg(windows)'.dependencies]
windows-sys = { version = "0.61", features = [
"Win32_Foundation",
"Win32_NetworkManagement_IpHelper",
"Win32_Networking_WinSock",
"Win32_System_Diagnostics_ToolHelp",
"Win32_System_Threading",
"Win32_System_JobObjects",
] }
[dev-dependencies]
tokio = { workspace = true, features = ["rt-multi-thread", "macros", "net"] }
ide-ssh = { workspace = true, features = ["testing"] }
+72 -149
View File
@@ -145,38 +145,30 @@ impl ClickhousePool {
let cancel = CancellationToken::new();
let initialize = async {
if let Err(error) = pool.execute("SELECT 1", 1, &cancel).await {
let Some(setting) = rejected_driver_setting(&error) else {
if !rejects_driver_setting(&error) {
return Err(error);
};
}
if !use_http_session {
if setting == "readonly" {
return Err(error);
}
if !source.read_only {
return Err(IdeError::new(
error.kind,
format!(
"{}; enable Read-only for independent queries on a strict read-only server",
error.message
),
));
}
// Every request still sends readonly=1, regardless of which node answers.
pool.0.session.lock().await.strict_read_only = true;
pool.execute("SELECT 1", 1, &cancel).await?;
} else {
// Only rely on the server's write protection after proving strict read-only
// in this same named session.
{
let mut session = pool.0.session.lock().await;
// The rejected probe may have opened a session on a different node.
session.id = Some(uuid::Uuid::new_v4().to_string());
session.strict_read_only = true;
}
let result = pool.execute("SELECT getSetting('readonly')", 1, &cancel).await?;
if result.rows.first().and_then(|row| row.first()).and_then(Option::as_deref) != Some("1") {
return Err(error);
}
return Err(IdeError::new(
error.kind,
format!(
"{}; use_http_session=false requires per-request read-only and result-limit settings. Strict read-only fallback requires an HTTP session on one node or session affinity",
error.message
),
));
}
// Retry only the connection probe. Keep relying on the server for write protection
// only after verifying strict read-only mode in this same session.
{
let mut session = pool.0.session.lock().await;
// Start the proof in a fresh session: the rejected probe may have left
// its id on another replica without applying the configured database.
session.id = Some(uuid::Uuid::new_v4().to_string());
session.strict_read_only = true;
}
let result = pool.execute("SELECT getSetting('readonly')", 1, &cancel).await?;
if result.rows.first().and_then(|row| row.first()).and_then(Option::as_deref) != Some("1") {
return Err(error);
}
}
// The HTTP database parameter applies to one request. A named session needs
@@ -244,7 +236,7 @@ impl ClickhousePool {
if !self.0.database.is_empty() && (session.id.is_none() || !session.initialized) {
request = request.query(&[("database", &self.0.database)]);
}
if self.0.read_only && (session.id.is_none() || !session.strict_read_only) {
if self.0.read_only && !session.strict_read_only {
request = request.query(&[("readonly", "1")]);
}
request
@@ -316,7 +308,6 @@ impl ClickhousePool {
has_more,
elapsed_ms: started.elapsed().as_secs_f64() * 1000.0,
execution_ms,
truncated: Vec::new(),
})
};
let result = tokio::select! {
@@ -333,7 +324,7 @@ impl ClickhousePool {
result
}
None => {
let killed = self.kill(&client, &query_id, &session).await;
let killed = self.kill(&client, &query_id).await;
match killed {
Ok(()) => Err(IdeError::cancelled()),
Err(error) => Err(IdeError::new(
@@ -345,16 +336,15 @@ impl ClickhousePool {
}
}
async fn kill(&self, client: &Client, query_id: &str, session: &Session) -> IdeResult<()> {
let mut request = client
async fn kill(&self, client: &Client, query_id: &str) -> IdeResult<()> {
let response = client
.post(self.0.endpoint.clone())
.basic_auth(&self.0.user, Some(&self.0.password))
.timeout(Duration::from_secs(3));
if self.0.read_only && session.id.is_none() {
request = request.query(&[("readonly", "1")]);
}
let response =
request.body(format!("KILL QUERY WHERE query_id = '{query_id}' SYNC")).send().await.map_err(http_error)?;
.timeout(Duration::from_secs(3))
.body(format!("KILL QUERY WHERE query_id = '{query_id}' SYNC"))
.send()
.await
.map_err(http_error)?;
let status = response.status();
let code = response
.headers()
@@ -561,14 +551,13 @@ fn read_pem(path: &str, label: &str) -> IdeResult<Vec<u8>> {
.map_err(|error| IdeError::new(ErrorKind::Io, format!("cannot read ClickHouse {label}: {error}")))
}
fn rejected_driver_setting(error: &IdeError) -> Option<&str> {
fn rejects_driver_setting(error: &IdeError) -> bool {
error
.message
.split_once(": ")
.and_then(|(_, detail)| detail.strip_prefix("Code: 164. DB::Exception: Cannot modify '"))
.and_then(|detail| detail.split_once("' setting in readonly mode"))
.map(|(name, _)| name)
.filter(|&name| {
.is_some_and(|(name, _)| {
matches!(
name,
"output_format_json_quote_denormals" | "max_result_rows" | "result_overflow_mode" | "readonly"
@@ -964,77 +953,19 @@ mod tests {
}
#[tokio::test]
async fn strict_stateless_connections_keep_readonly_on_every_request() {
let denied = "Code: 164. DB::Exception: Cannot modify 'max_result_rows' setting in readonly mode. (READONLY)";
let (port, requests) = server(vec![
("500 Internal Server Error", "X-ClickHouse-Exception-Code: 164\r\n", denied),
("200 OK", "", ONE),
(
async fn stateless_connections_never_fall_back_to_session_readonly_proof() {
for read_only in [false, true] {
let (port, requests) = server(vec![(
"500 Internal Server Error",
"X-ClickHouse-Exception-Code: 164\r\n",
"Code: 164. DB::Exception: Cannot execute query in readonly mode. (READONLY)",
),
("200 OK", "", "[\"n\"]\n[\"UInt64\"]\n[0]\n[1]\n[2]\n"),
])
.await;
let source = DataSource {
database: "fixture_database".into(),
read_only: true,
properties: vec![property("use_http_session", "false"), property("max_threads", "2")],
..source(port)
};
let pool = Pool::connect(&source, None, None).await.unwrap();
let cancel = CancellationToken::new();
let write = "CREATE TABLE fixture_table (n UInt8) ENGINE=Memory";
assert!(pool.execute(write, 1, &cancel).await.unwrap_err().message.contains("Code: 164"));
let sql = "SELECT number AS n FROM numbers(3) LIMIT 3";
let result = pool.execute(sql, 1, &cancel).await.unwrap();
assert_eq!(result.rows, vec![vec![Some("0".into())]]);
assert!(result.has_more);
let requests = requests.await.unwrap();
assert!(requests[0].ends_with("SELECT 1"));
assert!(requests[1].ends_with("SELECT 1"));
assert!(requests[2].ends_with(write));
assert!(requests[3].ends_with(sql));
for (index, request) in requests.iter().enumerate() {
let url = request_url(request);
for name in ["session_id", "session_check", "session_timeout", "use_http_session"] {
assert_eq!(query_value(&url, name), None, "{name}");
}
assert_eq!(query_value(&url, "readonly").as_deref(), Some("1"));
assert_eq!(query_value(&url, "database").as_deref(), Some("fixture_database"));
assert_eq!(query_value(&url, "max_threads").as_deref(), Some("2"));
assert_eq!(query_value(&url, "max_result_rows").as_deref(), (index == 0).then_some("2"));
assert_eq!(query_value(&url, "result_overflow_mode").as_deref(), (index == 0).then_some("break"));
assert_eq!(query_value(&url, "output_format_json_quote_denormals").as_deref(), (index == 0).then_some("1"));
}
}
#[tokio::test]
async fn stateless_connections_require_readonly_and_only_relax_driver_result_settings() {
for (read_only, detail, body) in [
(
false,
"enable Read-only",
"Code: 164. DB::Exception: Cannot modify 'max_result_rows' setting in readonly mode. (READONLY)",
),
(
true,
"Cannot modify 'readonly'",
"Code: 164. DB::Exception: Cannot modify 'readonly' setting in readonly mode. (READONLY)",
),
(
true,
"Cannot modify 'max_threads'",
"Code: 164. DB::Exception: Cannot modify 'max_threads' setting in readonly mode. (READONLY)",
),
] {
let (port, requests) =
server(vec![("500 Internal Server Error", "X-ClickHouse-Exception-Code: 164\r\n", body)]).await;
)])
.await;
let source =
DataSource { read_only, properties: vec![property("use_http_session", "false")], ..source(port) };
let error = Pool::connect(&source, None, None).await.err().expect("stateless fallback must be rejected");
assert!(error.message.contains(detail), "{}", error.message);
assert!(error.message.contains("Cannot modify 'max_result_rows'"));
assert!(error.message.contains("use_http_session=false requires per-request"));
let requests = requests.await.unwrap();
assert_eq!(requests.len(), 1);
assert!(requests[0].ends_with("SELECT 1"));
@@ -1110,7 +1041,7 @@ mod tests {
let error = IdeError::invalid(format!(
"ClickHouse HTTP 500: Code: {code}. DB::Exception: Cannot modify '{setting}' setting in readonly mode. (READONLY)"
));
assert_eq!(rejected_driver_setting(&error).is_some(), expected, "{setting}");
assert_eq!(rejects_driver_setting(&error), expected, "{setting}");
}
}
@@ -1153,45 +1084,37 @@ mod tests {
#[tokio::test]
async fn cancellation_sends_kill_outside_the_busy_session() {
for stateless in [false, true] {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
let (started, received) = tokio::sync::oneshot::channel();
let server = tokio::spawn(async move {
let (mut health, _) = listener.accept().await.unwrap();
read_request(&mut health).await;
reply(&mut health, "200 OK", "", ONE).await;
drop(health);
let (mut query, _) = listener.accept().await.unwrap();
let request = read_request(&mut query).await;
started.send(()).unwrap();
let (mut kill, _) =
tokio::time::timeout(Duration::from_secs(5), listener.accept()).await.unwrap().unwrap();
let kill_request = read_request(&mut kill).await;
reply(&mut kill, "200 OK", "", "").await;
(request, kill_request)
});
let source = DataSource {
read_only: true,
properties: vec![property("use_http_session", if stateless { "false" } else { "true" })],
..source(port)
};
let pool = Pool::connect(&source, None, None).await.unwrap();
let cancel = CancellationToken::new();
let query = pool.execute("SELECT sleep(30)", 1, &cancel);
let cancelled = async {
received.await.unwrap();
cancel.cancel();
};
let (result, ()) = tokio::join!(query, cancelled);
assert_eq!(result.unwrap_err().kind, ErrorKind::Cancelled);
let (query, kill) = server.await.unwrap();
let query_id = query_value(&request_url(&query), "query_id").unwrap();
assert!(kill.ends_with(&format!("KILL QUERY WHERE query_id = '{query_id}' SYNC")));
let url = request_url(&kill);
assert_eq!(query_value(&url, "session_id"), None);
assert_eq!(query_value(&url, "readonly").as_deref(), stateless.then_some("1"));
}
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
let (started, received) = tokio::sync::oneshot::channel();
let server = tokio::spawn(async move {
let (mut health, _) = listener.accept().await.unwrap();
read_request(&mut health).await;
reply(&mut health, "200 OK", "", ONE).await;
drop(health);
let (mut query, _) = listener.accept().await.unwrap();
let request = read_request(&mut query).await;
started.send(()).unwrap();
let (mut kill, _) = tokio::time::timeout(Duration::from_secs(5), listener.accept()).await.unwrap().unwrap();
let kill_request = read_request(&mut kill).await;
reply(&mut kill, "200 OK", "", "").await;
(request, kill_request)
});
let pool = Pool::connect(&source(port), None, None).await.unwrap();
let cancel = CancellationToken::new();
let query = pool.execute("SELECT sleep(30)", 1, &cancel);
let cancelled = async {
received.await.unwrap();
cancel.cancel();
};
let (result, ()) = tokio::join!(query, cancelled);
assert_eq!(result.unwrap_err().kind, ErrorKind::Cancelled);
let (query, kill) = server.await.unwrap();
let target = query.lines().next().unwrap().split_whitespace().nth(1).unwrap();
let url = Url::parse(&format!("http://localhost{target}")).unwrap();
let query_id = url.query_pairs().find(|(k, _)| k == "query_id").unwrap().1.into_owned();
assert!(kill.ends_with(&format!("KILL QUERY WHERE query_id = '{query_id}' SYNC")));
assert!(!kill.contains("session_id="));
}
#[tokio::test]
+55 -349
View File
@@ -12,7 +12,7 @@ use ide_core::{CancellationToken, IdeError, IdeResult, error::ErrorKind};
use serde::{Deserialize, Serialize};
use specta::Type;
use sqlx::{
Column, ColumnIndex, ConnectOptions, Connection, Decode, Executor, Row, SqlSafeStr, Sqlite, TypeInfo, ValueRef,
Column, ColumnIndex, Connection, Decode, Executor, Row, SqlSafeStr, Sqlite, TypeInfo, ValueRef,
mysql::{MySqlConnectOptions, MySqlConnection, MySqlSslMode},
pool::PoolConnection,
postgres::{PgConnectOptions, PgConnection, PgSslMode},
@@ -48,65 +48,6 @@ pub struct QueryResult {
pub elapsed_ms: f64,
/// Until the server's first answer; the rest of `elapsed_ms` is fetching.
pub execution_ms: f64,
/// Cells of `rows` cut short by [`QueryResult::cap_cells`], in row order.
pub truncated: Vec<TruncatedCell>,
}
/// A cell of a [`QueryResult`] whose text was cut to a prefix.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
#[serde(rename = "DbTruncatedCell")]
pub struct TruncatedCell {
pub row: u32,
pub column: u32,
/// Length of the whole value in UTF-16 code units (what a JavaScript string counts).
pub length: u32,
/// FNV-1a (32 bits) of the whole value's UTF-16 code units, each taken as one 16-bit step,
/// so a client that reads the value again can tell whether it is the one that was cut.
pub hash: u32,
}
/// FNV-1a over UTF-16 code units, one step per unit (the same on the client: see `cutCells.ts`).
fn fnv1a_utf16(text: &str) -> u32 {
let mut hash: u32 = 0x811c_9dc5;
let mut pair = [0u16; 2];
for ch in text.chars() {
for unit in ch.encode_utf16(&mut pair) {
hash = (hash ^ u32::from(*unit)).wrapping_mul(0x0100_0193);
}
}
hash
}
impl QueryResult {
/// Cuts every cell longer than `limit` UTF-16 code units to its first `limit` (never inside a
/// surrogate pair) and lists it in `truncated`, so a page's size no longer depends on how
/// wide its values are. The full value is read again, one row at a time, when it is needed.
pub fn cap_cells(&mut self, limit: usize) {
for (r, row) in self.rows.iter_mut().enumerate() {
for (c, cell) in row.iter_mut().enumerate() {
let Some(text) = cell else { continue };
// A UTF-16 length never exceeds the UTF-8 one.
if text.len() <= limit {
continue;
}
let mut units = 0;
let mut cut = text.len();
for (at, ch) in text.char_indices() {
if units + ch.len_utf16() > limit && cut == text.len() {
cut = at;
}
units += ch.len_utf16();
}
if units <= limit {
continue;
}
let hash = fnv1a_utf16(text);
text.truncate(cut);
self.truncated.push(TruncatedCell { row: r as u32, column: c as u32, length: units as u32, hash });
}
}
}
}
/// Session context belongs to the physical connection, including across pool checkouts.
@@ -135,7 +76,7 @@ impl Context {
}
macro_rules! sqlx_pool {
($manager:ident, $handle:ident, $options:ty, $connection:ty, $driver:expr, $query:expr $(, $after_init:ident)?) => {
($manager:ident, $handle:ident, $options:ty, $connection:ty, $driver:expr, $query:expr) => {
pub struct $manager {
options: $options,
init: Arc<Vec<String>>,
@@ -170,7 +111,7 @@ macro_rules! sqlx_pool {
async fn connect(&self) -> Result<Self::Connection, Self::Error> {
tokio::time::timeout(self.timeout, async {
let mut conn = self.options.connect().await?;
let mut conn = <$connection>::connect_with(&self.options).await?;
let context_sql = |value: Option<String>| {
value.map(|v| {
if $driver == DbDriver::Postgres {
@@ -183,9 +124,6 @@ macro_rules! sqlx_pool {
for sql in self.init.iter() {
sqlx::raw_sql(sqlx::AssertSqlSafe(sql.clone())).execute(&mut conn).await?;
}
$(if !self.init.is_empty() {
self.options.$after_init(&mut conn).await?;
})?
let row = sqlx::raw_sql(sqlx::AssertSqlSafe($query.to_owned())).fetch_one(&mut conn).await?;
let context = Context::new(context_sql(row.try_get(0)?));
Ok($handle {
@@ -212,88 +150,7 @@ macro_rules! sqlx_pool {
};
}
#[derive(Clone)]
struct PostgresOptions {
connection: PgConnectOptions,
read_only: bool,
}
const PG_READ_ONLY_HINT: &str = "Read-only requires the pooler to track default_transaction_read_only for each client. \
For PgBouncer, check track_extra_parameters.";
impl PostgresOptions {
async fn connect(&self) -> Result<PgConnection, sqlx::Error> {
let mut conn = self.connection.connect().await?;
// A pooler can silently discard startup options. Check before giving the startup script a connection.
self.verify_read_only(&mut conn).await?;
Ok(conn)
}
async fn verify_read_only(&self, conn: &mut PgConnection) -> Result<(), sqlx::Error> {
if self.read_only && !pg_setting_on(conn, "SHOW default_transaction_read_only").await? {
return Err(sqlx::Error::Configuration(
format!(
"PostgreSQL did not enable the requested default_transaction_read_only setting. \
Check the Advanced properties and startup script. {PG_READ_ONLY_HINT}"
)
.into(),
));
}
Ok(())
}
async fn verify_startup_script(&self, conn: &mut PgConnection) -> Result<(), sqlx::Error> {
self.verify_read_only(conn).await?;
if self.read_only && !pg_setting_on(conn, "SHOW transaction_read_only").await? {
return Err(sqlx::Error::Configuration(
"The startup script left a writable transaction open on a read-only PostgreSQL source.".into(),
));
}
Ok(())
}
}
async fn pg_setting_on(conn: &mut PgConnection, show: &'static str) -> Result<bool, sqlx::Error> {
let row = sqlx::raw_sql(show).fetch_one(conn).await?;
Ok(row.try_get::<&str, _>(0)? == "on")
}
fn postgres_read_only_hint(read_only: bool, code: Option<&str>, message: &str) -> Option<&'static str> {
match (read_only, code, message) {
(
true,
Some("08P01"),
"unsupported startup parameter in options: default_transaction_read_only"
| "unsupported startup parameter: default_transaction_read_only",
) => Some(PG_READ_ONLY_HINT),
(true, Some("08P01"), "unsupported startup parameter: options") => Some(
"This endpoint rejects PostgreSQL startup options. Use an endpoint that supports and tracks \
default_transaction_read_only for each client.",
),
_ => None,
}
}
fn postgres_connect_error(error: sqlx::Error, read_only: bool) -> IdeError {
let hint =
error.as_database_error().and_then(|db| postgres_read_only_hint(read_only, db.code().as_deref(), db.message()));
let mut error = db_err(error);
if let Some(hint) = hint {
error.message.push_str(". ");
error.message.push_str(hint);
}
error
}
sqlx_pool!(
PgManager,
PgHandle,
PostgresOptions,
PgConnection,
DbDriver::Postgres,
"SHOW search_path",
verify_startup_script
);
sqlx_pool!(PgManager, PgHandle, PgConnectOptions, PgConnection, DbDriver::Postgres, "SHOW search_path");
sqlx_pool!(MysqlManager, MysqlHandle, MySqlConnectOptions, MySqlConnection, DbDriver::Mysql, "SELECT DATABASE()");
pub struct ServerPool<M: ManageConnection> {
@@ -629,86 +486,6 @@ fn result_columns<R: Row>(row: &R) -> Vec<ResultColumn> {
.collect()
}
/// How far a statement's stream has been read: the columns seen so far, and the row that
/// showed more were coming, which the next read starts with.
pub(crate) struct Reader<R> {
columns: Vec<ResultColumn>,
carry: Option<R>,
}
impl<R> Default for Reader<R> {
fn default() -> Self {
Self { columns: Vec::new(), carry: None }
}
}
#[cfg(test)]
thread_local! {
/// Rows pulled from statement streams on this thread (tests count what paging reads).
pub(crate) static ROWS_PULLED: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
}
/// Reads on from `stream`: past the next `skip` rows without decoding them, then keeping at
/// most `max` rows with their cells read as `mode`. `rows_affected` reads a command's count.
async fn drain<S, D, R>(
stream: &mut S,
reader: &mut Reader<R>,
skip: usize,
max: usize,
mode: Cells,
rows_affected: impl Fn(&D) -> u64,
) -> IdeResult<Fetched>
where
S: futures::Stream<Item = Result<sqlx::Either<D, R>, sqlx::Error>> + Unpin,
R: Row,
usize: ColumnIndex<R>,
String: sqlx::Type<R::Database>,
for<'r> String: Decode<'r, R::Database>,
for<'r> Vec<u8>: Decode<'r, R::Database>,
{
let mut rows: Vec<Vec<Option<String>>> = Vec::new();
let mut affected: Option<u64> = None;
let mut has_more = false;
let mut first: Option<Instant> = None;
let mut to_skip = skip;
loop {
let item = match reader.carry.take() {
Some(row) => Ok(sqlx::Either::Right(row)),
None => match stream.next().await {
Some(item) => {
#[cfg(test)]
if matches!(item, Ok(sqlx::Either::Right(_))) {
ROWS_PULLED.with(|n| n.set(n.get() + 1));
}
item
}
None => break,
},
};
first.get_or_insert_with(Instant::now);
match item {
Ok(sqlx::Either::Left(done)) => affected = Some(affected.unwrap_or(0) + rows_affected(&done)),
Ok(sqlx::Either::Right(row)) => {
if reader.columns.is_empty() {
reader.columns = result_columns(&row);
}
if to_skip > 0 {
to_skip -= 1;
continue;
}
if rows.len() >= max {
reader.carry = Some(row);
has_more = true;
break;
}
rows.push((0..row.len()).map(|i| cell(&row, i, mode)).collect());
}
Err(e) => return Err(db_err(e)),
}
}
Ok((reader.columns.clone(), rows, affected, has_more, first))
}
/// Streams the results of `$sql` on executor `$exec`, reading past the first `$skip`
/// rows without decoding them, then keeping at most `$max` rows with their cells read as `$mode`.
macro_rules! fetch {
@@ -716,8 +493,44 @@ macro_rules! fetch {
fetch!($exec, $sql, 0usize, $max, $mode)
};
($exec:expr, $sql:expr, $skip:expr, $max:expr, $mode:expr) => {{
use futures::StreamExt;
let mut stream = sqlx::raw_sql(sqlx::AssertSqlSafe($sql.to_owned())).fetch_many($exec);
drain(&mut stream, &mut Reader::default(), $skip, $max, $mode, |done| done.rows_affected()).await
let mut columns: Vec<ResultColumn> = Vec::new();
let mut rows: Vec<Vec<Option<String>>> = Vec::new();
let mut affected: Option<u64> = None;
let mut has_more = false;
let mut failure = None;
let mut first: Option<Instant> = None;
let mut to_skip: usize = $skip;
while let Some(item) = stream.next().await {
first.get_or_insert_with(Instant::now);
match item {
Ok(sqlx::Either::Left(done)) => affected = Some(affected.unwrap_or(0) + done.rows_affected()),
Ok(sqlx::Either::Right(row)) => {
if columns.is_empty() {
columns = result_columns(&row);
}
if to_skip > 0 {
to_skip -= 1;
continue;
}
if rows.len() >= $max {
has_more = true;
break;
}
rows.push((0..row.len()).map(|i| cell(&row, i, $mode)).collect());
}
Err(e) => {
failure = Some(db_err(e));
break;
}
}
}
drop(stream);
match failure {
Some(e) => Err(e),
None => Ok((columns, rows, affected, has_more, first)),
}
}};
}
@@ -773,31 +586,6 @@ macro_rules! backend_id {
}};
}
mod cursor;
pub(crate) use cursor::{Cursors, Key as CursorKey};
/// Whether the pages of `sql`'s result can be read by a cursor (see [`cursor`]): a query that
/// leaves the session as it was.
pub(crate) fn cursor_statement(sql: &str) -> bool {
looks_like_query(sql) && !context_may_change(sql)
}
/// A [`QueryResult`] of what `fetched` read of `sql`, run since `started`.
pub(crate) fn query_result(sql: &str, fetched: Fetched, started: Instant) -> QueryResult {
let (columns, rows, affected, has_more, first) = fetched;
let elapsed_ms = started.elapsed().as_secs_f64() * 1000.0;
QueryResult {
statement: sql.to_owned(),
affected: if columns.is_empty() { Some(affected.unwrap_or(0) as f64) } else { None },
columns,
rows,
has_more,
elapsed_ms,
execution_ms: first.map_or(elapsed_ms, |t| t.duration_since(started).as_secs_f64() * 1000.0),
truncated: Vec::new(),
}
}
// Session control, scripts and PostgreSQL set_config can invalidate the tracked context.
fn context_may_change(sql: &str) -> bool {
let text = sql.trim().trim_end_matches(';');
@@ -1064,18 +852,17 @@ impl Pool {
if let Some(n) = setup.statement_cache {
opts = opts.statement_cache_capacity(n);
}
let options = PostgresOptions { connection: opts, read_only: source.read_only };
let mut manager = PgManager { options, init: init.clone(), timeout };
let mut manager = PgManager { options: opts, init: init.clone(), timeout };
// Open once directly so authentication failures retain their database error.
let first = match manager.connect().await {
Err(e) if source.ssl == DbSslMode::Prefer && tls_failed(&e) => {
tracing::info!("TLS handshake failed, connecting without TLS (SSL mode Prefer): {e}");
manager.options.connection = manager.options.connection.clone().ssl_mode(PgSslMode::Disable);
manager.options = manager.options.clone().ssl_mode(PgSslMode::Disable);
manager.connect().await
}
first => first,
}
.map_err(|e| postgres_connect_error(e, source.read_only))?;
.map_err(db_err)?;
let pool = Bb8Pool::builder().max_size(MAX).connection_timeout(timeout).build_unchecked(manager);
let _ = pool.add(first);
Ok(Pool::Postgres(ServerPool { inner: pool, closed: AtomicBool::new(false) }))
@@ -1198,12 +985,6 @@ impl Pool {
}
}
/// Whether a later page of a result can be read from a cursor instead of by running the statement
/// again: the drivers whose rows stream from one connection that can wait for the next page.
pub(crate) fn keeps_cursors(&self) -> bool {
matches!(self, Pool::Sqlite(_) | Pool::Postgres(_) | Pool::Mysql(_))
}
/// Runs `sql` (no row limit beyond `max`), for introspection: cells are text (see [`Cells::Text`]).
pub async fn rows(&self, sql: &str, max: usize) -> IdeResult<Vec<Vec<Option<String>>>> {
if let Pool::Jdbc(p) = self {
@@ -1622,7 +1403,17 @@ impl Held {
Held::Clickhouse(_) | Held::Snowflake(..) => unreachable!(),
};
self.after_statement(sql);
Ok(query_result(sql, fetched, started))
let (columns, rows, affected, has_more, first) = fetched;
let elapsed_ms = started.elapsed().as_secs_f64() * 1000.0;
Ok(QueryResult {
statement: sql.to_owned(),
affected: if columns.is_empty() { Some(affected.unwrap_or(0) as f64) } else { None },
columns,
rows,
has_more,
elapsed_ms,
execution_ms: first.map_or(elapsed_ms, |t| t.duration_since(started).as_secs_f64() * 1000.0),
})
}
}
@@ -1648,91 +1439,6 @@ mod tests {
use super::*;
use crate::source::{DbOptions, DbProperty};
fn rows(cells: Vec<Vec<Option<String>>>) -> QueryResult {
query_result("select", (Vec::new(), cells, None, false, None), Instant::now())
}
#[test]
fn capping_cells_bounds_a_page_and_reports_the_whole_length() {
let wide = "x".repeat(1_000_000);
let mut r = rows(vec![vec![Some("short".into()), Some(wide.clone()), None], vec![Some(wide), None, None]]);
r.cap_cells(100);
let size: usize = r.rows.iter().flatten().flatten().map(String::len).sum();
assert_eq!(size, 5 + 100 + 100);
assert_eq!(
r.truncated,
[
TruncatedCell { row: 0, column: 1, length: 1_000_000, hash: fnv1a_utf16(&"x".repeat(1_000_000)) },
TruncatedCell { row: 1, column: 0, length: 1_000_000, hash: fnv1a_utf16(&"x".repeat(1_000_000)) }
]
);
assert_eq!(r.rows[0][0].as_deref(), Some("short"));
assert_eq!(r.rows[0][2], None);
}
#[test]
fn a_cut_cell_is_hashed_by_its_utf16_units() {
// Fixed values: the client (`cutCells.ts`) computes the same hash to recognise a value it reads again.
assert_eq!(fnv1a_utf16(""), 2_166_136_261);
assert_eq!(fnv1a_utf16("a"), 3_826_002_220);
assert_eq!(fnv1a_utf16("a😀b"), 2_412_414_209);
assert_eq!(fnv1a_utf16("日本語日本語"), 2_778_669_755);
assert_ne!(fnv1a_utf16(&"x".repeat(100)), fnv1a_utf16(&format!("{}y", "x".repeat(99))));
let mut r = rows(vec![vec![Some("a😀b".into())]]);
r.cap_cells(2);
assert_eq!(r.truncated[0].hash, 2_412_414_209);
}
#[test]
fn capping_cells_keeps_values_at_or_under_the_limit_whole() {
let mut r = rows(vec![vec![Some("abcd".into()), Some("😀😀".into()), Some("ééé".into())]]);
// 4 units, 4 units (two pairs), 3 units in 6 bytes.
r.cap_cells(4);
assert!(r.truncated.is_empty());
assert_eq!(r.rows[0][1].as_deref(), Some("😀😀"));
r.cap_cells(3);
assert_eq!(
r.truncated,
[
TruncatedCell { row: 0, column: 0, length: 4, hash: fnv1a_utf16("abcd") },
TruncatedCell { row: 0, column: 1, length: 4, hash: fnv1a_utf16("😀😀") }
]
);
assert_eq!(r.rows[0][2].as_deref(), Some("ééé"));
}
#[test]
fn capping_cells_never_splits_a_character_or_a_surrogate_pair() {
// "a😀b": units a=1, 😀=2, b=1. A cut inside the pair falls back to before it.
let mut r = rows(vec![vec![Some("a😀b".into()), Some("日本語日本語".into())]]);
r.cap_cells(2);
assert_eq!(r.rows[0][0].as_deref(), Some("a"));
assert_eq!(r.rows[0][1].as_deref(), Some("日本"));
assert_eq!(r.truncated[0].length, 4);
assert_eq!(r.truncated[1].length, 6);
// What is kept is a prefix of the whole value, measured in UTF-16 units.
for (cut, whole) in [(&r.rows[0][0], "a😀b"), (&r.rows[0][1], "日本語日本語")] {
assert!(whole.starts_with(cut.as_deref().unwrap()));
assert!(cut.as_deref().unwrap().encode_utf16().count() <= 2);
}
}
#[test]
fn postgres_read_only_guidance_identifies_what_the_pooler_rejected() {
let rejected = "unsupported startup parameter in options: default_transaction_read_only";
assert_eq!(postgres_read_only_hint(true, Some("08P01"), rejected), Some(PG_READ_ONLY_HINT));
let direct = "unsupported startup parameter: default_transaction_read_only";
assert_eq!(postgres_read_only_hint(true, Some("08P01"), direct), Some(PG_READ_ONLY_HINT));
let options = postgres_read_only_hint(true, Some("08P01"), "unsupported startup parameter: options").unwrap();
assert!(options.contains("rejects PostgreSQL startup options"));
assert_eq!(postgres_read_only_hint(false, Some("08P01"), rejected), None);
assert_eq!(postgres_read_only_hint(true, Some("28P01"), rejected), None);
assert_eq!(
postgres_read_only_hint(true, Some("08P01"), "unsupported startup parameter: extra_float_digits"),
None
);
}
#[test]
fn prefer_retries_without_tls_only_after_a_failed_handshake() {
use std::io;
-474
View File
@@ -1,474 +0,0 @@
//! Result paging that reads on from where the previous page stopped.
//!
//! A statement has no way to start at row N: its server sends the rows before it, and a
//! page that re-runs the query reads and drops all of them. The page after another one
//! continues the same stream instead, so paging forward costs one page per click.
//!
//! A cursor keeps its statement's stream, and so its connection, open, which holds
//! server resources (locks, a snapshot) for as long as it lives. That is bounded:
//! one cursor per target, a few overall, each closed after [`IDLE`] without a page, when
//! its tab is closed or its target disconnects, and before a statement that is not a
//! query runs on its target. A page that finds no cursor at its position (jumping
//! to another page, going back, a closed cursor) starts a new one.
use super::{Cells, Fetched, Held, Pool, Reader, drain, looks_like_query, statement_columns};
use ide_core::{CancellationToken, IdeError, IdeResult, error::ErrorKind};
use parking_lot::Mutex;
use sqlx::{Executor, SqlSafeStr};
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::{mpsc, oneshot};
/// How long a cursor waits for its next page.
const IDLE: Duration = Duration::from_secs(30);
/// Cursors kept at once, over all targets (each holds a connection).
const MAX_CURSORS: usize = 4;
/// What a cursor reads the pages of: one statement of one target, in a schema context.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Key {
target: String,
statement: String,
schema: Option<String>,
}
impl Key {
pub(crate) fn new(target: &str, statement: &str, schema: Option<&str>) -> Self {
Self {
target: target.to_owned(),
statement: statement.to_owned(),
schema: schema.filter(|s| !s.is_empty()).map(str::to_owned),
}
}
}
/// A request for the next rows of a cursor's statement.
struct Read {
skip: usize,
max: usize,
cancel: CancellationToken,
reply: oneshot::Sender<IdeResult<Fetched>>,
}
/// A live cursor: where its stream stands, and the channel to the task that owns it.
struct Slot {
id: u64,
key: Key,
/// The number of rows read from the start of the statement (skipped or returned).
next: usize,
/// A page is being read from it: it stays registered meanwhile, so a release finds it.
busy: bool,
reads: mpsc::Sender<Read>,
}
/// Reads `max` rows after the first `skip` of a cursor's stream through `reads`; `None` when the cursor is gone.
async fn read(
reads: &mpsc::Sender<Read>,
skip: usize,
max: usize,
cancel: &CancellationToken,
) -> Option<IdeResult<Fetched>> {
let (reply, answer) = oneshot::channel();
reads.send(Read { skip, max, cancel: cancel.clone(), reply }).await.ok()?;
answer.await.ok()
}
#[derive(Default)]
struct Registry {
/// Oldest first.
slots: Vec<Slot>,
issued: u64,
}
#[derive(Default)]
pub(crate) struct Cursors {
registry: Mutex<Registry>,
}
impl Cursors {
/// The page at `skip` read from the cursor of `key` that stands there; `None` when
/// there is none (the caller starts one) or it failed (a lost connection: the caller
/// runs the statement again and reports whatever that returns).
pub(crate) async fn resume(
&self,
key: &Key,
skip: usize,
max: usize,
cancel: &CancellationToken,
) -> Option<IdeResult<Fetched>> {
let (id, reads) = {
let mut registry = self.registry.lock();
let slot = registry
.slots
.iter_mut()
.find(|s| s.key == *key && s.next == skip && !s.busy && !s.reads.is_closed())?;
slot.busy = true;
(slot.id, slot.reads.clone())
};
match read(&reads, 0, max, cancel).await {
Some(Ok(fetched)) => {
self.finish(id, &fetched);
Some(Ok(fetched))
}
Some(Err(e)) if e.kind == ErrorKind::Cancelled => {
self.close(id);
Some(Err(e))
}
_ => {
self.close(id);
None
}
}
}
/// Runs the statement of `key` on `held`, returns the page at `skip` and keeps the
/// statement's stream for the page after it. `held` is taken out of `pool` (its
/// context applied); `pool` stops the statement on the server when `cancel` fires.
pub(crate) async fn start(
&self,
held: Held,
pool: Arc<Pool>,
key: Key,
skip: usize,
max: usize,
cancel: &CancellationToken,
) -> IdeResult<Fetched> {
let (reads, requests) = mpsc::channel(1);
tokio::spawn(serve(held, pool, key.statement.clone(), requests));
let id = self.register(key, skip, reads.clone());
let fetched = match read(&reads, skip, max, cancel).await {
Some(Ok(fetched)) => fetched,
other => {
self.close(id);
return other.unwrap_or_else(|| Err(IdeError::internal("the statement stopped before it answered")));
}
};
self.finish(id, &fetched);
Ok(fetched)
}
/// Registers a cursor that is reading its first page. A target keeps one cursor (its
/// connection pool is small), and all together are bounded.
fn register(&self, key: Key, next: usize, reads: mpsc::Sender<Read>) -> u64 {
let mut registry = self.registry.lock();
registry.issued += 1;
let id = registry.issued;
registry.slots.retain(|s| s.key.target != key.target && !s.reads.is_closed());
registry.slots.push(Slot { id, key, next, busy: true, reads });
if registry.slots.len() > MAX_CURSORS {
registry.slots.remove(0);
}
id
}
/// Ready for the page after `fetched`, which cursor `id` just read, when more rows are waiting in its
/// stream; closed otherwise. A cursor released meanwhile is gone from the registry: the caller's
/// handle on its channel is the last, so the statement stops.
fn finish(&self, id: u64, fetched: &Fetched) {
let mut registry = self.registry.lock();
let Some(at) = registry.slots.iter().position(|s| s.id == id) else { return };
if fetched.3 {
let slot = &mut registry.slots[at];
slot.next += fetched.1.len();
slot.busy = false;
} else {
registry.slots.remove(at);
}
}
fn close(&self, id: u64) {
self.registry.lock().slots.retain(|s| s.id != id);
}
/// Closes the cursor of one statement of `target` (its result tab was closed), also when it is reading a page.
pub(crate) fn release(&self, key: &Key) {
self.registry.lock().slots.retain(|s| s.key != *key);
}
/// Closes the cursors of `target`: it disconnects, or a statement that changes
/// data or schema is about to run there.
pub(crate) fn release_target(&self, target: &str) {
self.registry.lock().slots.retain(|s| s.key.target != target);
}
}
/// Owns `held` and the stream of `sql` on it, answering reads until the stream ends,
/// nobody asks for [`IDLE`], or it is released (its channel closes).
async fn serve(mut held: Held, pool: Arc<Pool>, sql: String, mut reads: mpsc::Receiver<Read>) {
let Some(first) = reads.recv().await else { return held.discard().await };
// `$id`: the query naming the server process, `$kill`: how another connection stops it.
// Evaluates to whether the connection can go back to its pool (the stream was read to
// its end); otherwise it is closed rather than left to be drained.
macro_rules! serve {
($conn:expr, $id:expr, $kill:expr) => {{
let backend = match $id {
Some(q) => backend_id!(&mut **$conn, q),
None => None,
};
let mut stream = sqlx::raw_sql(sqlx::AssertSqlSafe(sql.clone())).fetch_many(&mut **$conn);
let mut reader = Reader::default();
let mut request = Some(first);
let mut last = None;
let mut reusable = false;
while let Some(Read { skip, max, cancel, reply }) = request.take() {
let read = tokio::select! {
r = drain(&mut stream, &mut reader, skip, max, Cells::Display, |done| done.rows_affected()) => r,
() = cancel.cancelled() => Err(IdeError::cancelled()),
};
if cancel.is_cancelled() {
if let Some(b) = backend {
let _ = pool.rows(&$kill(b), 1).await;
}
let _ = reply.send(Err(IdeError::cancelled()));
break;
}
match read {
Ok(fetched) if fetched.3 => {
if reply.send(Ok(fetched)).is_err() {
break;
}
request = tokio::time::timeout(IDLE, reads.recv()).await.unwrap_or(None);
}
Ok(fetched) => {
last = Some((reply, fetched));
reusable = true;
break;
}
Err(e) => {
let _ = reply.send(Err(e));
reusable = true;
break;
}
}
}
drop(stream);
if let Some((reply, mut fetched)) = last {
if fetched.0.is_empty() && looks_like_query(&sql) {
fetched.0 = (&mut **$conn)
.prepare(sqlx::AssertSqlSafe(sql.clone()).into_sql_str())
.await
.map(|s| statement_columns(&s))
.unwrap_or_default();
}
let _ = reply.send(Ok(fetched));
}
reusable
}};
}
let reusable = match &mut held {
Held::Sqlite(c) => serve!(c, None::<&str>, |_: String| String::new()),
Held::Postgres(c) => {
serve!(&mut ***c, Some("SELECT pg_backend_pid()"), |b: String| format!("SELECT pg_cancel_backend({b})"))
}
Held::Mysql(c) => serve!(&mut ***c, Some("SELECT CONNECTION_ID()"), |b: String| format!("KILL QUERY {b}")),
_ => unreachable!("only the sqlx drivers keep cursors"),
};
if !reusable {
held.discard().await;
}
}
#[cfg(test)]
mod tests {
use super::super::ROWS_PULLED;
use crate::{DataSource, DbDriver, DbManager};
use ide_core::{CancellationToken, error::ErrorKind};
const PAGE: usize = 100;
const ROWS: usize = 1000;
/// A SQLite data source `s1` with a table `t` of `ROWS` rows (`id` 1..=ROWS).
async fn manager() -> (tempfile::TempDir, DbManager) {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().to_path_buf();
std::fs::File::create(root.join("app.db")).unwrap();
let ssh = std::sync::Arc::new(ide_ssh::SshManager::new(root.join("ssh-passwords.json")));
let db = DbManager::new(root.clone(), root.join("passwords.json"), root.join("history.json"), ssh);
db.save_sources(vec![DataSource {
id: "s1".into(),
name: "app".into(),
driver: DbDriver::Sqlite,
file: Some("app.db".into()),
..Default::default()
}])
.await
.unwrap();
let cancel = CancellationToken::new();
db.execute("s1", "CREATE TABLE t (id INTEGER PRIMARY KEY, name TEXT)", 0, &cancel).await.unwrap();
db.execute(
"s1",
&format!(
"WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < {ROWS}) \
INSERT INTO t SELECT i, 'row ' || i FROM n"
),
0,
&cancel,
)
.await
.unwrap();
(tmp, db)
}
const QUERY: &str = "SELECT id, name FROM t ORDER BY id";
/// The ids of page `page` of `QUERY`, and whether more rows follow.
async fn page(db: &DbManager, statement: &str, page: usize) -> (Vec<i64>, bool) {
let r = db.execute_from("s1", statement, page * PAGE, PAGE, &CancellationToken::new(), None).await.unwrap();
(r.rows.iter().map(|row| row[0].as_deref().unwrap().parse().unwrap()).collect(), r.has_more)
}
fn ids(page: usize) -> Vec<i64> {
((page * PAGE + 1) as i64..=((page + 1) * PAGE) as i64).collect()
}
fn pulled() -> u64 {
ROWS_PULLED.with(std::cell::Cell::get)
}
#[tokio::test]
async fn paging_forward_reads_each_row_once() {
let (_tmp, db) = manager().await;
let before = pulled();
for p in 0..ROWS / PAGE {
let (rows, has_more) = page(&db, QUERY, p).await;
assert_eq!(rows, ids(p), "page {p}");
assert_eq!(has_more, p + 1 < ROWS / PAGE, "page {p} has_more");
}
// Running the query again for every page reads 1+2+…+10 pages (5500 rows); one pass reads ~1000.
assert!(pulled() - before < 2 * ROWS as u64, "read {} rows", pulled() - before);
}
#[tokio::test]
async fn jumping_and_going_back_return_the_right_pages() {
let (_tmp, db) = manager().await;
for p in [5, 6, 2, 3, 9, 0, 1, 7, 7, 8] {
assert_eq!(page(&db, QUERY, p).await.0, ids(p), "page {p}");
}
}
#[tokio::test]
async fn reading_a_row_leaves_the_cursor_of_the_pages_alone() {
let (_tmp, db) = manager().await;
page(&db, QUERY, 1).await;
let row = db.read_row("s1", QUERY, 350, &CancellationToken::new(), None).await.unwrap();
assert_eq!(row.rows, [[Some("351".to_owned()), Some("row 351".to_owned())]]);
assert_eq!(db.cursors.registry.lock().slots.len(), 1);
// The next page still continues the cursor: it reads one page, not 200 rows again.
let before = pulled();
assert_eq!(page(&db, QUERY, 2).await.0, ids(2));
assert!(pulled() - before <= PAGE as u64 + 1, "read {} rows", pulled() - before);
}
#[tokio::test]
async fn pages_past_the_end_are_empty() {
let (_tmp, db) = manager().await;
page(&db, QUERY, 8).await;
let r = db.execute_from("s1", QUERY, 2 * ROWS, PAGE, &CancellationToken::new(), None).await.unwrap();
assert!(r.rows.is_empty() && !r.has_more);
// The columns of an empty page still come from the statement.
assert_eq!(r.columns.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(), ["id", "name"]);
}
#[tokio::test]
async fn another_statement_does_not_continue_a_cursor() {
let (_tmp, db) = manager().await;
page(&db, QUERY, 1).await;
let other = "SELECT id, name FROM t ORDER BY id DESC";
let r = db.execute_from("s1", other, 2 * PAGE, PAGE, &CancellationToken::new(), None).await.unwrap();
let first: i64 = r.rows[0][0].as_deref().unwrap().parse().unwrap();
assert_eq!(first, (ROWS - 2 * PAGE) as i64);
}
#[tokio::test]
async fn a_statement_that_changes_data_closes_the_cursor() {
let (_tmp, db) = manager().await;
page(&db, QUERY, 1).await;
assert_eq!(db.cursors.registry.lock().slots.len(), 1);
db.execute("s1", "DELETE FROM t WHERE id = 150", 0, &CancellationToken::new()).await.unwrap();
assert_eq!(db.cursors.registry.lock().slots.len(), 0);
// The next page shows the change: row 150 is gone, so page 2 starts at 202.
assert_eq!(page(&db, QUERY, 2).await.0[0], 202);
}
#[tokio::test]
async fn releasing_and_abandoning_cursors_gives_their_connections_back() {
let (_tmp, db) = manager().await;
// The pool has 4 connections: a leak would starve `execute` after a few rounds.
for _ in 0..8 {
page(&db, QUERY, 1).await;
db.release_result("s1", QUERY, None);
assert_eq!(db.cursors.registry.lock().slots.len(), 0);
assert_eq!(page(&db, "SELECT count(*) FROM t", 0).await.0, [ROWS as i64]);
}
// Finishing a result also frees its connection.
for _ in 0..8 {
for p in 1..ROWS / PAGE {
page(&db, QUERY, p).await;
}
}
assert_eq!(db.cursors.registry.lock().slots.len(), 0);
}
#[tokio::test]
async fn a_cancelled_page_closes_its_cursor() {
let (_tmp, db) = manager().await;
page(&db, QUERY, 1).await;
let cancel = CancellationToken::new();
cancel.cancel();
let e = db.execute_from("s1", QUERY, 2 * PAGE, PAGE, &cancel, None).await.unwrap_err();
assert_eq!(e.kind, ErrorKind::Cancelled);
assert_eq!(db.cursors.registry.lock().slots.len(), 0);
assert_eq!(page(&db, QUERY, 2).await.0, ids(2));
}
/// A closed result tab releases its cursor even when a page is being read from it: the
/// cursor is not put back afterwards and its statement stops.
#[tokio::test]
async fn releasing_a_cursor_in_the_middle_of_a_page_read_closes_it() {
use super::{Cursors, Key, Read};
use std::sync::Arc;
use tokio::sync::{Notify, mpsc};
let cursors = Arc::new(Cursors::default());
let key = Key::new("s1", QUERY, None);
let (reads, mut requests) = mpsc::channel::<Read>(1);
cursors.register(key.clone(), 0, reads.clone());
let page = || (Vec::new(), vec![vec![Some("1".to_owned())]], None, true, None);
cursors.finish(1, &page());
drop(reads);
let in_read = Arc::new(Notify::new());
let (release, announced) = (Arc::new(Notify::new()), in_read.clone());
let server = tokio::spawn({
let release = release.clone();
async move {
let read = requests.recv().await.unwrap();
announced.notify_one();
release.notified().await;
let _ = read.reply.send(Ok(page()));
// The channel closes once nobody holds a handle on it.
requests.recv().await.is_none()
}
});
let resumed = tokio::spawn({
let (cursors, key) = (cursors.clone(), key.clone());
async move { cursors.resume(&key, 1, 1, &CancellationToken::new()).await.is_some() }
});
in_read.notified().await;
cursors.release(&key);
release.notify_one();
assert!(resumed.await.unwrap(), "the page that was being read is still returned");
assert!(cursors.registry.lock().slots.is_empty(), "the released cursor is not put back");
assert!(server.await.unwrap(), "the statement's task sees its channel close");
}
#[tokio::test]
async fn a_target_keeps_one_cursor_and_all_are_bounded() {
let (_tmp, db) = manager().await;
page(&db, QUERY, 1).await;
page(&db, "SELECT id, name FROM t WHERE id > 0 ORDER BY id", 1).await;
assert_eq!(db.cursors.registry.lock().slots.len(), 1);
// The first statement's cursor is gone: its next page is read again, and still right.
assert_eq!(page(&db, QUERY, 2).await.0, ids(2));
}
}
-436
View File
@@ -1,436 +0,0 @@
//! An approved foreground helper behind a loopback relay owned by the IDE.
use crate::DbExternalTunnel;
use ide_core::{IdeError, IdeResult, error::ErrorKind, process};
use parking_lot::Mutex;
use std::io;
use std::net::{IpAddr, Ipv4Addr, SocketAddr, SocketAddrV4};
use std::path::Path;
use std::process::{Child, Command, Stdio};
use std::sync::{Arc, Weak};
use std::time::Duration;
use tokio::net::{TcpListener, TcpSocket, TcpStream};
use tokio::sync::Semaphore;
use tokio::task::{JoinHandle, JoinSet};
#[cfg(target_os = "linux")]
#[path = "external_tunnel/linux.rs"]
mod platform;
#[cfg(target_os = "macos")]
#[path = "external_tunnel/macos.rs"]
mod platform;
#[cfg(windows)]
#[path = "external_tunnel/windows.rs"]
mod platform;
#[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
mod platform {
use super::*;
pub(super) async fn owns_socket(_: &Arc<Helper>, _: SocketAddr, _: Option<SocketAddr>) -> io::Result<bool> {
Err(io::Error::new(io::ErrorKind::Unsupported, "socket ownership cannot be verified on this OS"))
}
}
const STARTUP_TIMEOUT: Duration = Duration::from_secs(30);
const CONNECTION_TIMEOUT: Duration = Duration::from_secs(3);
const POLL_INTERVAL: Duration = Duration::from_millis(100);
const MAX_CONNECTIONS: usize = 128;
static VERIFICATION_SLOTS: Semaphore = Semaphore::const_new(8);
static HELPERS: Mutex<ActiveHelpers> = Mutex::new(ActiveHelpers { stopping: false, children: Vec::new() });
struct ActiveHelpers {
stopping: bool,
children: Vec<Weak<Helper>>,
}
/// Stop the IDE's external TCP tunnel processes before desktop exit or restart.
pub fn stop_external_tunnels_on_exit() {
let children = {
let mut active = HELPERS.lock();
active.stopping = true;
std::mem::take(&mut active.children)
};
for helper in children.into_iter().filter_map(|child| child.upgrade()) {
helper.stop();
}
}
pub(super) struct ExternalTunnel {
port: u16,
// Keep the address reserved even after the helper exits, until the last route reference drops.
_listener: Arc<TcpListener>,
helper: Weak<Helper>,
task: JoinHandle<()>,
}
impl ExternalTunnel {
pub(super) fn validate(config: &DbExternalTunnel, target: (&str, u16)) -> IdeResult<()> {
helper_target(config, target).map(|_| ())
}
pub(super) async fn open(config: &DbExternalTunnel, target: (&str, u16)) -> IdeResult<Self> {
if !cfg!(any(target_os = "linux", target_os = "macos", windows)) {
return Err(IdeError::unavailable("External TCP tunnel socket ownership cannot be verified on this OS"));
}
let listener = Arc::new(loopback_socket()?.listen(128)?);
let port = listener.local_addr()?.port();
let reservation = loopback_socket()?;
let endpoint = reservation.local_addr()?;
let arguments = helper_arguments(config, target, endpoint.port())?;
drop(reservation);
let helper = launch_helper(Path::new(&config.executable), &arguments)?;
let ready = tokio::time::timeout(STARTUP_TIMEOUT, async {
loop {
if !helper.is_alive() {
return Err(IdeError::new(
ErrorKind::Io,
"The external TCP tunnel helper exited before opening its loopback listener. \
Check the helper command in a terminal.",
));
}
if verify_socket(&helper, endpoint, None).await.map_err(|error| {
IdeError::new(ErrorKind::Io, format!("Could not verify the external TCP tunnel listener: {error}"))
})? {
return Ok(());
}
tokio::time::sleep(POLL_INTERVAL).await;
}
})
.await;
ready.map_err(|_| {
IdeError::new(
ErrorKind::Io,
format!(
"The external TCP tunnel helper did not open an owned listener at {endpoint} before the startup timeout. \
Check that the command binds to 127.0.0.1 and uses {{localPort}}."
),
)
})??;
let watched_helper = Arc::downgrade(&helper);
let task = tokio::spawn(relay(Arc::clone(&listener), endpoint, helper));
Ok(Self { port, _listener: listener, helper: watched_helper, task })
}
pub(super) fn port(&self) -> u16 {
self.port
}
pub(super) fn is_closed(&self) -> bool {
self.task.is_finished() || self.helper.upgrade().is_none_or(|helper| !helper.is_alive())
}
}
impl Drop for ExternalTunnel {
fn drop(&mut self) {
self.task.abort();
}
}
fn loopback_socket() -> io::Result<TcpSocket> {
let socket = TcpSocket::new_v4()?;
#[cfg(windows)]
platform::make_exclusive(&socket)?;
socket.bind(SocketAddrV4::new(Ipv4Addr::LOCALHOST, 0).into())?;
Ok(socket)
}
fn helper_target<'a>(config: &DbExternalTunnel, (host, port): (&'a str, u16)) -> IdeResult<(&'a str, u16)> {
let executable = Path::new(&config.executable);
if !executable.is_absolute() || executable.file_name().is_none() || config.executable.contains('\0') {
return Err(IdeError::invalid("Choose an absolute path to the external TCP tunnel executable"));
}
#[cfg(windows)]
if !executable.extension().is_some_and(|extension| extension.eq_ignore_ascii_case("exe")) {
return Err(IdeError::invalid("Choose an .exe file for the external TCP tunnel"));
}
let host = host.trim();
let host = host
.strip_prefix('[')
.and_then(|host| host.strip_suffix(']'))
.filter(|host| host.parse::<std::net::Ipv6Addr>().is_ok())
.unwrap_or(host);
let dns = host.strip_suffix('.').unwrap_or(host);
if host.parse::<IpAddr>().is_err()
&& (dns.len() > 253
|| !dns.split('.').all(|label| {
let bytes = label.as_bytes();
bytes.len() <= 63
&& bytes.first().is_some_and(u8::is_ascii_alphanumeric)
&& bytes.last().is_some_and(u8::is_ascii_alphanumeric)
&& bytes.iter().all(|byte| byte.is_ascii_alphanumeric() || *byte == b'-')
}))
{
return Err(IdeError::invalid("Enter a DNS name or IP address for the external TCP tunnel"));
}
if port == 0 {
return Err(IdeError::invalid("Enter a valid destination port for the external TCP tunnel"));
}
if !config.arguments.iter().any(|arg| arg.contains("{localPort}")) {
return Err(IdeError::invalid("Include {localPort} in the external TCP tunnel arguments"));
}
if config.arguments.iter().any(|arg| arg.contains('\0')) {
return Err(IdeError::invalid("External TCP tunnel arguments cannot contain NUL characters"));
}
Ok((host, port))
}
fn helper_arguments(config: &DbExternalTunnel, target: (&str, u16), local_port: u16) -> IdeResult<Vec<String>> {
let (host, port) = helper_target(config, target)?;
let target = if host.contains(':') { format!("[{host}]:{port}") } else { format!("{host}:{port}") };
let (local_port, port) = (local_port.to_string(), port.to_string());
let placeholders =
[("{host}:{port}", target.as_str()), ("{localPort}", &local_port), ("{host}", host), ("{port}", &port)];
Ok(config
.arguments
.iter()
.map(|arg| {
let mut remaining = arg.as_str();
let mut expanded = String::with_capacity(arg.len());
while let Some(start) = remaining.find('{') {
expanded.push_str(&remaining[..start]);
remaining = &remaining[start..];
if let Some((value, tail)) = placeholders
.into_iter()
.find_map(|(key, value)| remaining.strip_prefix(key).map(|tail| (value, tail)))
{
expanded.push_str(value);
remaining = tail;
} else {
expanded.push('{');
remaining = &remaining[1..];
}
}
expanded.push_str(remaining);
expanded
})
.collect())
}
fn launch_helper(executable: &Path, arguments: &[String]) -> IdeResult<Arc<Helper>> {
let mut active = HELPERS.lock();
if active.stopping {
return Err(IdeError::cancelled());
}
let helper = Arc::new(Helper::spawn(executable, arguments).map_err(|error| {
IdeError::new(ErrorKind::Io, format!("Could not start the external TCP tunnel helper: {error}"))
})?);
active.children.retain(|child| child.strong_count() > 0);
active.children.push(Arc::downgrade(&helper));
Ok(helper)
}
struct Helper {
child: Option<Child>,
#[cfg(windows)]
job: process::Job,
}
impl Helper {
fn spawn(executable: &Path, arguments: &[String]) -> io::Result<Self> {
let mut command = Command::new(executable);
command
.args(arguments)
.current_dir(executable.parent().expect("validated absolute executable path"))
.env_clear()
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null());
// Keep user config discovery available without inheriting database or project variables.
for key in [
"PATH",
"HOME",
"XDG_CONFIG_HOME",
"XDG_CACHE_HOME",
"XDG_DATA_HOME",
"XDG_RUNTIME_DIR",
"USERPROFILE",
"APPDATA",
"LOCALAPPDATA",
"SYSTEMROOT",
"WINDIR",
"TMPDIR",
"TEMP",
"TMP",
"SSH_AUTH_SOCK",
"NO_PROXY",
"no_proxy",
] {
if let Some(value) = process::host_var_os(key) {
command.env(key, value);
}
}
for key in ["HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "http_proxy", "https_proxy", "all_proxy"] {
if let Some(value) = process::host_var_os(key)
&& value.to_str().is_some_and(credential_free_proxy)
{
command.env(key, value);
}
}
#[cfg(unix)]
{
use std::os::unix::process::CommandExt;
// Membership of this group is an authorization check. A separate session limits
// membership to this child and its descendants; the leader also owns the group.
// SAFETY: setsid is async-signal-safe and does not access Rust state after fork.
unsafe {
command.pre_exec(|| if libc::setsid() == -1 { Err(io::Error::last_os_error()) } else { Ok(()) });
}
}
#[cfg(windows)]
{
platform::spawn_suspended(command)
}
#[cfg(not(windows))]
{
Ok(Self { child: Some(command.spawn()?) })
}
}
fn child(&self) -> &Child {
self.child.as_ref().expect("the live helper owns its child handle")
}
#[cfg(unix)]
fn pid(&self) -> u32 {
self.child().id()
}
fn is_alive(&self) -> bool {
#[cfg(unix)]
{
loop {
let mut info = std::mem::MaybeUninit::<libc::siginfo_t>::zeroed();
// Keep the group leader unreaped so its id cannot be reused before group cleanup.
// SAFETY: valid output buffer and the id of the child owned by `self`.
let result = unsafe {
libc::waitid(
libc::P_PID,
self.pid(),
info.as_mut_ptr(),
libc::WEXITED | libc::WNOHANG | libc::WNOWAIT,
)
};
if result == 0 {
// SAFETY: the buffer was zeroed and waitid returned successfully.
return unsafe { info.assume_init().si_pid() == 0 };
}
if io::Error::last_os_error().kind() != io::ErrorKind::Interrupted {
return false;
}
}
}
#[cfg(windows)]
{
use std::os::windows::io::AsRawHandle;
use windows_sys::Win32::Foundation::WAIT_TIMEOUT;
use windows_sys::Win32::System::Threading::WaitForSingleObject;
// SAFETY: the owned child handle stays open through this non-blocking check.
unsafe { WaitForSingleObject(self.child().as_raw_handle(), 0) == WAIT_TIMEOUT }
}
#[cfg(not(any(unix, windows)))]
{
false
}
}
fn stop(&self) {
#[cfg(windows)]
let _ = self.job.terminate();
#[cfg(unix)]
process::kill_tree_of(self.pid());
}
}
fn credential_free_proxy(value: &str) -> bool {
let url = if value.contains("://") {
reqwest::Url::parse(value)
} else {
reqwest::Url::parse(&format!("http://{value}"))
};
url.is_ok_and(|url| {
matches!(url.scheme(), "http" | "https" | "socks4" | "socks4a" | "socks5" | "socks5h")
&& url.host().is_some()
&& url.username().is_empty()
&& url.password().is_none()
&& matches!(url.path(), "" | "/")
&& url.query().is_none()
&& url.fragment().is_none()
})
}
impl Drop for Helper {
fn drop(&mut self) {
self.stop();
#[cfg(unix)]
if let Some(mut child) = self.child.take() {
// A helper blocked in the kernel must not hold up the async caller during cleanup.
if !matches!(child.try_wait(), Ok(Some(_))) {
let _ = std::thread::Builder::new().spawn(move || child.wait());
}
}
}
}
async fn relay(listener: Arc<TcpListener>, endpoint: SocketAddr, helper: Arc<Helper>) {
let mut connections = JoinSet::new();
let mut liveness = tokio::time::interval(Duration::from_secs(1));
liveness.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
loop {
tokio::select! {
_ = liveness.tick() => {
if !helper.is_alive() { break; }
}
accepted = listener.accept(), if connections.len() < MAX_CONNECTIONS => {
let Ok((mut client, _)) = accepted else {
// Transient errors such as descriptor exhaustion affect new sockets only.
tokio::time::sleep(POLL_INTERVAL).await;
continue;
};
let helper = Arc::clone(&helper);
connections.spawn(async move {
if let Ok(Ok(mut upstream)) = tokio::time::timeout(CONNECTION_TIMEOUT, connect_verified(&helper, endpoint)).await {
let _ = tokio::io::copy_bidirectional(&mut client, &mut upstream).await;
true
} else {
false
}
});
}
finished = connections.join_next(), if !connections.is_empty() => {
if matches!(finished, Some(Ok(false)))
// A slow ownership probe must not interrupt already verified connections.
&& matches!(tokio::time::timeout(CONNECTION_TIMEOUT, verify_socket(&helper, endpoint, None)).await, Ok(Ok(false)))
{
break;
}
}
}
}
}
async fn connect_verified(helper: &Arc<Helper>, endpoint: SocketAddr) -> io::Result<TcpStream> {
let upstream = TcpStream::connect(endpoint).await?;
let peer = upstream.local_addr()?;
// TCP connect can complete before the helper accepts. Check the server's half of this
// exact connection, keeping all client bytes in the IDE until that socket has an owner.
loop {
if !helper.is_alive() {
return Err(io::Error::new(io::ErrorKind::BrokenPipe, "external TCP tunnel helper exited"));
}
if verify_socket(helper, endpoint, Some(peer)).await? && helper.is_alive() {
return Ok(upstream);
}
tokio::time::sleep(POLL_INTERVAL).await;
}
}
async fn verify_socket(helper: &Arc<Helper>, local: SocketAddr, peer: Option<SocketAddr>) -> io::Result<bool> {
let _slot = VERIFICATION_SLOTS.acquire().await.map_err(io::Error::other)?;
platform::owns_socket(helper, local, peer).await
}
#[cfg(all(test, any(target_os = "linux", target_os = "macos", windows)))]
mod tests;
@@ -1,92 +0,0 @@
use super::{Helper, io};
use std::fs::{self, File};
use std::io::{BufRead, BufReader, Read};
use std::net::{SocketAddr, SocketAddrV4};
use std::sync::Arc;
pub(super) async fn owns_socket(helper: &Arc<Helper>, local: SocketAddr, peer: Option<SocketAddr>) -> io::Result<bool> {
let helper = Arc::clone(helper);
tokio::task::spawn_blocking(move || {
let (SocketAddr::V4(local), peer) = (local, peer) else { return Ok(false) };
let peer = match peer {
Some(SocketAddr::V4(peer)) => Some(peer),
None => None,
_ => return Ok(false),
};
let state = if peer.is_some() { "01" } else { "0A" };
for (table, ipv6) in [("/proc/net/tcp", false), ("/proc/net/tcp6", true)] {
let file = match File::open(table) {
Ok(file) => file,
Err(error) if ipv6 && error.kind() == io::ErrorKind::NotFound => continue,
Err(error) => return Err(error),
};
let local = address(local, ipv6);
let peer = peer.map(|peer| address(peer, ipv6));
// Kernel rows are small, but bound the time spent scanning a busy host's table.
for line in BufReader::new(file.take(8 * 1024 * 1024)).lines().skip(1) {
let line = line?;
let mut fields = line.split_ascii_whitespace().skip(1);
let (Some(left), Some(right), Some(current_state)) = (fields.next(), fields.next(), fields.next())
else {
continue;
};
if left != local || current_state != state || peer.as_deref().is_some_and(|peer| peer != right) {
continue;
}
let Some(inode) = fields.nth(5).and_then(|inode| inode.parse::<u64>().ok()).filter(|inode| *inode != 0)
else {
continue;
};
if group_holds_socket(helper.pid(), inode)? {
return Ok(true);
}
}
}
Ok(false)
})
.await
.map_err(io::Error::other)?
}
fn address(address: SocketAddrV4, ipv6: bool) -> String {
let ip = address.ip();
let port = address.port();
if !ipv6 {
return format!("{:08X}:{port:04X}", u32::from_ne_bytes(ip.octets()));
}
let octets = ip.to_ipv6_mapped().octets();
let [a, b, c, d] = octets.as_chunks::<4>().0 else { unreachable!() };
format!(
"{:08X}{:08X}{:08X}{:08X}:{port:04X}",
u32::from_ne_bytes(*a),
u32::from_ne_bytes(*b),
u32::from_ne_bytes(*c),
u32::from_ne_bytes(*d)
)
}
fn group_holds_socket(group: u32, inode: u64) -> io::Result<bool> {
let group = i32::try_from(group).map_err(io::Error::other)?;
let target = format!("socket:[{inode}]");
for process in fs::read_dir("/proc")? {
let Ok(process) = process else { continue };
let name = process.file_name();
let Some(pid) = name.to_str().and_then(|name| name.parse::<libc::pid_t>().ok()).filter(|pid| *pid > 0) else {
continue;
};
// SAFETY: this only queries the process group of the enumerated pid.
if unsafe { libc::getpgid(pid) } != group {
continue;
}
let Ok(descriptors) = fs::read_dir(process.path().join("fd")) else { continue };
for descriptor in descriptors.flatten() {
if fs::read_link(descriptor.path()).is_ok_and(|link| link.as_os_str() == target.as_str()) {
// SAFETY: check membership again after examining the fd directory.
if unsafe { libc::getpgid(pid) } == group {
return Ok(true);
}
}
}
}
Ok(false)
}
@@ -1,61 +0,0 @@
use super::{Helper, io};
use std::net::{IpAddr, SocketAddr};
use std::process::Stdio;
use std::sync::Arc;
use tokio::io::AsyncReadExt;
const MAX_OUTPUT: u64 = 64 * 1024;
pub(super) async fn owns_socket(helper: &Arc<Helper>, local: SocketAddr, peer: Option<SocketAddr>) -> io::Result<bool> {
let group = helper.pid().to_string();
let sockets = format!("-iTCP:{}", local.port());
let state = if peer.is_some() { "-sTCP:ESTABLISHED" } else { "-sTCP:LISTEN" };
let mut probe = tokio::process::Command::new("/usr/sbin/lsof")
.args(["-nP", "-a", "-g", &group, &sockets, state, "-Fgn"])
.env_clear()
.stdin(Stdio::null())
.stderr(Stdio::null())
.stdout(Stdio::piped())
.kill_on_drop(true)
.spawn()?;
let mut output = Vec::new();
probe.stdout.take().expect("stdout is piped").take(MAX_OUTPUT + 1).read_to_end(&mut output).await?;
if output.len() as u64 > MAX_OUTPUT {
return Err(io::Error::other("loopback socket ownership output exceeded its limit"));
}
let status = probe.wait().await?;
if !status.success() {
// lsof uses exit 1 for a successful scan with no matching descriptors.
return if status.code() == Some(1) && output.is_empty() {
Ok(false)
} else {
Err(io::Error::other("loopback socket ownership query failed"))
};
}
let mut owned = false;
for line in String::from_utf8_lossy(&output).lines() {
match line.as_bytes().first() {
Some(b'p') => owned = false,
Some(b'g') => owned = line[1..] == group,
Some(b'n') if owned => {
let (left, right) =
line[1..].split_once("->").map_or((&line[1..], None), |(left, right)| (left, Some(right)));
if address(left) == Some(local) && right.and_then(address) == peer && right.is_some() == peer.is_some()
{
return Ok(true);
}
}
_ => {}
}
}
Ok(false)
}
fn address(value: &str) -> Option<SocketAddr> {
let address = value.parse::<SocketAddr>().ok()?;
let ip = match address.ip() {
IpAddr::V6(ip) => ip.to_ipv4_mapped().map_or(IpAddr::V6(ip), IpAddr::V4),
ip => ip,
};
Some(SocketAddr::new(ip, address.port()))
}
-188
View File
@@ -1,188 +0,0 @@
use super::*;
use std::io::{Read, Write};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
const EXAMPLE: &[u8; 4] = b"test";
const FIXTURE: &str = "external_tunnel::tests::fixture_entry";
fn config(mode: &str) -> crate::DbExternalTunnel {
crate::DbExternalTunnel {
executable: std::env::current_exe().unwrap().to_str().unwrap().to_owned(),
arguments: vec!["--exact".into(), FIXTURE.into(), "--skip".into(), format!("wire-{mode}-{{localPort}}")],
}
}
const TARGET: (&str, u16) = ("db.example", 5432);
// The test binary doubles as a foreground helper without an external interpreter.
#[test]
fn fixture_entry() {
let Some(fixture) = std::env::args().find(|arg| arg.starts_with("wire-")) else { return };
#[cfg(unix)]
// SAFETY: these calls only inspect the current process's session and group.
assert_eq!(unsafe { libc::getsid(0) }, unsafe { libc::getpgrp() });
let (mode, port) = fixture.strip_prefix("wire-").unwrap().split_once('-').unwrap();
let endpoint = SocketAddrV4::new(Ipv4Addr::LOCALHOST, port.parse().unwrap());
match mode {
"exit" => (),
"idle" => std::thread::sleep(Duration::from_secs(60)),
"waiting" => {
let observer = std::env::args()
.find_map(|arg| arg.strip_prefix("observer-port-").and_then(|port| port.parse::<u16>().ok()))
.unwrap();
let _observer = std::net::TcpStream::connect((Ipv4Addr::LOCALHOST, observer)).unwrap();
std::thread::sleep(Duration::from_secs(60));
}
"tree" => {
let mut child = Command::new(std::env::current_exe().unwrap())
.args(["--exact", FIXTURE, "--skip", &format!("wire-echo-{port}")])
.spawn()
.unwrap();
assert!(child.wait().unwrap().success());
}
"echo" | "once" => {
let socket = std::net::TcpListener::bind(endpoint).unwrap();
std::thread::sleep(Duration::from_millis(150));
for stream in socket.incoming() {
let mut stream = stream.unwrap();
let mut bytes = [0; EXAMPLE.len()];
if stream.read_exact(&mut bytes).is_ok() {
stream.write_all(&bytes).unwrap();
stream.write_all(&endpoint.port().to_be_bytes()).unwrap();
if mode == "once" {
let _ = stream.read(&mut [0]);
break;
}
}
}
}
_ => unreachable!(),
}
}
#[tokio::test]
async fn forwards_multiple_connections_to_the_helpers_child_and_cleans_up() {
let tunnel = ExternalTunnel::open(&config("tree"), TARGET).await.unwrap();
let mut helper_port = 0;
for _ in 0..2 {
let result = tokio::time::timeout(Duration::from_secs(5), async {
let mut db = TcpStream::connect((Ipv4Addr::LOCALHOST, tunnel.port())).await.unwrap();
db.write_all(EXAMPLE).await.unwrap();
let mut bytes = [0; EXAMPLE.len()];
db.read_exact(&mut bytes).await.unwrap();
assert_eq!(&bytes, EXAMPLE);
db.read_u16().await.unwrap()
});
helper_port = result.await.unwrap();
}
assert_ne!(helper_port, tunnel.port());
assert!(!tunnel.is_closed());
drop(tunnel);
tokio::time::timeout(Duration::from_secs(5), async {
loop {
if TcpStream::connect((Ipv4Addr::LOCALHOST, helper_port)).await.is_err() {
break;
}
tokio::time::sleep(POLL_INTERVAL).await;
}
})
.await
.unwrap();
}
#[tokio::test]
async fn reports_a_helper_that_exits_without_listening() {
let result = ExternalTunnel::open(&config("exit"), TARGET).await;
assert!(result.err().unwrap().message.contains("exited"));
}
#[tokio::test]
async fn dropping_startup_stops_the_helper_before_it_listens() {
let observer = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await.unwrap();
let mut settings = config("waiting");
settings.arguments.extend(["--skip".into(), format!("observer-port-{}", observer.local_addr().unwrap().port())]);
let startup = tokio::spawn(async move { ExternalTunnel::open(&settings, TARGET).await });
let (mut helper_socket, _) =
tokio::time::timeout(Duration::from_secs(10), observer.accept()).await.unwrap().unwrap();
assert!(!startup.is_finished());
startup.abort();
assert!(startup.await.err().unwrap().is_cancelled());
let error = tokio::time::timeout(Duration::from_secs(5), helper_socket.read_u8()).await.unwrap().unwrap_err();
// Terminating the helper can reset its observer socket on Windows.
assert!(matches!(error.kind(), io::ErrorKind::UnexpectedEof | io::ErrorKind::ConnectionReset), "{error}");
}
#[tokio::test]
async fn refuses_an_unrelated_established_loopback_socket() {
let unrelated = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await.unwrap();
let endpoint = unrelated.local_addr().unwrap();
let settings = config("idle");
let arguments = helper_arguments(&settings, TARGET, endpoint.port()).unwrap();
let helper = Arc::new(Helper::spawn(Path::new(&settings.executable), &arguments).unwrap());
assert!(helper.is_alive());
assert!(!verify_socket(&helper, endpoint, None).await.unwrap());
let listener = loopback_socket().unwrap().listen(128).unwrap();
let relay_endpoint = listener.local_addr().unwrap();
let task = tokio::spawn(relay(Arc::new(listener), endpoint, helper));
tokio::time::timeout(Duration::from_secs(10), async {
let mut db = TcpStream::connect(relay_endpoint).await.unwrap();
db.write_all(EXAMPLE).await.unwrap();
let (mut accepted, _) = unrelated.accept().await.unwrap();
assert_eq!(accepted.read_u8().await.unwrap_err().kind(), io::ErrorKind::UnexpectedEof);
task.await.unwrap();
})
.await
.unwrap();
}
#[tokio::test]
async fn a_dead_helper_keeps_its_relay_port_reserved_until_the_route_drops() {
let tunnel = ExternalTunnel::open(&config("once"), TARGET).await.unwrap();
let endpoint = SocketAddrV4::new(Ipv4Addr::LOCALHOST, tunnel.port());
tokio::time::timeout(Duration::from_secs(5), async {
let mut db = TcpStream::connect(endpoint).await.unwrap();
db.write_all(EXAMPLE).await.unwrap();
let mut bytes = [0; EXAMPLE.len()];
db.read_exact(&mut bytes).await.unwrap();
assert_eq!(&bytes, EXAMPLE);
db.read_u16().await.unwrap();
drop(db);
while !tunnel.is_closed() {
tokio::time::sleep(POLL_INTERVAL).await;
}
})
.await
.unwrap();
assert!(std::net::TcpListener::bind(endpoint).is_err());
}
#[test]
fn only_credential_free_proxy_addresses_reach_the_helper() {
assert!(credential_free_proxy("proxy.example:3128"));
assert!(credential_free_proxy("socks5h://proxy.example:1080"));
assert!(!credential_free_proxy("https://user:[email protected]:3128"));
assert!(!credential_free_proxy("https://proxy.example:3128/?secret=value"));
}
#[test]
fn expands_only_literal_arguments_and_validates_the_target() {
let settings = crate::DbExternalTunnel {
executable: config("echo").executable,
arguments: vec!["--port={localPort}".into(), "{host}:{port}".into(), "a b \"quotes\"".into()],
};
let arguments = helper_arguments(&settings, TARGET, 12345).unwrap();
assert_eq!(arguments, ["--port=12345", "db.example:5432", "a b \"quotes\""]);
assert!(helper_arguments(&settings, ("--some-option", 5432), 12345).is_err());
}
#[test]
fn brackets_an_ipv6_host_port_pair_but_preserves_the_raw_host_argument() {
let settings = crate::DbExternalTunnel {
executable: config("echo").executable,
arguments: vec!["{localPort}".into(), "{host}:{port}".into(), "{host}".into(), "[{host}]:{port}".into()],
};
let arguments = helper_arguments(&settings, ("[2001:db8::a]", 6432), 12345).unwrap();
assert_eq!(arguments, ["12345", "[2001:db8::a]:6432", "2001:db8::a", "[2001:db8::a]:6432"]);
}
@@ -1,161 +0,0 @@
use super::{Helper, io, process};
use std::net::{Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4};
use std::os::windows::io::{AsRawHandle, AsRawSocket, FromRawHandle, OwnedHandle};
use std::os::windows::process::CommandExt;
use std::process::Command;
use std::sync::Arc;
use tokio::net::TcpSocket;
use windows_sys::Win32::Foundation::{ERROR_INSUFFICIENT_BUFFER, INVALID_HANDLE_VALUE, NO_ERROR};
use windows_sys::Win32::NetworkManagement::IpHelper::{
GetExtendedTcpTable, MIB_TCP_STATE_ESTAB, MIB_TCP_STATE_LISTEN, MIB_TCP6ROW_OWNER_PID, MIB_TCPROW_OWNER_PID,
TCP_TABLE_OWNER_PID_ALL,
};
use windows_sys::Win32::Networking::WinSock::{
AF_INET, AF_INET6, SO_EXCLUSIVEADDRUSE, SOCKET_ERROR, SOL_SOCKET, WSAGetLastError, setsockopt,
};
use windows_sys::Win32::System::Diagnostics::ToolHelp::{
CreateToolhelp32Snapshot, TH32CS_SNAPTHREAD, THREADENTRY32, Thread32First, Thread32Next,
};
use windows_sys::Win32::System::Threading::{CREATE_SUSPENDED, OpenThread, ResumeThread, THREAD_SUSPEND_RESUME};
pub(super) fn make_exclusive(socket: &TcpSocket) -> io::Result<()> {
let enabled = 1i32;
// SAFETY: the socket is open and the option value remains valid for this call.
let result = unsafe {
setsockopt(
socket.as_raw_socket() as usize,
SOL_SOCKET,
SO_EXCLUSIVEADDRUSE,
(&raw const enabled).cast(),
size_of::<i32>() as i32,
)
};
if result == SOCKET_ERROR {
// SAFETY: reads the last Winsock error on the calling thread.
return Err(io::Error::from_raw_os_error(unsafe { WSAGetLastError() }));
}
Ok(())
}
pub(super) fn spawn_suspended(mut command: Command) -> io::Result<Helper> {
let mut child = command.creation_flags(CREATE_SUSPENDED | process::CREATE_NO_WINDOW).spawn()?;
let Some(job) = process::Job::for_child(&child) else {
// The child has never executed, so there are no descendants to terminate.
let _ = child.kill();
return Err(io::Error::other("could not contain the external tunnel helper in a Windows job"));
};
let helper = Helper { child: Some(child), job };
resume_initial_thread(helper.child().id())?;
Ok(helper)
}
fn resume_initial_thread(pid: u32) -> io::Result<()> {
// SAFETY: the snapshot handle is owned here, and each enumeration call writes a sized entry.
unsafe {
let snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
if snapshot == INVALID_HANDLE_VALUE {
return Err(io::Error::last_os_error());
}
let snapshot = OwnedHandle::from_raw_handle(snapshot);
let mut entry = THREADENTRY32 { dwSize: size_of::<THREADENTRY32>() as u32, ..Default::default() };
let mut has_entry = Thread32First(snapshot.as_raw_handle(), &mut entry);
while has_entry != 0 {
if entry.th32OwnerProcessID == pid {
let thread = OpenThread(THREAD_SUSPEND_RESUME, 0, entry.th32ThreadID);
if thread.is_null() {
return Err(io::Error::last_os_error());
}
let thread = OwnedHandle::from_raw_handle(thread);
return match ResumeThread(thread.as_raw_handle()) {
1 => Ok(()),
u32::MAX => Err(io::Error::last_os_error()),
_ => Err(io::Error::other("external tunnel helper was not in its initial suspended state")),
};
}
entry.dwSize = size_of::<THREADENTRY32>() as u32;
has_entry = Thread32Next(snapshot.as_raw_handle(), &mut entry);
}
}
Err(io::Error::other("could not find the external tunnel helper's suspended thread"))
}
pub(super) async fn owns_socket(helper: &Arc<Helper>, local: SocketAddr, peer: Option<SocketAddr>) -> io::Result<bool> {
let helper = Arc::clone(helper);
tokio::task::spawn_blocking(move || {
let state = if peer.is_some() { MIB_TCP_STATE_ESTAB as u32 } else { MIB_TCP_STATE_LISTEN as u32 };
let table = tcp_table(u32::from(AF_INET))?;
// SAFETY: this is the AF_INET owner-PID table, whose rows contain only integers.
for row in unsafe { rows::<MIB_TCPROW_OWNER_PID>(&table)? } {
if row.dwState == state
&& v4_address(row.dwLocalAddr, row.dwLocalPort) == local
&& peer.is_none_or(|peer| v4_address(row.dwRemoteAddr, row.dwRemotePort) == peer)
&& helper.job.contains_pid(row.dwOwningPid)
{
return Ok(true);
}
}
let table = tcp_table(u32::from(AF_INET6))?;
// SAFETY: this is the AF_INET6 owner-PID table, whose rows contain only integers.
for row in unsafe { rows::<MIB_TCP6ROW_OWNER_PID>(&table)? } {
if row.dwState == state
&& mapped_address(row.ucLocalAddr, row.dwLocalPort) == Some(local)
&& peer.is_none_or(|peer| mapped_address(row.ucRemoteAddr, row.dwRemotePort) == Some(peer))
&& helper.job.contains_pid(row.dwOwningPid)
{
return Ok(true);
}
}
Ok(false)
})
.await
.map_err(io::Error::other)?
}
fn v4_address(address: u32, port: u32) -> SocketAddr {
SocketAddrV4::new(Ipv4Addr::from(address.to_ne_bytes()), u16::from_be(port as u16)).into()
}
fn mapped_address(address: [u8; 16], port: u32) -> Option<SocketAddr> {
let address = Ipv6Addr::from(address).to_ipv4_mapped()?;
Some(SocketAddrV4::new(address, u16::from_be(port as u16)).into())
}
fn tcp_table(family: u32) -> io::Result<Vec<u32>> {
const MAX_TABLE: u32 = 8 * 1024 * 1024;
let mut size = 0;
let mut buffer = Vec::<u32>::new();
for _ in 0..3 {
// SAFETY: the buffer has the supplied capacity and u32 alignment for the owner-PID table.
let result = unsafe {
GetExtendedTcpTable(
if buffer.is_empty() { std::ptr::null_mut() } else { buffer.as_mut_ptr().cast() },
&mut size,
0,
family,
TCP_TABLE_OWNER_PID_ALL,
0,
)
};
match result {
NO_ERROR => return Ok(buffer),
ERROR_INSUFFICIENT_BUFFER if size <= MAX_TABLE => {
buffer.resize(size.div_ceil(size_of::<u32>() as u32) as usize, 0);
size = (buffer.len() * size_of::<u32>()) as u32;
}
_ => return Err(io::Error::from_raw_os_error(result as i32)),
}
}
Err(io::Error::other("the TCP socket ownership table did not stabilize"))
}
// `T` must be the matching Windows owner-PID row for this table, with no invalid bit patterns.
unsafe fn rows<T>(table: &[u32]) -> io::Result<&[T]> {
let Some((&count, data)) = table.split_first() else {
return Err(io::Error::other("missing TCP socket ownership table header"));
};
if align_of::<T>() > align_of::<u32>() || count as usize > std::mem::size_of_val(data) / size_of::<T>() {
return Err(io::Error::other("invalid TCP socket ownership table size"));
}
// SAFETY: the caller supplies the matching row layout; alignment and length are checked above.
Ok(unsafe { std::slice::from_raw_parts(data.as_ptr().cast(), count as usize) })
}
+12 -22
View File
@@ -1,7 +1,6 @@
//! A trusted local driver profile is shared by data sources. JDBC URLs and properties
//! can run driver-specific initialization. A project source may connect only with the
//! settings its user last accepted in the dialog; the approval lives outside the project.
use crate::local_settings::persist_local;
use crate::{DataSource, DbManager, QueryResult, ResultColumn};
use ide_core::{CancellationToken, IdeError, IdeResult};
use serde::{Deserialize, Serialize};
@@ -23,14 +22,20 @@ const LIMIT: usize = 16 * 1024 * 1024;
pub struct DbJdbcDriver {
pub id: String,
pub name: String,
/// Data source preset id; absent for a generic JDBC profile.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub vendor: Option<String>,
pub jars: Vec<String>,
pub class_name: String,
pub url_template: String,
}
fn persist_local(path: &Path, data: &[u8]) -> IdeResult<()> {
let dir = path.parent().expect("registry paths have a parent");
std::fs::create_dir_all(dir)?;
let mut tmp = tempfile::NamedTempFile::new_in(dir)?;
std::io::Write::write_all(&mut tmp, data)?;
tmp.persist(path).map_err(|e| IdeError::from(e.error))?;
Ok(())
}
fn local_jar(jar: &str) -> IdeResult<&Path> {
if jar.contains(if cfg!(windows) { ';' } else { ':' }) {
return Err(IdeError::invalid("A JDBC JAR path contains the system classpath separator"));
@@ -141,7 +146,7 @@ impl DbManager {
fn jdbc_approval(&self, source: &DataSource) -> IdeResult<(PathBuf, String)> {
let registry = self.jdbc_registry()?;
let key = serde_json::to_vec(&(&self.root, &source.id)).map_err(|e| IdeError::internal(e.to_string()))?;
let mut settings = serde_json::to_vec(&(
let settings = serde_json::to_vec(&(
&source.jdbc_driver,
&source.url,
&source.user,
@@ -150,9 +155,6 @@ impl DbManager {
&source.options,
))
.map_err(|e| IdeError::internal(e.to_string()))?;
if self.jdbc_password_isolated(source) {
settings.extend_from_slice(b"\0jdbc-password");
}
Ok((
registry.with_file_name("jdbc-approvals").join(blake3::hash(&key).to_hex().as_str()),
blake3::hash(&settings).to_hex().to_string(),
@@ -193,9 +195,6 @@ impl DbManager {
.into_iter()
.find(|d| d.id == source.jdbc_driver)
.ok_or_else(|| IdeError::invalid("Select an installed JDBC driver profile"))?;
if !source.vendor.is_empty() && driver.vendor.as_deref() != Some(source.vendor.as_str()) {
return Err(IdeError::invalid("The JDBC driver profile is not associated with this data source type"));
}
JdbcPool::connect(source, password, driver, self.jdbc_registry()?.with_file_name("jdbc"))
.await
.map(Box::new)
@@ -304,9 +303,7 @@ async fn read_frame(output: &mut (impl AsyncRead + Unpin)) -> IdeResult<Vec<u8>>
const CANCEL_GRACE: Duration = Duration::from_secs(3);
fn cancel_timeout() -> IdeError {
IdeError::invalid(
"Cancellation timed out and the JDBC session was closed. Check the statement's status on the server before running it again. The next query will try to reconnect.",
)
IdeError::invalid("The JDBC driver did not stop in time. The session was closed. Reconnect to continue.")
}
async fn exchange(
@@ -598,7 +595,6 @@ fn decode(data: &[u8], sql: &str, elapsed_ms: f64) -> IdeResult<QueryResult> {
affected: (affected >= 0).then_some(affected as f64),
elapsed_ms,
execution_ms: elapsed_ms,
truncated: Vec::new(),
})
}
@@ -606,13 +602,7 @@ impl DbManager {
pub(crate) async fn jdbc_completion(&self, id: &str, pool: &JdbcPool) -> IdeResult<crate::CompletionModel> {
let mut tables = vec![];
let mut column_count = 0;
// Read the schemas the source's Schemas tab picks, like the database tree does. It also
// keeps large instances usable: an Oracle server exposes dozens of system schemas, and
// dumping the columns of all of them takes minutes, during which the bridge (a single
// Java process that runs one command at a time) executes none of the user's statements.
let introspection = self.source(id)?.introspection;
let schemas: Vec<String> =
self.schemas(id).await?.into_iter().filter(|s| introspection.shows_schema(s)).collect();
let schemas = self.schemas(id).await?;
for schema in &schemas {
// Columns of the whole namespace in one call; a driver that refuses it still completes tables.
let mut columns = if column_count < crate::MAX_META_ROWS {
+163 -331
View File
@@ -4,12 +4,7 @@
pub mod catalog;
mod clickhouse;
mod external_tunnel;
pub use external_tunnel::stop_external_tunnels_on_exit;
mod jdbc;
mod local_settings;
mod route;
mod tunnel_approval;
pub use jdbc::{DbJdbcDriver, jdbc_driver_classes};
pub mod conn;
pub mod history;
@@ -26,12 +21,12 @@ mod watch;
pub use watch::SourcesWatch;
pub use catalog::{CatalogDatabase, CatalogSchema, SourceCatalog};
pub use conn::{Held, Pool, QueryResult, ResultColumn, TruncatedCell};
pub use conn::{Held, Pool, QueryResult, ResultColumn};
pub use history::HistoryEntry;
pub use plan::{PlanNode, PlanProperty};
pub use source::{
DataSource, DbColor, DbDriver, DbExternalTunnel, DbIntrospection, DbOptions, DbProperty, DbSchemaSelection,
DbSnowflake, DbSnowflakeAuth, DbSsh, DbSshAuth, DbSslMode, DbTxMode, DbVisibilityChange,
DataSource, DbColor, DbDriver, DbIntrospection, DbOptions, DbProperty, DbSnowflake, DbSnowflakeAuth, DbSsh,
DbSshAuth, DbSslMode, DbTxMode,
};
pub use sql::{CellValue, DbRowEdit, SortKey};
@@ -257,14 +252,17 @@ pub struct Databases {
/// Connections of one project's data sources, keyed by connection target (see [`split_target`]).
pub struct DbManager {
root: PathBuf,
pools: Mutex<HashMap<String, Arc<route::ConnectionSlot>>>,
routes: route::Routes,
local_external_tunnels: bool,
pools: Mutex<HashMap<String, Arc<Pool>>>,
/// SSH tunnels by data source id, shared by the pools of its databases
/// (closed with the last of them).
tunnels: Mutex<HashMap<String, Arc<Tunnel>>>,
/// Serialises opening tunnels so concurrent connects share one.
tunnel_open: tokio::sync::Mutex<()>,
/// App-wide SSH connections and host-key trust.
ssh: Arc<SshManager>,
saved_passwords: Arc<SecretStore>,
saved_passwords: SecretStore,
/// Directory of the global data sources and their saved passwords ([`DbManager::with_global_sources`]).
global: Option<(PathBuf, Arc<SecretStore>)>,
global: Option<(PathBuf, SecretStore)>,
history: Arc<HistoryStore>,
/// What introspection read of each data source, kept between runs.
catalogs: catalog::CatalogStore,
@@ -275,8 +273,6 @@ pub struct DbManager {
/// Manual-commit data sources, each with the connection of its open
/// transaction (taken by the first statement after a commit / rollback).
sessions: Mutex<HashMap<String, Session>>,
/// Result pages read on from where the previous page stopped, not by running the statement again.
cursors: conn::Cursors,
/// The data sources as last read from disk, for [`DbManager::reconcile_sources`]
/// (`None` until [`DbManager::watch_sources`]).
on_disk: Mutex<Option<Vec<DataSource>>>,
@@ -423,27 +419,26 @@ impl DbManager {
}
}
Self {
saved_passwords: Arc::new(SecretStore::new(passwords, &root)),
saved_passwords: SecretStore::new(passwords, &root),
global: None,
history,
catalogs,
recorder,
root,
pools: Mutex::default(),
routes: Mutex::default(),
local_external_tunnels: false,
tunnels: Mutex::default(),
tunnel_open: tokio::sync::Mutex::new(()),
ssh,
session_passwords: Mutex::default(),
on_disk: Mutex::default(),
sessions: Mutex::default(),
cursors: conn::Cursors::default(),
}
}
/// Also lists the global data sources stored in `dir` (the app data directory).
pub fn with_global_sources(mut self, dir: PathBuf) -> Self {
let passwords = self.saved_passwords.scoped(&dir);
self.global = Some((dir, Arc::new(passwords)));
self.global = Some((dir, passwords));
self
}
@@ -473,36 +468,13 @@ impl DbManager {
}
}
fn store_of(&self, source: &DataSource) -> &Arc<SecretStore> {
fn store_of(&self, source: &DataSource) -> &SecretStore {
match &self.global {
Some((_, store)) if source.global => store,
_ => &self.saved_passwords,
}
}
fn non_password_snowflake(source: &DataSource) -> Option<DbSnowflake> {
let settings = match source.driver {
DbDriver::Snowflake => source.resolved().map(|source| source.snowflake()).unwrap_or_default(),
DbDriver::Jdbc => source.snowflake.clone()?,
_ => return None,
};
(settings.auth != DbSnowflakeAuth::Password).then_some(settings)
}
fn jdbc_password_isolated(&self, source: &DataSource) -> bool {
source.driver == DbDriver::Jdbc
&& (Self::non_password_snowflake(source).is_some()
|| self
.sources()
.unwrap_or_default()
.iter()
.any(|stored| stored.id == source.id && Self::non_password_snowflake(stored).is_some()))
}
fn password_key(&self, source: &DataSource) -> String {
if self.jdbc_password_isolated(source) { secrets::jdbc_key(&source.id) } else { source.id.clone() }
}
/// The connection settings of target `target` ([`DataSource::resolved`]), with
/// its database for `<id>:<database>`.
pub fn source(&self, target: &str) -> IdeResult<DataSource> {
@@ -513,25 +485,25 @@ impl DbManager {
.find(|s| s.id == id)
.ok_or_else(|| IdeError::not_found(format!("no data source {id}")))?
.resolved()?;
source.select_database(database);
if let Some(db) = database {
// The configured schema belongs to the configured database.
if source.driver == DbDriver::Snowflake && !source.database.eq_ignore_ascii_case(db) {
source.options.default_schema.clear();
}
source.database = db.to_owned();
}
Ok(source)
}
/// Saves the data source list, preserving connections when only visibility rules change.
/// Saves the data source list; connections of removed or changed sources are closed.
/// Global ones (`global`) go to the app-wide list, the others to the project's.
pub async fn save_sources(&self, mut sources: Vec<DataSource>) -> IdeResult<()> {
pub async fn save_sources(&self, sources: Vec<DataSource>) -> IdeResult<()> {
if sources.iter().any(|s| s.global && s.plugin_owner.is_some()) {
return Err(IdeError::invalid("plugin-owned data sources must stay project-scoped"));
}
let old = {
let _guard = plugin::EDIT.lock();
let old = self.sources().unwrap_or_default();
for source in sources.iter_mut().filter(|s| s.driver == DbDriver::Jdbc) {
// Retain the credential scope even when URL-only settings supplied the old authenticator.
if let Some(settings) = old.iter().find(|s| s.id == source.id).and_then(Self::non_password_snowflake) {
source.snowflake = Some(settings);
}
}
let (global, project): (Vec<_>, Vec<_>) = sources.iter().cloned().partition(|s| s.global);
match &self.global {
// Rewritten only when it changes: other projects' windows edit the same file.
@@ -550,10 +522,9 @@ impl DbManager {
};
for o in old {
match sources.iter().find(|s| s.id == o.id) {
Some(n) if o.same_except_visibility(n) => {}
Some(n) if *n == o => {}
gone_or_changed => {
let keys =
[o.id.clone(), secrets::jdbc_key(&o.id), secrets::ssh_key(&o.id), Self::sso_credential(&o.id)];
let keys = [o.id.clone(), secrets::ssh_key(&o.id), Self::sso_credential(&o.id)];
match gone_or_changed {
None => {
self.catalogs.forget(&o.id);
@@ -584,31 +555,6 @@ impl DbManager {
Ok(())
}
/// Updates one scope of a source's visibility against its latest saved rules.
pub fn save_source_visibility(&self, id: &str, available: &[String], change: DbVisibilityChange) -> IdeResult<()> {
let _guard = plugin::EDIT.lock();
let mut sources = source::load(&self.root)?;
let scoped_global = self.global.as_ref().filter(|_| !sources.iter().any(|source| source.id == id));
if let Some((dir, _)) = scoped_global {
sources = source::load_global(dir)?;
}
let selected = sources
.iter_mut()
.find(|source| source.id == id)
.ok_or_else(|| IdeError::not_found(format!("no data source {id}")))?;
let previous = selected.introspection.clone();
change.apply(&mut selected.introspection, available);
if selected.introspection == previous {
return Ok(());
}
if let Some((dir, _)) = scoped_global {
source::save_global(dir, &sources)?;
} else {
source::save(&self.root, &sources)?;
}
Ok(())
}
/// Watches the data source files (the project's and the global one) for edits made
/// outside the IDE; `on_change` runs on a background thread once they settle, and
/// should call [`DbManager::reconcile_sources`]. Stops when the result is dropped.
@@ -617,9 +563,9 @@ impl DbManager {
SourcesWatch::start(&self.root, self.global.as_ref().map(|(dir, _)| dir.as_path()), on_change)
}
/// Re-reads the data sources after their files changed on disk and closes affected
/// connections as on [`DbManager::save_sources`] (saved passwords stay, the source
/// may come back). Returns whether the list the tree
/// Re-reads the data sources after their files changed on disk: connections of
/// removed or changed sources close, as on [`DbManager::save_sources`] (saved
/// passwords stay, the source may come back). Returns whether the list the tree
/// shows changed, or the files no longer parse (the tree reports the error).
pub async fn reconcile_sources(&self) -> bool {
let now = match self.sources() {
@@ -634,7 +580,7 @@ impl DbManager {
return false;
}
for o in &before {
if now.iter().find(|s| s.id == o.id).is_none_or(|n| !o.same_except_visibility(n)) {
if now.iter().find(|s| s.id == o.id) != Some(o) {
self.disconnect_source(&o.id).await;
}
}
@@ -644,12 +590,7 @@ impl DbManager {
/// Remembers `password` for the session, and in the saved passwords when
/// the data source saves passwords (`None` forgets it).
pub async fn set_password(&self, id: &str, password: Option<String>, save: bool) -> IdeResult<()> {
let source = self.sources()?.into_iter().find(|s| s.id == id);
let (store, key) = match source.as_ref() {
Some(source) => (self.store_of(source), self.password_key(source)),
None => (&self.saved_passwords, id.to_owned()),
};
self.remember(store, key, password, save).await
self.remember(id, id.to_owned(), password, save).await
}
/// [`DbManager::set_password`] for the SSH password / key passphrase.
@@ -661,10 +602,10 @@ impl DbManager {
self.ssh.set_secret(&c, secret, save);
return Ok(());
}
self.remember(self.saved_for(id), secrets::ssh_key(id), secret, save).await
self.remember(id, secrets::ssh_key(id), secret, save).await
}
async fn remember(&self, store: &SecretStore, key: String, secret: Option<String>, save: bool) -> IdeResult<()> {
async fn remember(&self, id: &str, key: String, secret: Option<String>, save: bool) -> IdeResult<()> {
match &secret {
Some(p) => {
self.session_passwords.lock().insert(key.clone(), p.clone());
@@ -673,6 +614,7 @@ impl DbManager {
self.session_passwords.lock().remove(&key);
}
}
let store = self.saved_for(id);
let result = match (secret, save) {
(Some(p), true) => store.set(&key, &p),
_ => {
@@ -694,17 +636,11 @@ impl DbManager {
if !saved {
return None;
}
// The OS may wait for the user to unlock the credential store. A cancelled connection
// must be able to stop waiting without starting its helper when the prompt is answered.
let store = Arc::clone(self.store_of(source));
tokio::task::spawn_blocking(move || store.get(&key)).await.ok().flatten()
self.store_of(source).get(&key)
}
async fn password(&self, source: &DataSource) -> Option<String> {
match self
.secret(source, self.password_key(source), source.driver != DbDriver::Sqlite && source.save_password)
.await
{
match self.secret(source, source.id.clone(), source.driver != DbDriver::Sqlite && source.save_password).await {
Some(p) => Some(p),
None => source.url_password(),
}
@@ -735,6 +671,36 @@ impl DbManager {
}
}
/// Opens the SSH tunnel of `source` when it has one, returning the settings to
/// connect with (the tunnel's local end instead of the database host).
/// `shared` reuses (or registers) the data source's tunnel for its pools; Test
/// Connection opens a private one.
async fn endpoint(
&self,
source: &DataSource,
ssh_secret: Option<String>,
shared: bool,
) -> IdeResult<(DataSource, Option<Arc<Tunnel>>)> {
let Some(ssh) = source.ssh.as_ref().filter(|s| s.enabled && tunneled(source.driver)) else {
return Ok((source.clone(), None));
};
let local = |t: &Tunnel| DataSource { host: "127.0.0.1".into(), port: Some(t.port()), ..source.clone() };
let _opening = if shared { Some(self.tunnel_open.lock().await) } else { None };
if shared {
let existing = self.tunnels.lock().get(&source.id).filter(|t| !t.is_closed()).cloned();
if let Some(t) = existing {
return Ok((local(&t), Some(t)));
}
}
let session = self.ssh_session(source, ssh, ssh_secret).await?;
let (target_host, target_port) = tunnel_target(source);
let t = Arc::new(Tunnel::open(session, target_host, target_port).await?);
if shared {
self.tunnels.lock().insert(source.id.clone(), t.clone());
}
Ok((local(&t), Some(t)))
}
/// The SSH session the tunnel of `source` goes through: its shared SSH configuration's, or one
/// opened with the settings typed in the data source.
async fn ssh_session(
@@ -787,35 +753,23 @@ impl DbManager {
source: &DataSource,
password: Option<String>,
ssh_secret: Option<String>,
) -> IdeResult<String> {
if source.external_tunnel.is_some() {
return Err(IdeError::invalid("Review the external tunnel in the local Test Connection dialog"));
}
self.test_connection(source, password, ssh_secret, route::RouteUse::Test).await
}
pub async fn test_external_tunnel(&self, source: &DataSource, password: Option<String>) -> IdeResult<String> {
self.external_config(source)?;
self.test_connection(source, password, None, route::RouteUse::ReviewedExternalTest).await
}
async fn test_connection(
&self,
source: &DataSource,
password: Option<String>,
ssh_secret: Option<String>,
purpose: route::RouteUse,
) -> IdeResult<String> {
let source = &source.resolved()?;
let password = match password {
Some(p) => Some(p),
None => self.password(source).await,
};
let (target, _tunnel) = self.endpoint(source, ssh_secret, purpose).await?;
let (target, tunnel) = self.endpoint(source, ssh_secret, false).await?;
self.restore_sso(source).await;
let connected = self.open_pool(&target, password.as_deref(), true).await;
self.keep_sso(source).await;
let pool = connected.map_err(|e| self.connection_error(e, source))?;
let pool = connected.map_err(|e| {
through_tunnel(
e,
source,
tunnel.is_some().then(|| self.ssh_label(source.ssh.as_ref().expect("tunneled"))).as_deref(),
)
})?;
if let Pool::Jdbc(p) = &pool {
let version = p.version.clone();
pool.close().await;
@@ -836,8 +790,7 @@ impl DbManager {
_ => pool.rows(version, 1).await,
};
pool.close().await;
let strict =
source.external_tunnel.is_some() || matches!(source.driver, DbDriver::Clickhouse | DbDriver::Snowflake);
let strict = matches!(source.driver, DbDriver::Clickhouse | DbDriver::Snowflake);
let rows = if strict { result? } else { result.unwrap_or_default() };
let v = rows.into_iter().next().and_then(|r| r.into_iter().next().flatten());
Ok(v.unwrap_or_else(|| "Connected".into()))
@@ -863,15 +816,11 @@ impl DbManager {
if source.driver != tool.driver() {
return Err(IdeError::invalid(format!("{} cannot connect to {}", tool.program(), source.name)));
}
// Keep the same route as the connected pool for the entire tool invocation.
let connection = self.connection(id).await?;
let target = connection.target(&source);
self.pool(id).await?;
let password = self.password(&source).await;
let mut prepared = tools::prepare(job, executable, &target, password.as_deref())?;
if source.external_tunnel.is_some() {
// libpq gives PGHOSTADDR precedence over --host when choosing the TCP peer.
prepared.env.push(("PGHOSTADDR".into(), target.host.clone()));
}
// Holding the tunnel keeps it open while the tool runs, even if the tree disconnects.
let (target, _tunnel) = self.endpoint(&source, None, true).await?;
let prepared = tools::prepare(job, executable, &target, password.as_deref())?;
tools::run(executable, &prepared.args, &prepared.env, prepared.input.as_deref(), cancel, on_output).await
}
@@ -897,6 +846,89 @@ impl DbManager {
.ok_or_else(|| IdeError::internal("no server version"))
}
pub fn is_connected(&self, id: &str) -> bool {
self.pools.lock().get(id).is_some_and(|p| !p.is_closed())
}
/// Connected targets (data source ids, `<id>:<database>`).
pub fn connected(&self) -> Vec<String> {
self.pools.lock().iter().filter(|(_, p)| !p.is_closed()).map(|(id, _)| id.clone()).collect()
}
/// The pool of target `id`, connecting first if needed.
pub async fn pool(&self, id: &str) -> IdeResult<Arc<Pool>> {
let (source_id, _) = split_target(id);
// A dropped SSH session leaves every pool through it unusable: start over.
if self.tunnels.lock().get(source_id).is_some_and(|t| t.is_closed()) {
self.disconnect_source(source_id).await;
}
let cached = self.pools.lock().get(id).cloned();
if let Some(p) = cached {
if !p.is_closed() {
return Ok(p);
}
// The connection broke (a custom JDBC session whose TCP connection was dropped): reconnect.
self.disconnect(id).await;
}
let source = self.source(id)?;
let password = self.password(&source).await;
let (target, tunnel) = self.endpoint(&source, None, true).await?;
self.restore_sso(&source).await;
let connected = self.open_pool(&target, password.as_deref(), false).await;
self.keep_sso(&source).await;
let pool = match connected {
Ok(p) => Arc::new(p),
Err(e) => {
self.drop_unused_tunnel(source_id);
return Err(through_tunnel(
e,
&source,
tunnel.is_some().then(|| self.ssh_label(source.ssh.as_ref().expect("tunneled"))).as_deref(),
));
}
};
// Another caller may have connected meanwhile; keep theirs.
let kept = self.pools.lock().entry(id.to_owned()).or_insert_with(|| pool.clone()).clone();
if !Arc::ptr_eq(&kept, &pool) {
// Ours lost the race: close it rather than leave its session open on the server.
pool.close().await;
} else if let Some(secs) = source.options.keep_alive_secs.filter(|s| *s > 0) {
keep_alive(&pool, Duration::from_secs(secs.into()));
}
Ok(kept)
}
/// Closes the tunnel of `source_id` once none of its targets is connected.
fn drop_unused_tunnel(&self, source_id: &str) {
let in_use = self.pools.lock().keys().any(|k| split_target(k).0 == source_id);
if !in_use {
self.tunnels.lock().remove(source_id);
}
}
/// Disconnects target `id` (one database of a data source).
pub async fn disconnect(&self, id: &str) {
// A held connection would keep the pool from closing; manual mode stays on.
let session = self.sessions.lock().get(id).cloned();
if let Some(s) = session {
end_session(&s).await;
}
let pool = self.pools.lock().remove(id);
if let Some(p) = pool {
p.close().await;
}
self.drop_unused_tunnel(split_target(id).0);
}
/// Disconnects every database of data source `id`.
pub async fn disconnect_source(&self, id: &str) {
let targets: Vec<String> = self.pools.lock().keys().filter(|t| split_target(t).0 == id).cloned().collect();
for t in targets {
self.disconnect(&t).await;
}
self.tunnels.lock().remove(id);
}
/// Creates a database on the server of data source `id` by running `statement` on the data
/// source's own database, after closing the IDE's connections to `template`, the database
/// the server copies (PostgreSQL and SQL Server refuse to copy one that has sessions).
@@ -1478,25 +1510,6 @@ impl DbManager {
r
}
/// Row number `row` (from 0) of the result of `statement`, whole: what a page shows cut
/// short. It leaves the cursor of the result's pages where it stands, and is not recorded
/// in the history (the statement already was).
pub async fn read_row(
&self,
id: &str,
statement: &str,
row: usize,
cancel: &CancellationToken,
schema: Option<&str>,
) -> IdeResult<QueryResult> {
self.run_paged(id, statement, row, 1, cancel, schema, false).await
}
/// Closes the cursor that reads the pages of `statement` on `id` (its result tab was closed).
pub fn release_result(&self, id: &str, statement: &str, schema: Option<&str>) {
self.cursors.release(&conn::CursorKey::new(id, statement, schema));
}
fn remember_statement(&self, id: &str, statement: &str) {
let time = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
@@ -1568,44 +1581,12 @@ impl DbManager {
max_rows: usize,
cancel: &CancellationToken,
schema: Option<&str>,
) -> IdeResult<QueryResult> {
self.run_paged(id, statement, skip, max_rows, cancel, schema, true).await
}
/// `paging`: whether the page may continue a cursor of `statement` (see `conn::cursor`).
#[allow(clippy::too_many_arguments)]
async fn run_paged(
&self,
id: &str,
statement: &str,
skip: usize,
max_rows: usize,
cancel: &CancellationToken,
schema: Option<&str>,
paging: bool,
) -> IdeResult<QueryResult> {
let pool = self.pool(id).await?;
if let Pool::Jdbc(p) = &*pool {
return p.query_in_schema(statement, skip, max_rows, cancel, schema).await;
}
let session = self.sessions.lock().get(id).cloned();
if !conn::cursor_statement(statement) {
// A cursor's open statement could keep this one waiting (a lock), and would show data from before it.
self.cursors.release_target(id);
}
if paging && session.is_none() && skip > 0 && pool.keeps_cursors() && conn::cursor_statement(statement) {
let key = conn::CursorKey::new(id, statement, schema);
let started = std::time::Instant::now();
let page = match self.cursors.resume(&key, skip, max_rows, cancel).await {
Some(page) => page,
None => {
let mut held = Held::acquire(&pool).await?;
held.apply_context(schema).await?;
self.cursors.start(held, pool.clone(), key, skip, max_rows, cancel).await
}
};
return page.map(|fetched| conn::query_result(statement, fetched, started));
}
let Some(session) = session else {
if schema.is_none() {
return pool.execute_from(statement, skip, max_rows, cancel).await;
@@ -1767,83 +1748,6 @@ mod tests {
DbManager::new(dir.join("project"), data.join("db-passwords.json"), data.join("db-history.json"), ssh)
}
#[tokio::test]
async fn external_tunnel_approval_binds_the_command_destination_and_local_scope() {
let tmp = tempfile::tempdir().unwrap();
#[cfg(windows)]
let name = "forward.exe";
#[cfg(not(windows))]
let name = "forward";
let program = tmp.path().join(name);
std::fs::write(&program, b"fixture version 1").unwrap();
let app = tmp.path().join("app");
let desktop = |root: &Path| manager(root).with_global_sources(app.clone()).with_local_external_tunnels(true);
let db = desktop(tmp.path());
let other = desktop(&tmp.path().join("other"));
let mut source = DataSource {
id: "pg".into(),
name: "Example PostgreSQL".into(),
driver: DbDriver::Postgres,
host: "db.example".into(),
external_tunnel: Some(DbExternalTunnel {
executable: program.to_str().unwrap().into(),
arguments: vec!["--listen={localPort}".into(), "{host}:{port}".into()],
}),
..Default::default()
};
assert!(db.check_external_approval(&source).await.is_err());
db.approve_external_tunnel(&source).await.unwrap();
db.save_sources(vec![source.clone()]).await.unwrap();
db.check_external_approval(&db.source("pg").unwrap()).await.unwrap();
db.check_external_approval(&source).await.unwrap();
assert!(other.check_external_approval(&source).await.is_err());
for changed in [
DataSource { host: "other.example".into(), ..source.clone() },
DataSource { user: "other".into(), ..source.clone() },
DataSource { ssl: DbSslMode::Require, ..source.clone() },
] {
assert!(db.check_external_approval(&changed).await.is_err());
}
let mut changed = source.clone();
changed.external_tunnel.as_mut().unwrap().arguments.push("--changed".into());
assert!(db.check_external_approval(&changed).await.is_err());
source.global = true;
assert!(db.check_external_approval(&source).await.is_err());
db.approve_external_tunnel(&source).await.unwrap();
db.save_sources(vec![source.clone()]).await.unwrap();
db.check_external_approval(&db.source("pg").unwrap()).await.unwrap();
other.check_external_approval(&source).await.unwrap();
std::fs::write(&program, b"fixture version 2").unwrap();
assert!(db.check_external_approval(&source).await.is_err());
}
#[tokio::test]
async fn external_tunnel_rejects_incompatible_modes_and_implicit_test() {
let tmp = tempfile::tempdir().unwrap();
let source = DataSource {
id: "pg".into(),
driver: DbDriver::Postgres,
external_tunnel: Some(DbExternalTunnel {
executable: std::env::current_exe().unwrap().to_str().unwrap().into(),
arguments: vec!["{localPort}".into()],
}),
..Default::default()
};
let remote = manager(tmp.path()).with_global_sources(tmp.path().join("app"));
assert!(remote.test_external_tunnel(&source, None).await.is_err());
let db = remote.with_local_external_tunnels(true);
assert!(db.test(&source, None, None).await.is_err());
for bad in [
DataSource { ssl: DbSslMode::VerifyFull, ..source.clone() },
DataSource { url_only: true, ..source.clone() },
DataSource { plugin_owner: Some("sample".into()), ..source.clone() },
DataSource { driver: DbDriver::Jdbc, ..source.clone() },
DataSource { ssh: Some(DbSsh { enabled: true, ..Default::default() }), ..source.clone() },
] {
assert!(db.approve_external_tunnel(&bad).await.is_err());
}
}
#[tokio::test]
async fn saved_passwords_stay_off_disk() {
let tmp = tempfile::tempdir().unwrap();
@@ -1859,78 +1763,6 @@ mod tests {
);
}
#[tokio::test]
async fn switching_from_snowflake_key_pair_keeps_the_jdbc_password_separate() -> IdeResult<()> {
let tmp = tempfile::tempdir()?;
let db = manager(tmp.path()).with_global_sources(tmp.path().join("global"));
let native = DataSource {
id: "snowflake".into(),
name: "Snowflake".into(),
driver: DbDriver::Snowflake,
save_password: true,
url_only: true,
url: "jdbc:snowflake://example.invalid/?authenticator=SNOWFLAKE_JWT".into(),
..Default::default()
};
db.save_sources(vec![native.clone()]).await?;
db.set_password(&native.id, Some("native-passphrase".into()), true).await?;
let jdbc = DataSource { driver: DbDriver::Jdbc, url: "jdbc:fixture:".into(), ..native.clone() };
// Test Connection can use the JDBC draft before the user saves it.
assert_eq!(db.password(&jdbc).await, None);
assert_eq!(db.password(&native).await.as_deref(), Some("native-passphrase"));
db.approve_jdbc_source(&jdbc)?;
db.save_sources(vec![jdbc.clone()]).await?;
assert_eq!(db.password(&db.source(&jdbc.id)?).await, None);
db.set_password(&jdbc.id, Some("jdbc-password".into()), true).await?;
let reopened = manager(tmp.path()).with_global_sources(tmp.path().join("global"));
let saved = reopened.source(&jdbc.id)?;
assert_eq!(reopened.password(&saved).await.as_deref(), Some("jdbc-password"));
let err = reopened.pool(&jdbc.id).await.err().expect("no JDBC profile installed");
assert!(err.message.contains("Select an installed JDBC driver profile"));
source::save(&reopened.root, std::slice::from_ref(&jdbc))?;
let err = reopened.pool(&jdbc.id).await.err().expect("edited settings need approval");
assert!(err.message.contains("Review this project's JDBC URL and properties"));
source::save(&reopened.root, std::slice::from_ref(&saved))?;
let global = DataSource { global: true, ..saved };
reopened.save_sources(vec![global.clone()]).await?;
assert_eq!(reopened.password(&reopened.source(&jdbc.id)?).await.as_deref(), Some("jdbc-password"));
let native = DataSource { global: true, ..native };
reopened.save_sources(vec![native.clone()]).await?;
assert_eq!(reopened.password(&native).await.as_deref(), Some("native-passphrase"));
reopened.save_sources(Vec::new()).await?;
assert_eq!(reopened.password(&native).await, None);
assert_eq!(reopened.password(&global).await, None);
Ok(())
}
#[tokio::test]
async fn switching_from_snowflake_password_keeps_the_password() -> IdeResult<()> {
let tmp = tempfile::tempdir()?;
let db = manager(tmp.path());
let native = DataSource {
id: "snowflake".into(),
name: "Snowflake".into(),
driver: DbDriver::Snowflake,
save_password: true,
url_only: true,
url: "jdbc:snowflake://example.invalid/?authenticator=snowflake".into(),
..Default::default()
};
db.save_sources(vec![native.clone()]).await?;
db.set_password(&native.id, Some("existing-password".into()), true).await?;
let jdbc = DataSource { driver: DbDriver::Jdbc, url: "jdbc:fixture:".into(), ..native };
assert_eq!(db.password(&jdbc).await.as_deref(), Some("existing-password"));
db.save_sources(vec![jdbc.clone()]).await?;
let reopened = manager(tmp.path());
assert_eq!(reopened.password(&reopened.source(&jdbc.id)?).await.as_deref(), Some("existing-password"));
Ok(())
}
#[tokio::test]
async fn moves_plaintext_passwords_of_older_versions_off_disk() {
let tmp = tempfile::tempdir().unwrap();
-11
View File
@@ -1,11 +0,0 @@
use ide_core::{IdeError, IdeResult};
use std::path::Path;
pub(super) fn persist_local(path: &Path, data: &[u8]) -> IdeResult<()> {
let dir = path.parent().expect("registry paths have a parent");
std::fs::create_dir_all(dir)?;
let mut tmp = tempfile::NamedTempFile::new_in(dir)?;
std::io::Write::write_all(&mut tmp, data)?;
tmp.persist(path).map_err(|e| IdeError::from(e.error))?;
Ok(())
}
-1
View File
@@ -283,7 +283,6 @@ mod tests {
has_more: false,
elapsed_ms: 0.0,
execution_ms: 0.0,
truncated: Vec::new(),
}
}
-251
View File
@@ -1,251 +0,0 @@
//! A connection target owns its pool and keeps its data source's forwarding route alive.
//! Concurrent opens of sibling databases share a helper, but unrelated sources never wait on it.
use super::*;
use external_tunnel::ExternalTunnel;
use std::sync::Weak;
use tokio::sync::OnceCell;
#[derive(Clone, Copy, PartialEq, Eq)]
pub(super) enum RouteUse {
Connect,
Test,
ReviewedExternalTest,
}
pub(super) enum Route {
Ssh(Tunnel),
External(ExternalTunnel),
}
impl Route {
fn port(&self) -> u16 {
match self {
Self::Ssh(t) => t.port(),
Self::External(t) => t.port(),
}
}
fn is_closed(&self) -> bool {
match self {
Self::Ssh(t) => t.is_closed(),
Self::External(t) => t.is_closed(),
}
}
}
type RouteSlot = Arc<OnceCell<Route>>;
// The file watcher may observe a source edit after a new caller already read it.
pub(super) struct CachedRoute {
host: String,
port: u16,
ssh: Option<DbSsh>,
helper: Option<DbExternalTunnel>,
slot: Weak<OnceCell<Route>>,
}
impl CachedRoute {
fn matches(&self, source: &DataSource) -> bool {
let (host, port) = tunnel_target(source);
self.host == host && self.port == port && self.ssh == source.ssh && self.helper == source.external_tunnel
}
}
pub(super) type Routes = Mutex<HashMap<String, CachedRoute>>;
#[derive(Clone)]
pub(super) struct Connection {
pub(super) pool: Arc<Pool>,
route: Option<RouteSlot>,
}
impl Connection {
pub(super) fn target(&self, source: &DataSource) -> DataSource {
routed_target(source, self.route.as_ref())
}
fn is_closed(&self) -> bool {
self.pool.is_closed() || self.route.as_ref().and_then(|s| s.get()).is_some_and(Route::is_closed)
}
}
#[derive(Default)]
pub(super) struct ConnectionSlot {
pub(super) value: OnceCell<Connection>,
pub(super) cancel: CancellationToken,
}
fn routed_target(source: &DataSource, slot: Option<&RouteSlot>) -> DataSource {
match slot.and_then(|s| s.get()) {
Some(route) => DataSource { host: "127.0.0.1".into(), port: Some(route.port()), ..source.clone() },
None => source.clone(),
}
}
impl DbManager {
pub(super) async fn endpoint(
&self,
source: &DataSource,
ssh_secret: Option<String>,
purpose: RouteUse,
) -> IdeResult<(DataSource, Option<RouteSlot>)> {
let external = source.external_tunnel.as_ref();
let ssh = source.ssh.as_ref().filter(|ssh| ssh.enabled && tunneled(source.driver));
if external.is_none() && ssh.is_none() {
return Ok((source.clone(), None));
}
if external.is_some() {
match purpose {
RouteUse::Connect => self.check_external_approval(source).await?,
RouteUse::ReviewedExternalTest => {
self.external_config(source)?;
}
RouteUse::Test => {
return Err(IdeError::invalid("Review the external tunnel in the local Test Connection dialog"));
}
}
}
let slot = if purpose == RouteUse::Connect {
let mut routes = self.routes.lock();
if let Some(slot) = routes.get(&source.id).filter(|r| r.matches(source)).and_then(|r| r.slot.upgrade())
&& !slot.get().is_some_and(Route::is_closed)
{
slot
} else {
routes.retain(|_, r| r.slot.strong_count() > 0);
let slot = Arc::new(OnceCell::new());
let (host, port) = tunnel_target(source);
routes.insert(
source.id.clone(),
CachedRoute {
host: host.to_owned(),
port,
ssh: source.ssh.clone(),
helper: source.external_tunnel.clone(),
slot: Arc::downgrade(&slot),
},
);
slot
}
} else {
Arc::new(OnceCell::new())
};
slot.get_or_try_init(|| async {
if let Some(config) = external {
ExternalTunnel::open(config, tunnel_target(source)).await.map(Route::External)
} else {
let ssh = ssh.expect("enabled SSH transport");
let session = self.ssh_session(source, ssh, ssh_secret).await?;
let (host, port) = tunnel_target(source);
Tunnel::open(session, host, port).await.map(Route::Ssh)
}
})
.await?;
Ok((routed_target(source, Some(&slot)), Some(slot)))
}
pub(super) fn connection_error(&self, error: IdeError, source: &DataSource) -> IdeError {
if source.external_tunnel.is_some() && error.kind == ErrorKind::Io {
return IdeError::new(error.kind, format!("{} through the external database tunnel", error.message));
}
let via = source.ssh.as_ref().filter(|s| s.enabled && tunneled(source.driver)).map(|ssh| self.ssh_label(ssh));
through_tunnel(error, source, via.as_deref())
}
pub fn is_connected(&self, id: &str) -> bool {
self.pools.lock().get(id).and_then(|slot| slot.value.get()).is_some_and(|c| !c.is_closed())
}
pub fn connected(&self) -> Vec<String> {
self.pools
.lock()
.iter()
.filter(|(_, s)| s.value.get().is_some_and(|c| !c.is_closed()))
.map(|(id, _)| id.clone())
.collect()
}
pub async fn pool(&self, id: &str) -> IdeResult<Arc<Pool>> {
Ok(self.connection(id).await?.pool)
}
pub(super) async fn connection(&self, id: &str) -> IdeResult<Connection> {
let (slot, stale) = {
let mut pools = self.pools.lock();
let stale = if pools.get(id).and_then(|s| s.value.get()).is_some_and(Connection::is_closed) {
pools.remove(id)
} else {
None
};
(pools.entry(id.into()).or_default().clone(), stale)
};
if let Some(stale) = stale {
self.close_target(id, stale).await;
}
let result = tokio::select! {
biased;
_ = slot.cancel.cancelled() => Err(IdeError::cancelled()),
result = slot.value.get_or_try_init(|| self.open_connection(id)) => result.cloned(),
};
if result.is_err() {
let mut pools = self.pools.lock();
if Arc::strong_count(&slot) == 2 && pools.get(id).is_some_and(|s| Arc::ptr_eq(s, &slot)) {
pools.remove(id);
}
}
result
}
async fn open_connection(&self, id: &str) -> IdeResult<Connection> {
let (source_id, database) = split_target(id);
let mut source = self.source(source_id)?;
let password = self.password(&source).await;
// The approval belongs to the configured source, including its login database.
// Sibling database selection changes only the driver's target after routing.
let (mut target, route) = self.endpoint(&source, None, RouteUse::Connect).await?;
target.select_database(database);
source.select_database(database);
self.restore_sso(&source).await;
let result = self.open_pool(&target, password.as_deref(), false).await;
self.keep_sso(&source).await;
let pool = Arc::new(result.map_err(|e| self.connection_error(e, &source))?);
if let Some(secs) = source.options.keep_alive_secs.filter(|s| *s > 0) {
keep_alive(&pool, Duration::from_secs(secs.into()));
}
Ok(Connection { pool, route })
}
async fn close_target(&self, id: &str, slot: Arc<ConnectionSlot>) {
slot.cancel.cancel();
// A held transaction or result cursor keeps the pool from closing.
let session = self.sessions.lock().get(id).cloned();
if let Some(s) = session {
end_session(&s).await;
}
self.cursors.release_target(id);
if let Some(c) = slot.value.get() {
c.pool.close().await;
}
}
pub async fn disconnect(&self, id: &str) {
let slot = self.pools.lock().remove(id);
if let Some(slot) = slot {
self.close_target(id, slot).await;
}
}
pub async fn disconnect_source(&self, id: &str) {
let closing: Vec<_> = {
let mut pools = self.pools.lock();
let mut routes = self.routes.lock();
routes.remove(id);
pools.extract_if(|key, _| split_target(key).0 == id).collect()
};
for (_, slot) in &closing {
slot.cancel.cancel();
}
for (target, slot) in closing {
self.close_target(&target, slot).await;
}
}
}
-5
View File
@@ -18,11 +18,6 @@ pub fn ssh_key(id: &str) -> String {
format!("{id}#ssh")
}
/// JDBC password when the original credential is a Snowflake passphrase or token.
pub fn jdbc_key(id: &str) -> String {
format!("{id}#jdbc")
}
fn file_key(project: &str, key: &str) -> String {
format!("{project}|{key}")
}
-1
View File
@@ -892,7 +892,6 @@ impl SnowflakePool {
has_more,
elapsed_ms: started.elapsed().as_secs_f64() * 1000.0,
execution_ms,
truncated: Vec::new(),
})))
}
-234
View File
@@ -6,7 +6,6 @@
use ide_core::{IdeError, IdeResult, IpcPath, project_dir};
use serde::{Deserialize, Serialize};
use specta::Type;
use std::collections::BTreeMap;
use std::path::Path;
pub(crate) const FILE: &str = "data-sources.toml";
@@ -102,9 +101,6 @@ pub struct DbIntrospection {
pub databases: Vec<String>,
pub all_schemas: bool,
pub schemas: Vec<String>,
/// A database can replace the source's schema rules with all schemas or a list of exact names.
#[serde(skip_serializing_if = "BTreeMap::is_empty")]
pub schemas_by_database: BTreeMap<String, DbSchemaSelection>,
/// `pg_catalog`, `information_schema`, `mysql`…, and service databases (`rdsadmin`…).
pub show_system: bool,
/// PostgreSQL template databases (`template0`, `template1`).
@@ -121,7 +117,6 @@ impl Default for DbIntrospection {
databases: Vec::new(),
all_schemas: true,
schemas: Vec::new(),
schemas_by_database: BTreeMap::new(),
show_system: false,
show_templates: false,
object_filter: String::new(),
@@ -129,111 +124,6 @@ impl Default for DbIntrospection {
}
}
impl DbIntrospection {
pub(crate) fn with_visibility_from(self, source: &Self) -> Self {
Self {
all_databases: source.all_databases,
databases: source.databases.clone(),
all_schemas: source.all_schemas,
schemas: source.schemas.clone(),
schemas_by_database: source.schemas_by_database.clone(),
object_filter: source.object_filter.clone(),
..self
}
}
/// Whether the tree shows this schema: every one with `all_schemas`, otherwise it has to
/// match one of the `schemas` patterns. The completion model uses the same test, so it
/// offers exactly the tables the tree lists (and does not read the ones it never shows).
pub fn shows_schema(&self, name: &str) -> bool {
self.all_schemas
|| self.schemas.iter().map(|p| p.trim()).filter(|p| !p.is_empty()).any(|p| schema_matches(p, name))
}
}
/// `*` matches any run of characters, `?` a single one; a pattern without wildcards matches the
/// name as typed (the dialog fills names from the list the server returned, so case is settled).
fn schema_matches(pattern: &str, name: &str) -> bool {
if !pattern.contains('*') && !pattern.contains('?') {
return pattern == name;
}
let p: Vec<char> = pattern.chars().collect();
let n: Vec<char> = name.chars().collect();
let (mut pi, mut ni) = (0, 0);
// Position of the last `*` and how much of the name it has already swallowed.
let mut star: Option<(usize, usize)> = None;
while ni < n.len() {
if pi < p.len() && (p[pi] == '?' || p[pi] == n[ni]) {
pi += 1;
ni += 1;
} else if pi < p.len() && p[pi] == '*' {
star = Some((pi, ni));
pi += 1;
} else if let Some((at, taken)) = star {
pi = at + 1;
ni = taken + 1;
star = Some((at, taken + 1));
} else {
return false;
}
}
p[pi..].iter().all(|&c| c == '*')
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(default)]
pub struct DbSchemaSelection {
pub all: bool,
pub names: Vec<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
#[serde(tag = "kind", rename_all = "camelCase")]
pub enum DbVisibilityChange {
Databases { selection: DbSchemaSelection },
Schemas { selection: DbSchemaSelection },
DatabaseSchemas { database: String, selection: Option<DbSchemaSelection> },
}
impl DbVisibilityChange {
pub(crate) fn apply(self, introspection: &mut DbIntrospection, available: &[String]) {
let available: std::collections::HashSet<_> = available.iter().map(String::as_str).collect();
let keep_names = |before: &mut Vec<String>, selection: DbSchemaSelection, exact: bool| {
if selection.all || (!exact && before.iter().any(|name| name.contains(['*', '?']))) {
return;
}
before.retain(|name| !available.contains(if exact { name.as_str() } else { name.trim() }));
let mut seen: std::collections::HashSet<_> = before.iter().cloned().collect();
before.extend(
selection
.names
.into_iter()
.filter(|name| (exact || !name.contains(['*', '?'])) && seen.insert(name.clone())),
);
};
match self {
Self::Databases { selection } => {
introspection.all_databases = selection.all;
keep_names(&mut introspection.databases, selection, false);
}
Self::Schemas { selection } => {
introspection.all_schemas = selection.all;
keep_names(&mut introspection.schemas, selection, false);
}
Self::DatabaseSchemas { database, selection } => match selection {
Some(selection) => {
let rule = introspection.schemas_by_database.entry(database).or_default();
rule.all = selection.all;
keep_names(&mut rule.names, selection, true);
}
None => {
introspection.schemas_by_database.remove(&database);
}
},
}
}
}
/// Advanced tab: a driver property. PostgreSQL: run-time parameters (and
/// `application_name`); MySQL: session variables (and `charset`, `collation`);
/// SQLite: pragmas. See [`crate::conn`].
@@ -296,14 +186,6 @@ pub struct DbSsh {
pub save_secret: bool,
}
/// A foreground program that forwards an IDE-assigned loopback port to the database.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct DbExternalTunnel {
pub executable: String,
pub arguments: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase", default)]
pub struct DataSource {
@@ -326,8 +208,6 @@ pub struct DataSource {
pub read_only: bool,
/// SSH tunnel settings (`None`: never configured; kept but unused when not `enabled`).
pub ssh: Option<DbSsh>,
#[serde(skip_serializing_if = "Option::is_none")]
pub external_tunnel: Option<DbExternalTunnel>,
/// Wire-compatible product preset (`cockroachdb`, `tidb`…; empty: the driver itself).
pub vendor: String,
pub color: Option<DbColor>,
@@ -371,7 +251,6 @@ impl Default for DataSource {
save_password: false,
read_only: false,
ssh: None,
external_tunnel: None,
vendor: String::new(),
color: None,
comment: String::new(),
@@ -512,24 +391,6 @@ pub fn parse_url(raw: &str) -> IdeResult<ParsedUrl> {
}
impl DataSource {
pub(crate) fn select_database(&mut self, database: Option<&str>) {
if let Some(db) = database {
// The configured schema belongs to the configured database.
if self.driver == DbDriver::Snowflake && !self.database.eq_ignore_ascii_case(db) {
self.options.default_schema.clear();
}
self.database = db.to_owned();
}
}
pub(crate) fn same_except_visibility(&self, other: &Self) -> bool {
if self == other {
return true;
}
let introspection = other.introspection.clone().with_visibility_from(&self.introspection);
*self == Self { introspection, ..other.clone() }
}
/// The settings to connect with: with [`DataSource::url_only`], host, port,
/// database, user, SSL and driver properties come from the URL (properties
/// of the Advanced tab still apply after the URL's).
@@ -761,81 +622,6 @@ mod tests {
assert_eq!(load(tmp.path()).unwrap(), vec![s]);
}
#[test]
fn visibility_change_preserves_patterns_unavailable_names_and_other_scopes() {
let mut introspection = DbIntrospection {
schemas: vec!["app_*".into(), "unavailable_?".into()],
databases: vec!["reporting".into(), "offline".into()],
schemas_by_database: BTreeMap::from([
("reporting".into(), DbSchemaSelection { all: false, names: vec!["private".into()] }),
("sandbox".into(), DbSchemaSelection { all: false, names: vec!["experiments".into()] }),
]),
show_system: true,
..Default::default()
};
DbVisibilityChange::Schemas { selection: DbSchemaSelection { all: false, names: vec!["demo".into()] } }
.apply(&mut introspection, &["app_sales".into(), "demo".into()]);
assert_eq!(introspection.schemas, ["app_*", "unavailable_?"]);
DbVisibilityChange::Databases { selection: DbSchemaSelection { all: false, names: vec!["sandbox".into()] } }
.apply(&mut introspection, &["reporting".into(), "sandbox".into()]);
assert_eq!(introspection.databases, ["offline", "sandbox"]);
DbVisibilityChange::DatabaseSchemas {
database: "reporting".into(),
selection: Some(DbSchemaSelection {
all: false,
names: vec!["finance".into(), "finance".into(), "private".into()],
}),
}
.apply(&mut introspection, &["public".into(), "finance".into()]);
assert_eq!(introspection.schemas_by_database["reporting"].names, ["private", "finance"]);
assert_eq!(introspection.schemas_by_database["sandbox"].names, ["experiments"]);
assert!(introspection.show_system);
}
#[test]
fn schema_override_can_omit_default_fields() {
let introspection: DbIntrospection = toml::from_str(
r#"
[schemasByDatabase.reporting]
all = true
[schemasByDatabase.sandbox]
names = ["finance"]
"#,
)
.unwrap();
assert_eq!(
introspection.schemas_by_database,
BTreeMap::from([
("reporting".into(), DbSchemaSelection { all: true, names: vec![] }),
("sandbox".into(), DbSchemaSelection { all: false, names: vec!["finance".into()] }),
])
);
}
#[test]
fn round_trips_database_schema_overrides() {
let tmp = tempfile::tempdir().unwrap();
let source = DataSource {
id: "postgres".into(),
name: "PostgreSQL Demo".into(),
driver: DbDriver::Postgres,
introspection: DbIntrospection {
all_schemas: false,
schemas: vec!["app_*".into()],
schemas_by_database: BTreeMap::from([
("analytics".into(), DbSchemaSelection { all: true, names: vec![] }),
("reporting.eu".into(), DbSchemaSelection { all: false, names: vec!["public".into()] }),
("sandbox".into(), DbSchemaSelection { all: false, names: vec![] }),
]),
..Default::default()
},
..Default::default()
};
save(tmp.path(), std::slice::from_ref(&source)).unwrap();
assert_eq!(load(tmp.path()).unwrap(), vec![source]);
}
#[test]
fn sqlserver_defaults() {
assert_eq!(DbDriver::SqlServer.default_port(), Some(1433));
@@ -979,24 +765,4 @@ mod tests {
assert_eq!(r.snowflake().auth, DbSnowflakeAuth::Browser);
assert_eq!(scheme_driver("snowflake"), Some(DbDriver::Snowflake));
}
#[test]
fn introspection_shows_only_the_picked_schemas() {
let mut i = DbIntrospection::default();
assert!(i.shows_schema("SYS"), "the default reads every schema");
i.all_schemas = false;
assert!(!i.shows_schema("SYS"), "nothing picked: the tree lists nothing either");
i.schemas = vec!["XMCB".into(), " APP_* ".into()];
assert!(i.shows_schema("XMCB"));
assert!(i.shows_schema("APP_INFO"));
assert!(!i.shows_schema("APP"), "`*` needs the text that follows it");
assert!(!i.shows_schema("SYS"));
assert!(!i.shows_schema("xmcb"), "patterns match the names the server returned");
i.schemas = vec!["?".into()];
assert!(i.shows_schema("A"));
assert!(!i.shows_schema("AB"));
}
}
Loaded 100 of 2677 files, more files were not shown because too many files have changed in this diff. Show more