mirror of
https://github.com/l0ng-ai/openidea.git
synced 2026-11-24 09:01:00 -10:00
Compare commits
85
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
40379cdc91 | ||
|
|
1ad9189861 | ||
|
|
fba210e22d | ||
|
|
40c8e83084 | ||
|
|
c6ea0ddab1 | ||
|
|
c3d1ba28fd | ||
|
|
75781a5731 | ||
|
|
63f2f0280d | ||
|
|
cd3399df60 | ||
|
|
fc4e4fa39a | ||
|
|
13e27f0133 | ||
|
|
f028109518 | ||
|
|
8492dc530a | ||
|
|
8bc7fd76be | ||
|
|
e8ac5d7bc2 | ||
|
|
12712253a8 | ||
|
|
b3e4bd63f1 | ||
|
|
748e5cee89 | ||
|
|
d729ae8122 | ||
|
|
503ed3b9bb | ||
|
|
1dd213964d | ||
|
|
5636fc0ecd | ||
|
|
5f64cce2a4 | ||
|
|
4101e9d185 | ||
|
|
a3ca576edd | ||
|
|
8b4e1e71fb | ||
|
|
cdfc38231f | ||
|
|
d18bd6144a | ||
|
|
91cd0c058d | ||
|
|
3ba9354159 | ||
|
|
0eef66d793 | ||
|
|
ad81ff442e | ||
|
|
01bd7fbe6e | ||
|
|
9e80289aa3 | ||
|
|
fd959cc87d | ||
|
|
18eb515c83 | ||
|
|
72b4d5c6de | ||
|
|
6cca609d5c | ||
|
|
fb56bd211b | ||
|
|
ff1ef2b2f0 | ||
|
|
644a2d5784 | ||
|
|
40c616e46d | ||
|
|
c5f7b3ae98 | ||
|
|
5f628e8de3 | ||
|
|
82d13207a9 | ||
|
|
74a009dcc3 | ||
|
|
0c57c5bd0d | ||
|
|
b419c25912 | ||
|
|
798c88226c | ||
|
|
bb850b25d6 | ||
|
|
bee5e2ed1f | ||
|
|
4a14efc168 | ||
|
|
1a7bf6efdc | ||
|
|
a68cae9311 | ||
|
|
cf29d1342c | ||
|
|
d1cc323c9e | ||
|
|
7164e17f1c | ||
|
|
de325c4d3c | ||
|
|
af044d2435 | ||
|
|
1d19a6dfec | ||
|
|
c906064a16 | ||
|
|
5beeacedf9 | ||
|
|
c8419934b2 | ||
|
|
1f8eaec00a | ||
|
|
2f6bb7e995 | ||
|
|
f25df55a53 | ||
|
|
af60c1c5b9 | ||
|
|
6fce934e95 | ||
|
|
24ef4143e6 | ||
|
|
30e72ffa57 | ||
|
|
dd164c0909 | ||
|
|
7419eb85c8 | ||
|
|
64a168a2d1 | ||
|
|
77c531b9ca | ||
|
|
d411ace29b | ||
|
|
4074d079b1 | ||
|
|
2d0120f092 | ||
|
|
df470f93c6 | ||
|
|
764b6717e0 | ||
|
|
7aa6adb0ef | ||
|
|
7ebdf04e2f | ||
|
|
c0f7ec93d3 | ||
|
|
cc9089db11 | ||
|
|
62095b904e | ||
|
|
96c5e94975 |
No files matched your search
@@ -1,83 +0,0 @@
|
||||
---
|
||||
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.
|
||||
@@ -1,91 +0,0 @@
|
||||
---
|
||||
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>
|
||||
```
|
||||
@@ -1,57 +0,0 @@
|
||||
---
|
||||
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 +0,0 @@
|
||||
../../.agents/skills/eval
|
||||
@@ -1 +0,0 @@
|
||||
../../.agents/skills/issue-fix
|
||||
@@ -1 +0,0 @@
|
||||
../../.agents/skills/verify
|
||||
+65
-29
@@ -28,7 +28,9 @@ jobs:
|
||||
# shared runners to others. Pushes, the merge queue and manual runs always run everything.
|
||||
changes:
|
||||
name: Changes
|
||||
runs-on: ubuntu-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: ${{ 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: 5
|
||||
permissions:
|
||||
pull-requests: read
|
||||
@@ -108,10 +110,10 @@ jobs:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
os: [macos-latest, ubuntu-22.04, windows-latest]
|
||||
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-22.04' && 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 }}
|
||||
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 }}
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: pnpm/action-setup@v5
|
||||
@@ -144,8 +146,8 @@ jobs:
|
||||
- name: Linux deps
|
||||
if: runner.os == 'Linux'
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y libwebkit2gtk-4.1-dev libayatana-appindicator3-dev librsvg2-dev libxdo-dev libssl-dev patchelf
|
||||
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[@]}"; }
|
||||
# tauri-build checks that frontendDist exists.
|
||||
- run: pnpm install --frozen-lockfile && mkdir -p dist
|
||||
shell: bash
|
||||
@@ -156,7 +158,8 @@ jobs:
|
||||
- run: git config --global core.autocrlf false
|
||||
- run: cargo nextest run --workspace --no-fail-fast
|
||||
- name: Remote backend with Docker Compose
|
||||
if: runner.os == 'Linux'
|
||||
# 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 \
|
||||
@@ -175,7 +178,7 @@ jobs:
|
||||
name: Rust checks
|
||||
needs: [changes, rust]
|
||||
if: always()
|
||||
runs-on: ubuntu-latest
|
||||
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: 5
|
||||
steps:
|
||||
- env:
|
||||
@@ -192,16 +195,27 @@ jobs:
|
||||
needs: changes
|
||||
if: needs.changes.outputs.server == 'true'
|
||||
timeout-minutes: 40
|
||||
runs-on: ubuntu-22.04
|
||||
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' }}
|
||||
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 }
|
||||
- run: sudo apt-get update && sudo apt-get install -y musl-tools
|
||||
- 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: cargo build --locked -p ide-host --bin openidea-server --target x86_64-unknown-linux-musl
|
||||
- run: target/x86_64-unknown-linux-musl/debug/openidea-server --version
|
||||
- run: '"${CARGO_TARGET_DIR:-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.
|
||||
@@ -210,18 +224,31 @@ jobs:
|
||||
needs: changes
|
||||
if: needs.changes.outputs.plugins == 'true'
|
||||
timeout-minutes: 30
|
||||
runs-on: ubuntu-22.04
|
||||
env:
|
||||
CARGO_TARGET_DIR: ${{ github.workspace }}/target-plugins
|
||||
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' }}
|
||||
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: |
|
||||
@@ -238,7 +265,7 @@ jobs:
|
||||
- uses: pnpm/action-setup@v5
|
||||
with: { version: 11 }
|
||||
- uses: actions/setup-node@v5
|
||||
with: { node-version: 22 }
|
||||
with: { node-version: 22, package-manager-cache: false }
|
||||
# Plugin web pages (`web-src/`, their own pnpm projects): typecheck and test.
|
||||
- name: Web pages typecheck and test
|
||||
shell: bash
|
||||
@@ -262,7 +289,7 @@ jobs:
|
||||
needs: changes
|
||||
if: needs.changes.outputs.deny == 'true'
|
||||
timeout-minutes: 15
|
||||
runs-on: ubuntu-latest
|
||||
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' }}
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
@@ -274,13 +301,19 @@ jobs:
|
||||
needs: changes
|
||||
if: needs.changes.outputs.frontend == 'true'
|
||||
timeout-minutes: 30
|
||||
runs-on: ubuntu-22.04
|
||||
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' }}
|
||||
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: pnpm }
|
||||
with:
|
||||
node-version: 22
|
||||
cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }}
|
||||
package-manager-cache: ${{ runner.environment != 'self-hosted' }}
|
||||
- run: pnpm install --frozen-lockfile
|
||||
- run: pnpm typecheck
|
||||
- run: pnpm lint
|
||||
@@ -295,38 +328,41 @@ jobs:
|
||||
needs: changes
|
||||
if: needs.changes.outputs.catalog == 'true'
|
||||
timeout-minutes: 15
|
||||
runs-on: ubuntu-latest
|
||||
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' }}
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: pnpm/action-setup@v5
|
||||
with: { version: 11 }
|
||||
- uses: actions/setup-node@v5
|
||||
with: { node-version: 22, cache: pnpm }
|
||||
with:
|
||||
node-version: 22
|
||||
cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }}
|
||||
package-manager-cache: ${{ runner.environment != 'self-hosted' }}
|
||||
- run: pnpm install --frozen-lockfile
|
||||
- run: pnpm vitest run src/platform/locales/textCatalog.test.ts
|
||||
|
||||
e2e:
|
||||
name: E2E (${{ matrix.shard }}/2)
|
||||
name: E2E (${{ matrix.shard }}/4)
|
||||
needs: changes
|
||||
if: needs.changes.outputs.e2e == 'true'
|
||||
timeout-minutes: 30
|
||||
runs-on: ubuntu-24.04
|
||||
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' }}
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
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
|
||||
shard: [1, 2, 3, 4]
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: pnpm/action-setup@v5
|
||||
with: { version: 11 }
|
||||
- uses: actions/setup-node@v5
|
||||
with: { node-version: 22, cache: pnpm }
|
||||
with:
|
||||
node-version: 22
|
||||
cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }}
|
||||
package-manager-cache: ${{ runner.environment != 'self-hosted' }}
|
||||
- run: pnpm install --frozen-lockfile
|
||||
- run: pnpm e2e --shard=${{ matrix.shard }}/2
|
||||
env:
|
||||
HOME: /root
|
||||
- run: pnpm exec playwright install --with-deps chromium
|
||||
- run: pnpm e2e --shard=${{ matrix.shard }}/4
|
||||
- uses: actions/upload-artifact@v6
|
||||
if: failure()
|
||||
with:
|
||||
|
||||
@@ -57,6 +57,9 @@ 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).
|
||||
@@ -65,8 +68,6 @@ concurrency:
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
CARGO_INCREMENTAL: 0
|
||||
# Line tables keep test backtraces readable and the binaries the build job hands on small.
|
||||
CARGO_PROFILE_DEV_DEBUG: line-tables-only
|
||||
|
||||
jobs:
|
||||
# The languages a pull request can affect: a change to one language's fixture, definition or
|
||||
@@ -74,7 +75,9 @@ jobs:
|
||||
# run none; anything else runs them all. Pushes and manual runs always run them all.
|
||||
changes:
|
||||
name: Changes
|
||||
runs-on: ubuntu-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: ${{ 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: 5
|
||||
permissions:
|
||||
pull-requests: read
|
||||
@@ -139,17 +142,32 @@ jobs:
|
||||
name: Build
|
||||
needs: changes
|
||||
if: needs.changes.outputs.languages != '[]'
|
||||
# The tests find the fixtures through the checkout path compiled into them (CARGO_MANIFEST_DIR),
|
||||
# which is the same on every GitHub-hosted runner.
|
||||
runs-on: ubuntu-22.04
|
||||
# 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@v4
|
||||
- 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
|
||||
@@ -157,7 +175,7 @@ jobs:
|
||||
| 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 target/debug/openidea-server smoke-bin/
|
||||
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.
|
||||
@@ -172,11 +190,16 @@ jobs:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
language: ${{ fromJSON(needs.changes.outputs.languages) }}
|
||||
# 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' }}
|
||||
# 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: 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@v4
|
||||
- uses: actions/checkout@v5
|
||||
# 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
|
||||
@@ -187,18 +210,32 @@ jobs:
|
||||
tar -xf smoke-bin.tar && rm smoke-bin.tar
|
||||
mkdir -p target/debug && mv smoke-bin/openidea-server target/debug/
|
||||
|
||||
- uses: pnpm/action-setup@v4
|
||||
- uses: pnpm/action-setup@v5
|
||||
with: { version: 11 }
|
||||
- uses: actions/setup-node@v4
|
||||
with: { node-version: 22, cache: pnpm }
|
||||
- uses: actions/setup-node@v5
|
||||
with:
|
||||
node-version: 22
|
||||
cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }}
|
||||
package-manager-cache: ${{ runner.environment != 'self-hosted' }}
|
||||
- if: matrix.language == 'typescript'
|
||||
run: npm install --global "@vtsls/language-server@$VTSLS" "typescript@$TYPESCRIPT"
|
||||
|
||||
# The smoke builds the c-app fixture and debugs it with GDB's own DAP interpreter.
|
||||
# The smoke checks C/C++ with clangd and debugs c-app with GDB's own DAP interpreter (GDB 14+).
|
||||
- if: matrix.language == 'c' || matrix.language == 'cpp'
|
||||
shell: bash
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y gdb
|
||||
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
|
||||
|
||||
- if: matrix.language == 'python'
|
||||
uses: actions/setup-python@v5
|
||||
@@ -217,6 +254,7 @@ 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"
|
||||
|
||||
+5
-7
@@ -33,14 +33,12 @@ target/
|
||||
test-results/
|
||||
playwright-report/
|
||||
|
||||
# Local AI agent files. Shared skills live in .agents/skills; .claude/skills links to them.
|
||||
# Local AI agent files
|
||||
AGENTS.md
|
||||
CLAUDE.md
|
||||
CLAUDE.local.md
|
||||
.claude/*
|
||||
!.claude/skills/
|
||||
.claude/skills/*
|
||||
!.claude/skills/verify
|
||||
!.claude/skills/issue-fix
|
||||
!.claude/skills/eval
|
||||
.agents/
|
||||
.claude/
|
||||
|
||||
# Local reference screenshots
|
||||
pycharm-screenshots/
|
||||
@@ -147,6 +147,12 @@
|
||||
"prefer-rest-params": "error",
|
||||
"prefer-spread": "error"
|
||||
}
|
||||
},
|
||||
{
|
||||
"files": ["evals/**/*.ts", "perf/**/*.ts", "smoke/**/*.ts"],
|
||||
"rules": {
|
||||
"no-await-in-loop": "error"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,152 +0,0 @@
|
||||
# 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
|
||||
|
||||
- Optional: `mise install` provisions the contributor toolchain; `mise tasks` lists the task aliases.
|
||||
See [Development setup](docs/en/contribute/setup.mdx). The direct commands below still work without mise.
|
||||
- `pnpm tauri dev` — run the app with worktree isolation. Use Node 22.22.2 or later on the 22.x line.
|
||||
`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.
|
||||
- `pnpm dogfood:local [--build-only]` (or `mise run dogfood:local`) — build and locally install the grey-icon dogfood desktop app sharing release settings and data.
|
||||
- `pnpm dogfood:remote <remote_name> [--restart | --no-restart] [--clean]` (or `mise run dogfood:remote <remote_name>`) — sync backend sources to a host from **Tools › SSH Configurations**, build `openidea-server`, and stage it for Remote Development.
|
||||
- `pnpm dogfood:all <remote_name> [--restart | --no-restart]` (or `mise run dogfood:all <remote_name>`) — run `dogfood:local` and `dogfood:remote <remote_name>` in parallel.
|
||||
- `cargo nextest run --workspace` (or `cargo test`), `cargo clippy --workspace --all-targets -- -D warnings`, `cargo fmt --all`.
|
||||
- `cargo test -p ide-host --test language_smoke -- --ignored --exact <language>` — code intelligence
|
||||
on `fixtures/` with that language's real server installed (CI: `Language smoke`, pinned versions).
|
||||
- `pnpm smoke smoke/run.test.ts -t <language>` — run and test that language's fixture through the
|
||||
run store and a real `openidea-server` (build it first: `cargo build -p ide-host --bin openidea-server`).
|
||||
- `pnpm smoke smoke/debug.test.ts -t <language>` — debug that fixture's entry point the same way, with
|
||||
the debugger the IDE installs (on macOS, CodeLLDB and Delve may need Developer Mode:
|
||||
`sudo DevToolsSecurity -enable`).
|
||||
- `pnpm test`, `pnpm e2e`, `pnpm lint`, `pnpm format:check`, `pnpm knip`, `pnpm typecheck`,
|
||||
`pnpm gen:bindings`.
|
||||
- `pnpm perf` (UI interaction latency / frames / leaks), `pnpm perf:rust` (criterion
|
||||
benches vs budgets). Budgets: `perf/budgets.json`.
|
||||
- `pnpm eval [--only <id>] [--runs n] [--save-baseline]` — Java code intelligence (navigation,
|
||||
usages, gutter markers) in the production workbench against a release `openidea-server` and
|
||||
jdtls: time to feedback / first result / complete, results vs `evals/<language>/golden/`.
|
||||
Report: `target/eval/report.json`. Goldens and `evals/budgets.json` are changed by people only.
|
||||
Tool versions: `.github/tool-versions.env` (shared with Language smoke).
|
||||
- `pnpm release:prepare <version>` — the release commit's changes: app version everywhere,
|
||||
`Cargo.lock`, and the plugin API snapshot when `wit/` moved to a new version.
|
||||
|
||||
## Before opening a PR
|
||||
|
||||
Run what CI runs for the parts you touched:
|
||||
|
||||
- Rust: `cargo fmt --all --check`, `cargo clippy --workspace --all-targets -- -D warnings`,
|
||||
`cargo nextest run --workspace`. After changing IPC types, run `pnpm gen:bindings` and
|
||||
commit `src/bindings.ts`; CI fails if it differs.
|
||||
- Frontend: `pnpm typecheck`, `pnpm lint`, `pnpm format:check`, `pnpm knip`, `pnpm test`,
|
||||
`pnpm build`, and `pnpm e2e` for UI flows.
|
||||
- UI or runtime behaviour: verify in the running app (`.agents/skills/verify`).
|
||||
|
||||
## Pitfalls
|
||||
|
||||
- Run a subset of frontend tests with `pnpm vitest run <path>`. `pnpm test -- <path>` ignores
|
||||
the filter and runs the whole suite, which takes several minutes.
|
||||
- Don't run clippy while iterating: `pnpm tauri dev` compiles anyway. Run
|
||||
`cargo fmt --all` + `cargo clippy -p <crate> --all-targets -- -D warnings` once, right
|
||||
before committing. A cold build cache can take around 5 minutes. Run long checks one at
|
||||
a time, not chained in one shell call that may hit the 10-minute tool timeout.
|
||||
- `pnpm tauri dev` does a full debug build. Clippy only checks the code, so a passing clippy
|
||||
doesn't make the first launch fast.
|
||||
|
||||
## Parallel worktrees
|
||||
|
||||
Several worktrees can be developed and run side by side.
|
||||
|
||||
- Create one per task: `git worktree add ../<name> -b <branch> origin/main`, then
|
||||
`pnpm install` in it.
|
||||
- Launch with `pnpm tauri dev` / `pnpm dev:app`, not the raw `pnpm exec tauri dev` CLI. The
|
||||
wrapper starts Vite on a worktree-derived port (advancing if occupied), passes its actual
|
||||
URL to Tauri, and reports an existing launcher instead of starting another for the same
|
||||
worktree. HMR uses the Vite port.
|
||||
- Debug app identity, data, settings, logs and single-instance scope follow the canonical
|
||||
worktree path captured at build time, independent of launch cwd. Launching the same debug
|
||||
binary again focuses its existing instance and forwards its path argument. Different
|
||||
worktrees and the installed release can coexist. `--release` uses normal release identity
|
||||
and bypasses the development wrapper.
|
||||
- MCP bridge ports are dynamic (9223–9322). Use `pnpm dev:status`, connect to the reported
|
||||
port, verify identifier/cwd, and pass `appIdentifier: <port>` explicitly. Do not assume the
|
||||
default MCP session belongs to this worktree.
|
||||
- Keep each worktree's Cargo output directory separate; do not point `CARGO_TARGET_DIR` or
|
||||
`target` symlinks at a shared directory.
|
||||
- Each worktree's first build is cold (several minutes) and `cargo build` output takes
|
||||
around 9 GB; tests, clippy and incremental builds add more. Avoid running several heavy builds on one machine at the same time.
|
||||
- Stop only processes started for the current worktree/session. Never use broad
|
||||
process-name kills such as `pkill openidea`.
|
||||
- When done: stop that worktree's app and dev session, delete its build output, then
|
||||
`git worktree remove ../<name>`.
|
||||
@@ -1,7 +1,6 @@
|
||||
# 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
+49
-48
@@ -4144,7 +4144,7 @@ checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
|
||||
|
||||
[[package]]
|
||||
name = "ide-agent"
|
||||
version = "0.1.50"
|
||||
version = "0.1.51"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
@@ -4172,7 +4172,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-analysis"
|
||||
version = "0.1.50"
|
||||
version = "0.1.51"
|
||||
dependencies = [
|
||||
"ast-grep-core",
|
||||
"ide-core",
|
||||
@@ -4184,7 +4184,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-android"
|
||||
version = "0.1.50"
|
||||
version = "0.1.51"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"serde",
|
||||
@@ -4194,7 +4194,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-build"
|
||||
version = "0.1.50"
|
||||
version = "0.1.51"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"chardetng",
|
||||
@@ -4212,7 +4212,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-cli"
|
||||
version = "0.1.50"
|
||||
version = "0.1.51"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"serde",
|
||||
@@ -4226,7 +4226,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-clipboard"
|
||||
version = "0.1.50"
|
||||
version = "0.1.51"
|
||||
dependencies = [
|
||||
"gtk",
|
||||
"objc2 0.6.5",
|
||||
@@ -4237,7 +4237,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-command"
|
||||
version = "0.1.50"
|
||||
version = "0.1.51"
|
||||
dependencies = [
|
||||
"heck 0.5.0",
|
||||
"proc-macro2",
|
||||
@@ -4248,7 +4248,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-core"
|
||||
version = "0.1.50"
|
||||
version = "0.1.51"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"dunce",
|
||||
@@ -4266,7 +4266,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-coverage"
|
||||
version = "0.1.50"
|
||||
version = "0.1.51"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-run",
|
||||
@@ -4279,7 +4279,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-dap"
|
||||
version = "0.1.50"
|
||||
version = "0.1.51"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"futures",
|
||||
@@ -4308,7 +4308,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-db"
|
||||
version = "0.1.50"
|
||||
version = "0.1.51"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"bb8",
|
||||
@@ -4345,7 +4345,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-docker"
|
||||
version = "0.1.50"
|
||||
version = "0.1.51"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"serde",
|
||||
@@ -4358,7 +4358,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-drag-out"
|
||||
version = "0.1.50"
|
||||
version = "0.1.51"
|
||||
dependencies = [
|
||||
"gtk",
|
||||
"objc2 0.6.5",
|
||||
@@ -4372,7 +4372,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-extension"
|
||||
version = "0.1.50"
|
||||
version = "0.1.51"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
@@ -4392,7 +4392,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-flutter"
|
||||
version = "0.1.50"
|
||||
version = "0.1.51"
|
||||
dependencies = [
|
||||
"ide-android",
|
||||
"ide-core",
|
||||
@@ -4403,7 +4403,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-fonts"
|
||||
version = "0.1.50"
|
||||
version = "0.1.51"
|
||||
dependencies = [
|
||||
"objc2-core-foundation",
|
||||
"objc2-core-text",
|
||||
@@ -4415,7 +4415,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-github"
|
||||
version = "0.1.50"
|
||||
version = "0.1.51"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-vcs",
|
||||
@@ -4428,7 +4428,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-heap"
|
||||
version = "0.1.50"
|
||||
version = "0.1.51"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"ide-core",
|
||||
@@ -4447,7 +4447,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-host"
|
||||
version = "0.1.50"
|
||||
version = "0.1.51"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
@@ -4515,6 +4515,7 @@ dependencies = [
|
||||
"toml 0.9.12+spec-1.1.0",
|
||||
"tracing",
|
||||
"tracing-subscriber",
|
||||
"url",
|
||||
"uuid",
|
||||
"windows-sys 0.61.2",
|
||||
"zip",
|
||||
@@ -4522,7 +4523,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-http"
|
||||
version = "0.1.50"
|
||||
version = "0.1.51"
|
||||
dependencies = [
|
||||
"hyper-util",
|
||||
"ide-core",
|
||||
@@ -4541,7 +4542,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-index"
|
||||
version = "0.1.50"
|
||||
version = "0.1.51"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"criterion",
|
||||
@@ -4564,7 +4565,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jdwp"
|
||||
version = "0.1.50"
|
||||
version = "0.1.51"
|
||||
dependencies = [
|
||||
"ide-jvm-inspect",
|
||||
"proptest",
|
||||
@@ -4576,7 +4577,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jsonrpc"
|
||||
version = "0.1.50"
|
||||
version = "0.1.51"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"ide-core",
|
||||
@@ -4592,7 +4593,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jvm-attach"
|
||||
version = "0.1.50"
|
||||
version = "0.1.51"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"tempfile",
|
||||
@@ -4601,7 +4602,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jvm-inspect"
|
||||
version = "0.1.50"
|
||||
version = "0.1.51"
|
||||
dependencies = [
|
||||
"futures",
|
||||
"serde",
|
||||
@@ -4612,7 +4613,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-language"
|
||||
version = "0.1.50"
|
||||
version = "0.1.51"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"criterion",
|
||||
@@ -4671,7 +4672,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-lsp"
|
||||
version = "0.1.50"
|
||||
version = "0.1.51"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"dunce",
|
||||
@@ -4700,7 +4701,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-mcp"
|
||||
version = "0.1.50"
|
||||
version = "0.1.51"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"dunce",
|
||||
@@ -4719,7 +4720,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-notebook"
|
||||
version = "0.1.50"
|
||||
version = "0.1.51"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-vfs",
|
||||
@@ -4740,7 +4741,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-plugin"
|
||||
version = "0.1.50"
|
||||
version = "0.1.51"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -4762,7 +4763,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-profiler"
|
||||
version = "0.1.50"
|
||||
version = "0.1.51"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-jvm-attach",
|
||||
@@ -4776,7 +4777,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-remote"
|
||||
version = "0.1.50"
|
||||
version = "0.1.51"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"futures",
|
||||
@@ -4796,7 +4797,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-run"
|
||||
version = "0.1.50"
|
||||
version = "0.1.51"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"encoding_rs",
|
||||
@@ -4820,7 +4821,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-scaffold"
|
||||
version = "0.1.50"
|
||||
version = "0.1.51"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-tools",
|
||||
@@ -4836,7 +4837,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-sdk"
|
||||
version = "0.1.50"
|
||||
version = "0.1.51"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"dirs 6.0.0",
|
||||
@@ -4862,7 +4863,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-search"
|
||||
version = "0.1.50"
|
||||
version = "0.1.51"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"encoding_rs",
|
||||
@@ -4883,7 +4884,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-spell"
|
||||
version = "0.1.50"
|
||||
version = "0.1.51"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"parking_lot",
|
||||
@@ -4896,7 +4897,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-ssh"
|
||||
version = "0.1.50"
|
||||
version = "0.1.51"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"flate2",
|
||||
@@ -4921,7 +4922,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-streams"
|
||||
version = "0.1.50"
|
||||
version = "0.1.51"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-language",
|
||||
@@ -4934,7 +4935,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-syntax"
|
||||
version = "0.1.50"
|
||||
version = "0.1.51"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-language",
|
||||
@@ -4949,7 +4950,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-terminal"
|
||||
version = "0.1.50"
|
||||
version = "0.1.51"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"libc",
|
||||
@@ -4963,7 +4964,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-text"
|
||||
version = "0.1.50"
|
||||
version = "0.1.51"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"ide-core",
|
||||
@@ -4976,7 +4977,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-tools"
|
||||
version = "0.1.50"
|
||||
version = "0.1.51"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"hex",
|
||||
@@ -4997,7 +4998,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-vcs"
|
||||
version = "0.1.50"
|
||||
version = "0.1.51"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -5019,7 +5020,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-vfs"
|
||||
version = "0.1.50"
|
||||
version = "0.1.51"
|
||||
dependencies = [
|
||||
"chardetng",
|
||||
"dunce",
|
||||
@@ -5046,7 +5047,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-web"
|
||||
version = "0.1.50"
|
||||
version = "0.1.51"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"ide-core",
|
||||
@@ -5062,7 +5063,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-workspace"
|
||||
version = "0.1.50"
|
||||
version = "0.1.51"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -6691,7 +6692,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "openidea"
|
||||
version = "0.1.50"
|
||||
version = "0.1.51"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
|
||||
+1
-1
@@ -5,7 +5,7 @@ members = ["crates/*", "src-tauri"]
|
||||
exclude = ["sdk", "plugins"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.1.50"
|
||||
version = "0.1.51"
|
||||
edition = "2024"
|
||||
rust-version = "1.96"
|
||||
license = "Apache-2.0"
|
||||
|
||||
+329
-80
@@ -44,7 +44,9 @@ use ide_vcs::Repo;
|
||||
use parking_lot::{Mutex, RwLock};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Value, json};
|
||||
use std::collections::hash_map::DefaultHasher;
|
||||
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet, VecDeque};
|
||||
use std::hash::Hasher;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering};
|
||||
use std::sync::{Arc, Weak};
|
||||
@@ -68,6 +70,8 @@ pub type GitExecutableHook = Arc<dyn Fn() -> Option<PathBuf> + Send + Sync>;
|
||||
|
||||
/// Entry changes are batched for this long before they are sent.
|
||||
const FLUSH_DELAY: Duration = Duration::from_millis(40);
|
||||
/// A save asked for with `persist_soon` waits this long for others to join it.
|
||||
const SAVE_DELAY: Duration = Duration::from_millis(250);
|
||||
/// Updates that arrive this late after `session/load` returns are still replayed history.
|
||||
const REPLAY_GRACE: Duration = Duration::from_millis(300);
|
||||
/// Notifications are delivered on their own thread: the last `session/update`s of a turn
|
||||
@@ -545,8 +549,11 @@ struct Task {
|
||||
/// Unanswered permission requests: where to send the chosen option id.
|
||||
permissions: Mutex<HashMap<u32, std::sync::mpsc::Sender<Option<String>>>>,
|
||||
next_permission: AtomicU32,
|
||||
/// Set while `session/load` replays history we already have.
|
||||
/// Set while `session/load` replays the session's history.
|
||||
replaying: AtomicBool,
|
||||
/// The task has a session but none of its history (an imported session): the next load's
|
||||
/// replay becomes the task's history instead of being dropped.
|
||||
adopting_replay: AtomicBool,
|
||||
/// The saved session failed to load and the user was told: the next start opens a new one.
|
||||
start_fresh: AtomicBool,
|
||||
/// The current turn is being cancelled to send the first queued message right away.
|
||||
@@ -568,12 +575,24 @@ struct Task {
|
||||
/// Settings already sent this session (`(option, value)`), so a refusal is not retried.
|
||||
config_sent: Mutex<HashSet<(String, String)>>,
|
||||
dirty: Mutex<BTreeSet<(Session, usize)>>,
|
||||
/// How much of each session's streaming message was last sent, so the next flush sends the rest.
|
||||
streamed: Mutex<HashMap<Session, Sent>>,
|
||||
/// What was last sent of the entries that stream, so the next flush sends the rest.
|
||||
streamed: Mutex<Streamed>,
|
||||
flush_scheduled: AtomicBool,
|
||||
stderr: Mutex<VecDeque<String>>,
|
||||
/// Set by `delete`; held while saving.
|
||||
deleted: Mutex<bool>,
|
||||
/// Saves asked for (see `persist`); the file holds those up to `file.saved`.
|
||||
saves_asked: AtomicU64,
|
||||
save_scheduled: AtomicBool,
|
||||
/// Held while the file is written, so saves land in order and none follows a delete.
|
||||
file: Mutex<SavedFile>,
|
||||
}
|
||||
|
||||
/// What the task's file on disk holds.
|
||||
#[derive(Default)]
|
||||
struct SavedFile {
|
||||
/// Set by `delete`: nothing is written any more.
|
||||
deleted: bool,
|
||||
/// The saves asked for that the file holds.
|
||||
saved: u64,
|
||||
}
|
||||
|
||||
impl AgentManager {
|
||||
@@ -913,7 +932,7 @@ impl AgentManager {
|
||||
out
|
||||
}
|
||||
|
||||
/// Imports an external session as a task: its first turn loads and replays it (#312).
|
||||
/// Imports an external session as a task, loading it in the background to show its history (#312).
|
||||
pub fn import_session(&self, provider: &str, session_id: &str) -> IdeResult<AgentTask> {
|
||||
if !matches!(provider, "claude" | "codex") {
|
||||
return Err(IdeError::invalid(format!("cannot import {provider} sessions")));
|
||||
@@ -978,6 +997,13 @@ impl AgentManager {
|
||||
self.tasks.write().insert(task.id.clone(), handle.clone());
|
||||
handle.emit_task();
|
||||
handle.persist();
|
||||
// Loading the session replays its history into the task, so it shows before a first message.
|
||||
self.shared.runtime.spawn(async move {
|
||||
match handle.ensure_session().await {
|
||||
Ok(_) => handle.release_when_idle(),
|
||||
Err(e) => tracing::info!("agent task {}: loading the imported session failed: {e}", handle.id),
|
||||
}
|
||||
});
|
||||
Ok(task)
|
||||
}
|
||||
|
||||
@@ -1806,7 +1832,7 @@ impl AgentManager {
|
||||
// A copy of the task (a fork) may work in the same worktree.
|
||||
let shared = self.tasks.read().values().any(|t| t.id != id && t.state.lock().task.cwd.0 == cwd);
|
||||
self.tasks.write().remove(id);
|
||||
*task.deleted.lock() = true;
|
||||
task.file.lock().deleted = true;
|
||||
let _ = std::fs::remove_file(self.shared.paths.store_dir.join(format!("{id}.json")));
|
||||
let _ = std::fs::remove_dir_all(task.turn_dir());
|
||||
skills::remove_farm(&self.shared.paths.store_dir, id);
|
||||
@@ -2196,6 +2222,7 @@ impl Task {
|
||||
fn restore(file: TaskFile, shared: Arc<Shared>) -> Arc<Self> {
|
||||
let mut task = file.task;
|
||||
config::add_client_options(&task.provider, &mut task.config);
|
||||
let adopt = file.entries.is_empty() && file.session_id.is_some();
|
||||
let conversation = Conversation::restore(file.entries, file.subagents);
|
||||
let mut wanted = file.wanted;
|
||||
let pending_model = file.pending_switch.or_else(|| {
|
||||
@@ -2242,6 +2269,7 @@ impl Task {
|
||||
permissions: Mutex::new(HashMap::new()),
|
||||
next_permission: AtomicU32::new(1),
|
||||
replaying: AtomicBool::new(false),
|
||||
adopting_replay: AtomicBool::new(adopt),
|
||||
start_fresh: AtomicBool::new(false),
|
||||
send_now: AtomicBool::new(false),
|
||||
cancel_pending: AtomicBool::new(false),
|
||||
@@ -2252,10 +2280,12 @@ impl Task {
|
||||
skills_reload_pending: AtomicBool::new(false),
|
||||
config_sent: Mutex::new(HashSet::new()),
|
||||
dirty: Mutex::new(BTreeSet::new()),
|
||||
streamed: Mutex::new(HashMap::new()),
|
||||
streamed: Mutex::new(Streamed::default()),
|
||||
flush_scheduled: AtomicBool::new(false),
|
||||
stderr: Mutex::new(VecDeque::new()),
|
||||
deleted: Mutex::new(false),
|
||||
saves_asked: AtomicU64::new(0),
|
||||
save_scheduled: AtomicBool::new(false),
|
||||
file: Mutex::new(SavedFile::default()),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -2277,7 +2307,7 @@ impl Task {
|
||||
}
|
||||
|
||||
/// Records the checkout as a turn starts: what the turn's changes are compared with.
|
||||
async fn checkout_before_turn(&self) {
|
||||
async fn checkout_before_turn(self: &Arc<Self>) {
|
||||
let (cwd, previous, dir) = self.last_turn();
|
||||
let turn = match vcs(&self.shared, move || worktree::start_turn(&cwd, &dir, previous.as_deref())).await {
|
||||
Ok(turn) => Some(Arc::new(turn)),
|
||||
@@ -2287,12 +2317,12 @@ impl Task {
|
||||
}
|
||||
};
|
||||
self.state.lock().turn = turn;
|
||||
self.persist();
|
||||
self.persist_soon();
|
||||
}
|
||||
|
||||
/// Records the files that changed in the checkout while the turn ran: the turn's, and in
|
||||
/// the project's own checkout also the task's.
|
||||
async fn record_turn_changes(&self) {
|
||||
async fn record_turn_changes(self: &Arc<Self>) {
|
||||
let (cwd, turn, _) = self.last_turn();
|
||||
let Some(turn) = turn else { return };
|
||||
let start = turn.clone();
|
||||
@@ -2310,7 +2340,7 @@ impl Task {
|
||||
}
|
||||
s.turn = Some(Arc::new(worktree::TurnStart { changed: Some(all), ..(*turn).clone() }));
|
||||
}
|
||||
self.persist();
|
||||
self.persist_soon();
|
||||
}
|
||||
|
||||
fn base(&self) -> worktree::TaskBase {
|
||||
@@ -2391,19 +2421,29 @@ impl Task {
|
||||
}
|
||||
}
|
||||
|
||||
fn change_status(&self, status: AgentStatus, error: Option<String>) {
|
||||
let mut s = self.state.lock();
|
||||
s.task.retry = None;
|
||||
s.task.status = status;
|
||||
s.task.error = error;
|
||||
s.task.updated_ms = now_ms();
|
||||
}
|
||||
|
||||
fn set_status(&self, status: AgentStatus, error: Option<String>) {
|
||||
{
|
||||
let mut s = self.state.lock();
|
||||
s.task.retry = None;
|
||||
s.task.status = status;
|
||||
s.task.error = error;
|
||||
s.task.updated_ms = now_ms();
|
||||
}
|
||||
self.change_status(status, error);
|
||||
// Saved first: whoever reacts to the status change finds it on disk.
|
||||
self.persist();
|
||||
self.emit_task();
|
||||
}
|
||||
|
||||
/// `Running` again after the agent started or a request was answered: the turn's next stop
|
||||
/// saves what changed, and the turn start saved the message that began it.
|
||||
fn resume_running(self: &Arc<Self>) {
|
||||
self.change_status(AgentStatus::Running, None);
|
||||
self.persist_soon();
|
||||
self.emit_task();
|
||||
}
|
||||
|
||||
fn emit_attention(&self, reason: AgentAttentionReason) {
|
||||
let n = self.shared.attention_seq.fetch_add(1, Ordering::Relaxed);
|
||||
let tag = match reason {
|
||||
@@ -2426,15 +2466,40 @@ impl Task {
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes the task file, with everything changed so far, before it returns.
|
||||
fn persist(&self) {
|
||||
// Held from snapshot to rename, so saves land in order and none follows a delete.
|
||||
let deleted = self.deleted.lock();
|
||||
if *deleted {
|
||||
self.saves_asked.fetch_add(1, Ordering::AcqRel);
|
||||
self.save();
|
||||
}
|
||||
|
||||
/// Has the task file written within `SAVE_DELAY`, once for every change asked for by then:
|
||||
/// for what the next `persist` (the turn's next stop, shutdown) saves anyway, and a crash
|
||||
/// before it costs at most what changed in this window.
|
||||
fn persist_soon(self: &Arc<Self>) {
|
||||
self.saves_asked.fetch_add(1, Ordering::AcqRel);
|
||||
if !self.save_scheduled.swap(true, Ordering::AcqRel) {
|
||||
let task = self.clone();
|
||||
self.shared.runtime.spawn(async move {
|
||||
tokio::time::sleep(SAVE_DELAY).await;
|
||||
task.save_scheduled.store(false, Ordering::Release);
|
||||
let _ = tokio::task::spawn_blocking(move || task.save()).await;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes the file unless it holds every save asked for. The state is locked only to copy
|
||||
/// it: turning a long transcript into JSON and writing it is no reader's wait.
|
||||
fn save(&self) {
|
||||
// Held from the copy to the rename, so saves land in order and none follows a delete.
|
||||
let mut file = self.file.lock();
|
||||
// Read before the copy: whatever was asked for up to now is in it.
|
||||
let asked = self.saves_asked.load(Ordering::Acquire);
|
||||
if file.deleted || file.saved >= asked {
|
||||
return;
|
||||
}
|
||||
let bytes = {
|
||||
let copy = {
|
||||
let s = self.state.lock();
|
||||
serde_json::to_vec(&TaskFile {
|
||||
TaskFile {
|
||||
task: s.task.clone(),
|
||||
session_id: s.session_id.clone(),
|
||||
entries: s.conversation.main.entries.clone(),
|
||||
@@ -2448,11 +2513,14 @@ impl Task {
|
||||
subagents: s.conversation.saved_subagents(),
|
||||
pending_rollback: s.pending_rollback,
|
||||
title_renamed: s.title_renamed,
|
||||
})
|
||||
}
|
||||
};
|
||||
let bytes = serde_json::to_vec(©);
|
||||
drop(copy);
|
||||
let path = self.shared.paths.store_dir.join(format!("{}.json", self.id));
|
||||
if let Err(e) = bytes.map_err(|e| e.to_string()).and_then(|b| write_file(&path, &b)) {
|
||||
tracing::warn!("saving agent task {}: {e}", self.id);
|
||||
match bytes.map_err(|e| e.to_string()).and_then(|b| write_file(&path, &b)) {
|
||||
Ok(()) => file.saved = asked,
|
||||
Err(e) => tracing::warn!("saving agent task {}: {e}", self.id),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2477,7 +2545,7 @@ impl Task {
|
||||
.into_iter()
|
||||
.filter_map(|(subagent, i)| {
|
||||
let entry = s.conversation.timeline(&subagent)?.entries.get(i)?;
|
||||
Some(entry_event(&self.id, &mut streamed, subagent, i, entry))
|
||||
entry_event(&self.id, &mut streamed, subagent, i, entry)
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
@@ -2513,6 +2581,19 @@ impl Task {
|
||||
self.persist();
|
||||
}
|
||||
|
||||
/// Removes the task's own entries and returns them.
|
||||
fn take_entries(self: &Arc<Self>) -> Vec<AgentEntry> {
|
||||
let entries = {
|
||||
let mut s = self.state.lock();
|
||||
let entries = s.conversation.main.entries.clone();
|
||||
s.conversation.truncate(0);
|
||||
entries
|
||||
};
|
||||
self.streamed.lock().clear();
|
||||
self.shared.emit(AgentEvent::Truncated { task: self.id.clone(), length: 0 });
|
||||
entries
|
||||
}
|
||||
|
||||
fn push_entry(self: &Arc<Self>, entry: AgentEntry) -> usize {
|
||||
let i = self.state.lock().conversation.main.push(entry);
|
||||
self.mark_dirty([(None, i)]);
|
||||
@@ -2869,7 +2950,7 @@ impl Task {
|
||||
if self.cancel_pending.load(Ordering::Acquire) {
|
||||
return Ok("cancelled".into());
|
||||
}
|
||||
self.set_status(AgentStatus::Running, None);
|
||||
self.resume_running();
|
||||
if !prompt.images.is_empty() && !live.capabilities.images {
|
||||
return Err(Failure::from("This agent can't read images.".to_owned()));
|
||||
}
|
||||
@@ -3105,12 +3186,27 @@ impl Task {
|
||||
});
|
||||
}
|
||||
if let (Some(id), true, false) = (saved, can_load, start_fresh) {
|
||||
// The replay goes before what this turn already showed (the user's message).
|
||||
let shown = self.adopts_replay().then(|| self.take_entries());
|
||||
self.replaying.store(true, Ordering::Release);
|
||||
let mut params = session_params(&cwd_s, &mcp_servers, skills_delivery.as_ref(), &roots);
|
||||
params["sessionId"] = json!(&id);
|
||||
let loaded = self.request_with_auth(&peer, &init, &mut tried_auth, "session/load", params).await;
|
||||
tokio::time::sleep(REPLAY_GRACE).await;
|
||||
self.replaying.store(false, Ordering::Release);
|
||||
if let Some(shown) = shown {
|
||||
if loaded.is_ok() {
|
||||
self.adopting_replay.store(false, Ordering::Release);
|
||||
let changed = self.state.lock().conversation.end_turn(None);
|
||||
self.mark_dirty(changed);
|
||||
} else {
|
||||
// A failed load may still have replayed part of it.
|
||||
self.take_entries();
|
||||
}
|
||||
for entry in shown {
|
||||
self.push_entry(entry);
|
||||
}
|
||||
}
|
||||
match loaded {
|
||||
Ok(v) => session = Some((id, v)),
|
||||
// Not silently: a new session would lose the conversation and replace the saved id.
|
||||
@@ -3332,7 +3428,7 @@ impl Task {
|
||||
s.task.background.clear();
|
||||
*client.opening_config.lock() = None;
|
||||
}
|
||||
self.persist();
|
||||
self.persist_soon();
|
||||
self.emit_task();
|
||||
stop_on_err.0 = None;
|
||||
Ok(Live {
|
||||
@@ -3402,7 +3498,7 @@ impl Task {
|
||||
}
|
||||
}
|
||||
task.approve_pending();
|
||||
task.persist();
|
||||
task.persist_soon();
|
||||
task.emit_task();
|
||||
});
|
||||
}
|
||||
@@ -3428,7 +3524,7 @@ impl Task {
|
||||
let kind = update.get("sessionUpdate").and_then(Value::as_str).unwrap_or_default();
|
||||
// A subagent's title, settings and usage are its own, not the task's.
|
||||
if self.state.lock().conversation.owner(session).is_some() {
|
||||
if !SESSION_STATE.contains(&kind) && !self.replaying.load(Ordering::Acquire) {
|
||||
if !SESSION_STATE.contains(&kind) && (!self.replaying.load(Ordering::Acquire) || self.adopts_replay()) {
|
||||
self.apply(session, kind, update);
|
||||
}
|
||||
return;
|
||||
@@ -3464,7 +3560,7 @@ impl Task {
|
||||
std::mem::replace(&mut s.task.stats.compressions, depth) != depth
|
||||
};
|
||||
if changed {
|
||||
self.persist();
|
||||
self.persist_soon();
|
||||
self.emit_task();
|
||||
}
|
||||
}
|
||||
@@ -3482,11 +3578,11 @@ impl Task {
|
||||
if (user_named || !s.title_renamed) && s.task.title != title {
|
||||
s.task.title = title.to_owned();
|
||||
drop(s);
|
||||
self.persist();
|
||||
self.persist_soon();
|
||||
self.emit_task();
|
||||
} else if flag_changed {
|
||||
drop(s);
|
||||
self.persist();
|
||||
self.persist_soon();
|
||||
self.emit_task();
|
||||
}
|
||||
}
|
||||
@@ -3532,7 +3628,7 @@ impl Task {
|
||||
};
|
||||
self.shared.remember(&provider, Some(&config), Some(&commands), model.as_deref());
|
||||
if kind != "usage_update" {
|
||||
self.persist();
|
||||
self.persist_soon();
|
||||
}
|
||||
self.emit_task();
|
||||
if kind == "config_option_update" && !self.replaying.load(Ordering::Acquire) {
|
||||
@@ -3544,6 +3640,13 @@ impl Task {
|
||||
return;
|
||||
}
|
||||
if self.replaying.load(Ordering::Acquire) {
|
||||
if self.adopts_replay() {
|
||||
if kind == "user_message_chunk" {
|
||||
self.adopt_user_chunk(update);
|
||||
} else {
|
||||
self.apply(session, kind, update);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
// The first sign that the agent took the prompt: a stop sent before it is repeated.
|
||||
@@ -3556,14 +3659,52 @@ impl Task {
|
||||
self.apply(session, kind, update);
|
||||
}
|
||||
|
||||
fn adopts_replay(&self) -> bool {
|
||||
self.adopting_replay.load(Ordering::Acquire)
|
||||
}
|
||||
|
||||
/// A user message of the adopted history: live turns show the user's own, so only a replay's count.
|
||||
fn adopt_user_chunk(self: &Arc<Self>, update: &Value) {
|
||||
let content = update.get("content");
|
||||
let image = content.filter(|c| c.get("type").and_then(Value::as_str) == Some("image")).map(|c| AgentImage {
|
||||
mime_type: c.get("mimeType").and_then(Value::as_str).unwrap_or_default().to_owned(),
|
||||
data: c.get("data").and_then(Value::as_str).unwrap_or_default().to_owned(),
|
||||
name: None,
|
||||
});
|
||||
let text = timeline::content_text(content).unwrap_or_default();
|
||||
if text.is_empty() && image.is_none() {
|
||||
return;
|
||||
}
|
||||
let changed = {
|
||||
let mut s = self.state.lock();
|
||||
let entries = &mut s.conversation.main.entries;
|
||||
// The chunks of one message arrive in a row.
|
||||
if let Some(AgentEntry::User { text: shown, images, .. }) = entries.last_mut() {
|
||||
shown.push_str(&text);
|
||||
images.extend(image);
|
||||
entries.len() - 1
|
||||
} else {
|
||||
s.conversation.main.push(AgentEntry::User {
|
||||
text,
|
||||
attachments: Vec::new(),
|
||||
images: image.into_iter().collect(),
|
||||
sent_ms: None,
|
||||
done_ms: None,
|
||||
steered: false,
|
||||
})
|
||||
}
|
||||
};
|
||||
self.mark_dirty([(None, changed)]);
|
||||
}
|
||||
|
||||
fn apply(self: &Arc<Self>, session: Option<&str>, kind: &str, update: &Value) {
|
||||
// Output again: the retried request went through.
|
||||
self.set_retry(None);
|
||||
let applied = self.state.lock().conversation.apply(session, update, now_ms());
|
||||
self.mark_dirty(applied);
|
||||
// A subagent can start or finish after the turn that started it: saved right away.
|
||||
// A subagent can start or finish after the turn that started it: nothing else saves it then.
|
||||
if matches!(kind, "subagent_update" | "user_question") {
|
||||
self.persist();
|
||||
self.persist_soon();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3746,6 +3887,7 @@ impl Task {
|
||||
}
|
||||
|
||||
/// Records the answer to the request at `entry`; the turn runs on once nothing else waits.
|
||||
/// Saved before it returns, which is before the agent is told: a restart after that keeps the answer.
|
||||
fn settle(self: &Arc<Self>, entry: usize, chosen: String) {
|
||||
{
|
||||
let mut s = self.state.lock();
|
||||
@@ -3755,8 +3897,13 @@ impl Task {
|
||||
}
|
||||
self.mark_dirty([(None, entry)]);
|
||||
let still_asking = !self.permissions.lock().is_empty();
|
||||
if !still_asking && self.state.lock().task.status == AgentStatus::NeedsInput {
|
||||
self.set_status(AgentStatus::Running, None);
|
||||
let resumed = !still_asking && self.state.lock().task.status == AgentStatus::NeedsInput;
|
||||
if resumed {
|
||||
self.change_status(AgentStatus::Running, None);
|
||||
}
|
||||
self.persist();
|
||||
if resumed {
|
||||
self.emit_task();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3840,7 +3987,7 @@ impl Handler for Client {
|
||||
&& let Some(message) = params.get("message").and_then(Value::as_str).filter(|s| !s.trim().is_empty())
|
||||
{
|
||||
task.push_entry(AgentEntry::Error { message: message.to_owned() });
|
||||
task.persist();
|
||||
task.persist_soon();
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -4245,11 +4392,24 @@ fn file_uri(path: &Path) -> String {
|
||||
out
|
||||
}
|
||||
|
||||
/// The title of a task: the first line of the prompt that says something. A pasted Markdown
|
||||
/// block opens with a code fence (```` ```text ````), which names no task.
|
||||
/// The title of a task: the first line of the prompt that says something. Text inside a code
|
||||
/// fence (```` ```text ````) is pasted material, so a line outside the fences wins; a prompt
|
||||
/// that is all one pasted block still names its task from inside it.
|
||||
fn title_of(prompt: &AgentPrompt) -> String {
|
||||
let is_fence = |l: &str| l.starts_with("```") || l.starts_with("~~~");
|
||||
let line = prompt.text.lines().map(str::trim).find(|l| !l.is_empty() && !is_fence(l));
|
||||
let (mut outside, mut inside, mut fenced) = (None, None, false);
|
||||
for l in prompt.text.lines().map(str::trim) {
|
||||
if is_fence(l) {
|
||||
fenced = !fenced;
|
||||
} else if !l.is_empty() {
|
||||
let slot = if fenced { &mut inside } else { &mut outside };
|
||||
slot.get_or_insert(l);
|
||||
if outside.is_some() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
let line = outside.or(inside);
|
||||
let line = match line {
|
||||
Some(l) => l.to_owned(),
|
||||
None => prompt.files.first().map(|f| file_name(&f.0)).unwrap_or_else(|| "Image".into()),
|
||||
@@ -4269,12 +4429,21 @@ fn home_dir() -> Option<PathBuf> {
|
||||
std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE")).map(PathBuf::from)
|
||||
}
|
||||
|
||||
/// How many times each file was written, in test builds: lets a test count a task's saves.
|
||||
#[cfg(test)]
|
||||
static FILE_WRITES: std::sync::LazyLock<Mutex<HashMap<PathBuf, u32>>> = std::sync::LazyLock::new(Mutex::default);
|
||||
|
||||
fn write_file(path: &Path, bytes: &[u8]) -> Result<(), String> {
|
||||
if let Some(dir) = path.parent() {
|
||||
std::fs::create_dir_all(dir).map_err(|e| e.to_string())?;
|
||||
}
|
||||
let tmp = path.with_extension("json.tmp");
|
||||
std::fs::write(&tmp, bytes).and_then(|()| std::fs::rename(&tmp, path)).map_err(|e| e.to_string())
|
||||
std::fs::write(&tmp, bytes).and_then(|()| std::fs::rename(&tmp, path)).map_err(|e| e.to_string())?;
|
||||
#[cfg(test)]
|
||||
{
|
||||
*FILE_WRITES.lock().entry(path.to_owned()).or_default() += 1;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn blocking<T: Send + 'static>(f: impl FnOnce() -> IdeResult<T> + Send + 'static) -> IdeResult<T> {
|
||||
@@ -4320,80 +4489,160 @@ fn stdio_mcp_servers(executable: Option<&std::path::Path>, supported: bool, root
|
||||
vec![json!({ "name": BUILTIN_SERVER, "command": command[0], "args": command[1..], "env": env })]
|
||||
}
|
||||
|
||||
/// What was sent of a streaming message: its first `bytes` (`utf16` UTF-16 units), which
|
||||
/// ended with `tail`. A message only grows while it streams, so its tail tells a message
|
||||
/// that went on from one that was replaced without comparing (or keeping) all of it.
|
||||
/// What was sent of a streaming text: its first `bytes` (`utf16` UTF-16 units), hashed. The
|
||||
/// text only grows while it streams; the hash tells one that went on from one that was replaced
|
||||
/// (at its end or anywhere before) without keeping a copy of it.
|
||||
struct Sent {
|
||||
index: usize,
|
||||
bytes: usize,
|
||||
utf16: usize,
|
||||
tail: String,
|
||||
hash: u64,
|
||||
}
|
||||
|
||||
const SENT_TAIL: usize = 64;
|
||||
|
||||
impl Sent {
|
||||
fn new(index: usize, text: &str) -> Self {
|
||||
Self::after(index, text, 0, 0)
|
||||
Self { index, bytes: text.len(), utf16: text.encode_utf16().count(), hash: Self::digest(text) }
|
||||
}
|
||||
|
||||
/// `text` as sent, of which the first `bytes` (`utf16` units) were sent before.
|
||||
fn after(index: usize, text: &str, bytes: usize, utf16: usize) -> Self {
|
||||
let mut start = text.len().saturating_sub(SENT_TAIL);
|
||||
while !text.is_char_boundary(start) {
|
||||
start -= 1;
|
||||
fn digest(text: &str) -> u64 {
|
||||
let mut hasher = DefaultHasher::new();
|
||||
hasher.write(text.as_bytes());
|
||||
hasher.finish()
|
||||
}
|
||||
|
||||
/// `text` at `index` as sent after this, when it is this text with more at the end.
|
||||
fn extended(&self, index: usize, text: &str) -> Option<Self> {
|
||||
if self.index != index || text.len() <= self.bytes || !text.is_char_boundary(self.bytes) {
|
||||
return None;
|
||||
}
|
||||
let utf16 = utf16 + text[bytes..].encode_utf16().count();
|
||||
Self { index, bytes: text.len(), utf16, tail: text[start..].to_owned() }
|
||||
let mut hasher = DefaultHasher::new();
|
||||
hasher.write(&text.as_bytes()[..self.bytes]);
|
||||
if hasher.finish() != self.hash {
|
||||
return None;
|
||||
}
|
||||
let more = &text[self.bytes..];
|
||||
hasher.write(more.as_bytes());
|
||||
Some(Self { index, bytes: text.len(), utf16: self.utf16 + more.encode_utf16().count(), hash: hasher.finish() })
|
||||
}
|
||||
|
||||
/// Whether `text` at `index` is this message, gone on.
|
||||
fn extended_by(&self, index: usize, text: &str) -> bool {
|
||||
self.index == index
|
||||
&& text.len() > self.bytes
|
||||
&& text.is_char_boundary(self.bytes)
|
||||
&& text[..self.bytes].ends_with(&self.tail)
|
||||
/// Whether `text` is exactly what was sent.
|
||||
fn is(&self, text: &str) -> bool {
|
||||
text.len() == self.bytes && Self::digest(text) == self.hash
|
||||
}
|
||||
}
|
||||
|
||||
/// A running tool call as last sent: the entry without its output, and what was sent of that.
|
||||
struct SentTool {
|
||||
call: AgentEntry,
|
||||
output: Sent,
|
||||
}
|
||||
|
||||
/// What each window was last sent of the entries that stream, so the next flush sends the rest.
|
||||
#[derive(Default)]
|
||||
struct Streamed {
|
||||
/// The message each session streams now.
|
||||
messages: HashMap<Session, Sent>,
|
||||
/// The tool calls still running, by session and entry index.
|
||||
tools: HashMap<(Session, usize), SentTool>,
|
||||
}
|
||||
|
||||
impl Streamed {
|
||||
fn clear(&mut self) {
|
||||
self.messages.clear();
|
||||
self.tools.clear();
|
||||
}
|
||||
}
|
||||
|
||||
/// The event that brings the UI's copy of entry `i` up to date: only the new text when
|
||||
/// it extends the message last sent for the session, else the whole entry.
|
||||
/// it extends the message (or the tool output) last sent, else the whole entry; `None`
|
||||
/// when the UI's copy of a tool already is the entry.
|
||||
fn entry_event(
|
||||
task: &str,
|
||||
streamed: &mut HashMap<Session, Sent>,
|
||||
streamed: &mut Streamed,
|
||||
subagent: Session,
|
||||
i: usize,
|
||||
entry: &AgentEntry,
|
||||
) -> AgentEvent {
|
||||
) -> Option<AgentEvent> {
|
||||
let whole = |subagent| AgentEvent::Entry { task: task.to_owned(), subagent, index: i as u32, entry: entry.clone() };
|
||||
let text = match entry {
|
||||
AgentEntry::Agent { text } | AgentEntry::Thought { text, .. } => Some(text),
|
||||
AgentEntry::Tool { .. } => return tool_event(task, streamed, subagent, i, entry),
|
||||
_ => None,
|
||||
};
|
||||
let Some(text) = text else {
|
||||
if streamed.get(&subagent).is_some_and(|sent| sent.index == i) {
|
||||
streamed.remove(&subagent);
|
||||
if streamed.messages.get(&subagent).is_some_and(|sent| sent.index == i) {
|
||||
streamed.messages.remove(&subagent);
|
||||
}
|
||||
return AgentEvent::Entry { task: task.to_owned(), subagent, index: i as u32, entry: entry.clone() };
|
||||
return Some(whole(subagent));
|
||||
};
|
||||
match streamed.get(&subagent).filter(|sent| sent.extended_by(i, text)) {
|
||||
Some(sent) => {
|
||||
let (bytes, from) = (sent.bytes, sent.utf16);
|
||||
streamed.insert(subagent.clone(), Sent::after(i, text, bytes, from));
|
||||
AgentEvent::Append {
|
||||
match streamed.messages.get(&subagent).and_then(|sent| Some((sent.bytes, sent.utf16, sent.extended(i, text)?))) {
|
||||
Some((bytes, from, sent)) => {
|
||||
streamed.messages.insert(subagent.clone(), sent);
|
||||
Some(AgentEvent::Append {
|
||||
task: task.to_owned(),
|
||||
subagent,
|
||||
index: i as u32,
|
||||
from: from as u32,
|
||||
text: text[bytes..].to_owned(),
|
||||
}
|
||||
})
|
||||
}
|
||||
None => {
|
||||
streamed.insert(subagent.clone(), Sent::new(i, text));
|
||||
AgentEvent::Entry { task: task.to_owned(), subagent, index: i as u32, entry: entry.clone() }
|
||||
streamed.messages.insert(subagent.clone(), Sent::new(i, text));
|
||||
Some(whole(subagent))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// [`entry_event`] for a tool call: the output it grew by while the rest of it is unchanged.
|
||||
fn tool_event(
|
||||
task: &str,
|
||||
streamed: &mut Streamed,
|
||||
subagent: Session,
|
||||
i: usize,
|
||||
entry: &AgentEntry,
|
||||
) -> Option<AgentEvent> {
|
||||
let AgentEntry::Tool { id, title, kind, status, locations, images, output, diffs, started_ms, ended_ms } = entry
|
||||
else {
|
||||
return None;
|
||||
};
|
||||
let call = AgentEntry::Tool {
|
||||
id: id.clone(),
|
||||
title: title.clone(),
|
||||
kind: kind.clone(),
|
||||
status: *status,
|
||||
locations: locations.clone(),
|
||||
images: images.clone(),
|
||||
output: None,
|
||||
diffs: diffs.clone(),
|
||||
started_ms: *started_ms,
|
||||
ended_ms: *ended_ms,
|
||||
};
|
||||
let text = output.as_deref().unwrap_or_default();
|
||||
let key = (subagent, i);
|
||||
if let Some(sent) = streamed.tools.get_mut(&key).filter(|sent| sent.call == call) {
|
||||
if let Some(output) = sent.output.extended(i, text) {
|
||||
let (bytes, from) = (sent.output.bytes, sent.output.utf16);
|
||||
sent.output = output;
|
||||
return Some(AgentEvent::ToolOutput {
|
||||
task: task.to_owned(),
|
||||
subagent: key.0,
|
||||
index: i as u32,
|
||||
from: from as u32,
|
||||
text: text[bytes..].to_owned(),
|
||||
});
|
||||
}
|
||||
if sent.output.is(text) {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
if matches!(status, AgentToolStatus::Pending | AgentToolStatus::Running) {
|
||||
streamed.tools.insert(key.clone(), SentTool { call, output: Sent::new(i, text) });
|
||||
} else {
|
||||
streamed.tools.remove(&key);
|
||||
}
|
||||
Some(AgentEvent::Entry { task: task.to_owned(), subagent: key.0, index: i as u32, entry: entry.clone() })
|
||||
}
|
||||
|
||||
struct SessionOpenError {
|
||||
message: String,
|
||||
allow_acp_fallback: bool,
|
||||
|
||||
@@ -801,6 +801,16 @@ 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,
|
||||
|
||||
+730
-13
@@ -32,6 +32,10 @@ struct FakeAgent {
|
||||
servers: Mutex<Vec<Peer>>,
|
||||
calls: Mutex<Vec<String>>,
|
||||
permission_replies: Mutex<Vec<Value>>,
|
||||
/// The tasks' store directory: when set, a "decide" prompt notes what the task file holds
|
||||
/// for the answered request at the moment its reply arrives.
|
||||
store_dir: Mutex<Option<PathBuf>>,
|
||||
file_at_reply: Mutex<Vec<Value>>,
|
||||
/// Without `loadSession` (a session lives only as long as its process).
|
||||
no_load: bool,
|
||||
auth_on_new: bool,
|
||||
@@ -218,6 +222,10 @@ impl Handler for FakeAgent {
|
||||
}
|
||||
"session/load" if self.load_error.is_some() => Err(self.load_error.clone().unwrap()),
|
||||
"session/load" => {
|
||||
self.update(
|
||||
&session,
|
||||
json!({"sessionUpdate": "user_message_chunk", "content": {"type": "text", "text": "earlier question"}}),
|
||||
);
|
||||
self.say(&session, "replayed history");
|
||||
Ok(json!({}))
|
||||
}
|
||||
@@ -278,6 +286,24 @@ impl Handler for FakeAgent {
|
||||
self.say(&session, "running it in the background");
|
||||
return Ok(json!({"stopReason": "end_turn"}));
|
||||
}
|
||||
if text == "stream tool output" {
|
||||
// A long command whose output grows: every update carries all of it so far.
|
||||
let update = |kind: &str, status: &str, output: &str| {
|
||||
json!({"sessionUpdate": kind, "toolCallId": "build", "title": "cargo build",
|
||||
"kind": "execute", "status": status,
|
||||
"content": [{"type": "content", "content": {"type": "text", "text": output}}]})
|
||||
};
|
||||
self.update(&session, update("tool_call", "in_progress", "$ cargo build"));
|
||||
let mut output = String::from("$ cargo build");
|
||||
for i in 0..40 {
|
||||
output.push_str(&format!("\n{i:04} {}", "x".repeat(1500)));
|
||||
self.update(&session, update("tool_call_update", "in_progress", &output));
|
||||
// Longer than the flush interval: every update reaches the window on its own.
|
||||
std::thread::sleep(FLUSH_DELAY + Duration::from_millis(30));
|
||||
}
|
||||
self.update(&session, update("tool_call_update", "completed", &output));
|
||||
return Ok(json!({"stopReason": "end_turn"}));
|
||||
}
|
||||
if text == "delegate" {
|
||||
self.delegate(&session);
|
||||
return Ok(json!({"stopReason": "end_turn"}));
|
||||
@@ -318,6 +344,29 @@ impl Handler for FakeAgent {
|
||||
self.say(&session, &format!("late chose {chosen}"));
|
||||
return Ok(json!({"stopReason": "end_turn"}));
|
||||
}
|
||||
if text == "decide" {
|
||||
let peer = self.latest();
|
||||
let _: Value = tokio::runtime::Handle::current()
|
||||
.block_on(peer.request(
|
||||
"session/request_permission",
|
||||
json!({"sessionId": session, "toolCall": {"toolCallId": "d1", "title": "Run cargo test"},
|
||||
"options": [{"optionId": "yes", "name": "Allow", "kind": "allow_once"},
|
||||
{"optionId": "no", "name": "Reject", "kind": "reject_once"}]}),
|
||||
None,
|
||||
))
|
||||
.unwrap();
|
||||
if let Some(dir) = self.store_dir.lock().clone() {
|
||||
let held = std::fs::read_dir(dir)
|
||||
.unwrap()
|
||||
.filter_map(|f| serde_json::from_slice::<Value>(&std::fs::read(f.ok()?.path()).ok()?).ok())
|
||||
.flat_map(|file| file["entries"].as_array().cloned().unwrap_or_default())
|
||||
.find_map(|entry| entry.get("chosen").cloned())
|
||||
.unwrap_or(Value::Null);
|
||||
self.file_at_reply.lock().push(held);
|
||||
}
|
||||
self.say(&session, "decided");
|
||||
return Ok(json!({"stopReason": "end_turn"}));
|
||||
}
|
||||
if text == "escalate" {
|
||||
// A request for wider access, titled with text the model wrote.
|
||||
let peer = self.latest();
|
||||
@@ -1268,6 +1317,408 @@ async fn a_task_runs_asks_for_permission_and_survives_a_restart() {
|
||||
assert!(calls.contains(&"session/set_mode \"code\"".to_owned()), "{calls:?}");
|
||||
}
|
||||
|
||||
fn task_file(dir: &Path, id: &str) -> PathBuf {
|
||||
dir.join("store").join(format!("{id}.json"))
|
||||
}
|
||||
|
||||
fn saves(path: &Path) -> u32 {
|
||||
FILE_WRITES.lock().get(path).copied().unwrap_or(0)
|
||||
}
|
||||
|
||||
/// What a task's file holds: its status and how many entries it has.
|
||||
fn saved_task(path: &Path) -> Option<(Value, usize)> {
|
||||
let file: Value = serde_json::from_slice(&std::fs::read(path).ok()?).ok()?;
|
||||
Some((file["task"]["status"].clone(), file["entries"].as_array()?.len()))
|
||||
}
|
||||
|
||||
/// Shuts the manager down when the test ends, a failed assertion included: a failing test
|
||||
/// would otherwise never return while its turn is still running.
|
||||
struct ShutDown<'a>(&'a AgentManager);
|
||||
|
||||
impl Drop for ShutDown<'_> {
|
||||
fn drop(&mut self) {
|
||||
self.0.shutdown();
|
||||
}
|
||||
}
|
||||
|
||||
/// A turn does not rewrite the whole task file for every step it goes through, and where the
|
||||
/// task stops for the user (a question, the end) the file already holds everything, as the
|
||||
/// window that was told finds it.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_turn_saves_the_task_file_once_per_stop() {
|
||||
struct Stop {
|
||||
status: AgentStatus,
|
||||
saves: u32,
|
||||
file: Option<(Value, usize)>,
|
||||
}
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
let _shut_down = ShutDown(&mgr);
|
||||
let stops = Arc::new(Mutex::new(Vec::<Stop>::new()));
|
||||
let (sink, dir) = (stops.clone(), tmp.path().to_path_buf());
|
||||
mgr.subscribe_as(
|
||||
"",
|
||||
Arc::new(move |event| {
|
||||
if let AgentEvent::Task { task } = event
|
||||
&& matches!(task.status, AgentStatus::NeedsInput | AgentStatus::Ready)
|
||||
{
|
||||
let path = task_file(&dir, &task.id);
|
||||
sink.lock().push(Stop { status: task.status, saves: saves(&path), file: saved_task(&path) });
|
||||
}
|
||||
}),
|
||||
);
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
prompt: text("Fix the lexer"),
|
||||
provider: "claude".into(),
|
||||
isolation: Isolation::Local,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
// The first time the task stopped as `status` after the `from`th stop: what its file held then.
|
||||
let stopped = |status: AgentStatus, from: usize| {
|
||||
let stops = stops.clone();
|
||||
async move {
|
||||
for _ in 0..500 {
|
||||
if let Some(stop) = stops.lock().iter().skip(from).find(|s| s.status == status) {
|
||||
return (stop.saves, stop.file.clone());
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
panic!("the task never stopped as {status:?}");
|
||||
}
|
||||
};
|
||||
let status = |s: AgentStatus| serde_json::to_value(s).unwrap();
|
||||
|
||||
let (first_turn, asked) = stopped(AgentStatus::NeedsInput, 0).await;
|
||||
// The user's message, "Hi", the edit and the pending permission are all in the file.
|
||||
assert_eq!(asked, Some((status(AgentStatus::NeedsInput), 4)));
|
||||
|
||||
let permission = mgr
|
||||
.entries(&task.id, None)
|
||||
.unwrap()
|
||||
.iter()
|
||||
.find_map(|e| match e {
|
||||
AgentEntry::Permission { id, .. } => Some(*id),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap();
|
||||
let seen = stops.lock().len();
|
||||
mgr.respond(&task.id, permission, Some("yes".into())).unwrap();
|
||||
let (ready_at, ready) = stopped(AgentStatus::Ready, seen).await;
|
||||
assert_eq!(ready, Some((status(AgentStatus::Ready), 5)));
|
||||
let answered = ready_at - first_turn;
|
||||
|
||||
let seen = stops.lock().len();
|
||||
mgr.prompt(&task.id, text("again"), false).await.unwrap();
|
||||
let (again_at, again) = stopped(AgentStatus::Ready, seen).await;
|
||||
assert_eq!(again, Some((status(AgentStatus::Ready), 7)));
|
||||
let second_turn = again_at - ready_at;
|
||||
eprintln!(
|
||||
"task file saves: {first_turn} to the first question, {answered} to answer it and finish, {second_turn} for a second turn"
|
||||
);
|
||||
assert!(
|
||||
first_turn <= 4 && answered <= 2 && second_turn <= 3,
|
||||
"task file saves: {first_turn} to the first question (4 or fewer), {answered} to answer it and finish (2 or fewer), {second_turn} for a second turn (3 or fewer)"
|
||||
);
|
||||
}
|
||||
|
||||
/// A reader of the task's state waits only for a copy of it, not for the whole transcript to
|
||||
/// be turned into JSON and written.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn saving_a_large_task_does_not_hold_up_readers() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
prompt: text("again"),
|
||||
provider: "claude".into(),
|
||||
isolation: Isolation::Local,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
let handle = mgr.task(&task.id).unwrap();
|
||||
let path = task_file(tmp.path(), &task.id);
|
||||
for i in 0..24 {
|
||||
let text = format!("output {i}: \"quoted\"\n").repeat(40_000);
|
||||
handle.state.lock().conversation.main.push(AgentEntry::Agent { text });
|
||||
}
|
||||
let entries = handle.state.lock().conversation.main.entries.clone();
|
||||
let started = std::time::Instant::now();
|
||||
let json = serde_json::to_vec(&entries).unwrap();
|
||||
let serialising = started.elapsed();
|
||||
eprintln!("large task: {} MB of JSON, {serialising:?} to serialise", json.len() >> 20);
|
||||
|
||||
// The longest wait for the state lock while a save runs: the best of a few saves, so a
|
||||
// reader that was descheduled once does not fail the test.
|
||||
let mut waits = Vec::new();
|
||||
for _ in 0..3 {
|
||||
let writes = saves(&path);
|
||||
let stop = Arc::new(AtomicBool::new(false));
|
||||
let reader = {
|
||||
let (handle, stop) = (handle.clone(), stop.clone());
|
||||
std::thread::spawn(move || {
|
||||
let mut longest = Duration::ZERO;
|
||||
while !stop.load(Ordering::Acquire) {
|
||||
let asked = std::time::Instant::now();
|
||||
drop(handle.state.lock());
|
||||
longest = longest.max(asked.elapsed());
|
||||
std::thread::sleep(Duration::from_micros(200));
|
||||
}
|
||||
longest
|
||||
})
|
||||
};
|
||||
handle.persist();
|
||||
while saves(&path) == writes {
|
||||
tokio::time::sleep(Duration::from_millis(1)).await;
|
||||
}
|
||||
stop.store(true, Ordering::Release);
|
||||
waits.push(reader.join().unwrap());
|
||||
}
|
||||
let shortest = waits.iter().min().copied().unwrap();
|
||||
eprintln!("longest wait for the state lock while saving: {waits:?}");
|
||||
assert!(shortest * 3 < serialising, "readers waited {shortest:?} while the task was saved ({serialising:?})");
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
async fn idle_task(mgr: &AgentManager, title: &str) -> AgentTask {
|
||||
let request = NewAgentTask {
|
||||
prompt: text(title),
|
||||
provider: "claude".into(),
|
||||
isolation: Isolation::Local,
|
||||
idle: true,
|
||||
..Default::default()
|
||||
};
|
||||
mgr.create(request).await.unwrap()
|
||||
}
|
||||
|
||||
fn saved_title(path: &Path) -> Option<String> {
|
||||
let file: Value = serde_json::from_slice(&std::fs::read(path).ok()?).ok()?;
|
||||
file["task"]["title"].as_str().map(str::to_owned)
|
||||
}
|
||||
|
||||
/// Changes asked for in a burst are written once, as the latest state, and no older state is
|
||||
/// written after it.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn saves_asked_for_in_a_burst_write_the_latest_state_once() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
let task = idle_task(&mgr, "first").await;
|
||||
let handle = mgr.task(&task.id).unwrap();
|
||||
let path = task_file(tmp.path(), &task.id);
|
||||
let before = saves(&path);
|
||||
for i in 0..50 {
|
||||
handle.state.lock().task.title = format!("title {i}");
|
||||
handle.persist_soon();
|
||||
}
|
||||
for _ in 0..500 {
|
||||
if saved_title(&path).as_deref() == Some("title 49") {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
assert_eq!(saved_title(&path).as_deref(), Some("title 49"));
|
||||
tokio::time::sleep(SAVE_DELAY * 2).await;
|
||||
assert_eq!(saved_title(&path).as_deref(), Some("title 49"), "an older state was written back");
|
||||
let written = saves(&path) - before;
|
||||
mgr.shutdown();
|
||||
assert!(written <= 2, "50 changes in a burst were saved {written} times");
|
||||
}
|
||||
|
||||
/// Saves of one task from several threads, whether they wait or not, never put an older
|
||||
/// state back over a newer one, and saves of other tasks never mix in.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn concurrent_saves_keep_the_newest_state_of_each_task() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
let mut tasks = Vec::new();
|
||||
for name in ["alpha", "beta"] {
|
||||
let task = idle_task(&mgr, name).await;
|
||||
let handle = mgr.task(&task.id).unwrap();
|
||||
// Long enough that a save takes a while between the copy and the write.
|
||||
handle.state.lock().conversation.main.push(AgentEntry::Agent { text: "text ".repeat(60_000) });
|
||||
tasks.push((name, handle, task_file(tmp.path(), &task.id)));
|
||||
}
|
||||
// "<name> <n>", n growing with every change made under the state lock.
|
||||
let change = |name: &str, handle: &Task, n: &AtomicU64| {
|
||||
let mut s = handle.state.lock();
|
||||
s.task.title = format!("{name} {}", n.fetch_add(1, Ordering::AcqRel) + 1);
|
||||
};
|
||||
let stop = Arc::new(AtomicBool::new(false));
|
||||
let mut watchers = Vec::new();
|
||||
let mut writers = Vec::new();
|
||||
for (name, handle, path) in &tasks {
|
||||
let counter = Arc::new(AtomicU64::new(0));
|
||||
for pace in 0..2 {
|
||||
let (name, handle, counter) = (*name, handle.clone(), counter.clone());
|
||||
writers.push(std::thread::spawn(move || {
|
||||
for i in 0..40 {
|
||||
change(name, &handle, &counter);
|
||||
if (i + pace) % 2 == 0 {
|
||||
handle.persist();
|
||||
} else {
|
||||
handle.persist_soon();
|
||||
}
|
||||
}
|
||||
}));
|
||||
}
|
||||
let (name, path, stop) = (*name, path.clone(), stop.clone());
|
||||
watchers.push(std::thread::spawn(move || {
|
||||
let mut newest = 0;
|
||||
while !stop.load(Ordering::Acquire) {
|
||||
if let Some(title) = saved_title(&path) {
|
||||
// Nothing was saved yet but the task's name, before the first change.
|
||||
let n: u64 = match title.strip_prefix(&format!("{name} ")) {
|
||||
Some(n) => n.parse().unwrap(),
|
||||
None => {
|
||||
assert_eq!(title, name, "another task's state");
|
||||
0
|
||||
}
|
||||
};
|
||||
assert!(n >= newest, "{name}: state {n} was written after state {newest}");
|
||||
newest = n;
|
||||
}
|
||||
std::thread::sleep(Duration::from_micros(100));
|
||||
}
|
||||
}));
|
||||
}
|
||||
for writer in writers {
|
||||
writer.join().unwrap();
|
||||
}
|
||||
for (_, handle, _) in &tasks {
|
||||
handle.persist();
|
||||
}
|
||||
stop.store(true, Ordering::Release);
|
||||
for watcher in watchers {
|
||||
watcher.join().unwrap();
|
||||
}
|
||||
tokio::time::sleep(SAVE_DELAY * 2).await;
|
||||
for (name, handle, path) in &tasks {
|
||||
let title = handle.state.lock().task.title.clone();
|
||||
assert_eq!(title, format!("{name} 80"));
|
||||
assert_eq!(saved_title(path), Some(title));
|
||||
}
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
/// What was asked to be saved soon is written when the manager shuts down, and a task that
|
||||
/// is deleted meanwhile stays deleted.
|
||||
#[tokio::test]
|
||||
async fn shutdown_writes_the_saves_still_waiting_and_a_delete_drops_them() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
let kept = idle_task(&mgr, "kept").await;
|
||||
let gone = idle_task(&mgr, "gone").await;
|
||||
let (kept_path, gone_path) = (task_file(tmp.path(), &kept.id), task_file(tmp.path(), &gone.id));
|
||||
for id in [&kept.id, &gone.id] {
|
||||
let handle = mgr.task(id).unwrap();
|
||||
handle.state.lock().task.title = "renamed".into();
|
||||
handle.persist_soon();
|
||||
}
|
||||
// This runtime runs one thing at a time and nothing has yielded to it: the saves wait.
|
||||
assert_eq!(saved_title(&kept_path).as_deref(), Some("kept"));
|
||||
mgr.delete(&gone.id, false).await.unwrap();
|
||||
mgr.shutdown();
|
||||
assert_eq!(saved_title(&kept_path).as_deref(), Some("renamed"), "shutdown left the task unsaved");
|
||||
|
||||
let restored = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
assert_eq!(restored.task(&kept.id).unwrap().state.lock().task.title, "renamed");
|
||||
assert!(restored.task(&gone.id).is_err());
|
||||
tokio::time::sleep(SAVE_DELAY * 2).await;
|
||||
assert!(!gone_path.exists(), "the save that was waiting brought the deleted task back");
|
||||
assert_eq!(saved_title(&kept_path).as_deref(), Some("renamed"));
|
||||
}
|
||||
|
||||
/// Archiving saves the task as it is, including changes nobody asked to be saved.
|
||||
#[tokio::test]
|
||||
async fn archiving_saves_the_task_before_it_returns() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
let task = idle_task(&mgr, "task").await;
|
||||
let path = task_file(tmp.path(), &task.id);
|
||||
mgr.task(&task.id).unwrap().state.lock().task.title = "changed meanwhile".into();
|
||||
mgr.archive(&task.id).unwrap();
|
||||
assert_eq!(saved_task(&path).map(|(status, _)| status), Some(serde_json::to_value(AgentStatus::Archived).unwrap()));
|
||||
assert_eq!(saved_title(&path).as_deref(), Some("changed meanwhile"));
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
/// The answer to a request is in the task file before the agent hears it: a restart right
|
||||
/// after still shows the request as answered, not cancelled.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn an_answer_is_saved_before_the_agent_is_told() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
*agent.store_dir.lock() = Some(tmp.path().join("store"));
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
let _shut_down = ShutDown(&mgr);
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
prompt: text("decide"),
|
||||
provider: "claude".into(),
|
||||
isolation: Isolation::Local,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
|
||||
let permission = mgr
|
||||
.entries(&task.id, None)
|
||||
.unwrap()
|
||||
.iter()
|
||||
.find_map(|e| match e {
|
||||
AgentEntry::Permission { id, .. } => Some(*id),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap();
|
||||
mgr.respond(&task.id, permission, Some("yes".into())).unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
assert_eq!(*agent.file_at_reply.lock(), [json!("Allow")]);
|
||||
}
|
||||
|
||||
/// A turn that fails or hits the usage limit is in the task file by the time the window is
|
||||
/// told, like the end of a turn.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_failed_turn_is_saved_before_the_window_hears_of_it() {
|
||||
for (message, status) in [("auth", AgentStatus::Failed), ("limit", AgentStatus::Limited)] {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
let _shut_down = ShutDown(&mgr);
|
||||
let told = Arc::new(Mutex::new(None));
|
||||
let (sink, dir) = (told.clone(), tmp.path().to_path_buf());
|
||||
mgr.subscribe_as(
|
||||
"",
|
||||
Arc::new(move |event| {
|
||||
if let AgentEvent::Task { task } = event
|
||||
&& task.status == status
|
||||
{
|
||||
*sink.lock() = Some(saved_task(&task_file(&dir, &task.id)).map(|(status, _)| status));
|
||||
}
|
||||
}),
|
||||
);
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
prompt: text(message),
|
||||
provider: "claude".into(),
|
||||
isolation: Isolation::Local,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, status).await;
|
||||
for _ in 0..500 {
|
||||
if told.lock().is_some() {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
assert_eq!(*told.lock(), Some(Some(serde_json::to_value(status).unwrap())), "{status:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_session_that_fails_to_load_is_reported_and_replaced_only_when_sent_again() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
@@ -1736,6 +2187,9 @@ fn prompts_become_acp_content_blocks() {
|
||||
assert_eq!(title_of(&AgentPrompt { files: p.files.clone(), ..AgentPrompt::default() }), "my file.rs");
|
||||
let pasted = AgentPrompt { text: "```text\n\n ## Fix the tab title\n```".into(), ..AgentPrompt::default() };
|
||||
assert_eq!(title_of(&pasted), "## Fix the tab title");
|
||||
let fenced_first =
|
||||
AgentPrompt { text: "```txt\nlog line\n```\nWhy does this fail?".into(), ..AgentPrompt::default() };
|
||||
assert_eq!(title_of(&fenced_first), "Why does this fail?");
|
||||
assert!(clean(text(" ")).is_none());
|
||||
}
|
||||
|
||||
@@ -2092,6 +2546,55 @@ async fn renamed_titles_survive_updates_forks_and_restart() {
|
||||
restored.shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_session_without_history_takes_it_from_the_replay_before_the_first_message() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let path = {
|
||||
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
let _down = ShutDown(&mgr);
|
||||
let task = mgr
|
||||
.create(NewAgentTask { provider: "claude".into(), prompt: text("again"), ..Default::default() })
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
task_file(tmp.path(), &task.id)
|
||||
};
|
||||
let id = path.file_stem().unwrap().to_string_lossy().into_owned();
|
||||
// As an imported session is saved: its session id, none of its history.
|
||||
let mut file: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
|
||||
file["entries"] = json!([]);
|
||||
std::fs::write(&path, serde_json::to_vec(&file).unwrap()).unwrap();
|
||||
|
||||
{
|
||||
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
let _down = ShutDown(&mgr);
|
||||
mgr.prompt(&id, text("again"), false).await.unwrap();
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
wait_for(&mgr, &id, AgentStatus::Ready).await;
|
||||
let entries = mgr.entries(&id, None).unwrap();
|
||||
assert!(
|
||||
matches!(&entries[0], AgentEntry::User { text, sent_ms: None, .. } if text == "earlier question"),
|
||||
"{entries:?}"
|
||||
);
|
||||
assert_eq!(entries[1], AgentEntry::Agent { text: "replayed history".into() }, "{entries:?}");
|
||||
assert!(
|
||||
matches!(&entries[2], AgentEntry::User { text, sent_ms: Some(_), .. } if text == "again"),
|
||||
"{entries:?}"
|
||||
);
|
||||
assert_eq!(entries.last(), Some(&AgentEntry::Agent { text: "second turn".into() }), "{entries:?}");
|
||||
}
|
||||
assert_eq!(saved_task(&path).unwrap().1, 4);
|
||||
|
||||
// From then on the task has its history: a later reload's replay is dropped again.
|
||||
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
let _down = ShutDown(&mgr);
|
||||
mgr.prompt(&id, text("again"), false).await.unwrap();
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
wait_for(&mgr, &id, AgentStatus::Ready).await;
|
||||
let entries = mgr.entries(&id, None).unwrap();
|
||||
assert_eq!(entries.len(), 6, "{entries:?}");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn startup_warnings_survive_replay_and_restart_without_failing_the_task() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
@@ -3503,42 +4006,256 @@ async fn discovery_times_out_when_session_new_hangs() {
|
||||
assert!(!cursor.config.iter().any(|o| o.category.as_deref() == Some("model")));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_growing_tool_output_is_not_sent_whole_on_every_flush() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
// What a window receives of the tool's entry: events, and the bytes they take.
|
||||
let sent = Arc::new(Mutex::new((0usize, Vec::<AgentEvent>::new())));
|
||||
let sink = sent.clone();
|
||||
mgr.subscribe_as(
|
||||
"",
|
||||
Arc::new(move |e| {
|
||||
let json = serde_json::to_value(&e).unwrap();
|
||||
if json["entry"]["type"] == "tool" || json["type"] == "toolOutput" {
|
||||
let mut sent = sink.lock();
|
||||
sent.0 += json.to_string().len();
|
||||
sent.1.push(e);
|
||||
}
|
||||
}),
|
||||
);
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
project_root: None,
|
||||
prompt: text("stream tool output"),
|
||||
provider: "claude".into(),
|
||||
isolation: Isolation::Local,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
// The turn takes a few seconds: the agent paces its updates by the flush interval.
|
||||
let finished = |mgr: &AgentManager| {
|
||||
mgr.entries(&task.id, None).unwrap().into_iter().find_map(|e| match e {
|
||||
AgentEntry::Tool { output, status: AgentToolStatus::Completed, .. } => output,
|
||||
_ => None,
|
||||
})
|
||||
};
|
||||
for _ in 0..6000 {
|
||||
if finished(&mgr).is_some() {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
tokio::time::sleep(FLUSH_DELAY * 3).await;
|
||||
|
||||
let output = finished(&mgr).expect("the command's output was kept");
|
||||
assert!(output.len() > 60_000, "a long output that the timeline keeps whole: {}", output.len());
|
||||
let (bytes, events) = {
|
||||
let sent = sent.lock();
|
||||
(sent.0, sent.1.len())
|
||||
};
|
||||
assert!(events >= 30, "the output reached the window in many flushes: {events}");
|
||||
assert!(bytes < 3 * output.len(), "{bytes} bytes sent for {} bytes of output over {events} events", output.len());
|
||||
|
||||
// The window's copy, built as the UI does, ends as the conversation holds it.
|
||||
let mut shown: Option<String> = None;
|
||||
for e in &sent.lock().1 {
|
||||
match e {
|
||||
AgentEvent::Entry { entry: AgentEntry::Tool { output, .. }, .. } => shown = output.clone(),
|
||||
AgentEvent::ToolOutput { from, text, .. } => {
|
||||
let have = shown.get_or_insert_default();
|
||||
assert_eq!(*from as usize, have.encode_utf16().count(), "a delta goes on where the last one ended");
|
||||
have.push_str(text);
|
||||
}
|
||||
_ => unreachable!("{e:?}"),
|
||||
}
|
||||
}
|
||||
assert_eq!(shown, Some(output));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn streamed_text_is_sent_as_appends() {
|
||||
let mut streamed = HashMap::new();
|
||||
let mut streamed = Streamed::default();
|
||||
let agent = |t: &str| AgentEntry::Agent { text: t.into() };
|
||||
let first = entry_event("t", &mut streamed, None, 3, &agent("Hé"));
|
||||
let first = entry_event("t", &mut streamed, None, 3, &agent("Hé")).unwrap();
|
||||
assert!(matches!(first, AgentEvent::Entry { index: 3, .. }), "the first sight of a message is whole");
|
||||
let next = entry_event("t", &mut streamed, None, 3, &agent("Hé 👋 there"));
|
||||
let next = entry_event("t", &mut streamed, None, 3, &agent("Hé 👋 there")).unwrap();
|
||||
assert!(
|
||||
matches!(&next, AgentEvent::Append { subagent: None, index: 3, from: 2, text, .. } if text == " 👋 there"),
|
||||
"{next:?}"
|
||||
);
|
||||
let sub = entry_event("t", &mut streamed, Some("s".into()), 3, &agent("Hé 👋 there!"));
|
||||
let sub = entry_event("t", &mut streamed, Some("s".into()), 3, &agent("Hé 👋 there!")).unwrap();
|
||||
assert!(matches!(sub, AgentEvent::Entry { .. }), "each session streams on its own");
|
||||
let after = entry_event("t", &mut streamed, None, 3, &agent("Hé 👋 there."));
|
||||
let after = entry_event("t", &mut streamed, None, 3, &agent("Hé 👋 there.")).unwrap();
|
||||
assert!(
|
||||
matches!(&after, AgentEvent::Append { from: 11, text, .. } if text == "."),
|
||||
"from counts UTF-16 units: {after:?}"
|
||||
);
|
||||
let replaced = entry_event("t", &mut streamed, None, 3, &agent("Other"));
|
||||
let replaced = entry_event("t", &mut streamed, None, 3, &agent("Other")).unwrap();
|
||||
assert!(matches!(replaced, AgentEvent::Entry { .. }), "text that doesn't extend the sent text is sent whole");
|
||||
let thought = AgentEntry::Thought { text: "hmm…".into(), started_ms: None };
|
||||
let thought = entry_event("t", &mut streamed, None, 4, &thought);
|
||||
let thought = entry_event("t", &mut streamed, None, 4, &thought).unwrap();
|
||||
assert!(matches!(thought, AgentEvent::Entry { index: 4, .. }), "a new message starts whole");
|
||||
let tool = AgentEntry::Error { message: "x".into() };
|
||||
entry_event("t", &mut streamed, None, 4, &tool);
|
||||
entry_event("t", &mut streamed, None, 4, &tool).unwrap();
|
||||
let again = AgentEntry::Thought { text: "hmm… ok".into(), started_ms: None };
|
||||
let again = entry_event("t", &mut streamed, None, 4, &again);
|
||||
let again = entry_event("t", &mut streamed, None, 4, &again).unwrap();
|
||||
assert!(matches!(again, AgentEvent::Entry { .. }), "an entry replaced by another kind forgets its text");
|
||||
|
||||
let long = "é".repeat(5000);
|
||||
entry_event("t", &mut streamed, None, 5, &agent(&long));
|
||||
assert!(streamed[&None].tail.len() <= 64, "only the end of what was sent is kept");
|
||||
let on = entry_event("t", &mut streamed, None, 5, &agent(&format!("{long}!")));
|
||||
entry_event("t", &mut streamed, None, 5, &agent(&long)).unwrap();
|
||||
let on = entry_event("t", &mut streamed, None, 5, &agent(&format!("{long}!"))).unwrap();
|
||||
assert!(matches!(&on, AgentEvent::Append { from: 5000, text, .. } if text == "!"), "{on:?}");
|
||||
let rewritten = entry_event("t", &mut streamed, None, 5, &agent(&format!("{}x!??", "é".repeat(4999))));
|
||||
let rewritten = entry_event("t", &mut streamed, None, 5, &agent(&format!("{}x!??", "é".repeat(4999)))).unwrap();
|
||||
assert!(matches!(rewritten, AgentEvent::Entry { .. }), "a rewritten end is sent whole");
|
||||
// A text that goes on with its end as sent but an edited start is not an append.
|
||||
let kept_end =
|
||||
entry_event("t", &mut streamed, None, 5, &agent(&format!("{}{}", "e".repeat(5000), "é".repeat(5000))));
|
||||
assert!(matches!(kept_end, Some(AgentEvent::Entry { .. })), "{kept_end:?}");
|
||||
let edited_start =
|
||||
entry_event("t", &mut streamed, None, 5, &agent(&format!("{}{}!", "x".repeat(5000), "é".repeat(5000))));
|
||||
assert!(
|
||||
matches!(edited_start, Some(AgentEvent::Entry { .. })),
|
||||
"a rewritten start is sent whole even when the end is as sent: {edited_start:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_running_tools_output_is_sent_as_appends() {
|
||||
let mut streamed = Streamed::default();
|
||||
let call = |status, output: Option<&str>| AgentEntry::Tool {
|
||||
id: "t1".into(),
|
||||
title: "cargo build".into(),
|
||||
kind: "execute".into(),
|
||||
status,
|
||||
locations: Vec::new(),
|
||||
images: Vec::new(),
|
||||
output: output.map(str::to_owned),
|
||||
diffs: Vec::new(),
|
||||
started_ms: Some(1.0),
|
||||
ended_ms: None,
|
||||
};
|
||||
let running = |output| call(AgentToolStatus::Running, output);
|
||||
let event = |streamed: &mut Streamed, session: Session, i, entry: &AgentEntry| {
|
||||
entry_event("t", streamed, session, i, entry)
|
||||
};
|
||||
|
||||
let first = event(&mut streamed, None, 2, &running(None)).unwrap();
|
||||
assert!(matches!(first, AgentEvent::Entry { index: 2, .. }), "the first sight of a call is whole");
|
||||
let output = event(&mut streamed, None, 2, &running(Some("$ make"))).unwrap();
|
||||
assert!(
|
||||
matches!(&output, AgentEvent::ToolOutput { subagent: None, index: 2, from: 0, text, .. } if text == "$ make"),
|
||||
"{output:?}"
|
||||
);
|
||||
let next = event(&mut streamed, None, 2, &running(Some("$ make\ncc é.c 👋"))).unwrap();
|
||||
assert!(
|
||||
matches!(&next, AgentEvent::ToolOutput { from: 6, text, .. } if text == "\ncc é.c 👋"),
|
||||
"from counts UTF-16 units: {next:?}"
|
||||
);
|
||||
let after = event(&mut streamed, None, 2, &running(Some("$ make\ncc é.c 👋\nok"))).unwrap();
|
||||
assert!(matches!(&after, AgentEvent::ToolOutput { from: 16, text, .. } if text == "\nok"), "{after:?}");
|
||||
assert!(
|
||||
event(&mut streamed, None, 2, &running(Some("$ make\ncc é.c 👋\nok"))).is_none(),
|
||||
"what the window has is not sent again"
|
||||
);
|
||||
|
||||
// Anything else about the call goes whole, output included.
|
||||
let mut titled = running(Some("$ make\ncc é.c 👋\nok\n"));
|
||||
if let AgentEntry::Tool { title, .. } = &mut titled {
|
||||
*title = "make".into();
|
||||
}
|
||||
let renamed = event(&mut streamed, None, 2, &titled).unwrap();
|
||||
assert!(
|
||||
matches!(&renamed, AgentEvent::Entry { entry: AgentEntry::Tool { output: Some(o), .. }, .. } if o.ends_with("ok\n")),
|
||||
"{renamed:?}"
|
||||
);
|
||||
let on = event(&mut streamed, None, 2, &titled);
|
||||
assert!(on.is_none(), "the entry the window holds now is this one");
|
||||
if let AgentEntry::Tool { output, .. } = &mut titled {
|
||||
output.as_mut().unwrap().push_str("more");
|
||||
}
|
||||
let on = event(&mut streamed, None, 2, &titled).unwrap();
|
||||
assert!(matches!(&on, AgentEvent::ToolOutput { from: 20, text, .. } if text == "more"), "{on:?}");
|
||||
|
||||
// An image the tool returned is not part of the appended text: it goes with the whole entry.
|
||||
let mut shown = titled.clone();
|
||||
if let AgentEntry::Tool { images, output, .. } = &mut shown {
|
||||
images.push(AgentImage { mime_type: "image/png".into(), data: "AAAA".into(), name: None });
|
||||
output.as_mut().unwrap().push('!');
|
||||
}
|
||||
let imaged = event(&mut streamed, None, 2, &shown).unwrap();
|
||||
assert!(
|
||||
matches!(&imaged, AgentEvent::Entry { entry: AgentEntry::Tool { images, .. }, .. } if images.len() == 1),
|
||||
"{imaged:?}"
|
||||
);
|
||||
titled = shown;
|
||||
|
||||
// Output the call replaced rather than extended goes whole.
|
||||
let make = |output: &str| {
|
||||
let mut entry = titled.clone();
|
||||
if let AgentEntry::Tool { output: o, .. } = &mut entry {
|
||||
*o = Some(output.to_owned());
|
||||
}
|
||||
entry
|
||||
};
|
||||
let replaced = event(&mut streamed, None, 2, &make("$ make\nother")).unwrap();
|
||||
assert!(matches!(replaced, AgentEvent::Entry { .. }), "a rewritten output is sent whole");
|
||||
let on = event(&mut streamed, None, 2, &make("$ make\nother, but longer")).unwrap();
|
||||
assert!(matches!(on, AgentEvent::ToolOutput { from: 12, .. }), "and the next growth is appended to it: {on:?}");
|
||||
|
||||
// A replacement that keeps the old end, or the old length, is not mistaken for growth.
|
||||
let mut kept = make("$ make\nother, but longer");
|
||||
let swap = |entry: &mut AgentEntry, output: String| {
|
||||
if let AgentEntry::Tool { output: o, .. } = entry {
|
||||
*o = Some(output);
|
||||
}
|
||||
};
|
||||
let (long_tail, same_length) =
|
||||
(format!("{}{}", "X".repeat(100), "z".repeat(100)), "Y".repeat(100) + &"z".repeat(100));
|
||||
swap(&mut kept, long_tail.clone());
|
||||
event(&mut streamed, None, 2, &kept).unwrap();
|
||||
swap(&mut kept, same_length);
|
||||
let same = event(&mut streamed, None, 2, &kept).unwrap();
|
||||
assert!(
|
||||
matches!(&same, AgentEvent::Entry { entry: AgentEntry::Tool { output: Some(o), .. }, .. } if o.starts_with('Y')),
|
||||
"same length, same end, different start is sent whole: {same:?}"
|
||||
);
|
||||
swap(&mut kept, format!("{}{}!", "W".repeat(100), "z".repeat(100)));
|
||||
let grown = event(&mut streamed, None, 2, &kept).unwrap();
|
||||
assert!(
|
||||
matches!(grown, AgentEvent::Entry { .. }),
|
||||
"a replacement that also grows, with the old end, is sent whole: {grown:?}"
|
||||
);
|
||||
|
||||
// Calls run side by side, each in its own session.
|
||||
let whole = |e: &AgentEvent| matches!(e, AgentEvent::Entry { .. });
|
||||
let (a, b) = (
|
||||
event(&mut streamed, None, 3, &running(Some("a"))),
|
||||
event(&mut streamed, Some("s".into()), 3, &running(Some("b"))),
|
||||
);
|
||||
let c = event(&mut streamed, None, 4, &running(Some("c")));
|
||||
assert!([&a, &b, &c].into_iter().all(|e| whole(e.as_ref().unwrap())), "each call starts whole");
|
||||
let a = event(&mut streamed, None, 3, &running(Some("ab"))).unwrap();
|
||||
let c = event(&mut streamed, None, 4, &running(Some("cd"))).unwrap();
|
||||
let b = event(&mut streamed, Some("s".into()), 3, &running(Some("bc"))).unwrap();
|
||||
assert!(
|
||||
[&a, &b, &c].into_iter().all(|e| matches!(e, AgentEvent::ToolOutput { from: 1, .. })),
|
||||
"one call's flush does not end another's: {a:?} {b:?} {c:?}"
|
||||
);
|
||||
|
||||
// A call that ended is sent whole, and forgotten.
|
||||
let done = call(AgentToolStatus::Completed, Some("ab\ndone"));
|
||||
let done_event = event(&mut streamed, None, 3, &done).unwrap();
|
||||
assert!(matches!(done_event, AgentEvent::Entry { .. }));
|
||||
assert!(!streamed.tools.contains_key(&(None, 3)));
|
||||
let late = event(&mut streamed, None, 3, &call(AgentToolStatus::Completed, Some("ab\ndone\nlate"))).unwrap();
|
||||
assert!(matches!(late, AgentEvent::Entry { .. }), "an ended call's output is not appended to");
|
||||
|
||||
// A rollback forgets what was sent.
|
||||
streamed.clear();
|
||||
let again = event(&mut streamed, None, 4, &running(Some("cdef"))).unwrap();
|
||||
assert!(matches!(again, AgentEvent::Entry { .. }), "after the conversation was cut, calls start whole");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -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, find_javac, javac_step, module_classpath, module_classpaths,
|
||||
single_file_classpath, single_file_target,
|
||||
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,
|
||||
};
|
||||
pub use structure::{
|
||||
StructureJdk, StructureRoots, artifact_file, artifact_output, language_release, structure_outputs, structure_plan,
|
||||
structure_war_plan, structure_web_artifacts,
|
||||
StructureJdk, StructureRoots, artifact_file, artifact_output, language_release, structure_compile_file_plan,
|
||||
structure_outputs, structure_plan, structure_war_plan, structure_web_artifacts,
|
||||
};
|
||||
pub use up_to_date::{menu_up_to_date, record_menu_build};
|
||||
|
||||
|
||||
@@ -200,19 +200,22 @@ fn kotlin_line(line: &str) -> Option<RawMessage> {
|
||||
kotlin_location(rest, severity)
|
||||
}
|
||||
|
||||
/// javac: `A.java:12: error: msg` / `A.java:12: warning: [deprecation] msg`.
|
||||
/// javac: `A.java:12: error: msg` / `A.java:12: warning: [deprecation] msg`
|
||||
/// (and localized javac prefixes such as Chinese/Japanese `错误:` / `錯誤:` / `エラー:` / `警告:`).
|
||||
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) = if let Some(m) = rest.strip_prefix("error:") {
|
||||
(Severity::Error, m)
|
||||
} else {
|
||||
let m = rest.strip_prefix("warning:")?;
|
||||
(Severity::Warning, m)
|
||||
};
|
||||
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)))
|
||||
})?;
|
||||
Some(RawMessage::new(severity, msg.trim(), ColUnit::Char).at(path, ln, col))
|
||||
}
|
||||
|
||||
@@ -555,6 +558,31 @@ mod tests {
|
||||
assert_eq!(out[1].text, "[removal] finalize() has been deprecated");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn localized_javac_errors_and_warnings() {
|
||||
let out = parse(
|
||||
Format::Gradle,
|
||||
"/p/src/A.java:12: 错误: 找不到符号\n\
|
||||
\x20 Foo foo = new Foo();\n\
|
||||
\x20 ^\n\
|
||||
\x20 符号: 类 Foo\n\
|
||||
\x20 位置: 类 A\n\
|
||||
/p/src/B.java:5: 錯誤: 需要 ';'\n\
|
||||
\x20 int x = 1\n\
|
||||
\x20 ^\n\
|
||||
/p/src/C.java:8: 警告: [deprecation] old() 已过时\n\
|
||||
\x20 old();\n\
|
||||
\x20 ^\n",
|
||||
);
|
||||
assert_eq!(out.len(), 3, "{out:?}");
|
||||
assert_eq!(pos(&out[0]), (Severity::Error, "/p/src/A.java", 12, Some(9)));
|
||||
assert_eq!(out[0].text, "找不到符号\n符号: 类 Foo\n位置: 类 A");
|
||||
assert_eq!(pos(&out[1]), (Severity::Error, "/p/src/B.java", 5, Some(14)));
|
||||
assert_eq!(out[1].text, "需要 ';'");
|
||||
assert_eq!(pos(&out[2]), (Severity::Warning, "/p/src/C.java", 8, Some(5)));
|
||||
assert_eq!(out[2].text, "[deprecation] old() 已过时");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gradle_kotlin() {
|
||||
let out = parse(
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! Single-file Java compilation with `javac` for the Compile File action (#2476).
|
||||
//! Single-file Java compilation with `javac` for the Recompile 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,12 +6,93 @@
|
||||
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.
|
||||
@@ -41,12 +122,7 @@ 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> {
|
||||
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"));
|
||||
}
|
||||
is_java_file(file)?;
|
||||
let Some(m) = &model.maven else {
|
||||
return Err(IdeError::not_found("no linked Maven project found for module"));
|
||||
};
|
||||
@@ -70,8 +146,7 @@ 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 parts: Vec<&str> = rel.split('/').collect();
|
||||
let test = parts.windows(2).any(|w| w == ["src", "test"]);
|
||||
let test = is_test_source(&rel);
|
||||
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 })
|
||||
}
|
||||
@@ -112,7 +187,17 @@ 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> {
|
||||
classpath(root, model, target, "test", false)
|
||||
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)
|
||||
}
|
||||
|
||||
/// Runtime (or test) dependency classpath for a launch module.
|
||||
@@ -172,10 +257,12 @@ pub fn module_classpaths(
|
||||
}
|
||||
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) {
|
||||
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)?,
|
||||
Err(_) if targets.len() > 1 && !cancel.is_cancelled() => {
|
||||
classpaths(root, model, &targets[..1], scope, true, cancel)?
|
||||
}
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
if cancel.is_cancelled() {
|
||||
@@ -236,8 +323,9 @@ fn classpath(
|
||||
target: &SingleFileTarget,
|
||||
scope: &str,
|
||||
compile_first: bool,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<String> {
|
||||
Ok(classpaths(root, model, &[target], scope, compile_first)?.pop().unwrap())
|
||||
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.
|
||||
@@ -247,6 +335,7 @@ fn classpaths(
|
||||
targets: &[&SingleFileTarget],
|
||||
scope: &str,
|
||||
compile_first: bool,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<Vec<String>> {
|
||||
let top = &targets[0].top;
|
||||
let probe = CP_FILE;
|
||||
@@ -274,16 +363,17 @@ fn classpaths(
|
||||
}
|
||||
args.extend(["dependency:build-classpath", output_arg.as_str(), scope_arg.as_str(), "-q"]);
|
||||
let top_dir = subdir(root, &top.dir);
|
||||
let mut command = ProcCommand::new(&top.command);
|
||||
command.args(&args).envs(&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);
|
||||
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> = stdout.lines().chain(stderr.lines()).filter(|l| !l.trim().is_empty()).collect();
|
||||
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}")));
|
||||
}
|
||||
@@ -325,39 +415,14 @@ fn target_classpath(root: &Path, model: &BuildModel, target: &SingleFileTarget)
|
||||
})?;
|
||||
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));
|
||||
entries.dedup();
|
||||
Ok(entries.join(&separator.to_string()))
|
||||
Ok(join_classpath(entries))
|
||||
}
|
||||
|
||||
/// 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);
|
||||
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)
|
||||
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())
|
||||
}
|
||||
|
||||
/// The module's Java source folders that exist, generated ones included; test sources see
|
||||
@@ -383,8 +448,18 @@ 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(root, model, &target)?;
|
||||
let classpath = single_file_classpath_cancellable(root, model, &target, cancel)?;
|
||||
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 {
|
||||
@@ -394,6 +469,140 @@ pub fn compile_file_plan(root: &Path, model: &BuildModel, file: &Path) -> IdeRes
|
||||
})
|
||||
}
|
||||
|
||||
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::*;
|
||||
@@ -439,7 +648,8 @@ mod tests {
|
||||
#[test]
|
||||
fn target_finds_the_owning_module_and_the_test_scope() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
let root_buf = dunce::canonicalize(dir.path()).unwrap();
|
||||
let root = root_buf.as_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"));
|
||||
@@ -453,7 +663,8 @@ mod tests {
|
||||
#[test]
|
||||
fn target_rejects_non_java_missing_and_unlinked_files() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
let root_buf = dunce::canonicalize(dir.path()).unwrap();
|
||||
let root = root_buf.as_path();
|
||||
let model = fixture(root);
|
||||
write(root, "app/pom.xml", "<project/>");
|
||||
assert!(single_file_target(root, &model, &root.join("app/pom.xml")).is_err());
|
||||
@@ -465,7 +676,8 @@ mod tests {
|
||||
#[test]
|
||||
fn javac_prefers_the_module_jdk_and_scopes_test_sources() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
let root_buf = dunce::canonicalize(dir.path()).unwrap();
|
||||
let root = root_buf.as_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();
|
||||
@@ -501,7 +713,8 @@ mod tests {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
let root_buf = dunce::canonicalize(dir.path()).unwrap();
|
||||
let root = root_buf.as_path();
|
||||
fixture(root);
|
||||
let script = root.join("mvnw");
|
||||
fs::write(
|
||||
@@ -532,6 +745,7 @@ 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();
|
||||
@@ -539,6 +753,8 @@ 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.
|
||||
@@ -548,7 +764,8 @@ mod tests {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
let root_buf = dunce::canonicalize(dir.path()).unwrap();
|
||||
let root = root_buf.as_path();
|
||||
fixture(root);
|
||||
let script = root.join("mvnw");
|
||||
fs::write(
|
||||
@@ -605,7 +822,8 @@ mod tests {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
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");
|
||||
@@ -646,7 +864,8 @@ mod tests {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
let root_buf = dunce::canonicalize(dir.path()).unwrap();
|
||||
let root = root_buf.as_path();
|
||||
fixture(root);
|
||||
let script = root.join("mvnw");
|
||||
// `dependency:build-classpath` reports reactor outputs as absolute paths. Keep
|
||||
@@ -712,4 +931,79 @@ mod tests {
|
||||
calls.push('x');
|
||||
assert_eq!(fs::read_to_string(root.join("calls.txt")).unwrap(), calls);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn javac_step_omits_empty_classpath_and_uses_source_target_on_jdk_8() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root_buf = dunce::canonicalize(dir.path()).unwrap();
|
||||
let root = root_buf.as_path();
|
||||
let mut model = fixture(root);
|
||||
let file = root.join("app/src/main/java/demo/Main.java");
|
||||
let jdk8 = root.join("jdk8");
|
||||
fs::create_dir_all(jdk8.join("bin")).unwrap();
|
||||
fs::write(jdk8.join("release"), "JAVA_VERSION=\"1.8.0_372\"\n").unwrap();
|
||||
let project = model.maven.as_mut().unwrap().projects.iter_mut().find(|p| p.dir == "app").unwrap();
|
||||
project.java_version = Some(8);
|
||||
let mut target = single_file_target(root, &model, &file).unwrap();
|
||||
target.top.env.insert("JAVA_HOME".into(), jdk8.to_string_lossy().into_owned());
|
||||
let step = javac_step(&target, &file, "", "javac").unwrap();
|
||||
assert!(!step.args.iter().any(|a| a == "-cp"), "{:?}", step.args);
|
||||
assert!(step.args.iter().any(|a| a == "-g"), "{:?}", step.args);
|
||||
assert!(step.args.windows(4).any(|w| w == ["-source", "1.8", "-target", "1.8"]), "{:?}", step.args);
|
||||
assert!(!step.args.iter().any(|a| a == "--release"), "{:?}", step.args);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn gradle_single_file_compiles_with_source_set_classpath_and_siblings() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root_buf = dunce::canonicalize(dir.path()).unwrap();
|
||||
let root = root_buf.as_path();
|
||||
write(root, "settings.gradle", "include ':lib', ':app'");
|
||||
write(root, "lib/build.gradle", "plugins { id 'java' }");
|
||||
write(root, "app/build.gradle", "plugins { id 'java' }");
|
||||
write(root, "app/src/main/java/demo/App.java", "package demo; class App {}");
|
||||
write(root, "app/src/test/java/demo/AppTest.java", "package demo; class AppTest {}");
|
||||
fs::create_dir_all(root.join("lib/build/classes/java/main")).unwrap();
|
||||
fs::create_dir_all(root.join("app/build/classes/java/main")).unwrap();
|
||||
let wrapper = root.join("gradlew");
|
||||
fs::write(
|
||||
&wrapper,
|
||||
"#!/bin/sh\nprintf '%s\\n' \"$@\" > gradle_args.txt\nscope='main'\nfor a in \"$@\"; do\ncase \"$a\" in -Popenidea.scope=*) scope=\"${a#-Popenidea.scope=}\" ;; esac\ndone\nprintf '@openidea-compile-cp\\t{\"outDir\":\"%s/app/build/classes/java/%s\",\"classpath\":[\"%s/deps/guava.jar\"],\"srcDirs\":[\"%s/app/src/%s/java\"],\"release\":17}\\n' \"$PWD\" \"$scope\" \"$PWD\" \"$PWD\" \"$scope\"\n",
|
||||
)
|
||||
.unwrap();
|
||||
fs::set_permissions(&wrapper, fs::Permissions::from_mode(0o755)).unwrap();
|
||||
|
||||
let model = crate::load(root, &root.join("cache"), None);
|
||||
let cache = root.join("cache");
|
||||
let cancel = CancellationToken::new();
|
||||
|
||||
let main_file = root.join("app/src/main/java/demo/App.java");
|
||||
let main_plan = gradle_compile_file_plan(root, &model, &main_file, &cache, &cancel).unwrap();
|
||||
assert_eq!(main_plan.system, BuildSystem::Gradle);
|
||||
assert_eq!(main_plan.title, "Compile App.java");
|
||||
let step = &main_plan.steps[0];
|
||||
let args = fs::read_to_string(root.join("gradle_args.txt")).unwrap();
|
||||
assert!(args.lines().any(|a| a == "-Popenidea.target=:app"), "{args}");
|
||||
assert!(args.lines().any(|a| a == "-Popenidea.scope=main"), "{args}");
|
||||
let cp = &step.args[step.args.iter().position(|a| a == "-cp").unwrap() + 1];
|
||||
let paths: Vec<_> = std::env::split_paths(cp).collect();
|
||||
assert!(paths.contains(&root.join("app/build/classes/java/main")), "{cp}");
|
||||
assert!(paths.contains(&root.join("lib/build/classes/java/main")), "{cp}");
|
||||
assert!(paths.contains(&root.join("deps/guava.jar")), "{cp}");
|
||||
assert!(step.args.windows(2).any(|w| w == ["--release", "17"]), "{:?}", step.args);
|
||||
assert!(step.args.iter().any(|a| a == "-implicit:none"), "{:?}", step.args);
|
||||
|
||||
let test_file = root.join("app/src/test/java/demo/AppTest.java");
|
||||
let test_plan = gradle_compile_file_plan(root, &model, &test_file, &cache, &cancel).unwrap();
|
||||
assert_eq!(test_plan.title, "Compile AppTest.java");
|
||||
let test_step = &test_plan.steps[0];
|
||||
let args = fs::read_to_string(root.join("gradle_args.txt")).unwrap();
|
||||
assert!(args.lines().any(|a| a == "-Popenidea.scope=test"), "{args}");
|
||||
assert!(
|
||||
test_step.args.windows(2).any(|w| w == ["-d", &root.join("app/build/classes/java/test").to_string_lossy()])
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -162,16 +162,6 @@ 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('_', ".");
|
||||
@@ -179,6 +169,25 @@ 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`.
|
||||
@@ -203,16 +212,7 @@ pub fn structure_plan(
|
||||
return Ok(None);
|
||||
}
|
||||
let (main_out, test_out) = structure_outputs(root, ps);
|
||||
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 (level, env, javac) = structure_compiler(root, ps, jdk, language_level);
|
||||
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(release_args(level, jdk));
|
||||
step.args.extend(single::release_args(level, jdk.map(|j| j.major)));
|
||||
step.args.push(format!("@{}", args_file.to_string_lossy()));
|
||||
step.env = env.clone();
|
||||
step.mkdirs = vec![out.to_path_buf()];
|
||||
@@ -281,6 +281,47 @@ 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)
|
||||
@@ -1008,4 +1049,99 @@ 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
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
// 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])
|
||||
}
|
||||
@@ -336,6 +336,7 @@ 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 {
|
||||
@@ -348,6 +349,7 @@ impl Default for CodeEditingSettings {
|
||||
quick_doc_delay: 500,
|
||||
next_error_errors_only: true,
|
||||
sticky_lines_max: 5,
|
||||
sticky_lines_disabled_languages: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -585,3 +587,20 @@ mod folding_tests {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[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);
|
||||
}
|
||||
}
|
||||
@@ -41,6 +41,11 @@ pub enum ErrorData {
|
||||
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
|
||||
|
||||
@@ -460,6 +460,16 @@ 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")]
|
||||
@@ -487,6 +497,8 @@ 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,
|
||||
}
|
||||
|
||||
@@ -508,6 +520,7 @@ 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(),
|
||||
}
|
||||
}
|
||||
@@ -718,4 +731,19 @@ mod tests {
|
||||
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,5 +1,6 @@
|
||||
//! Class-table snapshots of a debugged JVM, read over the HotSpot attach listener or, where
|
||||
//! that is unavailable, counted by the debugger; and the JVM's objects through the debugger.
|
||||
//! that is unavailable, counted by the debugger; the JVM's objects through the debugger; and
|
||||
//! its thread dumps.
|
||||
|
||||
mod fallback;
|
||||
mod heap;
|
||||
@@ -10,6 +11,7 @@ mod snapshot;
|
||||
pub(crate) mod test_support;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
mod threads;
|
||||
|
||||
use crate::session::Session;
|
||||
use crate::session::Suspension;
|
||||
@@ -28,6 +30,8 @@ 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);
|
||||
@@ -190,6 +194,25 @@ 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 {
|
||||
@@ -206,6 +229,8 @@ 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),
|
||||
}
|
||||
@@ -261,6 +286,7 @@ 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),
|
||||
|
||||
@@ -15,7 +15,8 @@ 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 or a heap dump makes, so tests can stand in for a JVM.
|
||||
/// The attach calls a snapshot, a heap dump or a thread 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.
|
||||
@@ -27,6 +28,11 @@ 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 {
|
||||
@@ -73,6 +79,18 @@ 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 {
|
||||
|
||||
@@ -3,6 +3,7 @@ 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};
|
||||
@@ -39,6 +40,13 @@ 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>;
|
||||
@@ -97,6 +105,10 @@ 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()),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -167,6 +179,20 @@ 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";
|
||||
@@ -1160,6 +1186,341 @@ 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"]) {
|
||||
|
||||
@@ -0,0 +1,181 @@
|
||||
//! 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 } }
|
||||
}
|
||||
@@ -27,7 +27,7 @@ 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, SharedSink};
|
||||
use ide_core::{DebugSessionId, IdeError, IdeResult, RunId, SharedSink};
|
||||
use ide_language::LanguageRegistry;
|
||||
pub use js_cdp::JsResponseRule;
|
||||
pub use js_debug::JsResponseBody;
|
||||
@@ -460,6 +460,15 @@ 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
|
||||
@@ -1047,7 +1056,7 @@ impl DebugManager {
|
||||
adapter_name: String,
|
||||
parent: Option<DebugSessionId>,
|
||||
request: String,
|
||||
arguments: Value,
|
||||
mut arguments: Value,
|
||||
spec: AdapterSpec,
|
||||
reuse_port: Option<u16>,
|
||||
exception_classes: Option<Arc<dyn ide_jvm_inspect::ExceptionClassBreakpoints>>,
|
||||
@@ -1067,6 +1076,7 @@ impl DebugManager {
|
||||
.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);
|
||||
if let Some(launch_type) = arguments.get("type").and_then(Value::as_str) {
|
||||
let _ = session.launch_type.set(launch_type.to_owned());
|
||||
@@ -1967,6 +1977,34 @@ 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(
|
||||
|
||||
@@ -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, TaskId};
|
||||
use ide_core::{DebugSessionId, IdeEvent, RunId, TaskId};
|
||||
use parking_lot::Mutex;
|
||||
use serde_json::{Value, json};
|
||||
use std::collections::{BTreeSet, HashMap};
|
||||
@@ -117,6 +117,9 @@ 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>>,
|
||||
@@ -333,6 +336,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(),
|
||||
|
||||
@@ -3074,6 +3074,55 @@ 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() {
|
||||
|
||||
@@ -316,6 +316,7 @@ impl ClickhousePool {
|
||||
has_more,
|
||||
elapsed_ms: started.elapsed().as_secs_f64() * 1000.0,
|
||||
execution_ms,
|
||||
truncated: Vec::new(),
|
||||
})
|
||||
};
|
||||
let result = tokio::select! {
|
||||
|
||||
+241
-48
@@ -48,6 +48,65 @@ 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.
|
||||
@@ -486,6 +545,86 @@ 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 {
|
||||
@@ -493,44 +632,8 @@ 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);
|
||||
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)),
|
||||
}
|
||||
drain(&mut stream, &mut Reader::default(), $skip, $max, $mode, |done| done.rows_affected()).await
|
||||
}};
|
||||
}
|
||||
|
||||
@@ -586,6 +689,31 @@ 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(';');
|
||||
@@ -985,6 +1113,12 @@ 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 {
|
||||
@@ -1403,17 +1537,7 @@ impl Held {
|
||||
Held::Clickhouse(_) | Held::Snowflake(..) => unreachable!(),
|
||||
};
|
||||
self.after_statement(sql);
|
||||
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),
|
||||
})
|
||||
Ok(query_result(sql, fetched, started))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1439,6 +1563,75 @@ 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 prefer_retries_without_tls_only_after_a_failed_handshake() {
|
||||
use std::io;
|
||||
|
||||
@@ -0,0 +1,474 @@
|
||||
//! 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));
|
||||
}
|
||||
}
|
||||
@@ -606,6 +606,7 @@ 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(),
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -21,7 +21,7 @@ mod watch;
|
||||
pub use watch::SourcesWatch;
|
||||
|
||||
pub use catalog::{CatalogDatabase, CatalogSchema, SourceCatalog};
|
||||
pub use conn::{Held, Pool, QueryResult, ResultColumn};
|
||||
pub use conn::{Held, Pool, QueryResult, ResultColumn, TruncatedCell};
|
||||
pub use history::HistoryEntry;
|
||||
pub use plan::{PlanNode, PlanProperty};
|
||||
pub use source::{
|
||||
@@ -273,6 +273,8 @@ 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>>>,
|
||||
@@ -432,6 +434,7 @@ impl DbManager {
|
||||
session_passwords: Mutex::default(),
|
||||
on_disk: Mutex::default(),
|
||||
sessions: Mutex::default(),
|
||||
cursors: conn::Cursors::default(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -975,6 +978,7 @@ impl DbManager {
|
||||
if let Some(s) = session {
|
||||
end_session(&s).await;
|
||||
}
|
||||
self.cursors.release_target(id);
|
||||
let pool = self.pools.lock().remove(id);
|
||||
if let Some(p) = pool {
|
||||
p.close().await;
|
||||
@@ -1572,6 +1576,25 @@ 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)
|
||||
@@ -1643,12 +1666,44 @@ 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;
|
||||
|
||||
@@ -283,6 +283,7 @@ mod tests {
|
||||
has_more: false,
|
||||
elapsed_ms: 0.0,
|
||||
execution_ms: 0.0,
|
||||
truncated: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -892,6 +892,7 @@ impl SnowflakePool {
|
||||
has_more,
|
||||
elapsed_ms: started.elapsed().as_secs_f64() * 1000.0,
|
||||
execution_ms,
|
||||
truncated: Vec::new(),
|
||||
})))
|
||||
}
|
||||
|
||||
|
||||
@@ -298,3 +298,27 @@ async fn dumps_and_restores_with_the_client_tools() -> IdeResult<()> {
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn later_pages_continue_the_result_where_the_previous_page_stopped() -> IdeResult<()> {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let Some(db) = manager(&tmp, "").await else { return Ok(()) };
|
||||
let c = CancellationToken::new();
|
||||
let query = "WITH RECURSIVE n(id) AS (SELECT 1 UNION ALL SELECT id + 1 FROM n WHERE id < 1000) \
|
||||
SELECT id, REPEAT('x', 10) AS pad FROM n ORDER BY id";
|
||||
// Forward, back, and jumping: every page holds its own rows whichever cursor served it.
|
||||
for page in [0, 1, 2, 3, 1, 7, 8, 9, 4, 0] {
|
||||
let r = db.execute_from("m", query, page * 100, 100, &c, None).await?;
|
||||
let ids: Vec<_> = r.rows.iter().map(|row| row[0].clone().unwrap()).collect();
|
||||
let want: Vec<_> = (page * 100 + 1..=page * 100 + 100).map(|n| n.to_string()).collect();
|
||||
assert_eq!(ids, want, "page {page}");
|
||||
assert_eq!(r.has_more, page < 9, "page {page}");
|
||||
}
|
||||
// A pool of 4 connections: cursors that were left open must not exhaust it.
|
||||
for _ in 0..8 {
|
||||
db.execute_from("m", query, 100, 100, &c, None).await?;
|
||||
db.release_result("m", query, None);
|
||||
assert_eq!(db.execute("m", "SELECT 1", 1, &c).await?.rows[0][0].as_deref(), Some("1"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -342,3 +342,59 @@ async fn dumps_and_restores_with_the_client_tools() -> IdeResult<()> {
|
||||
db.execute("p", "DROP DATABASE oi_restore", 1, &c).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn later_pages_continue_the_result_where_the_previous_page_stopped() -> IdeResult<()> {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let Some(db) = manager(&tmp).await else { return Ok(()) };
|
||||
let c = CancellationToken::new();
|
||||
let query = "SELECT g AS id, repeat('x', 10) AS pad FROM generate_series(1, 1000) g ORDER BY g";
|
||||
// Forward, back, and jumping: every page holds its own rows whichever cursor served it.
|
||||
for page in [0, 1, 2, 3, 1, 7, 8, 9, 4, 0] {
|
||||
let r = db.execute_from("p", query, page * 100, 100, &c, None).await?;
|
||||
let ids: Vec<_> = r.rows.iter().map(|row| row[0].clone().unwrap()).collect();
|
||||
let want: Vec<_> = (page * 100 + 1..=page * 100 + 100).map(|n| n.to_string()).collect();
|
||||
assert_eq!(ids, want, "page {page}");
|
||||
assert_eq!(r.has_more, page < 9, "page {page}");
|
||||
}
|
||||
// A pool of 4 connections: cursors that were left open must not exhaust it.
|
||||
for _ in 0..8 {
|
||||
db.execute_from("p", query, 100, 100, &c, None).await?;
|
||||
db.release_result("p", query, None);
|
||||
assert_eq!(db.execute("p", "SELECT 1", 1, &c).await?.rows[0][0].as_deref(), Some("1"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cancelling_a_later_page_stops_its_statement_on_the_server() -> IdeResult<()> {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let Some(db) = manager(&tmp).await else { return Ok(()) };
|
||||
let marker = "oi_cursor_cancel_marker";
|
||||
let slow = format!("SELECT g, pg_sleep(0.05) AS {marker} FROM generate_series(1, 100000) g");
|
||||
let cancel = CancellationToken::new();
|
||||
let stop = cancel.clone();
|
||||
tokio::spawn(async move {
|
||||
tokio::time::sleep(std::time::Duration::from_millis(500)).await;
|
||||
stop.cancel();
|
||||
});
|
||||
let started = std::time::Instant::now();
|
||||
let e = db.execute_from("p", &slow, 5, 10, &cancel, None).await.unwrap_err();
|
||||
assert_eq!(e.kind, ide_core::error::ErrorKind::Cancelled);
|
||||
assert!(started.elapsed() < std::time::Duration::from_secs(5));
|
||||
let c = CancellationToken::new();
|
||||
let active = format!(
|
||||
"SELECT count(*) FROM pg_stat_activity WHERE state = 'active' AND query LIKE '%{marker}%' \
|
||||
AND query NOT LIKE '%pg_stat_activity%'"
|
||||
);
|
||||
let mut running = 1;
|
||||
for _ in 0..20 {
|
||||
running = db.execute("p", &active, 1, &c).await?.rows[0][0].as_deref().unwrap().parse().unwrap();
|
||||
if running == 0 {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
|
||||
}
|
||||
assert_eq!(running, 0, "the cancelled statement still runs on the server");
|
||||
Ok(())
|
||||
}
|
||||
@@ -557,6 +557,53 @@ fn map_layers(layers: Vec<ApiLayer>, now: i64) -> Vec<DockerImageLayer> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Per-volume disk usage (`GET /system/df?type=volume`).
|
||||
pub(crate) fn volume_sizes(ep: &DockerEndpoint, timeout: Duration) -> Option<IdeResult<BTreeMap<String, String>>> {
|
||||
let addr = address(ep)?;
|
||||
Some((|| {
|
||||
let body = check(request(&addr, "GET", "/system/df?type=volume", timeout)?)?;
|
||||
map_volume_sizes(&body)
|
||||
})())
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Default)]
|
||||
#[serde(rename_all = "PascalCase", default)]
|
||||
struct ApiDiskUsage {
|
||||
volumes: Option<Vec<ApiVolumeUsage>>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Default)]
|
||||
#[serde(rename_all = "PascalCase", default)]
|
||||
struct ApiVolumeUsage {
|
||||
name: String,
|
||||
usage_data: Option<ApiVolumeUsageData>,
|
||||
}
|
||||
|
||||
const fn unknown_volume_size() -> i64 {
|
||||
-1
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Default)]
|
||||
#[serde(rename_all = "PascalCase", default)]
|
||||
struct ApiVolumeUsageData {
|
||||
#[serde(default = "unknown_volume_size")]
|
||||
size: i64,
|
||||
}
|
||||
|
||||
fn map_volume_sizes(body: &str) -> IdeResult<BTreeMap<String, String>> {
|
||||
let parsed = serde_json::from_str::<ApiDiskUsage>(body)
|
||||
.map_err(|e| IdeError::internal(format!("the Docker daemon's disk usage is not JSON: {e}")))?;
|
||||
Ok(parsed
|
||||
.volumes
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.filter_map(|v| {
|
||||
let size = v.usage_data?.size;
|
||||
(!v.name.is_empty() && size >= 0).then(|| (v.name, human_size(size)))
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
fn unix_now() -> i64 {
|
||||
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs() as i64).unwrap_or(0)
|
||||
}
|
||||
@@ -1158,6 +1205,15 @@ mod tests {
|
||||
(top.titles, top.processes),
|
||||
(vec!["PID".to_owned(), "CMD".to_owned()], vec![vec!["1".to_owned(), "sh".to_owned()]])
|
||||
);
|
||||
let sizes = map_volume_sizes(
|
||||
r#"{"Volumes":[{"Name":"shop_pgdata","UsageData":{"RefCount":1,"Size":145442}},{"Name":"empty","UsageData":{"RefCount":0,"Size":0}},{"Name":"remote","UsageData":{"RefCount":1,"Size":-1}},{"Name":"missing","UsageData":null}]}"#,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(sizes.get("shop_pgdata").map(String::as_str), Some("145.442kB"));
|
||||
assert_eq!(sizes.get("empty").map(String::as_str), Some("0B"));
|
||||
assert!(!sizes.contains_key("remote"));
|
||||
assert!(!sizes.contains_key("missing"));
|
||||
assert!(map_volume_sizes(r#"{"Volumes":null}"#).unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -315,6 +315,17 @@ pub fn container_stats(ep: &DockerEndpoint, id: &str) -> IdeResult<DockerContain
|
||||
parse_container_stats(&out).ok_or_else(|| IdeError::not_found("no container stats returned"))
|
||||
}
|
||||
|
||||
/// Per-volume disk usage (`docker system df -v --format '{{json .Volumes}}'`).
|
||||
pub fn volume_sizes(ep: &DockerEndpoint) -> IdeResult<std::collections::BTreeMap<String, String>> {
|
||||
if docker_executable().is_none()
|
||||
&& let Some(sizes) = engine::volume_sizes(ep, QUICK)
|
||||
{
|
||||
return sizes;
|
||||
}
|
||||
let out = run(ep, &["system", "df", "-v", "--format", "{{json .Volumes}}"], QUICK)?;
|
||||
Ok(parse_volume_sizes(&out))
|
||||
}
|
||||
|
||||
/// How long log lines collect before they are handed on together.
|
||||
const LOG_BATCH: Duration = Duration::from_millis(30);
|
||||
|
||||
|
||||
@@ -473,6 +473,33 @@ pub fn parse_container_stats(text: &str) -> Option<DockerContainerStats> {
|
||||
})
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Default)]
|
||||
#[serde(rename_all = "PascalCase", default)]
|
||||
struct RawVolumeUsage {
|
||||
name: String,
|
||||
size: String,
|
||||
}
|
||||
|
||||
/// `docker system df -v --format '{{json .Volumes}}'` volume name → human size.
|
||||
pub fn parse_volume_sizes(text: &str) -> BTreeMap<String, String> {
|
||||
let trimmed = text.trim();
|
||||
let items: Vec<RawVolumeUsage> = if trimmed.is_empty() || trimmed == "null" {
|
||||
Vec::new()
|
||||
} else if let Ok(parsed) = serde_json::from_str::<Option<Vec<RawVolumeUsage>>>(trimmed) {
|
||||
parsed.unwrap_or_default()
|
||||
} else {
|
||||
lines::<RawVolumeUsage>(text).collect()
|
||||
};
|
||||
items
|
||||
.into_iter()
|
||||
.filter(|v| {
|
||||
let size = v.size.trim();
|
||||
!v.name.is_empty() && !size.is_empty() && !size.eq_ignore_ascii_case("n/a")
|
||||
})
|
||||
.map(|v| (v.name, v.size.trim().to_owned()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Default)]
|
||||
#[serde(default)]
|
||||
struct RawVersion {
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
use ide_docker::{
|
||||
PS_FORMAT, parse_container_stats, parse_container_top, parse_containers, parse_image_history, parse_images,
|
||||
parse_networks, parse_volumes,
|
||||
parse_networks, parse_volume_sizes, parse_volumes,
|
||||
};
|
||||
|
||||
const PS: &str = include_str!("fixtures/ps.jsonl");
|
||||
@@ -113,4 +113,12 @@ fn image_history_top_and_stats() {
|
||||
assert_eq!(stats.net_io, "12kB / 8kB");
|
||||
assert_eq!(stats.block_io, "1.2MB / 0B");
|
||||
assert_eq!(stats.pids, "14");
|
||||
|
||||
let df_volumes = r#"[{"Availability":"N/A","Driver":"local","Links":"4","Mountpoint":"/var/lib/docker/volumes/selfhost_runner-persist/_data","Name":"selfhost_runner-persist","Scope":"local","Size":"145.4kB"},{"Name":"unused_anon","Size":"0B"},{"Name":"remote_nfs","Size":"N/A"}]"#;
|
||||
let volume_sizes = parse_volume_sizes(df_volumes);
|
||||
assert_eq!(volume_sizes.get("selfhost_runner-persist").map(String::as_str), Some("145.4kB"));
|
||||
assert_eq!(volume_sizes.get("unused_anon").map(String::as_str), Some("0B"));
|
||||
assert!(!volume_sizes.contains_key("remote_nfs"));
|
||||
assert!(parse_volume_sizes("null\n").is_empty());
|
||||
assert!(parse_volume_sizes("").is_empty());
|
||||
}
|
||||
@@ -34,7 +34,7 @@ use std::path::{Component, Path, PathBuf};
|
||||
|
||||
pub const MANIFEST_FILE: &str = "plugin.toml";
|
||||
/// The plugin API (engine) version this host implements.
|
||||
pub const ENGINE_VERSION: &str = "1.15.0";
|
||||
pub const ENGINE_VERSION: &str = "1.16.0";
|
||||
/// The 0.1 API, still accepted for contribution-only packages and 0.1 components.
|
||||
pub const LEGACY_API: &str = "0.1";
|
||||
/// Marketplace categories, in the order they are shown.
|
||||
|
||||
@@ -68,6 +68,7 @@ specta.workspace = true
|
||||
specta-typescript.workspace = true
|
||||
tokio = { workspace = true, features = ["io-std"] }
|
||||
tracing.workspace = true
|
||||
url = "2"
|
||||
tracing-subscriber.workspace = true
|
||||
parking_lot.workspace = true
|
||||
dunce.workspace = true
|
||||
|
||||
@@ -514,6 +514,7 @@ fn cmd_keygen(args: &[String]) -> Result<(), String> {
|
||||
let mut seed = [0u8; 32];
|
||||
getrandom::fill(&mut seed).map_err(|e| format!("random: {e}"))?;
|
||||
let key = PublisherKey::from_seed(seed);
|
||||
create_parent(Path::new(file))?;
|
||||
std::fs::write(file, key.seed_base64()).map_err(|e| format!("{file}: {e}"))?;
|
||||
#[cfg(unix)]
|
||||
{
|
||||
@@ -577,7 +578,8 @@ fn cmd_pack(args: &[String]) -> Result<(), String> {
|
||||
let out = a.value("out").map(PathBuf::from).unwrap_or_else(|| {
|
||||
PathBuf::from(format!("{}-{}.{}", manifest.id, manifest.version, package::PACKAGE_EXTENSION))
|
||||
});
|
||||
package::pack(&dir, &files, &out, signature.as_ref())?;
|
||||
create_parent(&out)?;
|
||||
package::pack(&dir, &files, &out, signature.as_ref()).map_err(|e| format!("{}: {e}", out.display()))?;
|
||||
let size = std::fs::metadata(&out).map(|m| m.len()).unwrap_or(0);
|
||||
let signed = signature.as_ref().map_or("unsigned".to_owned(), |s| format!("signed by {}", s.publisher));
|
||||
println!("-> {} ({}, {signed})", out.display(), human_size(size));
|
||||
@@ -764,8 +766,17 @@ fn cmd_merge(args: &[String]) -> Result<(), String> {
|
||||
write_index(&index, Path::new(out))
|
||||
}
|
||||
|
||||
/// Creates the directories an output file goes into.
|
||||
fn create_parent(file: &Path) -> Result<(), String> {
|
||||
match file.parent() {
|
||||
Some(parent) => std::fs::create_dir_all(parent).map_err(|e| format!("{}: {e}", parent.display())),
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
fn write_index(index: &Index, out: &Path) -> Result<(), String> {
|
||||
let json = serde_json::to_string_pretty(index).map_err(|e| e.to_string())?;
|
||||
create_parent(out)?;
|
||||
std::fs::write(out, json).map_err(|e| format!("{}: {e}", out.display()))?;
|
||||
println!("-> {} ({} plugins)", out.display(), index.plugins.len());
|
||||
Ok(())
|
||||
@@ -856,6 +867,48 @@ mod tests {
|
||||
cmd_pack(&args).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn output_files_go_into_missing_directories() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let t = tmp.path();
|
||||
let key = t.join("config/openidea/acme.key");
|
||||
cmd_keygen(&strings(&[key.to_str().unwrap()])).unwrap();
|
||||
assert!(read_key(key.to_str().unwrap()).is_ok());
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
assert_eq!(std::fs::metadata(&key).unwrap().permissions().mode() & 0o777, 0o600);
|
||||
}
|
||||
let key = key.to_string_lossy().into_owned();
|
||||
// `signed_theme` creates `out` itself, so pack into a directory it doesn't know about.
|
||||
signed_theme(t, "acme.night", "acme", &key, &t.join("staging"));
|
||||
let package = t.join("dist/v1/acme.night.oiplugin");
|
||||
let src = t.join("src/acme.night-0.1.0");
|
||||
cmd_pack(&strings(&[
|
||||
src.to_str().unwrap(),
|
||||
"--key",
|
||||
&key,
|
||||
"--publisher",
|
||||
"acme",
|
||||
"--out",
|
||||
package.to_str().unwrap(),
|
||||
]))
|
||||
.unwrap();
|
||||
assert!(package.is_file());
|
||||
let index = t.join("site/market/index.json");
|
||||
cmd_index(&strings(&[
|
||||
t.join("dist/v1").to_str().unwrap(),
|
||||
"--publisher",
|
||||
"acme",
|
||||
"--key",
|
||||
&key,
|
||||
"--out",
|
||||
index.to_str().unwrap(),
|
||||
]))
|
||||
.unwrap();
|
||||
assert!(index.is_file());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_release_keeps_the_versions_older_ides_need() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -106,6 +106,7 @@ pub struct Host {
|
||||
syntax: Arc<OnceLock<Arc<Syntax>>>,
|
||||
pub global_settings: SettingsStore,
|
||||
pub dependency_versions: Arc<ide_workspace::dependencies::VersionCache>,
|
||||
pub pypi_names: Arc<ide_workspace::dependencies::pypi::NameCache>,
|
||||
pub terminals: TerminalManager,
|
||||
pub processes: ProcessManager,
|
||||
/// Debug sessions (adapters run on this machine, next to the project).
|
||||
@@ -207,6 +208,7 @@ impl Host {
|
||||
dependency_versions: Arc::new(ide_workspace::dependencies::VersionCache::new(
|
||||
data_dir.join("cache/dependency-versions"),
|
||||
)),
|
||||
pypi_names: Arc::new(ide_workspace::dependencies::pypi::NameCache::new(data_dir.join("cache"))),
|
||||
// Sessions, runs and terminals report to the window that started them (`window_sink`).
|
||||
terminals: TerminalManager::new(),
|
||||
processes: ProcessManager::new(),
|
||||
|
||||
@@ -870,6 +870,7 @@ async fn occurrences(
|
||||
max_matches: 0,
|
||||
context,
|
||||
include_excluded: false,
|
||||
skip_large_files: false,
|
||||
};
|
||||
let host = call.host();
|
||||
let request = crate::mcp::tool::request_id();
|
||||
|
||||
@@ -650,6 +650,7 @@ async fn text_search(call: Call, is_regex: bool) -> IdeResult<Output> {
|
||||
max_matches,
|
||||
context: Default::default(),
|
||||
include_excluded: call.flag("includeExcluded", false)?,
|
||||
skip_large_files: false,
|
||||
};
|
||||
if is_regex && let Err(e) = ide_search::match_ranges("", &query) {
|
||||
return Err(IdeError::invalid(format!("Invalid regex pattern: {pattern} ({})", e.message)));
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Agents tool window: coding agent tasks of the project (over ACP). In a remote
|
||||
//! window they run on the host, next to the project they work on.
|
||||
use super::Channel;
|
||||
use super::{Channel, blocking, blocking_value};
|
||||
use crate::Host;
|
||||
use crate::agent_secrets::{AgentSecrets, Kept};
|
||||
use ide_agent::registry::{AgentRegistry, RegistryPaths};
|
||||
@@ -63,9 +63,7 @@ pub async fn agent_providers(host: &Host, window: &str) -> IdeResult<Vec<AgentPr
|
||||
pub async fn agent_hermes_profiles(host: &Host, window: &str) -> IdeResult<Vec<ide_agent::hermes::HermesProfile>> {
|
||||
host.require_trust(window)?;
|
||||
let root = ide_agent::hermes::root(dirs::home_dir().as_deref());
|
||||
tokio::task::spawn_blocking(move || root.map(|r| ide_agent::hermes::labeled_profiles(&r)).unwrap_or_default())
|
||||
.await
|
||||
.map_err(join_err)
|
||||
blocking_value(move || root.map(|r| ide_agent::hermes::labeled_profiles(&r)).unwrap_or_default()).await
|
||||
}
|
||||
|
||||
/// Refreshes the model catalog; force bypasses freshness, not the cooldown.
|
||||
@@ -126,20 +124,15 @@ pub(crate) fn registry_paths(host: &Host) -> RegistryPaths {
|
||||
RegistryPaths::new(&host.config_dir, &host.local_data_dir)
|
||||
}
|
||||
|
||||
fn join_err(e: impl std::fmt::Display) -> IdeError {
|
||||
IdeError::internal(e.to_string())
|
||||
}
|
||||
|
||||
/// Agents of the ACP Registry this machine can run, with what is installed; the list
|
||||
/// saved earlier when the registry is unreachable. Cancel with `cancel_request(request)`.
|
||||
#[command(trust = always)]
|
||||
pub async fn agent_registry_list(host: &Host, request: RequestId) -> IdeResult<AgentRegistry> {
|
||||
let paths = registry_paths(host);
|
||||
let cancel = host.begin_request(request);
|
||||
let result =
|
||||
tokio::task::spawn_blocking(move || ide_agent::registry::list(&paths, &cancel)).await.map_err(join_err);
|
||||
let result = blocking(move || ide_agent::registry::list(&paths, &cancel)).await;
|
||||
host.end_request(request);
|
||||
let mut registry = result??;
|
||||
let mut registry = result?;
|
||||
let installing = installing();
|
||||
for agent in &mut registry.agents {
|
||||
agent.installing = installing.contains(&agent.id);
|
||||
@@ -204,7 +197,7 @@ pub async fn agent_registry_install(
|
||||
});
|
||||
}
|
||||
};
|
||||
let result = tokio::task::spawn_blocking(move || {
|
||||
let result = blocking(move || {
|
||||
let _installing = installing;
|
||||
let _cancel = ide_core::task::on_cancel(task, {
|
||||
let cancel = cancel.clone();
|
||||
@@ -223,10 +216,9 @@ pub async fn agent_registry_install(
|
||||
report(None, Some(1.0), true);
|
||||
result
|
||||
})
|
||||
.await
|
||||
.map_err(join_err);
|
||||
.await;
|
||||
host.end_request(request);
|
||||
result??;
|
||||
result?;
|
||||
for project in host.projects() {
|
||||
project.agents.reload_providers();
|
||||
}
|
||||
@@ -237,7 +229,7 @@ pub async fn agent_registry_install(
|
||||
#[command(trust = always)]
|
||||
pub async fn agent_registry_remove(host: &Host, id: String) -> IdeResult<()> {
|
||||
let paths = registry_paths(host);
|
||||
tokio::task::spawn_blocking(move || ide_agent::registry::remove(&paths, &id)).await.map_err(join_err)??;
|
||||
blocking(move || ide_agent::registry::remove(&paths, &id)).await?;
|
||||
for project in host.projects() {
|
||||
project.agents.reload_providers();
|
||||
}
|
||||
@@ -273,7 +265,7 @@ pub async fn agent_entries(
|
||||
pub async fn agent_external_sessions(host: &Host, window: &str) -> IdeResult<Vec<ExternalSession>> {
|
||||
// Reads transcripts from disk on the blocking pool.
|
||||
let agents = host.project(window)?.agents.clone();
|
||||
tokio::task::spawn_blocking(move || agents.external_sessions()).await.map_err(join_err)
|
||||
blocking_value(move || agents.external_sessions()).await
|
||||
}
|
||||
|
||||
/// Imports an external session as a task: its first turn loads and replays it.
|
||||
@@ -286,7 +278,7 @@ pub async fn agent_import_session(
|
||||
) -> IdeResult<AgentTask> {
|
||||
host.require_trust(window)?;
|
||||
let agents = host.project(window)?.agents.clone();
|
||||
tokio::task::spawn_blocking(move || agents.import_session(&provider, &session_id)).await.map_err(join_err)?
|
||||
blocking(move || agents.import_session(&provider, &session_id)).await
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
@@ -408,14 +400,13 @@ async fn cli_update(
|
||||
let project = host.project(window)?;
|
||||
let installing = offer.as_ref().map(|_| Installing::begin(&provider)).transpose()?;
|
||||
let cancel = host.begin_project_request(window, request);
|
||||
let result = tokio::task::spawn_blocking(move || {
|
||||
let result = blocking(move || {
|
||||
let _installing = installing;
|
||||
project.agents.cli_update(&provider, offer.as_ref(), &cancel)
|
||||
})
|
||||
.await
|
||||
.map_err(join_err);
|
||||
.await;
|
||||
host.end_request(request);
|
||||
result?
|
||||
result
|
||||
}
|
||||
|
||||
/// What the agent reports about itself when it starts (no session: no MCP servers, hooks
|
||||
@@ -818,11 +809,7 @@ pub fn agent_mcp_import(host: &Host, window: &str) -> IdeResult<Vec<McpServer>>
|
||||
pub async fn agent_mcp_discover_sources(host: &Host, window: &str) -> IdeResult<Vec<McpExternalSource>> {
|
||||
let project_root = host.project(window).ok().filter(|p| !p.light).map(|p| p.root.clone());
|
||||
let home = dirs::home_dir();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
ide_agent::mcp::discover_external_sources(home.as_deref(), project_root.as_deref())
|
||||
})
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()))
|
||||
blocking_value(move || ide_agent::mcp::discover_external_sources(home.as_deref(), project_root.as_deref())).await
|
||||
}
|
||||
|
||||
/// Imports selected servers from discovered external MCP configuration files into User or Workspace scope.
|
||||
@@ -1061,7 +1048,7 @@ pub async fn agent_skills_list(host: &Host, window: &str) -> IdeResult<Vec<Agent
|
||||
let project = host.project(window).ok().filter(|p| !p.light);
|
||||
let policy = host_skills_policy(host, project.as_deref());
|
||||
let home = dirs::home_dir();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
blocking(move || {
|
||||
Ok(ide_agent::skills::resolve(
|
||||
ide_agent::skills::discover_skills_with_plugins(
|
||||
&policy.workspace_roots,
|
||||
@@ -1075,7 +1062,6 @@ pub async fn agent_skills_list(host: &Host, window: &str) -> IdeResult<Vec<Agent
|
||||
))
|
||||
})
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()))?
|
||||
}
|
||||
|
||||
/// Sets how `name` may run in `scope`, in the settings file of that scope, and returns the
|
||||
@@ -1139,14 +1125,13 @@ pub async fn agent_skills_browse(
|
||||
) -> IdeResult<RemoteSkillBrowseResult> {
|
||||
let cancel = host.begin_request(request);
|
||||
let search_path = ide_core::tool_path::search_path();
|
||||
let res = tokio::task::spawn_blocking(move || {
|
||||
let res = blocking(move || {
|
||||
let fetcher = ide_agent::skill_installer::GitHubHttpFetcher::new(&search_path)?;
|
||||
ide_agent::skill_installer::browse_skills(&fetcher, &source, &cancel)
|
||||
})
|
||||
.await
|
||||
.map_err(join_err);
|
||||
.await;
|
||||
host.end_request(request);
|
||||
res?
|
||||
res
|
||||
}
|
||||
|
||||
/// Fetches one skill's `SKILL.md`, file list, and static security scan warnings before installation.
|
||||
@@ -1164,7 +1149,7 @@ pub async fn agent_skills_preview(
|
||||
let ws_root = host.project(window).ok().filter(|p| !p.light).map(|p| p.root.clone());
|
||||
let home = dirs::home_dir();
|
||||
let search_path = ide_core::tool_path::search_path();
|
||||
let res = tokio::task::spawn_blocking(move || {
|
||||
let res = blocking(move || {
|
||||
let fetcher = ide_agent::skill_installer::GitHubHttpFetcher::new(&search_path)?;
|
||||
ide_agent::skill_installer::preview_skill(
|
||||
&fetcher,
|
||||
@@ -1175,10 +1160,9 @@ pub async fn agent_skills_preview(
|
||||
&cancel,
|
||||
)
|
||||
})
|
||||
.await
|
||||
.map_err(join_err);
|
||||
.await;
|
||||
host.end_request(request);
|
||||
res?
|
||||
res
|
||||
}
|
||||
|
||||
/// Installs the selected skill subtree into `~/.agents/skills` (User) or `<workspace>/.agents/skills` (Workspace).
|
||||
@@ -1199,7 +1183,7 @@ pub async fn agent_skills_install(
|
||||
let search_path = ide_core::tool_path::search_path();
|
||||
let install_home = home.clone();
|
||||
let install_ws = ws_root.clone();
|
||||
let res = tokio::task::spawn_blocking(move || {
|
||||
let res = blocking(move || {
|
||||
let fetcher = ide_agent::skill_installer::GitHubHttpFetcher::new(&search_path)?;
|
||||
ide_agent::skill_installer::install_skill(
|
||||
&fetcher,
|
||||
@@ -1209,10 +1193,9 @@ pub async fn agent_skills_install(
|
||||
&cancel,
|
||||
)
|
||||
})
|
||||
.await
|
||||
.map_err(join_err);
|
||||
.await;
|
||||
host.end_request(request);
|
||||
res??;
|
||||
res?;
|
||||
|
||||
let event = IdeEvent::SettingsChanged { key: "agents.skills".into() };
|
||||
for p in host.projects() {
|
||||
@@ -1221,7 +1204,7 @@ pub async fn agent_skills_install(
|
||||
}
|
||||
|
||||
let policy = host_skills_policy(host, project.as_deref());
|
||||
tokio::task::spawn_blocking(move || {
|
||||
blocking(move || {
|
||||
Ok(ide_agent::skills::resolve(
|
||||
ide_agent::skills::discover_skills_with_plugins(
|
||||
&policy.workspace_roots,
|
||||
@@ -1235,7 +1218,6 @@ pub async fn agent_skills_install(
|
||||
))
|
||||
})
|
||||
.await
|
||||
.map_err(join_err)?
|
||||
}
|
||||
|
||||
/// The user's and the workspace's skill policies (`[agents.skills.<name>]`).
|
||||
|
||||
@@ -8,7 +8,7 @@ use crate::Project;
|
||||
use crate::ops::Channel;
|
||||
use ide_command::command;
|
||||
|
||||
use super::doc::blocking;
|
||||
use super::blocking;
|
||||
use ide_analysis::{
|
||||
DuplicateOptions, DuplicatesReport, SourceFile, StructuralFile, StructuralQuery, StructuralSummary,
|
||||
};
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
pub(super) mod workspace;
|
||||
|
||||
use super::dependencies::{MavenCentralArtifacts, MavenCentralGroups, MavenCentralVersions};
|
||||
use super::{blocking, blocking_value};
|
||||
use crate::ops::Channel;
|
||||
use crate::{Host, Project};
|
||||
use ide_command::command;
|
||||
@@ -22,10 +23,6 @@ use std::path::{Path, PathBuf};
|
||||
use std::sync::{Arc, Mutex, OnceLock};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
fn join_err(e: tokio::task::JoinError) -> IdeError {
|
||||
IdeError::internal(e.to_string())
|
||||
}
|
||||
|
||||
/// POM gutters in several editors refresh together. A very short cache lets those
|
||||
/// requests share one reactor scan without serving a stale module list after edits settle.
|
||||
const MAVEN_MODULE_CACHE_TTL: Duration = Duration::from_millis(250);
|
||||
@@ -200,7 +197,7 @@ pub async fn build_model(host: &Host, window: &str) -> IdeResult<BuildModel> {
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
let config = host.config_dir.clone();
|
||||
tokio::task::spawn_blocking(move || workspace::load_project(&project, &config)).await.map_err(join_err)?
|
||||
blocking(move || workspace::load_project(&project, &config)).await
|
||||
}
|
||||
|
||||
fn linked_gradle_paths(
|
||||
@@ -253,7 +250,7 @@ fn linked_gradle_paths(
|
||||
async fn set_gradle_projects(host: &Host, window: &str, paths: Vec<String>, link: bool) -> IdeResult<BuildModel> {
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
tokio::task::spawn_blocking(move || {
|
||||
blocking(move || {
|
||||
if ide_workspace::workspace::Workspace::load(&project.root)?.is_some() {
|
||||
return Err(IdeError::invalid("Open a workspace member as a project to link Gradle builds"));
|
||||
}
|
||||
@@ -269,7 +266,6 @@ async fn set_gradle_projects(host: &Host, window: &str, paths: Vec<String>, link
|
||||
Ok::<BuildModel, IdeError>(load(&project.root, &project.build_cache_dir(), &settings))
|
||||
})
|
||||
.await
|
||||
.map_err(join_err)?
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
@@ -335,7 +331,7 @@ pub async fn build_sync(
|
||||
let bridge_profiles = profiles.clone();
|
||||
let p = project.clone();
|
||||
let config = host.config_dir.clone();
|
||||
let result = tokio::task::spawn_blocking(move || {
|
||||
let result = blocking(move || {
|
||||
let scopes = workspace::scopes(&p, &config)?;
|
||||
let selected: Vec<_> =
|
||||
scopes.iter().filter(|scope| workspace::selected(scope, &p.root, tool, build_dir.as_deref())).collect();
|
||||
@@ -416,10 +412,9 @@ pub async fn build_sync(
|
||||
};
|
||||
Ok::<_, IdeError>((model, profiles_changed || offline_changed, updates, snapshots))
|
||||
})
|
||||
.await
|
||||
.map_err(join_err);
|
||||
.await;
|
||||
let result = async {
|
||||
let (mut model, reconfigure, updates, snapshots) = result??;
|
||||
let (mut model, reconfigure, updates, snapshots) = result?;
|
||||
if completion_token.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
@@ -445,7 +440,7 @@ pub async fn build_sync(
|
||||
// JDT LS resolves the binary jars while importing Maven projects.
|
||||
update_java_projects(&lsp, &updates, reconfigure, Some(&completion_token)).await;
|
||||
let cancel = completion_token.clone();
|
||||
let (updated, refreshed) = tokio::task::spawn_blocking(move || {
|
||||
let (updated, refreshed) = blocking_value(move || {
|
||||
let mut refreshed = Vec::new();
|
||||
if let Some(maven) = &model.maven {
|
||||
for batch in snapshots {
|
||||
@@ -464,8 +459,7 @@ pub async fn build_sync(
|
||||
}
|
||||
(model, refreshed)
|
||||
})
|
||||
.await
|
||||
.map_err(join_err)?;
|
||||
.await?;
|
||||
model = updated;
|
||||
tokio::spawn(async move {
|
||||
refresh_library_archives(&lsp, &documents, &updates, refreshed).await;
|
||||
@@ -584,12 +578,11 @@ pub async fn gradle_published_catalog(
|
||||
coordinates: String,
|
||||
) -> IdeResult<Option<ide_core::IpcPath>> {
|
||||
let project = host.project(window)?;
|
||||
tokio::task::spawn_blocking(move || {
|
||||
blocking_value(move || {
|
||||
ide_sdk::libraries::published_version_catalog(&project.root, &project.settings.effective(), &coordinates)
|
||||
.map(Into::into)
|
||||
})
|
||||
.await
|
||||
.map_err(join_err)
|
||||
}
|
||||
|
||||
/// The resolved dependency tree of a Gradle project for one configuration (Dependency Analyzer).
|
||||
@@ -608,7 +601,7 @@ pub async fn gradle_dependencies(
|
||||
let project = host.project(window)?;
|
||||
let config = host.config_dir.clone();
|
||||
let token = host.begin_project_request(window, request);
|
||||
let result = tokio::task::spawn_blocking(move || {
|
||||
let result = blocking(move || {
|
||||
let scopes = workspace::scopes(&project, &config)?;
|
||||
let scope = scopes
|
||||
.iter()
|
||||
@@ -636,10 +629,9 @@ pub async fn gradle_dependencies(
|
||||
}
|
||||
Ok(report.dependencies)
|
||||
})
|
||||
.await
|
||||
.map_err(join_err);
|
||||
.await;
|
||||
host.end_request(request);
|
||||
result?
|
||||
result
|
||||
}
|
||||
|
||||
/// What the Dependency Analyzer has of the builds of `project` at `root` (the project, or one
|
||||
@@ -686,12 +678,11 @@ pub async fn maven_dependency_declaration(
|
||||
) -> IdeResult<Location> {
|
||||
let project = host.project(window)?;
|
||||
let config = host.config_dir.clone();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
blocking(move || {
|
||||
let (path, _, range) = declaring_pom(&project, &config, &pom, &dependency)?;
|
||||
Ok(Location::file(path, range))
|
||||
})
|
||||
.await
|
||||
.map_err(join_err)?
|
||||
}
|
||||
|
||||
/// The go-to-declaration target at `pos` of a Maven POM: the definition of the
|
||||
@@ -705,7 +696,7 @@ pub async fn maven_goto_declaration(host: &Host, window: &str, pom: String, pos:
|
||||
// without a managed version the target is the artifact's own POM (a project module's, or the
|
||||
// local repository's). `None` when nothing resolvable is under the caret.
|
||||
let project = host.project(window)?;
|
||||
tokio::task::spawn_blocking(move || {
|
||||
blocking(move || {
|
||||
let given = Path::new(&pom);
|
||||
let path = if given.is_absolute() { given.to_path_buf() } else { project.root.join(given) };
|
||||
let text = project.text_of(&path)?;
|
||||
@@ -716,7 +707,6 @@ pub async fn maven_goto_declaration(host: &Host, window: &str, pom: String, pos:
|
||||
Ok(ide_build::maven::goto_declaration_with(&text, &path, pos, options, modules))
|
||||
})
|
||||
.await
|
||||
.map_err(join_err)?
|
||||
}
|
||||
|
||||
/// Gutter targets of the unversioned dependencies and plugins in a Maven POM:
|
||||
@@ -731,7 +721,7 @@ pub async fn maven_managed_declarations(
|
||||
) -> IdeResult<Vec<PomManagedDeclaration>> {
|
||||
let project = host.project(window)?;
|
||||
let cancel = host.begin_project_read_request(window, request);
|
||||
let result = tokio::task::spawn_blocking(move || {
|
||||
let result = blocking(move || {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
@@ -753,10 +743,7 @@ pub async fn maven_managed_declarations(
|
||||
})
|
||||
.await;
|
||||
host.end_request(request);
|
||||
match result {
|
||||
Ok(result) => result,
|
||||
Err(error) => Err(join_err(error)),
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// How long completion waits for Maven Central before answering from the local repository.
|
||||
@@ -855,7 +842,7 @@ pub async fn maven_exclude_dependency(
|
||||
) -> IdeResult<Location> {
|
||||
let project = host.project(window)?;
|
||||
let config = host.config_dir.clone();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
blocking(move || {
|
||||
let (path, text, range) = declaring_pom(&project, &config, &pom, &dependency)?;
|
||||
match ide_build::pom_edit::add_exclusion(&text, &dependency, &exclusion) {
|
||||
Some(Exclusion::Edit(edit)) => {
|
||||
@@ -871,7 +858,6 @@ pub async fn maven_exclude_dependency(
|
||||
Ok(Location::file(path, range))
|
||||
})
|
||||
.await
|
||||
.map_err(join_err)?
|
||||
}
|
||||
|
||||
/// Build / Rebuild / Build Artifacts of a Java project without a build tool, from its
|
||||
@@ -989,7 +975,7 @@ pub async fn build_run(
|
||||
let config_dir = host.config_dir.clone();
|
||||
let token = host.begin_project_request(window, request);
|
||||
let launch_project = project.clone();
|
||||
let result = tokio::task::spawn_blocking(move || {
|
||||
let result = blocking(move || {
|
||||
// Fast path (#2476): an unchanged single-project Maven build skips
|
||||
// Maven entirely. Previous diagnostics stay: nothing changed, so they
|
||||
// are still accurate.
|
||||
@@ -1111,10 +1097,9 @@ pub async fn build_run(
|
||||
}
|
||||
Ok::<_, IdeError>(result)
|
||||
})
|
||||
.await
|
||||
.map_err(join_err);
|
||||
.await;
|
||||
host.end_request(request);
|
||||
let outcome = result??;
|
||||
let outcome = result?;
|
||||
// Maven generated sources (protobuf, gRPC) stay invisible to jdtls until the
|
||||
// folders the build wrote are attached. An up-to-date build skips Maven and
|
||||
// still needs this: the classes can already be on disk.
|
||||
@@ -1124,11 +1109,39 @@ pub async fn build_run(
|
||||
Ok(outcome)
|
||||
}
|
||||
|
||||
/// Build › Compile File: compiles one Java source of a linked Maven module with
|
||||
/// `javac`, streaming the console and messages on `on_event`; cancellable with
|
||||
/// `cancel_request(request)`. Diagnostics of `clear` (the files of the previous
|
||||
/// build) are cleared first; the new messages are published as `build`
|
||||
/// diagnostics.
|
||||
fn plan_compile_file(
|
||||
root: &Path,
|
||||
cache: &Path,
|
||||
settings: &Settings,
|
||||
detected: &[ide_workspace::roots::SourceFolder],
|
||||
file: &Path,
|
||||
cancel: &CancellationToken,
|
||||
on_progress: &dyn Fn(String),
|
||||
) -> IdeResult<compile::BuildPlan> {
|
||||
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"));
|
||||
}
|
||||
let name = file.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
let model = with_profiles(load(root, cache, settings), cache);
|
||||
if compile::single_file_target(root, &model, file).is_ok() {
|
||||
on_progress(format!("Resolving classpath for {name}…"));
|
||||
return compile::compile_file_plan_cancellable(root, &model, file, cancel);
|
||||
}
|
||||
if compile::has_gradle_file_target(root, &model, file) {
|
||||
on_progress(format!("Resolving classpath for {name}…"));
|
||||
return compile::gradle_compile_file_plan(root, &model, file, cache, cancel);
|
||||
}
|
||||
let (ps, roots, jdk) = structure_inputs(root, settings, detected);
|
||||
compile::structure_compile_file_plan(root, &ps, &roots, jdk.as_ref(), &settings.languages.java.language_level, file)
|
||||
}
|
||||
|
||||
/// Build › Recompile: compiles one Java source file with `javac`, streaming the
|
||||
/// console and messages on `on_event`; cancellable with `cancel_request(request)`.
|
||||
/// Diagnostics of `clear` (the files of the previous build) are cleared first;
|
||||
/// the new messages are published as `build` diagnostics.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn build_compile_file(
|
||||
host: &Host,
|
||||
@@ -1140,10 +1153,21 @@ pub async fn build_compile_file(
|
||||
) -> IdeResult<BuildResult> {
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
let (root, cache, sink) = (project.root.clone(), project.build_cache_dir(), project.sink.clone());
|
||||
let settings = project.settings.effective();
|
||||
let file = ide_core::project_roots::resolve(&project.root, &file);
|
||||
let scope = {
|
||||
let (project, file) = (project.clone(), file.clone());
|
||||
blocking(move || workspace::scope_for(&project, &file)).await?
|
||||
};
|
||||
let scope_root = scope.root.clone();
|
||||
let detected = if scope.root == project.root {
|
||||
project.detected_roots.read().clone()
|
||||
} else {
|
||||
let root = scope.root.clone();
|
||||
blocking_value(move || ide_workspace::roots::detect(&root)).await?
|
||||
};
|
||||
let sink = project.sink.clone();
|
||||
let token = host.begin_project_request(window, request);
|
||||
let result = tokio::task::spawn_blocking(move || {
|
||||
let result = blocking(move || {
|
||||
for path in clear {
|
||||
sink.emit(IdeEvent::Diagnostics {
|
||||
path: path.into(),
|
||||
@@ -1151,8 +1175,11 @@ pub async fn build_compile_file(
|
||||
items: Vec::new(),
|
||||
});
|
||||
}
|
||||
let plan = compile::compile_file_plan(&root, &with_profiles(load(&root, &cache, &settings), &cache), &file)?;
|
||||
let result = compile::run(&root, &plan, &token, &|e| {
|
||||
let plan =
|
||||
plan_compile_file(&scope.root, &scope.cache, &scope.settings, &detected, &file, &token, &|message| {
|
||||
let _ = on_event.send(BuildEvent::Progress { message, fraction: None });
|
||||
})?;
|
||||
let result = compile::run(&scope.root, &plan, &token, &|e| {
|
||||
let _ = on_event.send(e);
|
||||
})?;
|
||||
for (path, items) in compile::diagnostics(&result.messages) {
|
||||
@@ -1160,12 +1187,11 @@ pub async fn build_compile_file(
|
||||
}
|
||||
Ok::<_, IdeError>(result)
|
||||
})
|
||||
.await
|
||||
.map_err(join_err);
|
||||
.await;
|
||||
host.end_request(request);
|
||||
let outcome = result??;
|
||||
let outcome = result?;
|
||||
if outcome.system == ide_build::compile::BuildSystem::Maven {
|
||||
project.lsp.sync_maven_generated_sources(&project.root).await;
|
||||
project.lsp.sync_maven_generated_sources(&scope_root).await;
|
||||
}
|
||||
Ok(outcome)
|
||||
}
|
||||
@@ -1390,6 +1416,60 @@ mod build_tool_settings_tests {
|
||||
assert_eq!(model.env["JAVA_HOME"], root.join("jdk21").to_string_lossy());
|
||||
assert_eq!(model.env["GRADLE_USER_HOME"], root.join("user-home").to_string_lossy());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn single_file_plan_falls_back_to_project_structure_and_resolves_workspace_scope() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let plain = base.join("plain");
|
||||
let java_file = plain.join("src/Main.java");
|
||||
std::fs::create_dir_all(java_file.parent().unwrap()).unwrap();
|
||||
std::fs::write(&java_file, "class Main {}").unwrap();
|
||||
let detected = ide_workspace::roots::detect(&plain);
|
||||
let plan = plan_compile_file(
|
||||
&plain,
|
||||
&base.join("cache"),
|
||||
&Settings::default(),
|
||||
&detected,
|
||||
&java_file,
|
||||
&ide_core::CancellationToken::new(),
|
||||
&|_| {},
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(plan.system, compile::BuildSystem::Javac);
|
||||
assert_eq!(plan.title, "Compile Main.java");
|
||||
|
||||
let txt = plain.join("notes.txt");
|
||||
std::fs::write(&txt, "hi").unwrap();
|
||||
assert!(
|
||||
plan_compile_file(
|
||||
&plain,
|
||||
&base.join("cache"),
|
||||
&Settings::default(),
|
||||
&detected,
|
||||
&txt,
|
||||
&ide_core::CancellationToken::new(),
|
||||
&|_| {},
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
|
||||
let host =
|
||||
Host::new(crate::HostConfig { local_data_dir: base.join("local"), ..crate::HostConfig::for_test(&base) });
|
||||
let member_a = base.join("member-a");
|
||||
let member_b = base.join("member-b");
|
||||
for m in [&member_a, &member_b] {
|
||||
std::fs::create_dir_all(m.join("src")).unwrap();
|
||||
std::fs::write(m.join("src/App.java"), "class App {}").unwrap();
|
||||
}
|
||||
let ws = base.join("ws");
|
||||
std::fs::create_dir_all(&ws).unwrap();
|
||||
ide_workspace::workspace::Workspace::save(&ws, "WS", vec![member_a.clone(), member_b.clone()], true).unwrap();
|
||||
let project = host.open_project("win", &ws).unwrap();
|
||||
let scope = workspace::scope_for(&project, &member_b.join("src/App.java")).unwrap();
|
||||
assert_eq!(scope.root, member_b);
|
||||
host.close_project("win");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
use crate::Host;
|
||||
use ide_command::command;
|
||||
|
||||
use crate::ops::doc::blocking;
|
||||
use crate::ops::blocking;
|
||||
use ide_core::IdeResult;
|
||||
use ide_vfs::{ByteRange, FileProbe};
|
||||
use std::path::PathBuf;
|
||||
|
||||
@@ -2,17 +2,14 @@
|
||||
use crate::Host;
|
||||
use ide_command::command;
|
||||
|
||||
use ide_core::{IdeError, IdeResult, IpcPath};
|
||||
use super::blocking;
|
||||
use ide_core::{IdeResult, IpcPath};
|
||||
use ide_coverage::{CoveragePrepared, CoverageReportSpec, CoverageSuite};
|
||||
use ide_run::RunConfig;
|
||||
|
||||
/// Output directories kept per kind (older runs' data is deleted).
|
||||
pub const KEEP_RUNS: usize = 10;
|
||||
|
||||
pub async fn blocking<T: Send + 'static>(f: impl FnOnce() -> IdeResult<T> + Send + 'static) -> IdeResult<T> {
|
||||
tokio::task::spawn_blocking(f).await.map_err(|e| IdeError::internal(e.to_string()))?
|
||||
}
|
||||
|
||||
/// How to run `config` with coverage: the command to launch and where its report will be,
|
||||
/// or which tool is missing.
|
||||
#[command(trust = trusted)]
|
||||
|
||||
+135
-19
@@ -384,9 +384,12 @@ pub async fn db_execute(
|
||||
#[default] skip: u32,
|
||||
max_rows: u32,
|
||||
schema: Option<String>,
|
||||
// Cells longer than this many UTF-16 units come back cut (`truncated` lists them); none: whole.
|
||||
#[default] cell_limit: Option<u32>,
|
||||
) -> IdeResult<Vec<StatementOutcome>> {
|
||||
let mut outcomes = Vec::new();
|
||||
execute_statements(host, window, request, &id, statements, skip, max_rows, schema.as_deref(), |event| {
|
||||
let limits = Limits { skip, max_rows, cell_limit };
|
||||
execute_statements(host, window, request, &id, statements, limits, schema.as_deref(), |event| {
|
||||
if let ExecutionEvent::Completed { outcome, .. } = event {
|
||||
outcomes.push(outcome);
|
||||
}
|
||||
@@ -396,6 +399,38 @@ pub async fn db_execute(
|
||||
Ok(outcomes)
|
||||
}
|
||||
|
||||
/// Row `row` (from 0) of the result of `statement`, whole: what a page of a run with a
|
||||
/// `cell_limit` shows cut short.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn db_result_row(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
request: RequestId,
|
||||
id: String,
|
||||
statement: SqlStatement,
|
||||
row: u32,
|
||||
schema: Option<String>,
|
||||
) -> IdeResult<QueryResult> {
|
||||
let db = host.project(window)?.db.clone();
|
||||
let cancel = host.begin_request(request);
|
||||
let result = db.read_row(&id, &statement.text, row as usize, &cancel, schema.as_deref()).await;
|
||||
host.end_request(request);
|
||||
result
|
||||
}
|
||||
|
||||
/// Closes what the pages of a result keep open on the server (its result tab was closed).
|
||||
#[command(trust = trusted)]
|
||||
pub fn db_release_result(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
id: String,
|
||||
statement: String,
|
||||
schema: Option<String>,
|
||||
) -> IdeResult<()> {
|
||||
host.project(window)?.db.release_result(&id, &statement, schema.as_deref());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[command(trust = trusted)]
|
||||
pub async fn db_execute_stream(
|
||||
@@ -406,9 +441,11 @@ pub async fn db_execute_stream(
|
||||
statements: Vec<SqlStatement>,
|
||||
max_rows: u32,
|
||||
schema: Option<String>,
|
||||
#[default] cell_limit: Option<u32>,
|
||||
on_progress: Channel<ExecutionEvent>,
|
||||
) -> IdeResult<()> {
|
||||
let result = execute_statements(host, window, request, &id, statements, 0, max_rows, schema.as_deref(), |event| {
|
||||
let limits = Limits { skip: 0, max_rows, cell_limit };
|
||||
let result = execute_statements(host, window, request, &id, statements, limits, schema.as_deref(), |event| {
|
||||
on_progress.send(event)
|
||||
})
|
||||
.await;
|
||||
@@ -416,6 +453,14 @@ pub async fn db_execute_stream(
|
||||
on_progress.send(ExecutionEvent::Done { error: result.err() })
|
||||
}
|
||||
|
||||
/// What a run of statements returns of each result.
|
||||
#[derive(Clone, Copy)]
|
||||
struct Limits {
|
||||
skip: u32,
|
||||
max_rows: u32,
|
||||
cell_limit: Option<u32>,
|
||||
}
|
||||
|
||||
/// Runs in order on one request and stops on cancellation or the first error.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
async fn execute_statements(
|
||||
@@ -424,8 +469,7 @@ async fn execute_statements(
|
||||
request: RequestId,
|
||||
id: &str,
|
||||
statements: Vec<SqlStatement>,
|
||||
skip: u32,
|
||||
max_rows: u32,
|
||||
Limits { skip, max_rows, cell_limit }: Limits,
|
||||
schema: Option<&str>,
|
||||
mut emit: impl FnMut(ExecutionEvent) -> IdeResult<()>,
|
||||
) -> IdeResult<()> {
|
||||
@@ -441,7 +485,12 @@ async fn execute_statements(
|
||||
.execute_from(id, &statement.text, skip as usize, max_rows.max(1) as usize, &cancel, schema)
|
||||
.await
|
||||
{
|
||||
Ok(result) => StatementOutcome { statement, result: Some(result), error: None },
|
||||
Ok(mut result) => {
|
||||
if let Some(limit) = cell_limit {
|
||||
result.cap_cells(limit as usize);
|
||||
}
|
||||
StatementOutcome { statement, result: Some(result), error: None }
|
||||
}
|
||||
Err(e) if e.kind == ide_core::error::ErrorKind::Cancelled => return Err(e),
|
||||
// The UI may retry a login failure only before any statement has completed.
|
||||
Err(e) if e.kind == ide_core::error::ErrorKind::PermissionDenied && index == 0 => return Err(e),
|
||||
@@ -620,6 +669,8 @@ ide_command::domain!(
|
||||
db_save_jdbc_driver,
|
||||
db_remove_jdbc_driver,
|
||||
db_object_ddl,
|
||||
db_release_result,
|
||||
db_result_row,
|
||||
db_remove_history,
|
||||
db_retain_catalog,
|
||||
db_save_source_visibility,
|
||||
@@ -647,9 +698,8 @@ mod tests {
|
||||
use crate::HostConfig;
|
||||
use ide_db::DbDriver;
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn a_reporting_error_stops_the_batch_and_releases_the_request() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
/// A trusted project with an empty SQLite data source `test`.
|
||||
async fn host_with_sqlite(temp: &tempfile::TempDir) -> Host {
|
||||
let base = dunce::canonicalize(temp.path()).unwrap();
|
||||
let root = base.join("project");
|
||||
std::fs::create_dir(&root).unwrap();
|
||||
@@ -657,28 +707,44 @@ mod tests {
|
||||
let window = "main";
|
||||
host.open_project(window, &root).unwrap();
|
||||
host.set_project_trust(&root, true, false).await.unwrap();
|
||||
let id = "test";
|
||||
let file = root.join("test.sqlite");
|
||||
std::fs::File::create(&file).unwrap();
|
||||
db_save_sources(
|
||||
&host,
|
||||
window,
|
||||
vec![DataSource { id: id.into(), name: id.into(), file: Some(file.into()), ..Default::default() }],
|
||||
vec![DataSource { id: "test".into(), name: "test".into(), file: Some(file.into()), ..Default::default() }],
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
host
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn a_reporting_error_stops_the_batch_and_releases_the_request() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let host = host_with_sqlite(&temp).await;
|
||||
let (window, id) = ("main", "test");
|
||||
let statements =
|
||||
ide_db::split::split("CREATE TABLE items (n INTEGER); INSERT INTO items VALUES (1);", DbDriver::Sqlite);
|
||||
let request = RequestId(1);
|
||||
let error = execute_statements(&host, window, request, id, statements, 0, 10, None, |event| match event {
|
||||
ExecutionEvent::Started { index: 0 } => Ok(()),
|
||||
ExecutionEvent::Completed { index: 0, outcome } => {
|
||||
assert!(outcome.error.is_none(), "{:?}", outcome.error);
|
||||
Err(IdeError::internal("cannot report result"))
|
||||
}
|
||||
_ => panic!("the failed callback must stop execution"),
|
||||
})
|
||||
let error = execute_statements(
|
||||
&host,
|
||||
window,
|
||||
request,
|
||||
id,
|
||||
statements,
|
||||
Limits { skip: 0, max_rows: 10, cell_limit: None },
|
||||
None,
|
||||
|event| match event {
|
||||
ExecutionEvent::Started { index: 0 } => Ok(()),
|
||||
ExecutionEvent::Completed { index: 0, outcome } => {
|
||||
assert!(outcome.error.is_none(), "{:?}", outcome.error);
|
||||
Err(IdeError::internal("cannot report result"))
|
||||
}
|
||||
_ => panic!("the failed callback must stop execution"),
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(error.message, "cannot report result");
|
||||
@@ -691,7 +757,57 @@ mod tests {
|
||||
"SELECT 99 AS n UNION ALL SELECT count(*) FROM items ORDER BY n DESC",
|
||||
DbDriver::Sqlite,
|
||||
);
|
||||
let outcomes = db_execute(&host, window, RequestId(2), id.into(), query, 1, 10, None).await.unwrap();
|
||||
let outcomes = db_execute(&host, window, RequestId(2), id.into(), query, 1, 10, None, None).await.unwrap();
|
||||
assert_eq!(outcomes[0].result.as_ref().unwrap().rows, vec![vec![Some("0".into())]]);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn a_page_with_a_cell_limit_carries_prefixes_and_each_whole_value_is_read_on_demand() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let host = host_with_sqlite(&temp).await;
|
||||
let (window, id) = ("main", "test");
|
||||
let wide = "😀é".repeat(50_000);
|
||||
let setup = ide_db::split::split(
|
||||
&format!(
|
||||
"CREATE TABLE docs (n INTEGER, body TEXT); INSERT INTO docs VALUES (1, 'tiny'), (2, '{wide}'), (3, '{wide}');"
|
||||
),
|
||||
DbDriver::Sqlite,
|
||||
);
|
||||
db_execute(&host, window, RequestId(1), id.into(), setup, 0, 10, None, None).await.unwrap();
|
||||
|
||||
let query = || ide_db::split::split("SELECT n, body FROM docs ORDER BY n", DbDriver::Sqlite);
|
||||
let capped = db_execute(&host, window, RequestId(2), id.into(), query(), 0, 10, None, Some(100)).await.unwrap();
|
||||
let page = capped[0].result.as_ref().unwrap();
|
||||
// The page no longer carries more than the limit of each cell.
|
||||
let size: usize = page.rows.iter().flatten().flatten().map(String::len).sum();
|
||||
assert!(size < 1_000, "{size} bytes");
|
||||
assert_eq!(page.rows[0][1].as_deref(), Some("tiny"));
|
||||
let whole = 150_000;
|
||||
// What the client checks a value it reads again against: FNV-1a over its UTF-16 units.
|
||||
let hash =
|
||||
wide.encode_utf16().fold(0x811c_9dc5_u32, |hash, unit| (hash ^ u32::from(unit)).wrapping_mul(0x0100_0193));
|
||||
assert_eq!(
|
||||
page.truncated,
|
||||
[
|
||||
ide_db::TruncatedCell { row: 1, column: 1, length: whole, hash },
|
||||
ide_db::TruncatedCell { row: 2, column: 1, length: whole, hash }
|
||||
]
|
||||
);
|
||||
|
||||
// The row of a cut cell, read alone and without a limit, is the whole value.
|
||||
for row in [1, 2] {
|
||||
let statement = query().remove(0);
|
||||
let one = db_result_row(&host, window, RequestId(3), id.into(), statement, row, None).await.unwrap();
|
||||
assert!(one.truncated.is_empty());
|
||||
let full = one.rows[0][1].clone().unwrap();
|
||||
assert_eq!(full.encode_utf16().count(), whole as usize);
|
||||
assert!(full.starts_with(page.rows[row as usize][1].as_deref().unwrap()));
|
||||
}
|
||||
|
||||
// Without a limit nothing is cut or listed.
|
||||
let all = db_execute(&host, window, RequestId(4), id.into(), query(), 0, 10, None, None).await.unwrap();
|
||||
let all = all[0].result.as_ref().unwrap();
|
||||
assert!(all.truncated.is_empty());
|
||||
assert_eq!(all.rows[2][1].as_deref(), Some(wide.as_str()));
|
||||
}
|
||||
}
|
||||
@@ -671,6 +671,13 @@ pub async fn debug_jvm_memory_classes(
|
||||
host.debugger.jvm_memory_classes(session).await
|
||||
}
|
||||
|
||||
/// A `Thread.print -l` of the debuggee JVM, or why it cannot be taken.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn debug_jvm_thread_dump(host: &Host, window: &str, session: DebugSessionId) -> IdeResult<JvmThreadsResult> {
|
||||
host.require_trust(window)?;
|
||||
host.debugger.jvm_thread_dump(session).await
|
||||
}
|
||||
|
||||
/// Up to `limit` live instances of the class in the stopped JVM.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn debug_jvm_memory_instances(
|
||||
@@ -867,6 +874,7 @@ ide_command::domain!(
|
||||
debug_jvm_memory_fields,
|
||||
debug_jvm_memory_instances,
|
||||
debug_jvm_memory_referrers,
|
||||
debug_jvm_thread_dump,
|
||||
debug_listen_for_jvm,
|
||||
debug_pause,
|
||||
debug_redefine_classes,
|
||||
|
||||
@@ -330,6 +330,31 @@ pub async fn pypi_package(
|
||||
result
|
||||
}
|
||||
|
||||
/// PyPI project names containing `query`, best match first, 51 at most (50 are shown). Answers from a cached copy of
|
||||
/// PyPI's name list, which the first search downloads and a search a day later refreshes.
|
||||
#[command(trust = outside_restricted)]
|
||||
pub async fn pypi_search(host: &Host, window: &str, query: String, request: RequestId) -> IdeResult<Vec<String>> {
|
||||
let names = host.pypi_names.clone();
|
||||
let cancel = host.begin_project_read_request(window, request);
|
||||
let result = host
|
||||
.blocking(move || {
|
||||
let fetch: pypi::Fetch = std::sync::Arc::new(|cancel: &CancellationToken| {
|
||||
let search_path = std::env::var_os("PATH").unwrap_or_default();
|
||||
ide_tools::Http::new(&search_path)?
|
||||
.https_only()
|
||||
.accept(pypi::SIMPLE_INDEX_ACCEPT)
|
||||
.compressed()
|
||||
.get_text_limited(pypi::SIMPLE_INDEX_URL, Some(256 * 1024 * 1024), cancel)
|
||||
});
|
||||
let index = names.index(&cancel, fetch)?;
|
||||
// One more than shown, so the UI can tell the list was cut.
|
||||
index.search(&query, 51, &cancel)
|
||||
})
|
||||
.await;
|
||||
host.end_request(request);
|
||||
result
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -456,4 +481,4 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
ide_command::domain!(dependencies: dependency_versions, python_requirements, pypi_package);
|
||||
ide_command::domain!(dependencies: dependency_versions, python_requirements, pypi_package, pypi_search);
|
||||
@@ -214,6 +214,25 @@ pub async fn deploy_test_connection(
|
||||
host.remote.test_connection_with(&connection, &path, password).await
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn remote_upload_into(
|
||||
window: &str,
|
||||
host: &Host,
|
||||
connection: FsConnection,
|
||||
paths: Vec<IpcPath>,
|
||||
target: String,
|
||||
replace: bool,
|
||||
request: RequestId,
|
||||
) -> IdeResult<TransferReport> {
|
||||
let project = host.project(window)?;
|
||||
let token = host.begin_request(request);
|
||||
let (mut report, done) = progress(project.sink.clone(), "Uploading", token.clone());
|
||||
let result = host.remote.upload_into(&connection, &local(paths), &target, replace, &token, &mut report).await;
|
||||
done();
|
||||
host.end_request(request);
|
||||
result
|
||||
}
|
||||
|
||||
ide_command::domain!(
|
||||
deploy:
|
||||
deploy_compare,
|
||||
@@ -227,6 +246,7 @@ ide_command::domain!(
|
||||
deploy_upload,
|
||||
remote_delete,
|
||||
remote_download_into,
|
||||
remote_upload_into,
|
||||
remote_list,
|
||||
remote_mkdir,
|
||||
remote_of,
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
use super::blocking;
|
||||
use crate::Host;
|
||||
use ide_command::command;
|
||||
use ide_core::{ChangeSet, DocId, IdeResult};
|
||||
|
||||
@@ -1,17 +1,12 @@
|
||||
use crate::Host;
|
||||
use crate::ops::blocking;
|
||||
use ide_command::command;
|
||||
use ide_core::{DocId, IdeError, IdeResult, OutlineItem, Range, TextEdit};
|
||||
use ide_core::{DocId, IdeResult, OutlineItem, Range, TextEdit};
|
||||
use ide_language::{FoldRange, SyntaxHighlights};
|
||||
use ide_text::LineEnding;
|
||||
use ide_workspace::{DocumentEncoding, DocumentInfo, DocumentLanguage, HistoryEntry};
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// Runs blocking work (disk I/O, parsing, large copies) on the blocking pool,
|
||||
/// keeping it off the main thread and the async runtime's workers.
|
||||
pub async fn blocking<T: Send + 'static>(f: impl FnOnce() -> IdeResult<T> + Send + 'static) -> IdeResult<T> {
|
||||
tokio::task::spawn_blocking(f).await.map_err(|e| IdeError::internal(e.to_string()))?
|
||||
}
|
||||
|
||||
/// Opens a read-only virtual document (see `lsp_virtual_document`) as an
|
||||
/// editor buffer, so syntax features and language-server requests work in it.
|
||||
#[command(trust = always)]
|
||||
|
||||
@@ -6,7 +6,7 @@ use ide_core::IdeResult;
|
||||
use ide_workspace::DirectoryHistory;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use super::doc::blocking;
|
||||
use super::blocking;
|
||||
|
||||
/// Show History on a folder: snapshots of the files under it (deleted ones included) and labels.
|
||||
#[command(trust = always)]
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::doc::blocking;
|
||||
use super::blocking;
|
||||
use crate::Host;
|
||||
use crate::plugins::{ProviderKind, editor_providers_for as editor_providers};
|
||||
use ide_command::command;
|
||||
@@ -70,27 +70,121 @@ pub async fn lsp_completion(
|
||||
pos: Pos,
|
||||
trigger: Option<String>,
|
||||
) -> IdeResult<CompletionList> {
|
||||
let lsp = host.project(window)?.lsp.clone();
|
||||
let project = host.project(window)?;
|
||||
// Typing on in a word whose list only some plugins marked incomplete: ask those plugins
|
||||
// again and keep the rest (the language server's list, the other plugins' items).
|
||||
let word = project.documents.snapshot(doc).ok().and_then(|snap| CompletionWord::at(&snap.text, pos));
|
||||
let resumed = match (&word, trigger.is_none()) {
|
||||
(Some(word), true) => project
|
||||
.completion_session
|
||||
.lock()
|
||||
.as_ref()
|
||||
.filter(|s| s.resumes(doc, word))
|
||||
.map(|s| (s.kept.clone(), s.incomplete.clone())),
|
||||
_ => None,
|
||||
};
|
||||
if let Some((kept, only)) = resumed {
|
||||
let Some((plugins, d)) = plugin_providers(host, window, doc, ProviderKind::Completion) else {
|
||||
*project.completion_session.lock() = None;
|
||||
return Ok(CompletionList { is_incomplete: false, items: kept });
|
||||
};
|
||||
let asked = only.clone();
|
||||
let answer = plugin_call(move || plugins.provide_completion_for_editor(&d, pos, None, Some(&asked)))
|
||||
.await
|
||||
.unwrap_or_default();
|
||||
let mut items = kept;
|
||||
items.extend(answer.items.into_iter().map(|(_, item)| plugin_completion(item)));
|
||||
let mut session = project.completion_session.lock();
|
||||
if let Some(s) = session.as_mut().filter(|s| s.incomplete == only) {
|
||||
s.incomplete = answer.incomplete.clone();
|
||||
}
|
||||
return Ok(CompletionList { is_incomplete: !answer.incomplete.is_empty(), items });
|
||||
}
|
||||
*project.completion_session.lock() = None;
|
||||
|
||||
let lsp = project.lsp.clone();
|
||||
let (target, cancel) = begin_position_request(host, window, request, doc, pos).await?;
|
||||
let result = lsp.completion(target, pos, trigger.clone(), cancel).await;
|
||||
host.end_request(request);
|
||||
// Plugin providers (`[[contributes.providers]]`) add theirs.
|
||||
let Some((plugins, d)) = plugin_providers(host, window, doc, ProviderKind::Completion) else { return result };
|
||||
let (covered, items) = plugin_call(move || plugins.provide_completion_for_editor(&d, pos, trigger.as_deref()))
|
||||
let answer = plugin_call(move || plugins.provide_completion_for_editor(&d, pos, trigger.as_deref(), None))
|
||||
.await
|
||||
.unwrap_or_default();
|
||||
if items.is_empty() {
|
||||
return if covered {
|
||||
if answer.items.is_empty() && answer.incomplete.is_empty() {
|
||||
return if answer.covered {
|
||||
Ok(result.unwrap_or(CompletionList { is_incomplete: true, items: Vec::new() }))
|
||||
} else {
|
||||
result
|
||||
};
|
||||
}
|
||||
let mut list = result.unwrap_or(CompletionList { is_incomplete: false, items: Vec::new() });
|
||||
list.items.extend(items.into_iter().map(|(_, item)| plugin_completion(item)));
|
||||
let server_complete = !list.is_incomplete;
|
||||
let mut fresh = Vec::new();
|
||||
for (id, item) in answer.items {
|
||||
let item = plugin_completion(item);
|
||||
if answer.incomplete.contains(&id) { fresh.push(item) } else { list.items.push(item) }
|
||||
}
|
||||
if !answer.incomplete.is_empty() {
|
||||
// Only a complete server list can be kept; else typing on asks everyone, as before.
|
||||
if let (true, Some(word)) = (server_complete, word) {
|
||||
*project.completion_session.lock() =
|
||||
Some(CompletionSession { doc, word, kept: list.items.clone(), incomplete: answer.incomplete });
|
||||
}
|
||||
list.is_incomplete = true;
|
||||
}
|
||||
list.items.extend(fresh);
|
||||
Ok(list)
|
||||
}
|
||||
|
||||
/// The word completion is asked in: its line and the line's text before the word.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct CompletionWord {
|
||||
line: u32,
|
||||
before: String,
|
||||
}
|
||||
|
||||
impl CompletionWord {
|
||||
/// The identifier ending at `pos` in `text` (possibly empty, right after a `.`).
|
||||
fn at(text: &str, pos: Pos) -> Option<Self> {
|
||||
let line = text.split('\n').nth(pos.line as usize)?.trim_end_matches('\r');
|
||||
let mut col = 0u32;
|
||||
let mut end = line.len();
|
||||
for (i, c) in line.char_indices() {
|
||||
if col >= pos.col {
|
||||
end = i;
|
||||
break;
|
||||
}
|
||||
col += c.len_utf16() as u32;
|
||||
}
|
||||
if col < pos.col {
|
||||
return None;
|
||||
}
|
||||
let head = &line[..end];
|
||||
let word_len: usize =
|
||||
head.chars().rev().take_while(|c| c.is_alphanumeric() || *c == '_' || *c == '$').map(char::len_utf8).sum();
|
||||
let before = &head[..head.len() - word_len];
|
||||
Some(Self { line: pos.line, before: before.to_owned() })
|
||||
}
|
||||
}
|
||||
|
||||
/// A completion whose list some plugins marked incomplete (API 1.16): while the user types on in
|
||||
/// the same word, only those plugins are asked again.
|
||||
pub(crate) struct CompletionSession {
|
||||
doc: DocId,
|
||||
word: CompletionWord,
|
||||
/// The language server's list (complete) and the other plugins' items.
|
||||
kept: Vec<CompletionItem>,
|
||||
/// The plugins asked again.
|
||||
incomplete: std::collections::BTreeSet<String>,
|
||||
}
|
||||
|
||||
impl CompletionSession {
|
||||
fn resumes(&self, doc: DocId, word: &CompletionWord) -> bool {
|
||||
self.doc == doc && &self.word == word && !self.incomplete.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
/// The plugin host and the document, when some plugin provides `kind`.
|
||||
pub(crate) fn plugin_providers(
|
||||
host: &Host,
|
||||
@@ -2224,6 +2318,25 @@ pub fn plugin_formatters() -> IdeResult<Vec<crate::plugins::language_features::F
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn a_completion_word_is_its_line_and_what_precedes_it() {
|
||||
use super::*;
|
||||
let word = |text: &str, line: u32, col: u32| CompletionWord::at(text, Pos::new(line, col));
|
||||
let before = |text: &str, line: u32, col: u32| word(text, line, col).map(|w| w.before);
|
||||
assert_eq!(before("Book.findByTitle", 0, 16).as_deref(), Some("Book."));
|
||||
// Typing on in the word, or deleting back into it, is the same word.
|
||||
assert_eq!(word("Book.findByTitleA", 0, 17), word("Book.findBy", 0, 11));
|
||||
assert_eq!(word("Book.findBy", 0, 5), word("Book.findBy", 0, 11));
|
||||
// Another line, or a change before the word, is another one.
|
||||
assert_ne!(word("a\nBook.find", 1, 9), word("Book.find\na", 0, 9));
|
||||
assert_ne!(word("Book.find", 0, 9), word("Look.find", 0, 9));
|
||||
// Columns count UTF-16 units; CRLF line ends don't count.
|
||||
assert_eq!(before("😀 x.ab", 0, 7).as_deref(), Some("😀 x."));
|
||||
assert_eq!(before("x.ab\r\nnext", 0, 4).as_deref(), Some("x."));
|
||||
assert_eq!(word("short", 0, 9), None);
|
||||
assert_eq!(word("short", 3, 0), None);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn python_optimize_imports_without_a_server_runs_ruff_on_the_unsaved_text() {
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
//! poms the nearest pom declares itself are followed from there; a parent outside
|
||||
//! that walk that no pom declares is not.
|
||||
|
||||
use super::doc::blocking;
|
||||
use super::blocking;
|
||||
use crate::Host;
|
||||
use ide_build::maven;
|
||||
use ide_core::{DocId, Location, Pos};
|
||||
|
||||
@@ -39,6 +39,7 @@ pub mod ssh;
|
||||
pub mod stream_trace;
|
||||
pub mod syntax;
|
||||
pub mod term;
|
||||
pub mod thread_dump;
|
||||
pub mod tools;
|
||||
pub mod vcs;
|
||||
pub mod web;
|
||||
@@ -118,15 +119,115 @@ ide_command::domains!(
|
||||
stream_trace: crate::ops::stream_trace,
|
||||
syntax: crate::ops::syntax,
|
||||
term: crate::ops::term,
|
||||
thread_dump: crate::ops::thread_dump,
|
||||
tools: crate::ops::tools,
|
||||
vcs: crate::ops::vcs,
|
||||
vcs_commands: crate::ops::vcs::commands,
|
||||
web: crate::ops::web,
|
||||
);
|
||||
|
||||
/// A blocking task that panicked or was cancelled, as the error a command returns.
|
||||
pub(crate) fn join_error(e: tokio::task::JoinError) -> IdeError {
|
||||
IdeError::internal(e.to_string())
|
||||
}
|
||||
|
||||
/// Runs blocking work (disk I/O, parsing, large copies) on the ambient runtime's blocking
|
||||
/// pool, keeping it off the main thread and the async runtime's workers.
|
||||
pub async fn blocking<T: Send + 'static>(f: impl FnOnce() -> IdeResult<T> + Send + 'static) -> IdeResult<T> {
|
||||
tokio::task::spawn_blocking(f).await.map_err(join_error)?
|
||||
}
|
||||
|
||||
/// [`blocking`] for work that cannot fail: only a panic or cancellation is an error.
|
||||
pub(crate) async fn blocking_value<T: Send + 'static>(f: impl FnOnce() -> T + Send + 'static) -> IdeResult<T> {
|
||||
tokio::task::spawn_blocking(f).await.map_err(join_error)
|
||||
}
|
||||
|
||||
impl Host {
|
||||
/// Runs blocking work (disk I/O, parsing, large copies) on the blocking pool.
|
||||
/// [`blocking`] on this host's runtime instead of the ambient one.
|
||||
pub async fn blocking<T: Send + 'static>(&self, f: impl FnOnce() -> IdeResult<T> + Send + 'static) -> IdeResult<T> {
|
||||
self.runtime.spawn_blocking(f).await.map_err(|e| IdeError::internal(e.to_string()))?
|
||||
self.runtime.spawn_blocking(f).await.map_err(join_error)?
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod blocking_tests {
|
||||
use super::{blocking, blocking_value};
|
||||
use crate::{Host, HostConfig};
|
||||
use ide_core::error::ErrorKind;
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use std::sync::Arc;
|
||||
|
||||
fn runtime(name: &str) -> tokio::runtime::Runtime {
|
||||
tokio::runtime::Builder::new_multi_thread().worker_threads(1).thread_name(name).enable_all().build().unwrap()
|
||||
}
|
||||
|
||||
fn thread_name() -> String {
|
||||
std::thread::current().name().unwrap_or_default().to_owned()
|
||||
}
|
||||
|
||||
fn assert_panic(error: &IdeError) {
|
||||
assert_eq!(error.kind, ErrorKind::Internal);
|
||||
assert!(error.data.is_none());
|
||||
// tokio's JoinError text: `task <id> panicked with message "boom"` (the id varies).
|
||||
assert!(error.message.starts_with("task "), "{}", error.message);
|
||||
assert!(error.message.ends_with(" panicked with message \"boom\""), "{}", error.message);
|
||||
}
|
||||
|
||||
fn host_on(handle: tokio::runtime::Handle, base: &std::path::Path) -> Host {
|
||||
Host::new(HostConfig {
|
||||
config_dir: base.join("config"),
|
||||
data_dir: base.join("data"),
|
||||
local_data_dir: base.join("local"),
|
||||
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
|
||||
syntax: Arc::default(),
|
||||
sink_for: Box::new(|_| Arc::new(|_| {})),
|
||||
owner: |w| w,
|
||||
runtime: handle,
|
||||
project_environment: false,
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blocking_returns_the_value_and_passes_the_closure_error_through() {
|
||||
runtime("ambient").block_on(async {
|
||||
assert_eq!(blocking(|| Ok(7)).await.unwrap(), 7);
|
||||
let error = blocking::<()>(|| Err(IdeError::invalid("nope"))).await.unwrap_err();
|
||||
assert_eq!((error.kind, error.message.as_str()), (ErrorKind::InvalidInput, "nope"));
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blocking_maps_a_panic_to_an_internal_error() {
|
||||
runtime("ambient").block_on(async {
|
||||
assert_panic(&blocking::<()>(|| panic!("boom")).await.unwrap_err());
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blocking_runs_on_the_ambient_runtime() {
|
||||
let name = runtime("ambient").block_on(async { blocking(|| Ok(thread_name())).await.unwrap() });
|
||||
assert_eq!(name, "ambient");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blocking_value_returns_the_value_and_maps_a_panic() {
|
||||
runtime("ambient").block_on(async {
|
||||
assert_eq!(blocking_value(thread_name).await.unwrap(), "ambient");
|
||||
assert_panic(&blocking_value::<()>(|| panic!("boom")).await.unwrap_err());
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn host_blocking_runs_on_the_hosts_runtime_not_the_ambient_one() {
|
||||
let (ambient, hosts) = (runtime("ambient"), runtime("hosts"));
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let host = host_on(hosts.handle().clone(), temp.path());
|
||||
ambient.block_on(async {
|
||||
assert_eq!(host.blocking(|| Ok(thread_name())).await.unwrap(), "hosts");
|
||||
assert_eq!(host.blocking(|| IdeResult::Ok(7)).await.unwrap(), 7);
|
||||
let error = host.blocking::<()>(|| Err(IdeError::invalid("nope"))).await.unwrap_err();
|
||||
assert_eq!((error.kind, error.message.as_str()), (ErrorKind::InvalidInput, "nope"));
|
||||
assert_panic(&host.blocking::<()>(|| panic!("boom")).await.unwrap_err());
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::doc::blocking;
|
||||
use super::blocking;
|
||||
use super::python_stubs::{
|
||||
PythonStubLinks, counterpart_candidates, match_declarations, module_name, site_packages, stub_path,
|
||||
};
|
||||
|
||||
@@ -12,7 +12,7 @@ use ide_workspace::{FileMove, UndoOutcome};
|
||||
use parking_lot::Mutex;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use super::doc::blocking;
|
||||
use super::blocking;
|
||||
|
||||
fn pairs(moves: &[FileMove]) -> Vec<(PathBuf, PathBuf)> {
|
||||
moves.iter().map(|m| (m.from.to_path_buf(), m.to.to_path_buf())).collect()
|
||||
|
||||
@@ -13,7 +13,7 @@ use std::time::Duration;
|
||||
pub async fn run_configs(host: &Arc<Host>, window: &str) -> IdeResult<Vec<RunConfig>> {
|
||||
// Detection reads build files (and Spring Boot sources): off the command thread.
|
||||
let (host, window) = (host.clone(), window.to_owned());
|
||||
super::doc::blocking(move || configs(&host, &window)).await
|
||||
super::blocking(move || configs(&host, &window)).await
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
@@ -25,7 +25,7 @@ pub async fn run_save_configs(
|
||||
) -> IdeResult<()> {
|
||||
let (host, window) = (host.clone(), window.to_owned());
|
||||
let removed = removed_detected_ids.unwrap_or_default();
|
||||
super::doc::blocking(move || save_configs(&host, &window, &configs, &removed)).await
|
||||
super::blocking(move || save_configs(&host, &window, &configs, &removed)).await
|
||||
}
|
||||
|
||||
/// Detected configs followed by user-defined ones (user ids win on conflict).
|
||||
@@ -263,7 +263,7 @@ fn settings_only(
|
||||
#[command(trust = trusted)]
|
||||
pub async fn run_without_derived(host: &Arc<Host>, window: &str, configs: Vec<RunConfig>) -> IdeResult<Vec<RunConfig>> {
|
||||
let (host, window) = (host.clone(), window.to_owned());
|
||||
super::doc::blocking(move || without_derived(&host, &window, configs)).await
|
||||
super::blocking(move || without_derived(&host, &window, configs)).await
|
||||
}
|
||||
|
||||
/// Without what settings derived (toolchain commands, Maven options, `JAVA_HOME`…), so they
|
||||
@@ -287,7 +287,7 @@ fn without_derived(host: &Host, window: &str, configs: Vec<RunConfig>) -> IdeRes
|
||||
#[command(trust = trusted)]
|
||||
pub async fn run_apply_settings(host: &Arc<Host>, window: &str, configs: Vec<RunConfig>) -> IdeResult<Vec<RunConfig>> {
|
||||
let (host, window) = (host.clone(), window.to_owned());
|
||||
super::doc::blocking(move || apply_settings(&host, &window, configs)).await
|
||||
super::blocking(move || apply_settings(&host, &window, configs)).await
|
||||
}
|
||||
|
||||
/// Today's settings applied, as [`configs`] lists the others.
|
||||
|
||||
@@ -100,20 +100,20 @@ pub async fn run_application_publish(
|
||||
#[command(trust = trusted)]
|
||||
pub async fn run_templates(host: &Host, window: &str) -> IdeResult<Vec<RunConfig>> {
|
||||
let root = host.project(window)?.root.clone();
|
||||
crate::ops::doc::blocking(move || ide_run::load_templates(&root)).await
|
||||
crate::ops::blocking(move || ide_run::load_templates(&root)).await
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn run_save_templates(host: &Host, window: &str, templates: Vec<RunConfig>) -> IdeResult<()> {
|
||||
let root = host.project(window)?.root.clone();
|
||||
crate::ops::doc::blocking(move || ide_run::save_templates(&root, &templates)).await
|
||||
crate::ops::blocking(move || ide_run::save_templates(&root, &templates)).await
|
||||
}
|
||||
|
||||
/// Project files run configurations can be imported from (`.vscode/launch.json`).
|
||||
#[command(trust = trusted)]
|
||||
pub async fn run_import_sources(host: &Host, window: &str) -> IdeResult<Vec<RunImportSource>> {
|
||||
let root = host.project(window)?.root.clone();
|
||||
crate::ops::doc::blocking(move || Ok(ide_run::import::available(&root))).await
|
||||
crate::ops::blocking(move || Ok(ide_run::import::available(&root))).await
|
||||
}
|
||||
|
||||
/// Configurations read from `source`, not saved; names already in `existing` are skipped.
|
||||
@@ -127,7 +127,7 @@ pub async fn run_import_configs(
|
||||
// `existing`: the configurations being edited.
|
||||
host.require_trust(window)?;
|
||||
let root = host.project(window)?.root.clone();
|
||||
crate::ops::doc::blocking(move || ide_run::import_configs(&root, source, &existing)).await
|
||||
crate::ops::blocking(move || ide_run::import_configs(&root, source, &existing)).await
|
||||
}
|
||||
|
||||
/// The environment runs inherit when "Include system environment variables" is on.
|
||||
@@ -141,7 +141,7 @@ pub fn run_system_env() -> std::collections::BTreeMap<String, String> {
|
||||
pub async fn run_env_files(files: Vec<std::path::PathBuf>) -> IdeResult<std::collections::BTreeMap<String, String>> {
|
||||
// In order (later files win): the same files a run loads, over the system environment
|
||||
// debug adapters inherit.
|
||||
crate::ops::doc::blocking(move || {
|
||||
crate::ops::blocking(move || {
|
||||
ide_run::envfile::load(&files, &ide_run::system_env())
|
||||
.map_err(|e| IdeError::not_found(format!("cannot read .env file: {e}")))
|
||||
})
|
||||
|
||||
@@ -1,17 +1,14 @@
|
||||
//! File › New Project (`ide-scaffold`). Its commands run in Restricted Mode: New Project writes
|
||||
//! only where the user chose and runs no code of an open project.
|
||||
use super::{blocking, blocking_value};
|
||||
use crate::Host;
|
||||
use crate::ops::Channel;
|
||||
use ide_command::command;
|
||||
|
||||
use ide_core::{IdeError, IdeResult, IpcPath, RequestId};
|
||||
use ide_core::{IdeResult, IpcPath, RequestId};
|
||||
use ide_scaffold::{CreateRequest, Field, GeneratorInfo, Requirement, ScaffoldEvent, Values};
|
||||
use std::path::PathBuf;
|
||||
|
||||
fn join_err(e: impl std::fmt::Display) -> IdeError {
|
||||
IdeError::internal(e.to_string())
|
||||
}
|
||||
|
||||
/// The project generators File › New Project offers, in list order.
|
||||
#[command(trust = always)]
|
||||
pub fn scaffold_catalog() -> Vec<GeneratorInfo> {
|
||||
@@ -29,30 +26,28 @@ pub async fn scaffold_options(
|
||||
) -> IdeResult<Vec<Field>> {
|
||||
// Spring Initializr's Boot versions and dependencies…; empty for other generators.
|
||||
let cancel = host.begin_request(request);
|
||||
let result = tokio::task::spawn_blocking(move || ide_scaffold::options(&generator, &values, &cancel))
|
||||
.await
|
||||
.map_err(join_err);
|
||||
let result = blocking(move || ide_scaffold::options(&generator, &values, &cancel)).await;
|
||||
host.end_request(request);
|
||||
result?
|
||||
result
|
||||
}
|
||||
|
||||
/// The programs a generator needs for `values`, and whether they are installed.
|
||||
#[command(trust = always)]
|
||||
pub async fn scaffold_requirements(generator: String, values: Values) -> IdeResult<Vec<Requirement>> {
|
||||
tokio::task::spawn_blocking(move || ide_scaffold::requirements(&generator, &values)).await.map_err(join_err)?
|
||||
blocking(move || ide_scaffold::requirements(&generator, &values)).await
|
||||
}
|
||||
|
||||
/// Whether a project named `name` cannot be created in `location`: something other than an
|
||||
/// empty folder is already there.
|
||||
#[command(trust = always)]
|
||||
pub async fn scaffold_target_taken(location: PathBuf, name: String) -> IdeResult<bool> {
|
||||
tokio::task::spawn_blocking(move || ide_scaffold::target_taken(&location.join(name.trim()))).await.map_err(join_err)
|
||||
blocking_value(move || ide_scaffold::target_taken(&location.join(name.trim()))).await
|
||||
}
|
||||
|
||||
/// The first of `base`, `base1`, `base2`, … that names nothing in `location` yet.
|
||||
#[command(trust = always)]
|
||||
pub async fn scaffold_free_name(location: PathBuf, base: String) -> IdeResult<String> {
|
||||
tokio::task::spawn_blocking(move || ide_scaffold::free_name(&location, &base)).await.map_err(join_err)
|
||||
blocking_value(move || ide_scaffold::free_name(&location, &base)).await
|
||||
}
|
||||
|
||||
/// Creates a project, streaming progress through `on_event`, and returns its directory,
|
||||
@@ -66,15 +61,14 @@ pub async fn scaffold_create(
|
||||
) -> IdeResult<IpcPath> {
|
||||
// Trusted because the user just created it; a failed or cancelled run leaves no files behind.
|
||||
let cancel = host.begin_request(request);
|
||||
let result = tokio::task::spawn_blocking(move || {
|
||||
let result = blocking(move || {
|
||||
ide_scaffold::create(&req, &cancel, &|e| {
|
||||
let _ = on_event.send(e);
|
||||
})
|
||||
})
|
||||
.await
|
||||
.map_err(join_err);
|
||||
.await;
|
||||
host.end_request(request);
|
||||
let dir = result??;
|
||||
let dir = result?;
|
||||
host.set_project_trust(&dir, true, false).await?;
|
||||
Ok(dir.into())
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
//! Interpreters / toolchains (`ide-sdk`): discovery, Python virtualenvs and packages.
|
||||
use super::{blocking, blocking_value, join_error};
|
||||
use crate::Host;
|
||||
use crate::ops::Channel;
|
||||
use ide_command::command;
|
||||
@@ -13,10 +14,6 @@ use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
pub mod container_python;
|
||||
pub use container_python::{ContainerPython, sdk_container_python, sdk_container_python_refresh};
|
||||
|
||||
fn join_err(e: impl std::fmt::Display) -> IdeError {
|
||||
IdeError::internal(e.to_string())
|
||||
}
|
||||
|
||||
/// Executables found for "run this file", and where single files are compiled to.
|
||||
#[derive(Clone, Debug, serde::Serialize, specta::Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
@@ -48,7 +45,7 @@ pub async fn sdk_detect(host: &Host, window: &str, kind: SdkKind) -> IdeResult<V
|
||||
(Some(p), SdkKind::Python) => ide_sdk::apply::python_interpreter(&p.root, &p.settings.effective()),
|
||||
_ => None,
|
||||
};
|
||||
tokio::task::spawn_blocking(move || {
|
||||
blocking_value(move || {
|
||||
let mut sdks = ide_sdk::detect(kind, root.as_deref());
|
||||
if let Some(path) = current
|
||||
&& !sdks.iter().any(|s| *s.path == *path)
|
||||
@@ -59,7 +56,6 @@ pub async fn sdk_detect(host: &Host, window: &str, kind: SdkKind) -> IdeResult<V
|
||||
sdks
|
||||
})
|
||||
.await
|
||||
.map_err(join_err)
|
||||
}
|
||||
|
||||
/// The Python interpreters of the recently opened projects, each with its project.
|
||||
@@ -78,7 +74,7 @@ pub async fn sdk_python_project_interpreters(host: &Host, window: &str) -> IdeRe
|
||||
.filter(|root| current.as_deref() != Some(root.as_path()))
|
||||
.filter(|root| host.trust.window_trusted(root).unwrap_or(false))
|
||||
.collect();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
blocking_value(move || {
|
||||
// Each project resolves its configured interpreter, else its own virtualenv. The
|
||||
// probes run `python`, so keep them off the async runtime and bound how many run at
|
||||
// once: the recent list can hold ~30 projects, and each probe starts a process.
|
||||
@@ -107,7 +103,6 @@ pub async fn sdk_python_project_interpreters(host: &Host, window: &str) -> IdeRe
|
||||
found.into_iter().map(|(_, interpreter)| interpreter).collect()
|
||||
})
|
||||
.await
|
||||
.map_err(join_err)
|
||||
}
|
||||
|
||||
/// An existing Python executable or virtualenv folder as an SDK; `None` if Python cannot run.
|
||||
@@ -115,9 +110,7 @@ pub async fn sdk_python_project_interpreters(host: &Host, window: &str) -> IdeRe
|
||||
pub async fn sdk_python_interpreter(host: &Host, window: &str, path: PathBuf) -> IdeResult<Option<Sdk>> {
|
||||
host.require_trust_if_project(window)?;
|
||||
let root = host.project(window).ok().map(|p| p.root.clone());
|
||||
tokio::task::spawn_blocking(move || Ok(ide_sdk::python_interpreter_sdk(&path, root.as_deref())))
|
||||
.await
|
||||
.map_err(join_err)?
|
||||
blocking(move || Ok(ide_sdk::python_interpreter_sdk(&path, root.as_deref()))).await
|
||||
}
|
||||
|
||||
/// `sys.path` of the interpreter `python`, for All Interpreters › Show Paths.
|
||||
@@ -130,7 +123,7 @@ pub async fn sdk_python_sys_path(
|
||||
) -> IdeResult<Vec<ide_core::IpcPath>> {
|
||||
host.require_trust_if_project(window)?;
|
||||
let cancel = host.begin_project_request(window, request);
|
||||
let result = tokio::task::spawn_blocking(move || {
|
||||
let result = blocking(move || {
|
||||
let paths = ide_sdk::libraries::python_sys_path(&python, &cancel);
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
@@ -143,10 +136,9 @@ pub async fn sdk_python_sys_path(
|
||||
})?;
|
||||
Ok(paths.iter().map(|p| p.as_path().into()).collect())
|
||||
})
|
||||
.await
|
||||
.map_err(join_err);
|
||||
.await;
|
||||
host.end_request(request);
|
||||
result?
|
||||
result
|
||||
}
|
||||
|
||||
/// For each folder added to an interpreter's paths, why it stays off the import path
|
||||
@@ -158,9 +150,7 @@ pub async fn sdk_python_user_path_problems(
|
||||
paths: Vec<String>,
|
||||
) -> IdeResult<Vec<Option<ide_sdk::apply::UserPathProblem>>> {
|
||||
host.require_trust_if_project(window)?;
|
||||
tokio::task::spawn_blocking(move || paths.iter().map(|p| ide_sdk::apply::user_path(p).err()).collect())
|
||||
.await
|
||||
.map_err(join_err)
|
||||
blocking_value(move || paths.iter().map(|p| ide_sdk::apply::user_path(p).err()).collect()).await
|
||||
}
|
||||
|
||||
/// The interpreter of the workspace member `near` belongs to, else the project's.
|
||||
@@ -201,9 +191,7 @@ pub async fn sdk_python_effective(
|
||||
let project = host.project(window)?;
|
||||
let config_dir = host.config_dir.clone();
|
||||
// Loading a member's settings needs more stack than a sync command's main thread has left.
|
||||
tokio::task::spawn_blocking(move || Ok(effective_python(&config_dir, &project, near.as_deref()).map(Into::into)))
|
||||
.await
|
||||
.map_err(join_err)?
|
||||
blocking(move || Ok(effective_python(&config_dir, &project, near.as_deref()).map(Into::into))).await
|
||||
}
|
||||
|
||||
/// The PHP interpreter chosen in Settings › Languages & Frameworks › PHP; `None`: the `php` on `PATH`.
|
||||
@@ -226,7 +214,7 @@ pub async fn sdk_php_xdebug(
|
||||
) -> IdeResult<ide_sdk::php::PhpXdebug> {
|
||||
host.require_trust(window)?;
|
||||
let cwd = cwd.or_else(|| host.project(window).ok().map(|p| p.root.clone()));
|
||||
tokio::task::spawn_blocking(move || ide_sdk::php::xdebug(&php, cwd.as_deref())).await.map_err(join_err)?
|
||||
blocking(move || ide_sdk::php::xdebug(&php, cwd.as_deref())).await
|
||||
}
|
||||
|
||||
/// The PHP language level of the project `path` belongs to (a workspace member, by path, as
|
||||
@@ -249,7 +237,7 @@ pub async fn sdk_php_language_level(host: &Host, window: &str, path: PathBuf) ->
|
||||
let project = host.project(window)?;
|
||||
let (project_root, project_settings) = (project.root.clone(), project.settings.effective());
|
||||
let config_dir = host.config_dir.clone();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
blocking_value(move || {
|
||||
let member = ide_workspace::workspace::Workspace::load(&project_root).ok().flatten().and_then(|w| {
|
||||
w.projects.into_iter().filter(|p| path.starts_with(p)).max_by_key(|p| p.components().count())
|
||||
});
|
||||
@@ -264,7 +252,6 @@ pub async fn sdk_php_language_level(host: &Host, window: &str, path: PathBuf) ->
|
||||
}
|
||||
})
|
||||
.await
|
||||
.map_err(join_err)
|
||||
}
|
||||
|
||||
/// The Composer project `path` belongs to, when its dependencies need `composer install`.
|
||||
@@ -288,12 +275,11 @@ pub async fn sdk_php_composer_install(
|
||||
return Ok(None);
|
||||
}
|
||||
let root = project.root.clone();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
blocking_value(move || {
|
||||
ide_sdk::php::composer_install(&path, &root)
|
||||
.map(|(root, reason)| ComposerInstallState { root: ide_core::IpcPath::from(root), reason })
|
||||
})
|
||||
.await
|
||||
.map_err(join_err)
|
||||
}
|
||||
|
||||
/// SDK / library source folders shown under "External Libraries" in the Project view,
|
||||
@@ -354,7 +340,7 @@ pub async fn sdk_project_libraries(
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
let groups =
|
||||
ide_sdk::libraries::merge_groups([libraries.map_err(join_err)?, dependencies.map_err(join_err)?].concat());
|
||||
ide_sdk::libraries::merge_groups([libraries.map_err(join_error)?, dependencies.map_err(join_error)?].concat());
|
||||
if host.project(window).is_ok_and(|current| std::sync::Arc::ptr_eq(¤t, &project)) {
|
||||
host.mcp_reports
|
||||
.set_libraries(window, groups.iter().flat_map(|g| g.roots.iter().map(|r| r.path.0.clone())).collect());
|
||||
@@ -371,12 +357,11 @@ pub async fn sdk_locate_tools(
|
||||
near: Option<PathBuf>,
|
||||
) -> IdeResult<LocatedTools> {
|
||||
host.require_trust(window)?;
|
||||
tokio::task::spawn_blocking(move || LocatedTools {
|
||||
blocking_value(move || LocatedTools {
|
||||
tools: ide_sdk::locate::locate_tools(&names, near.as_deref()),
|
||||
compile_dir: ide_sdk::locate::compile_dir().into(),
|
||||
})
|
||||
.await
|
||||
.map_err(join_err)
|
||||
}
|
||||
|
||||
/// The environments the window's project defines for Hatch, `default` first (hatch must be on PATH).
|
||||
@@ -385,10 +370,9 @@ pub async fn sdk_python_hatch_envs(host: &Host, window: &str, request: RequestId
|
||||
host.require_trust_if_project(window)?;
|
||||
let root = host.project(window)?.root.clone();
|
||||
let cancel = host.begin_project_request(window, request);
|
||||
let result =
|
||||
tokio::task::spawn_blocking(move || ide_sdk::python::hatch_envs(&root, &cancel)).await.map_err(join_err);
|
||||
let result = blocking(move || ide_sdk::python::hatch_envs(&root, &cancel)).await;
|
||||
host.end_request(request);
|
||||
result?
|
||||
result
|
||||
}
|
||||
|
||||
/// Creates a Python environment and streams its output through `on_output`.
|
||||
@@ -407,15 +391,14 @@ pub async fn sdk_python_create_venv(
|
||||
) -> IdeResult<Sdk> {
|
||||
host.require_trust_if_project(window)?;
|
||||
let cancel = host.begin_project_request(window, request);
|
||||
let result = tokio::task::spawn_blocking(move || {
|
||||
let result = blocking(move || {
|
||||
ide_sdk::python::create_venv(tool, &base, &location, install_packages, &cancel, &|line| {
|
||||
let _ = on_output.send(line);
|
||||
})
|
||||
})
|
||||
.await
|
||||
.map_err(join_err);
|
||||
.await;
|
||||
host.end_request(request);
|
||||
result?
|
||||
result
|
||||
}
|
||||
|
||||
#[command(trust = outside_restricted)]
|
||||
@@ -428,11 +411,9 @@ pub async fn sdk_python_packages(
|
||||
) -> IdeResult<Vec<PythonPackage>> {
|
||||
host.require_trust_if_project(window)?;
|
||||
let cancel = host.begin_project_request(window, request);
|
||||
let result = tokio::task::spawn_blocking(move || ide_sdk::python::list_packages(&python, outdated, &cancel))
|
||||
.await
|
||||
.map_err(join_err);
|
||||
let result = blocking(move || ide_sdk::python::list_packages(&python, outdated, &cancel)).await;
|
||||
host.end_request(request);
|
||||
result?
|
||||
result
|
||||
}
|
||||
|
||||
/// A package index other than PyPI that installing from `python` uses; `None` for PyPI.
|
||||
@@ -446,13 +427,9 @@ pub async fn sdk_python_package_index(
|
||||
host.require_trust_if_project(window)?;
|
||||
let project_root = host.project(window).ok().map(|p| p.root.clone());
|
||||
let cancel = host.begin_project_request(window, request);
|
||||
let result = tokio::task::spawn_blocking(move || {
|
||||
ide_sdk::python::configured_index(&python, project_root.as_deref(), &cancel)
|
||||
})
|
||||
.await
|
||||
.map_err(join_err);
|
||||
let result = blocking(move || ide_sdk::python::configured_index(&python, project_root.as_deref(), &cancel)).await;
|
||||
host.end_request(request);
|
||||
result?
|
||||
result
|
||||
}
|
||||
|
||||
/// Installs (`uninstall = false`) or removes a package; output streams through `on_output`.
|
||||
@@ -471,7 +448,7 @@ pub async fn sdk_python_pip(
|
||||
host.require_trust_if_project(window)?;
|
||||
let project_root = host.project(window).ok().map(|p| p.root.clone());
|
||||
let cancel = host.begin_project_request(window, request);
|
||||
let result = tokio::task::spawn_blocking(move || {
|
||||
let result = blocking(move || {
|
||||
let send = |line: String| {
|
||||
let _ = on_output.send(line);
|
||||
};
|
||||
@@ -481,21 +458,16 @@ pub async fn sdk_python_pip(
|
||||
ide_sdk::python::install_package(&python, &requirement, upgrade, project_root.as_deref(), &cancel, &send)
|
||||
}
|
||||
})
|
||||
.await
|
||||
.map_err(join_err);
|
||||
.await;
|
||||
host.end_request(request);
|
||||
result?
|
||||
result
|
||||
}
|
||||
|
||||
/// The JDK whose home is `path`, as the SDK list shows it; `None` when it is no JDK home.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn sdk_jdk_at(path: String) -> IdeResult<Option<Sdk>> {
|
||||
// A macOS bundle too (Add JDK from Disk…).
|
||||
tokio::task::spawn_blocking(move || {
|
||||
ide_sdk::java::jdk_at(std::path::Path::new(&path)).map(|j| ide_sdk::jdk_sdk(&j))
|
||||
})
|
||||
.await
|
||||
.map_err(join_err)
|
||||
blocking_value(move || ide_sdk::java::jdk_at(std::path::Path::new(&path)).map(|j| ide_sdk::jdk_sdk(&j))).await
|
||||
}
|
||||
|
||||
#[cfg(all(test, unix))]
|
||||
|
||||
@@ -3,7 +3,7 @@ use crate::Host;
|
||||
use crate::Project;
|
||||
use ide_command::command;
|
||||
|
||||
use super::doc::blocking;
|
||||
use super::blocking;
|
||||
use ide_core::settings::SpellingSettings;
|
||||
use ide_core::{DocId, IdeError, IdeResult, RequestId};
|
||||
use ide_language::SpellingKind;
|
||||
|
||||
@@ -10,7 +10,7 @@ use crate::Host;
|
||||
use crate::Project;
|
||||
use ide_command::command;
|
||||
|
||||
use super::doc::blocking;
|
||||
use super::blocking;
|
||||
use ide_core::{CancellationToken, DocId, IdeError, IdeResult, LanguageId, Pos, Range, RequestId};
|
||||
use ide_syntax::{
|
||||
ExpressionAt, FileIdentifiers, IdentifierOccurrence, Locals, NodeAt, Snapshot, StructuralRanges, StructureResult,
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
use crate::Host;
|
||||
use ide_command::command;
|
||||
use ide_core::{IdeResult, RunId};
|
||||
use ide_dap::{JvmMemoryUnavailable, JvmThreadsResult, JvmThreadsUnavailable};
|
||||
use ide_jvm_attach::{ProcEntry, is_hotspot, process_table, select_run_jvm};
|
||||
use std::sync::Arc;
|
||||
|
||||
/// A `Thread.print -l` of the JVM a run started: the deepest HotSpot JVM of the run's process
|
||||
/// tree, else the one carrying `token` (the run's marker property).
|
||||
#[command(trust = trusted)]
|
||||
pub async fn run_jvm_thread_dump(
|
||||
host: &Arc<Host>,
|
||||
window: &str,
|
||||
id: RunId,
|
||||
token: Option<String>,
|
||||
) -> IdeResult<JvmThreadsResult> {
|
||||
host.require_trust(window)?;
|
||||
let remote = host.remote.runs.contains(id);
|
||||
let root = if remote { None } else { host.processes.pid(id) };
|
||||
let selected = host.blocking(move || Ok(run_jvm(remote, root, token.as_deref(), process_table, is_hotspot)));
|
||||
let pid = match selected.await? {
|
||||
Ok(pid) => pid,
|
||||
Err(refused) => return Ok(refused),
|
||||
};
|
||||
// A debugger attached to this run or JVM (Debug of a build tool's run, Attach to Process)
|
||||
// may hold it suspended, which only its session knows.
|
||||
if let Some(dump) = host.debugger.debugged_jvm_thread_dump(id, pid).await {
|
||||
return dump;
|
||||
}
|
||||
// The attach handshake blocks for seconds.
|
||||
host.blocking(move || Ok(ide_dap::run_jvm_thread_dump(pid))).await
|
||||
}
|
||||
|
||||
fn unavailable(reason: JvmThreadsUnavailable) -> JvmThreadsResult {
|
||||
JvmThreadsResult::Unavailable { reason }
|
||||
}
|
||||
|
||||
fn jvm(reason: JvmMemoryUnavailable) -> JvmThreadsResult {
|
||||
unavailable(JvmThreadsUnavailable::Jvm { reason })
|
||||
}
|
||||
|
||||
/// The run's JVM, or why none can be dumped. `root` is the run's process while it runs; the
|
||||
/// process table is read only once the cheaper reasons to refuse are ruled out.
|
||||
fn run_jvm(
|
||||
remote: bool,
|
||||
root: Option<u32>,
|
||||
token: Option<&str>,
|
||||
table: impl FnOnce() -> Vec<ProcEntry>,
|
||||
is_hotspot: impl Fn(u32) -> bool,
|
||||
) -> Result<u32, JvmThreadsResult> {
|
||||
if remote {
|
||||
return Err(unavailable(JvmThreadsUnavailable::RemoteRun));
|
||||
}
|
||||
let Some(root) = root else { return Err(jvm(JvmMemoryUnavailable::ProgramExited)) };
|
||||
if !cfg!(unix) {
|
||||
return Err(jvm(JvmMemoryUnavailable::UnsupportedPlatform));
|
||||
}
|
||||
select_run_jvm(&table(), root, token, is_hotspot).ok_or_else(|| jvm(JvmMemoryUnavailable::NoJvmProcess))
|
||||
}
|
||||
|
||||
ide_command::domain!(thread_dump: run_jvm_thread_dump);
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn never_called<T>() -> T {
|
||||
panic!("not reached")
|
||||
}
|
||||
|
||||
fn proc(pid: u32, ppid: u32, command: &str) -> ProcEntry {
|
||||
ProcEntry { pid, ppid, command: command.into() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remote_run_is_refused() {
|
||||
let result = run_jvm(true, Some(10), None, never_called, |_| never_called());
|
||||
assert_eq!(result, Err(unavailable(JvmThreadsUnavailable::RemoteRun)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exited_run_reports_program_exited() {
|
||||
let result = run_jvm(false, None, None, never_called, |_| never_called());
|
||||
assert_eq!(result, Err(jvm(JvmMemoryUnavailable::ProgramExited)));
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn no_jvm_in_tree() {
|
||||
let table = || vec![proc(10, 1, "sh -c run"), proc(11, 10, "sleep 100")];
|
||||
let result = run_jvm(false, Some(10), None, table, |_| false);
|
||||
assert_eq!(result, Err(jvm(JvmMemoryUnavailable::NoJvmProcess)));
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn finds_the_jvm_below_the_run() {
|
||||
let table = || vec![proc(10, 1, "sh -c run"), proc(11, 10, "java -jar app.jar")];
|
||||
assert_eq!(run_jvm(false, Some(10), None, table, |pid| pid == 11), Ok(11));
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
#[test]
|
||||
fn unsupported_without_reading_the_process_table() {
|
||||
let result = run_jvm(false, Some(10), None, never_called, |_| never_called());
|
||||
assert_eq!(result, Err(jvm(JvmMemoryUnavailable::UnsupportedPlatform)));
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
//! Language server / debug adapter installer and JDK downloads (`ide-tools`).
|
||||
use super::{blocking, blocking_value};
|
||||
use crate::Host;
|
||||
use crate::ops::Channel;
|
||||
use ide_command::command;
|
||||
@@ -51,10 +52,6 @@ fn languages(host: &Host, window: &str) -> Vec<ide_language::LanguageConfig> {
|
||||
langs
|
||||
}
|
||||
|
||||
fn join_err(e: impl std::fmt::Display) -> IdeError {
|
||||
IdeError::internal(e.to_string())
|
||||
}
|
||||
|
||||
fn reconfigure_servers(host: &Host) {
|
||||
for project in host.projects() {
|
||||
let lsp = project.lsp.clone();
|
||||
@@ -67,7 +64,7 @@ fn reconfigure_servers(host: &Host) {
|
||||
pub async fn tools_list(host: &Host, window: &str) -> IdeResult<Vec<ToolInfo>> {
|
||||
let tools = tools(host, window)?;
|
||||
let langs = languages(host, window);
|
||||
tokio::task::spawn_blocking(move || tools.list(&langs)).await.map_err(join_err)
|
||||
blocking_value(move || tools.list(&langs)).await
|
||||
}
|
||||
|
||||
/// Installs (or reinstalls) a tool into `<app-data>/tools`, streaming output through
|
||||
@@ -83,15 +80,14 @@ pub async fn tools_install(
|
||||
let tools = tools(host, window)?;
|
||||
let langs = languages(host, window);
|
||||
let cancel = host.begin_request(request);
|
||||
let result = tokio::task::spawn_blocking(move || {
|
||||
let result = blocking(move || {
|
||||
tools.install(&name, &langs, &cancel, &|e| {
|
||||
let _ = on_event.send(e);
|
||||
})
|
||||
})
|
||||
.await
|
||||
.map_err(join_err);
|
||||
.await;
|
||||
host.end_request(request);
|
||||
let info = result??;
|
||||
let info = result?;
|
||||
// Language servers whose launch depends on installed tools (jdtls loads the
|
||||
// java-debug bundle) pick the change up.
|
||||
reconfigure_servers(host);
|
||||
@@ -104,9 +100,9 @@ pub async fn tools_install(
|
||||
pub async fn tools_updates(host: &Host, window: &str, request: RequestId) -> IdeResult<Vec<ToolUpdate>> {
|
||||
let tools = tools(host, window)?;
|
||||
let cancel = host.begin_request(request);
|
||||
let result = tokio::task::spawn_blocking(move || tools.updates(&cancel)).await.map_err(join_err);
|
||||
let result = blocking(move || tools.updates(&cancel)).await;
|
||||
host.end_request(request);
|
||||
result?
|
||||
result
|
||||
}
|
||||
|
||||
/// Removes a tool the IDE installed.
|
||||
@@ -114,7 +110,7 @@ pub async fn tools_updates(host: &Host, window: &str, request: RequestId) -> Ide
|
||||
pub async fn tools_uninstall(host: &Host, window: &str, name: String) -> IdeResult<ToolInfo> {
|
||||
let tools = tools(host, window)?;
|
||||
let langs = languages(host, window);
|
||||
let info = tokio::task::spawn_blocking(move || tools.uninstall(&name, &langs)).await.map_err(join_err)??;
|
||||
let info = blocking(move || tools.uninstall(&name, &langs)).await?;
|
||||
reconfigure_servers(host);
|
||||
Ok(info)
|
||||
}
|
||||
@@ -130,9 +126,9 @@ pub fn jdk_download_vendors() -> Vec<JdkVendor> {
|
||||
pub async fn jdk_download_releases(host: &Host, vendor: String, request: RequestId) -> IdeResult<JdkReleases> {
|
||||
let tools = Tools::new(&host.local_data_dir);
|
||||
let cancel = host.begin_request(request);
|
||||
let result = tokio::task::spawn_blocking(move || tools.jdk_releases(&vendor, &cancel)).await.map_err(join_err);
|
||||
let result = blocking(move || tools.jdk_releases(&vendor, &cancel)).await;
|
||||
host.end_request(request);
|
||||
result?
|
||||
result
|
||||
}
|
||||
|
||||
/// Where Download JDK puts JDKs unless told otherwise.
|
||||
@@ -157,7 +153,7 @@ pub async fn jdk_download(
|
||||
let tools = Tools::new(&host.local_data_dir);
|
||||
let location = location.filter(|p| !p.as_os_str().is_empty());
|
||||
let cancel = host.begin_request(request);
|
||||
let result = tokio::task::spawn_blocking(move || {
|
||||
let result = blocking(move || {
|
||||
let jdk = tools.download_jdk(&vendor, version, location.as_deref(), &cancel, &|e| {
|
||||
let _ = on_event.send(e);
|
||||
})?;
|
||||
@@ -171,10 +167,9 @@ pub async fn jdk_download(
|
||||
.ok_or_else(|| IdeError::internal(format!("{} is not a JDK home", home.display())))?;
|
||||
IdeResult::Ok(ide_sdk::jdk_sdk(&jdk))
|
||||
})
|
||||
.await
|
||||
.map_err(join_err);
|
||||
.await;
|
||||
host.end_request(request);
|
||||
let sdk = result??;
|
||||
let sdk = result?;
|
||||
reconfigure_servers(host);
|
||||
Ok(sdk)
|
||||
}
|
||||
@@ -193,7 +188,7 @@ pub async fn jdtls_required_java(host: &Host, window: &str) -> IdeResult<Option<
|
||||
};
|
||||
ide_sdk::apply::server_launch_overrides(&mut cfg, &settings);
|
||||
ide_sdk::apply::server_protocol_overrides(&mut cfg, &settings);
|
||||
tokio::task::spawn_blocking(move || ide_sdk::java::jdtls_required_java(&cfg)).await.map_err(join_err)
|
||||
blocking_value(move || ide_sdk::java::jdtls_required_java(&cfg)).await
|
||||
}
|
||||
|
||||
ide_command::domain!(
|
||||
|
||||
@@ -3,6 +3,7 @@ use super::*;
|
||||
use crate::Host;
|
||||
use crate::Project;
|
||||
use crate::ops::Channel;
|
||||
use crate::ops::blocking;
|
||||
use ide_command::command;
|
||||
use ide_core::error::PushDivergence;
|
||||
use ide_core::ipc_path::IpcPath;
|
||||
@@ -413,10 +414,6 @@ fn per_backend(
|
||||
per_repo(project, paths, recorded, |r, paths| f(r as &dyn Backend, paths))
|
||||
}
|
||||
|
||||
async fn blocking<T: Send + 'static>(f: impl FnOnce() -> IdeResult<T> + Send + 'static) -> IdeResult<T> {
|
||||
tokio::task::spawn_blocking(f).await.map_err(|e| ide_core::IdeError::internal(e.to_string()))?
|
||||
}
|
||||
|
||||
fn with_shelf_batch<T>(project: &Project, batch: Option<String>, operation: impl FnOnce() -> T) -> T {
|
||||
let Some(batch) = batch.and_then(|id| uuid::Uuid::parse_str(&id).ok()) else { return operation() };
|
||||
let repos = project.repos();
|
||||
|
||||
@@ -3516,6 +3516,7 @@ impl PluginWorkspace for HostWorkspace {
|
||||
max_matches: limit.min(10_000).saturating_add(1),
|
||||
context: Default::default(),
|
||||
include_excluded: false,
|
||||
skip_large_files: false,
|
||||
};
|
||||
query.exclude.extend(project.search_excludes());
|
||||
let files = Mutex::new(Vec::new());
|
||||
|
||||
@@ -5,18 +5,15 @@ use super::{
|
||||
PluginInfo, PluginStatusItem, WorkbenchEvent,
|
||||
};
|
||||
use crate::Host;
|
||||
use crate::ops::blocking;
|
||||
use ide_command::command;
|
||||
use ide_core::{IdeError, IdeResult, RequestId};
|
||||
use ide_core::{IdeResult, RequestId};
|
||||
use ide_plugin::Invocation;
|
||||
use ide_workspace::settings::SettingsScope;
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
|
||||
async fn blocking<T: Send + 'static>(f: impl FnOnce() -> IdeResult<T> + Send + 'static) -> IdeResult<T> {
|
||||
tokio::task::spawn_blocking(f).await.map_err(|e| IdeError::internal(e.to_string()))?
|
||||
}
|
||||
|
||||
/// Runs a plugin command in the context of this window's project and focused editor.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[command(trust = trusted)]
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
use super::PluginHost;
|
||||
use crate::ops::blocking;
|
||||
use ide_command::command;
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use ide_plugin::Invocation;
|
||||
@@ -200,10 +201,6 @@ pub async fn plugin_navigation_markers(
|
||||
.await
|
||||
}
|
||||
|
||||
async fn blocking<T: Send + 'static>(f: impl FnOnce() -> IdeResult<T> + Send + 'static) -> IdeResult<T> {
|
||||
tokio::task::spawn_blocking(f).await.map_err(|e| IdeError::internal(e.to_string()))?
|
||||
}
|
||||
|
||||
ide_command::domain!(
|
||||
plugins_index_ops:
|
||||
plugin_endpoints,
|
||||
|
||||
@@ -11,6 +11,7 @@ use super::{PackageFile, PluginEvent, PluginHost, PluginSource, PluginStatus, Pl
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use ide_extension::package::{self, Index, IndexEntry, PackageSignature, PluginIcon, SIGNATURE_FILE};
|
||||
use ide_extension::{MANIFEST_FILE, Manifest};
|
||||
use ide_tools::mirror;
|
||||
use semver::Version;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::path::{Path, PathBuf};
|
||||
@@ -237,6 +238,11 @@ impl PluginHost {
|
||||
*self.default_market_url.write() = url.filter(|u| !u.trim().is_empty());
|
||||
}
|
||||
|
||||
/// Where plugin packages are fetched from first (Tools › Download sources).
|
||||
pub fn set_downloads(&self, downloads: ide_core::settings::ToolDownloadSettings) {
|
||||
*self.downloads.write() = downloads;
|
||||
}
|
||||
|
||||
pub fn set_market_url(&self, url: Option<String>) {
|
||||
self.state.lock().market_url = url.filter(|u| !u.trim().is_empty());
|
||||
self.save_state();
|
||||
@@ -355,40 +361,111 @@ impl PluginHost {
|
||||
entry.id, entry.version
|
||||
)));
|
||||
}
|
||||
let bytes = read_url(&download, MAX_PACKAGE).map_err(IdeError::unavailable)?;
|
||||
let candidates = mirror::candidates(&download, &self.downloads.read());
|
||||
let downloads = self.plugins_dir.join(DOWNLOADS);
|
||||
std::fs::create_dir_all(&downloads)?;
|
||||
let archive = downloads.join(format!("{}-{}.{}", entry.id, entry.version, package::PACKAGE_EXTENSION));
|
||||
std::fs::write(&archive, bytes)?;
|
||||
let dir = self.unpack_package(&archive);
|
||||
let _ = std::fs::remove_file(&archive);
|
||||
let dir = dir?;
|
||||
let manifest = Manifest::load(&dir).map_err(IdeError::invalid)?;
|
||||
let files = self.package_files_in(&dir)?;
|
||||
let digest = package::package_digest(&dir, &files)?;
|
||||
if (manifest.id.as_str(), manifest.version.as_str(), digest.as_str())
|
||||
!= (&entry.id, &entry.version, &entry.digest)
|
||||
{
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
return Err(IdeError::invalid("the download does not match the marketplace's entry"));
|
||||
let picked = try_sources(&candidates, |index, candidate| {
|
||||
// Bytes a failed source left behind must not be unpacked as the next one's.
|
||||
if index > 0 {
|
||||
let _ = std::fs::remove_file(&archive);
|
||||
}
|
||||
// Which source a package comes from is the first thing to look at when an install
|
||||
// is slow or fails (a mirror is one of several candidates), so it goes in the log.
|
||||
tracing::info!(
|
||||
"plugins: {} {} from {} ({}){}",
|
||||
entry.id,
|
||||
entry.version,
|
||||
candidate.url,
|
||||
candidate.describe(),
|
||||
if candidates.len() > 1 {
|
||||
format!(", source {} of {}", index + 1, candidates.len())
|
||||
} else {
|
||||
String::new()
|
||||
}
|
||||
);
|
||||
let fetched = self.fetch_market_package(&candidate.url, &entry, &archive);
|
||||
if let Err(e) = &fetched {
|
||||
tracing::warn!("plugins: {} from {} failed: {}", entry.id, candidate.url, e.message);
|
||||
}
|
||||
fetched
|
||||
});
|
||||
match picked {
|
||||
Ok((dir, index)) => {
|
||||
tracing::info!(
|
||||
"plugins: {} {} installed from {}",
|
||||
entry.id,
|
||||
entry.version,
|
||||
candidates[index].describe()
|
||||
);
|
||||
Ok(dir)
|
||||
}
|
||||
Err(e) => Err(e),
|
||||
}
|
||||
if self.verified_publisher(&dir).is_none() {
|
||||
}
|
||||
|
||||
/// Fetches the package of `entry` from `url`, checks it against the index (its digest, then
|
||||
/// the publisher's signature) and only then hands it over, unpacked. A failure here is that
|
||||
/// source's failure.
|
||||
///
|
||||
/// The index has no hash of the archive itself, only [`package_digest`] of the unpacked
|
||||
/// contents, so the bytes have to be unpacked before they can be checked. The unpacked
|
||||
/// files of a source that does **not** check are therefore kept out of reach until they
|
||||
/// pass: they go to a staging folder of this attempt, and every exit but the verified one
|
||||
/// removes it, so nothing a mirror served is ever left where the install page reads from.
|
||||
fn fetch_market_package(&self, url: &str, entry: &IndexEntry, archive: &Path) -> IdeResult<PathBuf> {
|
||||
let bytes = read_url(url, MAX_PACKAGE).map_err(IdeError::unavailable)?;
|
||||
std::fs::write(archive, bytes)?;
|
||||
let unpacked = self.unpack_package(archive);
|
||||
// The archive is needed only until it is unpacked; a failed source leaves none behind.
|
||||
let _ = std::fs::remove_file(archive);
|
||||
let dir = unpacked?;
|
||||
self.verify_market_package(&dir, entry).inspect_err(|_| {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
return Err(IdeError::invalid("the marketplace package is not signed by a trusted publisher"));
|
||||
}
|
||||
})?;
|
||||
Ok(dir)
|
||||
}
|
||||
|
||||
/// Whether the unpacked package in `dir` is the one `entry` names: same id, version and
|
||||
/// digest, and signed by a publisher the index trusts.
|
||||
fn verify_market_package(&self, dir: &Path, entry: &IndexEntry) -> IdeResult<()> {
|
||||
let manifest = Manifest::load(dir).map_err(IdeError::invalid)?;
|
||||
let files = self.package_files_in(dir)?;
|
||||
let digest = package::package_digest(dir, &files)?;
|
||||
if (manifest.id.as_str(), manifest.version.as_str(), digest.as_str())
|
||||
!= (&entry.id, &entry.version, &entry.digest)
|
||||
{
|
||||
return Err(IdeError::invalid("the download does not match the marketplace's entry"));
|
||||
}
|
||||
if self.verified_publisher(dir).is_none() {
|
||||
return Err(IdeError::invalid("the marketplace package is not signed by a trusted publisher"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Unpacks a package file (`.oiplugin`, or a `.zip` of a package) next to the downloads; returns the folder.
|
||||
///
|
||||
/// A package that fails to unpack leaves nothing: the folder is removed, so a half-written
|
||||
/// zip is never mistaken for a package (a mirror's bytes reach here before they are checked).
|
||||
pub fn unpack_package(&self, archive: &Path) -> IdeResult<PathBuf> {
|
||||
let stem = archive.file_stem().and_then(|s| s.to_str()).unwrap_or("package");
|
||||
let dir = self.plugins_dir.join(DOWNLOADS).join(format!("{stem}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let unpacked = package::unpack(archive, &dir).map_err(IdeError::invalid)?;
|
||||
let unpacked = match package::unpack(archive, &dir) {
|
||||
Ok(unpacked) => unpacked,
|
||||
Err(e) => {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
return Err(IdeError::invalid(e));
|
||||
}
|
||||
};
|
||||
// Kept with the files: install checks it and keeps it with the installed copy.
|
||||
if let Some(sig) = unpacked.signature {
|
||||
let json = serde_json::to_string_pretty(&sig).map_err(|e| IdeError::internal(e.to_string()))?;
|
||||
std::fs::write(dir.join(SIGNATURE_FILE), json)?;
|
||||
let json = serde_json::to_string_pretty(&sig).map_err(|e| IdeError::internal(e.to_string()));
|
||||
let written = json.and_then(|json| std::fs::write(dir.join(SIGNATURE_FILE), json).map_err(IdeError::from));
|
||||
if let Err(e) = written {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
return Err(e);
|
||||
}
|
||||
}
|
||||
Ok(dir)
|
||||
}
|
||||
@@ -540,6 +617,31 @@ pub(super) fn read_signature(dir: &Path) -> Option<PackageSignature> {
|
||||
serde_json::from_str(&text).ok()
|
||||
}
|
||||
|
||||
/// The first `candidate` whose `attempt` succeeds, with its index.
|
||||
///
|
||||
/// A mirror is a third party: when one fails, that failure is its own and the official host
|
||||
/// below still gets its turn. The official host is the last candidate, so its failure is the
|
||||
/// download's: returned as it is when nothing came before it, else with the mirrors' reasons.
|
||||
fn try_sources<T>(
|
||||
candidates: &[mirror::Candidate],
|
||||
mut attempt: impl FnMut(usize, &mirror::Candidate) -> IdeResult<T>,
|
||||
) -> IdeResult<(T, usize)> {
|
||||
let mut failures: Vec<String> = Vec::new();
|
||||
for (index, candidate) in candidates.iter().enumerate() {
|
||||
match attempt(index, candidate) {
|
||||
Ok(value) => return Ok((value, index)),
|
||||
// A mirror's failure is its own: the next source still gets a turn.
|
||||
Err(e) if candidate.mirror.is_some() => failures.push(format!("{}: {}", candidate.describe(), e.message)),
|
||||
Err(e) if failures.is_empty() => return Err(e),
|
||||
Err(e) => {
|
||||
failures.push(format!("{}: {}", candidate.describe(), e.message));
|
||||
return Err(IdeError::unavailable(format!("could not download ({})", failures.join("; "))));
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(IdeError::unavailable(format!("could not download ({})", failures.join("; "))))
|
||||
}
|
||||
|
||||
/// Keeps the signature of a package with its installed copy.
|
||||
pub(super) fn copy_signature(src: &Path, installed: &Path) {
|
||||
if src.join(SIGNATURE_FILE).is_file() {
|
||||
@@ -588,6 +690,60 @@ mod tests {
|
||||
assert!(reachable_from("/srv/market/index.json", "/srv/market/a.oiplugin"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_mirror_that_serves_a_bad_package_leaves_the_official_host_its_turn() {
|
||||
// Two sources: the mirror, then the official host. The mirror answers with bytes that
|
||||
// do not verify — which is exactly the failure `fetch_market_package` reports for a
|
||||
// tampered package — and the official host must still be asked.
|
||||
let candidates = mirror::candidates(
|
||||
"https://github.com/acme/hello/releases/download/v1/acme.hello-1.0.0.oiplugin",
|
||||
&ide_core::settings::ToolDownloadSettings { github_mirror: "https://gh-proxy.com/".into() },
|
||||
);
|
||||
let asked: std::cell::RefCell<Vec<usize>> = std::cell::RefCell::new(Vec::new());
|
||||
let picked = try_sources(&candidates, |index, candidate| {
|
||||
asked.borrow_mut().push(index);
|
||||
match candidate.mirror.is_some() {
|
||||
true => Err(IdeError::invalid("the download does not match the marketplace's entry")),
|
||||
false => Ok("the official copy"),
|
||||
}
|
||||
});
|
||||
let (copy, index) = picked.unwrap();
|
||||
assert_eq!((copy, index), ("the official copy", 1));
|
||||
assert_eq!(*asked.borrow(), [0, 1], "the mirror was tried first, then the official host");
|
||||
|
||||
// Both failing: the official host's error is the download's, with the mirror's folded in.
|
||||
let err = try_sources(&candidates, |index, candidate| -> IdeResult<&str> {
|
||||
match candidate.mirror.is_some() {
|
||||
true => Err(IdeError::invalid("the download does not match the marketplace's entry")),
|
||||
false => Err(IdeError::unavailable(format!("nothing at {index}"))),
|
||||
}
|
||||
})
|
||||
.unwrap_err();
|
||||
assert!(err.message.contains("https://gh-proxy.com/"), "{}", err.message);
|
||||
assert!(err.message.contains("nothing at 1"), "{}", err.message);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_download_goes_to_the_mirror_first_and_the_official_host_last() {
|
||||
let url = "https://github.com/acme/hello/releases/download/v1/acme.hello-1.0.0.oiplugin";
|
||||
let through = mirror::candidates(
|
||||
url,
|
||||
&ide_core::settings::ToolDownloadSettings { github_mirror: "https://gh-proxy.com/".into() },
|
||||
);
|
||||
assert_eq!(through.len(), 2);
|
||||
assert_eq!(through[0].url, format!("https://gh-proxy.com/{url}"));
|
||||
assert!(through[0].mirror.is_some());
|
||||
assert_eq!((through[1].url.as_str(), through[1].mirror.is_none()), (url, true));
|
||||
|
||||
// A local index's own package is not on GitHub: no prefix may carry it.
|
||||
let local = mirror::candidates(
|
||||
"/srv/market/a.oiplugin",
|
||||
&ide_core::settings::ToolDownloadSettings { github_mirror: "https://gh-proxy.com/".into() },
|
||||
);
|
||||
assert_eq!(local.len(), 1);
|
||||
assert_eq!(local[0].url, "/srv/market/a.oiplugin");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_read_says_why() {
|
||||
// A port nothing listens on: refused.
|
||||
@@ -595,7 +751,10 @@ mod tests {
|
||||
let url = format!("http://127.0.0.1:{port}/a.oiplugin");
|
||||
let err = read_url(&url, 1 << 20).unwrap_err();
|
||||
assert_eq!(err.matches(&url).count(), 1, "{err}");
|
||||
assert!(err.to_lowercase().contains("refused"), "{err}");
|
||||
// The cause follows the URL. Its wording is the OS's, and localised: assert that it is
|
||||
// there rather than spelling out any one language's phrase for a refused connection.
|
||||
let cause = err.strip_prefix(&url).unwrap_or_default().trim_start_matches([':', ' ']);
|
||||
assert!(cause.len() > 1, "the failure says nothing beyond the URL: {err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -429,6 +429,8 @@ pub struct PluginHost {
|
||||
announced_updates: Mutex<Vec<String>>,
|
||||
/// The marketplace used while the user has set none (the app's official one).
|
||||
default_market_url: RwLock<Option<String>>,
|
||||
/// Tools › Download sources: where plugin packages are fetched from first.
|
||||
downloads: RwLock<ide_core::settings::ToolDownloadSettings>,
|
||||
/// Updates not confirmed yet (the new version hasn't started once): what
|
||||
/// to roll back to.
|
||||
updates: Mutex<HashMap<String, PendingUpdate>>,
|
||||
@@ -499,6 +501,7 @@ impl PluginHost {
|
||||
official_keys: RwLock::new(official_keys),
|
||||
announced_updates: Mutex::default(),
|
||||
default_market_url: RwLock::new(None),
|
||||
downloads: RwLock::new(Default::default()),
|
||||
updates: Mutex::default(),
|
||||
project_policy: RwLock::new(Arc::new(|_| false)),
|
||||
engine: PluginEngine::new().map_err(IdeError::internal)?,
|
||||
|
||||
@@ -265,9 +265,21 @@ use ide_plugin::{
|
||||
ActorError, CallError, CodeAction, CompletionItem, InlineSuggestion, LineMarker, Location, Pending, PluginHover,
|
||||
PluginInlayHint, ProviderDocument, Runtime, SemanticToken,
|
||||
};
|
||||
use std::collections::BTreeSet;
|
||||
use std::sync::Weak;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// What the plugins answered for completion in the editor.
|
||||
#[derive(Debug, Default)]
|
||||
pub(crate) struct EditorCompletion {
|
||||
/// Some plugin completes in the document, so an empty answer still asks again on typing.
|
||||
pub covered: bool,
|
||||
/// Items with the id of the plugin that gave them.
|
||||
pub items: Vec<(String, CompletionItem)>,
|
||||
/// Plugins that marked their items incomplete (API 1.16 `completion-list-provider`).
|
||||
pub incomplete: BTreeSet<String>,
|
||||
}
|
||||
|
||||
/// How long a superseded inline completion may take to return after its
|
||||
/// request was cancelled before it is interrupted.
|
||||
const CANCEL_GRACE: Duration = Duration::from_millis(250);
|
||||
@@ -332,13 +344,21 @@ impl PluginHost {
|
||||
doc: &ProviderDocument,
|
||||
owner: Option<&str>,
|
||||
f: impl FnOnce(&mut Runtime, Duration) -> Result<R, CallError> + Clone + Send + 'static,
|
||||
) -> Vec<(Arc<LoadedPlugin>, R)> {
|
||||
self.document_calls_where(kind, doc, |id| owner.is_none_or(|o| o == id), f)
|
||||
}
|
||||
/// [`Self::document_calls`] for the plugins whose id `keep` accepts.
|
||||
pub(super) fn document_calls_where<R: Send + 'static>(
|
||||
&self,
|
||||
kind: ProviderKind,
|
||||
doc: &ProviderDocument,
|
||||
keep: impl Fn(&str) -> bool,
|
||||
f: impl FnOnce(&mut Runtime, Duration) -> Result<R, CallError> + Clone + Send + 'static,
|
||||
) -> Vec<(Arc<LoadedPlugin>, R)> {
|
||||
let plugins = self
|
||||
.provider_plugins(kind, &doc.language)
|
||||
.into_iter()
|
||||
.filter(|p| {
|
||||
p.dev_root.as_ref().is_none_or(|r| doc.path.starts_with(r)) && owner.is_none_or(|id| p.id() == id)
|
||||
})
|
||||
.filter(|p| p.dev_root.as_ref().is_none_or(|r| doc.path.starts_with(r)) && keep(p.id()))
|
||||
.collect();
|
||||
self.edit_calls_plugins(plugins, f)
|
||||
}
|
||||
@@ -413,41 +433,48 @@ impl PluginHost {
|
||||
at: ide_core::Pos,
|
||||
trigger: Option<&str>,
|
||||
) -> Vec<(String, CompletionItem)> {
|
||||
self.provide_completion_for_editor(doc, at, trigger).1
|
||||
self.provide_completion_for_editor(doc, at, trigger, None).items
|
||||
}
|
||||
|
||||
/// Completion from the plugins for the editor; with `only`, from those plugins alone (the ones
|
||||
/// whose list was incomplete, asked again while the user types on).
|
||||
pub(crate) fn provide_completion_for_editor(
|
||||
&self,
|
||||
doc: &ProviderDocument,
|
||||
at: ide_core::Pos,
|
||||
trigger: Option<&str>,
|
||||
) -> (bool, Vec<(String, CompletionItem)>) {
|
||||
only: Option<&BTreeSet<String>>,
|
||||
) -> EditorCompletion {
|
||||
// An injection-capable outer document (e.g. SQL embedded in text) may complete at other
|
||||
// positions even when `at` is outside an injection, so avoid marking document-wide backoff.
|
||||
let mut covered = self.has_document_providers(ProviderKind::Injections, doc);
|
||||
let items = self
|
||||
.feature_documents(doc, Some(at))
|
||||
.into_iter()
|
||||
.flat_map(|(doc, bounds)| {
|
||||
if self.has_document_providers(ProviderKind::Completion, &doc) {
|
||||
covered = true;
|
||||
let mut incomplete = BTreeSet::new();
|
||||
let mut items = Vec::new();
|
||||
for (doc, bounds) in self.feature_documents(doc, Some(at)) {
|
||||
if self.has_document_providers(ProviderKind::Completion, &doc) {
|
||||
covered = true;
|
||||
}
|
||||
let (d, t) = (Arc::new(doc.clone()), trigger.map(str::to_owned));
|
||||
let answers = self.document_calls_where(
|
||||
ProviderKind::Completion,
|
||||
&doc,
|
||||
|id| only.is_none_or(|ids| ids.contains(id)),
|
||||
move |rt, timeout| rt.provide_completion_list(&d, at, t.as_deref(), timeout),
|
||||
);
|
||||
for (p, (list, more)) in answers {
|
||||
if more {
|
||||
incomplete.insert(p.id().to_owned());
|
||||
}
|
||||
let (d, t) = (Arc::new(doc.clone()), trigger.map(str::to_owned));
|
||||
self.document_calls(ProviderKind::Completion, &doc, move |rt, timeout| {
|
||||
rt.provide_completion(&d, at, t.as_deref(), timeout)
|
||||
})
|
||||
.into_iter()
|
||||
.flat_map(|(p, items)| items.into_iter().map(move |i| (p.id().to_owned(), i)))
|
||||
.filter_map(move |(p, mut i)| {
|
||||
items.extend(list.into_iter().filter_map(|mut i| {
|
||||
if i.replace.is_some_and(|r| !bounds.contains(r)) {
|
||||
return None;
|
||||
}
|
||||
i.additional_edits.retain(|e| bounds.contains(e.range));
|
||||
Some((p, i))
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
(covered, items)
|
||||
Some((p.id().to_owned(), i))
|
||||
}));
|
||||
}
|
||||
}
|
||||
EditorCompletion { covered, items, incomplete }
|
||||
}
|
||||
|
||||
pub fn provide_code_actions(
|
||||
|
||||
@@ -20,6 +20,7 @@
|
||||
|
||||
use super::{Consent, HostWorkspace, PluginEvent, PluginHost, PluginSource, SecretStore};
|
||||
use crate::catalogue::TrustClass;
|
||||
use crate::ops::blocking;
|
||||
use crate::rpc::{Dispatcher, PeerHandle};
|
||||
use base64::Engine as _;
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
@@ -451,10 +452,6 @@ impl RemotePlugins {
|
||||
}
|
||||
}
|
||||
|
||||
async fn blocking<T: Send + 'static>(f: impl FnOnce() -> IdeResult<T> + Send + 'static) -> IdeResult<T> {
|
||||
tokio::task::spawn_blocking(f).await.map_err(|e| IdeError::internal(e.to_string()))?
|
||||
}
|
||||
|
||||
fn spawn_supervision(host: Weak<PluginHost>) -> IdeResult<()> {
|
||||
std::thread::Builder::new().name("remote-plugins".into()).spawn(move || {
|
||||
for n in 1u32.. {
|
||||
|
||||
@@ -36,6 +36,7 @@
|
||||
//! priority = "default" # or "option": only through Open With
|
||||
//! layout = "tab" # or "split" / "preview": beside the text editor
|
||||
//! web = "web/index.html" # a web page from the package instead of rendered content
|
||||
//! frames = ["https://example.com"] # API 1.16: origins the page may embed; each needs `net:<host>`
|
||||
//!
|
||||
//! [[contributes.editorPanels]]
|
||||
//! id = "minimap"
|
||||
@@ -641,6 +642,65 @@ struct ViewDecl {
|
||||
/// A web page of the package (`web/index.html`) instead of content the code renders.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
web: Option<String>,
|
||||
/// Origins the web page may embed in `<iframe>`s (API 1.16).
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
frames: Vec<String>,
|
||||
}
|
||||
|
||||
/// Most origins one web page may declare in `frames`.
|
||||
const MAX_FRAMES: usize = 16;
|
||||
|
||||
/// Checks a web page's `frames` and returns them as origins (`https://host[:port]`).
|
||||
/// Each is HTTPS, or HTTP to a loopback host, and must be covered by a `net:` or
|
||||
/// `net.http:` capability of the manifest, so the install page lists it; the page
|
||||
/// gets only the ones the user granted.
|
||||
fn frame_origins(pkg: &Package, frames: &[String], web: bool, what: &str) -> Result<Vec<String>, String> {
|
||||
if frames.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
pkg.manifest.needs_api(&format!("{what}: `frames`"), 16)?;
|
||||
if !web {
|
||||
return Err(format!("{what}: `frames` is for a web page (`web`)"));
|
||||
}
|
||||
if frames.len() > MAX_FRAMES {
|
||||
return Err(format!("{what}: at most {MAX_FRAMES} `frames`"));
|
||||
}
|
||||
let mut origins = Vec::new();
|
||||
for frame in frames {
|
||||
let origin = frame_origin(frame).map_err(|e| format!("{what}: frames: {frame:?}: {e}"))?;
|
||||
let cap = ide_plugin::net_capability(&origin).map_err(|e| format!("{what}: frames: {frame:?}: {e}"))?;
|
||||
if !pkg.manifest.capabilities.all().any(|c| c.covers(&cap)) {
|
||||
return Err(format!("{what}: frames: {frame:?} needs the `{cap}` capability (required or optional)"));
|
||||
}
|
||||
if !origins.contains(&origin) {
|
||||
origins.push(origin);
|
||||
}
|
||||
}
|
||||
Ok(origins)
|
||||
}
|
||||
|
||||
/// `https://host[:port]` (or `http://` to a loopback host) with nothing after it.
|
||||
fn frame_origin(frame: &str) -> Result<String, String> {
|
||||
let url = url::Url::parse(frame).map_err(|e| format!("not a URL ({e})"))?;
|
||||
let loopback = matches!(
|
||||
url.host(),
|
||||
Some(url::Host::Domain("localhost")) | Some(url::Host::Ipv4(std::net::Ipv4Addr::LOCALHOST))
|
||||
) || url.host() == Some(url::Host::Ipv6(std::net::Ipv6Addr::LOCALHOST));
|
||||
match url.scheme() {
|
||||
"https" => {}
|
||||
"http" if loopback => {}
|
||||
_ => return Err("an origin is https://, or http:// to localhost".into()),
|
||||
}
|
||||
if url.host_str().is_none_or(|h| h.contains('*')) {
|
||||
return Err("name one exact host".into());
|
||||
}
|
||||
if !url.username().is_empty() || url.password().is_some() {
|
||||
return Err("no user name or password".into());
|
||||
}
|
||||
if url.path() != "/" || url.query().is_some() || url.fragment().is_some() {
|
||||
return Err("an origin only: no path, query or fragment".into());
|
||||
}
|
||||
Ok(url.origin().ascii_serialization())
|
||||
}
|
||||
|
||||
/// The files of a `web` entry, or a check that the code renders the view.
|
||||
@@ -655,7 +715,7 @@ fn web_or_code(pkg: &Package, web: Option<&str>, what: &str) -> Result<Vec<PathB
|
||||
}
|
||||
|
||||
pub(super) fn view(pkg: &Package, decl: toml::Value) -> Result<UiDecl, String> {
|
||||
let d: ViewDecl = decode(VIEWS, decl)?;
|
||||
let mut d: ViewDecl = decode(VIEWS, decl)?;
|
||||
validate_item_id(&d.id, "view id")?;
|
||||
title(VIEWS, &d.title)?;
|
||||
if let Some(group) = &d.group {
|
||||
@@ -668,6 +728,7 @@ pub(super) fn view(pkg: &Package, decl: toml::Value) -> Result<UiDecl, String> {
|
||||
}
|
||||
|
||||
let files = web_or_code(pkg, d.web.as_deref(), &format!("view {:?}", d.id))?;
|
||||
d.frames = frame_origins(pkg, &d.frames, d.web.is_some(), &format!("view {:?}", d.id))?;
|
||||
if !["left", "right", "bottom", SERVICES_LOCATION].contains(&d.location.as_str()) {
|
||||
return Err(format!("view {:?}: `location` is left, right, bottom or services", d.id));
|
||||
}
|
||||
@@ -734,6 +795,9 @@ struct CustomEditorDecl {
|
||||
layout: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
web: Option<String>,
|
||||
/// Origins the web page may embed (API 1.16).
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
frames: Vec<String>,
|
||||
}
|
||||
|
||||
fn default_priority() -> String {
|
||||
@@ -758,11 +822,12 @@ fn file_patterns(patterns: &[String], what: &str) -> Result<(), String> {
|
||||
}
|
||||
|
||||
pub(super) fn custom_editor(pkg: &Package, decl: toml::Value) -> Result<UiDecl, String> {
|
||||
let d: CustomEditorDecl = decode(CUSTOM_EDITORS, decl)?;
|
||||
let mut d: CustomEditorDecl = decode(CUSTOM_EDITORS, decl)?;
|
||||
validate_item_id(&d.id, "custom editor id")?;
|
||||
title(CUSTOM_EDITORS, &d.title)?;
|
||||
let what = format!("custom editor {:?}", d.id);
|
||||
let files = web_or_code(pkg, d.web.as_deref(), &what)?;
|
||||
d.frames = frame_origins(pkg, &d.frames, d.web.is_some(), &what)?;
|
||||
file_patterns(&d.patterns, &what)?;
|
||||
if d.priority != "default" && d.priority != "option" {
|
||||
return Err(format!("{what}: `priority` is default or option"));
|
||||
@@ -783,6 +848,9 @@ struct EditorPanelDecl {
|
||||
width: u32,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
when: Option<String>,
|
||||
/// Origins the page may embed (API 1.16).
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
frames: Vec<String>,
|
||||
}
|
||||
|
||||
const EDITOR_PANEL_WIDTH: std::ops::RangeInclusive<u32> = 40..=400;
|
||||
@@ -791,7 +859,7 @@ const EDITOR_PANEL_WIDTH: std::ops::RangeInclusive<u32> = 40..=400;
|
||||
/// editor group, beside its text editor. It sees each file the group shows, so it
|
||||
/// needs `editor.read`.
|
||||
pub(super) fn editor_panel(pkg: &Package, decl: toml::Value) -> Result<UiDecl, String> {
|
||||
let d: EditorPanelDecl = decode(EDITOR_PANELS, decl)?;
|
||||
let mut d: EditorPanelDecl = decode(EDITOR_PANELS, decl)?;
|
||||
pkg.manifest.needs_api(&format!("contributes.{EDITOR_PANELS}"), 9)?;
|
||||
validate_item_id(&d.id, "editor panel id")?;
|
||||
let what = format!("editor panel {:?}", d.id);
|
||||
@@ -805,6 +873,7 @@ pub(super) fn editor_panel(pkg: &Package, decl: toml::Value) -> Result<UiDecl, S
|
||||
return Err(format!("{what}: needs the `editor.read` capability (the page sees the files editors show)"));
|
||||
}
|
||||
let files = super::web::web_files(pkg, &d.web, &what)?;
|
||||
d.frames = frame_origins(pkg, &d.frames, true, &what)?;
|
||||
let mut out = UiDecl::new(d.id.clone(), d.id.clone(), json(&d)?);
|
||||
out.files = files;
|
||||
Ok(out)
|
||||
@@ -1333,6 +1402,80 @@ mod tests {
|
||||
assert!(check(&optional).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn web_pages_declare_frames_their_net_capabilities_cover() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
std::fs::create_dir(dir.path().join("web")).unwrap();
|
||||
std::fs::write(dir.path().join("web/index.html"), "<iframe></iframe>").unwrap();
|
||||
let header = "id = \"p\"\nname = \"P\"\nversion = \"1.0.0\"\nengines.openidea = \"^1.16\"\nwasm = \"p.wasm\"\n\
|
||||
[capabilities]\nrequired = [\"editor.read\", \"net:example.com\", \"net:*.games.test\", \"net:localhost\"]\n";
|
||||
let check = |point: &str, body: &str, header: &str| {
|
||||
let manifest = ide_extension::Manifest::parse(&format!("{header}[[contributes.{point}]]\n{body}"))?;
|
||||
let decl = manifest.declarations(point).into_iter().next().unwrap();
|
||||
let pkg = Package::new(manifest, dir.path().to_path_buf());
|
||||
match point {
|
||||
VIEWS => view(&pkg, decl),
|
||||
CUSTOM_EDITORS => custom_editor(&pkg, decl),
|
||||
_ => editor_panel(&pkg, decl),
|
||||
}
|
||||
};
|
||||
let view_with =
|
||||
|frames: &str| format!("id = \"v\"\ntitle = \"V\"\nweb = \"web/index.html\"\nframes = {frames}\n");
|
||||
let ok = check(
|
||||
VIEWS,
|
||||
&view_with(r#"["https://EXAMPLE.com/", "https://a.games.test:8443", "http://localhost:5173"]"#),
|
||||
header,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
ok.json["frames"],
|
||||
serde_json::json!(["https://example.com", "https://a.games.test:8443", "http://localhost:5173"])
|
||||
);
|
||||
assert!(
|
||||
check(VIEWS, "id = \"v\"\ntitle = \"V\"\nweb = \"web/index.html\"\n", header)
|
||||
.unwrap()
|
||||
.json
|
||||
.get("frames")
|
||||
.is_none()
|
||||
);
|
||||
let editor = "id = \"e\"\ntitle = \"E\"\npatterns = [\"*.x\"]\nweb = \"web/index.html\"\nframes = [\"https://example.com\"]\n";
|
||||
assert_eq!(
|
||||
check(CUSTOM_EDITORS, editor, header).unwrap().json["frames"],
|
||||
serde_json::json!(["https://example.com"])
|
||||
);
|
||||
let panel = "id = \"m\"\nweb = \"web/index.html\"\nwidth = 110\nframes = [\"https://example.com\"]\n";
|
||||
assert_eq!(
|
||||
check(EDITOR_PANELS, panel, header).unwrap().json["frames"],
|
||||
serde_json::json!(["https://example.com"])
|
||||
);
|
||||
|
||||
for (frames, error) in [
|
||||
(r#"["https://other.com"]"#, "`net:other.com` capability"),
|
||||
(r#"["https://games.test"]"#, "`net:games.test` capability"),
|
||||
(r#"["http://example.com"]"#, "https://, or http:// to localhost"),
|
||||
(r#"["ftp://example.com"]"#, "https://, or http:// to localhost"),
|
||||
(r#"["https://example.com/room"]"#, "no path"),
|
||||
(r#"["https://example.com?x"]"#, "no path"),
|
||||
(r#"["https://example.com/#x"]"#, "no path"),
|
||||
(r#"["https://*.games.test"]"#, "one exact host"),
|
||||
(r#"["https://[email protected]"]"#, "user name"),
|
||||
(r#"["example.com"]"#, "not a URL"),
|
||||
(r#"["data:text/html,x"]"#, "https://"),
|
||||
] {
|
||||
let err = check(VIEWS, &view_with(frames), header).unwrap_err();
|
||||
assert!(err.contains(error), "{frames} → {err}");
|
||||
}
|
||||
let many = format!("[{}]", vec!["\"https://example.com\""; 17].join(", "));
|
||||
assert!(check(VIEWS, &view_with(&many), header).unwrap_err().contains("at most 16"));
|
||||
let older = header.replace("^1.16", "^1.15");
|
||||
assert!(check(VIEWS, &view_with(r#"["https://example.com"]"#), &older).unwrap_err().contains("1.16"));
|
||||
let code_view = "id = \"v\"\ntitle = \"V\"\nframes = [\"https://example.com\"]\n";
|
||||
assert!(check(VIEWS, code_view, header).unwrap_err().contains("for a web page"));
|
||||
// `net:ask` is not a listed host: the install page would not show the origin.
|
||||
let ask = header.replace("\"net:example.com\"", "\"net:ask\"");
|
||||
assert!(check(VIEWS, &view_with(r#"["https://example.com"]"#), &ask).unwrap_err().contains("capability"));
|
||||
}
|
||||
|
||||
fn package_with_catalogs(files: &[(&str, &str)]) -> (tempfile::TempDir, Package) {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
std::fs::create_dir(dir.path().join(LOCALES_DIR)).unwrap();
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
//! the desktop for local projects, `openidea-server` for remote ones.
|
||||
|
||||
use super::{PluginEditor, PluginHost, PluginOutputLine};
|
||||
use crate::ops::blocking;
|
||||
use ide_command::command;
|
||||
use ide_core::{DocId, IdeError, IdeResult};
|
||||
use ide_plugin::{EditorContext, Invocation, ServiceTab, View, ViewEvent, Viewport};
|
||||
@@ -35,10 +36,6 @@ pub fn view_invocation(
|
||||
})
|
||||
}
|
||||
|
||||
async fn blocking<T: Send + 'static>(f: impl FnOnce() -> IdeResult<T> + Send + 'static) -> IdeResult<T> {
|
||||
tokio::task::spawn_blocking(f).await.map_err(|e| IdeError::internal(e.to_string()))?
|
||||
}
|
||||
|
||||
/// Content of a plugin view (`doc`: the document of a custom editor; `editor`: for
|
||||
/// a tool window, the window's active editor, as commands get it).
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
|
||||
@@ -121,6 +121,10 @@ pub(super) struct WebPtySession {
|
||||
pub struct WebFile {
|
||||
pub bytes: Vec<u8>,
|
||||
pub mime: &'static str,
|
||||
/// The origins a page may embed: `None` when no web page whose directory holds
|
||||
/// the file declares `frames` (API 1.16), else the declared origins the user has
|
||||
/// granted (`net:` / `net.http:`), possibly none.
|
||||
pub frames: Option<Vec<String>>,
|
||||
}
|
||||
|
||||
impl PluginHost {
|
||||
@@ -324,6 +328,32 @@ impl PluginHost {
|
||||
})
|
||||
}
|
||||
|
||||
/// `frames` of the web pages whose directory holds `rel`, kept to those `granted`.
|
||||
fn web_frames(&self, plugin: &str, rel: &str, granted: &[ide_extension::Capability]) -> Option<Vec<String>> {
|
||||
let declared: Vec<String> = super::ui_points::WEB_POINTS
|
||||
.iter()
|
||||
.flat_map(|point| self.ui.items(point, Some(plugin)))
|
||||
.filter(|item| {
|
||||
let dir = item.decl.get("web").and_then(|w| w.as_str()).and_then(|e| e.rsplit_once('/'));
|
||||
dir.is_some_and(|(dir, _)| rel.starts_with(&format!("{dir}/")))
|
||||
})
|
||||
.filter_map(|item| item.decl.get("frames").and_then(|f| f.as_array()).cloned())
|
||||
.flatten()
|
||||
.filter_map(|f| f.as_str().map(str::to_owned))
|
||||
.collect();
|
||||
if declared.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let mut allowed = Vec::new();
|
||||
for origin in declared {
|
||||
let ok = ide_plugin::net_capability(&origin).is_ok_and(|cap| granted.iter().any(|g| g.covers(&cap)));
|
||||
if ok && !allowed.contains(&origin) {
|
||||
allowed.push(origin);
|
||||
}
|
||||
}
|
||||
Some(allowed)
|
||||
}
|
||||
|
||||
/// The web roots `plugin` declares (entry directories, package-relative, `/`-terminated).
|
||||
fn web_dirs(&self, plugin: &str) -> Vec<String> {
|
||||
super::ui_points::WEB_POINTS
|
||||
@@ -376,7 +406,14 @@ impl PluginHost {
|
||||
return Err(IdeError::not_found(format!("{rel}: not part of a web view")));
|
||||
}
|
||||
let bytes = plugin.pkg.read_bytes(rel_path).map_err(IdeError::not_found)?;
|
||||
Ok(WebFile { bytes, mime: mime(rel) })
|
||||
let mime = mime(rel);
|
||||
let frames = if mime.starts_with("text/html") {
|
||||
let granted = plugin.meta.lock().granted.clone();
|
||||
self.web_frames(plugin_id, rel, &granted)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
Ok(WebFile { bytes, mime, frames })
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -55,6 +55,8 @@ pub struct Project {
|
||||
pub(crate) java_launches: crate::ops::java::cache::Sessions,
|
||||
/// Reasons this window was already told why Kotlin is debugged with kotlin-debug-adapter.
|
||||
pub(crate) kotlin_debug_notices: Mutex<HashSet<&'static str>>,
|
||||
/// The completion only some plugins asked to complete again ([`crate::ops::lsp::lsp_completion`]).
|
||||
pub(crate) completion_session: Mutex<Option<crate::ops::lsp::CompletionSession>>,
|
||||
/// Database tool window: data sources and their connections.
|
||||
pub db: Arc<ide_db::DbManager>,
|
||||
/// HTTP Client responses (IDEA's `.idea/httpRequests`), in the app data dir.
|
||||
@@ -662,6 +664,7 @@ impl Host {
|
||||
cache_dir: self.local_data_dir.join("cache").join(&project_key),
|
||||
java_launches: Default::default(),
|
||||
kotlin_debug_notices: Mutex::default(),
|
||||
completion_session: Mutex::default(),
|
||||
db,
|
||||
http_history,
|
||||
agents,
|
||||
@@ -910,6 +913,7 @@ impl Host {
|
||||
cache_dir: self.local_data_dir.join("cache").join(&project_key),
|
||||
java_launches: Default::default(),
|
||||
kotlin_debug_notices: Mutex::default(),
|
||||
completion_session: Mutex::default(),
|
||||
db,
|
||||
http_history,
|
||||
agents,
|
||||
|
||||
@@ -28,7 +28,9 @@ use std::pin::Pin;
|
||||
use std::sync::{Arc, OnceLock};
|
||||
|
||||
/// 3: binary arguments (`IpcBytes`) are base64 strings, not arrays of numbers.
|
||||
pub const PROTOCOL_VERSION: u32 = 3;
|
||||
/// 4: a running tool's output arrives as `AgentEvent::ToolOutput` appends; a client that
|
||||
/// doesn't know the event would show stale output.
|
||||
pub const PROTOCOL_VERSION: u32 = 4;
|
||||
pub const SESSION_REPLACED: &str = "session_replaced";
|
||||
pub const SHUTDOWN_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(90);
|
||||
|
||||
|
||||
@@ -26,13 +26,14 @@ async fn invoke(peer: &Peer, window: &str, cmd: &str, args: Value) -> Result<Val
|
||||
|
||||
const NO_SESSION: i64 = 4242;
|
||||
|
||||
fn calls() -> [(&'static str, Value); 4] {
|
||||
fn calls() -> [(&'static str, Value); 5] {
|
||||
let object = json!({"generation": 1, "id": 7});
|
||||
[
|
||||
("debug_jvm_memory_classes", json!({"session": NO_SESSION})),
|
||||
("debug_jvm_memory_instances", json!({"session": NO_SESSION, "className": "java.lang.String", "limit": 10})),
|
||||
("debug_jvm_memory_fields", json!({"session": NO_SESSION, "object": object})),
|
||||
("debug_jvm_memory_referrers", json!({"session": NO_SESSION, "object": object, "limit": 10})),
|
||||
("debug_jvm_thread_dump", json!({"session": NO_SESSION})),
|
||||
]
|
||||
}
|
||||
|
||||
@@ -80,3 +81,14 @@ async fn class_table_is_refused_in_restricted_mode() {
|
||||
let error = ide_host::ops::debug::debug_jvm_memory_classes(&host, "main", session).await.unwrap_err();
|
||||
assert!(error.message.contains("Restricted Mode"), "{error:?}");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn thread_dumps_are_refused_in_restricted_mode() {
|
||||
let (host, _tmp) = host(false);
|
||||
let session = ide_core::DebugSessionId(NO_SESSION as u32);
|
||||
let error = ide_host::ops::debug::debug_jvm_thread_dump(&host, "main", session).await.unwrap_err();
|
||||
assert!(error.message.contains("Restricted Mode"), "{error:?}");
|
||||
let error =
|
||||
ide_host::ops::thread_dump::run_jvm_thread_dump(&host, "main", ide_core::RunId(1), None).await.unwrap_err();
|
||||
assert!(error.message.contains("Restricted Mode"), "{error:?}");
|
||||
}
|
||||
@@ -209,6 +209,11 @@ fn write_index(
|
||||
path.to_string_lossy().into_owned()
|
||||
}
|
||||
|
||||
/// The download sources setting with `mirror` as the GitHub proxy prefix (Tools › Download sources).
|
||||
fn download_sources(mirror: &str) -> ide_core::settings::ToolDownloadSettings {
|
||||
ide_core::settings::ToolDownloadSettings { github_mirror: mirror.into() }
|
||||
}
|
||||
|
||||
/// Security audit lead 5: an index entry's id and version name the download file,
|
||||
/// so an entry whose id or version would place it outside the downloads folder
|
||||
/// is not offered, and nothing is written for it.
|
||||
@@ -439,6 +444,168 @@ fn serve(body: String) -> String {
|
||||
})
|
||||
}
|
||||
|
||||
/// A loopback HTTP server that logs every request path it is asked for and answers with
|
||||
/// `bytes` (a package file); the base URL to put in front of the GitHub one.
|
||||
fn serve_bytes(bytes: Vec<u8>, paths: Arc<Mutex<Vec<String>>>) -> String {
|
||||
use std::io::{BufRead, BufReader, Write};
|
||||
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let base = format!("http://127.0.0.1:{}", listener.local_addr().unwrap().port());
|
||||
std::thread::spawn(move || {
|
||||
for mut stream in listener.incoming().flatten() {
|
||||
let mut reader = BufReader::new(stream.try_clone().unwrap());
|
||||
let mut line = String::new();
|
||||
if reader.read_line(&mut line).unwrap_or(0) > 0 {
|
||||
paths.lock().push(line.trim().to_owned());
|
||||
}
|
||||
while reader.read_line(&mut line).unwrap_or(0) > 0 && line != "\r\n" {
|
||||
line.clear();
|
||||
}
|
||||
let _ = write!(
|
||||
stream,
|
||||
"HTTP/1.1 200 OK\r\nContent-Type: application/octet-stream\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
|
||||
bytes.len()
|
||||
);
|
||||
let _ = stream.write_all(&bytes);
|
||||
}
|
||||
});
|
||||
base
|
||||
}
|
||||
|
||||
/// A configured mirror is tried before the official host, and its bytes must still pass the
|
||||
/// index's digest and the publisher's signature: a mirror only ever carries the download
|
||||
/// (Tools › Download sources), never the trust root.
|
||||
#[test]
|
||||
fn a_mirror_prefix_carries_plugin_packages_and_only_bytes_that_check() {
|
||||
let f = fixture();
|
||||
let market = f.work.join("market");
|
||||
std::fs::create_dir_all(&market).unwrap();
|
||||
let key = PublisherKey::from_seed([3; 32]);
|
||||
let (package, mut entry) = signed_hello(&market, "1.0.0", &key, &f.host);
|
||||
// The download is a GitHub one, which is the only kind a prefix may carry.
|
||||
entry.download = format!(
|
||||
"https://github.com/acme/openidea-hello/releases/download/v1.0.0/{}",
|
||||
package.file_name().unwrap().to_string_lossy()
|
||||
);
|
||||
let url = write_index(&market, &key, vec![entry.clone()], vec![], false);
|
||||
f.host.set_market_url(Some(url));
|
||||
f.host.refresh_market().unwrap();
|
||||
|
||||
// The mirror answers with the real package.
|
||||
let paths: Arc<Mutex<Vec<String>>> = Arc::default();
|
||||
let base = serve_bytes(std::fs::read(&package).unwrap(), paths.clone());
|
||||
f.host.set_downloads(download_sources(&base));
|
||||
let dir = f.host.download_market_plugin("acme.hello").unwrap();
|
||||
assert_eq!(f.host.preview_install(&dir).unwrap().version, "1.0.0");
|
||||
let asked = paths.lock().clone();
|
||||
assert_eq!(asked.len(), 1, "{asked:?}");
|
||||
assert!(
|
||||
asked[0].contains(entry.download.trim_start_matches("https://")),
|
||||
"the official URL is appended to the prefix unchanged: {asked:?}"
|
||||
);
|
||||
|
||||
// No mirror: the official URL is what is asked for, exactly as before.
|
||||
f.host.set_downloads(download_sources(""));
|
||||
assert_eq!(
|
||||
ide_tools::mirror::candidates(&entry.download, &download_sources("")),
|
||||
vec![ide_tools::mirror::Candidate { url: entry.download.clone(), mirror: None }]
|
||||
);
|
||||
|
||||
// A download that is not on GitHub is not one a prefix may carry: it stays official.
|
||||
let mut local = entry.clone();
|
||||
local.download = package.to_string_lossy().into_owned();
|
||||
assert_eq!(
|
||||
ide_tools::mirror::candidates(&local.download, &download_sources(&base)),
|
||||
vec![ide_tools::mirror::Candidate { url: local.download.clone(), mirror: None }]
|
||||
);
|
||||
}
|
||||
|
||||
/// A mirror serving a tampered package is a source that fails its checks — and the unpacked
|
||||
/// bytes it served must not be left behind where the install page reads from.
|
||||
///
|
||||
/// The index has no hash of the archive itself (only `package_digest` of the unpacked
|
||||
/// contents), so the bytes have to be unpacked before they can be checked; the test therefore
|
||||
/// watches the staging folders, not the archive.
|
||||
#[test]
|
||||
fn a_tampered_package_from_a_mirror_is_refused_and_leaves_nothing_behind() {
|
||||
let f = fixture();
|
||||
let market = f.work.join("market");
|
||||
std::fs::create_dir_all(&market).unwrap();
|
||||
let key = PublisherKey::from_seed([3; 32]);
|
||||
let (package, mut entry) = signed_hello(&market, "1.0.0", &key, &f.host);
|
||||
entry.download = format!(
|
||||
"https://github.com/acme/openidea-hello/releases/download/v1.0.0/{}",
|
||||
package.file_name().unwrap().to_string_lossy()
|
||||
);
|
||||
let url = write_index(&market, &key, vec![entry.clone()], vec![], false);
|
||||
f.host.set_market_url(Some(url));
|
||||
f.host.refresh_market().unwrap();
|
||||
|
||||
// A package whose manifest was changed after signing: its digest disagrees with the index,
|
||||
// and it carries no signature at all.
|
||||
let tampered = {
|
||||
let dir = f.work.join("tampered-src");
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let unpacked = f.host.unpack_package(&package).unwrap();
|
||||
copy_dir(&unpacked, &dir.join("pkg"));
|
||||
let manifest = std::fs::read_to_string(dir.join("pkg/plugin.toml")).unwrap();
|
||||
std::fs::write(dir.join("pkg/plugin.toml"), manifest.replace("Sample plugin", "Totally safe plugin")).unwrap();
|
||||
let files = f.host.package_files_of(&dir.join("pkg")).unwrap();
|
||||
let out = dir.join("tampered.oiplugin");
|
||||
package::pack(&dir.join("pkg"), &files, &out, None).unwrap();
|
||||
out
|
||||
};
|
||||
|
||||
let mirror_paths: Arc<Mutex<Vec<String>>> = Arc::default();
|
||||
let mirror = serve_bytes(std::fs::read(&tampered).unwrap(), mirror_paths.clone());
|
||||
let downloads = f.plugins_dir.join(".downloads");
|
||||
// Browsing the package above went through `unpack_package`, which stages a folder of its
|
||||
// own: clear what that left so the baseline is this attempt's alone.
|
||||
for dir in staging_dirs(&downloads) {
|
||||
let _ = std::fs::remove_dir_all(downloads.join(dir));
|
||||
}
|
||||
let staging_before = staging_dirs(&downloads);
|
||||
assert!(staging_before.is_empty(), "{staging_before:?}");
|
||||
|
||||
// The mirror answers with the tampered package, and it is the only source configured: the
|
||||
// download must fail rather than install what the mirror served.
|
||||
f.host.set_downloads(download_sources(&mirror));
|
||||
let err = f.host.download_market_plugin("acme.hello").unwrap_err();
|
||||
assert!(err.message.contains("could not download"), "{}", err.message);
|
||||
assert!(err.message.contains("does not match the marketplace's entry"), "{}", err.message);
|
||||
assert_eq!(mirror_paths.lock().len(), 1, "the mirror was asked once");
|
||||
|
||||
// Nothing the mirror served stays where the install page reads from, and the staging folder
|
||||
// of the refused attempt is gone.
|
||||
assert_eq!(staging_dirs(&downloads), staging_before, "a refused package left its staging folder");
|
||||
let leftovers: Vec<PathBuf> = std::fs::read_dir(&downloads)
|
||||
.unwrap()
|
||||
.flatten()
|
||||
.map(|e| e.path())
|
||||
.filter(|p| p.to_string_lossy().contains("acme.hello"))
|
||||
.collect();
|
||||
assert!(leftovers.is_empty(), "a refused package left files behind: {leftovers:?}");
|
||||
|
||||
// The official host, serving the real package, still installs.
|
||||
let official_paths: Arc<Mutex<Vec<String>>> = Arc::default();
|
||||
let official = serve_bytes(std::fs::read(&package).unwrap(), official_paths.clone());
|
||||
f.host.set_downloads(download_sources(&official));
|
||||
let dir = f.host.download_market_plugin("acme.hello").unwrap();
|
||||
assert_eq!(f.host.preview_install(&dir).unwrap().version, "1.0.0");
|
||||
assert_eq!(official_paths.lock().len(), 1);
|
||||
}
|
||||
|
||||
/// The staging folders under `<plugins>/.downloads`: one per unpacked package, `<stem>-<pid>`.
|
||||
fn staging_dirs(downloads: &Path) -> Vec<String> {
|
||||
let Ok(entries) = std::fs::read_dir(downloads) else { return Vec::new() };
|
||||
let mut names: Vec<String> = entries
|
||||
.flatten()
|
||||
.filter(|e| e.file_type().map(|t| t.is_dir()).unwrap_or(false))
|
||||
.map(|e| e.file_name().to_string_lossy().into_owned())
|
||||
.collect();
|
||||
names.sort();
|
||||
names
|
||||
}
|
||||
|
||||
/// An index is read up to the size an index may have, whatever its server says or sends:
|
||||
/// the marketplace is read again every day, with nobody asking.
|
||||
#[test]
|
||||
|
||||
@@ -128,7 +128,9 @@ struct Smoke {
|
||||
}
|
||||
|
||||
fn fixture_dir(name: &str) -> PathBuf {
|
||||
Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures").join(name)
|
||||
let manifest_dir =
|
||||
std::env::var_os("CARGO_MANIFEST_DIR").map_or_else(|| PathBuf::from(env!("CARGO_MANIFEST_DIR")), PathBuf::from);
|
||||
manifest_dir.join("../../fixtures").join(name)
|
||||
}
|
||||
|
||||
fn copy_dir(from: &Path, to: &Path) {
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
//! API 1.16 `completion-list-provider`: a plugin marks its completion incomplete, and typing on
|
||||
//! in the same word asks that plugin again while the language server's list is kept.
|
||||
mod common;
|
||||
|
||||
use ide_core::{ChangeSet, Pos, RequestId, TextChange};
|
||||
use ide_host::plugins::{Consent, HostWorkspace, PluginHost, set_editor_providers};
|
||||
use ide_host::{Host, HostConfig, ops};
|
||||
use ide_jsonrpc::{Handler, Peer};
|
||||
use ide_plugin::{Limits, ProviderDocument};
|
||||
use parking_lot::Mutex;
|
||||
use serde_json::{Value, json};
|
||||
use std::{path::Path, sync::Arc, time::Duration};
|
||||
|
||||
fn fixture() -> std::path::PathBuf {
|
||||
Path::new(env!("CARGO_MANIFEST_DIR")).join("../ide-plugin/tests/fixtures/completion-list")
|
||||
}
|
||||
|
||||
fn plugins(base: &Path) -> Arc<PluginHost> {
|
||||
let p = Arc::new(
|
||||
PluginHost::new(
|
||||
base.join("plugins"),
|
||||
Arc::new(|_: Option<&str>, _| {}),
|
||||
Limits { edit_soft: Duration::from_secs(3), edit_hard: Duration::from_secs(5), ..Default::default() },
|
||||
)
|
||||
.unwrap(),
|
||||
);
|
||||
p.install_from_dir(&fixture(), &Consent::all()).unwrap();
|
||||
p
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_export_replaces_providers_completion_and_carries_the_flag() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let p = plugins(tmp.path());
|
||||
let doc = |text: &str| ProviderDocument {
|
||||
path: tmp.path().join("a.txt"),
|
||||
language: "text".into(),
|
||||
version: 1,
|
||||
text: text.into(),
|
||||
};
|
||||
// `completion` ("legacy") is not called once `completion-list-provider` is exported.
|
||||
let items = p.provide_completion(&doc("Book.findByTitleAnd"), Pos::new(0, 19), None);
|
||||
let labels: Vec<_> = items.iter().map(|(_, i)| i.label.as_str()).collect();
|
||||
assert_eq!(labels, ["findByTitleAndTitle", "findByTitleAndAuthor"]);
|
||||
}
|
||||
|
||||
/// A language server for plain text that counts its completion requests.
|
||||
#[derive(Default)]
|
||||
struct Server {
|
||||
completions: Mutex<usize>,
|
||||
}
|
||||
|
||||
impl Handler for Server {
|
||||
fn on_notification(&self, _: &str, _: Value) {}
|
||||
fn on_request(&self, method: &str, _: Value) -> Result<Value, (i64, String)> {
|
||||
Ok(match method {
|
||||
"initialize" => {
|
||||
json!({"capabilities": {"textDocumentSync": {"openClose": true, "change": 1}, "completionProvider": {}}})
|
||||
}
|
||||
"textDocument/completion" => {
|
||||
*self.completions.lock() += 1;
|
||||
json!({"isIncomplete": false, "items": [{"label": "server-item"}]})
|
||||
}
|
||||
_ => Value::Null,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn typing_on_asks_only_the_plugins_that_marked_their_list_incomplete() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap().join("project");
|
||||
std::fs::create_dir(&root).unwrap();
|
||||
let host =
|
||||
Arc::new(Host::new(HostConfig { local_data_dir: tmp.path().join("local"), ..common::host_config(tmp.path()) }));
|
||||
host.open_project("main", &root).unwrap();
|
||||
// Language servers start only in trusted projects.
|
||||
ops::project::project_trust_set(&host, root.clone(), true, false).await.unwrap();
|
||||
let p = plugins(tmp.path());
|
||||
p.set_workspace(Some(Arc::new(HostWorkspace(Arc::downgrade(&host)))));
|
||||
set_editor_providers(Some(&p));
|
||||
|
||||
let listener = tokio::net::TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
let server = Arc::new(Server::default());
|
||||
let peers = Arc::new(Mutex::new(Vec::<Peer>::new()));
|
||||
let (accepted, state) = (peers.clone(), server.clone());
|
||||
tokio::spawn(async move {
|
||||
while let Ok((stream, _)) = listener.accept().await {
|
||||
let (r, w) = stream.into_split();
|
||||
accepted.lock().push(Peer::connect(r, w, state.clone()));
|
||||
}
|
||||
});
|
||||
let cfg: ide_language::LanguageServerConfig =
|
||||
toml::from_str(&format!("name='text-server'\ncommand='no-process-required'\nconnect='127.0.0.1:{port}'"))
|
||||
.unwrap();
|
||||
let project = host.project("main").unwrap();
|
||||
project.lsp.set_servers_hook(Box::new(move |_, _| vec![cfg.clone()]));
|
||||
|
||||
let path = root.join("finders.txt");
|
||||
std::fs::write(&path, "Book.findByTitleAnd").unwrap();
|
||||
let doc = ops::doc::doc_open(&host, "main", path).await.unwrap();
|
||||
let labels = |list: &ide_lsp::types::CompletionList| list.items.iter().map(|i| i.label.clone()).collect::<Vec<_>>();
|
||||
|
||||
let first = ops::lsp::lsp_completion(&host, "main", RequestId(1), doc.id, Pos::new(0, 19), None).await.unwrap();
|
||||
assert!(first.is_incomplete);
|
||||
assert_eq!(labels(&first), ["server-item", "findByTitleAndTitle", "findByTitleAndAuthor"]);
|
||||
assert_eq!(*server.completions.lock(), 1);
|
||||
|
||||
// Typing on in the same word: the plugin answers for the new text, the server isn't asked again.
|
||||
let insert = |from, text: &str| ChangeSet { changes: vec![TextChange { from, to: from, insert: text.into() }] };
|
||||
let version = ops::doc::doc_edit(&host, "main", doc.id, doc.version, insert(19, "A")).await.unwrap();
|
||||
let next = ops::lsp::lsp_completion(&host, "main", RequestId(2), doc.id, Pos::new(0, 20), None).await.unwrap();
|
||||
assert!(next.is_incomplete);
|
||||
assert_eq!(labels(&next), ["server-item", "findByTitleAndATitle", "findByTitleAndAAuthor"]);
|
||||
assert_eq!(*server.completions.lock(), 1);
|
||||
|
||||
// Another word starts another completion: everyone is asked.
|
||||
ops::doc::doc_edit(&host, "main", doc.id, version, insert(20, " x.y")).await.unwrap();
|
||||
let other = ops::lsp::lsp_completion(&host, "main", RequestId(3), doc.id, Pos::new(0, 24), None).await.unwrap();
|
||||
assert_eq!(labels(&other), ["server-item", "yTitle", "yAuthor"]);
|
||||
assert_eq!(*server.completions.lock(), 2);
|
||||
|
||||
set_editor_providers(None);
|
||||
}
|
||||
@@ -124,6 +124,7 @@ impl PluginWorkspace for TestWorkspace {
|
||||
max_matches: limit,
|
||||
context: Default::default(),
|
||||
include_excluded: false,
|
||||
skip_large_files: false,
|
||||
};
|
||||
let files = Mutex::new(Vec::new());
|
||||
let summary = ide_search::search(root, &query, &|_| None, cancel, &|file| files.lock().push(file))
|
||||
@@ -3902,6 +3903,68 @@ path = "templates/new.draw"
|
||||
assert!(f.host.web_page("web-demo", "draw").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn web_pages_embed_only_declared_and_granted_frames() {
|
||||
let f = fixture(Limits::default());
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let pkg = tmp.path().join("frame-demo");
|
||||
for (path, text) in [
|
||||
("hall/index.html", "<iframe src=\"https://play.games.test:8443/room\"></iframe>"),
|
||||
("hall/rules.html", "<p>rules</p>"),
|
||||
("hall/app.js", "console.log(1)"),
|
||||
("panel/index.html", "<p>panel</p>"),
|
||||
] {
|
||||
std::fs::create_dir_all(pkg.join(path).parent().unwrap()).unwrap();
|
||||
std::fs::write(pkg.join(path), text).unwrap();
|
||||
}
|
||||
std::fs::write(
|
||||
pkg.join("plugin.toml"),
|
||||
r#"id = "frame-demo"
|
||||
name = "Frame Demo"
|
||||
version = "1.0.0"
|
||||
engines.openidea = "^1.16"
|
||||
|
||||
[capabilities]
|
||||
optional = ["net:example.com", "net:*.games.test"]
|
||||
|
||||
[[contributes.views]]
|
||||
id = "hall"
|
||||
title = "Hall"
|
||||
web = "hall/index.html"
|
||||
frames = ["https://example.com/", "https://play.games.test:8443", "https://example.com"]
|
||||
|
||||
[[contributes.views]]
|
||||
id = "panel"
|
||||
title = "Panel"
|
||||
web = "panel/index.html"
|
||||
"#,
|
||||
)
|
||||
.unwrap();
|
||||
let info = f.install(&pkg);
|
||||
assert_eq!(info.status, PluginStatus::Static, "{:?}", info.error);
|
||||
assert_eq!(
|
||||
f.host.ui_items("views").iter().find(|v| v.decl["id"] == "hall").unwrap().decl["frames"],
|
||||
serde_json::json!(["https://example.com", "https://play.games.test:8443"])
|
||||
);
|
||||
let page = f.host.web_page("frame-demo", "hall").unwrap();
|
||||
let rev = page.path.strip_prefix("frame-demo/").unwrap().split_once('/').unwrap().0.to_owned();
|
||||
let frames = |path: &str| f.host.web_file("frame-demo", &format!("{rev}/{path}")).unwrap().frames;
|
||||
let both = Some(vec!["https://example.com".to_owned(), "https://play.games.test:8443".to_owned()]);
|
||||
// Every page in the declaring view's directory, not its other files nor another view's pages.
|
||||
assert_eq!(frames("hall/index.html"), both);
|
||||
assert_eq!(frames("hall/rules.html"), both);
|
||||
assert_eq!(frames("hall/app.js"), None);
|
||||
assert_eq!(frames("panel/index.html"), None);
|
||||
|
||||
// Only what the user granted: declining a host takes it out of the policy.
|
||||
f.host.set_capability("frame-demo", "net:example.com", false).unwrap();
|
||||
assert_eq!(frames("hall/index.html"), Some(vec!["https://play.games.test:8443".to_owned()]));
|
||||
f.host.set_capability("frame-demo", "net:*.games.test", false).unwrap();
|
||||
assert_eq!(frames("hall/index.html"), Some(Vec::new()));
|
||||
f.host.set_capability("frame-demo", "net:example.com", true).unwrap();
|
||||
assert_eq!(frames("hall/index.html"), Some(vec!["https://example.com".to_owned()]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn file_icons_without_patterns_require_api_1_8_and_project_assets() {
|
||||
let f = fixture(Limits::default());
|
||||
|
||||
@@ -53,7 +53,9 @@ fn copy_dir(from: &Path, to: &Path) {
|
||||
async fn open(fixture: &str) -> Opened {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap().join(fixture);
|
||||
copy_dir(&Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures").join(fixture), &root);
|
||||
let manifest_dir =
|
||||
std::env::var_os("CARGO_MANIFEST_DIR").map_or_else(|| PathBuf::from(env!("CARGO_MANIFEST_DIR")), PathBuf::from);
|
||||
copy_dir(&manifest_dir.join("../../fixtures").join(fixture), &root);
|
||||
let app = tmp.path().join("app");
|
||||
let host = Arc::new(Host::new(common::host_config(&app)));
|
||||
host.trust.decide(&root, true, false).unwrap();
|
||||
|
||||
@@ -40,6 +40,7 @@ async fn find(host: &Host, paths: Vec<PathBuf>, pattern: &str) -> Vec<ide_search
|
||||
max_matches: 0,
|
||||
context: Default::default(),
|
||||
include_excluded: false,
|
||||
skip_large_files: false,
|
||||
},
|
||||
ide_host::ops::Channel::new(move |event| {
|
||||
if let search::SearchEvent::File { file } = event {
|
||||
@@ -161,6 +162,7 @@ async fn properties_search_git_and_document_coordinates_agree() {
|
||||
max_matches: 0,
|
||||
context: Default::default(),
|
||||
include_excluded: false,
|
||||
skip_large_files: false,
|
||||
};
|
||||
search::replace_in_files(
|
||||
&host,
|
||||
|
||||
@@ -432,6 +432,14 @@ async fn patches_read_and_write_the_requested_repository() {
|
||||
})
|
||||
.collect::<String>();
|
||||
let root = Some(roots[0].clone());
|
||||
// Automatic mappings wait for indexing; the new folders and exclude rule may start a rescan.
|
||||
tokio::time::sleep(Duration::from_millis(200)).await;
|
||||
for _ in 0..500 {
|
||||
if !project.index.status().indexing {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
let preview = vcs::vcs_patch_preview(&host, "main", root.clone(), patch.clone(), None, None).await.unwrap();
|
||||
assert!(preview.files.iter().all(|file| file.applies && !file.missing_base));
|
||||
assert_eq!(preview.automatic_mappings.len(), 1);
|
||||
|
||||
+20
-12
@@ -5,8 +5,10 @@
|
||||
//! { "$shared": { "version": "v1" }, "dev": { "host": "localhost:8080" } }
|
||||
//! ```
|
||||
//!
|
||||
//! Lookup order for `{{name}}`: file variables (`@name = …`), the private
|
||||
//! environment, the public environment, private `$shared`, public `$shared`.
|
||||
//! Lookup order for `{{name}}` with an environment selected: the private
|
||||
//! environment, the public environment, private `$shared`, public `$shared`, then
|
||||
//! file variables (`@name = …`), as in the JetBrains HTTP Client. Without one, file
|
||||
//! variables come before `$shared`.
|
||||
//! Dynamic variables: `$uuid` / `$random.uuid`, `$timestamp`, `$isoTimestamp`,
|
||||
//! `$randomInt` / `$random.integer`.
|
||||
|
||||
@@ -267,17 +269,19 @@ fn iso8601(secs: u64) -> String {
|
||||
pub struct Resolver<'a> {
|
||||
pub file_vars: &'a [(String, String)],
|
||||
pub env: HashMap<String, String>,
|
||||
/// An environment is selected: its values override file variables.
|
||||
pub env_first: bool,
|
||||
}
|
||||
|
||||
impl Resolver<'_> {
|
||||
fn lookup(&self, name: &str, depth: u32, missing: &mut BTreeSet<String>) -> Option<String> {
|
||||
if let Some((_, v)) = self.file_vars.iter().rev().find(|(k, _)| k == name) {
|
||||
return Some(if depth < 8 { self.substitute_inner(v, depth + 1, missing) } else { v.clone() });
|
||||
let file = || self.file_vars.iter().rev().find(|(k, _)| k == name).map(|(_, v)| v);
|
||||
let env = || self.env.get(name);
|
||||
let found = if self.env_first { env().or_else(file) } else { file().or_else(env) };
|
||||
match found {
|
||||
Some(v) => Some(if depth < 8 { self.substitute_inner(v, depth + 1, missing) } else { v.clone() }),
|
||||
None => dynamic(name),
|
||||
}
|
||||
if let Some(v) = self.env.get(name) {
|
||||
return Some(if depth < 8 { self.substitute_inner(v, depth + 1, missing) } else { v.clone() });
|
||||
}
|
||||
dynamic(name)
|
||||
}
|
||||
|
||||
fn substitute_inner(&self, text: &str, depth: u32, missing: &mut BTreeSet<String>) -> String {
|
||||
@@ -346,7 +350,7 @@ mod tests {
|
||||
let envs = Environments::from_json(&json, "").unwrap();
|
||||
let vars = envs.variables(Some("dev"));
|
||||
assert_eq!(vars["value"], token);
|
||||
let resolver = Resolver { file_vars: &[], env: vars };
|
||||
let resolver = Resolver { file_vars: &[], env: vars, env_first: true };
|
||||
let mut missing = BTreeSet::new();
|
||||
assert_eq!(resolver.substitute("{\"value\":{{value}}}", &mut missing), format!(r#"{{"value":{token}}}"#));
|
||||
assert!(missing.is_empty());
|
||||
@@ -449,11 +453,15 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn substitutes_file_env_and_dynamic_variables() {
|
||||
let file_vars = vec![("base".to_owned(), "https://{{host}}".to_owned())];
|
||||
let file_vars =
|
||||
vec![("host".to_owned(), "localhost".to_owned()), ("base".to_owned(), "https://{{host}}".to_owned())];
|
||||
let env = HashMap::from([("host".to_owned(), "example.com".to_owned())]);
|
||||
let r = Resolver { file_vars: &file_vars, env };
|
||||
let r = Resolver { file_vars: &file_vars, env: env.clone(), env_first: true };
|
||||
let mut missing = BTreeSet::new();
|
||||
// The environment's `host` overrides the file's, also inside a file variable.
|
||||
assert_eq!(r.substitute("{{ base }}/a?x={{nope}}", &mut missing), "https://example.com/a?x={{nope}}");
|
||||
let file_first = Resolver { file_vars: &file_vars, env, env_first: false };
|
||||
assert_eq!(file_first.substitute("{{base}}", &mut BTreeSet::new()), "https://localhost");
|
||||
assert_eq!(missing.into_iter().collect::<Vec<_>>(), vec!["nope"]);
|
||||
let mut missing = BTreeSet::new();
|
||||
let id = r.substitute("{{$uuid}}", &mut missing);
|
||||
@@ -465,7 +473,7 @@ mod tests {
|
||||
#[test]
|
||||
fn self_reference_terminates() {
|
||||
let file_vars = vec![("a".to_owned(), "{{a}}".to_owned())];
|
||||
let r = Resolver { file_vars: &file_vars, env: HashMap::new() };
|
||||
let r = Resolver { file_vars: &file_vars, env: HashMap::new(), env_first: true };
|
||||
let mut missing = BTreeSet::new();
|
||||
assert_eq!(r.substitute("{{a}}", &mut missing), "{{a}}");
|
||||
}
|
||||
|
||||
@@ -77,7 +77,7 @@ pub fn prepare(
|
||||
env: Option<&str>,
|
||||
base_dir: Option<&Path>,
|
||||
) -> IdeResult<PreparedRequest> {
|
||||
let resolver = Resolver { file_vars, env: envs.variables(env) };
|
||||
let resolver = Resolver { file_vars, env: envs.variables(env), env_first: env.is_some() };
|
||||
let mut missing = BTreeSet::new();
|
||||
let url = resolver.substitute(&raw.block.url, &mut missing);
|
||||
let headers: Vec<(String, String)> =
|
||||
@@ -290,6 +290,18 @@ mod tests {
|
||||
assert_eq!(p.body.as_deref(), Some("{\"id\": \"{{id}}\"}"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selected_environment_overrides_file_variables() {
|
||||
let f = parse("@host = localhost:8080\n@path = {{host}}/v1\nGET http://{{path}}/x?env={{name}}\n");
|
||||
let envs =
|
||||
Environments::from_json(r#"{"$shared":{"host":"shared","name":"none"},"dev":{"host":"dev.test"}}"#, "")
|
||||
.unwrap();
|
||||
let url = |env| prepare(&f.requests[0], &f.variables, &envs, env, None).unwrap().url;
|
||||
assert_eq!(url(Some("dev")), "http://dev.test/v1/x?env=none");
|
||||
// No environment: the file's value wins over `$shared`.
|
||||
assert_eq!(url(None), "http://localhost:8080/v1/x?env=none");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reports_unresolved_variables() {
|
||||
let f = parse("GET https://{{host}}/x\n");
|
||||
|
||||
Loaded 100 of 714 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user