mirror of
https://github.com/l0ng-ai/openidea.git
synced 2026-11-25 02:44:03 -10:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f53f7c0208 |
No files matched your search
@@ -0,0 +1,83 @@
|
||||
---
|
||||
name: eval
|
||||
description: Run the code-intelligence evals (`pnpm eval`), pick the worst failing scenario, diagnose it from the attached timeline, fix it, prove the fix with before / after numbers measured on this machine without regressing other scenarios, and open one PR. Use for "跑 eval", "优化 Java 代码智能", "eval 失败了", an issue labelled `eval`, or any change to Java navigation / usages / gutter markers that needs numbers.
|
||||
---
|
||||
|
||||
# Eval loop: measure → fix → prove
|
||||
|
||||
`pnpm eval` drives the production workbench in Chromium against a release `openidea-server`
|
||||
with real language servers (Java / jdtls for now) and judges every scenario on what the user
|
||||
sees: time to feedback, to the first result, to the final one, and the results themselves vs
|
||||
`evals/<language>/golden/`. One machine, before and after: numbers from different machines or
|
||||
from the nightly host don't judge a fix.
|
||||
|
||||
## 0. Preconditions
|
||||
|
||||
- `jdtls` on PATH and `JAVA_HOME` pointing at a JDK of the pinned `JAVA` version (projects
|
||||
compile against it, and the JDK scenarios' results are in its sources; jdtls itself runs on
|
||||
a newer installed JDK when it needs one). Pinned versions: `.github/tool-versions.env`. A
|
||||
mismatch prints a warning and the report records both: say so in the PR when it applies.
|
||||
- First run builds `cargo build --release -p ide-host --bin openidea-server` and the perf
|
||||
bundle; later iterations of a frontend-only change can use `--no-build` after a
|
||||
`pnpm exec vite build --mode perf --outDir target/eval/dist`, a backend-only one after the
|
||||
cargo build alone.
|
||||
- Run evals one at a time on this machine, with nothing heavy (builds, other evals) beside them.
|
||||
|
||||
## 1. Baseline on the base commit
|
||||
|
||||
```sh
|
||||
git switch --detach origin/main # or the fix branch's merge base
|
||||
pnpm eval --save-baseline # target/eval/baseline.json, this machine only
|
||||
```
|
||||
|
||||
Read `target/eval/report.json`. Each verdict has `status`, `failures` (`kind`: `error`,
|
||||
`timeout`, `degraded`, `correctness`, `budget`, `golden`), `regressions`, `repro` (the command
|
||||
that reruns it) and, for failures, `diagnostics`: every command sent to the server in the
|
||||
slowest run's window (`cmd`, `start`, `ms`, `ok`, `bytes`, `items`), background tasks, server
|
||||
status changes and the server's log tail.
|
||||
|
||||
## 2. Pick one problem
|
||||
|
||||
Worst first: wrong or missing results and silent degradation, then timeouts, then the
|
||||
feedback budget (100 ms), then the slowest `completeMs`. One problem per PR. Say which
|
||||
scenario and metric, with its value vs budget.
|
||||
|
||||
## 3. Diagnose from the timeline
|
||||
|
||||
- Commands in the window ordered by `start`: what ran, what waited on what, what's serial
|
||||
that could overlap, which request returned many `items`/`bytes`, which failed.
|
||||
- `feedbackMs` far above 16 ms with a fast `firstResultMs`: the UI shows nothing while it
|
||||
waits (a hint or popup that only appears after a delay).
|
||||
- A task still running across the window: background work competing with the request.
|
||||
- For the frontend side rerun with `--trace` and open `target/eval/traces/<id>@<cond>.json`
|
||||
in Chrome's Performance panel.
|
||||
- Name the cause at class level (as in `issue-fix`): it usually affects sibling scenarios.
|
||||
|
||||
## 4. Fix, then rerun that scenario until it passes
|
||||
|
||||
```sh
|
||||
pnpm eval --only <scenario> --condition <warm|cold> # the verdict's `repro`
|
||||
```
|
||||
|
||||
Correctness is enforced, so a faster answer that drops, truncates or serves stale results
|
||||
fails. Don't trade a budget miss for a degraded answer.
|
||||
|
||||
## 5. Full suite, then PR
|
||||
|
||||
```sh
|
||||
pnpm eval # vs the baseline from step 1: no new failures or regressions
|
||||
```
|
||||
|
||||
PR per `issue-fix` §6, plus in **How it was verified** the before / after table from
|
||||
`target/eval/report.md` (both on this machine, commits named) and the tool versions line.
|
||||
|
||||
## Guard rails
|
||||
|
||||
- Goldens (`evals/*/golden/`) and budgets (`evals/budgets.json`) are human-owned. Don't edit
|
||||
them, and don't run `--update-golden`, to make a scenario pass. When a golden looks wrong
|
||||
(a tool bump, a deliberate behaviour change), stop and say so: a PR that touches them gets
|
||||
`needs-decision`.
|
||||
- Don't weaken a scenario's checks or timeouts in `evals/<language>/scenarios.ts` to pass.
|
||||
Adding a scenario (for a case the sweep or a user found) is fine; record its golden with
|
||||
`--update-golden --only <id>` and ask a person to review the file.
|
||||
- A flaky timing (passes on rerun) is not a regression: rerun once before acting on one.
|
||||
@@ -0,0 +1,91 @@
|
||||
---
|
||||
name: issue-fix
|
||||
description: Triage and fix a GitHub issue (or a user-reported bug) end to end — reproduce, find the root cause, generalise it to every sibling case, fix the class rather than the instance, verify, and open one PR. Use when given an issue URL/number or asked to fix a reported bug and open a PR ("看看这个 issue", "修一下这个 bug", "提 pr").
|
||||
---
|
||||
|
||||
# Fix an issue: from one case to the whole class
|
||||
|
||||
The reported case is one sample of a defect class. A fix that only makes the
|
||||
screenshot go away is not done: the next question is always "does this break for other
|
||||
languages / platforms / entry points too?". Answer that before anyone asks.
|
||||
|
||||
## 1. Read and reproduce
|
||||
|
||||
- `gh issue view <n> --comments` (repo `l0ng-ai/openidea`). Read attached logs/screenshots
|
||||
closely: OS, language, toolchain versions, exact error text.
|
||||
- Locate the code path and confirm the claim in code, with `file:line` evidence.
|
||||
Say plainly whether it is a real bug, a missing feature, or user environment.
|
||||
- Reproduce locally when possible (`fixtures/` projects, `/verify` for runtime). If the
|
||||
reporter's platform (often Windows/Linux) can't be reproduced here, say so up front.
|
||||
- Do not ask for a generic environment/log checklist before trying the flow and inspecting the code.
|
||||
Record the attempt and result; ask only for a fact that actually blocks the next diagnostic step.
|
||||
Missing fields, limited time, or unavailable automation are not by themselves reasons to ask the reporter.
|
||||
- Treat a maintainer-confirmed bug as an investigation task even if local reproduction fails. Distinguish
|
||||
“not reproduced here” from “not a bug”, and do not require the reporter to prove its existence again.
|
||||
|
||||
## 2. Name the root cause as a class
|
||||
|
||||
Write one sentence of the form "<mechanism> is missing/wrong, so any <X> hits it",
|
||||
not "<this button> is broken". Typical classes in this codebase:
|
||||
|
||||
- Per-language config handled for one language only (`languages/*.toml`, `ide-sdk`).
|
||||
- Platform gaps: paths, executables, shells, `.cmd`/`.exe`, separators — macOS-only code.
|
||||
- Toolchain/version discovery: one probe location, no version check, no rescan.
|
||||
- Two features each implementing half a flow and never joined (feature isolation →
|
||||
should go through an action/service).
|
||||
- State not reset on project switch / window reuse; events not scoped per window.
|
||||
- Failure surfaced as raw stderr/stack trace or retried until "crashed" instead of a
|
||||
clear status with an action.
|
||||
- UI: same primitive styled differently in N places.
|
||||
|
||||
## 3. Sweep for siblings
|
||||
|
||||
Search systematically, not by memory:
|
||||
|
||||
- Same pattern elsewhere: `git grep` the function, the config key, the error string,
|
||||
the hard-coded path/flag. Check every `languages/*.toml` entry and every platform branch.
|
||||
- Same flow for other languages/runtimes (Java ↔ Kotlin/Gradle, Python ↔ venv/uv,
|
||||
Node ↔ Deno/Bun, Go, Rust …): would they fail the same way?
|
||||
- Other callers/entry points of the same flow (menu, context menu, gutter, shortcut, CLI arg).
|
||||
- Neighbouring failure modes of the same mechanism (not installed / wrong version /
|
||||
installed but crashes / slow start / installed mid-session).
|
||||
For broad sweeps spawn one Explore agent with the class description, not the instance.
|
||||
|
||||
## 4. Decide the fix at the right altitude
|
||||
|
||||
- Fix the mechanism once (shared helper, action, config hook) so siblings are fixed
|
||||
by construction; don't patch each call site.
|
||||
- Respect `AGENTS.md` rules (crate boundaries, no cross-feature imports, `IdeResult`,
|
||||
UTF-16). If the right fix breaks a rule, pick the rule-respecting design and say why.
|
||||
- Compare with how established IDEs solve it when relevant; prefer the established answer.
|
||||
- Present: root cause, sibling table, proposed fix, what's deferred. When the user leaves
|
||||
the choice to you, go ahead without asking again.
|
||||
|
||||
## 5. Implement and test the class
|
||||
|
||||
- Tests cover the class: table-driven over languages/platforms/states, not just the
|
||||
reported input. Include the reporter's case verbatim.
|
||||
- Run the scoped checks (`pnpm vitest run <path>`, `cargo nextest run -p <crate>`), then
|
||||
`/verify` in the app for UI or runtime behaviour.
|
||||
|
||||
## 6. PR
|
||||
|
||||
- One branch `fix/<slug>`, one PR unless the user asks otherwise; `Fixes #<n>` in the body.
|
||||
- Don't stage untracked IDE-state dirs (`.ideal/`, `.openidea/`) or screenshots.
|
||||
- PR body follows `.github/pull_request_template.md`: `Closes #<n>`, then
|
||||
**What and why** (user-visible change + root cause at class level, 2–4 sentences),
|
||||
**How it was verified** (commands run and results, siblings fixed/deferred, what could break and how
|
||||
it was checked, what was not verified, e.g. "Windows not tested"; for UI changes the before/after
|
||||
screenshot paths from `/verify`), **Review focus** (optional). Short and plain.
|
||||
|
||||
## Report format
|
||||
|
||||
Reply in the user's language:
|
||||
|
||||
```
|
||||
Root cause: <one sentence, class level>
|
||||
Sibling sweep:
|
||||
| Location / case | Affected? | Action |
|
||||
Fixed / not covered (why) / not verified (platform)
|
||||
PR: <url>
|
||||
```
|
||||
@@ -0,0 +1,57 @@
|
||||
---
|
||||
name: verify
|
||||
description: Build, launch and drive the OpenIDEA desktop app through the Tauri MCP bridge to verify a change at runtime.
|
||||
---
|
||||
|
||||
# Verify OpenIDEA in the running app
|
||||
|
||||
## Launch
|
||||
|
||||
- Run the app from the worktree that holds the change: `pnpm tauri dev` in the background, logging
|
||||
into your task's scratch subdirectory. Use `pnpm dev:app` instead when your checks call
|
||||
`window.__TAURI__` from `execute_js`. The wrapper gives each worktree its own app identity, data,
|
||||
settings and Vite port, so other worktrees and the installed app don't interfere. If it reports a
|
||||
session already running for this worktree, reuse that one.
|
||||
- Once the app is up, `pnpm dev:status` lists this worktree's MCP bridges. Pass the reported
|
||||
`appIdentifier` (the port) on every `mcp__tauri__*` call. The MCP server is shared between
|
||||
sessions: never `driver_session stop` without an `appIdentifier`, and re-check `document.title` /
|
||||
`location.href` before acting if anything looks off.
|
||||
- Make sure the binary contains the change: a session already running for this worktree may be an
|
||||
older build. Restart it after Rust changes; frontend changes reload through Vite.
|
||||
- After the app restarts, `driver_session start` again for your port (a stale session says "Already connected").
|
||||
- If the `pnpm tauri dev` process exits while the app window stays open, Vite is gone and any webview
|
||||
reload shows an empty `#root`. Stop that app and start the session again.
|
||||
- Stop everything you started when done and nothing else; never use process-name kills.
|
||||
|
||||
## Driving
|
||||
|
||||
- `manage_window focus` before screenshots / timing-sensitive steps: a background window throttles timers
|
||||
(debounced LSP / VCS refreshes stall, `setTimeout` promises in `execute_js` time out) and native
|
||||
screenshots come back black.
|
||||
- Settings is a separate native window `settings-main`; pass `windowId`, focus it before screenshotting.
|
||||
- CodeMirror / xterm ignore MCP `type`. Focus the element, then `document.execCommand('insertText', false, text)`.
|
||||
For xterm Enter, dispatch a `keydown` (`key: 'Enter', keyCode: 13`) on `.xterm-helper-textarea`.
|
||||
- MCP clicks arrive with `event.detail === 0`; CodeMirror treats them as line-select clicks. Set the caret
|
||||
through the view instead: `document.querySelector('.cm-content').cmTile.view`.
|
||||
- MCP `text` strategy can resolve to a hidden node; prefer coordinates (CSS px = image px × 0.9) or CSS selectors.
|
||||
- CSS-module edits often trigger a full page reload in dev: dialogs close, Run sessions and terminal
|
||||
scrollback reset, and each reload spawns a fresh shell. Re-open what you were testing.
|
||||
|
||||
## Evidence
|
||||
|
||||
- For UI or interaction changes, capture `before.png` (on `main` or with the fix reverted) and
|
||||
`after.png` at the same state and window size, into your task's scratch subdirectory. Multi-step
|
||||
flows: a numbered series (`after-1.png`, `after-2.png`, ...).
|
||||
- Report the absolute paths; they go into the PR's **How it was verified** section and the triage
|
||||
acceptance entry. Never commit screenshots to the feature branch.
|
||||
|
||||
## Fixture
|
||||
|
||||
`fixtures/` has sample projects (go-app, rust-app, ts-app, kotlin-gradle, polyglot). Copy one into
|
||||
your scratch directory before editing it, and don't commit the IDE state it creates (`.openidea/`).
|
||||
|
||||
## Flows worth driving
|
||||
|
||||
⌘⇧O Goto File · ⌘⇧F Find in Files (preview scroll + highlight) · ⌘⇧A Find Action · editor edit/undo/autosave ·
|
||||
Terminal (Unicode, venv) · Commit view at the default narrow width · Problems · Run → Stop · Project view
|
||||
New / Delete (nested `a/b.txt` names) · ⌘, Settings search (+ Keymap filter) · Git Log on a repo without commits.
|
||||
Symlink
+1
@@ -0,0 +1 @@
|
||||
../../.agents/skills/eval
|
||||
Symlink
+1
@@ -0,0 +1 @@
|
||||
../../.agents/skills/issue-fix
|
||||
Symlink
+1
@@ -0,0 +1 @@
|
||||
../../.agents/skills/verify
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 160 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 169 KiB |
@@ -1,41 +0,0 @@
|
||||
name: Cancel runs of closed PRs
|
||||
on:
|
||||
# pull_request_target so it also runs for PRs from forks. It never checks out or
|
||||
# runs PR code: it only lists and cancels workflow runs of the closed PR's branch.
|
||||
pull_request_target:
|
||||
types: [closed]
|
||||
|
||||
permissions:
|
||||
actions: write
|
||||
|
||||
jobs:
|
||||
cancel:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/github-script@v8
|
||||
with:
|
||||
script: |
|
||||
// A merged or closed PR's remaining CI only holds runners other PRs wait for.
|
||||
const pr = context.payload.pull_request;
|
||||
const { owner, repo } = context.repo;
|
||||
const headRepo = pr.head.repo?.full_name;
|
||||
// The API's status filter lags behind new runs: list the branch and check each one.
|
||||
const runs = await github.paginate(github.rest.actions.listWorkflowRunsForRepo, {
|
||||
owner,
|
||||
repo,
|
||||
branch: pr.head.ref,
|
||||
per_page: 100,
|
||||
});
|
||||
let cancelled = 0;
|
||||
for (const run of runs) {
|
||||
if (run.id === context.runId || run.status === 'completed') continue;
|
||||
if (run.head_repository?.full_name !== headRepo) continue;
|
||||
if (!['pull_request', 'pull_request_target'].includes(run.event)) continue;
|
||||
try {
|
||||
await github.rest.actions.cancelWorkflowRun({ owner, repo, run_id: run.id });
|
||||
cancelled++;
|
||||
} catch (e) {
|
||||
core.warning(`run ${run.id}: ${e.message}`);
|
||||
}
|
||||
}
|
||||
core.info(`Cancelled ${cancelled} run(s) of #${pr.number}`);
|
||||
+45
-179
@@ -5,7 +5,6 @@ on:
|
||||
pull_request:
|
||||
branches: [main]
|
||||
types: [opened, synchronize, reopened]
|
||||
merge_group:
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
@@ -13,9 +12,8 @@ permissions:
|
||||
|
||||
concurrency:
|
||||
group: ci-${{ github.ref }}
|
||||
# A newer push supersedes a pull request's run in progress. Runs on main and in the merge
|
||||
# queue finish, so a broken main shows up and the queue's required checks report.
|
||||
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
|
||||
# A newer push supersedes the run in progress, on main too.
|
||||
cancel-in-progress: true
|
||||
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
@@ -25,23 +23,16 @@ env:
|
||||
|
||||
jobs:
|
||||
# Which parts a pull request touches, so jobs it can't affect skip and leave the
|
||||
# shared runners to others. Pushes, the merge queue and manual runs always run everything.
|
||||
# shared runners to others. Pushes and manual runs always run everything.
|
||||
changes:
|
||||
name: Changes
|
||||
# Self-hosted runners (scripts/selfhost-runner) only for trusted events, and only while the
|
||||
# SELFHOSTED_RUNNERS repository variable is 'true': runs-on cannot fall back when none is online.
|
||||
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
permissions:
|
||||
pull-requests: read
|
||||
outputs:
|
||||
rust: ${{ steps.classify.outputs.rust }}
|
||||
server: ${{ steps.classify.outputs.server }}
|
||||
plugins: ${{ steps.classify.outputs.plugins }}
|
||||
deny: ${{ steps.classify.outputs.deny }}
|
||||
frontend: ${{ steps.classify.outputs.frontend }}
|
||||
e2e: ${{ steps.classify.outputs.e2e }}
|
||||
catalog: ${{ steps.classify.outputs.catalog }}
|
||||
steps:
|
||||
- id: classify
|
||||
env:
|
||||
@@ -49,105 +40,55 @@ jobs:
|
||||
PR: ${{ github.event.pull_request.number }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
jobs="rust server plugins deny frontend e2e catalog"
|
||||
if [ "$GITHUB_EVENT_NAME" != pull_request ]; then
|
||||
for job in $jobs; do echo "$job=true" >> "$GITHUB_OUTPUT"; done
|
||||
echo "rust=true" >> "$GITHUB_OUTPUT"
|
||||
echo "frontend=true" >> "$GITHUB_OUTPUT"
|
||||
exit 0
|
||||
fi
|
||||
gh api --paginate "repos/$GITHUB_REPOSITORY/pulls/$PR/files" \
|
||||
--jq '.[] | .filename, (.previous_filename // empty)' > files.txt
|
||||
cat files.txt
|
||||
# A change to CI itself runs everything.
|
||||
ci='^\.github/(workflows/ci\.yml|actions/)'
|
||||
docs='^(docs/|\.agents/|\.claude/|\.idea/|\.github/ISSUE_TEMPLATE/|\.github/pull_request_template\.md$|[^/]+\.md$|LICENSE$|NOTICE$)'
|
||||
# Frontend-only paths. The Rust code embeds a few files under src/; those stay out.
|
||||
web='^(src/|e2e/|perf/|public/|scripts/|smoke/|evals/|index\.html$|vite\.config\.ts$|tsconfig[^/]*\.json$|knip\.ts$|playwright\.config\.ts$|\.oxlintrc\.json$|\.oxfmtrc\.json$)'
|
||||
web='^(src/|e2e/|perf/|public/|scripts/|smoke/|index\.html$|vite\.config\.ts$|tsconfig[^/]*\.json$|knip\.ts$|playwright\.config\.ts$|\.oxlintrc\.json$|\.oxfmtrc\.json$)'
|
||||
embedded='^src/(bindings\.ts|styles/tokens\.css|features/plugins/views/frame-bridge\.js|platform/keymaps/)'
|
||||
# Plugin web pages are their own pnpm projects, checked by the Plugins job only.
|
||||
plugin_web='^plugins/official/[^/]+/web-src/'
|
||||
# Paths the frontend checks never read...
|
||||
backend='^(crates/|src-tauri/|sdk/|wit/|java/|fixtures/|Cargo\.(toml|lock)$|deny\.toml$|rustfmt\.toml$|rust-toolchain(\.toml)?$|\.cargo/)'
|
||||
# ...except these, which frontend tests and e2e fixtures load (the crate manifests:
|
||||
# scripts/smoke-paths.test.ts, through cargo metadata).
|
||||
read_by_web='^(fixtures/(folding|django-app)/|(crates/[^/]+/)?Cargo\.toml$|crates/ide-plugin/tests/fixtures/|crates/ide-db/(src|tests/fixtures)/snowflake/|src-tauri/(icons|capabilities)/|src-tauri/tauri\.conf\.json$)'
|
||||
# What the browser app and its e2e tests are built from.
|
||||
app='^(src/|e2e/|public/|index\.html$|vite\.config\.ts$|tsconfig\.json$|playwright\.config\.ts$|package\.json$|pnpm-(lock|workspace)\.yaml$|crates/ide-plugin/tests/fixtures/|src-tauri/(icons|capabilities)/|src-tauri/tauri\.conf\.json$)'
|
||||
# The plugin workspaces: the SDK, the plugins, their interface and the host's fixture plugins.
|
||||
plugin_ws='^(sdk/|plugins/|wit/|crates/ide-plugin/tests/fixtures/|rust-toolchain(\.toml)?$)'
|
||||
# Never compiled into the openidea-server binary.
|
||||
not_server='^(src-tauri/|sdk/|fixtures/|crates/[^/]+/(tests|benches)/)'
|
||||
deps='(^|/)Cargo\.(toml|lock)$|^deny\.toml$'
|
||||
# The text catalog test reads the string literals of every Rust source.
|
||||
rust_source='^(crates|src-tauri/src)/.*\.rs$'
|
||||
|
||||
any() { grep -Eq "$1" files.txt; }
|
||||
outside() { [ -n "$(grep -Ev "$1" files.txt || true)" ]; }
|
||||
set_job() { echo "$1=$2" | tee -a "$GITHUB_OUTPUT"; }
|
||||
|
||||
if any "$ci"; then
|
||||
for job in $jobs; do set_job "$job" true; done
|
||||
exit 0
|
||||
fi
|
||||
on() { if "${@:2}"; then set_job "$1" true; else set_job "$1" false; fi; }
|
||||
rust_build() { outside "$1" || any "$embedded"; }
|
||||
web_checks() { outside "$docs|$plugin_web|$backend" || any "$read_by_web"; }
|
||||
catalog_only() { ! web_checks && any "$rust_source"; }
|
||||
on rust rust_build "$docs|$web|$plugin_web"
|
||||
on server rust_build "$docs|$web|$plugin_web|$not_server"
|
||||
on plugins any "$plugin_ws"
|
||||
on deny any "$deps"
|
||||
on frontend web_checks
|
||||
on e2e any "$app"
|
||||
on catalog catalog_only
|
||||
# A job runs when any changed file falls outside the paths that can't affect it.
|
||||
rust=false
|
||||
if grep -Ev "$docs|$web" files.txt | grep -q . || grep -Eq "$embedded" files.txt; then rust=true; fi
|
||||
frontend=false
|
||||
if grep -Ev "$docs" files.txt | grep -q .; then frontend=true; fi
|
||||
echo "rust=$rust frontend=$frontend"
|
||||
echo "rust=$rust" >> "$GITHUB_OUTPUT"
|
||||
echo "frontend=$frontend" >> "$GITHUB_OUTPUT"
|
||||
|
||||
rust:
|
||||
name: Rust (${{ matrix.os }})
|
||||
needs: changes
|
||||
if: needs.changes.outputs.rust == 'true'
|
||||
permissions:
|
||||
contents: read
|
||||
timeout-minutes: 60
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
os: [macos-latest, ubuntu-latest, windows-latest]
|
||||
# Self-hosted runners (scripts/selfhost-runner) only for trusted events, and only while the
|
||||
# SELFHOSTED_RUNNERS repository variable is 'true': runs-on cannot fall back when none is online.
|
||||
runs-on: ${{ matrix.os == 'ubuntu-latest' && vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || matrix.os }}
|
||||
os: [macos-latest, ubuntu-22.04, windows-latest]
|
||||
runs-on: ${{ matrix.os }}
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: pnpm/action-setup@v5
|
||||
with: { version: 11 }
|
||||
- uses: actions/setup-node@v5
|
||||
with:
|
||||
node-version: 22
|
||||
cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }}
|
||||
package-manager-cache: ${{ runner.environment != 'self-hosted' }}
|
||||
with: { node-version: 22, cache: pnpm }
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
with: { components: "clippy, rustfmt" }
|
||||
# Self-hosted runners keep persistent local Cargo caches; GitHub-hosted runners use Actions cache
|
||||
# (only main saves it because saving takes minutes on Windows; PRs restore main's).
|
||||
# Only main saves the cache (saving takes minutes on Windows); PRs restore main's.
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
if: runner.environment != 'self-hosted'
|
||||
with:
|
||||
save-if: ${{ github.ref == 'refs/heads/main' }}
|
||||
# The persistent target dir makes incremental builds pay off; cap its size so it can't fill the disk.
|
||||
- name: Persistent Cargo target dir
|
||||
if: runner.environment == 'self-hosted'
|
||||
shell: bash
|
||||
run: |
|
||||
echo "CARGO_INCREMENTAL=1" >> "$GITHUB_ENV"
|
||||
size=$(du -sm "$CARGO_TARGET_DIR" 2>/dev/null | cut -f1 || true)
|
||||
if [ "${size:-0}" -gt 40000 ]; then
|
||||
echo "$CARGO_TARGET_DIR is ${size} MB; clearing it"
|
||||
rm -rf "$CARGO_TARGET_DIR"
|
||||
fi
|
||||
- uses: taiki-e/install-action@nextest
|
||||
- name: Linux deps
|
||||
if: runner.os == 'Linux'
|
||||
run: |
|
||||
pkgs=(libwebkit2gtk-4.1-dev libayatana-appindicator3-dev librsvg2-dev libxdo-dev libssl-dev patchelf)
|
||||
dpkg -s "${pkgs[@]}" >/dev/null 2>&1 || { sudo apt-get update && sudo apt-get install -y "${pkgs[@]}"; }
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y libwebkit2gtk-4.1-dev libayatana-appindicator3-dev librsvg2-dev libxdo-dev libssl-dev patchelf
|
||||
# tauri-build checks that frontendDist exists.
|
||||
- run: pnpm install --frozen-lockfile && mkdir -p dist
|
||||
shell: bash
|
||||
@@ -157,98 +98,48 @@ jobs:
|
||||
# Test fixtures write LF files; keep Git from converting them on checkout.
|
||||
- run: git config --global core.autocrlf false
|
||||
- run: cargo nextest run --workspace --no-fail-fast
|
||||
- name: Remote backend with Docker Compose
|
||||
# Self-hosted runner containers do not mount /var/run/docker.sock (scripts/selfhost-runner/README.md).
|
||||
if: runner.os == 'Linux' && runner.environment != 'self-hosted'
|
||||
run: |
|
||||
docker pull busybox:latest
|
||||
cargo nextest run -p ide-host --test remote_daemon --run-ignored only \
|
||||
-E 'test(=compose_service_survives_disconnect_and_is_removed_on_stop)'
|
||||
# nextest skips doctests; ide-command's are its compile-fail tests.
|
||||
- if: runner.os == 'Linux'
|
||||
run: cargo test --doc -p ide-command
|
||||
# nextest ran export_bindings, which rewrites src/bindings.ts and the command snapshot.
|
||||
- name: Bindings and command snapshot are up to date
|
||||
if: runner.os == 'Linux'
|
||||
run: git diff --exit-code src/bindings.ts src-tauri/tests/commands.snap
|
||||
|
||||
# One check that always reports, for the ruleset to require: a skipped matrix job reports
|
||||
# under its unexpanded name, so the per-OS checks never appear on frontend-only PRs.
|
||||
rust-checks:
|
||||
name: Rust checks
|
||||
needs: [changes, rust]
|
||||
if: always()
|
||||
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
|
||||
timeout-minutes: 5
|
||||
steps:
|
||||
- env:
|
||||
CHANGES: ${{ needs.changes.result }}
|
||||
RUST: ${{ needs.rust.result }}
|
||||
run: |
|
||||
echo "changes: $CHANGES, rust: $RUST"
|
||||
[ "$CHANGES" = success ] && { [ "$RUST" = success ] || [ "$RUST" = skipped ]; }
|
||||
|
||||
# The remote development server ships as a static Linux binary (release-build.yml):
|
||||
# keep that build working.
|
||||
server:
|
||||
name: Remote server (linux musl)
|
||||
needs: changes
|
||||
if: needs.changes.outputs.server == 'true'
|
||||
if: needs.changes.outputs.rust == 'true'
|
||||
timeout-minutes: 40
|
||||
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
|
||||
runs-on: ubuntu-22.04
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
with: { targets: x86_64-unknown-linux-musl }
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
if: runner.environment != 'self-hosted'
|
||||
with: { key: server-musl }
|
||||
- name: Persistent Cargo target dir
|
||||
if: runner.environment == 'self-hosted'
|
||||
shell: bash
|
||||
run: |
|
||||
echo "CARGO_INCREMENTAL=1" >> "$GITHUB_ENV"
|
||||
size=$(du -sm "$CARGO_TARGET_DIR" 2>/dev/null | cut -f1 || true)
|
||||
if [ "${size:-0}" -gt 40000 ]; then
|
||||
echo "$CARGO_TARGET_DIR is ${size} MB; clearing it"
|
||||
rm -rf "$CARGO_TARGET_DIR"
|
||||
fi
|
||||
- run: dpkg -s musl-tools >/dev/null 2>&1 || { sudo apt-get update && sudo apt-get install -y musl-tools; }
|
||||
- run: sudo apt-get update && sudo apt-get install -y musl-tools
|
||||
- run: cargo build --locked -p ide-host --bin openidea-server --target x86_64-unknown-linux-musl
|
||||
- run: '"${CARGO_TARGET_DIR:-target}/x86_64-unknown-linux-musl/debug/openidea-server" --version'
|
||||
- run: target/x86_64-unknown-linux-musl/debug/openidea-server --version
|
||||
|
||||
# The plugin SDK, the official plugins and the test fixtures build in their
|
||||
# own workspaces (the root excludes them), so the jobs above don't see them.
|
||||
plugins:
|
||||
name: Plugins (SDK, official, fixtures)
|
||||
needs: changes
|
||||
if: needs.changes.outputs.plugins == 'true'
|
||||
if: needs.changes.outputs.rust == 'true'
|
||||
timeout-minutes: 30
|
||||
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
|
||||
runs-on: ubuntu-22.04
|
||||
env:
|
||||
CARGO_TARGET_DIR: ${{ github.workspace }}/target-plugins
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
with: { targets: wasm32-wasip2, components: "clippy, rustfmt" }
|
||||
- if: runner.environment != 'self-hosted'
|
||||
shell: bash
|
||||
run: echo "CARGO_TARGET_DIR=$GITHUB_WORKSPACE/target-plugins" >> "$GITHUB_ENV"
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
if: runner.environment != 'self-hosted'
|
||||
with:
|
||||
key: plugins
|
||||
cache-directories: target-plugins
|
||||
save-if: ${{ github.ref == 'refs/heads/main' }}
|
||||
- name: Persistent Cargo target dir
|
||||
if: runner.environment == 'self-hosted'
|
||||
shell: bash
|
||||
run: |
|
||||
echo "CARGO_INCREMENTAL=1" >> "$GITHUB_ENV"
|
||||
size=$(du -sm "$CARGO_TARGET_DIR" 2>/dev/null | cut -f1 || true)
|
||||
if [ "${size:-0}" -gt 40000 ]; then
|
||||
echo "$CARGO_TARGET_DIR is ${size} MB; clearing it"
|
||||
rm -rf "$CARGO_TARGET_DIR"
|
||||
fi
|
||||
echo "CARGO_TARGET_DIR=$CARGO_TARGET_DIR/plugins" >> "$GITHUB_ENV"
|
||||
- name: Format, lint (host and wasm) and test each crate
|
||||
shell: bash
|
||||
run: |
|
||||
@@ -265,7 +156,7 @@ jobs:
|
||||
- uses: pnpm/action-setup@v5
|
||||
with: { version: 11 }
|
||||
- uses: actions/setup-node@v5
|
||||
with: { node-version: 22, package-manager-cache: false }
|
||||
with: { node-version: 22 }
|
||||
# Plugin web pages (`web-src/`, their own pnpm projects): typecheck and test.
|
||||
- name: Web pages typecheck and test
|
||||
shell: bash
|
||||
@@ -287,9 +178,9 @@ jobs:
|
||||
deny:
|
||||
name: Cargo deny
|
||||
needs: changes
|
||||
if: needs.changes.outputs.deny == 'true'
|
||||
if: needs.changes.outputs.rust == 'true'
|
||||
timeout-minutes: 15
|
||||
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
@@ -301,19 +192,13 @@ jobs:
|
||||
needs: changes
|
||||
if: needs.changes.outputs.frontend == 'true'
|
||||
timeout-minutes: 30
|
||||
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
|
||||
runs-on: ubuntu-22.04
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
# scripts/smoke-paths.test.ts runs `cargo metadata`, which is not preinstalled in the runner container.
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
if: runner.environment == 'self-hosted'
|
||||
- uses: pnpm/action-setup@v5
|
||||
with: { version: 11 }
|
||||
- uses: actions/setup-node@v5
|
||||
with:
|
||||
node-version: 22
|
||||
cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }}
|
||||
package-manager-cache: ${{ runner.environment != 'self-hosted' }}
|
||||
with: { node-version: 22, cache: pnpm }
|
||||
- run: pnpm install --frozen-lockfile
|
||||
- run: pnpm typecheck
|
||||
- run: pnpm lint
|
||||
@@ -322,47 +207,28 @@ jobs:
|
||||
- run: pnpm test
|
||||
- run: pnpm build
|
||||
|
||||
# A backend-only change can still drop a string the text catalog uses: run that one test.
|
||||
catalog:
|
||||
name: Text catalog
|
||||
needs: changes
|
||||
if: needs.changes.outputs.catalog == 'true'
|
||||
timeout-minutes: 15
|
||||
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: pnpm/action-setup@v5
|
||||
with: { version: 11 }
|
||||
- uses: actions/setup-node@v5
|
||||
with:
|
||||
node-version: 22
|
||||
cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }}
|
||||
package-manager-cache: ${{ runner.environment != 'self-hosted' }}
|
||||
- run: pnpm install --frozen-lockfile
|
||||
- run: pnpm vitest run src/platform/locales/textCatalog.test.ts
|
||||
|
||||
e2e:
|
||||
name: E2E (${{ matrix.shard }}/4)
|
||||
name: E2E (${{ matrix.shard }}/2)
|
||||
needs: changes
|
||||
if: needs.changes.outputs.e2e == 'true'
|
||||
timeout-minutes: 45
|
||||
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
|
||||
if: needs.changes.outputs.frontend == 'true'
|
||||
timeout-minutes: 30
|
||||
runs-on: ubuntu-24.04
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
shard: [1, 2, 3, 4]
|
||||
shard: [1, 2]
|
||||
# Browsers and their system libraries are preinstalled; keep the tag in step with @playwright/test.
|
||||
container: mcr.microsoft.com/playwright:v1.64.1-noble
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: pnpm/action-setup@v5
|
||||
with: { version: 11 }
|
||||
- uses: actions/setup-node@v5
|
||||
with:
|
||||
node-version: 22
|
||||
cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }}
|
||||
package-manager-cache: ${{ runner.environment != 'self-hosted' }}
|
||||
with: { node-version: 22, cache: pnpm }
|
||||
- run: pnpm install --frozen-lockfile
|
||||
- run: pnpm exec playwright install --with-deps chromium
|
||||
- run: pnpm e2e --shard=${{ matrix.shard }}/4
|
||||
- run: pnpm e2e --shard=${{ matrix.shard }}/2
|
||||
env:
|
||||
HOME: /root
|
||||
- uses: actions/upload-artifact@v6
|
||||
if: failure()
|
||||
with:
|
||||
|
||||
@@ -8,9 +8,6 @@ name: Language smoke
|
||||
# (Run, Run tests, the test tree, Rerun Failed Tests): smoke/run.test.ts; and debugging its
|
||||
# entry point with the debugger the IDE installs (breakpoint, frames, variables, evaluate,
|
||||
# Step Over, Resume): smoke/debug.test.ts.
|
||||
# The paths below and the Changes step's patterns must cover every file the smoke loads and
|
||||
# every crate it runs: scripts/smoke-paths.test.ts checks them (`node scripts/smoke-paths.ts
|
||||
# [file…]` lists what they miss, or the languages a change runs).
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
@@ -18,37 +15,14 @@ on:
|
||||
- "crates/**"
|
||||
- "languages/**"
|
||||
- "fixtures/**"
|
||||
- "java/**"
|
||||
- "Cargo.toml"
|
||||
- "Cargo.lock"
|
||||
- "src/features/run/**"
|
||||
- "src/features/debugger/**"
|
||||
- "src/features/build-tools/**"
|
||||
- "src/platform/**"
|
||||
- "src/workbench/**"
|
||||
- "src/ui/**"
|
||||
- "src/editor/api.ts"
|
||||
- "src/editor/navigationProviders.ts"
|
||||
- "src/editor/relatedProviders.ts"
|
||||
- "src/editor/core/cm/cornerInset.ts"
|
||||
- "src/editor/core/cm/iconArea.ts"
|
||||
- "src/editor/lsp/availability.ts"
|
||||
- "src/editor/lsp/diagnostics.ts"
|
||||
- "src/editor/lsp/files.ts"
|
||||
- "src/editor/lsp/hint.ts"
|
||||
- "src/editor/lsp/lsp.ts"
|
||||
- "src/editor/lsp/positions.ts"
|
||||
- "src/bindings.ts"
|
||||
- "src/styles/tokens.css"
|
||||
- "src/test/setup.ts"
|
||||
- "src-tauri/icons/128x128.png"
|
||||
- "smoke/**"
|
||||
- "vite.config.ts"
|
||||
- "tsconfig.json"
|
||||
- "package.json"
|
||||
- "pnpm-lock.yaml"
|
||||
- "pnpm-workspace.yaml"
|
||||
- "patches/**"
|
||||
- ".github/workflows/language-smoke.yml"
|
||||
- ".github/tool-versions.env"
|
||||
pull_request:
|
||||
@@ -57,9 +31,6 @@ on:
|
||||
paths: *paths
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: language-smoke-${{ github.ref }}
|
||||
# A new push supersedes a PR's run; on main every merge runs to the end (and saves the cache).
|
||||
@@ -70,172 +41,39 @@ env:
|
||||
CARGO_INCREMENTAL: 0
|
||||
|
||||
jobs:
|
||||
# The languages a pull request can affect: a change to one language's fixture, definition or
|
||||
# JDT LS bundle runs that language; crates the smoke doesn't exercise and other crates' tests
|
||||
# run none; anything else runs them all. Pushes and manual runs always run them all.
|
||||
changes:
|
||||
name: Changes
|
||||
# Self-hosted runners (scripts/selfhost-runner) only for trusted events, and only while the
|
||||
# SELFHOSTED_RUNNERS repository variable is 'true': runs-on cannot fall back when none is online.
|
||||
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
|
||||
timeout-minutes: 5
|
||||
permissions:
|
||||
pull-requests: read
|
||||
outputs:
|
||||
languages: ${{ steps.classify.outputs.languages }}
|
||||
steps:
|
||||
- id: classify
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
PR: ${{ github.event.pull_request.number }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
all="typescript python rust go java kotlin php c cpp"
|
||||
emit() { tr ' ' '\n' <<< "$1" | { grep . || true; } | sort -u | jq -Rsc 'split("\n") | map(select(. != ""))'; }
|
||||
if [ "$GITHUB_EVENT_NAME" != pull_request ]; then
|
||||
echo "languages=$(emit "$all")" | tee -a "$GITHUB_OUTPUT"
|
||||
exit 0
|
||||
fi
|
||||
gh api --paginate "repos/$GITHUB_REPOSITORY/pulls/$PR/files" \
|
||||
--jq '.[] | .filename, (.previous_filename // empty)' > files.txt
|
||||
cat files.txt
|
||||
# Crates outside what the smoke runs (language servers, debuggers, run configurations,
|
||||
# SDKs, build tools, the project model, Find Usages candidates, debug stream traces):
|
||||
# cargo metadata, ide-host's direct deps ide-search/ide-streams and the deps of
|
||||
# ide-lsp/dap/run/sdk/tools.
|
||||
unused='^crates/(ide-agent|ide-analysis|ide-android|ide-cli|ide-clipboard|ide-coverage|ide-db|ide-docker|ide-fonts|ide-github|ide-http|ide-mcp|ide-notebook|ide-profiler|ide-scaffold|ide-spell|ide-ssh|ide-vcs|ide-web)/'
|
||||
# The workflow's paths, less those handled per language below.
|
||||
smoke='^(crates/|Cargo\.(toml|lock)$|src/features/(run|debugger|build-tools)/|src/platform/|src/workbench/|src/ui/|src/editor/(api|navigationProviders|relatedProviders|core/cm/(cornerInset|iconArea)|lsp/(availability|diagnostics|files|hint|lsp|positions))\.ts$|src/bindings\.ts$|src/styles/tokens\.css$|src/test/setup\.ts$|src-tauri/icons/128x128\.png$|smoke/|vite\.config\.ts$|tsconfig\.json$|package\.json$|pnpm-(lock|workspace)\.yaml$|patches/|\.github/workflows/language-smoke\.yml$|\.github/tool-versions\.env$)'
|
||||
langs=""
|
||||
while read -r f; do
|
||||
case "$f" in
|
||||
crates/ide-host/tests/language_smoke.rs | crates/ide-host/tests/project_smoke.rs) langs="$all"; break ;;
|
||||
crates/*/tests/* | crates/*/benches/*) ;;
|
||||
fixtures/ts-app/*) langs+=" typescript" ;;
|
||||
fixtures/python-app/*) langs+=" python" ;;
|
||||
fixtures/rust-app/*) langs+=" rust" ;;
|
||||
fixtures/go-app/*) langs+=" go" ;;
|
||||
fixtures/java-app/*) langs+=" java" ;;
|
||||
fixtures/kotlin-gradle/*) langs+=" kotlin" ;;
|
||||
fixtures/php-app/*) langs+=" php" ;;
|
||||
fixtures/c-app/*) langs+=" c cpp" ;;
|
||||
fixtures/*) ;;
|
||||
languages/typescript.toml | languages/typescriptreact.toml | languages/javascript.toml | languages/javascriptreact.toml) langs+=" typescript" ;;
|
||||
languages/python.toml) langs+=" python" ;;
|
||||
languages/rust.toml) langs+=" rust" ;;
|
||||
languages/go.toml | languages/gomod.toml | languages/gowork.toml) langs+=" go" ;;
|
||||
languages/java.toml) langs+=" java" ;;
|
||||
languages/kotlin.toml) langs+=" kotlin" ;;
|
||||
languages/php.toml) langs+=" php" ;;
|
||||
languages/c.toml) langs+=" c" ;;
|
||||
languages/cpp.toml) langs+=" cpp" ;;
|
||||
languages/*) ;;
|
||||
java/kotlin-bridge/*) langs+=" kotlin" ;;
|
||||
java/*) langs+=" java kotlin" ;;
|
||||
*) if grep -Eq "$smoke" <<< "$f" && ! grep -Eq "$unused" <<< "$f"; then langs="$all"; break; fi ;;
|
||||
esac
|
||||
done < files.txt
|
||||
echo "languages=$(emit "$langs")" | tee -a "$GITHUB_OUTPUT"
|
||||
|
||||
# Builds the smoke test binaries and openidea-server once for every language below.
|
||||
build:
|
||||
name: Build
|
||||
needs: changes
|
||||
if: needs.changes.outputs.languages != '[]'
|
||||
# Self-hosted runners (scripts/selfhost-runner) only for trusted events, and only while the
|
||||
# SELFHOSTED_RUNNERS repository variable is 'true': runs-on cannot fall back when none is online.
|
||||
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
|
||||
timeout-minutes: 30
|
||||
env:
|
||||
# Line tables keep test backtraces readable and the binaries handed on small without
|
||||
# stripping local-variable debuginfo from fixtures debugged in the smoke job (CodeLLDB).
|
||||
CARGO_PROFILE_DEV_DEBUG: line-tables-only
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
if: runner.environment != 'self-hosted'
|
||||
with:
|
||||
shared-key: language-smoke
|
||||
save-if: ${{ github.ref == 'refs/heads/main' }}
|
||||
- name: Persistent Cargo target dir
|
||||
if: runner.environment == 'self-hosted'
|
||||
shell: bash
|
||||
run: |
|
||||
echo "CARGO_INCREMENTAL=1" >> "$GITHUB_ENV"
|
||||
size=$(du -sm "$CARGO_TARGET_DIR" 2>/dev/null | cut -f1 || true)
|
||||
if [ "${size:-0}" -gt 40000 ]; then
|
||||
echo "$CARGO_TARGET_DIR is ${size} MB; clearing it"
|
||||
rm -rf "$CARGO_TARGET_DIR"
|
||||
fi
|
||||
- run: |
|
||||
set -euo pipefail
|
||||
mkdir -p smoke-bin
|
||||
cargo test --locked -p ide-host --test language_smoke --test project_smoke --no-run --message-format=json \
|
||||
| jq -r 'select(.reason == "compiler-artifact" and .executable != null and .target.kind == ["test"]) | "\(.target.name) \(.executable)"' \
|
||||
| while read -r name exe; do cp "$exe" "smoke-bin/$name"; done
|
||||
cargo build --locked -p ide-host --bin openidea-server
|
||||
cp "${CARGO_TARGET_DIR:-target}/debug/openidea-server" smoke-bin/
|
||||
ls -l smoke-bin
|
||||
test -x smoke-bin/language_smoke && test -x smoke-bin/project_smoke
|
||||
# A tar keeps the executable bits, which artifacts drop.
|
||||
tar -cf smoke-bin.tar smoke-bin
|
||||
- uses: actions/upload-artifact@v6
|
||||
with: { name: smoke-bin, path: smoke-bin.tar, retention-days: 1 }
|
||||
|
||||
smoke:
|
||||
name: Language smoke (${{ matrix.language }})
|
||||
needs: [changes, build]
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
language: ${{ fromJSON(needs.changes.outputs.languages) }}
|
||||
# Self-hosted runners (scripts/selfhost-runner) only for trusted events, and only while the
|
||||
# SELFHOSTED_RUNNERS repository variable is 'true': runs-on cannot fall back when none is online.
|
||||
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
|
||||
language: [typescript, python, rust, go, java, kotlin, php, c, cpp]
|
||||
# C/C++ debug with GDB, whose DAP interpreter needs 14+: 22.04 ships 12.1, 24.04 ships 15.
|
||||
runs-on: ${{ (matrix.language == 'c' || matrix.language == 'cpp') && 'ubuntu-24.04' || 'ubuntu-22.04' }}
|
||||
timeout-minutes: 40
|
||||
# Self-hosted runner slots have distinct checkout paths (/persist/slot-<N>/work/...); override
|
||||
# the compiled-in CARGO_MANIFEST_DIR so binaries from the Build job find this slot's fixtures.
|
||||
env:
|
||||
CARGO_MANIFEST_DIR: ${{ github.workspace }}/crates/ide-host
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/checkout@v4
|
||||
# Tool versions, shared with the evals (pnpm eval).
|
||||
- run: grep -E '^[A-Z0-9_]+=' .github/tool-versions.env >> "$GITHUB_ENV"
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
with: { components: "rust-analyzer, rustfmt" }
|
||||
- uses: actions/download-artifact@v6
|
||||
with: { name: smoke-bin }
|
||||
- run: |
|
||||
tar -xf smoke-bin.tar && rm smoke-bin.tar
|
||||
mkdir -p target/debug && mv smoke-bin/openidea-server target/debug/
|
||||
|
||||
- uses: pnpm/action-setup@v5
|
||||
with: { version: 11 }
|
||||
- uses: actions/setup-node@v5
|
||||
# One build cache for every language; main saves it.
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
with:
|
||||
node-version: 22
|
||||
cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }}
|
||||
package-manager-cache: ${{ runner.environment != 'self-hosted' }}
|
||||
shared-key: language-smoke
|
||||
save-if: ${{ github.ref == 'refs/heads/main' && matrix.language == 'rust' }}
|
||||
|
||||
- uses: pnpm/action-setup@v4
|
||||
with: { version: 11 }
|
||||
- uses: actions/setup-node@v4
|
||||
with: { node-version: 22, cache: pnpm }
|
||||
- if: matrix.language == 'typescript'
|
||||
run: npm install --global "@vtsls/language-server@$VTSLS" "typescript@$TYPESCRIPT"
|
||||
|
||||
# The smoke checks C/C++ with clangd and debugs c-app with GDB's own DAP interpreter (GDB 14+).
|
||||
# The smoke builds the c-app fixture and debugs it with GDB's own DAP interpreter.
|
||||
- if: matrix.language == 'c' || matrix.language == 'cpp'
|
||||
shell: bash
|
||||
run: |
|
||||
pkgs=()
|
||||
command -v clangd >/dev/null || pkgs+=(clangd)
|
||||
command -v gdb >/dev/null || pkgs+=(gdb)
|
||||
if [ "${#pkgs[@]}" -gt 0 ]; then
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y "${pkgs[@]}"
|
||||
fi
|
||||
major=$(gdb --version | head -n1 | grep -Eo '[0-9]+\.[0-9]+' | head -n1 | cut -d. -f1)
|
||||
if [ "${major:-0}" -lt 14 ]; then
|
||||
echo "::error::GDB 14+ is required for its DAP interpreter; recreate the runner from scripts/selfhost-runner (Ubuntu 24.04)."
|
||||
exit 1
|
||||
fi
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y gdb
|
||||
|
||||
- if: matrix.language == 'python'
|
||||
uses: actions/setup-python@v5
|
||||
@@ -254,7 +92,6 @@ jobs:
|
||||
with: { distribution: temurin, java-version: "${{ env.JAVA }}" }
|
||||
- if: matrix.language == 'java'
|
||||
run: |
|
||||
command -v mvn >/dev/null || { sudo apt-get update && sudo apt-get install -y maven; }
|
||||
mkdir -p "$RUNNER_TEMP/jdtls"
|
||||
curl -fsSL "https://download.eclipse.org/jdtls/milestones/${JDTLS%-*}/jdt-language-server-$JDTLS.tar.gz" \
|
||||
| tar xz -C "$RUNNER_TEMP/jdtls"
|
||||
@@ -279,20 +116,17 @@ jobs:
|
||||
- if: matrix.language == 'php'
|
||||
run: npm install --global "intelephense@$INTELEPHENSE"
|
||||
|
||||
# The binaries from the build job, run from the crate directory as `cargo test` does.
|
||||
- working-directory: crates/ide-host
|
||||
run: ../../smoke-bin/language_smoke --ignored --exact ${{ matrix.language }}
|
||||
- run: cargo test --locked -p ide-host --test language_smoke --no-run
|
||||
- run: cargo test --locked -p ide-host --test language_smoke -- --ignored --exact ${{ matrix.language }}
|
||||
- if: matrix.language == 'java'
|
||||
working-directory: crates/ide-host
|
||||
run: ../../smoke-bin/project_smoke --ignored --exact maven_sync jdk maven_launch_classpath_uses_the_runner_jdk_classifier
|
||||
run: cargo test --locked -p ide-host --test project_smoke -- --ignored --exact maven_sync jdk maven_launch_classpath_uses_the_runner_jdk_classifier
|
||||
- if: matrix.language == 'kotlin'
|
||||
working-directory: crates/ide-host
|
||||
run: ../../smoke-bin/project_smoke --ignored --exact gradle_sync
|
||||
run: cargo test --locked -p ide-host --test project_smoke -- --ignored --exact gradle_sync
|
||||
- if: matrix.language == 'python'
|
||||
working-directory: crates/ide-host
|
||||
run: ../../smoke-bin/project_smoke --ignored --exact python_venv
|
||||
run: cargo test --locked -p ide-host --test project_smoke -- --ignored --exact python_venv
|
||||
|
||||
- run: pnpm install --frozen-lockfile
|
||||
- run: cargo build --locked -p ide-host --bin openidea-server
|
||||
- run: pnpm smoke smoke/run.test.ts -t "^${{ matrix.language }}$"
|
||||
- run: pnpm smoke smoke/debug.test.ts -t "^${{ matrix.language }}$"
|
||||
# The IDE installs the debugger from GitHub releases: authenticated, against rate limits.
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
name: Nightly
|
||||
|
||||
# Twice a day, builds the newest main commit that passed CI as a prerelease tagged with its own
|
||||
# version, so remote development finds the server of that version. The `nightly` release holds
|
||||
# the manifest the nightly app updates from; its tag marks the commit last built, and a run with
|
||||
# nothing newer stops there. Only the latest builds are kept.
|
||||
on:
|
||||
schedule:
|
||||
- cron: "17 2,14 * * *"
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
force:
|
||||
description: "Build even if nothing is newer than the last nightly"
|
||||
type: boolean
|
||||
default: false
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: nightly
|
||||
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
GH_REPO: ${{ github.repository }}
|
||||
|
||||
jobs:
|
||||
prepare:
|
||||
permissions:
|
||||
actions: read
|
||||
contents: write
|
||||
if: github.repository == 'l0ng-ai/openidea'
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
sha: ${{ steps.commit.outputs.sha }}
|
||||
tag: ${{ steps.release.outputs.tag }}
|
||||
release_id: ${{ steps.release.outputs.id }}
|
||||
steps:
|
||||
- id: commit
|
||||
env:
|
||||
FORCE: ${{ inputs.force }}
|
||||
run: |
|
||||
sha="$(gh run list --workflow ci.yml --branch main --event push --status success --limit 1 \
|
||||
--json headSha --jq '.[0].headSha // ""')"
|
||||
if [ -z "$sha" ]; then
|
||||
echo "::notice::no main commit has passed CI"
|
||||
exit 0
|
||||
fi
|
||||
# No `nightly` tag yet (the first run): compare fails and the build goes on.
|
||||
status="$(gh api "repos/$GH_REPO/compare/nightly...$sha" --jq .status 2>/dev/null)" || status=ahead
|
||||
if [ "$status" != ahead ] && [ "$FORCE" != true ]; then
|
||||
echo "::notice::$sha is not newer than the last nightly"
|
||||
exit 0
|
||||
fi
|
||||
echo "sha=$sha" >> "$GITHUB_OUTPUT"
|
||||
- uses: actions/checkout@v5
|
||||
if: steps.commit.outputs.sha != ''
|
||||
with: { ref: "${{ steps.commit.outputs.sha }}" }
|
||||
- uses: actions/setup-node@v5
|
||||
if: steps.commit.outputs.sha != ''
|
||||
with: { node-version: 22 }
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
if: steps.commit.outputs.sha != ''
|
||||
- id: release
|
||||
if: steps.commit.outputs.sha != ''
|
||||
env:
|
||||
SHA: ${{ steps.commit.outputs.sha }}
|
||||
run: |
|
||||
version="$(node scripts/nightly-prepare.ts "$(date -u +%Y%m%d%H%M)")"
|
||||
tag="v$version"
|
||||
git config user.name "github-actions[bot]"
|
||||
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
|
||||
git commit -am "chore: $tag"
|
||||
git tag "$tag"
|
||||
git push origin "$tag"
|
||||
id="$(gh api -X POST "repos/$GH_REPO/releases" -f tag_name="$tag" -f name="OpenIDEA Nightly $version" \
|
||||
-F draft=true -F prerelease=true -f body="Built from $SHA." --jq .id)"
|
||||
echo "tag=$tag" >> "$GITHUB_OUTPUT"
|
||||
echo "id=$id" >> "$GITHUB_OUTPUT"
|
||||
|
||||
binaries:
|
||||
permissions:
|
||||
contents: write
|
||||
needs: prepare
|
||||
if: needs.prepare.outputs.tag != ''
|
||||
uses: ./.github/workflows/release-build.yml
|
||||
with:
|
||||
tag: ${{ needs.prepare.outputs.tag }}
|
||||
release_id: ${{ needs.prepare.outputs.release_id }}
|
||||
secrets: inherit
|
||||
|
||||
publish:
|
||||
permissions:
|
||||
contents: write
|
||||
needs: [prepare, binaries]
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
TAG: ${{ needs.prepare.outputs.tag }}
|
||||
SHA: ${{ needs.prepare.outputs.sha }}
|
||||
KEEP: 14
|
||||
steps:
|
||||
- name: Publish the build
|
||||
run: gh release edit "$TAG" --tag "$TAG" --draft=false
|
||||
- name: Point the updater at it
|
||||
run: |
|
||||
gh release download "$TAG" -p latest.json -D "$RUNNER_TEMP"
|
||||
gh release view nightly >/dev/null 2>&1 ||
|
||||
gh release create nightly --prerelease --latest=false --target "$SHA" --title "OpenIDEA Nightly" \
|
||||
--notes "The update manifest of the nightly builds, and the commit last built."
|
||||
gh release upload nightly "$RUNNER_TEMP/latest.json" --clobber
|
||||
gh api -X PATCH "repos/$GH_REPO/git/refs/tags/nightly" -f sha="$SHA" -F force=true --silent
|
||||
# Failed builds' drafts go too, once they are this old.
|
||||
- name: Delete old builds
|
||||
run: |
|
||||
gh release list --limit 200 --json tagName,createdAt --jq \
|
||||
'[.[] | select(.tagName | contains("-nightly."))] | sort_by(.createdAt) | reverse | .[env.KEEP | tonumber:][].tagName' |
|
||||
while read -r tag; do
|
||||
gh release delete "$tag" --cleanup-tag --yes
|
||||
done
|
||||
@@ -1,7 +1,7 @@
|
||||
name: Release build
|
||||
|
||||
# Builds a tag's desktop apps, remote servers and updater manifest into its draft release
|
||||
# (run by release.yml).
|
||||
# Builds a tag's desktop apps, remote servers and updater manifest into its draft release.
|
||||
# Stable releases (release.yml) and nightly builds (nightly.yml) both run it.
|
||||
on:
|
||||
workflow_call:
|
||||
inputs:
|
||||
@@ -224,17 +224,18 @@ jobs:
|
||||
return;
|
||||
}
|
||||
// Bundle suffix → updater platform keys, as tauri-action names them.
|
||||
const windows = (arch, msi, nsis) => [
|
||||
[msi, [`windows-${arch}`, `windows-${arch}-msi`]],
|
||||
[nsis, [`windows-${arch}-nsis`]],
|
||||
];
|
||||
// Nightly versions don't fit MSI or RPM, so those builds offer NSIS on Windows.
|
||||
const nightly = tag.includes("-nightly.");
|
||||
const windows = (arch, msi, nsis) => nightly
|
||||
? [[nsis, [`windows-${arch}`, `windows-${arch}-nsis`]]]
|
||||
: [[msi, [`windows-${arch}`, `windows-${arch}-msi`]], [nsis, [`windows-${arch}-nsis`]]];
|
||||
const kinds = [
|
||||
[/_aarch64\.AppImage$/, ["linux-aarch64", "linux-aarch64-appimage"]],
|
||||
[/_arm64\.deb$/, ["linux-aarch64-deb"]],
|
||||
[/\.aarch64\.rpm$/, ["linux-aarch64-rpm"]],
|
||||
...(nightly ? [] : [[/\.aarch64\.rpm$/, ["linux-aarch64-rpm"]]]),
|
||||
[/_amd64\.AppImage$/, ["linux-x86_64", "linux-x86_64-appimage"]],
|
||||
[/_amd64\.deb$/, ["linux-x86_64-deb"]],
|
||||
[/\.x86_64\.rpm$/, ["linux-x86_64-rpm"]],
|
||||
...(nightly ? [] : [[/\.x86_64\.rpm$/, ["linux-x86_64-rpm"]]]),
|
||||
[/_aarch64\.app\.tar\.gz$/, ["darwin-aarch64", "darwin-aarch64-app"]],
|
||||
[/_x64\.app\.tar\.gz$/, ["darwin-x86_64", "darwin-x86_64-app"]],
|
||||
...windows("aarch64", /_arm64_en-US\.msi$/, /_arm64-setup\.exe$/),
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
name: Release
|
||||
on:
|
||||
push:
|
||||
tags: ["v*"]
|
||||
tags: ["v*", "!v*-nightly.*"]
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
tag:
|
||||
@@ -23,6 +23,7 @@ env:
|
||||
jobs:
|
||||
# Creates (or reuses) one draft release that every platform build uploads into.
|
||||
create-release:
|
||||
if: ${{ !contains(github.event.inputs.tag || github.ref_name, '-nightly.') }}
|
||||
permissions:
|
||||
contents: write
|
||||
runs-on: ubuntu-latest
|
||||
@@ -61,7 +62,7 @@ jobs:
|
||||
core.setOutput("id", existing.id);
|
||||
return;
|
||||
}
|
||||
// Prereleases are skipped: the notes span stable release to stable release.
|
||||
// Nightly builds are prereleases: the notes span stable release to stable release.
|
||||
const previous = releases.find((r) => !r.draft && !r.prerelease);
|
||||
const { data: notes } = await github.rest.repos.generateReleaseNotes({
|
||||
owner, repo, tag_name: tag, previous_tag_name: previous?.tag_name,
|
||||
|
||||
+7
-5
@@ -33,12 +33,14 @@ target/
|
||||
test-results/
|
||||
playwright-report/
|
||||
|
||||
# Local AI agent files
|
||||
AGENTS.md
|
||||
CLAUDE.md
|
||||
# Local AI agent files. Shared skills live in .agents/skills; .claude/skills links to them.
|
||||
CLAUDE.local.md
|
||||
.agents/
|
||||
.claude/
|
||||
.claude/*
|
||||
!.claude/skills/
|
||||
.claude/skills/*
|
||||
!.claude/skills/verify
|
||||
!.claude/skills/issue-fix
|
||||
!.claude/skills/eval
|
||||
|
||||
# Local reference screenshots
|
||||
pycharm-screenshots/
|
||||
@@ -1,15 +0,0 @@
|
||||
{
|
||||
"detector": {
|
||||
"ignoreRules": [],
|
||||
"ignoreFiles": [],
|
||||
"ignoreValues": [
|
||||
{
|
||||
"rule": "gradient-text",
|
||||
"value": "*",
|
||||
"files": ["src/features/agents/Session.module.css"],
|
||||
"createdAt": "2026-11-24T14:58:12.514Z",
|
||||
"reason": "agent: .shimmer is an animated in-progress sweep on running-step labels (commit 18b286e7e, comment documents intent), not decorative gradient text"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -1,557 +0,0 @@
|
||||
{
|
||||
"schemaVersion": 2,
|
||||
"generatedAt": "2026-11-24T15:06:05+00:00",
|
||||
"title": "Design System: OpenIDEA",
|
||||
"extensions": {
|
||||
"colorMeta": {
|
||||
"workbench-blue": {
|
||||
"role": "primary",
|
||||
"displayName": "Workbench Blue",
|
||||
"canonical": "#3871e1",
|
||||
"tonalRamp": [
|
||||
"oklch(15% 0.073 262)",
|
||||
"oklch(25% 0.121 262)",
|
||||
"oklch(35% 0.17 262)",
|
||||
"oklch(48% 0.17 262)",
|
||||
"oklch(60% 0.17 262)",
|
||||
"oklch(72% 0.136 262)",
|
||||
"oklch(84% 0.078 262)",
|
||||
"oklch(95% 0.024 262)"
|
||||
]
|
||||
},
|
||||
"link-blue": {
|
||||
"role": "primary",
|
||||
"displayName": "Link Blue",
|
||||
"canonical": "#2f5eb9",
|
||||
"tonalRamp": [
|
||||
"oklch(15% 0.064 262)",
|
||||
"oklch(25% 0.107 262)",
|
||||
"oklch(35% 0.15 262)",
|
||||
"oklch(48% 0.15 262)",
|
||||
"oklch(60% 0.15 262)",
|
||||
"oklch(72% 0.12 262)",
|
||||
"oklch(84% 0.069 262)",
|
||||
"oklch(95% 0.021 262)"
|
||||
]
|
||||
},
|
||||
"selection-wash": {
|
||||
"role": "primary",
|
||||
"displayName": "Selection Wash",
|
||||
"canonical": "#d0dffe",
|
||||
"tonalRamp": [
|
||||
"oklch(15% 0.034 262)",
|
||||
"oklch(25% 0.057 262)",
|
||||
"oklch(35% 0.08 262)",
|
||||
"oklch(48% 0.08 262)",
|
||||
"oklch(60% 0.08 262)",
|
||||
"oklch(72% 0.064 262)",
|
||||
"oklch(84% 0.037 262)",
|
||||
"oklch(95% 0.011 262)"
|
||||
]
|
||||
},
|
||||
"tab-wash": {
|
||||
"role": "primary",
|
||||
"displayName": "Tab Wash",
|
||||
"canonical": "#e3ebfe",
|
||||
"tonalRamp": [
|
||||
"oklch(15% 0.026 262)",
|
||||
"oklch(25% 0.043 262)",
|
||||
"oklch(35% 0.06 262)",
|
||||
"oklch(48% 0.06 262)",
|
||||
"oklch(60% 0.06 262)",
|
||||
"oklch(72% 0.048 262)",
|
||||
"oklch(84% 0.027 262)",
|
||||
"oklch(95% 0.009 262)"
|
||||
]
|
||||
},
|
||||
"danger": {
|
||||
"role": "status",
|
||||
"displayName": "Danger",
|
||||
"canonical": "#c54e58",
|
||||
"tonalRamp": [
|
||||
"oklch(15% 0.064 18)",
|
||||
"oklch(25% 0.107 18)",
|
||||
"oklch(35% 0.15 18)",
|
||||
"oklch(48% 0.15 18)",
|
||||
"oklch(60% 0.15 18)",
|
||||
"oklch(72% 0.12 18)",
|
||||
"oklch(84% 0.069 18)",
|
||||
"oklch(95% 0.021 18)"
|
||||
]
|
||||
},
|
||||
"warning": {
|
||||
"role": "status",
|
||||
"displayName": "Warning",
|
||||
"canonical": "#a56906",
|
||||
"tonalRamp": [
|
||||
"oklch(15% 0.056 70)",
|
||||
"oklch(25% 0.093 70)",
|
||||
"oklch(35% 0.13 70)",
|
||||
"oklch(48% 0.13 70)",
|
||||
"oklch(60% 0.13 70)",
|
||||
"oklch(72% 0.104 70)",
|
||||
"oklch(84% 0.059 70)",
|
||||
"oklch(95% 0.019 70)"
|
||||
]
|
||||
},
|
||||
"success": {
|
||||
"role": "status",
|
||||
"displayName": "Success",
|
||||
"canonical": "#338555",
|
||||
"tonalRamp": [
|
||||
"oklch(15% 0.047 152)",
|
||||
"oklch(25% 0.079 152)",
|
||||
"oklch(35% 0.11 152)",
|
||||
"oklch(48% 0.11 152)",
|
||||
"oklch(60% 0.11 152)",
|
||||
"oklch(72% 0.088 152)",
|
||||
"oklch(84% 0.05 152)",
|
||||
"oklch(95% 0.016 152)"
|
||||
]
|
||||
},
|
||||
"frame-grey": {
|
||||
"role": "neutral",
|
||||
"displayName": "Frame Grey",
|
||||
"tonalRamp": [
|
||||
"oklch(15% 0.005 265)",
|
||||
"oklch(25% 0.009 265)",
|
||||
"oklch(35% 0.012 265)",
|
||||
"oklch(48% 0.012 265)",
|
||||
"oklch(60% 0.012 265)",
|
||||
"oklch(72% 0.01 265)",
|
||||
"oklch(84% 0.005 265)",
|
||||
"oklch(95% 0.002 265)"
|
||||
]
|
||||
},
|
||||
"island-white": {
|
||||
"role": "neutral",
|
||||
"displayName": "Island White",
|
||||
"tonalRamp": [
|
||||
"oklch(15% 0.005 265)",
|
||||
"oklch(25% 0.009 265)",
|
||||
"oklch(35% 0.012 265)",
|
||||
"oklch(48% 0.012 265)",
|
||||
"oklch(60% 0.012 265)",
|
||||
"oklch(72% 0.01 265)",
|
||||
"oklch(84% 0.005 265)",
|
||||
"oklch(95% 0.002 265)"
|
||||
]
|
||||
},
|
||||
"raised-paper": {
|
||||
"role": "neutral",
|
||||
"displayName": "Raised Paper",
|
||||
"tonalRamp": [
|
||||
"oklch(15% 0.005 265)",
|
||||
"oklch(25% 0.009 265)",
|
||||
"oklch(35% 0.012 265)",
|
||||
"oklch(48% 0.012 265)",
|
||||
"oklch(60% 0.012 265)",
|
||||
"oklch(72% 0.01 265)",
|
||||
"oklch(84% 0.005 265)",
|
||||
"oklch(95% 0.002 265)"
|
||||
]
|
||||
},
|
||||
"ink": {
|
||||
"role": "neutral",
|
||||
"displayName": "Ink",
|
||||
"tonalRamp": [
|
||||
"oklch(15% 0.005 265)",
|
||||
"oklch(25% 0.009 265)",
|
||||
"oklch(35% 0.012 265)",
|
||||
"oklch(48% 0.012 265)",
|
||||
"oklch(60% 0.012 265)",
|
||||
"oklch(72% 0.01 265)",
|
||||
"oklch(84% 0.005 265)",
|
||||
"oklch(95% 0.002 265)"
|
||||
]
|
||||
},
|
||||
"ink-secondary": {
|
||||
"role": "neutral",
|
||||
"displayName": "Ink Secondary",
|
||||
"tonalRamp": [
|
||||
"oklch(15% 0.005 265)",
|
||||
"oklch(25% 0.009 265)",
|
||||
"oklch(35% 0.012 265)",
|
||||
"oklch(48% 0.012 265)",
|
||||
"oklch(60% 0.012 265)",
|
||||
"oklch(72% 0.01 265)",
|
||||
"oklch(84% 0.005 265)",
|
||||
"oklch(95% 0.002 265)"
|
||||
]
|
||||
},
|
||||
"ink-muted": {
|
||||
"role": "neutral",
|
||||
"displayName": "Ink Muted",
|
||||
"tonalRamp": [
|
||||
"oklch(15% 0.005 265)",
|
||||
"oklch(25% 0.009 265)",
|
||||
"oklch(35% 0.012 265)",
|
||||
"oklch(48% 0.012 265)",
|
||||
"oklch(60% 0.012 265)",
|
||||
"oklch(72% 0.01 265)",
|
||||
"oklch(84% 0.005 265)",
|
||||
"oklch(95% 0.002 265)"
|
||||
]
|
||||
},
|
||||
"ink-faint": {
|
||||
"role": "neutral",
|
||||
"displayName": "Ink Faint",
|
||||
"tonalRamp": [
|
||||
"oklch(15% 0.005 265)",
|
||||
"oklch(25% 0.009 265)",
|
||||
"oklch(35% 0.012 265)",
|
||||
"oklch(48% 0.012 265)",
|
||||
"oklch(60% 0.012 265)",
|
||||
"oklch(72% 0.01 265)",
|
||||
"oklch(84% 0.005 265)",
|
||||
"oklch(95% 0.002 265)"
|
||||
]
|
||||
},
|
||||
"hairline": {
|
||||
"role": "neutral",
|
||||
"displayName": "Hairline",
|
||||
"tonalRamp": [
|
||||
"oklch(15% 0.005 265)",
|
||||
"oklch(25% 0.009 265)",
|
||||
"oklch(35% 0.012 265)",
|
||||
"oklch(48% 0.012 265)",
|
||||
"oklch(60% 0.012 265)",
|
||||
"oklch(72% 0.01 265)",
|
||||
"oklch(84% 0.005 265)",
|
||||
"oklch(95% 0.002 265)"
|
||||
]
|
||||
},
|
||||
"control-edge": {
|
||||
"role": "neutral",
|
||||
"displayName": "Control Edge",
|
||||
"tonalRamp": [
|
||||
"oklch(15% 0.005 265)",
|
||||
"oklch(25% 0.009 265)",
|
||||
"oklch(35% 0.012 265)",
|
||||
"oklch(48% 0.012 265)",
|
||||
"oklch(60% 0.012 265)",
|
||||
"oklch(72% 0.01 265)",
|
||||
"oklch(84% 0.005 265)",
|
||||
"oklch(95% 0.002 265)"
|
||||
]
|
||||
},
|
||||
"frame-grey-dark": {
|
||||
"role": "neutral",
|
||||
"displayName": "Frame Grey (Dark)",
|
||||
"tonalRamp": [
|
||||
"oklch(15% 0.005 265)",
|
||||
"oklch(25% 0.009 265)",
|
||||
"oklch(35% 0.012 265)",
|
||||
"oklch(48% 0.012 265)",
|
||||
"oklch(60% 0.012 265)",
|
||||
"oklch(72% 0.01 265)",
|
||||
"oklch(84% 0.005 265)",
|
||||
"oklch(95% 0.002 265)"
|
||||
]
|
||||
},
|
||||
"island-dark": {
|
||||
"role": "neutral",
|
||||
"displayName": "Island (Dark)",
|
||||
"tonalRamp": [
|
||||
"oklch(15% 0.005 265)",
|
||||
"oklch(25% 0.009 265)",
|
||||
"oklch(35% 0.012 265)",
|
||||
"oklch(48% 0.012 265)",
|
||||
"oklch(60% 0.012 265)",
|
||||
"oklch(72% 0.01 265)",
|
||||
"oklch(84% 0.005 265)",
|
||||
"oklch(95% 0.002 265)"
|
||||
]
|
||||
},
|
||||
"ink-dark": {
|
||||
"role": "neutral",
|
||||
"displayName": "Ink (Dark)",
|
||||
"tonalRamp": [
|
||||
"oklch(15% 0.005 265)",
|
||||
"oklch(25% 0.009 265)",
|
||||
"oklch(35% 0.012 265)",
|
||||
"oklch(48% 0.012 265)",
|
||||
"oklch(60% 0.012 265)",
|
||||
"oklch(72% 0.01 265)",
|
||||
"oklch(84% 0.005 265)",
|
||||
"oklch(95% 0.002 265)"
|
||||
]
|
||||
},
|
||||
"ink-strong-dark": {
|
||||
"role": "neutral",
|
||||
"displayName": "Ink Strong (Dark)",
|
||||
"tonalRamp": [
|
||||
"oklch(15% 0.005 265)",
|
||||
"oklch(25% 0.009 265)",
|
||||
"oklch(35% 0.012 265)",
|
||||
"oklch(48% 0.012 265)",
|
||||
"oklch(60% 0.012 265)",
|
||||
"oklch(72% 0.01 265)",
|
||||
"oklch(84% 0.005 265)",
|
||||
"oklch(95% 0.002 265)"
|
||||
]
|
||||
},
|
||||
"ink-muted-dark": {
|
||||
"role": "neutral",
|
||||
"displayName": "Ink Muted (Dark)",
|
||||
"tonalRamp": [
|
||||
"oklch(15% 0.005 265)",
|
||||
"oklch(25% 0.009 265)",
|
||||
"oklch(35% 0.012 265)",
|
||||
"oklch(48% 0.012 265)",
|
||||
"oklch(60% 0.012 265)",
|
||||
"oklch(72% 0.01 265)",
|
||||
"oklch(84% 0.005 265)",
|
||||
"oklch(95% 0.002 265)"
|
||||
]
|
||||
},
|
||||
"control-edge-dark": {
|
||||
"role": "neutral",
|
||||
"displayName": "Control Edge (Dark)",
|
||||
"tonalRamp": [
|
||||
"oklch(15% 0.005 265)",
|
||||
"oklch(25% 0.009 265)",
|
||||
"oklch(35% 0.012 265)",
|
||||
"oklch(48% 0.012 265)",
|
||||
"oklch(60% 0.012 265)",
|
||||
"oklch(72% 0.01 265)",
|
||||
"oklch(84% 0.005 265)",
|
||||
"oklch(95% 0.002 265)"
|
||||
]
|
||||
},
|
||||
"selection-wash-dark": {
|
||||
"role": "primary",
|
||||
"displayName": "Selection Wash (Dark)",
|
||||
"canonical": "#2a4371",
|
||||
"tonalRamp": [
|
||||
"oklch(15% 0.034 262)",
|
||||
"oklch(25% 0.057 262)",
|
||||
"oklch(35% 0.08 262)",
|
||||
"oklch(48% 0.08 262)",
|
||||
"oklch(60% 0.08 262)",
|
||||
"oklch(72% 0.064 262)",
|
||||
"oklch(84% 0.037 262)",
|
||||
"oklch(95% 0.011 262)"
|
||||
]
|
||||
}
|
||||
},
|
||||
"typographyMeta": {
|
||||
"title": {
|
||||
"displayName": "Title",
|
||||
"purpose": "Tool window titles, section headers, dialog titles; weight 600 is the main emphasis."
|
||||
},
|
||||
"body": {
|
||||
"displayName": "Body",
|
||||
"purpose": "Default UI text, menus, rows, buttons."
|
||||
},
|
||||
"label": {
|
||||
"displayName": "Label",
|
||||
"purpose": "Secondary metadata, chips, status bar, table cells; the most-used size."
|
||||
},
|
||||
"label-tiny": {
|
||||
"displayName": "Label Tiny",
|
||||
"purpose": "Stripe labels, counters, badges."
|
||||
},
|
||||
"input-large": {
|
||||
"displayName": "Input Large",
|
||||
"purpose": "Search Everywhere and other large query fields."
|
||||
},
|
||||
"code": {
|
||||
"displayName": "Code",
|
||||
"purpose": "Editor, console, terminal and every monospace preview; size and weights are user settings."
|
||||
}
|
||||
},
|
||||
"shadows": [
|
||||
{
|
||||
"name": "shadow-popup",
|
||||
"value": "0 6px 20px rgba(0, 0, 0, 0.12)",
|
||||
"purpose": "Popups, menus, completion, floating toolbar (Light; Dark uses 0.45 alpha)."
|
||||
},
|
||||
{
|
||||
"name": "shadow-dialog",
|
||||
"value": "0 0 0 0.5px rgba(0, 0, 0, 0.1), 0 10px 24px rgba(0, 0, 0, 0.1), 0 24px 72px rgba(0, 0, 0, 0.2)",
|
||||
"purpose": "Window-style shadow for dialogs (Light)."
|
||||
},
|
||||
{
|
||||
"name": "shadow-tooltip",
|
||||
"value": "0 4px 12px rgba(0, 0, 0, 0.12)",
|
||||
"purpose": "Hover tooltips (Light)."
|
||||
},
|
||||
{
|
||||
"name": "shadow-balloon",
|
||||
"value": "0 8px 24px rgba(0, 0, 0, 0.14)",
|
||||
"purpose": "Notification balloons (Light)."
|
||||
}
|
||||
],
|
||||
"motion": [
|
||||
{
|
||||
"name": "ease",
|
||||
"value": "cubic-bezier(0.2, 0, 0, 1)",
|
||||
"purpose": "Default easing for every state transition."
|
||||
},
|
||||
{
|
||||
"name": "dur-fast",
|
||||
"value": "80ms",
|
||||
"purpose": "Hover, press and focus changes on controls."
|
||||
},
|
||||
{
|
||||
"name": "dur",
|
||||
"value": "140ms",
|
||||
"purpose": "Standard transitions such as popup fades."
|
||||
},
|
||||
{
|
||||
"name": "dur-slow",
|
||||
"value": "220ms",
|
||||
"purpose": "Upper bound for any state transition."
|
||||
}
|
||||
],
|
||||
"density": [
|
||||
{
|
||||
"name": "default",
|
||||
"value": "rows 24px, fields/buttons 28px, titlebar 40px, tab bar 38px, status bar 30px, island gap 6px, island radius 10px"
|
||||
},
|
||||
{
|
||||
"name": "compact",
|
||||
"value": "rows 22px, fields/buttons 24px, titlebar/headers 32px, tab bar 32px, status bar 24px, island gap 4px, island radius 8px, chrome text -1px"
|
||||
}
|
||||
]
|
||||
},
|
||||
"components": [
|
||||
{
|
||||
"name": "Primary Button",
|
||||
"kind": "button",
|
||||
"refersTo": "button-primary",
|
||||
"description": "The one default action in a dialog or form.",
|
||||
"html": "<button class=\"ds-btn ds-btn-primary\">OK</button>",
|
||||
"css": ".ds-btn { display:inline-flex; align-items:center; justify-content:center; height:var(--h-button,28px); min-width:72px; padding:0 16px; border:0; border-radius:var(--radius-control,4px); font-family:var(--font-ui); font-size:var(--fs-ui,13px); line-height:1; cursor:default; transition:background var(--dur-fast,80ms) var(--ease), color var(--dur-fast,80ms) var(--ease), box-shadow var(--dur-fast,80ms) var(--ease); } .ds-btn:focus-visible { outline:2px solid var(--focus-ring,#3871e1); outline-offset:1px; } .ds-btn-primary { background:var(--bg-button-primary,#3871e1); color:var(--fg-button-primary,#fff); } .ds-btn-primary:hover { background:var(--bg-button-primary-hover,#3366cc); }"
|
||||
},
|
||||
{
|
||||
"name": "Secondary Button",
|
||||
"kind": "button",
|
||||
"refersTo": "button-secondary",
|
||||
"description": "Every other dialog action: Cancel, Apply, Browse.",
|
||||
"html": "<button class=\"ds-btn ds-btn-secondary\">Cancel</button>",
|
||||
"css": ".ds-btn { display:inline-flex; align-items:center; justify-content:center; height:var(--h-button,28px); min-width:72px; padding:0 16px; border:0; border-radius:var(--radius-control,4px); font-family:var(--font-ui); font-size:var(--fs-ui,13px); line-height:1; cursor:default; transition:background var(--dur-fast,80ms) var(--ease), box-shadow var(--dur-fast,80ms) var(--ease); } .ds-btn:focus-visible { outline:2px solid var(--focus-ring,#3871e1); outline-offset:1px; } .ds-btn-secondary { background:var(--bg-button,#fff); color:var(--fg-strong,#000); box-shadow:inset 0 0 0 1px var(--border-button,#d1d3d9); } .ds-btn-secondary:hover { background:color-mix(in srgb, var(--bg-button,#fff) 94%, var(--fg-strong,#000)); }"
|
||||
},
|
||||
{
|
||||
"name": "Ghost Button",
|
||||
"kind": "button",
|
||||
"refersTo": "button-ghost",
|
||||
"description": "Low-emphasis text actions in headers and inline rows.",
|
||||
"html": "<button class=\"ds-btn-ghost\">Show all</button>",
|
||||
"css": ".ds-btn-ghost { display:inline-flex; align-items:center; height:var(--h-button,28px); padding:0 8px; border:0; background:transparent; border-radius:var(--radius-control,4px); color:var(--fg-secondary,#5f6269); font-family:var(--font-ui); font-size:var(--fs-ui,13px); cursor:default; transition:background var(--dur-fast,80ms) var(--ease), color var(--dur-fast,80ms) var(--ease); } .ds-btn-ghost:hover { background:var(--bg-toolbar-hover,#00000012); color:var(--fg-strong,#000); } .ds-btn-ghost:active { background:var(--bg-toolbar-pressed,#00000020); } .ds-btn-ghost:focus-visible { outline:2px solid var(--focus-ring,#3871e1); outline-offset:1px; }"
|
||||
},
|
||||
{
|
||||
"name": "Toolbar Icon Button",
|
||||
"kind": "button",
|
||||
"refersTo": "icon-button",
|
||||
"description": "Toolbar and tool window header actions; frameless at rest, toggles show Selection Wash.",
|
||||
"html": "<div class=\"ds-iconbar\"><button class=\"ds-icon-btn\" aria-label=\"Refresh\"><svg width=\"16\" height=\"16\" viewBox=\"0 0 16 16\" fill=\"none\"><path d=\"M13 8a5 5 0 1 1-1.46-3.54M13 3v2.5h-2.5\" stroke=\"currentColor\" stroke-width=\"1.2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/></svg></button><button class=\"ds-icon-btn\" aria-label=\"Show options\" aria-pressed=\"true\"><svg width=\"16\" height=\"16\" viewBox=\"0 0 16 16\" fill=\"none\"><path d=\"M2.5 4.5h11M2.5 8h11M2.5 11.5h11\" stroke=\"currentColor\" stroke-width=\"1.2\" stroke-linecap=\"round\"/></svg></button></div>",
|
||||
"css": ".ds-iconbar { display:flex; gap:2px; } .ds-icon-btn { display:inline-flex; align-items:center; justify-content:center; width:24px; height:24px; padding:0; border:0; background:transparent; border-radius:var(--radius-toolbar-button,6px); color:var(--fg-muted,#6c707e); cursor:default; transition:background var(--dur-fast,80ms) var(--ease), color var(--dur-fast,80ms) var(--ease); } .ds-icon-btn:hover { background:var(--bg-toolbar-hover,#00000012); color:var(--fg-strong,#000); } .ds-icon-btn:active { background:var(--bg-toolbar-pressed,#00000020); } .ds-icon-btn[aria-pressed=\"true\"] { background:var(--bg-toolbar-selected,#d0dffe); color:var(--fg-strong,#000); } .ds-icon-btn:focus-visible { outline:2px solid var(--focus-ring,#3871e1); outline-offset:-2px; }"
|
||||
},
|
||||
{
|
||||
"name": "Text Field",
|
||||
"kind": "input",
|
||||
"refersTo": "input",
|
||||
"description": "Framed text field; the frame doubles in Workbench Blue on focus.",
|
||||
"html": "<input class=\"ds-input\" placeholder=\"Project name\" />",
|
||||
"css": ".ds-input { height:var(--h-field,28px); padding:0 8px; border:0; appearance:none; border-radius:var(--radius-control,4px); background:var(--bg-field,#fff); color:var(--fg-strong,#000); font-family:var(--font-ui); font-size:var(--fs-ui,13px); outline:none; box-shadow:inset 0 0 0 1px var(--border-button,#d1d3d9); transition:box-shadow var(--dur-fast,80ms) var(--ease); } .ds-input::placeholder { color:var(--fg-faint,#9fa2a8); } .ds-input:focus { box-shadow:inset 0 0 0 1px var(--focus-ring,#3871e1), 0 0 0 1px var(--focus-ring,#3871e1); }"
|
||||
},
|
||||
{
|
||||
"name": "Chip",
|
||||
"kind": "chip",
|
||||
"refersTo": "chip",
|
||||
"description": "Flat read-only fact or picker trigger, sized like the toolbar widgets.",
|
||||
"html": "<button class=\"ds-chip\"><svg width=\"14\" height=\"14\" viewBox=\"0 0 16 16\" fill=\"none\"><circle cx=\"5\" cy=\"4\" r=\"1.5\" stroke=\"currentColor\"/><circle cx=\"5\" cy=\"12\" r=\"1.5\" stroke=\"currentColor\"/><circle cx=\"11\" cy=\"6\" r=\"1.5\" stroke=\"currentColor\"/><path d=\"M5 5.5v5M11 7.5c0 2-2 2.5-6 3\" stroke=\"currentColor\"/></svg><span>main</span></button>",
|
||||
"css": ".ds-chip { display:inline-flex; align-items:center; gap:var(--space-1,4px); height:22px; padding:0 6px; border:0; background:transparent; border-radius:var(--radius-toolbar-button,6px); color:var(--fg-secondary,#5f6269); font-family:var(--font-ui); font-size:var(--fs-small,12px); line-height:1; cursor:default; transition:background var(--dur-fast,80ms) var(--ease); } .ds-chip svg { color:var(--fg-muted,#6c707e); } .ds-chip:hover { background:var(--bg-toolbar-hover,#00000012); } .ds-chip:focus-visible { outline:2px solid var(--focus-ring,#3871e1); outline-offset:-2px; }"
|
||||
},
|
||||
{
|
||||
"name": "Tree Rows",
|
||||
"kind": "custom",
|
||||
"refersTo": "list-row-selected",
|
||||
"description": "24px rows with an inset rounded selection wash; unfocused selection turns neutral.",
|
||||
"html": "<div class=\"ds-tree\" tabindex=\"0\"><div class=\"ds-row\">src</div><div class=\"ds-row ds-row-sel\">main.tsx</div><div class=\"ds-row\">workbench</div></div>",
|
||||
"css": ".ds-tree { width:220px; padding:4px var(--tree-inset,6px); background:var(--bg-island,#fff); border-radius:var(--island-radius,10px); font-family:var(--font-ui); font-size:var(--fs-ui,13px); color:var(--fg,#000); outline:none; } .ds-row { height:var(--h-row,24px); display:flex; align-items:center; padding:0 8px; border-radius:var(--radius-row,4px); } .ds-row:hover { background:var(--bg-tree-hover,#0000000a); } .ds-row-sel, .ds-row-sel:hover { background:var(--bg-tree-selected-inactive,#e9eaee); } .ds-tree:focus .ds-row-sel { background:var(--bg-tree-selected,#d0dffe); }"
|
||||
},
|
||||
{
|
||||
"name": "Island on Frame",
|
||||
"kind": "card",
|
||||
"description": "The signature layout unit: rounded islands 6px apart on the grey frame, flat at rest.",
|
||||
"html": "<div class=\"ds-frame\"><div class=\"ds-island ds-side\"><div class=\"ds-head\">Project</div></div><div class=\"ds-island ds-main\"><code>fn main() {}</code></div></div>",
|
||||
"css": ".ds-frame { display:flex; gap:var(--island-gap,6px); padding:var(--island-gap,6px); background:var(--bg-frame,#e9eaee); height:160px; } .ds-island { background:var(--bg-island,#fff); border-radius:var(--island-radius,10px); } .ds-side { width:140px; } .ds-main { flex:1; padding:12px; font-family:var(--font-mono); font-size:var(--fs-code,13px); color:var(--fg-editor,#080808); } .ds-head { height:40px; display:flex; align-items:center; padding:0 12px; font-family:var(--font-ui); font-size:var(--fs-ui,13px); font-weight:600; color:var(--fg-strong,#000); }"
|
||||
},
|
||||
{
|
||||
"name": "Tooltip",
|
||||
"kind": "custom",
|
||||
"refersTo": "tooltip",
|
||||
"description": "Floating hover help: one of the few surfaces allowed a shadow.",
|
||||
"html": "<div class=\"ds-tooltip\">Run 'main' <span class=\"ds-kbd\">⌃R</span></div>",
|
||||
"css": ".ds-tooltip { display:inline-flex; gap:8px; align-items:center; padding:6px 10px; border-radius:var(--radius-tooltip,6px); background:var(--bg-tooltip,#fff); color:var(--fg-tooltip,#000); border:1px solid var(--border-tooltip,#d1d3d9); box-shadow:var(--shadow-tooltip,0 4px 12px rgba(0,0,0,.12)); font-family:var(--font-ui); font-size:var(--fs-ui,13px); } .ds-kbd { font-family:var(--font-keys); color:var(--fg-muted,#6c707e); }"
|
||||
}
|
||||
],
|
||||
"narrative": {
|
||||
"northStar": "The Quiet Workbench",
|
||||
"overview": "The interface is a workbench, not a showroom. Code, trees, logs and diffs are the work. The chrome around them stays quiet, so the eye goes to the content and a long session stays calm.\n\nThe visual language is the JetBrains new UI in its **Islands** form, and this document records it rather than inventing one. The tokens in `src/styles/tokens.css` take their values from the Islands Light and Islands Dark theme JSON and editor schemes, at 100% zoom. Component metrics follow the matching IntelliJ theme keys (a Swing `arc` is a diameter, so the CSS radius is half of it), and component CSS names the key it follows. Behaviour follows IDEA as well, from focus and selection to dialogs and drag and drop. Users bring their JetBrains muscle memory, so a layout, metric or state that looks or behaves differently from IDEA counts as a bug, not a style choice.\n\nEvery panel sits on a grey frame as a rounded island (10px corners, 6px gaps). Depth comes from that tonal step, not from decoration. The density is that of a professional desktop tool: 13px UI text, 24px rows, 28px controls, with a compact mode that tightens all of them.\n\nThe tokens are a theming contract, not one palette. The built-in themes are Islands Light (the default), Islands Dark, High Contrast, Solarized Light and Solarized Dark. Users can also change the accent colour, give tool windows a different background from the editor, set a background image, use contrast scrollbars, or adjust colours for red-green vision deficiency. Imported IntelliJ themes and plugin themes set the same tokens at runtime. A component that looks right only in Islands Light is broken.\n\nExpression is kept to precise details: one blue accent, controls with no frame until they're hovered, hairline frames on fields and secondary buttons, and fast state transitions. Three things are rejected outright. It must not look like a web app: no big rounded cards, airy marketing whitespace, decorative gradients or illustrations. It has no second accent colour. And it has no eye-catching animation.",
|
||||
"keyCharacteristics": [
|
||||
"JetBrains new UI (Islands): metrics and behaviour follow IntelliJ's theme keys.",
|
||||
"Grey frame, rounded content islands, tonal layering only.",
|
||||
"A single accent (Workbench Blue) for primary actions, focus, selection and the active tool window.",
|
||||
"High density on a 4px grid. Compact mode is a first-class variant.",
|
||||
"Controls are quiet at rest: toolbar buttons and chips have no frame until hover.",
|
||||
"Semantic colour (status, VCS, diff, syntax) carries meaning and is never decoration.",
|
||||
"Every colour and metric is a token in `src/styles/tokens.css`. Tokens are the public theme API for plugins."
|
||||
],
|
||||
"rules": [
|
||||
{
|
||||
"name": "The IDEA Reference Rule",
|
||||
"body": "When tokens and this document don't answer a question, the answer is what IntelliJ IDEA does in the Islands theme, with the same metric and the same state behaviour. Take the value from the theme key, add it as a token, and name the key in a CSS comment.",
|
||||
"section": "overview"
|
||||
},
|
||||
{
|
||||
"name": "The One Accent Rule",
|
||||
"body": "Workbench Blue is the only accent. Every other hue in the UI belongs to a functional vocabulary (status, VCS, diff, syntax, charts) and means something specific. If a new colour has no meaning to carry, it doesn't ship.",
|
||||
"section": "colors"
|
||||
},
|
||||
{
|
||||
"name": "The Token Only Rule",
|
||||
"body": "Components never contain hex, `rgb()` or named colour literals. A new colour is a new token with a value in every theme variant, named for its purpose. Run `pnpm gen:theme-docs` afterwards.",
|
||||
"section": "colors"
|
||||
},
|
||||
{
|
||||
"name": "The Flat Scale Rule",
|
||||
"body": "The UI uses 11, 12, 13 and 15px, and nothing in between. Emphasis is weight 600 or a stronger ink colour, not a bigger size.",
|
||||
"section": "typography"
|
||||
},
|
||||
{
|
||||
"name": "The User Owns Size Rule",
|
||||
"body": "Sizes are tokens because users change them (UI font size, editor font, compact mode's -1px chrome offset). Never hard-code a font size.",
|
||||
"section": "typography"
|
||||
},
|
||||
{
|
||||
"name": "The Flat at Rest Rule",
|
||||
"body": "No docked panel, island, row or control gets a shadow. A shadow means \"this floats over the workbench and will go away\". Depth inside the layout is only ever a tonal step.",
|
||||
"section": "elevation"
|
||||
}
|
||||
],
|
||||
"dos": [
|
||||
"**Do** match IntelliJ IDEA's Islands theme for any metric or state that isn't tokenized yet. Take the value from the theme key and name the key in a CSS comment (for example `Button.arc 8 (radius 4)`).",
|
||||
"**Do** take every colour and metric from `src/styles/tokens.css`, and add a token for every theme variant when you need a new one.",
|
||||
"**Do** separate regions with a tonal step (frame against island) or a 1px hairline, never with a shadow.",
|
||||
"**Do** keep toolbar buttons and chips without a frame at rest, with the toolbar hover wash over the full hit target.",
|
||||
"**Do** draw frames and focus rings as inset box-shadows (1px at rest, doubled on focus), and keep the 2px Workbench Blue focus outline visible.",
|
||||
"**Do** check every surface in Islands Light and Islands Dark at least, as the contribution guidelines require. Check High Contrast and compact density whenever a change touches colour or metrics.",
|
||||
"**Do** keep transitions to state changes: 80ms (`--dur-fast`), 140ms (`--dur`) or at most 220ms (`--dur-slow`) with `--ease`, and none under reduced motion.",
|
||||
"**Do** use icons from the `src/ui/icons.tsx` registry, drawn in `currentColor`."
|
||||
],
|
||||
"donts": [
|
||||
"**Don't** make it look like a web app: no large rounded cards, airy marketing whitespace, decorative gradients, hero illustrations or corners above 10px. The project wash is the one gradient in the chrome. Progress shimmer counts as activity, not decoration.",
|
||||
"**Don't** invent a look or behaviour where IDEA already has one. A custom variant of an IDEA pattern breaks muscle memory.",
|
||||
"**Don't** add a second accent. Any hue other than Workbench Blue must carry status, VCS, diff, syntax or chart meaning.",
|
||||
"**Don't** add attention-seeking animation: no bounces, no staggered entrances, and no state transition over 220ms. Looping animation is only for activity that is really happening (spinners, progress, loading shimmer, a running pulse, the caret), never decoration.",
|
||||
"**Don't** put shadows on docked panels, islands, rows or controls.",
|
||||
"**Don't** use sizes off the 11/12/13/15px scale, or hard-code a font size users can change.",
|
||||
"**Don't** use hex, `rgb()` or named colours in component CSS or inline styles.",
|
||||
"**Don't** use emoji as icons or decoration, or inline ad-hoc SVG in a feature."
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -9,7 +9,6 @@
|
||||
"dist",
|
||||
"target",
|
||||
"src/bindings.ts",
|
||||
"docs/snippets/plugin-catalog.jsx",
|
||||
"evals/*/golden",
|
||||
"src/editor/core/cm/angular/parser*.ts",
|
||||
"src/editor/core/cm/jsp/parser*.ts",
|
||||
|
||||
@@ -147,32 +147,6 @@
|
||||
"prefer-rest-params": "error",
|
||||
"prefer-spread": "error"
|
||||
}
|
||||
},
|
||||
{
|
||||
"files": [
|
||||
"evals/**/*.ts",
|
||||
"perf/**/*.ts",
|
||||
"smoke/**/*.ts",
|
||||
"src/features/vcs/**/*.ts",
|
||||
"src/features/vcs/**/*.tsx",
|
||||
"src/features/run/**/*.ts",
|
||||
"src/features/run/**/*.tsx",
|
||||
"src/features/database/**/*.ts",
|
||||
"src/features/database/**/*.tsx",
|
||||
"src/features/analysis/**/*.ts",
|
||||
"src/features/analysis/**/*.tsx",
|
||||
"src/features/project-tree/**/*.ts",
|
||||
"src/features/project-tree/**/*.tsx",
|
||||
"src/features/http-client/**/*.ts",
|
||||
"src/features/http-client/**/*.tsx",
|
||||
"src/platform/**/*.ts",
|
||||
"src/platform/**/*.tsx",
|
||||
"src/features/debugger/**/*.ts",
|
||||
"src/features/debugger/**/*.tsx"
|
||||
],
|
||||
"rules": {
|
||||
"no-await-in-loop": "error"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
# 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`
|
||||
(thin typed IPC adapters), `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.
|
||||
- Streaming → `tauri::ipc::Channel<T>`; cancellable → UI-allocated `RequestId` +
|
||||
`cancel_request`. Backend → UI notifications → `IdeEvent` via `EventSink`.
|
||||
- Long work never blocks the UI thread or a Tauri command thread: use
|
||||
`spawn_blocking`/rayon, honour `CancellationToken`.
|
||||
- Frontend features never import each other; communicate via actions, contributions
|
||||
and services. All user-invocable behaviour is an action with a stable id; default
|
||||
shortcuts live in `src/platform/keymaps/`.
|
||||
- Styling: CSS Modules + tokens only (no hex literals in components). Inline SVG
|
||||
icons from `src/ui/icons.tsx`, never emoji. Real `<button>`/`<input>`; `aria-label` on icon buttons.
|
||||
`gap` uses the `--space-*` scale (`src/styles/tokens.css`, 4px grid) where a value is on it.
|
||||
- User-visible text goes through the text catalog: add every new string to both
|
||||
`src/platform/locales/text/en.json` and `zh.json` (`textCatalog.test.ts` enforces it).
|
||||
Other locales may lack entries; their UI shows the English text until a translator adds it.
|
||||
- Keep comments sparse and purposeful; match surrounding style.
|
||||
- For GUI verification, prefer Tauri MCP; use Computer Use only when Tauri MCP is
|
||||
unavailable or cannot cover the required checks.
|
||||
|
||||
## Issues & PRs
|
||||
|
||||
Follow `CONTRIBUTING.md` and `.github/pull_request_template.md`: one problem per PR
|
||||
(`Closes #<n>` when it resolves an issue), reproduce first, keep the diff focused, short plain description, and a
|
||||
**How it was verified** section with commands run, results and, when the change alters what users
|
||||
see, before/after screenshots (not for UI removed along with a feature, copy-only or non-visual changes).
|
||||
Unclear product decisions → `needs-decision` and stop.
|
||||
|
||||
## Skills
|
||||
|
||||
Do not use Impeccable or its related skills in this repository, including globally installed copies.
|
||||
|
||||
Shared agent skills live in `.agents/skills/` (`.claude/skills/` links to them):
|
||||
`verify` drives the running app through Tauri MCP and captures screenshot evidence;
|
||||
`issue-fix` takes an issue from reproduction to one PR;
|
||||
`eval` takes a failing code-intelligence eval to a fix with before / after numbers.
|
||||
|
||||
## Commands
|
||||
|
||||
- `pnpm tauri dev` — run the app with worktree isolation (Node 22.18+).
|
||||
`pnpm dev:app` also enables the global Tauri API. `pnpm dev:status` reports
|
||||
this worktree's running MCP bridges and actual ports.
|
||||
- `pnpm build` — typecheck + bundle frontend.
|
||||
- `cargo nextest run --workspace` (or `cargo test`), `cargo clippy --workspace --all-targets -- -D warnings`, `cargo fmt --all`.
|
||||
- `cargo test -p ide-host --test language_smoke -- --ignored --exact <language>` — code intelligence
|
||||
on `fixtures/` with that language's real server installed (CI: `Language smoke`, pinned versions).
|
||||
- `pnpm smoke smoke/run.test.ts -t <language>` — run and test that language's fixture through the
|
||||
run store and a real `openidea-server` (build it first: `cargo build -p ide-host --bin openidea-server`).
|
||||
- `pnpm smoke smoke/debug.test.ts -t <language>` — debug that fixture's entry point the same way, with
|
||||
the debugger the IDE installs (on macOS, CodeLLDB and Delve may need Developer Mode:
|
||||
`sudo DevToolsSecurity -enable`).
|
||||
- `pnpm test`, `pnpm e2e`, `pnpm lint`, `pnpm format:check`, `pnpm knip`, `pnpm typecheck`,
|
||||
`pnpm gen:bindings`.
|
||||
- `pnpm perf` (UI interaction latency / frames / leaks), `pnpm perf:rust` (criterion
|
||||
benches vs budgets). Budgets: `perf/budgets.json`.
|
||||
- `pnpm eval [--only <id>] [--runs n] [--save-baseline]` — Java code intelligence (navigation,
|
||||
usages, gutter markers) in the production workbench against a release `openidea-server` and
|
||||
jdtls: time to feedback / first result / complete, results vs `evals/<language>/golden/`.
|
||||
Report: `target/eval/report.json`. Goldens and `evals/budgets.json` are changed by people only.
|
||||
Tool versions: `.github/tool-versions.env` (shared with Language smoke).
|
||||
- `pnpm release:prepare <version>` — the release commit's changes: app version everywhere,
|
||||
`Cargo.lock`, and the plugin API snapshot when `wit/` moved to a new version.
|
||||
|
||||
## Before opening a PR
|
||||
|
||||
Run what CI runs for the parts you touched:
|
||||
|
||||
- Rust: `cargo fmt --all --check`, `cargo clippy --workspace --all-targets -- -D warnings`,
|
||||
`cargo nextest run --workspace`. After changing IPC types, run `pnpm gen:bindings` and
|
||||
commit `src/bindings.ts`; CI fails if it differs.
|
||||
- Frontend: `pnpm typecheck`, `pnpm lint`, `pnpm format:check`, `pnpm knip`, `pnpm test`,
|
||||
`pnpm build`, and `pnpm e2e` for UI flows.
|
||||
- UI or runtime behaviour: verify in the running app (`.agents/skills/verify`).
|
||||
|
||||
## Pitfalls
|
||||
|
||||
- Run a subset of frontend tests with `pnpm vitest run <path>`. `pnpm test -- <path>` ignores
|
||||
the filter and runs the whole suite, which takes several minutes.
|
||||
- Don't run clippy while iterating: `pnpm tauri dev` compiles anyway. Run
|
||||
`cargo fmt --all` + `cargo clippy -p <crate> --all-targets -- -D warnings` once, right
|
||||
before committing. A cold build cache can take around 5 minutes. Run long checks one at
|
||||
a time, not chained in one shell call that may hit the 10-minute tool timeout.
|
||||
- `pnpm tauri dev` does a full debug build. Clippy only checks the code, so a passing clippy
|
||||
doesn't make the first launch fast.
|
||||
|
||||
## Parallel worktrees
|
||||
|
||||
Several worktrees can be developed and run side by side.
|
||||
|
||||
- Create one per task: `git worktree add ../<name> -b <branch> origin/main`, then
|
||||
`pnpm install` in it.
|
||||
- Launch with `pnpm tauri dev` / `pnpm dev:app`, not the raw `pnpm exec tauri dev` CLI. The
|
||||
wrapper starts Vite on a worktree-derived port (advancing if occupied), passes its actual
|
||||
URL to Tauri, and reports an existing launcher instead of starting another for the same
|
||||
worktree. HMR uses the Vite port.
|
||||
- Debug app identity, data, settings, logs and single-instance scope follow the canonical
|
||||
worktree path captured at build time, independent of launch cwd. Launching the same debug
|
||||
binary again focuses its existing instance and forwards its path argument. Different
|
||||
worktrees and the installed release can coexist. `--release` uses normal release identity
|
||||
and bypasses the development wrapper.
|
||||
- MCP bridge ports are dynamic (9223–9322). Use `pnpm dev:status`, connect to the reported
|
||||
port, verify identifier/cwd, and pass `appIdentifier: <port>` explicitly. Do not assume the
|
||||
default MCP session belongs to this worktree.
|
||||
- Keep each worktree's Cargo output directory separate; do not point `CARGO_TARGET_DIR` or
|
||||
`target` symlinks at a shared directory.
|
||||
- Each worktree's first build is cold (several minutes) and `cargo build` output takes
|
||||
around 9 GB; tests, clippy and incremental builds add more. Avoid running several heavy builds on one machine at the same time.
|
||||
- Stop only processes started for the current worktree/session. Never use broad
|
||||
process-name kills such as `pkill openidea`.
|
||||
- When done: stop that worktree's app and dev session, delete its build output, then
|
||||
`git worktree remove ../<name>`.
|
||||
@@ -1,6 +1,7 @@
|
||||
# Contributing to OpenIDEA
|
||||
|
||||
These rules apply to everyone, and to any coding agent working on their behalf.
|
||||
Project layout, coding rules, commands and checks are in [AGENTS.md](AGENTS.md).
|
||||
|
||||
## Issues
|
||||
|
||||
|
||||
Generated
+148
-195
File diff suppressed because it is too large.
Load diff
+3
-10
@@ -5,7 +5,7 @@ members = ["crates/*", "src-tauri"]
|
||||
exclude = ["sdk", "plugins"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.1.51"
|
||||
version = "0.1.45"
|
||||
edition = "2024"
|
||||
rust-version = "1.96"
|
||||
license = "Apache-2.0"
|
||||
@@ -38,12 +38,10 @@ ide-web = { path = "crates/ide-web" }
|
||||
ide-spell = { path = "crates/ide-spell" }
|
||||
ide-agent = { path = "crates/ide-agent" }
|
||||
ide-clipboard = { path = "crates/ide-clipboard" }
|
||||
ide-drag-out = { path = "crates/ide-drag-out" }
|
||||
ide-fonts = { path = "crates/ide-fonts" }
|
||||
ide-ssh = { path = "crates/ide-ssh" }
|
||||
ide-remote = { path = "crates/ide-remote" }
|
||||
ide-host = { path = "crates/ide-host" }
|
||||
ide-command = { path = "crates/ide-command" }
|
||||
ide-mcp = { path = "crates/ide-mcp" }
|
||||
ide-scaffold = { path = "crates/ide-scaffold" }
|
||||
ide-notebook = { path = "crates/ide-notebook" }
|
||||
@@ -54,7 +52,6 @@ ide-jvm-attach = { path = "crates/ide-jvm-attach" }
|
||||
ide-jvm-inspect = { path = "crates/ide-jvm-inspect" }
|
||||
ide-jdwp = { path = "crates/ide-jdwp" }
|
||||
ide-heap = { path = "crates/ide-heap" }
|
||||
ide-streams = { path = "crates/ide-streams" }
|
||||
|
||||
# serialization & IPC typing
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
@@ -69,11 +66,13 @@ tokio = { version = "1", features = ["rt-multi-thread", "macros", "sync", "time"
|
||||
tokio-util = { version = "0.7", features = ["rt"] }
|
||||
parking_lot = "0.12"
|
||||
rayon = "1"
|
||||
dashmap = "6"
|
||||
futures = "0.3"
|
||||
tokio-tungstenite = { version = "0.28", default-features = false, features = ["connect", "__rustls-tls"] }
|
||||
|
||||
# errors & diagnostics
|
||||
thiserror = "2"
|
||||
anyhow = "1"
|
||||
tracing = "0.1"
|
||||
tracing-subscriber = { version = "0.3", features = ["env-filter", "fmt"] }
|
||||
|
||||
@@ -124,12 +123,6 @@ uuid = { version = "1", features = ["v4"] }
|
||||
keyring = "4.2"
|
||||
keyring-core = "1"
|
||||
|
||||
# proc macros
|
||||
heck = "0.5"
|
||||
proc-macro2 = "1"
|
||||
quote = "1"
|
||||
syn = { version = "2", features = ["full"] }
|
||||
|
||||
# testing
|
||||
insta = { version = "1", features = ["yaml"] }
|
||||
proptest = "1"
|
||||
|
||||
@@ -1,323 +0,0 @@
|
||||
---
|
||||
name: OpenIDEA
|
||||
description: The IDE you know, rebuilt in Rust.
|
||||
colors:
|
||||
workbench-blue: "#3871e1"
|
||||
link-blue: "#2f5eb9"
|
||||
frame-grey: "#e9eaee"
|
||||
island-white: "#ffffff"
|
||||
raised-paper: "#f7f8f9"
|
||||
ink: "#000000"
|
||||
ink-secondary: "#5f6269"
|
||||
ink-muted: "#6c707e"
|
||||
ink-faint: "#9fa2a8"
|
||||
hairline: "#e9eaee"
|
||||
control-edge: "#d1d3d9"
|
||||
selection-wash: "#d0dffe"
|
||||
tab-wash: "#e3ebfe"
|
||||
danger: "#c54e58"
|
||||
warning: "#a56906"
|
||||
success: "#338555"
|
||||
frame-grey-dark: "#26282c"
|
||||
island-dark: "#191a1c"
|
||||
ink-dark: "#d1d3d9"
|
||||
ink-strong-dark: "#dfe1e5"
|
||||
ink-muted-dark: "#8c8f95"
|
||||
control-edge-dark: "#40434a"
|
||||
selection-wash-dark: "#2a4371"
|
||||
typography:
|
||||
title:
|
||||
fontFamily: "Inter Variable, Inter, system-ui, -apple-system, sans-serif"
|
||||
fontSize: "13px"
|
||||
fontWeight: 600
|
||||
lineHeight: 1.4
|
||||
body:
|
||||
fontFamily: "Inter Variable, Inter, system-ui, -apple-system, sans-serif"
|
||||
fontSize: "13px"
|
||||
fontWeight: 400
|
||||
lineHeight: 1.4
|
||||
label:
|
||||
fontFamily: "Inter Variable, Inter, system-ui, -apple-system, sans-serif"
|
||||
fontSize: "12px"
|
||||
fontWeight: 400
|
||||
lineHeight: 1.4
|
||||
label-tiny:
|
||||
fontFamily: "Inter Variable, Inter, system-ui, -apple-system, sans-serif"
|
||||
fontSize: "11px"
|
||||
fontWeight: 400
|
||||
lineHeight: 1.4
|
||||
input-large:
|
||||
fontFamily: "Inter Variable, Inter, system-ui, -apple-system, sans-serif"
|
||||
fontSize: "15px"
|
||||
fontWeight: 400
|
||||
code:
|
||||
fontFamily: "JetBrains Mono, JetBrains Mono Variable, ui-monospace, Menlo, monospace"
|
||||
fontSize: "13px"
|
||||
fontWeight: 400
|
||||
lineHeight: "22px"
|
||||
fontFeature: "\"liga\" 0"
|
||||
rounded:
|
||||
small: "4px"
|
||||
control: "4px"
|
||||
row: "4px"
|
||||
selection: "5px"
|
||||
tab: "6px"
|
||||
toolbar-button: "6px"
|
||||
tooltip: "6px"
|
||||
popup: "8px"
|
||||
island: "10px"
|
||||
popup-large: "10px"
|
||||
dialog: "10px"
|
||||
spacing:
|
||||
space-0-5: "2px"
|
||||
space-1: "4px"
|
||||
space-1-5: "6px"
|
||||
space-2: "8px"
|
||||
space-3: "12px"
|
||||
space-4: "16px"
|
||||
components:
|
||||
button-primary:
|
||||
backgroundColor: "{colors.workbench-blue}"
|
||||
textColor: "{colors.island-white}"
|
||||
typography: "{typography.body}"
|
||||
rounded: "{rounded.control}"
|
||||
padding: "0 16px"
|
||||
height: "28px"
|
||||
button-secondary:
|
||||
backgroundColor: "{colors.island-white}"
|
||||
textColor: "{colors.ink}"
|
||||
typography: "{typography.body}"
|
||||
rounded: "{rounded.control}"
|
||||
padding: "0 16px"
|
||||
height: "28px"
|
||||
button-ghost:
|
||||
textColor: "{colors.ink-secondary}"
|
||||
typography: "{typography.body}"
|
||||
rounded: "{rounded.control}"
|
||||
padding: "0 8px"
|
||||
height: "28px"
|
||||
icon-button:
|
||||
textColor: "{colors.ink-muted}"
|
||||
rounded: "{rounded.toolbar-button}"
|
||||
size: "24px"
|
||||
icon-button-selected:
|
||||
backgroundColor: "{colors.selection-wash}"
|
||||
textColor: "{colors.ink}"
|
||||
rounded: "{rounded.toolbar-button}"
|
||||
size: "24px"
|
||||
input:
|
||||
backgroundColor: "{colors.island-white}"
|
||||
textColor: "{colors.ink}"
|
||||
typography: "{typography.body}"
|
||||
rounded: "{rounded.control}"
|
||||
padding: "0 8px"
|
||||
height: "28px"
|
||||
chip:
|
||||
textColor: "{colors.ink-secondary}"
|
||||
typography: "{typography.label}"
|
||||
rounded: "{rounded.toolbar-button}"
|
||||
padding: "0 6px"
|
||||
height: "22px"
|
||||
tooltip:
|
||||
backgroundColor: "{colors.island-white}"
|
||||
textColor: "{colors.ink}"
|
||||
typography: "{typography.body}"
|
||||
rounded: "{rounded.tooltip}"
|
||||
padding: "6px 10px"
|
||||
list-row-selected:
|
||||
backgroundColor: "{colors.selection-wash}"
|
||||
textColor: "{colors.ink}"
|
||||
rounded: "{rounded.row}"
|
||||
height: "24px"
|
||||
---
|
||||
|
||||
# Design System: OpenIDEA
|
||||
|
||||
## Overview
|
||||
|
||||
**Creative North Star: "The Quiet Workbench"**
|
||||
|
||||
The interface is a workbench, not a showroom. Code, trees, logs and diffs are the work. The chrome around them stays quiet, so the eye goes to the content and a long session stays calm.
|
||||
|
||||
The visual language is the JetBrains new UI in its **Islands** form, and this document records it rather than inventing one. The tokens in `src/styles/tokens.css` take their values from the Islands Light and Islands Dark theme JSON and editor schemes, at 100% zoom. Component metrics follow the matching IntelliJ theme keys (a Swing `arc` is a diameter, so the CSS radius is half of it), and component CSS names the key it follows. Behaviour follows IDEA as well, from focus and selection to dialogs and drag and drop. Users bring their JetBrains muscle memory, so a layout, metric or state that looks or behaves differently from IDEA counts as a bug, not a style choice.
|
||||
|
||||
Every panel sits on a grey frame as a rounded island (10px corners, 6px gaps). Depth comes from that tonal step, not from decoration. The density is that of a professional desktop tool: 13px UI text, 24px rows, 28px controls, with a compact mode that tightens all of them.
|
||||
|
||||
The tokens are a theming contract, not one palette. The built-in themes are Islands Light (the default), Islands Dark, High Contrast, Solarized Light and Solarized Dark. Users can also change the accent colour, give tool windows a different background from the editor, set a background image, use contrast scrollbars, or adjust colours for red-green vision deficiency. Imported IntelliJ themes and plugin themes set the same tokens at runtime. A component that looks right only in Islands Light is broken.
|
||||
|
||||
Expression is kept to precise details: one blue accent, controls with no frame until they're hovered, hairline frames on fields and secondary buttons, and fast state transitions. Three things are rejected outright. It must not look like a web app: no big rounded cards, airy marketing whitespace, decorative gradients or illustrations. It has no second accent colour. And it has no eye-catching animation.
|
||||
|
||||
### Named Rules
|
||||
|
||||
**The IDEA Reference Rule.** When tokens and this document don't answer a question, the answer is what IntelliJ IDEA does in the Islands theme, with the same metric and the same state behaviour. Take the value from the theme key, add it as a token, and name the key in a CSS comment.
|
||||
|
||||
**Key Characteristics:**
|
||||
|
||||
- JetBrains new UI (Islands): metrics and behaviour follow IntelliJ's theme keys.
|
||||
- Grey frame, rounded content islands, tonal layering only.
|
||||
- A single accent (Workbench Blue) for primary actions, focus, selection and the active tool window.
|
||||
- High density on a 4px grid. Compact mode is a first-class variant.
|
||||
- Controls are quiet at rest: toolbar buttons and chips have no frame until hover.
|
||||
- Semantic colour (status, VCS, diff, syntax) carries meaning and is never decoration.
|
||||
- Every colour and metric is a token in `src/styles/tokens.css`. Tokens are the public theme API for plugins.
|
||||
|
||||
## Colors
|
||||
|
||||
A near-neutral grey ramp with one cool blue accent. Status, VCS and syntax colours are functional vocabularies with fixed meanings. Values in the frontmatter are Islands Light (the default), and `-dark` keys are the Islands Dark counterparts. High Contrast, the Solarized themes, imported IntelliJ themes and plugin themes override the same tokens, so the names describe roles, not hexes.
|
||||
|
||||
### Project colour
|
||||
|
||||
- **Project wash** (`--project-color`): a radial tint of the project's colour (22% strength, 600 × 300px) that fades in from the frame's top-left corner, as the IDEA project gradient does. It identifies the project window. It is the one gradient in the chrome.
|
||||
|
||||
### Primary
|
||||
|
||||
- **Workbench Blue** (`--accent`): primary buttons, the focus ring, the selected-and-active stripe button, and search-match emphasis. The appearance setting can override it, so components reference `--accent`, never the hex.
|
||||
- **Link Blue** (`--link`): inline links. In Dark it lightens to stay readable on the dark islands.
|
||||
|
||||
### Neutral
|
||||
|
||||
- **Frame Grey** (`--bg-frame`): the window frame behind the islands, and the stripes (the tool window button bars).
|
||||
- **Island White** (`--bg-island`, `--bg-app`): editor and tool window surfaces. This is where the work lives.
|
||||
- **Raised Paper** (`--bg-elev`, `--bg-dialog`): dialog bodies and inline popups, one tonal step off the island.
|
||||
- **Ink** (`--fg`, `--fg-strong`): primary text. **Ink Secondary / Muted / Faint** (`--fg-secondary`, `--fg-muted`, `--fg-faint`): metadata, icons and placeholders, then disabled text.
|
||||
- **Hairline** (`--border`): dividers between regions inside an island. **Control Edge** (`--border-button`, `--border-strong`): the 1px inset frame of fields and secondary buttons.
|
||||
- **Selection Wash** (`--bg-tree-selected`, `--bg-selected`, `--bg-toolbar-selected`): the selected row in focused trees and lists, and pressed-on toolbar toggles. When the tree loses focus, the selection drops to the neutral `--bg-tree-selected-inactive`.
|
||||
|
||||
### Functional vocabularies
|
||||
|
||||
- **Status:** `--danger`, `--warning`, `--success` and `--info`, each with `--bg-feedback-*` and `--border-feedback-*` pairs for banners.
|
||||
- **VCS and diff:** `--vcs-*` for file status in trees and tabs, `--gutter-*` for gutter marks, and `--diff-*` for diff fills and their error-stripe marks.
|
||||
- **Syntax:** `--syn-*`, from the editor colour scheme. Users and plugins replace these per scheme.
|
||||
|
||||
### Named Rules
|
||||
|
||||
**The One Accent Rule.** Workbench Blue is the only accent. Every other hue in the UI belongs to a functional vocabulary (status, VCS, diff, syntax, charts) and means something specific. If a new colour has no meaning to carry, it doesn't ship.
|
||||
|
||||
**The Token Only Rule.** Components never contain hex, `rgb()` or named colour literals. A new colour is a new token with a value in every theme variant, named for its purpose. Run `pnpm gen:theme-docs` afterwards.
|
||||
|
||||
## Typography
|
||||
|
||||
**UI Font:** Inter Variable (with system-ui and -apple-system fallbacks)
|
||||
**Code Font:** JetBrains Mono (with ui-monospace and Menlo fallbacks)
|
||||
**Key Glyph Font:** the system UI font (`--font-keys`), so shortcut glyphs such as ⌘⇧⌥⌃↵ render as they do in native menus
|
||||
|
||||
**Character:** a neutral sans for chrome and a coding mono for content. Neither performs. Hierarchy comes from weight and colour, not size.
|
||||
|
||||
### Hierarchy
|
||||
|
||||
- **Title** (600, 13px, 1.4): tool window titles, section headers, dialog titles and emphasised names. Weight 600 is the system's main emphasis.
|
||||
- **Body** (400, 13px, 1.4): default UI text, menus, tree and list rows, and buttons.
|
||||
- **Label** (400, 12px): the most common size. It covers secondary metadata, chips, status bar items, table cells and hints.
|
||||
- **Label Tiny** (400, 11px): stripe labels, counters and badges.
|
||||
- **Input Large** (400, 15px): Search Everywhere and similar large query fields.
|
||||
- **Code** (400, 13px, 22px line height): the editor, console, terminal and every monospace preview. Ligatures are off by default and follow the `editor.ligatures` setting. Users set the weights (`--fw-code`, `--fw-code-bold`) and the size.
|
||||
|
||||
### Named Rules
|
||||
|
||||
**The Flat Scale Rule.** The UI uses 11, 12, 13 and 15px, and nothing in between. Emphasis is weight 600 or a stronger ink colour, not a bigger size.
|
||||
|
||||
**The User Owns Size Rule.** Sizes are tokens because users change them (UI font size, editor font, compact mode's -1px chrome offset). Never hard-code a font size.
|
||||
|
||||
## Layout
|
||||
|
||||
The window is a grey frame holding docked islands: the editor in the centre, tool windows around it, stripes of tool window buttons on the edges (58px wide), a titlebar with the main toolbar (40px), and a status bar (30px). The status bar sits directly on the frame with no divider. Islands sit 6px apart and have 10px corners. Trees are inset 6px inside their island.
|
||||
|
||||
Spacing follows a 4px grid (`--space-0-5` to `--space-4`, 2–16px). It is used for gaps, with component heights doing most of the rhythm work: rows 24px, fields and buttons 28px, small controls 24px or 20px, tabs 28px in a 38px tab bar, and tool window headers 40px.
|
||||
|
||||
**Compact mode** (`data-compact`) is a full variant, not an afterthought. Rows drop to 22px, fields and buttons to 24px, the titlebar and headers to 32px, the status bar to 24px, the island gap to 4px and island corners to 8px, and chrome text gets 1px smaller. Every layout must hold in both modes.
|
||||
|
||||
The app is a desktop window. It is never a scrolling page: the document never scrolls, and every scroll region is its own scroller inside an island. Dialogs open about 10vh from the top and below the titlebar. Wide reading surfaces, such as an agent conversation, cap their width (900px) inside the island.
|
||||
|
||||
## Elevation & Depth
|
||||
|
||||
Static layout is flat and layered by tone. The grey frame sits under white islands (in Dark, a lighter frame under darker islands). Shadows exist only on surfaces that float above the layout: popups, menus, dialogs, tooltips, balloons, undocked tool windows and drag ghosts. Dialogs use a window-style shadow, because they are separate windows in spirit.
|
||||
|
||||
### Shadow Vocabulary
|
||||
|
||||
- **Popup** (`--shadow-popup`; Light `0 6px 20px rgba(0,0,0,0.12)`): popups, menus, completion and the floating editor toolbar.
|
||||
- **Dialog** (`--shadow-dialog`): a hairline ring plus two soft drops, like a native window shadow.
|
||||
- **Tooltip** (`--shadow-tooltip`) and **Balloon** (`--shadow-balloon`): small and medium drops for hover help and notifications.
|
||||
|
||||
### Named Rules
|
||||
|
||||
**The Flat at Rest Rule.** No docked panel, island, row or control gets a shadow. A shadow means "this floats over the workbench and will go away". Depth inside the layout is only ever a tonal step.
|
||||
|
||||
## Shapes
|
||||
|
||||
Corners scale with the size of the surface. Small controls get 4px (buttons, fields, combos, rows, small icon buttons). Toolbar buttons, chips, tabs and tooltips get 6px, and selection highlights get 5px. Popups get 8–10px, and islands and dialogs get 10px. Compact mode tightens island corners to 8px and combo corners to 2px. Frames are drawn as 1px inset box-shadows rather than borders, so they never shift layout and can double on focus. There are no pills, circles (apart from macOS window buttons and status dots), or rounding beyond 10px.
|
||||
|
||||
## Components
|
||||
|
||||
Quiet and dependable. Components don't call attention to themselves, they behave the same everywhere, and they come from `src/ui/` primitives before anything custom.
|
||||
|
||||
### Buttons
|
||||
|
||||
- **Shape:** gently rounded (4px). Minimum width 72px, 28px tall, 16px horizontal padding. The small variant is 24px tall with 10px padding.
|
||||
- **Primary:** Workbench Blue fill with white text. Hover mixes it toward the strong ink colour (`--accent-hover`). Use it for one default action per dialog.
|
||||
- **Secondary:** island-coloured with a 1px Control Edge inset frame. Hover darkens the fill by about 6%.
|
||||
- **Ghost:** no fill or frame, secondary ink colour, 8px padding. Hover shows the toolbar hover wash and strong ink. Pressed is a stronger wash.
|
||||
- **Focus:** a 2px Workbench Blue outline, 1px outside the button. **Disabled:** transparent fill, faint text and a hairline frame.
|
||||
- **Motion:** background, colour and frame change over 80ms (`--dur-fast`) with `--ease`. There are no transitions under `prefers-reduced-motion`, and forced-colours mode gets a real border.
|
||||
|
||||
### Icon Buttons (toolbar actions)
|
||||
|
||||
- 20, 24 or 28px square, with 6px corners (4px at 20px). The icon is muted at rest.
|
||||
- Hover shows the toolbar hover wash (`--bg-toolbar-hover`, a translucent ink) across the full hit target, and the icon turns strong ink. Pressed shows `--bg-toolbar-pressed`.
|
||||
- A toggled-on button (`aria-pressed`) shows Selection Wash. The focus ring is drawn 2px inside the button.
|
||||
- Tone variants (`danger`, `accent`) recolour only the icon.
|
||||
|
||||
### Chips
|
||||
|
||||
- **Style:** flat, like the main toolbar's project and branch widgets. They are 22px tall with 6px corners, have no fill or frame at rest, and use 12px secondary ink with a muted icon.
|
||||
- **State:** a chip that opens a picker gets the toolbar hover wash. A read-only chip never changes on hover.
|
||||
|
||||
### Inputs / Fields
|
||||
|
||||
- **Style:** 28px tall with 8px horizontal padding and 4px corners. Island fill with a 1px Control Edge inset frame. Placeholders use the faint ink.
|
||||
- **Focus:** the frame turns Workbench Blue and doubles with a 1px outer ring, drawn entirely with box-shadow.
|
||||
- **Error:** the same doubled ring in `--danger`. **Disabled:** transparent fill, faint text and a hairline frame.
|
||||
- Search fields have a muted leading icon. Monospace fields use the code font.
|
||||
|
||||
### Lists and Trees
|
||||
|
||||
- Rows are 24px (22px compact). The selection is a 4–5px rounded wash inset from the island edge, not a full-bleed bar.
|
||||
- A focused selection uses Selection Wash, and an unfocused one drops to a neutral grey. Hover is a faint translucent wash. Search matches use `--bg-search-match`.
|
||||
|
||||
### Popups, Menus and Dialogs
|
||||
|
||||
- **Popups and menus:** `--bg-popup` with a 1px popup frame, 10px corners (`--radius-popup-large`) and the popup shadow.
|
||||
- **Dialogs:** Raised Paper body with 10px corners and the dialog shadow. They behave like IDEA's dialogs, which are separate windows: the modal layer blocks the workbench but never dims it. The footer actions are right-aligned buttons. Focus returns to wherever it came from when the dialog closes.
|
||||
|
||||
### Tabs
|
||||
|
||||
- 28px tabs (24px compact) in a 38px bar, with 6px corners and 8px horizontal padding.
|
||||
- As in IDEA, only the part holding focus accents its selected tab (`--bg-tab-selected` with `--border-tab-selected`). Elsewhere the selected tab drops to the neutral inactive pair.
|
||||
- **Tooltips:** 6px corners with 6px × 10px padding, using `--bg-tooltip` (white in Light, dark grey in Dark) and the tooltip shadow.
|
||||
|
||||
### Tool Window Stripes (signature)
|
||||
|
||||
The edge bars of tool window buttons are 58px wide on Frame Grey, with icons over 11px labels. Hover and selected states are translucent ink washes. The selected button of the active tool window fills with Workbench Blue and white content. This is the one place the accent fills a large shape in the chrome, and it marks the active tool window.
|
||||
|
||||
## Do's and Don'ts
|
||||
|
||||
### Do:
|
||||
|
||||
- **Do** match IntelliJ IDEA's Islands theme for any metric or state that isn't tokenized yet. Take the value from the theme key and name the key in a CSS comment (for example `Button.arc 8 (radius 4)`).
|
||||
- **Do** take every colour and metric from `src/styles/tokens.css`, and add a token for every theme variant when you need a new one.
|
||||
- **Do** separate regions with a tonal step (frame against island) or a 1px hairline, never with a shadow.
|
||||
- **Do** keep toolbar buttons and chips without a frame at rest, with the toolbar hover wash over the full hit target.
|
||||
- **Do** draw frames and focus rings as inset box-shadows (1px at rest, doubled on focus), and keep the 2px Workbench Blue focus outline visible.
|
||||
- **Do** check every surface in Islands Light and Islands Dark at least, as the contribution guidelines require. Check High Contrast and compact density whenever a change touches colour or metrics.
|
||||
- **Do** keep transitions to state changes: 80ms (`--dur-fast`), 140ms (`--dur`) or at most 220ms (`--dur-slow`) with `--ease`, and none under reduced motion.
|
||||
- **Do** use icons from the `src/ui/icons.tsx` registry, drawn in `currentColor`.
|
||||
|
||||
### Don't:
|
||||
|
||||
- **Don't** make it look like a web app: no large rounded cards, airy marketing whitespace, decorative gradients, hero illustrations or corners above 10px. The project wash is the one gradient in the chrome. Progress shimmer counts as activity, not decoration.
|
||||
- **Don't** invent a look or behaviour where IDEA already has one. A custom variant of an IDEA pattern breaks muscle memory.
|
||||
- **Don't** add a second accent. Any hue other than Workbench Blue must carry status, VCS, diff, syntax or chart meaning.
|
||||
- **Don't** add attention-seeking animation: no bounces, no staggered entrances, and no state transition over 220ms. Looping animation is only for activity that is really happening (spinners, progress, loading shimmer, a running pulse, the caret), never decoration.
|
||||
- **Don't** put shadows on docked panels, islands, rows or controls.
|
||||
- **Don't** use sizes off the 11/12/13/15px scale, or hard-code a font size users can change.
|
||||
- **Don't** use hex, `rgb()` or named colours in component CSS or inline styles.
|
||||
- **Don't** use emoji as icons or decoration, or inline ad-hoc SVG in a feature.
|
||||
-73
@@ -1,73 +0,0 @@
|
||||
# Product
|
||||
|
||||
<!-- impeccable:product-schema 1 -->
|
||||
|
||||
## Platform
|
||||
|
||||
web
|
||||
|
||||
The IDE is a Tauri desktop app for macOS, Windows and Linux. Its UI is a web frontend (React, CSS Modules) inside the system webview, with its own design language rather than each operating system's native one. Scope: this record covers the IDE application only. The openidea.sh docs site and home page (`docs/`) are out of scope.
|
||||
|
||||
## Users
|
||||
|
||||
- **Primary: JetBrains users who want something lighter.** They already know the IntelliJ IDEA keymap, tool windows and search-everything habits, and find IDEA heavy and slow. They do everyday multi-language development on the desktop: editing, navigating, refactoring, running and debugging, Git, terminal, database and HTTP clients.
|
||||
- **Primary: developers working with AI coding agents.** They run CLI agents (Claude Code, Codex, Gemini CLI, Copilot, Cursor and others over ACP) inside the IDE as tasks, often several at once, each in its own Git worktree or in the checkout. They review the agents' diffs, answer their permission requests, and give agents the IDE's own tools through the built-in MCP server.
|
||||
- **Secondary: people moving from VS Code or Eclipse.** Their keymaps are built in.
|
||||
|
||||
## Product Purpose
|
||||
|
||||
OpenIDEA brings the IntelliJ IDEA way of working to a native app with a Rust core: editor, code insight, debugger, Git, terminal, database and HTTP clients for 60+ languages. Success means people who know the IDEA way of working can switch without relearning anything, and it opens, responds and quits much faster while using a fraction of the memory.
|
||||
|
||||
## Positioning
|
||||
|
||||
"The IDE you know, rebuilt in Rust." The habits are familiar (keymap, tool windows, Search Everywhere, Alt+Enter), the app is open source (Apache 2.0), and performance is measured: on the published benchmark, the window opens in 0.9 s against 3.1 s and the app uses 169 MB against 2011 MB. Coding agents are part of the IDE (tasks, worktrees, diffs and the IDE's tools over MCP) rather than a separate chat app.
|
||||
|
||||
## Operating Context
|
||||
|
||||
- Long sessions in one desktop window: the editor in the middle, tool windows docked around it, and keyboard-first navigation (Search Everywhere, Find Action, Go to Class/File/Symbol).
|
||||
- Local projects, and remote development over SSH or in dev containers through the `openidea-server` backend.
|
||||
- Agent tasks running alongside the developer's own work, with diff review and permission prompts.
|
||||
- Built-in themes: Islands Light (the default), Islands Dark, High Contrast, Solarized Light and Solarized Dark, with an option to follow the OS's light or dark mode. Users can import IntelliJ themes and `.icls` colour schemes, and plugins add more themes.
|
||||
|
||||
## Capabilities and Constraints
|
||||
|
||||
Hard constraints future work must preserve:
|
||||
|
||||
1. The default keymap and interaction habits stay the same as IDEA's.
|
||||
2. All user-visible text is written in English and must also have a Chinese translation, through the text catalog (`T`, translated `aria-label`).
|
||||
3. WebKit floor is Safari 15.4 (macOS 12). No regex lookbehind or `v` flag, no import attributes, and no newer runtime APIs in startup code. `scripts/check-webkit.ts` enforces this.
|
||||
4. Design tokens in `src/styles/tokens.css` are the public theme API for plugins. Components use tokens only and never colour literals. A new token needs a value for every theme variant, and the docs must be regenerated with `pnpm gen:theme-docs`.
|
||||
5. Every user operation is an action with a stable id, reachable from the keyboard and Find Action, not only by mouse.
|
||||
6. No emoji as icons or decoration, in the UI or in user-visible text. Icons come from the `src/ui/icons.tsx` registry.
|
||||
7. Performance (startup, memory, idle CPU) is the core selling point. UI work must not slow it down.
|
||||
|
||||
Other facts:
|
||||
|
||||
- Plugins are sandboxed WebAssembly components that add actions, completion, quick fixes, tool windows, custom editors, themes, file icons and languages. The plugin API is still a preview.
|
||||
- UI is built from the primitives in `src/ui/` (Button, Dialog, Popup, Menu, List, Tree, Tabs and others). Workbench pieces come from contributions, not custom layout.
|
||||
|
||||
## Brand Commitments
|
||||
|
||||
- Name: OpenIDEA. Wordmarks are in `src-tauri/icons/source/` (`openidea-wordmark.svg` and `openidea-wordmark-dark.svg`).
|
||||
- Not affiliated with JetBrains. IntelliJ IDEA is a trademark of JetBrains s.r.o.
|
||||
- Voice is plain, short and factual. It states measurements with their conditions rather than superlatives.
|
||||
|
||||
## Evidence on Hand
|
||||
|
||||
- Benchmark table and method: `README.md`, `perf/compare`. The conditions are stated with it: freqtrade, warm caches, median of 5 runs, Windows 11, 32-core AMD.
|
||||
- Demo video linked from `README.md`.
|
||||
- No testimonials, customer logos or user counts exist. Do not fabricate them.
|
||||
|
||||
## Product Principles
|
||||
|
||||
1. **Familiar first.** Existing IDEA habits must keep working. New behaviour must not break that muscle memory.
|
||||
2. **Speed is a feature.** Every surface is judged by how much it costs in startup time, memory and responsiveness.
|
||||
3. **Keyboard reachable.** If something can be done, it is an action that can be found and bound.
|
||||
4. **Agents work inside the IDE.** Agent work is reviewed and controlled with the IDE's own tools: diffs, worktrees and permissions.
|
||||
5. **Themeable by contract.** Visual decisions go through tokens that themes and plugins can rely on.
|
||||
|
||||
## Accessibility & Inclusion
|
||||
|
||||
- Use real `<button>` and `<input>` elements or the primitives that render them. Every icon-only button has a translated `aria-label`.
|
||||
- Keep focus visible and predictable. Dialogs and popups return focus to where it came from.
|
||||
- A dark high-contrast theme (`dark-hc`) ships and must be kept working.
|
||||
@@ -68,7 +68,7 @@ the [official plugins](plugins/official). The plugin API is still a preview.
|
||||
- [Discord](https://discord.gg/2Zy4yn7gP) — questions, feedback and release news.
|
||||
- WeChat group — scan to join:
|
||||
|
||||
<img src=".github/assets/wechat-group-4.png" alt="WeChat group QR code" width="200">
|
||||
<img src=".github/assets/wechat-group-3.png" alt="WeChat group QR code" width="200">
|
||||
|
||||
- Contributing: see [CONTRIBUTING.md](CONTRIBUTING.md) and the [contributor docs](https://openidea.sh/en/contribute/setup).
|
||||
|
||||
|
||||
+1
-1
@@ -68,7 +68,7 @@ Eklentileri Ayarlar › Eklentiler (Settings › Plugins) bölümünden kur ya d
|
||||
- [Discord](https://discord.gg/2Zy4yn7gP): sorular, geri bildirim ve sürüm haberleri.
|
||||
- WeChat grubu, katılmak için kodu okut:
|
||||
|
||||
<img src=".github/assets/wechat-group-4.png" alt="WeChat grubu QR kodu" width="200">
|
||||
<img src=".github/assets/wechat-group-3.png" alt="WeChat grubu QR kodu" width="200">
|
||||
|
||||
- Katkıda bulunmak için: [CONTRIBUTING.md](CONTRIBUTING.md) ve [katkıcı belgeleri](https://openidea.sh/en/contribute/setup).
|
||||
|
||||
|
||||
+1
-1
@@ -66,7 +66,7 @@ WebAssembly 组件运行;主题、图标主题和语言无需编写代码。
|
||||
- [Discord](https://discord.gg/2Zy4yn7gP):提问、反馈和版本发布消息。
|
||||
- 微信群,扫码加入:
|
||||
|
||||
<img src=".github/assets/wechat-group-4.png" alt="微信群二维码" width="200">
|
||||
<img src=".github/assets/wechat-group-3.png" alt="微信群二维码" width="200">
|
||||
|
||||
- 参与贡献:参见 [CONTRIBUTING.md](CONTRIBUTING.md) 和[贡献者文档](https://openidea.sh/zh/contribute/setup)。
|
||||
|
||||
|
||||
+2
-71
@@ -4,7 +4,7 @@
|
||||
|
||||
`src/ui/brands/*.svg` use the unmodified logo paths from
|
||||
[Simple Icons](https://github.com/simple-icons/simple-icons), retrieved through
|
||||
Iconify (`simple-icons:angular`, `simple-icons:astro`, `simple-icons:cplusplus`, `simple-icons:dart`, `simple-icons:deepseek`, `simple-icons:django`, `simple-icons:dotnet`, `simple-icons:elixir`, `simple-icons:express`, `simple-icons:fastapi`, `simple-icons:flask`, `simple-icons:flutter`, `simple-icons:go`, `simple-icons:haskell`, `simple-icons:html5`, `simple-icons:kotlin`, `simple-icons:ktor`, `simple-icons:laravel`, `simple-icons:nestjs`, `simple-icons:nextdotjs`, `simple-icons:nodedotjs`, `simple-icons:nuxt`, `simple-icons:openjdk`, `simple-icons:phoenixframework`, `simple-icons:php`, `simple-icons:python`, `simple-icons:quarkus`, `simple-icons:ruby`, `simple-icons:rubyonrails`, `simple-icons:rust`, `simple-icons:scala`, `simple-icons:springboot`, `simple-icons:svelte`, `simple-icons:swift`, `simple-icons:symfony`, `simple-icons:vite`, `simple-icons:zig`) and filled with the brand colors (the standard icon grey for black logos). Licensed under [CC0 1.0 Universal](https://github.com/simple-icons/simple-icons/blob/develop/LICENSE.md).
|
||||
Iconify (`simple-icons:angular`, `simple-icons:astro`, `simple-icons:cplusplus`, `simple-icons:dart`, `simple-icons:django`, `simple-icons:dotnet`, `simple-icons:elixir`, `simple-icons:express`, `simple-icons:fastapi`, `simple-icons:flask`, `simple-icons:flutter`, `simple-icons:go`, `simple-icons:haskell`, `simple-icons:html5`, `simple-icons:kotlin`, `simple-icons:ktor`, `simple-icons:laravel`, `simple-icons:nestjs`, `simple-icons:nextdotjs`, `simple-icons:nodedotjs`, `simple-icons:nuxt`, `simple-icons:openjdk`, `simple-icons:phoenixframework`, `simple-icons:php`, `simple-icons:python`, `simple-icons:quarkus`, `simple-icons:ruby`, `simple-icons:rubyonrails`, `simple-icons:rust`, `simple-icons:scala`, `simple-icons:springboot`, `simple-icons:svelte`, `simple-icons:swift`, `simple-icons:symfony`, `simple-icons:vite`, `simple-icons:zig`) and filled with the brand colors (the standard icon grey for black logos). Licensed under [CC0 1.0 Universal](https://github.com/simple-icons/simple-icons/blob/develop/LICENSE.md).
|
||||
|
||||
## Project Lombok
|
||||
|
||||
@@ -35,8 +35,7 @@ icon set, copied unmodified (some renamed) from JetBrains' open-source repositor
|
||||
→ `maven/`); `plugins/gradle` (`icons/expui/gradle` → `toolwindows/gradle`,
|
||||
`icons/expui/gradleLoadChanges` → `build/gradleLoadChanges`,
|
||||
`icons/expui/gradle`, `icons/gradleSubproject` → `gradle/`);
|
||||
`platform/external-system-impl` (`icons/newui/task` → `externalSystem/task`);
|
||||
`platform/dvcs-impl` (`icons/new/cherryPick` → `vcs/cherryPick`).
|
||||
`platform/external-system-impl` (`icons/newui/task` → `externalSystem/task`).
|
||||
Copyright 2000-2026 JetBrains s.r.o. and contributors. Apache License 2.0 (below).
|
||||
- [intellij-plugins](https://github.com/JetBrains/intellij-plugins) (each plugin
|
||||
carries its own licence): `protobuf/protoeditor-core` (`newui/protoFile` →
|
||||
@@ -61,44 +60,6 @@ Their original copyright headers and Apache-2.0 licensing are retained.
|
||||
|
||||
At render time `src/ui/icons.tsx` may recolour monochrome icons to `currentColor`.
|
||||
|
||||
## Flutter plugin icons
|
||||
|
||||
These icons of [flutter-intellij](https://github.com/flutter/flutter-intellij) (commit `d02813ad5890`) are used
|
||||
under the BSD 3-Clause License:
|
||||
|
||||
- `src/ui/expui/flutter/*.svg`: the DevTools tool window icons, copied unmodified from
|
||||
`resources/icons/expui/`.
|
||||
- `src/ui/expui/flutter/[email protected]` and `[email protected]`: the Flutter outline's widget
|
||||
icons, `resources/icons/custom/[email protected]` and `[email protected]`, renamed, content unmodified.
|
||||
|
||||
```text
|
||||
Copyright 2016 The Chromium Authors. All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without modification,
|
||||
are permitted provided that the following conditions are met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright
|
||||
notice, this list of conditions and the following disclaimer.
|
||||
* Redistributions in binary form must reproduce the above
|
||||
copyright notice, this list of conditions and the following
|
||||
disclaimer in the documentation and/or other materials provided
|
||||
with the distribution.
|
||||
* Neither the name of Google Inc. nor the names of its
|
||||
contributors may be used to endorse or promote products derived
|
||||
from this software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
|
||||
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
|
||||
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
```
|
||||
|
||||
## JetBrains IntelliJ Platform VCS log graph algorithms
|
||||
|
||||
`crates/ide-vcs/src/bek.rs` and `src/features/vcs/graph.ts` adapt the Bek ordering,
|
||||
@@ -233,36 +194,6 @@ declarations, key and animation binding names (`(keydown.enter)`, `[@fade]`,
|
||||
`(@fade.done)`), runs of text that entities split (`a && b`) parsed as one, and one
|
||||
token for `{` and `}`.
|
||||
|
||||
## Julia CodeMirror language support
|
||||
|
||||
[`@plutojl/lang-julia`](https://github.com/JuliaPluto/lang-julia) 1.2.0 and its
|
||||
[`@plutojl/lezer-julia`](https://github.com/JuliaPluto/lezer-julia) parser dependency
|
||||
provide the Julia CodeMirror 6 language mode. Both packages are MIT licensed;
|
||||
the full license text is below. The mode wraps a Lezer grammar and exposes its
|
||||
syntax tags through `julia()`.
|
||||
|
||||
### MIT License (@plutojl/lang-julia and @plutojl/lezer-julia)
|
||||
|
||||
Copyright (c) 2021 Andrey Popp
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
|
||||
## nvim-treesitter queries
|
||||
|
||||
`crates/ide-syntax/queries/<grammar>/locals.scm` are derived from the `locals.scm`
|
||||
|
||||
@@ -7,7 +7,6 @@ license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
encoding_rs.workspace = true
|
||||
base64.workspace = true
|
||||
blake3.workspace = true
|
||||
ide-vfs.workspace = true
|
||||
ide-core.workspace = true
|
||||
@@ -26,10 +25,6 @@ dunce.workspace = true
|
||||
uuid.workspace = true
|
||||
tempfile.workspace = true
|
||||
which = "8"
|
||||
semver = "1"
|
||||
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
rustix = { version = "1", features = ["fs"] }
|
||||
|
||||
[dev-dependencies]
|
||||
tokio = { workspace = true, features = ["test-util"] }
|
||||
@@ -14,21 +14,20 @@ use std::collections::BTreeMap;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
const CONFIG_UPDATE_TIMEOUT: Duration = if cfg!(test) { Duration::from_millis(100) } else { Duration::from_secs(5) };
|
||||
const DISCOVER_TIMEOUT: Duration = if cfg!(test) { Duration::from_secs(3) } else { Duration::from_secs(120) };
|
||||
|
||||
/// Opens `session/new`, reads `configOptions`, and records the `thought_level` choices of the
|
||||
/// session's model: they describe that model only, and other models may offer different ones.
|
||||
pub(crate) async fn run(shared: &Arc<Shared>, spec: &ProviderSpec, model: Option<&str>) -> Result<Discovered, String> {
|
||||
pub(crate) async fn run(shared: &Arc<Shared>, spec: &ProviderSpec) -> Result<Discovered, String> {
|
||||
let prefer_stored = crate::provider::prefer_stored_copilot_auth();
|
||||
match run_once(shared, spec, prefer_stored, model).await {
|
||||
match run_once(shared, spec, prefer_stored).await {
|
||||
Err(err)
|
||||
if !prefer_stored
|
||||
&& crate::provider::is_copilot_provider(&spec.id)
|
||||
&& crate::provider::has_unconfigured_copilot_ambient_token(&spec.env)
|
||||
&& super::auth_required(0, &err) =>
|
||||
{
|
||||
let retry = run_once(shared, spec, true, model).await;
|
||||
let retry = run_once(shared, spec, true).await;
|
||||
if retry.is_ok() {
|
||||
crate::provider::mark_prefer_stored_copilot_auth();
|
||||
}
|
||||
@@ -38,12 +37,7 @@ pub(crate) async fn run(shared: &Arc<Shared>, spec: &ProviderSpec, model: Option
|
||||
}
|
||||
}
|
||||
|
||||
async fn run_once(
|
||||
shared: &Arc<Shared>,
|
||||
spec: &ProviderSpec,
|
||||
strip_ambient: bool,
|
||||
selected_model: Option<&str>,
|
||||
) -> Result<Discovered, String> {
|
||||
async fn run_once(shared: &Arc<Shared>, spec: &ProviderSpec, strip_ambient: bool) -> Result<Discovered, String> {
|
||||
let root = shared.paths.project_root.clone();
|
||||
let launch = spec.clone();
|
||||
let launch = tokio::task::spawn_blocking({
|
||||
@@ -51,70 +45,30 @@ async fn run_once(
|
||||
move || launch.resolve_for_launch_with_copilot_env(&root, strip_ambient)
|
||||
})
|
||||
.await
|
||||
.map_err(|e| e.to_string())??;
|
||||
.map_err(|e| e.to_string())?;
|
||||
let cwd = dunce::canonicalize(&root).unwrap_or(root);
|
||||
let updates = Arc::new(DiscoveryUpdates { provider: spec.id.clone(), ..Default::default() });
|
||||
let updates = Arc::new(DiscoveryUpdates { provider: spec.id.clone(), commands: Mutex::new(None) });
|
||||
let client = Dialect::wrap(updates.clone());
|
||||
let on_stderr: Box<dyn Fn(String) + Send + Sync> = Box::new(|_| {});
|
||||
let peer = (shared.connector)(&launch, &cwd, client.clone(), on_stderr)
|
||||
.map_err(|e| format!("Couldn't start {} for model discovery: {e}", launch.name))?;
|
||||
.map_err(|e| format!("Couldn't start {} (`{}`): {e}", launch.name, launch.command))?;
|
||||
let _stop = crate::catalogs::KillPeer(peer.clone());
|
||||
let conn = Conn::new(peer.clone(), client);
|
||||
let work = async {
|
||||
conn.initialize(&client_info()).await.map_err(discovery_error)?;
|
||||
conn.initialize(&client_info()).await.map_err(|e| e.to_string())?;
|
||||
let cwd_s = cwd.to_string_lossy().into_owned();
|
||||
// No project MCP during discovery: Cursor can spend a long time spawning servers.
|
||||
let new: Value = conn
|
||||
.request("session/new", json!({ "cwd": cwd_s, "mcpServers": [] }), None)
|
||||
.await
|
||||
.map_err(discovery_error)?;
|
||||
.map_err(|e| e.to_string())?;
|
||||
let mut options = config::options_of(&new);
|
||||
config::add_client_options(&launch.id, &mut options);
|
||||
let model_option = options.iter().find(|o| o.category.as_deref() == Some("model"));
|
||||
let mut levels = BTreeMap::new();
|
||||
let has_config = new.get("configOptions").is_some_and(Value::is_array);
|
||||
if has_config && let Some(model) = model_option.and_then(|o| o.current.as_ref()) {
|
||||
levels.insert(model.clone(), levels_for_model_from_slice(&options));
|
||||
}
|
||||
if let Some(selected) = selected_model
|
||||
&& let Some(option) = model_option.filter(|o| o.values.iter().any(|v| v.value == selected))
|
||||
&& !levels.contains_key(selected)
|
||||
{
|
||||
let session =
|
||||
new.get("sessionId").and_then(Value::as_str).ok_or("The agent did not return a session ID")?;
|
||||
let (method, mut params) = config::set_request(option, selected);
|
||||
params["sessionId"] = json!(session);
|
||||
updates.config.lock().session = Some(session.to_owned());
|
||||
let response: Value = conn.request(method, params, None).await.map_err(discovery_error)?;
|
||||
let settings = if let Some(settings) = selected_settings(&response, selected) {
|
||||
Some(settings)
|
||||
} else {
|
||||
tokio::time::timeout(CONFIG_UPDATE_TIMEOUT, async {
|
||||
loop {
|
||||
let notified = updates.changed.notified();
|
||||
if let Some(settings) = updates
|
||||
.config
|
||||
.lock()
|
||||
.options
|
||||
.as_ref()
|
||||
.and_then(|options| selected_settings(options, selected))
|
||||
{
|
||||
return settings;
|
||||
}
|
||||
notified.await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.ok()
|
||||
};
|
||||
match settings {
|
||||
Some(settings) => levels.insert(selected.to_owned(), levels_for_model_from_slice(&settings)),
|
||||
// An agent on the legacy `models` field that says nothing more: the model has
|
||||
// no settings of its own, and switching to it must not fail.
|
||||
None if !has_config => levels.insert(selected.to_owned(), Vec::new()),
|
||||
None => return Err("The agent did not report settings for the selected model".to_owned()),
|
||||
};
|
||||
}
|
||||
let model = options.iter().find(|o| o.category.as_deref() == Some("model")).and_then(|o| o.current.clone());
|
||||
let levels = match (model, levels_for_model_from_slice(&options)) {
|
||||
(Some(model), Some(effort)) => BTreeMap::from([(model, effort)]),
|
||||
_ => BTreeMap::new(),
|
||||
};
|
||||
let commands = updates
|
||||
.commands
|
||||
.lock()
|
||||
@@ -134,38 +88,16 @@ async fn run_once(
|
||||
struct DiscoveryUpdates {
|
||||
provider: String,
|
||||
commands: Mutex<Option<Vec<crate::AgentCommand>>>,
|
||||
config: Mutex<DiscoveryConfig>,
|
||||
changed: tokio::sync::Notify,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct DiscoveryConfig {
|
||||
session: Option<String>,
|
||||
options: Option<Value>,
|
||||
}
|
||||
|
||||
impl ide_jsonrpc::Handler for DiscoveryUpdates {
|
||||
fn on_notification(&self, method: &str, params: Value) {
|
||||
if method != "session/update" {
|
||||
return;
|
||||
}
|
||||
let Some(update) = params.get("update") else { return };
|
||||
match update["sessionUpdate"].as_str() {
|
||||
Some("available_commands_update") => {
|
||||
// Commands are protocol data, not stderr (which may contain credentials).
|
||||
*self.commands.lock() = Some(config::commands_of(update, &self.provider));
|
||||
}
|
||||
Some("config_option_update") => {
|
||||
let mut config = self.config.lock();
|
||||
if config.session.as_deref() == params.get("sessionId").and_then(Value::as_str)
|
||||
&& config.session.is_some()
|
||||
&& update.get("configOptions").is_some_and(Value::is_array)
|
||||
{
|
||||
config.options = Some(update.clone());
|
||||
self.changed.notify_one();
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
if method == "session/update"
|
||||
&& let Some(update) = params.get("update")
|
||||
&& update["sessionUpdate"] == "available_commands_update"
|
||||
{
|
||||
// Commands are protocol data, not stderr (which may contain credentials).
|
||||
*self.commands.lock() = Some(config::commands_of(update, &self.provider));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -174,36 +106,21 @@ impl ide_jsonrpc::Handler for DiscoveryUpdates {
|
||||
}
|
||||
}
|
||||
|
||||
fn discovery_error(error: ide_jsonrpc::RpcError) -> String {
|
||||
match error {
|
||||
ide_jsonrpc::RpcError::Server { code, message, .. } if super::auth_required(code, &message) => {
|
||||
"Sign in required: the agent could not authenticate model discovery".into()
|
||||
}
|
||||
other => format!("The agent could not complete model discovery: {other}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn selected_settings(response: &Value, model: &str) -> Option<Vec<AgentConfigOption>> {
|
||||
response.get("configOptions")?.as_array()?;
|
||||
let options = config::options_of(response);
|
||||
let current = options.iter().find(|o| o.category.as_deref() == Some("model")).and_then(|o| o.current.as_deref());
|
||||
current.is_none_or(|current| current == model).then_some(options)
|
||||
}
|
||||
|
||||
fn levels_for_model_from_slice(options: &[AgentConfigOption]) -> Vec<AgentConfigOption> {
|
||||
options
|
||||
fn levels_for_model_from_slice(options: &[AgentConfigOption]) -> Option<Vec<AgentConfigOption>> {
|
||||
let levels: Vec<_> = options
|
||||
.iter()
|
||||
.filter(|o| config::is_per_model_option(o))
|
||||
.cloned()
|
||||
.map(|mut o| {
|
||||
if config::is_context_option(&o.id) || config::is_fast_option(&o.id) {
|
||||
if config::is_context_option(&o.id) {
|
||||
if o.category.is_none() {
|
||||
o.category = Some("model_config".into());
|
||||
}
|
||||
} else if o.category.is_none() {
|
||||
} else if o.category.as_deref() != Some("thought_level") {
|
||||
o.category = Some("thought_level".into());
|
||||
}
|
||||
o
|
||||
})
|
||||
.collect()
|
||||
.collect();
|
||||
(!levels.is_empty()).then_some(levels)
|
||||
}
|
||||
@@ -203,11 +203,7 @@ async fn a_task_runs_on_a_v2_agent_and_resumes_its_session() {
|
||||
let agent2 = Arc::new(FakeV2Agent::default());
|
||||
let mgr2 = manager(tmp.path(), agent2.clone());
|
||||
mgr2.prompt(&task.id, text("again"), false).await.unwrap();
|
||||
// The task is Ready until the resumed turn starts: wait for the turn's entries first.
|
||||
let deadline = std::time::Instant::now() + Duration::from_secs(10);
|
||||
while mgr2.entries(&task.id, None).unwrap().len() < 8 && std::time::Instant::now() < deadline {
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
wait_for(&mgr2, &task.id, AgentStatus::Ready).await;
|
||||
let entries = mgr2.entries(&task.id, None).unwrap();
|
||||
assert_eq!(summary(&entries[6..]), ["user: again", "agent: second turn"]);
|
||||
|
||||
@@ -27,7 +27,7 @@ use serde::de::DeserializeOwned;
|
||||
use serde_json::{Value, json};
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, AtomicU8, Ordering};
|
||||
use std::sync::atomic::{AtomicU8, Ordering};
|
||||
use tokio::sync::oneshot;
|
||||
|
||||
/// ACP's error code for a request that needs the user to sign in.
|
||||
@@ -162,16 +162,9 @@ impl Negotiated {
|
||||
Self { generation: 2, capabilities, agent_info: response.get("info").cloned(), auth_methods, meta }
|
||||
}
|
||||
|
||||
/// Whether a saved session can be reopened: `loadSession`, or a v1 agent's
|
||||
/// `sessionCapabilities.resume` (DeepSeek Harness), which stands in for it.
|
||||
/// Whether a saved session can be reopened (`session/load` on v1, `session/resume` on v2).
|
||||
pub fn load_session(&self) -> bool {
|
||||
self.capabilities.get("loadSession").and_then(Value::as_bool) == Some(true) || self.session("resume")
|
||||
}
|
||||
|
||||
/// Whether `session/load` must be sent as `session/resume`: a v1 agent that advertises
|
||||
/// `sessionCapabilities.resume` instead of `loadSession` (DeepSeek Harness).
|
||||
pub fn resume_instead_of_load(&self) -> bool {
|
||||
self.capabilities.get("loadSession").and_then(Value::as_bool) != Some(true) && self.session("resume")
|
||||
self.capabilities.get("loadSession").and_then(Value::as_bool) == Some(true)
|
||||
}
|
||||
|
||||
/// `promptCapabilities.<name>` (`image`, `audio`, `embeddedContext`).
|
||||
@@ -212,8 +205,6 @@ pub(crate) struct Dialect {
|
||||
inner: Arc<dyn Handler>,
|
||||
/// 0 until `initialize` answers; then 1 or 2.
|
||||
generation: AtomicU8,
|
||||
/// Set by `initialize`: a v1 agent's `session/load` is sent as `session/resume`.
|
||||
resume_load: AtomicBool,
|
||||
normalizer: Mutex<Normalizer>,
|
||||
/// Running v2 prompts, by session id.
|
||||
turns: Mutex<HashMap<String, Turn>>,
|
||||
@@ -231,7 +222,6 @@ impl Dialect {
|
||||
Arc::new(Self {
|
||||
inner,
|
||||
generation: AtomicU8::new(0),
|
||||
resume_load: AtomicBool::new(false),
|
||||
normalizer: Mutex::new(Normalizer::default()),
|
||||
turns: Mutex::new(HashMap::new()),
|
||||
})
|
||||
@@ -241,10 +231,6 @@ impl Dialect {
|
||||
self.generation.load(Ordering::Acquire)
|
||||
}
|
||||
|
||||
fn resume_load(&self) -> bool {
|
||||
self.resume_load.load(Ordering::Acquire)
|
||||
}
|
||||
|
||||
fn v2(&self) -> bool {
|
||||
self.generation() == 2
|
||||
}
|
||||
@@ -394,7 +380,6 @@ impl Conn {
|
||||
let response: Value = self.peer.request("initialize", initialize_params(client_info), None).await?;
|
||||
let negotiated = Negotiated::from_initialize(&response);
|
||||
self.dialect.generation.store(negotiated.generation, Ordering::Release);
|
||||
self.dialect.resume_load.store(negotiated.resume_instead_of_load(), Ordering::Release);
|
||||
Ok(negotiated)
|
||||
}
|
||||
|
||||
@@ -408,9 +393,6 @@ impl Conn {
|
||||
let params = serde_json::to_value(params).map_err(|e| RpcError::Protocol(e.to_string()))?;
|
||||
let value = if self.dialect.v2() {
|
||||
self.request_v2(method, params, cancel).await?
|
||||
} else if method == "session/load" && self.dialect.resume_load() {
|
||||
// Same request shape, without a replay and without v2's setup translation.
|
||||
self.peer.request("session/resume", params, cancel).await?
|
||||
} else {
|
||||
self.peer.request(method, params, cancel).await?
|
||||
};
|
||||
|
||||
@@ -168,12 +168,11 @@ async fn discovery_reads_effort_and_fast_from_session_new_then_stops_the_agent()
|
||||
assert_eq!(calls.iter().map(|(m, _)| m.as_str()).collect::<Vec<_>>(), ["initialize", "session/new"]);
|
||||
assert_eq!(calls[1].1["mcpServers"], json!([]));
|
||||
let cursor = mgr.providers().into_iter().find(|p| p.id == "cursor").unwrap();
|
||||
// Per-model options (`effort`, `fast`, `context`) belong to the session's model, not provider-wide config.
|
||||
assert!(!cursor.config.iter().any(|o| o.id == "fast"));
|
||||
assert_eq!(cursor.thought_levels.keys().collect::<Vec<_>>(), ["m1"]);
|
||||
let fast = cursor.thought_levels["m1"].iter().find(|o| o.id == "fast").expect("fast option");
|
||||
let fast = cursor.config.iter().find(|o| o.id == "fast").expect("fast option");
|
||||
assert_eq!(fast.category.as_deref(), Some("model_config"));
|
||||
assert_eq!(fast.current.as_deref(), Some("false"));
|
||||
// The effort option belongs to the session's model; m2 may offer other levels.
|
||||
assert_eq!(cursor.thought_levels.keys().collect::<Vec<_>>(), ["m1"]);
|
||||
assert!(cursor.thought_levels["m1"].iter().any(|o| o.category.as_deref() == Some("thought_level")));
|
||||
}
|
||||
|
||||
@@ -181,7 +180,6 @@ async fn discovery_reads_effort_and_fast_from_session_new_then_stops_the_agent()
|
||||
fn a_v2_initialize_response_reads_as_v1_capabilities() {
|
||||
let n = Negotiated::from_initialize(&result(TURN, 1));
|
||||
assert_eq!(n.generation, 2);
|
||||
assert!(!n.resume_instead_of_load(), "v2 maps `session/load` itself");
|
||||
assert!(n.load_session());
|
||||
assert!(n.prompt("image") && n.prompt("embeddedContext") && !n.prompt("audio"));
|
||||
assert!(n.session("fork") && n.session("resume") && n.session("close") && n.session("delete"));
|
||||
@@ -683,87 +681,3 @@ fn stdio_mcp_is_v1_baseline_and_negotiated_in_v2() {
|
||||
.mcp_stdio()
|
||||
);
|
||||
}
|
||||
|
||||
/// A v1 agent that answers `initialize` with `init` and records every request it gets.
|
||||
/// Keeps its own `Peer` so the duplex stays open while the client sends.
|
||||
struct V1Agent {
|
||||
init: Value,
|
||||
peer: std::sync::OnceLock<Peer>,
|
||||
requests: parking_lot::Mutex<Vec<(String, Value)>>,
|
||||
}
|
||||
|
||||
impl Handler for V1Agent {
|
||||
fn on_notification(&self, _: &str, _: Value) {}
|
||||
|
||||
fn on_request(&self, method: &str, params: Value) -> Result<Value, (i64, String)> {
|
||||
self.requests.lock().push((method.to_owned(), params));
|
||||
Ok(if method == "initialize" { self.init.clone() } else { json!({}) })
|
||||
}
|
||||
}
|
||||
|
||||
async fn connect_v1(agent: Arc<V1Agent>) -> (Conn, Negotiated) {
|
||||
let (a, b) = tokio::io::duplex(1 << 20);
|
||||
let (ar, aw) = tokio::io::split(a);
|
||||
let (br, bw) = tokio::io::split(b);
|
||||
let _ = agent.peer.set(Peer::connect_framed(br, bw, agent.clone(), Framing::Lines));
|
||||
let dialect = Dialect::wrap(Arc::new(Recorder::default()));
|
||||
let conn = Conn::new(Peer::connect_framed(ar, aw, dialect.clone(), Framing::Lines), dialect);
|
||||
let n = conn.initialize(&json!({ "name": "OpenIDEA", "version": "0" })).await.unwrap();
|
||||
assert_eq!((n.generation, conn.generation()), (1, 1));
|
||||
(conn, n)
|
||||
}
|
||||
|
||||
fn v1_agent(init: Value) -> Arc<V1Agent> {
|
||||
Arc::new(V1Agent { init, peer: Default::default(), requests: Default::default() })
|
||||
}
|
||||
|
||||
/// A v1 agent that advertises `sessionCapabilities.resume` instead of `loadSession`
|
||||
/// (DeepSeek Harness) can reopen a saved session, but only through `session/resume`.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_v1_agent_with_resume_instead_of_load_reopens_through_session_resume() {
|
||||
let agent = v1_agent(json!({
|
||||
"protocolVersion": 1,
|
||||
"agentInfo": { "name": "deepseek-harness-acp", "version": "0.0.1" },
|
||||
"agentCapabilities": { "sessionCapabilities": { "close": {}, "list": {}, "resume": {} } },
|
||||
}));
|
||||
let (conn, n) = connect_v1(agent.clone()).await;
|
||||
assert!(n.load_session(), "a resume-only agent is reloadable");
|
||||
assert!(n.resume_instead_of_load());
|
||||
assert!(n.session("resume"));
|
||||
|
||||
let params = json!({ "sessionId": "s1", "cwd": "/p", "mcpServers": [] });
|
||||
let _: Value = conn.request("session/load", params.clone(), None).await.unwrap();
|
||||
let requests = agent.requests.lock().clone();
|
||||
assert_eq!(requests.iter().map(|(m, _)| m.as_str()).collect::<Vec<_>>(), ["initialize", "session/resume"]);
|
||||
assert_eq!(requests[1].1, params, "same request shape as `session/load`");
|
||||
}
|
||||
|
||||
/// Every other v1 agent is untouched: `loadSession` still sends `session/load`, and an
|
||||
/// agent advertising neither capability is not treated as loadable.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn v1_agents_that_do_not_advertise_resume_keep_session_load() {
|
||||
for (init, loadable) in [
|
||||
(json!({ "protocolVersion": 1, "agentCapabilities": { "loadSession": true } }), true),
|
||||
(json!({ "protocolVersion": 1, "agentCapabilities": { "loadSession": false } }), false),
|
||||
(json!({ "protocolVersion": 1, "agentCapabilities": { "sessionCapabilities": { "resume": null } } }), false),
|
||||
(json!({ "protocolVersion": 1 }), false),
|
||||
] {
|
||||
let agent = v1_agent(init);
|
||||
let (conn, n) = connect_v1(agent.clone()).await;
|
||||
assert_eq!(n.load_session(), loadable);
|
||||
assert!(!n.resume_instead_of_load());
|
||||
let _: Value = conn.request("session/load", json!({ "sessionId": "s1" }), None).await.unwrap();
|
||||
let methods: Vec<String> = agent.requests.lock().iter().map(|(m, _)| m.clone()).collect();
|
||||
assert_eq!(methods, ["initialize", "session/load"]);
|
||||
}
|
||||
// `loadSession: true` wins over a resume-only advertisement.
|
||||
let agent = v1_agent(json!({
|
||||
"protocolVersion": 1,
|
||||
"agentCapabilities": { "loadSession": true, "sessionCapabilities": { "resume": {} } },
|
||||
}));
|
||||
let (conn, n) = connect_v1(agent.clone()).await;
|
||||
assert!(n.load_session() && !n.resume_instead_of_load());
|
||||
let _: Value = conn.request("session/load", json!({ "sessionId": "s1" }), None).await.unwrap();
|
||||
let methods: Vec<String> = agent.requests.lock().iter().map(|(m, _)| m.clone()).collect();
|
||||
assert_eq!(methods, ["initialize", "session/load"]);
|
||||
}
|
||||
@@ -1,80 +0,0 @@
|
||||
//! Codex's asynchronous questions are answered by a user message, not a permission response.
|
||||
|
||||
use crate::AgentQuestion;
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use serde_json::json;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
/// The wire reply and its readable record. Question ids, not wording, associate each answer.
|
||||
pub(crate) fn reply(questions: &[AgentQuestion], answers: &str) -> IdeResult<(String, String)> {
|
||||
let answers: BTreeMap<String, Vec<String>> =
|
||||
serde_json::from_str(answers).map_err(|_| IdeError::invalid("invalid question answers"))?;
|
||||
if questions.is_empty() || answers.len() != questions.len() {
|
||||
return Err(IdeError::invalid("answer every question"));
|
||||
}
|
||||
let mut replies = Vec::new();
|
||||
let mut record = Vec::new();
|
||||
for question in questions {
|
||||
let key = question.answer_key.as_deref().ok_or_else(|| IdeError::invalid("missing question id"))?;
|
||||
let values = answers.get(key).ok_or_else(|| IdeError::invalid("missing question answer"))?;
|
||||
if values.is_empty()
|
||||
|| (!question.multi_select && values.len() != 1)
|
||||
|| values.iter().any(|v| v.trim().is_empty())
|
||||
{
|
||||
return Err(IdeError::invalid("empty or invalid question answer"));
|
||||
}
|
||||
let answer = values.iter().map(|v| v.trim()).collect::<Vec<_>>().join(", ");
|
||||
let mut title = question.question.clone();
|
||||
let mut end = title.len().min(512);
|
||||
while !title.is_char_boundary(end) {
|
||||
end -= 1;
|
||||
}
|
||||
title.truncate(end);
|
||||
title = title.replace(['\n', '\r'], " ");
|
||||
replies.push(json!({ "questionItemId": key, "question": title, "answer": answer }));
|
||||
record.push(format!("{}: {}", question.question, answer));
|
||||
}
|
||||
Ok((
|
||||
format!("<send_user_message_question_reply>\n{}\n</send_user_message_question_reply>", json!(replies)),
|
||||
record.join("\n"),
|
||||
))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn question(key: &str) -> AgentQuestion {
|
||||
AgentQuestion {
|
||||
answer_key: Some(key.into()),
|
||||
header: String::new(),
|
||||
question: "Which?".into(),
|
||||
multi_select: false,
|
||||
options: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn identical_wording_keeps_answers_associated_with_ids() {
|
||||
let (wire, record) =
|
||||
reply(&[question("first"), question("second")], r#"{"first":[" One "],"second":["Two"]}"#).unwrap();
|
||||
let body = wire
|
||||
.strip_prefix("<send_user_message_question_reply>\n")
|
||||
.unwrap()
|
||||
.strip_suffix("\n</send_user_message_question_reply>")
|
||||
.unwrap();
|
||||
let replies: serde_json::Value = serde_json::from_str(body).unwrap();
|
||||
assert_eq!(replies[0], json!({"questionItemId":"first","question":"Which?","answer":"One"}));
|
||||
assert_eq!(replies[1]["answer"], "Two");
|
||||
assert_eq!(record, "Which?: One\nWhich?: Two");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_missing_and_empty_answers_are_rejected() {
|
||||
for answers in
|
||||
["no", "{}", r#"{"other":["One"]}"#, r#"{"first":[]}"#, r#"{"first":[" "]}"#, r#"{"first":["One","Two"]}"#]
|
||||
{
|
||||
assert!(reply(&[question("first")], answers).is_err(), "{answers}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -15,8 +15,6 @@ use tokio::time::Instant;
|
||||
|
||||
const FRESH_FOR: Duration = Duration::from_secs(15 * 60);
|
||||
const COOLDOWN: Duration = Duration::from_secs(30);
|
||||
/// Persisted catalog layout version; bump when option classification changes so stale per-model entries re-discover.
|
||||
const CATALOG_SCHEMA: u8 = 2;
|
||||
|
||||
type Store = Arc<Mutex<HashMap<String, Known>>>;
|
||||
type Key = (PathBuf, PathBuf, String);
|
||||
@@ -47,18 +45,9 @@ struct Entry {
|
||||
error: Option<String>,
|
||||
flight: Option<watch::Receiver<bool>>,
|
||||
abort: Option<tokio::task::AbortHandle>,
|
||||
flight_model: Option<String>,
|
||||
requested_model: Option<String>,
|
||||
model_failures: HashMap<String, ModelFailure>,
|
||||
catalog: Option<CatalogData>,
|
||||
}
|
||||
|
||||
struct ModelFailure {
|
||||
completed: Instant,
|
||||
retry_at_ms: f64,
|
||||
error: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Default, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub(crate) struct CatalogData {
|
||||
@@ -82,8 +71,6 @@ impl CatalogData {
|
||||
pub(crate) struct SavedCatalog {
|
||||
/// An opaque cryptographic digest, never raw launch arguments or credentials.
|
||||
fingerprint: String,
|
||||
#[serde(default)]
|
||||
schema: u8,
|
||||
#[serde(flatten)]
|
||||
catalog: CatalogData,
|
||||
}
|
||||
@@ -115,7 +102,7 @@ impl LaunchContext {
|
||||
hash.update(&(value.len() as u64).to_le_bytes());
|
||||
hash.update(value);
|
||||
}
|
||||
field(&mut hash, b"openidea-model-catalog-v2");
|
||||
field(&mut hash, b"openidea-model-catalog-v1");
|
||||
field(
|
||||
&mut hash,
|
||||
match self.spec.driver {
|
||||
@@ -198,21 +185,14 @@ impl AgentCatalogs {
|
||||
(shared.paths.models_file.clone(), shared.paths.project_root.clone(), provider.to_owned())
|
||||
}
|
||||
|
||||
/// The catalog saved for this project, for before this run looked anything up.
|
||||
fn saved(shared: &Shared, provider: &str) -> CatalogData {
|
||||
fn fallback(shared: &Shared, provider: &str) -> CatalogData {
|
||||
let cache = shared.known.lock();
|
||||
cache
|
||||
.get(provider)
|
||||
.and_then(|known| known.catalogs.get(&shared.root_key()))
|
||||
.map(|saved| {
|
||||
let mut catalog = saved.catalog.clone();
|
||||
if saved.schema < CATALOG_SCHEMA {
|
||||
catalog.refreshed_at_ms = None;
|
||||
catalog.thought_levels.clear();
|
||||
}
|
||||
catalog
|
||||
})
|
||||
.unwrap_or_default()
|
||||
let Some(known) = cache.get(provider) else { return CatalogData::default() };
|
||||
known.catalogs.get(&shared.root_key()).map(|saved| saved.catalog.clone()).unwrap_or_else(|| CatalogData {
|
||||
config: known.config.clone(),
|
||||
thought_levels: known.thought_levels.clone(),
|
||||
refreshed_at_ms: None,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn cached(&self, shared: &Shared, provider: &str) -> CatalogData {
|
||||
@@ -221,58 +201,7 @@ impl AgentCatalogs {
|
||||
.entries
|
||||
.get(&Self::key(shared, provider))
|
||||
.and_then(|e| e.catalog.clone())
|
||||
.unwrap_or_else(|| Self::saved(shared, provider))
|
||||
}
|
||||
|
||||
/// The entry a chat may switch to: exactly what the picker offers from the cached catalog,
|
||||
/// however long ago it was read. Refreshing keeps that catalog current; a listed model is
|
||||
/// never refused because the catalog aged.
|
||||
pub(super) fn listed_model(&self, shared: &Shared, provider: &str, model: &str) -> Option<crate::AgentConfigValue> {
|
||||
self.cached(shared, provider).model_option()?.values.iter().find(|value| value.value == model).cloned()
|
||||
}
|
||||
|
||||
pub(crate) fn levels(&self, shared: &Shared, provider: &str, model: &str) -> Option<Vec<AgentConfigOption>> {
|
||||
let state = self.state.lock();
|
||||
if let Some(catalog) = state.entries.get(&Self::key(shared, provider)).and_then(|entry| entry.catalog.as_ref())
|
||||
{
|
||||
return catalog.thought_levels.get(model).cloned();
|
||||
}
|
||||
drop(state);
|
||||
let cache = shared.known.lock();
|
||||
let saved = cache.get(provider)?.catalogs.get(&shared.root_key())?;
|
||||
(saved.schema >= CATALOG_SCHEMA).then(|| saved.catalog.thought_levels.get(model).cloned()).flatten()
|
||||
}
|
||||
|
||||
pub(super) async fn load_levels(
|
||||
self: &Arc<Self>,
|
||||
shared: &Arc<Shared>,
|
||||
provider: &str,
|
||||
model: &str,
|
||||
) -> Result<Vec<AgentConfigOption>, String> {
|
||||
if let Some(levels) = self.levels(shared, provider, model) {
|
||||
return Ok(levels);
|
||||
}
|
||||
let unavailable = || "The agent did not report settings for the selected model".to_owned();
|
||||
let spec = shared.spec(provider).ok_or_else(unavailable)?;
|
||||
let (_, flight) = self.request(shared, spec, false, Some(model));
|
||||
if let Some(mut ready) = flight {
|
||||
while !*ready.borrow_and_update() {
|
||||
if ready.changed().await.is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
self.levels(shared, provider, model).ok_or_else(|| {
|
||||
let state = self.state.lock();
|
||||
state
|
||||
.entries
|
||||
.get(&Self::key(shared, provider))
|
||||
.and_then(|entry| {
|
||||
entry.model_failures.get(model).map(|failure| &failure.error).or(entry.error.as_ref())
|
||||
})
|
||||
.cloned()
|
||||
.unwrap_or_else(unavailable)
|
||||
})
|
||||
.unwrap_or_else(|| Self::fallback(shared, provider))
|
||||
}
|
||||
|
||||
pub(crate) fn evict_if_idle(&self, shared: &Shared, provider: &str) {
|
||||
@@ -284,28 +213,17 @@ impl AgentCatalogs {
|
||||
}
|
||||
|
||||
fn snapshot(&self, shared: &Shared, provider: &str, entry: &Entry) -> AgentModelCatalog {
|
||||
let catalog = entry.catalog.clone().unwrap_or_default();
|
||||
let model_failure = entry.requested_model.as_ref().and_then(|model| entry.model_failures.get(model));
|
||||
let unknown_model = entry
|
||||
.requested_model
|
||||
.as_deref()
|
||||
.is_some_and(|model| catalog.lists(model) && !catalog.thought_levels.contains_key(model));
|
||||
let catalog = entry.catalog.clone().unwrap_or_else(|| Self::fallback(shared, provider));
|
||||
AgentModelCatalog {
|
||||
provider: provider.to_owned(),
|
||||
config: shared.config_for_new_task(catalog.config, provider),
|
||||
thought_levels: shared.thought_levels_for_new_task(catalog.thought_levels, provider),
|
||||
thought_levels: catalog.thought_levels,
|
||||
refreshing: entry.flight.is_some(),
|
||||
refreshed_at_ms: catalog.refreshed_at_ms,
|
||||
retry_at_ms: model_failure
|
||||
.filter(|failure| self.now().duration_since(failure.completed) < COOLDOWN)
|
||||
.map(|failure| failure.retry_at_ms)
|
||||
.or_else(|| {
|
||||
(!unknown_model)
|
||||
.then_some(entry.retry_at_ms)
|
||||
.flatten()
|
||||
.filter(|_| entry.completed.is_some_and(|at| self.now().duration_since(at) < COOLDOWN))
|
||||
}),
|
||||
error: model_failure.map(|failure| failure.error.clone()).or_else(|| entry.error.clone()),
|
||||
retry_at_ms: entry
|
||||
.retry_at_ms
|
||||
.filter(|_| entry.completed.is_some_and(|at| self.now().duration_since(at) < COOLDOWN)),
|
||||
error: entry.error.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -315,7 +233,6 @@ impl AgentCatalogs {
|
||||
shared: &Arc<Shared>,
|
||||
spec: provider::ProviderSpec,
|
||||
force: bool,
|
||||
model: Option<&str>,
|
||||
) -> (AgentModelCatalog, Option<watch::Receiver<bool>>) {
|
||||
let key = Self::key(shared, &spec.id);
|
||||
let context = LaunchContext::new(spec.clone(), &shared.paths.project_root);
|
||||
@@ -330,9 +247,7 @@ impl AgentCatalogs {
|
||||
let generation = state.generation;
|
||||
let saved =
|
||||
shared.known.lock().get(&spec.id).and_then(|known| known.catalogs.get(&shared.root_key())).cloned();
|
||||
let matching = saved
|
||||
.as_ref()
|
||||
.is_some_and(|saved| saved.schema >= CATALOG_SCHEMA && saved.fingerprint == context.fingerprint());
|
||||
let matching = saved.as_ref().is_some_and(|saved| saved.fingerprint == context.fingerprint());
|
||||
let age = saved
|
||||
.as_ref()
|
||||
.filter(|_| matching)
|
||||
@@ -349,7 +264,6 @@ impl AgentCatalogs {
|
||||
let mut catalog = saved.catalog;
|
||||
if !matching {
|
||||
catalog.refreshed_at_ms = None;
|
||||
catalog.thought_levels.clear();
|
||||
}
|
||||
catalog
|
||||
});
|
||||
@@ -365,72 +279,31 @@ impl AgentCatalogs {
|
||||
error: None,
|
||||
flight: None,
|
||||
abort: None,
|
||||
flight_model: None,
|
||||
requested_model: None,
|
||||
model_failures: HashMap::new(),
|
||||
},
|
||||
);
|
||||
}
|
||||
state.generation += 1;
|
||||
let generation = state.generation;
|
||||
let entry = state.entries.get_mut(&key).expect("catalog entry");
|
||||
let empty = CatalogData::default();
|
||||
let catalog = entry.catalog.as_ref().unwrap_or(&empty);
|
||||
let cooling = entry.completed.is_some_and(|at| now.duration_since(at) < COOLDOWN);
|
||||
let fresh = entry.successful.is_some_and(|at| now.duration_since(at) < FRESH_FOR);
|
||||
let target = model
|
||||
.filter(|model| {
|
||||
(catalog.lists(model) && !catalog.thought_levels.contains_key(*model))
|
||||
|| (!fresh && catalog.model_option().is_none())
|
||||
})
|
||||
.map(str::to_owned);
|
||||
if model.is_some() && entry.requested_model.as_deref() != model {
|
||||
entry.requested_model = model.map(str::to_owned);
|
||||
}
|
||||
let superseded = model.is_some()
|
||||
&& entry.flight.is_some()
|
||||
&& (entry.flight_model.is_some() || target.is_some())
|
||||
&& entry.flight_model.as_deref() != target.as_deref();
|
||||
if superseded {
|
||||
if let Some(abort) = entry.abort.take() {
|
||||
abort.abort();
|
||||
}
|
||||
entry.flight = None;
|
||||
entry.generation = generation;
|
||||
entry.flight_model = None;
|
||||
}
|
||||
let cooling = match target.as_ref() {
|
||||
Some(model) => entry.model_failures.get(model).is_some_and(|f| now.duration_since(f.completed) < COOLDOWN),
|
||||
None => entry.completed.is_some_and(|at| now.duration_since(at) < COOLDOWN),
|
||||
};
|
||||
let eligible = !cooling && (target.is_some() || force || !fresh);
|
||||
let mut start = None;
|
||||
if entry.flight.is_none() && eligible {
|
||||
if entry.flight.is_none() && !cooling && (force || !fresh) {
|
||||
let (done, ready) = watch::channel(false);
|
||||
entry.flight = Some(ready);
|
||||
entry.flight_model = target.clone();
|
||||
entry.error = None;
|
||||
if let Some(model) = target.as_ref() {
|
||||
entry.model_failures.remove(model);
|
||||
}
|
||||
entry.retry_at_ms = None;
|
||||
// Every flight has its own generation, including superseded model selections.
|
||||
entry.generation = generation;
|
||||
start = Some((entry.generation, target, done));
|
||||
start = Some((entry.generation, done));
|
||||
}
|
||||
let snapshot = self.snapshot(shared, &spec.id, entry);
|
||||
let flight = entry.flight.clone();
|
||||
drop(state);
|
||||
if superseded && start.is_none() {
|
||||
self.broadcast(shared, &snapshot);
|
||||
}
|
||||
if let Some((generation, model, done)) = start {
|
||||
if let Some((generation, done)) = start {
|
||||
self.broadcast(shared, &snapshot);
|
||||
let coordinator = self.clone();
|
||||
let shared = shared.clone();
|
||||
let flight_key = key.clone();
|
||||
let task = shared.runtime.clone().spawn(async move {
|
||||
let result = discover(&shared, spec, model.as_deref()).await;
|
||||
coordinator.complete(&shared, flight_key, generation, model, result);
|
||||
let result = discover(&shared, spec).await;
|
||||
coordinator.complete(&shared, flight_key, generation, result);
|
||||
let _ = done.send(true);
|
||||
});
|
||||
// A subscriber can re-enter and change configuration during the start event.
|
||||
@@ -446,14 +319,7 @@ impl AgentCatalogs {
|
||||
(snapshot, flight)
|
||||
}
|
||||
|
||||
fn complete(
|
||||
&self,
|
||||
shared: &Shared,
|
||||
key: Key,
|
||||
generation: u64,
|
||||
model: Option<String>,
|
||||
result: Result<Discovered, String>,
|
||||
) {
|
||||
fn complete(&self, shared: &Shared, key: Key, generation: u64, result: Result<Discovered, String>) {
|
||||
let current = provider::load(shared.paths.custom_agents_dir.as_deref(), shared.env_secrets())
|
||||
.into_iter()
|
||||
.find(|spec| spec.id == key.2)
|
||||
@@ -464,7 +330,6 @@ impl AgentCatalogs {
|
||||
if current.as_ref() != Some(&entry.context) {
|
||||
entry.flight = None;
|
||||
entry.abort = None;
|
||||
entry.flight_model = None;
|
||||
entry.completed = None;
|
||||
entry.retry_at_ms = None;
|
||||
entry.error = None;
|
||||
@@ -475,16 +340,12 @@ impl AgentCatalogs {
|
||||
return;
|
||||
}
|
||||
let now = self.now();
|
||||
if model.is_none() {
|
||||
entry.completed = Some(now);
|
||||
entry.retry_at_ms = Some(self.epoch_ms() + COOLDOWN.as_millis() as f64);
|
||||
}
|
||||
entry.completed = Some(now);
|
||||
entry.retry_at_ms = Some(self.epoch_ms() + COOLDOWN.as_millis() as f64);
|
||||
entry.flight = None;
|
||||
entry.abort = None;
|
||||
entry.flight_model = None;
|
||||
let success = match result {
|
||||
Ok(found) => {
|
||||
let previous = entry.catalog.take().unwrap_or_default();
|
||||
let mut cache = shared.known.lock();
|
||||
let known = cache.entry(key.2.clone()).or_default();
|
||||
let mut catalog = CatalogData {
|
||||
@@ -493,49 +354,30 @@ impl AgentCatalogs {
|
||||
refreshed_at_ms: Some(self.epoch_ms()),
|
||||
};
|
||||
// Efforts sessions reported for models discovery doesn't read stay while listed.
|
||||
for (model, levels) in previous.thought_levels {
|
||||
for (model, levels) in entry.catalog.take().map(|old| old.thought_levels).unwrap_or_default() {
|
||||
if catalog.lists(&model) && !catalog.thought_levels.contains_key(&model) {
|
||||
catalog.thought_levels.insert(model, levels);
|
||||
}
|
||||
}
|
||||
known.config = catalog.config.clone();
|
||||
known.thought_levels = catalog.thought_levels.clone();
|
||||
if let Some(commands) = found.commands {
|
||||
known.commands.insert(shared.root_key(), commands);
|
||||
}
|
||||
known.authoritative = true;
|
||||
known.refreshed_at_ms = catalog.refreshed_at_ms;
|
||||
known.catalogs.insert(
|
||||
shared.root_key(),
|
||||
SavedCatalog {
|
||||
fingerprint: entry.context.fingerprint(),
|
||||
schema: CATALOG_SCHEMA,
|
||||
catalog: catalog.clone(),
|
||||
},
|
||||
SavedCatalog { fingerprint: entry.context.fingerprint(), catalog: catalog.clone() },
|
||||
);
|
||||
entry.catalog = Some(catalog);
|
||||
shared.persist_known(&cache);
|
||||
entry.successful = Some(now);
|
||||
entry.completed = Some(now);
|
||||
entry.retry_at_ms = Some(self.epoch_ms() + COOLDOWN.as_millis() as f64);
|
||||
entry.model_failures.retain(|model, _| {
|
||||
entry
|
||||
.catalog
|
||||
.as_ref()
|
||||
.is_some_and(|catalog| catalog.lists(model) && !catalog.thought_levels.contains_key(model))
|
||||
});
|
||||
entry.error = None;
|
||||
true
|
||||
}
|
||||
Err(error) => {
|
||||
if let Some(model) = model {
|
||||
entry.model_failures.insert(
|
||||
model,
|
||||
ModelFailure {
|
||||
completed: now,
|
||||
retry_at_ms: self.epoch_ms() + COOLDOWN.as_millis() as f64,
|
||||
error,
|
||||
},
|
||||
);
|
||||
} else {
|
||||
entry.error = Some(error);
|
||||
}
|
||||
entry.error = Some(error);
|
||||
false
|
||||
}
|
||||
};
|
||||
@@ -606,22 +448,18 @@ impl AgentCatalogs {
|
||||
|
||||
impl crate::AgentManager {
|
||||
/// Return cached choices immediately and schedule discovery when eligible.
|
||||
pub fn refresh_models(&self, provider: &str, force: bool, model: Option<&str>) -> IdeResult<AgentModelCatalog> {
|
||||
pub fn refresh_models(&self, provider: &str, force: bool) -> IdeResult<AgentModelCatalog> {
|
||||
// Settings and environment secrets can change while this window is open.
|
||||
*self.shared.providers.write() =
|
||||
provider::load(self.shared.paths.custom_agents_dir.as_deref(), self.shared.env_secrets());
|
||||
let spec = self.shared.spec(provider).ok_or_else(|| IdeError::invalid(format!("unknown agent {provider}")))?;
|
||||
Ok(self.shared.paths.catalogs.request(&self.shared, spec, force, model).0)
|
||||
Ok(self.shared.paths.catalogs.request(&self.shared, spec, force).0)
|
||||
}
|
||||
}
|
||||
|
||||
async fn discover(
|
||||
shared: &Arc<Shared>,
|
||||
spec: provider::ProviderSpec,
|
||||
model: Option<&str>,
|
||||
) -> Result<Discovered, String> {
|
||||
async fn discover(shared: &Arc<Shared>, spec: provider::ProviderSpec) -> Result<Discovered, String> {
|
||||
match spec.driver {
|
||||
provider::Driver::Acp => acp::discover::run(shared, &spec, model).await,
|
||||
provider::Driver::Acp => acp::discover::run(shared, &spec).await,
|
||||
provider::Driver::Codex => native::codex::discover(spec, shared.paths.project_root.clone()).await,
|
||||
provider::Driver::Claude => {
|
||||
let found = native::claude::discover(spec.clone(), shared.paths.project_root.clone()).await?;
|
||||
@@ -646,7 +484,7 @@ async fn discover(
|
||||
provider::Driver::Copilot => {
|
||||
if shared.uses_copilot_acp_fallback(&spec) {
|
||||
let acp_spec = native::copilot::acp_fallback_spec(&spec);
|
||||
return acp::discover::run(shared, &acp_spec, model).await;
|
||||
return acp::discover::run(shared, &acp_spec).await;
|
||||
}
|
||||
match native::copilot::discover(spec.clone(), shared.paths.project_root.clone()).await {
|
||||
Ok(found) => Ok(Discovered {
|
||||
@@ -675,7 +513,7 @@ async fn discover(
|
||||
);
|
||||
shared.mark_copilot_acp_fallback(&spec);
|
||||
let acp_spec = native::copilot::acp_fallback_spec(&spec);
|
||||
acp::discover::run(shared, &acp_spec, model).await
|
||||
acp::discover::run(shared, &acp_spec).await
|
||||
}
|
||||
Err(err) => Err(err.message),
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,395 +0,0 @@
|
||||
//! Checks and updates only the global npm installation selected by the agent launcher.
|
||||
use crate::{AgentManager, AgentSource, provider};
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult, error::ErrorKind};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
use specta::Type;
|
||||
use std::{
|
||||
fs, io,
|
||||
path::{Path, PathBuf},
|
||||
process::Command,
|
||||
};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
pub struct AgentCliOffer {
|
||||
pub current: String,
|
||||
pub latest: String,
|
||||
pub prefix: PathBuf,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(tag = "status", rename_all = "camelCase")]
|
||||
pub enum AgentCliUpdateResult {
|
||||
Available(AgentCliOffer),
|
||||
Permission(AgentCliOffer),
|
||||
Current { current: String },
|
||||
Channel { current: String },
|
||||
Updated { current: String },
|
||||
Unmanaged,
|
||||
Error { code: String },
|
||||
}
|
||||
|
||||
pub(crate) fn package(id: &str) -> Option<&'static str> {
|
||||
Some(match id {
|
||||
"claude" => "@anthropic-ai/claude-code",
|
||||
"codex" => "@openai/codex",
|
||||
"gemini" => "@google/gemini-cli",
|
||||
"opencode" => "opencode-ai",
|
||||
"copilot" => "@github/copilot",
|
||||
"qwen" => "@qwen-code/qwen-code",
|
||||
"auggie" => "@augmentcode/auggie",
|
||||
"qoder" => "@qoder-ai/qodercli",
|
||||
"omp" => "@oh-my-pi/pi-coding-agent",
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
impl AgentManager {
|
||||
pub fn cli_update(
|
||||
&self,
|
||||
id: &str,
|
||||
offer: Option<&AgentCliOffer>,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<AgentCliUpdateResult> {
|
||||
let spec = self.shared.spec(id).ok_or_else(|| IdeError::invalid(format!("unknown agent {id}")))?;
|
||||
let (Some(pkg), Some(builtin)) = (package(id), provider::builtin_spec(id)) else {
|
||||
return Ok(AgentCliUpdateResult::Unmanaged);
|
||||
};
|
||||
if spec.source != AgentSource::Builtin {
|
||||
return Ok(AgentCliUpdateResult::Unmanaged);
|
||||
}
|
||||
let Ok(npm) = which::which("npm") else { return Ok(AgentCliUpdateResult::Unmanaged) };
|
||||
let program = spec.resolve_for_launch(&self.shared.paths.project_root).command;
|
||||
match maintain(&npm, Path::new(&program), &builtin.command, pkg, offer, cancel) {
|
||||
Err(e) if e.kind == ErrorKind::Unavailable => Ok(AgentCliUpdateResult::Error { code: e.message }),
|
||||
result => result,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct Installation {
|
||||
modules: PathBuf,
|
||||
folder: PathBuf,
|
||||
link: PathBuf,
|
||||
}
|
||||
|
||||
impl Installation {
|
||||
fn at(prefix: &Path, pkg: &str, bin: &str) -> Self {
|
||||
let modules = prefix.join(if cfg!(windows) { "node_modules" } else { "lib/node_modules" });
|
||||
let link = if cfg!(windows) { prefix.join(format!("{bin}.cmd")) } else { prefix.join("bin").join(bin) };
|
||||
Self { folder: modules.join(pkg), modules, link }
|
||||
}
|
||||
|
||||
fn version(&self, program: &Path, pkg: &str, bin: &str) -> IdeResult<Option<String>> {
|
||||
if !program.is_absolute() || !self.folder.try_exists()? || !self.link.try_exists()? || !program.try_exists()? {
|
||||
return Ok(None);
|
||||
}
|
||||
let folder = dunce::canonicalize(&self.folder)?;
|
||||
if fs::symlink_metadata(&self.folder)?.is_symlink()
|
||||
|| dunce::canonicalize(program)? != dunce::canonicalize(&self.link)?
|
||||
{
|
||||
return Ok(None);
|
||||
}
|
||||
let manifest = self.folder.join("package.json");
|
||||
if !manifest.try_exists()? {
|
||||
return Ok(None);
|
||||
}
|
||||
let manifest: Value = serde_json::from_slice(&fs::read(manifest)?)
|
||||
.map_err(|_| IdeError::invalid("Invalid npm package manifest"))?;
|
||||
let entry = manifest["bin"].as_str().or_else(|| manifest["bin"][bin].as_str());
|
||||
let Some(entry) = entry.filter(|_| manifest["name"] == pkg) else { return Ok(None) };
|
||||
let Some(version) = manifest["version"].as_str() else {
|
||||
return Err(IdeError::invalid("Missing npm package version"));
|
||||
};
|
||||
let entry = folder.join(entry);
|
||||
if !entry.try_exists()? {
|
||||
return Ok(None);
|
||||
}
|
||||
let entry = dunce::canonicalize(entry)?;
|
||||
if !entry.starts_with(&folder) {
|
||||
return Ok(None);
|
||||
}
|
||||
#[cfg(unix)]
|
||||
let owns = fs::symlink_metadata(&self.link)?.is_symlink() && dunce::canonicalize(&self.link)? == entry;
|
||||
#[cfg(windows)]
|
||||
let owns = {
|
||||
let prefix = dunce::canonicalize(self.link.parent().unwrap())?;
|
||||
let Ok(target) = entry.strip_prefix(prefix) else { return Ok(None) };
|
||||
let needle = format!("%dp0%\\{}\"", target.display()).to_lowercase();
|
||||
fs::read_to_string(&self.link)?.replace('/', "\\").to_lowercase().contains(&needle)
|
||||
};
|
||||
Ok(owns.then(|| version.to_owned()))
|
||||
}
|
||||
|
||||
fn writable(&self) -> io::Result<bool> {
|
||||
for dir in [&*self.folder, self.folder.parent().unwrap(), &self.modules, self.link.parent().unwrap()] {
|
||||
#[cfg(unix)]
|
||||
let access: io::Result<()> =
|
||||
rustix::fs::accessat(rustix::fs::CWD, dir, rustix::fs::Access::WRITE_OK, rustix::fs::AtFlags::empty())
|
||||
.map_err(Into::into);
|
||||
#[cfg(windows)]
|
||||
let access = tempfile::tempfile_in(dir).map(drop);
|
||||
match access {
|
||||
Err(e) if matches!(e.kind(), io::ErrorKind::PermissionDenied | io::ErrorKind::ReadOnlyFilesystem) => {
|
||||
return Ok(false);
|
||||
}
|
||||
other => other?,
|
||||
}
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
}
|
||||
|
||||
fn stable(version: &str) -> Option<semver::Version> {
|
||||
semver::Version::parse(version).ok().filter(|v| v.pre.is_empty() && v.build.is_empty())
|
||||
}
|
||||
|
||||
fn maintain(
|
||||
npm: &Path,
|
||||
program: &Path,
|
||||
bin: &str,
|
||||
pkg: &str,
|
||||
approved: Option<&AgentCliOffer>,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<AgentCliUpdateResult> {
|
||||
use AgentCliUpdateResult::*;
|
||||
let run = |args: &[&str]| {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
let mut cmd = Command::new(npm);
|
||||
cmd.args(args)
|
||||
.current_dir(npm.parent().unwrap())
|
||||
.env("NPM_CONFIG_UPDATE_NOTIFIER", "false")
|
||||
.env("NPM_CONFIG_LOGLEVEL", "error");
|
||||
ide_tools::run_streamed(cmd, cancel, &|_| {}).map_err(|e| {
|
||||
if e.kind == ErrorKind::Cancelled {
|
||||
return e;
|
||||
}
|
||||
// npm diagnostics can contain private registry URLs; expose only known codes.
|
||||
let code = e
|
||||
.message
|
||||
.split(|c: char| !c.is_ascii_alphanumeric() && c != '_')
|
||||
.find(|w| {
|
||||
matches!(
|
||||
*w,
|
||||
"EACCES"
|
||||
| "EPERM"
|
||||
| "EROFS"
|
||||
| "ENOTFOUND"
|
||||
| "EAI_AGAIN"
|
||||
| "ETIMEDOUT"
|
||||
| "E404"
|
||||
| "E401"
|
||||
| "E403"
|
||||
)
|
||||
})
|
||||
.unwrap_or("npm");
|
||||
IdeError::unavailable(code)
|
||||
})
|
||||
};
|
||||
let output = run(&["prefix", "-g"])?;
|
||||
let prefix = Path::new(output.trim_end());
|
||||
if !prefix.is_absolute() {
|
||||
return Err(IdeError::invalid("Invalid npm global prefix"));
|
||||
}
|
||||
let installation = Installation::at(prefix, pkg, bin);
|
||||
let Some(current) = installation.version(program, pkg, bin)? else { return Ok(Unmanaged) };
|
||||
let latest: String = serde_json::from_str(&run(&["view", &format!("{pkg}@latest"), "version", "--json"])?)
|
||||
.map_err(|_| IdeError::invalid("Invalid npm version response"))?;
|
||||
let (Some(before), Some(after)) = (stable(¤t), stable(&latest)) else {
|
||||
return Ok(Channel { current });
|
||||
};
|
||||
if before >= after {
|
||||
return Ok(Current { current });
|
||||
}
|
||||
let offer = AgentCliOffer { current, latest, prefix: prefix.to_owned() };
|
||||
if !installation.writable()? {
|
||||
return Ok(Permission(offer));
|
||||
}
|
||||
if approved != Some(&offer) {
|
||||
return Ok(Available(offer));
|
||||
}
|
||||
run(&[
|
||||
"install",
|
||||
"-g",
|
||||
"--prefix",
|
||||
prefix.to_str().unwrap(),
|
||||
"--no-audit",
|
||||
"--no-fund",
|
||||
&format!("{pkg}@{}", offer.latest),
|
||||
])?;
|
||||
if installation.version(program, pkg, bin)?.as_ref() != Some(&offer.latest) {
|
||||
return Err(IdeError::invalid("npm installation verification failed"));
|
||||
}
|
||||
Ok(Updated { current: offer.latest })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
use tempfile::TempDir;
|
||||
|
||||
const PKG: &str = "@anthropic-ai/claude-code";
|
||||
|
||||
struct Fixture {
|
||||
root: TempDir,
|
||||
install: Installation,
|
||||
}
|
||||
|
||||
impl Fixture {
|
||||
fn new() -> Self {
|
||||
let root = tempfile::Builder::new().prefix("全局 prefix ").tempdir().unwrap();
|
||||
let install = Installation::at(root.path(), PKG, "claude");
|
||||
fs::create_dir_all(&install.folder).unwrap();
|
||||
fs::create_dir_all(install.link.parent().unwrap()).unwrap();
|
||||
fs::write(install.folder.join("entry.js"), "").unwrap();
|
||||
#[cfg(unix)]
|
||||
std::os::unix::fs::symlink(install.folder.join("entry.js"), &install.link).unwrap();
|
||||
#[cfg(windows)]
|
||||
fs::write(&install.link, r#"@"%dp0%\node_modules\@anthropic-ai\claude-code\entry.js""#).unwrap();
|
||||
let fixture = Self { root, install };
|
||||
fixture.manifest(PKG, "2.1.9");
|
||||
fixture
|
||||
}
|
||||
|
||||
fn manifest(&self, name: &str, version: &str) {
|
||||
fs::write(
|
||||
self.install.folder.join("package.json"),
|
||||
json!({"name":name,"version":version,"bin":{"claude":"entry.js"}}).to_string(),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
fn version(&self) -> Option<String> {
|
||||
self.install.version(&self.install.link, PKG, "claude").unwrap()
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn npm(&self, script: &str) -> PathBuf {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let path = self.root.path().join("npm");
|
||||
fs::write(&path, format!("#!/bin/sh\nset -eu\n{script}\n")).unwrap();
|
||||
fs::set_permissions(&path, fs::Permissions::from_mode(0o755)).unwrap();
|
||||
path
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn requires_the_selected_install_and_its_exact_package_entry() {
|
||||
let f = Fixture::new();
|
||||
assert_eq!(f.version().as_deref(), Some("2.1.9"));
|
||||
let other = f.root.path().join("other");
|
||||
fs::write(&other, "").unwrap();
|
||||
assert_eq!(f.install.version(&other, PKG, "claude").unwrap(), None);
|
||||
f.manifest("other-package", "2.1.9");
|
||||
assert_eq!(f.version(), None);
|
||||
f.manifest(PKG, "2.1.9");
|
||||
fs::remove_file(&f.install.link).unwrap();
|
||||
#[cfg(unix)]
|
||||
std::os::unix::fs::symlink(&other, &f.install.link).unwrap();
|
||||
#[cfg(windows)]
|
||||
fs::write(&f.install.link, r#"@"%dp0%\other""#).unwrap();
|
||||
assert_eq!(f.version(), None);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
const NPM: &str = r#"case "$1" in
|
||||
prefix) pwd -P ;;
|
||||
view) cat latest ;;
|
||||
install)
|
||||
test "$2" = "-g" && test "$3" = "--prefix" && test "$4" = "$(pwd -P)"
|
||||
test "$7" = "@anthropic-ai/[email protected]"
|
||||
cp updated.json "$4/lib/node_modules/@anthropic-ai/claude-code/package.json"
|
||||
touch installed ;;
|
||||
*) exit 2 ;;
|
||||
esac"#;
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn installs_only_the_confirmed_offer_and_rechecks_ownership() {
|
||||
use AgentCliUpdateResult::*;
|
||||
let f = Fixture::new();
|
||||
let npm = f.npm(NPM);
|
||||
let cancel = CancellationToken::new();
|
||||
let run =
|
||||
|offer: Option<&AgentCliOffer>| maintain(&npm, &f.install.link, "claude", PKG, offer, &cancel).unwrap();
|
||||
let latest = f.root.path().join("latest");
|
||||
fs::write(&latest, r#""2.1.12""#).unwrap();
|
||||
let Available(offer) = run(None) else { panic!("expected an offer") };
|
||||
for different in [
|
||||
AgentCliOffer { prefix: PathBuf::from("/other"), ..offer.clone() },
|
||||
AgentCliOffer { current: "2.0.0".into(), ..offer.clone() },
|
||||
] {
|
||||
assert_eq!(run(Some(&different)), Available(offer.clone()));
|
||||
}
|
||||
fs::write(&latest, r#""2.2.0""#).unwrap();
|
||||
assert!(matches!(run(Some(&offer)), Available(new) if new.latest == "2.2.0"));
|
||||
fs::write(&latest, r#""2.0.0""#).unwrap();
|
||||
assert!(matches!(run(Some(&offer)), Current { .. }));
|
||||
fs::write(&latest, r#""2.2.0-beta.1""#).unwrap();
|
||||
assert!(matches!(run(Some(&offer)), Channel { .. }));
|
||||
fs::write(&latest, r#""2.1.12""#).unwrap();
|
||||
f.manifest("other-package", "2.1.9");
|
||||
assert_eq!(run(Some(&offer)), Unmanaged);
|
||||
assert!(!f.root.path().join("installed").exists());
|
||||
f.manifest(PKG, "2.1.12");
|
||||
fs::copy(f.install.folder.join("package.json"), f.root.path().join("updated.json")).unwrap();
|
||||
f.manifest(PKG, "2.1.9");
|
||||
assert_eq!(run(Some(&offer)), Updated { current: "2.1.12".into() });
|
||||
assert!(f.root.path().join("installed").exists());
|
||||
assert_eq!(run(None), Current { current: "2.1.12".into() });
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn permission_failure_never_starts_an_install() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let f = Fixture::new();
|
||||
let npm = f.npm(NPM);
|
||||
fs::write(f.root.path().join("latest"), r#""2.1.12""#).unwrap();
|
||||
let run = |offer: Option<&AgentCliOffer>| {
|
||||
maintain(&npm, &f.install.link, "claude", PKG, offer, &CancellationToken::new()).unwrap()
|
||||
};
|
||||
let AgentCliUpdateResult::Available(offer) = run(None) else { panic!("expected an offer") };
|
||||
fs::set_permissions(&f.install.folder, fs::Permissions::from_mode(0o555)).unwrap();
|
||||
// root can write even when no mode bit grants write permission.
|
||||
if tempfile::tempfile_in(&f.install.folder).is_err() {
|
||||
assert_eq!(run(Some(&offer)), AgentCliUpdateResult::Permission(offer));
|
||||
}
|
||||
fs::set_permissions(&f.install.folder, fs::Permissions::from_mode(0o755)).unwrap();
|
||||
assert!(!f.root.path().join("installed").exists());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn cancellation_stops_a_running_npm_process() {
|
||||
use std::time::{Duration, Instant};
|
||||
let f = Fixture::new();
|
||||
let npm = f.npm(
|
||||
r#"case "$1" in
|
||||
prefix) pwd -P ;;
|
||||
view) echo '"2.1.12"' ;;
|
||||
install) touch started; exec sleep 30 ;;
|
||||
esac"#,
|
||||
);
|
||||
let cancel = CancellationToken::new();
|
||||
let AgentCliUpdateResult::Available(offer) =
|
||||
maintain(&npm, &f.install.link, "claude", PKG, None, &cancel).unwrap()
|
||||
else {
|
||||
panic!("expected an offer")
|
||||
};
|
||||
let started = f.root.path().join("started");
|
||||
std::thread::scope(|s| {
|
||||
let op = s.spawn(|| maintain(&npm, &f.install.link, "claude", PKG, Some(&offer), &cancel));
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
while !started.exists() && Instant::now() < deadline {
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
cancel.cancel();
|
||||
assert!(started.exists());
|
||||
assert_eq!(op.join().unwrap().unwrap_err().kind, ErrorKind::Cancelled);
|
||||
});
|
||||
assert_eq!(f.version().as_deref(), Some("2.1.9"));
|
||||
}
|
||||
}
|
||||
+28
-138
@@ -3,7 +3,7 @@
|
||||
|
||||
use crate::model::{
|
||||
AgentCommand, AgentCommandSource, AgentConfigOption, AgentConfigValue, AgentConfigVia, AgentCost, AgentLimit,
|
||||
AgentModelPricing, AgentTokens, AgentUsage,
|
||||
AgentModelPricing, AgentUsage,
|
||||
};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
@@ -65,7 +65,7 @@ fn bypass_value(category: &str) -> Option<fn(&str) -> bool> {
|
||||
}
|
||||
|
||||
/// Moves options that approve everything without asking to a value that asks: the agent's
|
||||
/// own default (when it asks), else `default` or `ask`, else its first one that asks.
|
||||
/// default or ask mode, else its first one that asks.
|
||||
pub(crate) fn ask_for_approvals(config: &mut [AgentConfigOption]) {
|
||||
for option in config {
|
||||
let Some(bypass) = option.category.as_deref().and_then(bypass_value) else { continue };
|
||||
@@ -73,15 +73,9 @@ pub(crate) fn ask_for_approvals(config: &mut [AgentConfigOption]) {
|
||||
continue;
|
||||
}
|
||||
let asks = |v: &&AgentConfigValue| !bypass(&v.value);
|
||||
let value = option
|
||||
.default_value
|
||||
.as_deref()
|
||||
.and_then(|def| option.values.iter().filter(asks).find(|v| v.value == def))
|
||||
.or_else(|| {
|
||||
["default", "ask"]
|
||||
.iter()
|
||||
.find_map(|preferred| option.values.iter().filter(asks).find(|v| v.value == *preferred))
|
||||
})
|
||||
let value = ["default", "ask"]
|
||||
.iter()
|
||||
.find_map(|preferred| option.values.iter().filter(asks).find(|v| v.value == *preferred))
|
||||
.or_else(|| option.values.iter().find(asks));
|
||||
if let Some(value) = value {
|
||||
option.current = Some(value.value.clone());
|
||||
@@ -89,26 +83,11 @@ pub(crate) fn ask_for_approvals(config: &mut [AgentConfigOption]) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Moves approval-bearing options (`mode`, `permissions`, `approval`) to their approving value.
|
||||
pub(crate) fn apply_bypass_approvals(config: &mut [AgentConfigOption]) {
|
||||
for option in config {
|
||||
let Some(bypass) = option.category.as_deref().and_then(bypass_value) else { continue };
|
||||
if let Some(value) = option.values.iter().find(|v| bypass(&v.value)) {
|
||||
option.current = Some(value.value.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Applies provider-specific defaults to per-model options for new tasks without altering `default_value`.
|
||||
pub(crate) fn apply_model_defaults(provider: &str, options: &mut [AgentConfigOption]) {
|
||||
if provider != "cursor" {
|
||||
return;
|
||||
}
|
||||
if let Some(fast) = options.iter_mut().find(|o| is_fast_option(&o.id))
|
||||
&& fast.values.iter().any(|v| v.value == "false")
|
||||
{
|
||||
fast.current = Some("false".into());
|
||||
}
|
||||
/// The mode that approves everything without asking (`bypassPermissions`, `yolo`, `full-access`…), if the agent has one.
|
||||
pub(crate) fn bypass_mode(options: &[AgentConfigOption]) -> Option<(&AgentConfigOption, &AgentConfigValue)> {
|
||||
let option = options.iter().find(|o| o.category.as_deref() == Some("mode"))?;
|
||||
let value = option.values.iter().find(|v| is_bypass_mode(&v.value))?;
|
||||
Some((option, value))
|
||||
}
|
||||
|
||||
fn is_bypass_mode(mode: &str) -> bool {
|
||||
@@ -147,20 +126,14 @@ pub(crate) fn options_of(result: &Value) -> Vec<AgentConfigOption> {
|
||||
}
|
||||
|
||||
pub(crate) fn is_context_option(id: &str) -> bool {
|
||||
matches!(id, "context" | "context_tier" | "contextTier")
|
||||
}
|
||||
|
||||
pub(crate) fn is_fast_option(id: &str) -> bool {
|
||||
id == "fast"
|
||||
matches!(id, "context_tier" | "contextTier")
|
||||
}
|
||||
|
||||
/// Whether an option's available values and default belong to the selected model
|
||||
/// (`thought_level`, `context_tier`, and `model_config` options like `context` and `fast`)
|
||||
/// rather than the provider as a whole.
|
||||
/// (`thought_level` and model context-tier options) rather than the provider as a whole.
|
||||
pub(crate) fn is_per_model_option(o: &AgentConfigOption) -> bool {
|
||||
matches!(o.category.as_deref(), Some("thought_level" | "context_tier" | "model_config"))
|
||||
matches!(o.category.as_deref(), Some("thought_level" | "context_tier"))
|
||||
|| matches!(o.id.as_str(), "effort" | "reasoning_effort" | "thinking" | "reasoning")
|
||||
|| is_fast_option(&o.id)
|
||||
|| is_context_option(&o.id)
|
||||
}
|
||||
|
||||
@@ -191,7 +164,7 @@ pub(crate) fn parse_options(options: &Value) -> Vec<AgentConfigOption> {
|
||||
matches!(id.as_str(), "effort" | "reasoning_effort" | "thinking" | "reasoning")
|
||||
.then(|| "thought_level".into())
|
||||
})
|
||||
.or_else(|| (is_fast_option(&id) || is_context_option(&id)).then(|| "model_config".into()))
|
||||
.or_else(|| (id == "fast" || is_context_option(&id)).then(|| "model_config".into()))
|
||||
}),
|
||||
current,
|
||||
default_value,
|
||||
@@ -246,23 +219,6 @@ pub(crate) fn set_request(option: &AgentConfigOption, value: &str) -> (&'static
|
||||
}
|
||||
}
|
||||
|
||||
/// Legacy setters and agents that report the change in a notification may return no model.
|
||||
pub(super) fn accepts_model(reply: &Value, id: &str, value: &str) -> bool {
|
||||
reply
|
||||
.get("configOptions")
|
||||
.and_then(Value::as_array)
|
||||
.and_then(|options| {
|
||||
options.iter().find(|option| {
|
||||
option.get("category").and_then(Value::as_str) == Some("model")
|
||||
|| option.get("id").or_else(|| option.get("configId")).and_then(Value::as_str) == Some(id)
|
||||
})
|
||||
})
|
||||
.and_then(|option| option.get("currentValue"))
|
||||
.or_else(|| reply.pointer("/models/currentModelId"))
|
||||
.and_then(Value::as_str)
|
||||
.is_none_or(|current| current == value)
|
||||
}
|
||||
|
||||
/// `available_commands_update`.
|
||||
pub(crate) fn commands_of(update: &Value, provider: &str) -> Vec<AgentCommand> {
|
||||
update
|
||||
@@ -299,18 +255,6 @@ pub(crate) fn usage_of(update: &Value) -> Option<AgentUsage> {
|
||||
Some(AgentUsage { used: tokens("used")?, size: tokens("size").filter(|s| *s > 0)?, cost })
|
||||
}
|
||||
|
||||
/// The `usage` of a `session/prompt` result: `{ inputTokens, cachedReadTokens, outputTokens }`.
|
||||
pub(crate) fn tokens_of(result: &Value) -> Option<AgentTokens> {
|
||||
let usage = result.get("usage")?;
|
||||
let tokens = |key: &str| usage.get(key).and_then(Value::as_u64).map_or(0, |n| u32::try_from(n).unwrap_or(u32::MAX));
|
||||
let tokens = AgentTokens {
|
||||
input: tokens("inputTokens"),
|
||||
cached: tokens("cachedReadTokens"),
|
||||
output: tokens("outputTokens"),
|
||||
};
|
||||
(tokens != AgentTokens::default()).then_some(tokens)
|
||||
}
|
||||
|
||||
/// The usage-limit windows a [`crate::LIMITS_UPDATE`] carries; malformed entries are skipped.
|
||||
pub(crate) fn limits_of(update: &Value) -> Vec<AgentLimit> {
|
||||
let limits = update.get("limits").and_then(Value::as_array).into_iter().flatten();
|
||||
@@ -364,11 +308,6 @@ fn legacy(
|
||||
}
|
||||
}
|
||||
|
||||
fn clean_label(s: String, fallback: &str) -> String {
|
||||
let trimmed = s.trim_matches(|c: char| c.is_whitespace() || matches!(c, '\u{200B}'..='\u{200D}' | '\u{FEFF}'));
|
||||
if trimmed.is_empty() { fallback.to_owned() } else { trimmed.to_owned() }
|
||||
}
|
||||
|
||||
fn value_of(v: &Value) -> Option<AgentConfigValue> {
|
||||
let value = v.get("value")?.as_str()?.to_owned();
|
||||
let meta = v.get("_meta");
|
||||
@@ -384,7 +323,7 @@ fn value_of(v: &Value) -> Option<AgentConfigValue> {
|
||||
.filter(|s| !s.is_empty())
|
||||
.map(str::to_owned);
|
||||
Some(AgentConfigValue {
|
||||
name: str_of(v, "name").map(|n| clean_label(n, &value)).unwrap_or_else(|| value.clone()),
|
||||
name: str_of(v, "name").unwrap_or_else(|| value.clone()),
|
||||
description: str_of(v, "description"),
|
||||
cost_category,
|
||||
usage_multiplier,
|
||||
@@ -412,15 +351,6 @@ mod tests {
|
||||
c.iter().map(|o| (o.id.as_str(), o.current.as_deref())).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_hermes_prompt_result_reports_the_turns_tokens() {
|
||||
let result = json!({"stopReason": "end_turn", "usage": {"cachedReadTokens": 51306, "inputTokens": 77284,
|
||||
"outputTokens": 509, "thoughtTokens": 0, "totalTokens": 77793}});
|
||||
assert_eq!(tokens_of(&result), Some(AgentTokens { input: 77284, cached: 51306, output: 509 }));
|
||||
assert_eq!(tokens_of(&json!({"stopReason": "end_turn"})), None);
|
||||
assert_eq!(tokens_of(&json!({"usage": {}})), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn config_options_win_over_the_older_fields() {
|
||||
let r = json!({
|
||||
@@ -466,16 +396,19 @@ mod tests {
|
||||
]}
|
||||
}));
|
||||
assert!(bypass_approvals(&full_access));
|
||||
assert_eq!(bypass_mode(&full_access).map(|(_, v)| v.value.as_str()), Some("full-access"));
|
||||
|
||||
let mut asking = options_of(&json!({
|
||||
let asking = options_of(&json!({
|
||||
"modes": {"currentModeId": "ask", "availableModes": [
|
||||
{"id": "ask", "name": "Ask"}, {"id": "full-access", "name": "Full Access"}
|
||||
]}
|
||||
}));
|
||||
assert!(!bypass_approvals(&asking));
|
||||
apply_bypass_approvals(&mut asking);
|
||||
assert_eq!(asking[0].current.as_deref(), Some("full-access"));
|
||||
assert!(bypass_approvals(&asking));
|
||||
assert_eq!(
|
||||
bypass_mode(&asking).map(|(_, v)| v.value.as_str()),
|
||||
Some("full-access"),
|
||||
"the offered bypass mode stays available"
|
||||
);
|
||||
|
||||
let permissions = |current: &str| {
|
||||
options_of(&json!({"configOptions": [{
|
||||
@@ -532,7 +465,7 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn effort_context_and_fast_are_per_model_options() {
|
||||
fn effort_and_fast_categories_are_inferred_from_ids() {
|
||||
let mut c = options_of(&json!({
|
||||
"configOptions": [
|
||||
{"id": "model", "type": "select", "currentValue": "gemini-4-carbon",
|
||||
@@ -541,39 +474,19 @@ mod tests {
|
||||
"_meta": {"copilotPriceCategory": "Medium", "copilotUsage": "1x"}}]},
|
||||
{"id": "effort", "type": "select", "currentValue": "medium",
|
||||
"options": [{"value": "low"}, {"value": "medium"}, {"value": "high"}]},
|
||||
{"id": "context", "type": "select", "currentValue": "256k",
|
||||
"options": [{"value": "256k", "name": "256K"}, {"value": "500k", "name": "500K"}]},
|
||||
{"id": "contextTier", "type": "select", "currentValue": "default",
|
||||
"options": [{"value": "default", "name": "200K"}, {"value": "long_context", "name": "1M"}]},
|
||||
{"id": "fast", "type": "select", "currentValue": "true",
|
||||
"options": [{"value": "false", "name": "Off"}, {"value": "true", "name": "Fast\u{200b}\u{200b}"}]}
|
||||
{"id": "fast", "type": "select", "currentValue": "false",
|
||||
"options": [{"value": "false", "name": "Off"}, {"value": "true", "name": "On"}]}
|
||||
]
|
||||
}));
|
||||
assert_eq!(c.len(), 5);
|
||||
assert_eq!(c.len(), 4);
|
||||
assert_eq!(c[0].values[0].cost_category.as_deref(), Some("medium"));
|
||||
assert_eq!(c[0].values[0].usage_multiplier.as_deref(), Some("1x"));
|
||||
assert_eq!(c[1].category.as_deref(), Some("thought_level"));
|
||||
assert_eq!(c[1].default_value.as_deref(), Some("medium"));
|
||||
assert_eq!(c[2].category.as_deref(), Some("model_config"));
|
||||
assert_eq!(c[3].category.as_deref(), Some("model_config"));
|
||||
assert_eq!(c[4].category.as_deref(), Some("model_config"));
|
||||
assert_eq!(c[4].values[1].name, "Fast");
|
||||
assert!(
|
||||
is_per_model_option(&c[1])
|
||||
&& is_per_model_option(&c[2])
|
||||
&& is_per_model_option(&c[3])
|
||||
&& is_per_model_option(&c[4])
|
||||
);
|
||||
assert!(!is_per_model_option(&c[0]));
|
||||
|
||||
// Cursor defaults fast off for new tasks while preserving the agent's own default_value.
|
||||
let mut cursor_opts = c.clone();
|
||||
apply_model_defaults("cursor", &mut cursor_opts);
|
||||
let fast = cursor_opts.iter().find(|o| o.id == "fast").unwrap();
|
||||
assert_eq!((fast.current.as_deref(), fast.default_value.as_deref()), (Some("false"), Some("true")));
|
||||
let mut other_opts = c.clone();
|
||||
apply_model_defaults("claude", &mut other_opts);
|
||||
assert_eq!(other_opts.iter().find(|o| o.id == "fast").unwrap().current.as_deref(), Some("true"));
|
||||
assert!(is_per_model_option(&c[1]) && is_per_model_option(&c[2]) && !is_per_model_option(&c[3]));
|
||||
|
||||
// Editing effort on the same model preserves its initial `default_value` for Reset.
|
||||
merge_update(
|
||||
@@ -595,34 +508,11 @@ mod tests {
|
||||
{"id": "model", "type": "select", "currentValue": "gpt-6-sol",
|
||||
"options": [{"value": "gemini-4-carbon"}, {"value": "gpt-6-sol"}]},
|
||||
{"id": "effort", "type": "select", "currentValue": "low",
|
||||
"options": [{"value": "low"}, {"value": "medium"}, {"value": "high"}]},
|
||||
{"id": "context", "type": "select", "currentValue": "1m",
|
||||
"options": [{"value": "300k", "name": "300K"}, {"value": "1m", "name": "1M"}]}
|
||||
"options": [{"value": "low"}, {"value": "medium"}, {"value": "high"}]}
|
||||
]),
|
||||
);
|
||||
let effort = c.iter().find(|o| o.id == "effort").unwrap();
|
||||
assert_eq!((effort.current.as_deref(), effort.default_value.as_deref()), (Some("low"), Some("low")));
|
||||
let context = c.iter().find(|o| o.id == "context").unwrap();
|
||||
assert_eq!((context.current.as_deref(), context.default_value.as_deref()), (Some("1m"), Some("1m")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn apply_bypass_approvals_covers_mode_permissions_and_approval() {
|
||||
let mut c = options_of(&json!({"configOptions": [
|
||||
{"id": "mode", "category": "mode", "type": "select", "currentValue": "ask",
|
||||
"options": [{"value": "ask"}, {"value": "full-access"}]},
|
||||
{"id": "allow_all", "category": "permissions", "type": "select", "currentValue": "off",
|
||||
"options": [{"value": "off"}, {"value": "on"}]},
|
||||
{"id": "approval", "category": "approval", "type": "select", "currentValue": "ask",
|
||||
"options": [{"value": "ask"}, {"value": "bypass"}]}
|
||||
]}));
|
||||
apply_bypass_approvals(&mut c);
|
||||
assert_eq!(ids(&c), [("mode", Some("full-access")), ("allow_all", Some("on")), ("approval", Some("bypass"))]);
|
||||
// Original agent default_values stay intact.
|
||||
assert_eq!(
|
||||
c.iter().map(|o| o.default_value.as_deref()).collect::<Vec<_>>(),
|
||||
[Some("ask"), Some("off"), Some("ask")]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -1,111 +0,0 @@
|
||||
//! Hermes Agent profiles on disk: `default` is the Hermes home itself, the others are
|
||||
//! `<home>/profiles/<name>` directories holding one of Hermes' identity files.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use serde::Serialize;
|
||||
use specta::Type;
|
||||
|
||||
const PROFILE_FILES: &[&str] = &["config.yaml", ".env", "SOUL.md", "profile.yaml", "auth.json", "state.db"];
|
||||
|
||||
/// Hermes' home directory (`~/.hermes`; `%LOCALAPPDATA%\hermes` on Windows).
|
||||
pub fn root(home: Option<&Path>) -> Option<PathBuf> {
|
||||
#[cfg(windows)]
|
||||
if let Some(local) = std::env::var_os("LOCALAPPDATA") {
|
||||
return Some(PathBuf::from(local).join("hermes"));
|
||||
}
|
||||
home.map(|h| h.join(".hermes"))
|
||||
}
|
||||
|
||||
/// The profile names under `root`: `default` first, then the others by name; none without `root`.
|
||||
pub fn profiles(root: &Path) -> Vec<String> {
|
||||
if !root.is_dir() {
|
||||
return Vec::new();
|
||||
}
|
||||
let mut named: Vec<String> = std::fs::read_dir(root.join("profiles"))
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.flatten()
|
||||
.filter(|e| PROFILE_FILES.iter().any(|f| e.path().join(f).exists()))
|
||||
.filter_map(|e| e.file_name().to_str().map(str::to_owned))
|
||||
.filter(|name| name != "default")
|
||||
.collect();
|
||||
named.sort();
|
||||
std::iter::once("default".to_owned()).chain(named).collect()
|
||||
}
|
||||
|
||||
/// A profile and the name Hermes shows for it (`hermes profile list`).
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Type)]
|
||||
pub struct HermesProfile {
|
||||
/// What `hermes -p` takes; `default` is the Hermes home itself.
|
||||
pub name: String,
|
||||
/// `display_name` from the profile's `profile.yaml`, else the name.
|
||||
pub label: String,
|
||||
}
|
||||
|
||||
/// [`profiles`] with the names Hermes shows for them.
|
||||
pub fn labeled_profiles(root: &Path) -> Vec<HermesProfile> {
|
||||
profiles(root)
|
||||
.into_iter()
|
||||
.map(|name| {
|
||||
let home = if name == "default" { root.to_path_buf() } else { root.join("profiles").join(&name) };
|
||||
let label = display_name(&home).unwrap_or_else(|| name.clone());
|
||||
HermesProfile { name, label }
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The top-level `display_name:` of `<home>/profile.yaml`, the only key read (no YAML parser).
|
||||
fn display_name(home: &Path) -> Option<String> {
|
||||
let text = std::fs::read_to_string(home.join("profile.yaml")).ok()?;
|
||||
let value = text.lines().find_map(|l| l.strip_prefix("display_name:"))?;
|
||||
let value = value.trim().trim_matches(['"', '\'']).trim();
|
||||
(!value.is_empty()).then(|| value.to_owned())
|
||||
}
|
||||
|
||||
/// The home of the profile an agent id stands for: `hermes` and `hermes-default` are the
|
||||
/// default profile, `hermes-<slug>` the profile whose name slugifies to `<slug>`.
|
||||
pub fn profile_home(root: &Path, provider: &str) -> Option<PathBuf> {
|
||||
let slug = match provider {
|
||||
"hermes" | "hermes-default" => return Some(root.to_path_buf()),
|
||||
_ => provider.strip_prefix("hermes-")?,
|
||||
};
|
||||
profiles(root).into_iter().find(|p| crate::provider::slugify_id(p) == slug).map(|p| root.join("profiles").join(p))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn lists_default_and_profiles_with_an_identity_file() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
assert!(profiles(&dir.path().join("missing")).is_empty());
|
||||
let root = dir.path().join(".hermes");
|
||||
std::fs::create_dir_all(root.join("profiles/empty")).unwrap();
|
||||
assert_eq!(profiles(&root), ["default"]);
|
||||
for (name, file) in [("work", "config.yaml"), ("Dom 2", "SOUL.md"), ("db", "state.db")] {
|
||||
std::fs::create_dir_all(root.join("profiles").join(name)).unwrap();
|
||||
std::fs::write(root.join("profiles").join(name).join(file), "").unwrap();
|
||||
}
|
||||
std::fs::write(root.join("profiles/stray.yaml"), "").unwrap();
|
||||
assert_eq!(profiles(&root), ["default", "Dom 2", "db", "work"]);
|
||||
assert_eq!(profile_home(&root, "hermes"), Some(root.clone()));
|
||||
assert_eq!(profile_home(&root, "hermes-dom-2"), Some(root.join("profiles/Dom 2")));
|
||||
assert_eq!(profile_home(&root, "hermes-empty"), None);
|
||||
assert_eq!(profile_home(&root, "claude"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn labels_profiles_with_their_display_name() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path().join(".hermes");
|
||||
std::fs::create_dir_all(root.join("profiles/work")).unwrap();
|
||||
std::fs::write(root.join("profile.yaml"), "description: mine\ndisplay_name: \"qb\"\n").unwrap();
|
||||
std::fs::write(root.join("profiles/work/profile.yaml"), "ui_meta:\n display_name: nested\n").unwrap();
|
||||
let label = |name: &str, label: &str| HermesProfile { name: name.into(), label: label.into() };
|
||||
assert_eq!(labeled_profiles(&root), [label("default", "qb"), label("work", "work")]);
|
||||
std::fs::remove_file(root.join("profile.yaml")).unwrap();
|
||||
assert_eq!(labeled_profiles(&root)[0], label("default", "default"));
|
||||
}
|
||||
}
|
||||
@@ -1,143 +0,0 @@
|
||||
//! Images in agent content: ACP content blocks, `data:` URLs and image files on disk.
|
||||
|
||||
use crate::model::AgentImage;
|
||||
use base64::Engine;
|
||||
use serde_json::{Value, json};
|
||||
use std::path::Path;
|
||||
|
||||
/// Image files larger than this are not inlined into the conversation.
|
||||
const MAX_FILE_BYTES: u64 = 10 * 1024 * 1024;
|
||||
|
||||
/// The image an ACP content block shows: an `image` (inline or by URI), a `resource` with an
|
||||
/// image blob, or a `resource_link` to an image file.
|
||||
pub(crate) fn from_content(content: &Value) -> Option<AgentImage> {
|
||||
match str_of(content, "type")? {
|
||||
"image" => {
|
||||
if let (Some(data), Some(mime)) = (str_of(content, "data"), str_of(content, "mimeType"))
|
||||
&& mime.starts_with("image/")
|
||||
{
|
||||
return Some(AgentImage { mime_type: mime.into(), data: data.into(), name: None });
|
||||
}
|
||||
from_uri(str_of(content, "uri")?)
|
||||
}
|
||||
"resource" => {
|
||||
let resource = content.get("resource")?;
|
||||
let (data, mime) = (str_of(resource, "blob")?, str_of(resource, "mimeType")?);
|
||||
mime.starts_with("image/").then(|| AgentImage { mime_type: mime.into(), data: data.into(), name: None })
|
||||
}
|
||||
"resource_link" => {
|
||||
let uri = str_of(content, "uri")?;
|
||||
let declared = str_of(content, "mimeType").is_some_and(|m| m.starts_with("image/"));
|
||||
if !declared && mime_of(Path::new(&uri_path(uri))).is_none() {
|
||||
return None;
|
||||
}
|
||||
let mut image = from_uri(uri)?;
|
||||
image.name = str_of(content, "name").map(str::to_owned);
|
||||
Some(image)
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn str_of<'a>(v: &'a Value, key: &str) -> Option<&'a str> {
|
||||
v.get(key).and_then(Value::as_str).filter(|s| !s.is_empty())
|
||||
}
|
||||
|
||||
/// The image at a `data:` URL or a `file://` URI.
|
||||
pub(crate) fn from_uri(uri: &str) -> Option<AgentImage> {
|
||||
if let Some(rest) = uri.strip_prefix("data:") {
|
||||
let (mime, data) = rest.split_once(";base64,")?;
|
||||
return (mime.starts_with("image/") && !data.is_empty()).then(|| AgentImage {
|
||||
mime_type: mime.into(),
|
||||
data: data.into(),
|
||||
name: None,
|
||||
});
|
||||
}
|
||||
uri.starts_with("file://").then(|| from_file(Path::new(&uri_path(uri))))?
|
||||
}
|
||||
|
||||
/// The image file at `path`, when it has an image extension and isn't too large.
|
||||
pub(crate) fn from_file(path: &Path) -> Option<AgentImage> {
|
||||
let mime = mime_of(path)?;
|
||||
if std::fs::metadata(path).ok()?.len() > MAX_FILE_BYTES {
|
||||
return None;
|
||||
}
|
||||
let bytes = std::fs::read(path).ok()?;
|
||||
(!bytes.is_empty()).then(|| AgentImage {
|
||||
mime_type: mime.into(),
|
||||
data: base64::engine::general_purpose::STANDARD.encode(bytes),
|
||||
name: path.file_name().and_then(|n| n.to_str()).map(str::to_owned),
|
||||
})
|
||||
}
|
||||
|
||||
/// `image` as an ACP image content block.
|
||||
pub(crate) fn content(image: &AgentImage) -> Value {
|
||||
json!({ "type": "image", "mimeType": image.media_type(), "data": image.data })
|
||||
}
|
||||
|
||||
fn mime_of(path: &Path) -> Option<&'static str> {
|
||||
let ext = path.extension()?.to_str()?.to_ascii_lowercase();
|
||||
Some(match ext.as_str() {
|
||||
"png" => "image/png",
|
||||
"jpg" | "jpeg" => "image/jpeg",
|
||||
"gif" => "image/gif",
|
||||
"webp" => "image/webp",
|
||||
"bmp" => "image/bmp",
|
||||
"svg" => "image/svg+xml",
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// The path of a `file://` URI (percent-decoded); other URIs as they are.
|
||||
pub(crate) fn uri_path(uri: &str) -> String {
|
||||
let Some(rest) = uri.strip_prefix("file://") else { return uri.to_owned() };
|
||||
let bytes = rest.as_bytes();
|
||||
let mut out = Vec::with_capacity(bytes.len());
|
||||
let mut i = 0;
|
||||
while i < bytes.len() {
|
||||
if bytes[i] == b'%'
|
||||
&& let Some(b) = rest.get(i + 1..i + 3).and_then(|h| u8::from_str_radix(h, 16).ok())
|
||||
{
|
||||
out.push(b);
|
||||
i += 3;
|
||||
} else {
|
||||
out.push(bytes[i]);
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
let path = String::from_utf8_lossy(&out).into_owned();
|
||||
// `file:///C:/x` on Windows.
|
||||
match path.as_bytes() {
|
||||
[b'/', drive, b':', ..] if drive.is_ascii_alphabetic() => path[1..].to_owned(),
|
||||
_ => path,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn content_blocks_inline_data_urls_blobs_and_image_files() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let file = dir.path().join("shot 1.png");
|
||||
std::fs::write(&file, b"\x89PNG\r\n").unwrap();
|
||||
std::fs::write(dir.path().join("notes.txt"), b"hi").unwrap();
|
||||
let uri = crate::file_uri(&file);
|
||||
let inline = json!({"type": "image", "mimeType": "image/png", "data": "aW1n"});
|
||||
assert_eq!(from_content(&inline).unwrap().data, "aW1n");
|
||||
let by_url = json!({"type": "image", "uri": "data:image/jpeg;base64,AAA"});
|
||||
assert_eq!(from_content(&by_url).unwrap().mime_type, "image/jpeg");
|
||||
let by_file = from_content(&json!({"type": "image", "uri": uri})).unwrap();
|
||||
assert_eq!(by_file.data, base64::engine::general_purpose::STANDARD.encode(b"\x89PNG\r\n"));
|
||||
let blob = json!({"type": "resource", "resource": {"uri": "x", "mimeType": "image/gif", "blob": "R0lG"}});
|
||||
assert_eq!(from_content(&blob).unwrap().mime_type, "image/gif");
|
||||
let link = from_content(&json!({"type": "resource_link", "uri": uri, "name": "shot"})).unwrap();
|
||||
assert_eq!((link.mime_type.as_str(), link.name.as_deref()), ("image/png", Some("shot")));
|
||||
let text = crate::file_uri(&dir.path().join("notes.txt"));
|
||||
assert!(from_content(&json!({"type": "resource_link", "uri": text, "name": "notes"})).is_none());
|
||||
assert!(from_content(&json!({"type": "resource", "resource": {"uri": "x", "text": "t"}})).is_none());
|
||||
assert!(from_content(&json!({"type": "image", "uri": "https://example.com/a.png"})).is_none());
|
||||
assert!(from_file(&dir.path().join("missing.png")).is_none());
|
||||
}
|
||||
}
|
||||
+560
-1936
File diff suppressed because it is too large.
Load diff
+150
-548
@@ -10,7 +10,7 @@ use crate::{
|
||||
};
|
||||
use ide_core::IpcPath;
|
||||
use serde_json::{Value, json};
|
||||
use std::collections::{BTreeMap, BTreeSet, HashSet};
|
||||
use std::collections::{BTreeMap, HashSet};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
@@ -86,66 +86,6 @@ fn matches_agent(agents: &[String], provider: &str) -> bool {
|
||||
})
|
||||
}
|
||||
|
||||
/// The configured servers off for this session: off by default and not switched on for it, or
|
||||
/// switched off for it. Named so an agent that also loads its own configuration can keep a
|
||||
/// same-named server of it off too. Workspace entries take precedence, as in [`acp_mcp_servers`].
|
||||
pub(crate) fn servers_off(all: &[McpServer], provider: &str, overrides: &BTreeMap<String, bool>) -> Vec<String> {
|
||||
let mut seen_configured = HashSet::new();
|
||||
let mut enabled_names = HashSet::new();
|
||||
let mut off = BTreeSet::new();
|
||||
|
||||
let ordered = all
|
||||
.iter()
|
||||
.filter(|s| s.scope == McpScope::Workspace && !s.unapproved)
|
||||
.chain(all.iter().filter(|s| s.scope == McpScope::User));
|
||||
|
||||
for srv in ordered {
|
||||
if !seen_configured.insert(srv.name.as_str()) {
|
||||
continue;
|
||||
}
|
||||
let explicit = overrides.get(&srv.name).copied();
|
||||
let matches = explicit == Some(true) || matches_agent(&srv.agents, provider);
|
||||
let active = explicit.unwrap_or(srv.enabled) && matches;
|
||||
if active {
|
||||
enabled_names.insert(srv.name.as_str());
|
||||
} else {
|
||||
off.insert(srv.name.clone());
|
||||
}
|
||||
}
|
||||
|
||||
for srv in all.iter().filter(|s| s.scope == McpScope::Workspace && s.unapproved) {
|
||||
if !enabled_names.contains(srv.name.as_str()) {
|
||||
off.insert(srv.name.clone());
|
||||
}
|
||||
}
|
||||
|
||||
// A server switched off that the IDE doesn't configure may still be the agent's own.
|
||||
for (name, &on) in overrides {
|
||||
if !on && name.as_str() != BUILTIN_MCP_NAME && !enabled_names.contains(name.as_str()) {
|
||||
off.insert(name.clone());
|
||||
}
|
||||
}
|
||||
|
||||
off.into_iter().collect()
|
||||
}
|
||||
|
||||
/// Names of MCP servers present in Codex's own TOML configuration files (`~/.codex/config.toml`
|
||||
/// and `<workspace_root>/.codex/config.toml`).
|
||||
pub(crate) fn codex_external_server_names(home_dir: Option<&Path>, workspace_root: &Path) -> BTreeSet<String> {
|
||||
let mut names = BTreeSet::new();
|
||||
let mut paths = Vec::new();
|
||||
if let Some(home) = home_dir {
|
||||
paths.push(home.join(".codex").join("config.toml"));
|
||||
}
|
||||
paths.push(workspace_root.join(".codex").join("config.toml"));
|
||||
for path in paths {
|
||||
if let Ok(text) = std::fs::read_to_string(&path) {
|
||||
names.extend(parse_codex_toml_servers(&text).into_keys());
|
||||
}
|
||||
}
|
||||
names
|
||||
}
|
||||
|
||||
/// Builds the ACP `mcpServers` array for `session/new`, `session/load`, and `session/fork`.
|
||||
/// Workspace entries take precedence over User entries with the same name. Per-session
|
||||
/// `overrides` (`server_name` -> `enabled`) can enable a disabled server or disable an enabled one
|
||||
@@ -399,429 +339,163 @@ pub fn apply_save_json(
|
||||
Ok(saved_names)
|
||||
}
|
||||
|
||||
const COPILOT_PLUGIN_MANIFESTS: &[&str] = &[
|
||||
".github/plugin/plugin.json",
|
||||
".plugin/plugin.json",
|
||||
".claude-plugin/plugin.json",
|
||||
".cursor-plugin/plugin.json",
|
||||
"plugin.json",
|
||||
];
|
||||
|
||||
#[derive(Clone, PartialEq, Eq)]
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum SourceFormat {
|
||||
Jsonc,
|
||||
CodexToml,
|
||||
CopilotPlugin { root: PathBuf },
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct SourceSpec {
|
||||
id: String,
|
||||
label: String,
|
||||
id: &'static str,
|
||||
label: &'static str,
|
||||
path: PathBuf,
|
||||
format: SourceFormat,
|
||||
suggested_scope: McpScope,
|
||||
native_provider: Option<&'static str>,
|
||||
claude_project_lookup: bool,
|
||||
disabled_servers: std::sync::Arc<BTreeSet<String>>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct CopilotSettings {
|
||||
disabled_mcp_servers: std::sync::Arc<BTreeSet<String>>,
|
||||
disabled_plugins: BTreeSet<String>,
|
||||
}
|
||||
|
||||
fn external_source_specs(home_dir: Option<&Path>, workspace_root: Option<&Path>) -> Vec<SourceSpec> {
|
||||
let mut specs = Vec::new();
|
||||
let no_disabled: std::sync::Arc<BTreeSet<String>> = std::sync::Arc::new(BTreeSet::new());
|
||||
if let Some(root) = workspace_root {
|
||||
specs.push(SourceSpec {
|
||||
id: "workspace-mcp".into(),
|
||||
label: "Project (.mcp.json)".into(),
|
||||
id: "workspace-mcp",
|
||||
label: "Project (.mcp.json)",
|
||||
path: root.join(".mcp.json"),
|
||||
format: SourceFormat::Jsonc,
|
||||
suggested_scope: McpScope::Workspace,
|
||||
native_provider: Some("claude"),
|
||||
claude_project_lookup: false,
|
||||
disabled_servers: no_disabled.clone(),
|
||||
});
|
||||
specs.push(SourceSpec {
|
||||
id: "vscode-mcp".into(),
|
||||
label: "VS Code (.vscode/mcp.json)".into(),
|
||||
id: "vscode-mcp",
|
||||
label: "VS Code (.vscode/mcp.json)",
|
||||
path: root.join(".vscode").join("mcp.json"),
|
||||
format: SourceFormat::Jsonc,
|
||||
suggested_scope: McpScope::Workspace,
|
||||
native_provider: None,
|
||||
claude_project_lookup: false,
|
||||
disabled_servers: no_disabled.clone(),
|
||||
});
|
||||
specs.push(SourceSpec {
|
||||
id: "cursor-project".into(),
|
||||
label: "Cursor Project (.cursor/mcp.json)".into(),
|
||||
id: "cursor-project",
|
||||
label: "Cursor Project (.cursor/mcp.json)",
|
||||
path: root.join(".cursor").join("mcp.json"),
|
||||
format: SourceFormat::Jsonc,
|
||||
suggested_scope: McpScope::Workspace,
|
||||
native_provider: Some("cursor"),
|
||||
claude_project_lookup: false,
|
||||
disabled_servers: no_disabled.clone(),
|
||||
});
|
||||
specs.push(SourceSpec {
|
||||
id: "codex-project".into(),
|
||||
label: "Codex Project (.codex/config.toml)".into(),
|
||||
id: "codex-project",
|
||||
label: "Codex Project (.codex/config.toml)",
|
||||
path: root.join(".codex").join("config.toml"),
|
||||
format: SourceFormat::CodexToml,
|
||||
suggested_scope: McpScope::Workspace,
|
||||
native_provider: Some("codex"),
|
||||
claude_project_lookup: false,
|
||||
disabled_servers: no_disabled.clone(),
|
||||
});
|
||||
specs.push(SourceSpec {
|
||||
id: "gemini-project".into(),
|
||||
label: "Gemini Project (.gemini/settings.json)".into(),
|
||||
id: "gemini-project",
|
||||
label: "Gemini Project (.gemini/settings.json)",
|
||||
path: root.join(".gemini").join("settings.json"),
|
||||
format: SourceFormat::Jsonc,
|
||||
suggested_scope: McpScope::Workspace,
|
||||
native_provider: Some("gemini"),
|
||||
claude_project_lookup: false,
|
||||
disabled_servers: no_disabled.clone(),
|
||||
});
|
||||
}
|
||||
if let Some(home) = home_dir {
|
||||
let copilot_dir = home.join(".copilot");
|
||||
let copilot_settings = read_copilot_settings(&copilot_dir);
|
||||
specs.push(SourceSpec {
|
||||
id: "copilot-cli".into(),
|
||||
label: "GitHub Copilot CLI".into(),
|
||||
path: copilot_dir.join("mcp-config.json"),
|
||||
id: "copilot-cli",
|
||||
label: "GitHub Copilot CLI",
|
||||
path: home.join(".copilot").join("mcp-config.json"),
|
||||
format: SourceFormat::Jsonc,
|
||||
suggested_scope: McpScope::User,
|
||||
native_provider: Some("copilot"),
|
||||
claude_project_lookup: false,
|
||||
disabled_servers: copilot_settings.disabled_mcp_servers.clone(),
|
||||
});
|
||||
specs.extend(copilot_plugin_source_specs(&copilot_dir, &copilot_settings));
|
||||
specs.push(SourceSpec {
|
||||
id: "claude-code".into(),
|
||||
label: "Claude Code".into(),
|
||||
id: "claude-code",
|
||||
label: "Claude Code",
|
||||
path: home.join(".claude.json"),
|
||||
format: SourceFormat::Jsonc,
|
||||
suggested_scope: McpScope::User,
|
||||
native_provider: Some("claude"),
|
||||
claude_project_lookup: true,
|
||||
disabled_servers: no_disabled.clone(),
|
||||
});
|
||||
specs.push(SourceSpec {
|
||||
id: "codex".into(),
|
||||
label: "Codex".into(),
|
||||
id: "codex",
|
||||
label: "Codex",
|
||||
path: home.join(".codex").join("config.toml"),
|
||||
format: SourceFormat::CodexToml,
|
||||
suggested_scope: McpScope::User,
|
||||
native_provider: Some("codex"),
|
||||
claude_project_lookup: false,
|
||||
disabled_servers: no_disabled.clone(),
|
||||
});
|
||||
specs.push(SourceSpec {
|
||||
id: "cursor".into(),
|
||||
label: "Cursor".into(),
|
||||
id: "cursor",
|
||||
label: "Cursor",
|
||||
path: home.join(".cursor").join("mcp.json"),
|
||||
format: SourceFormat::Jsonc,
|
||||
suggested_scope: McpScope::User,
|
||||
native_provider: Some("cursor"),
|
||||
claude_project_lookup: false,
|
||||
disabled_servers: no_disabled.clone(),
|
||||
});
|
||||
specs.push(SourceSpec {
|
||||
id: "gemini".into(),
|
||||
label: "Gemini CLI".into(),
|
||||
id: "gemini",
|
||||
label: "Gemini CLI",
|
||||
path: home.join(".gemini").join("settings.json"),
|
||||
format: SourceFormat::Jsonc,
|
||||
suggested_scope: McpScope::User,
|
||||
native_provider: Some("gemini"),
|
||||
claude_project_lookup: false,
|
||||
disabled_servers: no_disabled.clone(),
|
||||
});
|
||||
specs.push(SourceSpec {
|
||||
id: "jetbrains-air".into(),
|
||||
label: "JetBrains Air".into(),
|
||||
id: "jetbrains-air",
|
||||
label: "JetBrains Air",
|
||||
path: home.join(".jetbrains").join("mcp").join("mcp.json"),
|
||||
format: SourceFormat::Jsonc,
|
||||
suggested_scope: McpScope::User,
|
||||
native_provider: None,
|
||||
claude_project_lookup: false,
|
||||
disabled_servers: no_disabled.clone(),
|
||||
});
|
||||
specs.push(SourceSpec {
|
||||
id: "copilot-intellij".into(),
|
||||
label: "GitHub Copilot (JetBrains)".into(),
|
||||
id: "copilot-intellij",
|
||||
label: "GitHub Copilot (JetBrains)",
|
||||
path: home.join(".config").join("github-copilot").join("intellij").join("mcp.json"),
|
||||
format: SourceFormat::Jsonc,
|
||||
suggested_scope: McpScope::User,
|
||||
native_provider: None,
|
||||
claude_project_lookup: false,
|
||||
disabled_servers: no_disabled,
|
||||
});
|
||||
}
|
||||
specs
|
||||
}
|
||||
|
||||
fn read_copilot_settings(copilot_dir: &Path) -> CopilotSettings {
|
||||
let Ok(text) = std::fs::read_to_string(copilot_dir.join("settings.json")) else {
|
||||
return CopilotSettings::default();
|
||||
};
|
||||
let Ok(root) = parse_jsonc_value(&text) else {
|
||||
return CopilotSettings::default();
|
||||
};
|
||||
let disabled_mcp_servers = root
|
||||
.get("disabledMcpServers")
|
||||
.and_then(Value::as_array)
|
||||
.map(|arr| {
|
||||
arr.iter()
|
||||
.filter_map(|v| v.as_str().map(str::trim).filter(|s| !s.is_empty()).map(str::to_owned))
|
||||
.collect::<BTreeSet<_>>()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let disabled_plugins = root
|
||||
.get("enabledPlugins")
|
||||
.and_then(Value::as_object)
|
||||
.map(|obj| {
|
||||
obj.iter()
|
||||
.filter(|(_, v)| v.as_bool() == Some(false))
|
||||
.map(|(k, _)| k.trim().to_owned())
|
||||
.filter(|k| !k.is_empty())
|
||||
.collect::<BTreeSet<_>>()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
CopilotSettings { disabled_mcp_servers: std::sync::Arc::new(disabled_mcp_servers), disabled_plugins }
|
||||
}
|
||||
|
||||
fn copilot_plugin_source_specs(copilot_dir: &Path, settings: &CopilotSettings) -> Vec<SourceSpec> {
|
||||
let Ok(text) = std::fs::read_to_string(copilot_dir.join("config.json")) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let Ok(root) = parse_jsonc_value(&text) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let Some(installed) = root.get("installedPlugins").and_then(Value::as_array) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let mut seen_ids = HashSet::new();
|
||||
let mut specs = Vec::new();
|
||||
for entry in installed {
|
||||
let Some(obj) = entry.as_object() else { continue };
|
||||
if obj.get("enabled").and_then(Value::as_bool) == Some(false) {
|
||||
continue;
|
||||
}
|
||||
let Some(name) = obj.get("name").and_then(Value::as_str).map(str::trim).filter(|s| !s.is_empty()) else {
|
||||
continue;
|
||||
};
|
||||
let marketplace = obj.get("marketplace").and_then(Value::as_str).map(str::trim).unwrap_or_default();
|
||||
if settings.disabled_plugins.contains(name)
|
||||
|| (!marketplace.is_empty()
|
||||
&& (settings.disabled_plugins.contains(&format!("{name}@{marketplace}"))
|
||||
|| settings.disabled_plugins.contains(&format!("{marketplace}/{name}"))))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let Some(raw_cache) = obj.get("cache_path").and_then(Value::as_str).map(str::trim).filter(|s| !s.is_empty())
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let plugin_root =
|
||||
if Path::new(raw_cache).is_relative() { copilot_dir.join(raw_cache) } else { PathBuf::from(raw_cache) };
|
||||
if !plugin_root.is_dir() {
|
||||
continue;
|
||||
}
|
||||
let Some((manifest_path, _)) = read_copilot_plugin_servers(&plugin_root) else {
|
||||
continue;
|
||||
};
|
||||
let base_id = if marketplace.is_empty() {
|
||||
format!("copilot-plugin:{name}")
|
||||
} else {
|
||||
format!("copilot-plugin:{marketplace}/{name}")
|
||||
};
|
||||
let mut id = base_id.clone();
|
||||
let mut suffix = 2usize;
|
||||
while !seen_ids.insert(id.clone()) {
|
||||
id = format!("{base_id}#{suffix}");
|
||||
suffix += 1;
|
||||
}
|
||||
let label = if marketplace.is_empty() {
|
||||
format!("GitHub Copilot Plugin ({name})")
|
||||
} else {
|
||||
format!("GitHub Copilot Plugin ({name} · {marketplace})")
|
||||
};
|
||||
specs.push(SourceSpec {
|
||||
id,
|
||||
label,
|
||||
path: manifest_path,
|
||||
format: SourceFormat::CopilotPlugin { root: plugin_root },
|
||||
suggested_scope: McpScope::User,
|
||||
native_provider: Some("copilot"),
|
||||
claude_project_lookup: false,
|
||||
disabled_servers: settings.disabled_mcp_servers.clone(),
|
||||
});
|
||||
}
|
||||
specs
|
||||
}
|
||||
|
||||
fn resolve_within_dir(base_dir: &Path, candidate: &Path) -> Option<PathBuf> {
|
||||
if candidate.as_os_str().is_empty() {
|
||||
return None;
|
||||
}
|
||||
let base_canon = dunce::canonicalize(base_dir).ok()?;
|
||||
let clean = candidate.strip_prefix(".").unwrap_or(candidate);
|
||||
let joined = if clean.is_relative() { base_dir.join(clean) } else { clean.to_path_buf() };
|
||||
let meta = std::fs::metadata(&joined).ok()?;
|
||||
if !meta.is_file() {
|
||||
return None;
|
||||
}
|
||||
let target_canon = dunce::canonicalize(&joined).ok()?;
|
||||
target_canon.starts_with(&base_canon).then_some(joined)
|
||||
}
|
||||
|
||||
fn expand_plugin_root_vars(value: &str, root: &str) -> String {
|
||||
value.replace("${COPILOT_PLUGIN_ROOT}", root).replace("${CLAUDE_PLUGIN_ROOT}", root).replace("${PLUGIN_ROOT}", root)
|
||||
}
|
||||
|
||||
fn expand_plugin_servers(servers: &mut BTreeMap<String, AgentMcpServer>, plugin_root: &Path) {
|
||||
let root = plugin_root.to_string_lossy();
|
||||
for srv in servers.values_mut() {
|
||||
if let Some(cmd) = srv.command.as_mut() {
|
||||
*cmd = expand_plugin_root_vars(cmd, &root);
|
||||
}
|
||||
for arg in &mut srv.args {
|
||||
*arg = expand_plugin_root_vars(arg, &root);
|
||||
}
|
||||
if let Some(url) = srv.url.as_mut() {
|
||||
*url = expand_plugin_root_vars(url, &root);
|
||||
}
|
||||
for val in srv.env.values_mut() {
|
||||
*val = expand_plugin_root_vars(val, &root);
|
||||
}
|
||||
for val in srv.headers.values_mut() {
|
||||
*val = expand_plugin_root_vars(val, &root);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn extract_plugin_manifest_servers(
|
||||
plugin_root: &Path,
|
||||
manifest_path: &Path,
|
||||
mcp_val: &Value,
|
||||
) -> (PathBuf, BTreeMap<String, AgentMcpServer>) {
|
||||
match mcp_val {
|
||||
Value::String(rel) => {
|
||||
if let Some(path) = resolve_within_dir(plugin_root, Path::new(rel.trim())) {
|
||||
let map = read_external_file(&path);
|
||||
return (path, map);
|
||||
}
|
||||
(manifest_path.to_path_buf(), BTreeMap::new())
|
||||
}
|
||||
Value::Object(_) => {
|
||||
let wrapper = json!({ "mcpServers": mcp_val });
|
||||
(manifest_path.to_path_buf(), extract_servers_from_root(&wrapper, None))
|
||||
}
|
||||
Value::Array(items) => {
|
||||
let mut merged = BTreeMap::new();
|
||||
let mut first_path: Option<PathBuf> = None;
|
||||
for item in items {
|
||||
match item {
|
||||
Value::String(rel) => {
|
||||
if let Some(path) = resolve_within_dir(plugin_root, Path::new(rel.trim())) {
|
||||
let map = read_external_file(&path);
|
||||
if !map.is_empty() && first_path.is_none() {
|
||||
first_path = Some(path);
|
||||
}
|
||||
merged.extend(map);
|
||||
}
|
||||
}
|
||||
Value::Object(_) => {
|
||||
let map = extract_servers_from_root(item, None);
|
||||
if !map.is_empty() && first_path.is_none() {
|
||||
first_path = Some(manifest_path.to_path_buf());
|
||||
}
|
||||
merged.extend(map);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
(first_path.unwrap_or_else(|| manifest_path.to_path_buf()), merged)
|
||||
}
|
||||
_ => (manifest_path.to_path_buf(), BTreeMap::new()),
|
||||
}
|
||||
}
|
||||
|
||||
fn read_copilot_plugin_servers(plugin_root: &Path) -> Option<(PathBuf, BTreeMap<String, AgentMcpServer>)> {
|
||||
if let Some(dot_mcp) = resolve_within_dir(plugin_root, Path::new(".mcp.json")) {
|
||||
let mut servers = read_external_file(&dot_mcp);
|
||||
if !servers.is_empty() {
|
||||
expand_plugin_servers(&mut servers, plugin_root);
|
||||
return Some((dot_mcp, servers));
|
||||
}
|
||||
}
|
||||
for rel in COPILOT_PLUGIN_MANIFESTS {
|
||||
let Some(manifest_path) = resolve_within_dir(plugin_root, Path::new(rel)) else {
|
||||
continue;
|
||||
};
|
||||
let Ok(text) = std::fs::read_to_string(&manifest_path) else {
|
||||
continue;
|
||||
};
|
||||
let Ok(manifest) = parse_jsonc_value(&text) else {
|
||||
continue;
|
||||
};
|
||||
let Some(mcp_val) = manifest.get("mcpServers") else {
|
||||
continue;
|
||||
};
|
||||
let (source_path, mut servers) = extract_plugin_manifest_servers(plugin_root, &manifest_path, mcp_val);
|
||||
if !servers.is_empty() {
|
||||
expand_plugin_servers(&mut servers, plugin_root);
|
||||
return Some((source_path, servers));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn read_source_servers(spec: &SourceSpec, workspace_root: Option<&Path>) -> BTreeMap<String, AgentMcpServer> {
|
||||
let mut servers = match &spec.format {
|
||||
SourceFormat::CopilotPlugin { root } => {
|
||||
read_copilot_plugin_servers(root).map(|(_, map)| map).unwrap_or_default()
|
||||
}
|
||||
SourceFormat::CodexToml => {
|
||||
let Ok(text) = std::fs::read_to_string(&spec.path) else {
|
||||
return BTreeMap::new();
|
||||
};
|
||||
parse_codex_toml_servers(&text)
|
||||
}
|
||||
SourceFormat::Jsonc => {
|
||||
let Ok(text) = std::fs::read_to_string(&spec.path) else {
|
||||
return BTreeMap::new();
|
||||
};
|
||||
let Ok(root) = parse_jsonc_value(&text) else {
|
||||
return BTreeMap::new();
|
||||
};
|
||||
let mut map = extract_servers_from_root(&root, None);
|
||||
if spec.claude_project_lookup
|
||||
&& let Some(ws) = workspace_root
|
||||
&& let Some(projects) = root.get("projects").and_then(Value::as_object)
|
||||
{
|
||||
let ws_canon = dunce::canonicalize(ws).unwrap_or_else(|_| ws.to_path_buf());
|
||||
for (proj_key, proj_val) in projects {
|
||||
let matches =
|
||||
Path::new(proj_key) == ws || dunce::canonicalize(proj_key).is_ok_and(|c| c == ws_canon);
|
||||
if matches {
|
||||
for (name, srv) in extract_servers_from_root(proj_val, None) {
|
||||
map.insert(name, srv);
|
||||
}
|
||||
}
|
||||
let Ok(text) = std::fs::read_to_string(&spec.path) else {
|
||||
return BTreeMap::new();
|
||||
};
|
||||
if spec.format == SourceFormat::CodexToml {
|
||||
return parse_codex_toml_servers(&text);
|
||||
}
|
||||
let Ok(root) = parse_jsonc_value(&text) else {
|
||||
return BTreeMap::new();
|
||||
};
|
||||
let mut servers = extract_servers_from_root(&root, None);
|
||||
if spec.claude_project_lookup
|
||||
&& let Some(ws) = workspace_root
|
||||
&& let Some(projects) = root.get("projects").and_then(Value::as_object)
|
||||
{
|
||||
let ws_canon = dunce::canonicalize(ws).unwrap_or_else(|_| ws.to_path_buf());
|
||||
for (proj_key, proj_val) in projects {
|
||||
let matches = Path::new(proj_key) == ws || dunce::canonicalize(proj_key).is_ok_and(|c| c == ws_canon);
|
||||
if matches {
|
||||
for (name, srv) in extract_servers_from_root(proj_val, None) {
|
||||
servers.insert(name, srv);
|
||||
}
|
||||
}
|
||||
map
|
||||
}
|
||||
};
|
||||
for name in spec.disabled_servers.iter() {
|
||||
if let Some(srv) = servers.get_mut(name) {
|
||||
srv.enabled = false;
|
||||
}
|
||||
}
|
||||
servers
|
||||
@@ -878,8 +552,8 @@ pub fn discover_external_sources(home_dir: Option<&Path>, workspace_root: Option
|
||||
})
|
||||
.collect();
|
||||
out.push(McpExternalSource {
|
||||
id: spec.id,
|
||||
label: spec.label,
|
||||
id: spec.id.to_owned(),
|
||||
label: spec.label.to_owned(),
|
||||
path: IpcPath(spec.path),
|
||||
suggested_scope: spec.suggested_scope,
|
||||
native_provider: spec.native_provider.map(str::to_owned),
|
||||
@@ -907,7 +581,7 @@ pub fn apply_import_selected(
|
||||
let mut by_source: BTreeMap<&str, BTreeMap<String, AgentMcpServer>> = BTreeMap::new();
|
||||
for spec in &specs {
|
||||
if selections.iter().any(|s| s.source_id == spec.id) {
|
||||
by_source.insert(spec.id.as_str(), read_source_servers(spec, workspace_root));
|
||||
by_source.insert(spec.id, read_source_servers(spec, workspace_root));
|
||||
}
|
||||
}
|
||||
let target = match scope {
|
||||
@@ -941,10 +615,107 @@ fn normalize_agents_list(agents: Vec<String>) -> Vec<String> {
|
||||
out
|
||||
}
|
||||
|
||||
/// Strips `//` line comments, `/* ... */` block comments, and trailing commas before `}` or `]`
|
||||
/// outside JSON string literals so JSONC config files parse cleanly with `serde_json`.
|
||||
pub(crate) fn strip_jsonc(input: &str) -> String {
|
||||
let bytes = input.as_bytes();
|
||||
let mut out = String::with_capacity(input.len());
|
||||
let mut i = 0;
|
||||
let mut in_str = false;
|
||||
while i < bytes.len() {
|
||||
if in_str {
|
||||
let ch = input[i..].chars().next().unwrap();
|
||||
out.push(ch);
|
||||
i += ch.len_utf8();
|
||||
if ch == '\\' && i < bytes.len() {
|
||||
let next = input[i..].chars().next().unwrap();
|
||||
out.push(next);
|
||||
i += next.len_utf8();
|
||||
} else if ch == '"' {
|
||||
in_str = false;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if bytes[i] == b'"' {
|
||||
in_str = true;
|
||||
out.push('"');
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if bytes[i] == b'/' && i + 1 < bytes.len() && bytes[i + 1] == b'/' {
|
||||
i += 2;
|
||||
while i < bytes.len() && bytes[i] != b'\n' {
|
||||
i += 1;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if bytes[i] == b'/' && i + 1 < bytes.len() && bytes[i + 1] == b'*' {
|
||||
i += 2;
|
||||
while i + 1 < bytes.len() && !(bytes[i] == b'*' && bytes[i + 1] == b'/') {
|
||||
if bytes[i] == b'\n' {
|
||||
out.push('\n');
|
||||
i += 1;
|
||||
} else {
|
||||
let ch = input[i..].chars().next().unwrap();
|
||||
i += ch.len_utf8();
|
||||
}
|
||||
}
|
||||
i = (i + 2).min(bytes.len());
|
||||
continue;
|
||||
}
|
||||
let ch = input[i..].chars().next().unwrap();
|
||||
out.push(ch);
|
||||
i += ch.len_utf8();
|
||||
}
|
||||
remove_trailing_commas(&out)
|
||||
}
|
||||
|
||||
fn remove_trailing_commas(input: &str) -> String {
|
||||
let bytes = input.as_bytes();
|
||||
let mut out = String::with_capacity(input.len());
|
||||
let mut i = 0;
|
||||
let mut in_str = false;
|
||||
while i < bytes.len() {
|
||||
if in_str {
|
||||
let ch = input[i..].chars().next().unwrap();
|
||||
out.push(ch);
|
||||
i += ch.len_utf8();
|
||||
if ch == '\\' && i < bytes.len() {
|
||||
let next = input[i..].chars().next().unwrap();
|
||||
out.push(next);
|
||||
i += next.len_utf8();
|
||||
} else if ch == '"' {
|
||||
in_str = false;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if bytes[i] == b'"' {
|
||||
in_str = true;
|
||||
out.push('"');
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if bytes[i] == b',' {
|
||||
let mut j = i + 1;
|
||||
while j < bytes.len() && bytes[j].is_ascii_whitespace() {
|
||||
j += 1;
|
||||
}
|
||||
if j < bytes.len() && (bytes[j] == b'}' || bytes[j] == b']') {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
let ch = input[i..].chars().next().unwrap();
|
||||
out.push(ch);
|
||||
i += ch.len_utf8();
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn parse_jsonc_value(raw: &str) -> Result<Value, String> {
|
||||
let trimmed = raw.trim().trim_start_matches('\u{feff}');
|
||||
serde_json::from_str::<Value>(trimmed)
|
||||
.or_else(|_| serde_json::from_str::<Value>(&ide_core::jsonc::strip(trimmed)))
|
||||
.or_else(|_| serde_json::from_str::<Value>(&strip_jsonc(trimmed)))
|
||||
.map_err(|e| format!("Invalid JSON: {e}"))
|
||||
}
|
||||
|
||||
@@ -1245,54 +1016,6 @@ fn parse_key_values_map(val: Option<&Value>) -> BTreeMap<String, String> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn configured(name: &str, scope: McpScope, enabled: bool) -> McpServer {
|
||||
McpServer {
|
||||
id: format!("{scope:?}:{name}"),
|
||||
name: name.into(),
|
||||
scope,
|
||||
transport: McpTransport::Stdio,
|
||||
enabled,
|
||||
command: Some("x".into()),
|
||||
args: Vec::new(),
|
||||
env: Vec::new(),
|
||||
url: None,
|
||||
headers: Vec::new(),
|
||||
agents: Vec::new(),
|
||||
unapproved: false,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn servers_off_follow_the_effective_state() {
|
||||
let mut claude_only = configured("claude-only", McpScope::User, true);
|
||||
claude_only.agents = vec!["claude".into()];
|
||||
let mut unapproved_ws = configured("unapproved-ws", McpScope::Workspace, false);
|
||||
unapproved_ws.unapproved = true;
|
||||
|
||||
let all = [
|
||||
configured("default-off", McpScope::User, false),
|
||||
configured("switched-on", McpScope::User, false),
|
||||
configured("on", McpScope::User, true),
|
||||
configured("switched-off", McpScope::User, true),
|
||||
// The workspace entry decides for its name.
|
||||
configured("both", McpScope::User, true),
|
||||
configured("both", McpScope::Workspace, false),
|
||||
claude_only,
|
||||
unapproved_ws,
|
||||
];
|
||||
let overrides = BTreeMap::from([
|
||||
("switched-on".to_owned(), true),
|
||||
("switched-off".to_owned(), false),
|
||||
("agent-own".to_owned(), false),
|
||||
(BUILTIN_MCP_NAME.to_owned(), false),
|
||||
]);
|
||||
assert_eq!(
|
||||
servers_off(&all, "copilot", &overrides),
|
||||
["agent-own", "both", "claude-only", "default-off", "switched-off", "unapproved-ws"]
|
||||
);
|
||||
assert_eq!(servers_off(&all[2..4], "copilot", &BTreeMap::new()), Vec::<String>::new());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn crud_and_acp_filtering_by_scope_agent_and_transport() {
|
||||
let mut user = BTreeMap::new();
|
||||
@@ -1539,125 +1262,4 @@ mod tests {
|
||||
assert_eq!(workspace["events-sse"].transport, McpTransport::Sse);
|
||||
assert_eq!(workspace["events-sse"].url.as_deref(), Some("https://sse.example.com/events"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn discovers_and_imports_copilot_installed_plugin_mcp_servers() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let home = tmp.path().join("home");
|
||||
let copilot = home.join(".copilot");
|
||||
let azure_root = copilot.join("installed-plugins/_direct/azure-skills");
|
||||
let inline_root = copilot.join("installed-plugins/awesome-copilot/inline-tools");
|
||||
let disabled_root = copilot.join("installed-plugins/_direct/disabled-plug");
|
||||
let outside_root = tmp.path().join("outside");
|
||||
|
||||
std::fs::create_dir_all(azure_root.join(".plugin")).unwrap();
|
||||
std::fs::create_dir_all(inline_root.join(".claude-plugin")).unwrap();
|
||||
std::fs::create_dir_all(&disabled_root).unwrap();
|
||||
std::fs::create_dir_all(&outside_root).unwrap();
|
||||
|
||||
std::fs::write(
|
||||
azure_root.join(".plugin/plugin.json"),
|
||||
r#"{"name":"azure","version":"1.2.106","mcpServers":"./.mcp.json"}"#,
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::write(
|
||||
azure_root.join(".mcp.json"),
|
||||
r#"{"mcpServers":{"azure":{"command":"npx","args":["-y","@azure/mcp@latest","${COPILOT_PLUGIN_ROOT}/cfg"],"env":{"PLUG_DIR":"${CLAUDE_PLUGIN_ROOT}"}}}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
std::fs::write(
|
||||
inline_root.join(".claude-plugin/plugin.json"),
|
||||
r#"{"name":"inline-tools","version":"0.1.0","mcpServers":{"inline-srv":{"command":"${PLUGIN_ROOT}/bin/run","args":["--stdio"]},"muted-srv":{"command":"echo","args":["off"]}}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
std::fs::write(
|
||||
disabled_root.join(".mcp.json"),
|
||||
r#"{"mcpServers":{"never":{"command":"npx","args":["never"]}}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
std::fs::write(outside_root.join("secret.json"), r#"{"mcpServers":{"escaped":{"command":"sh"}}}"#).unwrap();
|
||||
let escape_root = copilot.join("installed-plugins/_direct/escape-plug");
|
||||
std::fs::create_dir_all(escape_root.join(".plugin")).unwrap();
|
||||
std::fs::write(
|
||||
escape_root.join(".plugin/plugin.json"),
|
||||
r#"{"name":"escape-plug","mcpServers":"../../../../outside/secret.json"}"#,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
// `~/.copilot/config.json` includes leading `//` comments in Copilot CLI.
|
||||
let config_json = format!(
|
||||
"// Managed automatically.\n{}",
|
||||
serde_json::json!({
|
||||
"installedPlugins": [
|
||||
{
|
||||
"name": "azure",
|
||||
"marketplace": "",
|
||||
"enabled": true,
|
||||
"cache_path": azure_root,
|
||||
},
|
||||
{
|
||||
"name": "inline-tools",
|
||||
"marketplace": "awesome-copilot",
|
||||
"enabled": true,
|
||||
"cache_path": inline_root,
|
||||
},
|
||||
{
|
||||
"name": "disabled-plug",
|
||||
"marketplace": "",
|
||||
"enabled": false,
|
||||
"cache_path": disabled_root,
|
||||
},
|
||||
{
|
||||
"name": "escape-plug",
|
||||
"marketplace": "",
|
||||
"enabled": true,
|
||||
"cache_path": escape_root,
|
||||
}
|
||||
]
|
||||
})
|
||||
);
|
||||
std::fs::write(copilot.join("config.json"), config_json).unwrap();
|
||||
std::fs::write(copilot.join("settings.json"), r#"{"disabledMcpServers":["muted-srv"]}"#).unwrap();
|
||||
|
||||
let sources = discover_external_sources(Some(&home), None);
|
||||
assert_eq!(sources.len(), 2);
|
||||
|
||||
let azure_src = sources.iter().find(|s| s.id == "copilot-plugin:azure").unwrap();
|
||||
assert_eq!(azure_src.label, "GitHub Copilot Plugin (azure)");
|
||||
assert_eq!(azure_src.native_provider.as_deref(), Some("copilot"));
|
||||
assert_eq!(azure_src.path.0, azure_root.join(".mcp.json"));
|
||||
assert_eq!(azure_src.servers.len(), 1);
|
||||
assert!(azure_src.servers[0].enabled);
|
||||
assert_eq!(
|
||||
azure_src.servers[0].args,
|
||||
vec!["-y", "@azure/mcp@latest", &format!("{}/cfg", azure_root.display())]
|
||||
);
|
||||
|
||||
let inline_src = sources.iter().find(|s| s.id == "copilot-plugin:awesome-copilot/inline-tools").unwrap();
|
||||
assert_eq!(inline_src.label, "GitHub Copilot Plugin (inline-tools · awesome-copilot)");
|
||||
assert_eq!(inline_src.path.0, inline_root.join(".claude-plugin/plugin.json"));
|
||||
let active = inline_src.servers.iter().find(|s| s.name == "inline-srv").unwrap();
|
||||
assert!(active.enabled);
|
||||
assert_eq!(active.command.as_deref(), Some(format!("{}/bin/run", inline_root.display()).as_str()));
|
||||
let muted = inline_src.servers.iter().find(|s| s.name == "muted-srv").unwrap();
|
||||
assert!(!muted.enabled);
|
||||
|
||||
let mut user = BTreeMap::new();
|
||||
let mut workspace = BTreeMap::new();
|
||||
let imported = apply_import_selected(
|
||||
&mut user,
|
||||
&mut workspace,
|
||||
Some(&home),
|
||||
None,
|
||||
McpScope::User,
|
||||
&[McpImportSelection { source_id: "copilot-plugin:azure".into(), name: "azure".into() }],
|
||||
false,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(imported, vec!["azure".to_string()]);
|
||||
assert_eq!(user["azure"].env.get("PLUG_DIR").map(String::as_str), Some(azure_root.to_str().unwrap()));
|
||||
}
|
||||
}
|
||||
@@ -45,8 +45,9 @@ pub struct AgentCapabilities {
|
||||
pub steer: bool,
|
||||
/// It reports its background tasks and stops them one by one.
|
||||
pub background_tasks: bool,
|
||||
/// The connected agent can report a breakdown of its context window.
|
||||
pub context_usage: bool,
|
||||
/// The task runs read-only: it asks before anything, and requests that would change
|
||||
/// the project are denied (a temporary side conversation).
|
||||
pub read_only: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
@@ -110,32 +111,6 @@ pub struct AgentTask {
|
||||
/// Per-session MCP server enable/disable overrides (`server_name` -> `enabled`), including `"openidea"`.
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub mcp_overrides: BTreeMap<String, bool>,
|
||||
/// Per-session skill modes (`skill name` -> mode), on top of the settings' policies.
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub skill_overrides: BTreeMap<String, AgentSkillMode>,
|
||||
/// Token counts of the last turn and context compressions, when the agent reports them.
|
||||
// Boxed so that `AgentEvent::Task` stays within clippy's `large_enum_variant` bound on Windows.
|
||||
#[serde(default)]
|
||||
pub stats: Box<AgentSessionStats>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentSessionStats {
|
||||
/// The last turn's tokens (`session/prompt` result `usage`).
|
||||
#[serde(default)]
|
||||
pub tokens: Option<AgentTokens>,
|
||||
/// How many times the agent compressed the conversation (Hermes `compressionDepth`).
|
||||
#[serde(default)]
|
||||
pub compressions: u32,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentTokens {
|
||||
pub input: u32,
|
||||
pub cached: u32,
|
||||
pub output: u32,
|
||||
}
|
||||
|
||||
/// A task the agent runs in the background while the conversation goes on.
|
||||
@@ -280,24 +255,6 @@ pub struct AgentUsage {
|
||||
pub cost: Option<Box<AgentCost>>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentContextUsage {
|
||||
pub categories: Vec<AgentContextCategory>,
|
||||
pub total_tokens: u32,
|
||||
pub max_tokens: u32,
|
||||
pub model: String,
|
||||
pub is_auto_compact_enabled: Option<bool>,
|
||||
pub auto_compact_threshold: Option<u32>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
pub struct AgentContextCategory {
|
||||
pub name: String,
|
||||
pub tokens: u32,
|
||||
pub kind: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentCost {
|
||||
@@ -327,22 +284,6 @@ pub struct AgentImage {
|
||||
pub name: Option<String>,
|
||||
}
|
||||
|
||||
impl AgentImage {
|
||||
/// The type the bytes are in. Agents reject an image whose declared type doesn't match its
|
||||
/// bytes, and a pasted image's declared type can be wrong (a browser's JPEG or WebP copied as
|
||||
/// `image/png`). Falls back to `mime_type` for formats not recognised here.
|
||||
pub fn media_type(&self) -> &str {
|
||||
let head = crate::acp::normalize_base64(&self.data[..self.data.len().min(16)]);
|
||||
match head.as_slice() {
|
||||
[0x89, b'P', b'N', b'G', ..] => "image/png",
|
||||
[0xFF, 0xD8, 0xFF, ..] => "image/jpeg",
|
||||
[b'G', b'I', b'F', b'8', ..] => "image/gif",
|
||||
[b'R', b'I', b'F', b'F', _, _, _, _, b'W', b'E', b'B', b'P', ..] => "image/webp",
|
||||
_ => &self.mime_type,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A message to the agent: text, plus files to look at and images.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
@@ -515,19 +456,8 @@ pub enum AgentEntry {
|
||||
Agent {
|
||||
text: String,
|
||||
},
|
||||
/// A question that can be answered while the agent keeps working, or after the turn ends.
|
||||
Question {
|
||||
id: String,
|
||||
title: String,
|
||||
questions: Vec<AgentQuestion>,
|
||||
/// The submitted answers, or `Skipped`; `None` while unanswered.
|
||||
chosen: Option<String>,
|
||||
},
|
||||
Thought {
|
||||
text: String,
|
||||
/// When the reasoning started (ms since the epoch); `None` in tasks saved before.
|
||||
#[serde(default)]
|
||||
started_ms: Option<f64>,
|
||||
},
|
||||
Tool {
|
||||
id: String,
|
||||
@@ -536,17 +466,9 @@ pub enum AgentEntry {
|
||||
kind: String,
|
||||
status: AgentToolStatus,
|
||||
locations: Vec<IpcPath>,
|
||||
/// Images returned by the tool, kept separately from its truncated text.
|
||||
#[serde(default)]
|
||||
images: Vec<AgentImage>,
|
||||
/// Text the tool reported (command output…), truncated.
|
||||
output: Option<String>,
|
||||
diffs: Vec<AgentToolDiff>,
|
||||
/// When the call started and ended (ms since the epoch); `None` in tasks saved before.
|
||||
#[serde(default)]
|
||||
started_ms: Option<f64>,
|
||||
#[serde(default)]
|
||||
ended_ms: Option<f64>,
|
||||
},
|
||||
Plan {
|
||||
items: Vec<AgentPlanItem>,
|
||||
@@ -620,9 +542,6 @@ pub struct AgentProvider {
|
||||
pub command_read_only_reason: Option<AgentCommandReadOnlyReason>,
|
||||
/// Whether the command was found (on `PATH`).
|
||||
pub installed: bool,
|
||||
/// The built-in command can be owned by a global npm package.
|
||||
#[serde(default)]
|
||||
pub can_check_cli_update: bool,
|
||||
/// Environment variables it starts with (from its agent file).
|
||||
pub env: BTreeMap<String, String>,
|
||||
/// Settings (models, modes…) the agent offered last time it ran; empty before its first session.
|
||||
@@ -693,13 +612,6 @@ pub struct NewAgentTask {
|
||||
/// Per-session MCP server enable/disable overrides (`server_name` -> `enabled`).
|
||||
#[serde(default)]
|
||||
pub mcp_overrides: BTreeMap<String, bool>,
|
||||
/// Per-session skill modes (`skill name` -> mode).
|
||||
#[serde(default)]
|
||||
pub skill_overrides: BTreeMap<String, AgentSkillMode>,
|
||||
/// Creates the task without sending `prompt` (it only names the task): the composer's
|
||||
/// `!` command runs in it first.
|
||||
#[serde(default)]
|
||||
pub idle: bool,
|
||||
}
|
||||
|
||||
/// A file the task changed: against [`AgentTask::base_commit`], or against `HEAD` in the
|
||||
@@ -714,8 +626,6 @@ pub struct AgentChange {
|
||||
pub removed: u32,
|
||||
/// Path before a rename; the left side of its diff reads this path.
|
||||
pub old_path: Option<String>,
|
||||
/// The repository the file is in, when the task's project holds nested repositories.
|
||||
pub repo: Option<IpcPath>,
|
||||
}
|
||||
|
||||
/// A commit made while the task ran, with the files it changed against its first parent.
|
||||
@@ -741,8 +651,6 @@ pub enum AgentChangesView {
|
||||
SinceStart,
|
||||
/// The uncommitted files against `HEAD`; commits made since the start stay.
|
||||
Group,
|
||||
/// What the last turn changed, against the checkout as that turn started.
|
||||
LastTurn,
|
||||
}
|
||||
|
||||
/// A task's uncommitted files and the commits made since it started.
|
||||
@@ -769,7 +677,7 @@ pub struct AgentModelCatalog {
|
||||
pub error: Option<String>,
|
||||
}
|
||||
|
||||
/// Streamed to the window that subscribed (`AgentManager::subscribe_as`).
|
||||
/// Streamed to the window that subscribed (`AgentManager::subscribe`).
|
||||
#[derive(Clone, Debug, Serialize, Type)]
|
||||
#[serde(tag = "type", rename_all = "camelCase", rename_all_fields = "camelCase")]
|
||||
pub enum AgentEvent {
|
||||
@@ -801,16 +709,6 @@ pub enum AgentEvent {
|
||||
from: u32,
|
||||
text: String,
|
||||
},
|
||||
/// Text was appended to the output of tool entry `index`: it read the first `from` UTF-16
|
||||
/// units of its output when the previous event for it was sent. Any other change of the
|
||||
/// tool (status, title, diffs…) arrives as an `Entry`.
|
||||
ToolOutput {
|
||||
task: String,
|
||||
subagent: Option<String>,
|
||||
index: u32,
|
||||
from: u32,
|
||||
text: String,
|
||||
},
|
||||
/// An agent reported the usage limits of its account (shared by every task of `provider`).
|
||||
Limits {
|
||||
provider: String,
|
||||
@@ -900,104 +798,6 @@ fn default_true() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
pub use ide_core::settings::{AgentSkillMode, AgentSkillPolicy};
|
||||
|
||||
/// Which CLI's own folders a skill was discovered in (Settings › Agents › Skills groups by it).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum AgentSkillSource {
|
||||
/// The project's `.agents/skills` and `.openidea/skills`.
|
||||
#[default]
|
||||
Workspace,
|
||||
/// The user's `~/.agents/skills` (what `npx skills add` fills).
|
||||
User,
|
||||
/// Contributed by an enabled OpenIDEA plugin (`[[contributes.skills]]`).
|
||||
Plugin,
|
||||
/// The project's `.claude/skills`.
|
||||
ClaudeWorkspace,
|
||||
/// `~/.claude/skills`.
|
||||
ClaudeUser,
|
||||
/// The project's `.github/skills` (Copilot's repository skills).
|
||||
GithubWorkspace,
|
||||
/// `~/.copilot/skills` and `~/.copilot/installed-plugins/*`.
|
||||
CopilotUser,
|
||||
/// The project's `.codex/skills`.
|
||||
CodexWorkspace,
|
||||
/// `~/.codex/skills`.
|
||||
CodexUser,
|
||||
/// The project's `.cursor/skills`.
|
||||
CursorWorkspace,
|
||||
/// `~/.cursor/skills`.
|
||||
CursorUser,
|
||||
}
|
||||
|
||||
impl AgentSkillSource {
|
||||
/// Whether skills of this source are only read, never delivered by OpenIDEA: the CLI
|
||||
/// discovers them itself, so "off" holds only where the CLI supports a native disable.
|
||||
pub fn discovered(&self) -> bool {
|
||||
!matches!(self, Self::Workspace | Self::User | Self::Plugin)
|
||||
}
|
||||
}
|
||||
|
||||
/// One discovered skill: a folder with a `SKILL.md`.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentSkill {
|
||||
/// The frontmatter `name`, else the folder's name.
|
||||
pub name: String,
|
||||
pub description: String,
|
||||
/// Optional `argument-hint` from frontmatter, completed in the `/` menu.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub hint: Option<String>,
|
||||
/// Canonical folder holding `SKILL.md` (symlinks resolved, so duplicates collapse).
|
||||
pub path: IpcPath,
|
||||
pub source: AgentSkillSource,
|
||||
/// Other skill roots whose symlinked entry resolved to this same canonical `path`.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub also_in: Vec<AgentSkillSource>,
|
||||
/// False when frontmatter sets `user-invocable: false` (omitted from `/` completion).
|
||||
#[serde(default = "default_true")]
|
||||
pub user_invocable: bool,
|
||||
/// True when frontmatter sets `disable-model-invocation: true` (defaults to `slashOnly`).
|
||||
#[serde(default)]
|
||||
pub disable_model_invocation: bool,
|
||||
/// True when frontmatter sets `context: fork` (passed through natively to supporting CLIs).
|
||||
#[serde(default)]
|
||||
pub context_fork: bool,
|
||||
/// Optional `paths` / `globs` patterns from frontmatter (passed through natively to supporting CLIs).
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub paths: Vec<String>,
|
||||
/// The `SKILL.md` passes validation (`name` matches its folder, `description` present).
|
||||
pub valid: bool,
|
||||
/// What validation found (`name` mismatch, missing or over-long description…).
|
||||
pub warnings: Vec<String>,
|
||||
}
|
||||
|
||||
/// A skill as Settings › Agents › Skills shows it: discovery plus the effective mode and
|
||||
/// which layer decided it.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentSkillState {
|
||||
pub skill: AgentSkill,
|
||||
pub mode: AgentSkillMode,
|
||||
/// What set `mode`: a session override, the workspace, the user's settings, workspace
|
||||
/// trust, or nothing (the default `auto`).
|
||||
pub origin: AgentSkillOrigin,
|
||||
}
|
||||
|
||||
/// Which layer decided a skill's [`AgentSkillState::mode`].
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum AgentSkillOrigin {
|
||||
#[default]
|
||||
None,
|
||||
Session,
|
||||
Workspace,
|
||||
User,
|
||||
/// An untrusted workspace's skills and policies may only turn skills off.
|
||||
Trust,
|
||||
}
|
||||
|
||||
/// An external MCP configuration file discovered on disk (user CLI config or workspace file).
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
|
||||
@@ -170,14 +170,6 @@ struct Session {
|
||||
id: String,
|
||||
cwd: PathBuf,
|
||||
mcp_config: Option<tempfile::TempPath>,
|
||||
/// MCP servers switched off for this session (`--disallowedTools`), its own config's too.
|
||||
mcp_off: Vec<String>,
|
||||
/// The staged skills folder passed as `--add-dir` (its `.claude/skills` holds the copies).
|
||||
skills_add_dir: Option<PathBuf>,
|
||||
/// The workspace's other roots, each passed as `--add-dir`.
|
||||
additional_dirs: Vec<String>,
|
||||
/// The staged skills' `--settings` JSON (`skillOverrides` for the native ones too).
|
||||
skills_settings: Option<String>,
|
||||
shim: Weak<Shim>,
|
||||
st: Mutex<State>,
|
||||
/// Serializes (re)starting the process.
|
||||
@@ -352,24 +344,18 @@ impl Shim {
|
||||
cwd: PathBuf,
|
||||
start: Start,
|
||||
pending: bool,
|
||||
params: &Value,
|
||||
mcp_config: Option<String>,
|
||||
) -> Arc<Session> {
|
||||
let mcp_off = mcp_off(params);
|
||||
let mcp_config = mcp_config(params).and_then(|json| match write_mcp_config(&json) {
|
||||
let mcp_config = mcp_config.and_then(|json| match write_mcp_config(&json) {
|
||||
Ok(path) => Some(path),
|
||||
Err(e) => {
|
||||
tracing::warn!("Claude Code session {id}: cannot write its MCP configuration: {e}");
|
||||
None
|
||||
}
|
||||
});
|
||||
let skills = params.pointer("/_meta/openidea/skills");
|
||||
let session = Arc::new(Session {
|
||||
id: id.to_owned(),
|
||||
mcp_config,
|
||||
mcp_off,
|
||||
skills_add_dir: skills.and_then(|s| s.get("claudeAddDir")).and_then(Value::as_str).map(PathBuf::from),
|
||||
additional_dirs: additional_dirs(params),
|
||||
skills_settings: skills.and_then(|s| s.get("claudeSettings")).and_then(Value::as_str).map(str::to_owned),
|
||||
shim: Arc::downgrade(self),
|
||||
st: Mutex::new(State {
|
||||
proc: None,
|
||||
@@ -415,9 +401,9 @@ impl Shim {
|
||||
"agentCapabilities": {
|
||||
"loadSession": true,
|
||||
"promptCapabilities": { "image": true, "embeddedContext": true },
|
||||
"sessionCapabilities": { "fork": {}, "additionalDirectories": {} },
|
||||
"sessionCapabilities": { "fork": {} },
|
||||
"mcpCapabilities": { "stdio": true, "http": true, "sse": true },
|
||||
"_meta": { "openidea": { "rollback": true, "steer": true, "backgroundTasks": true, "contextUsage": true } },
|
||||
"_meta": { "openidea": { "rollback": true, "steer": true, "backgroundTasks": true } },
|
||||
},
|
||||
"agentInfo": { "name": "claude", "title": "Claude Code", "version": self.version() },
|
||||
"authMethods": [],
|
||||
@@ -425,8 +411,13 @@ impl Shim {
|
||||
}
|
||||
"session/new" => {
|
||||
let id = new_uuid(false);
|
||||
let session =
|
||||
self.add_session(&id, self.cwd_of(¶ms), Start::New { id: id.clone() }, false, ¶ms);
|
||||
let session = self.add_session(
|
||||
&id,
|
||||
self.cwd_of(¶ms),
|
||||
Start::New { id: id.clone() },
|
||||
false,
|
||||
mcp_config(¶ms),
|
||||
);
|
||||
rt.block_on(session.ensure()).map_err(|e| self.start_error(&session, e))?;
|
||||
session.announce_commands();
|
||||
Ok(json!({ "sessionId": id, "configOptions": session.st.lock().settings.options() }))
|
||||
@@ -442,7 +433,7 @@ impl Shim {
|
||||
None => return Err(invalid(format!("no Claude Code session {id} in {}", cwd.display()))),
|
||||
};
|
||||
let chain = self.base_chain(&cwd, &start).map_err(internal)?;
|
||||
let session = self.add_session(id, cwd, start, pending, ¶ms);
|
||||
let session = self.add_session(id, cwd, start, pending, mcp_config(¶ms));
|
||||
rt.block_on(session.ensure()).map_err(|e| self.start_error(&session, e))?;
|
||||
if method == "session/load" {
|
||||
session.replay(&chain);
|
||||
@@ -468,7 +459,7 @@ impl Shim {
|
||||
(start, st.settings.clone())
|
||||
};
|
||||
self.save_pending(&id, Some(&start));
|
||||
let session = self.add_session(&id, source.cwd.clone(), start, true, ¶ms);
|
||||
let session = self.add_session(&id, source.cwd.clone(), start, true, mcp_config(¶ms));
|
||||
session.st.lock().settings = settings;
|
||||
let options = session.st.lock().settings.options();
|
||||
Ok(json!({ "sessionId": id, "configOptions": options }))
|
||||
@@ -502,11 +493,6 @@ impl Shim {
|
||||
session.steer(params.get("prompt").cloned().unwrap_or_default()).map_err(invalid)?;
|
||||
Ok(json!({}))
|
||||
}
|
||||
"_openidea/context_usage" => {
|
||||
let session = self.session(¶ms)?;
|
||||
let proc = session.st.lock().proc.clone().ok_or_else(|| internal("Claude Code is not running"))?;
|
||||
rt.block_on(proc.control(json!({ "subtype": "get_context_usage" }))).map_err(internal)
|
||||
}
|
||||
"_openidea/stop_task" => {
|
||||
let session = self.session(¶ms)?;
|
||||
let task = params.get("taskId").and_then(Value::as_str).ok_or_else(|| invalid("no taskId"))?;
|
||||
@@ -680,20 +666,6 @@ impl Session {
|
||||
if let Some(config) = &self.mcp_config {
|
||||
args.extend(["--mcp-config".to_owned(), config.to_string_lossy().into_owned()]);
|
||||
}
|
||||
if !self.mcp_off.is_empty() {
|
||||
args.extend(["--disallowedTools".to_owned(), self.mcp_off.join(",")]);
|
||||
}
|
||||
// The staged skills: `.claude/skills` of the added directory is discovered like the
|
||||
// project's own, and the settings hold the modes of the skills it sees natively too.
|
||||
if let Some(dir) = &self.skills_add_dir {
|
||||
args.extend(["--add-dir".to_owned(), dir.to_string_lossy().into_owned()]);
|
||||
}
|
||||
for dir in &self.additional_dirs {
|
||||
args.extend(["--add-dir".to_owned(), dir.clone()]);
|
||||
}
|
||||
if let Some(settings) = &self.skills_settings {
|
||||
args.extend(["--settings".to_owned(), settings.clone()]);
|
||||
}
|
||||
args.extend(start.args());
|
||||
let launch =
|
||||
Launch { program: shim.config.program.clone(), args, cwd: self.cwd.clone(), env: shim.config.env.clone() };
|
||||
@@ -1007,16 +979,11 @@ impl Session {
|
||||
let mut updates = Vec::new();
|
||||
let mut finished = None;
|
||||
let mut read_title = false;
|
||||
let mut refresh_usage = false;
|
||||
{
|
||||
let mut st = self.st.lock();
|
||||
let st = &mut *st;
|
||||
match kind {
|
||||
"system" => match msg.get("subtype").and_then(Value::as_str) {
|
||||
Some("compact_boundary") => {
|
||||
refresh_usage = msg.pointer("/compact_metadata/post_tokens").is_none_or(Value::is_null);
|
||||
updates.extend(st.tr.on_message(&msg));
|
||||
}
|
||||
Some("init") => {
|
||||
st.terminal_only = strings(msg.get("terminal_slash_commands"));
|
||||
}
|
||||
@@ -1120,31 +1087,6 @@ impl Session {
|
||||
if read_title {
|
||||
self.read_title();
|
||||
}
|
||||
if refresh_usage {
|
||||
self.refresh_usage();
|
||||
}
|
||||
}
|
||||
|
||||
/// Sends what the context holds after a compaction that didn't report it, as Claude Code
|
||||
/// counts it (`get_context_usage`); until then the meter would show the count from before.
|
||||
fn refresh_usage(self: &Arc<Self>) {
|
||||
let me = self.clone();
|
||||
tokio::spawn(async move {
|
||||
let Some(proc) = me.st.lock().proc.clone() else { return };
|
||||
let usage = match proc.control(json!({ "subtype": "get_context_usage" })).await {
|
||||
Ok(usage) => usage,
|
||||
Err(e) => {
|
||||
tracing::debug!("reading claude context usage after compaction: {e}");
|
||||
return;
|
||||
}
|
||||
};
|
||||
let n = |k: &str| usage.get(k).and_then(Value::as_u64);
|
||||
let (Some(used), Some(size)) = (n("totalTokens"), n("maxTokens").filter(|m| *m > 0)) else { return };
|
||||
let update = me.st.lock().tr.on_context_usage(used, size);
|
||||
if let Some(shim) = me.shim() {
|
||||
shim.notify(vec![update]);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Sends the session's title once it has one: the one in its transcript, or else one
|
||||
@@ -1555,30 +1497,6 @@ fn write_mcp_config(json: &str) -> std::io::Result<tempfile::TempPath> {
|
||||
Ok(file.into_temp_path())
|
||||
}
|
||||
|
||||
/// The servers switched off for the session (`_meta.openidea.mcpServersOff`) as Claude Code
|
||||
/// permission rules that deny all of a server's tools (`mcp__<server>`), so a server of
|
||||
/// Claude Code's own configuration stays off too.
|
||||
/// The session's `additionalDirectories`: the workspace's other roots.
|
||||
fn additional_dirs(params: &Value) -> Vec<String> {
|
||||
let dirs = params.get("additionalDirectories").and_then(Value::as_array);
|
||||
dirs.into_iter().flatten().filter_map(Value::as_str).map(str::to_owned).collect()
|
||||
}
|
||||
|
||||
fn mcp_off(params: &Value) -> Vec<String> {
|
||||
params
|
||||
.pointer("/_meta/openidea/mcpServersOff")
|
||||
.and_then(Value::as_array)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(Value::as_str)
|
||||
.map(|name| {
|
||||
let name: String =
|
||||
name.chars().map(|c| if c.is_ascii_alphanumeric() || c == '_' || c == '-' { c } else { '_' }).collect();
|
||||
format!("mcp__{name}")
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// ACP `mcpServers` as Claude Code's `--mcp-config` JSON (`None` when there are none).
|
||||
fn mcp_config(params: &Value) -> Option<String> {
|
||||
let servers = params.get("mcpServers")?.as_array()?;
|
||||
|
||||
@@ -48,17 +48,10 @@ impl Settings {
|
||||
.filter_map(|m| {
|
||||
let s = |k: &str| m.get(k).and_then(Value::as_str).map(str::to_owned);
|
||||
let value = s("value")?;
|
||||
let resolved = s("resolvedModel");
|
||||
// The default entry follows the account's default model, so "Default
|
||||
// (recommended)" hides what actually runs: name the model it resolves to.
|
||||
let name = match (value.as_str(), resolved.as_deref()) {
|
||||
("default", Some(r)) if !r.is_empty() => format!("Default ({r})"),
|
||||
_ => s("displayName").unwrap_or_else(|| value.clone()),
|
||||
};
|
||||
Some(Model {
|
||||
name,
|
||||
name: s("displayName").unwrap_or_else(|| value.clone()),
|
||||
description: s("description"),
|
||||
resolved,
|
||||
resolved: s("resolvedModel"),
|
||||
efforts: if m.get("supportsEffort").and_then(Value::as_bool) == Some(true) {
|
||||
m.get("supportedEffortLevels")
|
||||
.and_then(Value::as_array)
|
||||
@@ -237,19 +230,6 @@ mod tests {
|
||||
assert_eq!(s.model, "claude-x-1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_default_entry_is_named_by_the_model_it_runs() {
|
||||
let s = Settings::from_cli(&init(), &json!({"applied": {"model": "claude-sonnet-5-5"}}));
|
||||
let names: Vec<_> = s.models.iter().map(|m| m.name.as_str()).collect();
|
||||
assert_eq!(names, ["Default (claude-sonnet-5-5)", "Opus", "Haiku 4.5"]);
|
||||
// Without a resolved model, the agent's own name stands.
|
||||
let s = Settings::from_cli(
|
||||
&json!({"models": [{"value": "default", "displayName": "Default (recommended)"}]}),
|
||||
&json!({}),
|
||||
);
|
||||
assert_eq!(s.models[0].name, "Default (recommended)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn options_follow_the_model() {
|
||||
let mut s = Settings::from_cli(&init(), &json!({"applied": {"model": "claude-sonnet-5-5", "effort": "high"}}));
|
||||
|
||||
@@ -531,38 +531,6 @@ async fn sessions_without_a_title_get_one_generated() {
|
||||
assert_eq!(request["request"]["persist"], true);
|
||||
}
|
||||
|
||||
/// A compaction that doesn't report what the context holds now (no `post_tokens`): the
|
||||
/// driver asks Claude Code, and the meter shows that instead of the count from before.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_compaction_without_its_token_count_reads_the_context_usage() {
|
||||
let mut processes = load_fixture("simple");
|
||||
processes[0].extend([
|
||||
Frame::Cli(json!({"type": "system", "subtype": "compact_boundary",
|
||||
"compact_metadata": {"trigger": "manual", "pre_tokens": 120000}})),
|
||||
Frame::Shim(json!({"type": "control_request", "request_id": "req_3",
|
||||
"request": {"subtype": "get_context_usage"}})),
|
||||
Frame::Cli(json!({"type": "control_response", "response": {"subtype": "success", "request_id": "req_3",
|
||||
"response": {"categories": [], "totalTokens": 4200, "maxTokens": 200000, "model": "claude"}}})),
|
||||
]);
|
||||
let cli = replay_cli(processes);
|
||||
let (config, cwd) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
|
||||
let cwd_path = std::fs::canonicalize(cwd.path()).unwrap();
|
||||
let h =
|
||||
Harness::connect(cli.clone(), config.path().into(), config.path().join("pending"), cwd_path, Vec::new()).await;
|
||||
let session = h.new_session().await;
|
||||
h.prompt(&session, "Reply with exactly: hello there").await.unwrap();
|
||||
let mut usage = Vec::new();
|
||||
for _ in 0..100 {
|
||||
usage = h.updates(&session, "usage_update");
|
||||
if usage.last().is_some_and(|u| u["used"] == 4200) {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
}
|
||||
assert!(cli.errors.lock().is_empty(), "{:?}", cli.errors.lock());
|
||||
assert_eq!(usage.last().map(|u| (u["used"].clone(), u["size"].clone())), Some((json!(4200), json!(200000))));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn replay_multi_turn() {
|
||||
let r = replay("multi_turn").await;
|
||||
@@ -1130,24 +1098,6 @@ fn streamed_text_is_not_sent_twice() {
|
||||
assert_eq!(usage[0].update, json!({"sessionUpdate": "usage_update", "used": 15, "size": 1000}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_compaction_replaces_the_context_usage() {
|
||||
let mut t = Translator::new("s", PathBuf::from("/w"), true);
|
||||
let assistant = json!({"type": "assistant", "parent_tool_use_id": null,
|
||||
"message": {"id": "m1", "model": "x", "content": [], "usage": {"input_tokens": 900, "output_tokens": 50}}});
|
||||
t.on_message(&assistant);
|
||||
let result = json!({"modelUsage": {"x": {"contextWindow": 1000}}});
|
||||
assert_eq!(t.on_result(&result)[0].update["used"], 950);
|
||||
let boundary = |meta: Value| json!({"type": "system", "subtype": "compact_boundary", "compact_metadata": meta});
|
||||
let out = t.on_message(&boundary(json!({"trigger": "manual", "pre_tokens": 950, "post_tokens": 120})));
|
||||
assert_eq!(out[0].update, json!({"sessionUpdate": "usage_update", "used": 120, "size": 1000}));
|
||||
// The `/compact` turn's result reports what compaction left, not the count from before.
|
||||
assert_eq!(t.on_result(&result)[0].update["used"], 120);
|
||||
// Without `post_tokens` nothing is known yet (the driver asks): the stale count stays out.
|
||||
assert!(t.on_message(&boundary(json!({"trigger": "auto", "pre_tokens": 950}))).is_empty());
|
||||
assert!(t.on_result(&result).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rate_limits_and_cost() {
|
||||
let mut t = Translator::new("s", PathBuf::from("/w"), false);
|
||||
@@ -1293,13 +1243,6 @@ async fn skipped_questions_have_no_answers() {
|
||||
assert_eq!(cancelled, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn servers_switched_off_become_disallowed_tools() {
|
||||
assert!(mcp_off(&json!({})).is_empty());
|
||||
let off = mcp_off(&json!({ "_meta": { "openidea": { "mcpServersOff": ["github", "my server.v2"] } } }));
|
||||
assert_eq!(off, ["mcp__github", "mcp__my_server_v2"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mcp_servers_become_an_mcp_config() {
|
||||
assert_eq!(mcp_config(&json!({ "mcpServers": [] })), None);
|
||||
@@ -1325,10 +1268,3 @@ fn mcp_servers_become_an_mcp_config() {
|
||||
drop(path);
|
||||
assert!(!kept.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn additional_directories_are_read_from_the_session_params() {
|
||||
let params = json!({ "cwd": "/w/api", "additionalDirectories": ["/w/web", 3, "/w/docs"] });
|
||||
assert_eq!(additional_dirs(¶ms), ["/w/web", "/w/docs"]);
|
||||
assert!(additional_dirs(&json!({ "cwd": "/w/api" })).is_empty());
|
||||
}
|
||||
@@ -144,22 +144,6 @@ pub(super) fn result_fields(name: &str, input: &Value, block: &Value, structured
|
||||
content.push(text(&t));
|
||||
}
|
||||
}
|
||||
if let Some(blocks) = block.get("content").and_then(Value::as_array) {
|
||||
for block in blocks {
|
||||
if block.get("type").and_then(Value::as_str) != Some("image") {
|
||||
continue;
|
||||
}
|
||||
let Some(source) = block.get("source") else { continue };
|
||||
if source.get("type").and_then(Value::as_str) != Some("base64") {
|
||||
continue;
|
||||
}
|
||||
let data = source.get("data").and_then(Value::as_str).unwrap_or_default();
|
||||
let mime = source.get("media_type").and_then(Value::as_str).unwrap_or_default();
|
||||
if !data.is_empty() && mime.starts_with("image/") {
|
||||
content.push(json!({"type": "content", "content": {"type": "image", "mimeType": mime, "data": data}}));
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut out = json!({ "status": if failed { "failed" } else { "completed" } });
|
||||
if !content.is_empty() {
|
||||
out["content"] = Value::Array(content);
|
||||
@@ -246,43 +230,6 @@ mod tests {
|
||||
assert_eq!(call_fields("WebSearch", &json!({"query": "q"}), cwd)["kind"], "fetch");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn image_tool_results_keep_text_and_inline_images() {
|
||||
let result = result_fields(
|
||||
"Read",
|
||||
&json!({"file_path": "/w/preview.png"}),
|
||||
&json!({"content": [
|
||||
{"type": "text", "text": "Preview ready"},
|
||||
{"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": "aW1hZ2U="}}
|
||||
]}),
|
||||
None,
|
||||
);
|
||||
assert_eq!(result["status"], "completed");
|
||||
assert_eq!(
|
||||
result["content"],
|
||||
json!([
|
||||
text("Preview ready"),
|
||||
{"type": "content", "content": {"type": "image", "mimeType": "image/png", "data": "aW1hZ2U="}}
|
||||
])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_shell_tool_images_keep_fallback_error_text() {
|
||||
let result = result_fields(
|
||||
"Bash",
|
||||
&json!({}),
|
||||
&json!({"is_error": true, "content": [
|
||||
{"type": "text", "text": "Preview command failed"},
|
||||
{"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": "aW1hZ2U="}}
|
||||
]}),
|
||||
Some(&json!({"stdout": "", "stderr": ""})),
|
||||
);
|
||||
assert_eq!(result["status"], "failed");
|
||||
assert_eq!(result["content"][0], text("Preview command failed"));
|
||||
assert_eq!(result["content"][1]["content"]["type"], "image");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn results() {
|
||||
let input = json!({"file_path": "/w/n.txt", "content": "two"});
|
||||
|
||||
@@ -458,13 +458,6 @@ impl Translator {
|
||||
let last = self.children.get(&tool_use).map(|c| c.last_text.clone()).filter(|t| !t.is_empty());
|
||||
self.finish_child(&tool_use, stop, last.or(summary))
|
||||
}
|
||||
// Compaction replaced the conversation with its summary: the context now holds
|
||||
// `post_tokens`. Without it the stale count must not come back with the result;
|
||||
// the driver asks Claude Code instead (`Session::refresh_usage`).
|
||||
Some("compact_boundary") => {
|
||||
self.used = msg.pointer("/compact_metadata/post_tokens").and_then(Value::as_u64);
|
||||
self.usage_update().into_iter().collect()
|
||||
}
|
||||
// A turn's background tasks (`run_in_background`) outlive it: the task keeps
|
||||
// the list and stays up while it isn't empty (see `Task::release_when_idle`).
|
||||
Some("background_tasks_changed") => {
|
||||
@@ -568,16 +561,6 @@ impl Translator {
|
||||
self.usage_update().into_iter().collect()
|
||||
}
|
||||
|
||||
/// The context usage Claude Code reports (`get_context_usage`), as a usage update.
|
||||
pub fn on_context_usage(&mut self, used: u64, size: u64) -> Update {
|
||||
self.used = Some(used);
|
||||
let mut update = json!({ "sessionUpdate": "usage_update", "used": used, "size": size });
|
||||
if let Some(amount) = self.cost_usd {
|
||||
update["cost"] = json!({ "amount": amount, "currency": "USD" });
|
||||
}
|
||||
Update { session: self.root.clone(), update }
|
||||
}
|
||||
|
||||
fn usage_update(&self) -> Option<Update> {
|
||||
let used = self.used?;
|
||||
let size = self
|
||||
|
||||
@@ -1,155 +0,0 @@
|
||||
//! Codex's built-in slash commands. `codex app-server` has no command-list API, so the
|
||||
//! native adapter owns this stable compatibility table; skills stay dynamic via `skills/list`.
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
/// Menu metadata shared by agent_commands and the prompt dispatcher.
|
||||
pub(crate) struct BuiltinCommandSpec {
|
||||
pub name: &'static str,
|
||||
pub description: &'static str,
|
||||
pub hint: Option<&'static str>,
|
||||
}
|
||||
|
||||
pub(crate) const BUILTIN_COMMANDS: &[BuiltinCommandSpec] = &[
|
||||
BuiltinCommandSpec { name: "plan", description: "Turn plan mode on or off.", hint: None },
|
||||
BuiltinCommandSpec {
|
||||
name: "mcp",
|
||||
description: "Show the status of the MCP servers, or reconnect them.",
|
||||
hint: Some("[reconnect]"),
|
||||
},
|
||||
BuiltinCommandSpec { name: "skills", description: "List available skills.", hint: None },
|
||||
BuiltinCommandSpec { name: "status", description: "Display session configuration and token usage.", hint: None },
|
||||
BuiltinCommandSpec {
|
||||
name: "review",
|
||||
description: "Review uncommitted changes, or review with custom instructions.",
|
||||
hint: Some("optional review instructions"),
|
||||
},
|
||||
BuiltinCommandSpec {
|
||||
name: "review-branch",
|
||||
description: "Review changes relative to a base branch.",
|
||||
hint: Some("branch name"),
|
||||
},
|
||||
BuiltinCommandSpec { name: "review-commit", description: "Review a specific commit.", hint: Some("commit sha") },
|
||||
BuiltinCommandSpec {
|
||||
name: "compact",
|
||||
description: "Summarize conversation to avoid hitting the context limit.",
|
||||
hint: None,
|
||||
},
|
||||
BuiltinCommandSpec {
|
||||
name: "goal",
|
||||
description: "Set a goal to keep pursuing.",
|
||||
hint: Some("[<objective>|clear|pause|resume]"),
|
||||
},
|
||||
BuiltinCommandSpec { name: "rename", description: "Rename the current session.", hint: Some("new name") },
|
||||
BuiltinCommandSpec {
|
||||
name: "logout",
|
||||
description: "Sign out of Codex. This option is available when you are logged in via ChatGPT.",
|
||||
hint: None,
|
||||
},
|
||||
];
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(super) enum BuiltinCommand {
|
||||
Plan,
|
||||
Mcp,
|
||||
Skills,
|
||||
Status,
|
||||
Review,
|
||||
ReviewBranch,
|
||||
ReviewCommit,
|
||||
Compact,
|
||||
Goal,
|
||||
Rename,
|
||||
Logout,
|
||||
}
|
||||
|
||||
impl BuiltinCommand {
|
||||
fn from_name(name: &str) -> Option<Self> {
|
||||
Some(match name {
|
||||
"plan" => Self::Plan,
|
||||
"mcp" => Self::Mcp,
|
||||
"skills" => Self::Skills,
|
||||
"status" => Self::Status,
|
||||
"review" => Self::Review,
|
||||
"review-branch" => Self::ReviewBranch,
|
||||
"review-commit" => Self::ReviewCommit,
|
||||
"compact" => Self::Compact,
|
||||
"goal" => Self::Goal,
|
||||
"rename" => Self::Rename,
|
||||
"logout" => Self::Logout,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub(super) struct ParsedCommand {
|
||||
pub command: BuiltinCommand,
|
||||
/// Everything after the command name, trimmed but otherwise unchanged.
|
||||
pub rest: String,
|
||||
}
|
||||
|
||||
impl ParsedCommand {
|
||||
/// Commands that Codex completes as a turn. Missing review arguments stay local so the
|
||||
/// adapter can print the command's usage without starting an unnecessary model request.
|
||||
pub fn starts_turn(&self) -> bool {
|
||||
matches!(self.command, BuiltinCommand::Compact | BuiltinCommand::Review)
|
||||
|| (matches!(self.command, BuiltinCommand::ReviewBranch | BuiltinCommand::ReviewCommit)
|
||||
&& !self.rest.is_empty())
|
||||
}
|
||||
}
|
||||
|
||||
/// A recognized Codex builtin at the start of the prompt. Unknown slash commands and
|
||||
/// `$skill` invocations return `None`, so they continue through Codex as ordinary prompts.
|
||||
pub(super) fn parse(prompt: &Value) -> Option<ParsedCommand> {
|
||||
let text = prompt.as_array()?.first()?.get("text")?.as_str()?.trim();
|
||||
let command_text = text.strip_prefix('/')?.trim();
|
||||
let (name, rest) = command_text.split_once(char::is_whitespace).unwrap_or((command_text, ""));
|
||||
let command = BuiltinCommand::from_name(&name.to_ascii_lowercase())?;
|
||||
Some(ParsedCommand { command, rest: rest.trim().to_owned() })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
fn text(value: &str) -> Value {
|
||||
json!([{ "type": "text", "text": value }])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_builtin_is_registered_and_parsed() {
|
||||
let expected = [
|
||||
"plan",
|
||||
"mcp",
|
||||
"skills",
|
||||
"status",
|
||||
"review",
|
||||
"review-branch",
|
||||
"review-commit",
|
||||
"compact",
|
||||
"goal",
|
||||
"rename",
|
||||
"logout",
|
||||
];
|
||||
assert_eq!(BUILTIN_COMMANDS.iter().map(|c| c.name).collect::<Vec<_>>(), expected);
|
||||
for name in expected {
|
||||
assert!(parse(&text(&format!("/{name}"))).is_some(), "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parsing_keeps_arguments_and_leaves_non_builtins_alone() {
|
||||
let parsed = parse(&text(" /review-branch origin/main ")).unwrap();
|
||||
assert_eq!(parsed.command, BuiltinCommand::ReviewBranch);
|
||||
assert_eq!(parsed.rest, "origin/main");
|
||||
assert!(parsed.starts_turn());
|
||||
assert!(!parse(&text("/review-branch")).unwrap().starts_turn());
|
||||
assert!(parse(&text("/$review check this")).is_none());
|
||||
assert!(parse(&text("review")).is_none());
|
||||
|
||||
let prompt = json!([{ "type": "text", "text": "/compact" }, { "type": "image", "data": "AA==" }]);
|
||||
assert_eq!(parse(&prompt).unwrap().command, BuiltinCommand::Compact);
|
||||
}
|
||||
}
|
||||
@@ -2,11 +2,7 @@
|
||||
//! translated to and from ACP. A codex thread is an ACP session; a subagent's thread is
|
||||
//! a subagent session of the thread that spawned it.
|
||||
|
||||
mod commands;
|
||||
mod translate;
|
||||
mod trust;
|
||||
|
||||
pub(crate) use commands::BUILTIN_COMMANDS;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -14,8 +10,6 @@ mod tests;
|
||||
use super::Shim;
|
||||
use crate::acp::AUTH_REQUIRED;
|
||||
use crate::provider::ProviderSpec;
|
||||
use crate::{AgentCommand, AgentCommandSource};
|
||||
use commands::{BuiltinCommand, ParsedCommand};
|
||||
use ide_jsonrpc::{Framing, Handler, Peer, RpcError, codes};
|
||||
use parking_lot::Mutex;
|
||||
use serde_json::{Value, json};
|
||||
@@ -38,19 +32,6 @@ const EXIT_GRACE: Duration = Duration::from_millis(100);
|
||||
const NAME_PROMPT: &str = "Name this conversation for a list of tasks: a short title of at most six words, in the \
|
||||
language the user writes in. Reply with the title only, without quotes or a closing period.";
|
||||
|
||||
/// Slash-command metadata for provider discovery and sessions without an advertised list.
|
||||
pub(crate) fn builtin_commands() -> Vec<AgentCommand> {
|
||||
BUILTIN_COMMANDS
|
||||
.iter()
|
||||
.map(|command| AgentCommand {
|
||||
name: command.name.to_owned(),
|
||||
description: command.description.to_owned(),
|
||||
hint: command.hint.map(str::to_owned),
|
||||
source: AgentCommandSource::Command,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub(crate) fn connect(
|
||||
spec: &ProviderSpec,
|
||||
cwd: &Path,
|
||||
@@ -202,8 +183,6 @@ struct State {
|
||||
threads: HashMap<String, Thread>,
|
||||
/// The last `account/rateLimits/updated` snapshot.
|
||||
rate_limits: Option<Value>,
|
||||
/// Project trust has been checked (and, when needed, asked about) on this connection.
|
||||
trust_checked: HashSet<String>,
|
||||
/// Codex exited.
|
||||
gone: bool,
|
||||
}
|
||||
@@ -236,8 +215,6 @@ struct Thread {
|
||||
early_cancel: Option<Instant>,
|
||||
/// The latest agent message (a subagent's answer).
|
||||
answer: String,
|
||||
/// The latest `thread/tokenUsage/updated` payload, for the `/status` command.
|
||||
token_usage: Option<Value>,
|
||||
/// The thread has a name.
|
||||
named: bool,
|
||||
/// A name is being asked for.
|
||||
@@ -334,38 +311,6 @@ fn str_param<'a>(params: &'a Value, key: &str) -> Result<&'a str, ResponseError>
|
||||
params.get(key).and_then(Value::as_str).ok_or_else(|| invalid(format!("missing {key}")))
|
||||
}
|
||||
|
||||
/// Fills a `thread/start`/`thread/resume`/`thread/fork` request's `config` with the session's
|
||||
/// MCP servers and its staged skills: the off ones, by path (`skills.config` entries with
|
||||
/// `enabled = false`, which the CLI honors for the copies it discovers natively too).
|
||||
fn apply_thread_config(params: &Value, request: &mut Value) {
|
||||
let mut config = translate::mcp_config(params).unwrap_or_else(|| json!({}));
|
||||
let off: Vec<Value> = params
|
||||
.pointer("/_meta/openidea/skills/codexOff")
|
||||
.and_then(Value::as_array)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|entry| {
|
||||
let path = entry.get(1)?.as_str()?;
|
||||
Some(json!({ "path": path, "enabled": false }))
|
||||
})
|
||||
.collect();
|
||||
if !off.is_empty()
|
||||
&& let Some(map) = config.as_object_mut()
|
||||
{
|
||||
map.insert("skills".into(), json!({ "config": off }));
|
||||
}
|
||||
if !config.as_object().is_some_and(|m| m.is_empty()) {
|
||||
request["config"] = config;
|
||||
}
|
||||
// The workspace's other roots join the thread's own: they are where `workspace-write`
|
||||
// may write and what the model is told the workspace holds.
|
||||
if let Some(extra) = params.get("additionalDirectories").and_then(Value::as_array).filter(|a| !a.is_empty())
|
||||
&& let Some(cwd) = params.get("cwd").filter(|c| c.is_string())
|
||||
{
|
||||
request["runtimeWorkspaceRoots"] = std::iter::once(cwd).chain(extra).cloned().collect();
|
||||
}
|
||||
}
|
||||
|
||||
impl CodexShim {
|
||||
fn codex(&self) -> &Peer {
|
||||
self.codex.get().expect("attached before any message")
|
||||
@@ -375,12 +320,6 @@ impl CodexShim {
|
||||
self.codex().request(method, params, None).await.map_err(from_codex)
|
||||
}
|
||||
|
||||
fn warning(&self, message: impl Into<String>) {
|
||||
if let Some(client) = self.client.get() {
|
||||
let _ = client.notify(crate::WARNING_NOTIFICATION, json!({ "message": message.into() }));
|
||||
}
|
||||
}
|
||||
|
||||
async fn handle(&self, method: &str, params: Value) -> Result<Value, ResponseError> {
|
||||
match method {
|
||||
"initialize" => self.initialize().await,
|
||||
@@ -413,7 +352,7 @@ impl CodexShim {
|
||||
"loadSession": true,
|
||||
"promptCapabilities": { "image": true, "audio": false, "embeddedContext": true },
|
||||
"mcpCapabilities": { "http": false, "sse": false, "stdio": true },
|
||||
"sessionCapabilities": { "fork": {}, "close": {}, "additionalDirectories": {} },
|
||||
"sessionCapabilities": { "fork": {}, "close": {} },
|
||||
"_meta": { "openidea": { "rollback": true, "steer": true } },
|
||||
},
|
||||
"agentInfo": { "name": "codex", "title": "Codex", "version": version },
|
||||
@@ -446,31 +385,6 @@ impl CodexShim {
|
||||
}
|
||||
}
|
||||
|
||||
/// Hands the session's staged skills to the app-server: the farm's `codex` tree joins
|
||||
/// its discovery roots. Best-effort: a CLI version without `skills/extraRoots/set`
|
||||
/// (the method arrived later than some pinned installs) runs without the farm, as
|
||||
/// before.
|
||||
async fn apply_skill_roots(&self, session: &str, params: &Value) {
|
||||
let roots = params
|
||||
.pointer("/_meta/openidea/skills/codexExtraRoots")
|
||||
.and_then(Value::as_array)
|
||||
.map(|a| a.iter().filter_map(Value::as_str).collect::<Vec<_>>())
|
||||
.unwrap_or_default();
|
||||
if roots.is_empty() {
|
||||
return;
|
||||
}
|
||||
let set = tokio::time::timeout(
|
||||
Duration::from_secs(5),
|
||||
self.call("skills/extraRoots/set", json!({ "extraRoots": roots })),
|
||||
)
|
||||
.await;
|
||||
match set {
|
||||
Ok(Ok(_)) => {}
|
||||
Ok(Err(e)) => tracing::info!("codex session {session}: could not set the extra skill roots: {}", e.message),
|
||||
Err(e) => tracing::info!("codex session {session}: could not set the extra skill roots: {e}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Registers a thread codex opened for a session of its own; returns its `configOptions`.
|
||||
fn open_thread(&self, result: &Value, models: &[ModelInfo], settings: Option<Settings>) -> (String, Value) {
|
||||
let thread = result.get("thread").unwrap_or(&Value::Null);
|
||||
@@ -489,15 +403,15 @@ impl CodexShim {
|
||||
|
||||
async fn new_session(&self, params: &Value) -> Result<Value, ResponseError> {
|
||||
let models = self.models().await?;
|
||||
self.prepare_project_trust(params).await;
|
||||
let mut request = json!({ "cwd": params.get("cwd") });
|
||||
apply_thread_config(params, &mut request);
|
||||
if let Some(config) = translate::mcp_config(params) {
|
||||
request["config"] = config;
|
||||
}
|
||||
let result = self.call("thread/start", request).await?;
|
||||
let (id, options) = self.open_thread(&result, &models, None);
|
||||
if id.is_empty() {
|
||||
return Err(error(codes::INTERNAL_ERROR, "codex started no thread"));
|
||||
}
|
||||
self.apply_skill_roots(&id, params).await;
|
||||
self.publish_skills(&id).await;
|
||||
Ok(json!({ "sessionId": id, "configOptions": options }))
|
||||
}
|
||||
@@ -506,9 +420,10 @@ impl CodexShim {
|
||||
async fn load_session(&self, params: &Value) -> Result<Value, ResponseError> {
|
||||
let id = str_param(params, "sessionId")?;
|
||||
let models = self.models().await?;
|
||||
self.prepare_project_trust(params).await;
|
||||
let mut request = json!({ "threadId": id, "cwd": params.get("cwd") });
|
||||
apply_thread_config(params, &mut request);
|
||||
if let Some(config) = translate::mcp_config(params) {
|
||||
request["config"] = config;
|
||||
}
|
||||
let result = self.call("thread/resume", request).await?;
|
||||
let (_, options) = self.open_thread(&result, &models, None);
|
||||
let cwd = self.state.lock().threads.get(id).and_then(|t| t.cwd.clone());
|
||||
@@ -516,7 +431,6 @@ impl CodexShim {
|
||||
for update in translate::history(thread, cwd.as_deref()) {
|
||||
self.emit(id, update);
|
||||
}
|
||||
self.apply_skill_roots(id, params).await;
|
||||
self.publish_skills(id).await;
|
||||
Ok(json!({ "configOptions": options }))
|
||||
}
|
||||
@@ -524,10 +438,11 @@ impl CodexShim {
|
||||
async fn fork_session(&self, params: &Value) -> Result<Value, ResponseError> {
|
||||
let source = str_param(params, "sessionId")?;
|
||||
let models = self.models().await?;
|
||||
self.prepare_project_trust(params).await;
|
||||
let settings = self.state.lock().threads.get(source).and_then(|t| t.settings.clone());
|
||||
let mut request = json!({ "threadId": source, "cwd": params.get("cwd") });
|
||||
apply_thread_config(params, &mut request);
|
||||
if let Some(config) = translate::mcp_config(params) {
|
||||
request["config"] = config;
|
||||
}
|
||||
if let Some(s) = &settings {
|
||||
request["model"] = json!(s.model_slug(&models));
|
||||
request["approvalPolicy"] = json!(s.mode.approval_policy());
|
||||
@@ -535,7 +450,6 @@ impl CodexShim {
|
||||
}
|
||||
let result = self.call("thread/fork", request).await?;
|
||||
let (id, options) = self.open_thread(&result, &models, settings);
|
||||
self.apply_skill_roots(&id, params).await;
|
||||
self.publish_skills(&id).await;
|
||||
Ok(json!({ "sessionId": id, "configOptions": options }))
|
||||
}
|
||||
@@ -557,18 +471,11 @@ impl CodexShim {
|
||||
|
||||
async fn prompt(&self, params: &Value) -> Result<Value, ResponseError> {
|
||||
let session = str_param(params, "sessionId")?.to_owned();
|
||||
let prompt = params.get("prompt").unwrap_or(&Value::Null);
|
||||
let command = commands::parse(prompt);
|
||||
if let Some(command) = command.as_ref()
|
||||
&& !command.starts_turn()
|
||||
{
|
||||
return self.local_command(&session, command).await;
|
||||
}
|
||||
let input = translate::user_input(prompt);
|
||||
let input = translate::user_input(params.get("prompt").unwrap_or(&Value::Null));
|
||||
if input.is_empty() {
|
||||
return Err(invalid("empty prompt"));
|
||||
}
|
||||
let models = if command.is_none() { Some(self.models().await?) } else { None };
|
||||
let models = self.models().await?;
|
||||
let (done, ended) = oneshot::channel();
|
||||
let settings = {
|
||||
let mut state = self.state.lock();
|
||||
@@ -584,213 +491,33 @@ impl CodexShim {
|
||||
t.error = None;
|
||||
t.settings.clone()
|
||||
};
|
||||
let started = match command.as_ref() {
|
||||
Some(command) => match command.command {
|
||||
BuiltinCommand::Compact => {
|
||||
// Codex reports compaction as its own turn, using the same started/completed
|
||||
// notifications that finish the pending session/prompt above.
|
||||
self.call("thread/compact/start", json!({ "threadId": session })).await
|
||||
}
|
||||
BuiltinCommand::Review | BuiltinCommand::ReviewBranch | BuiltinCommand::ReviewCommit => {
|
||||
self.call("review/start", json!({ "threadId": session, "target": review_target(command) })).await
|
||||
}
|
||||
_ => unreachable!("local commands return before a pending turn is created"),
|
||||
},
|
||||
None => {
|
||||
let models = models.expect("ordinary prompts load the model catalog");
|
||||
let mut request = json!({ "threadId": session, "input": input, "summary": "auto" });
|
||||
if let Some(s) = &settings {
|
||||
request["model"] = json!(s.model_slug(&models));
|
||||
request["approvalPolicy"] = json!(s.mode.approval_policy());
|
||||
request["sandboxPolicy"] = s.mode.sandbox_policy();
|
||||
// Omit the default so older app-server versions keep accepting normal
|
||||
// turns; selecting Plan opts into this newer request field.
|
||||
if s.collaboration_mode == translate::PLAN_COLLABORATION_MODE
|
||||
|| s.collaboration_mode_override.is_some()
|
||||
{
|
||||
request["collaborationMode"] = translate::collaboration_mode(s, &models);
|
||||
}
|
||||
if let Some(effort) = &s.effort {
|
||||
request["effort"] = json!(effort);
|
||||
}
|
||||
}
|
||||
self.call("turn/start", request).await
|
||||
let mut request = json!({ "threadId": session, "input": input, "summary": "auto" });
|
||||
if let Some(s) = settings {
|
||||
request["model"] = json!(s.model_slug(&models));
|
||||
request["approvalPolicy"] = json!(s.mode.approval_policy());
|
||||
request["sandboxPolicy"] = s.mode.sandbox_policy();
|
||||
if let Some(effort) = &s.effort {
|
||||
request["effort"] = json!(effort);
|
||||
}
|
||||
};
|
||||
if let Ok(started) = &started
|
||||
&& let Some(turn) = started.pointer("/turn/id").and_then(Value::as_str)
|
||||
{
|
||||
self.turn_known(&session, turn, false);
|
||||
}
|
||||
if started.is_ok()
|
||||
&& command.is_none()
|
||||
&& let Some(thread) = self.state.lock().threads.get_mut(&session)
|
||||
&& let Some(settings) = thread.settings.as_mut()
|
||||
{
|
||||
// A Default override is needed only for the first turn that resets a resumed
|
||||
// Plan thread; omitting it afterwards preserves compatibility with older Codex.
|
||||
settings.collaboration_mode_override = None;
|
||||
}
|
||||
if let Err(e) = started {
|
||||
if let Some(t) = self.state.lock().threads.get_mut(&session) {
|
||||
t.prompt = None;
|
||||
match self.call("turn/start", request).await {
|
||||
Ok(started) => {
|
||||
if let Some(turn) = started.pointer("/turn/id").and_then(Value::as_str) {
|
||||
self.turn_known(&session, turn, false);
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
if let Some(t) = self.state.lock().threads.get_mut(&session) {
|
||||
t.prompt = None;
|
||||
}
|
||||
return Err(e);
|
||||
}
|
||||
return Err(e);
|
||||
}
|
||||
let (turn, last_error) = ended.await.map_err(|_| error(codes::INTERNAL_ERROR, "Codex exited"))?;
|
||||
let rate_limits = self.state.lock().rate_limits.clone();
|
||||
stop_reason(&turn, last_error, rate_limits.as_ref())
|
||||
}
|
||||
|
||||
/// Runs commands that codex-acp historically handled locally: configuration, status,
|
||||
/// inventory, naming and account actions. They complete without starting a model turn.
|
||||
async fn local_command(&self, session: &str, command: &ParsedCommand) -> Result<Value, ResponseError> {
|
||||
let (settings, cwd, token_usage, rate_limits) = {
|
||||
let state = self.state.lock();
|
||||
if state.gone {
|
||||
return Err(error(codes::INTERNAL_ERROR, "Codex exited"));
|
||||
}
|
||||
let thread = state.threads.get(session).ok_or_else(|| invalid(format!("no session {session}")))?;
|
||||
if thread.prompt.is_some() || thread.turn.is_some() {
|
||||
return Err(invalid("a turn is already running"));
|
||||
}
|
||||
(thread.settings.clone(), thread.cwd.clone(), thread.token_usage.clone(), state.rate_limits.clone())
|
||||
};
|
||||
|
||||
match command.command {
|
||||
BuiltinCommand::Plan => {
|
||||
if !command.rest.is_empty() {
|
||||
self.say(session, command_usage(BuiltinCommand::Plan));
|
||||
return Ok(json!({ "stopReason": "end_turn" }));
|
||||
}
|
||||
let models = self.models().await?;
|
||||
let options = {
|
||||
let mut state = self.state.lock();
|
||||
let thread =
|
||||
state.threads.get_mut(session).ok_or_else(|| invalid(format!("no session {session}")))?;
|
||||
let settings = thread.settings.as_mut().ok_or_else(|| invalid(format!("no session {session}")))?;
|
||||
settings.collaboration_mode = if settings.collaboration_mode == translate::PLAN_COLLABORATION_MODE {
|
||||
translate::DEFAULT_COLLABORATION_MODE.to_owned()
|
||||
} else {
|
||||
translate::PLAN_COLLABORATION_MODE.to_owned()
|
||||
};
|
||||
settings.collaboration_mode_override = Some(settings.collaboration_mode.clone());
|
||||
translate::config_options(&models, settings)
|
||||
};
|
||||
self.emit(session, json!({ "sessionUpdate": "config_option_update", "configOptions": options }));
|
||||
}
|
||||
BuiltinCommand::Status => {
|
||||
let text =
|
||||
status_text(session, settings.as_ref(), cwd.as_deref(), token_usage.as_ref(), rate_limits.as_ref());
|
||||
self.say(session, text);
|
||||
}
|
||||
BuiltinCommand::Skills => {
|
||||
let cwd = cwd.ok_or_else(|| invalid(format!("no session {session}")))?;
|
||||
let found = self.call("skills/list", json!({ "cwds": [cwd] })).await?;
|
||||
self.say(session, skills_text(&found));
|
||||
}
|
||||
BuiltinCommand::Mcp => match command.rest.as_str() {
|
||||
"" => self.say(session, self.mcp_text(session).await?),
|
||||
rest if rest.eq_ignore_ascii_case("reconnect") => {
|
||||
self.call("config/mcpServer/reload", json!({})).await?;
|
||||
self.say(session, self.mcp_text(session).await?);
|
||||
}
|
||||
_ => self.say(session, command_usage(BuiltinCommand::Mcp)),
|
||||
},
|
||||
BuiltinCommand::Rename => {
|
||||
if command.rest.is_empty() {
|
||||
self.say(session, command_usage(BuiltinCommand::Rename));
|
||||
} else {
|
||||
self.call("thread/name/set", json!({ "threadId": session, "name": command.rest })).await?;
|
||||
// User commands are authoritative over the automatic title, so the manager
|
||||
// must retain this title through later generated-name updates.
|
||||
self.emit(
|
||||
session,
|
||||
json!({ "sessionUpdate": "session_info_update", "title": command.rest, "userNamed": true }),
|
||||
);
|
||||
}
|
||||
}
|
||||
BuiltinCommand::Logout => {
|
||||
self.call("account/logout", Value::Null).await?;
|
||||
self.say(session, "Logged out from Codex account.");
|
||||
}
|
||||
BuiltinCommand::Goal => self.goal_command(session, &command.rest).await?,
|
||||
BuiltinCommand::ReviewBranch | BuiltinCommand::ReviewCommit if command.rest.is_empty() => {
|
||||
self.say(session, command_usage(command.command));
|
||||
}
|
||||
BuiltinCommand::ReviewBranch | BuiltinCommand::ReviewCommit => {
|
||||
return Err(invalid("review command did not start a turn"));
|
||||
}
|
||||
BuiltinCommand::Review | BuiltinCommand::Compact => {
|
||||
return Err(invalid("turn command reached the local command path"));
|
||||
}
|
||||
}
|
||||
Ok(json!({ "stopReason": "end_turn" }))
|
||||
}
|
||||
|
||||
async fn goal_command(&self, session: &str, rest: &str) -> Result<(), ResponseError> {
|
||||
let argument = rest.trim();
|
||||
if argument.is_empty() {
|
||||
self.say(session, command_usage(BuiltinCommand::Goal));
|
||||
return Ok(());
|
||||
}
|
||||
match argument.to_ascii_lowercase().as_str() {
|
||||
"clear" => {
|
||||
self.call("thread/goal/clear", json!({ "threadId": session })).await?;
|
||||
self.say(session, "Goal cleared.");
|
||||
}
|
||||
"pause" => {
|
||||
let response = self
|
||||
.call("thread/goal/set", json!({ "threadId": session, "status": "paused", "origin": "user" }))
|
||||
.await?;
|
||||
self.say(
|
||||
session,
|
||||
format!(
|
||||
"Goal is now {}.",
|
||||
response.pointer("/goal/status").and_then(Value::as_str).unwrap_or("paused")
|
||||
),
|
||||
);
|
||||
}
|
||||
"resume" => {
|
||||
let response = self
|
||||
.call("thread/goal/set", json!({ "threadId": session, "status": "active", "origin": "user" }))
|
||||
.await?;
|
||||
self.say(
|
||||
session,
|
||||
format!(
|
||||
"Goal is now {}.",
|
||||
response.pointer("/goal/status").and_then(Value::as_str).unwrap_or("active")
|
||||
),
|
||||
);
|
||||
}
|
||||
_ if argument.chars().count() > 4000 => {
|
||||
self.say(session, "Command \"/goal\" requires goal text of at most 4000 characters.");
|
||||
}
|
||||
_ => {
|
||||
let response = self
|
||||
.call(
|
||||
"thread/goal/set",
|
||||
json!({ "threadId": session, "objective": argument, "status": "active", "origin": "user" }),
|
||||
)
|
||||
.await?;
|
||||
let status = response.pointer("/goal/status").and_then(Value::as_str).unwrap_or("active");
|
||||
self.say(session, format!("Goal set and {status}."));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn mcp_text(&self, session: &str) -> Result<String, ResponseError> {
|
||||
let response = self
|
||||
.call("mcpServerStatus/list", json!({ "threadId": session, "detail": "toolsAndAuthOnly", "limit": 100 }))
|
||||
.await?;
|
||||
Ok(mcp_text(&response))
|
||||
}
|
||||
|
||||
fn say(&self, session: &str, text: impl AsRef<str>) {
|
||||
self.emit(session, translate::chunk("agent_message_chunk", text.as_ref()));
|
||||
}
|
||||
|
||||
async fn steer(&self, params: &Value) -> Result<Value, ResponseError> {
|
||||
let session = str_param(params, "sessionId")?;
|
||||
let turn = self.state.lock().threads.get(session).and_then(|t| t.turn.clone());
|
||||
@@ -916,25 +643,6 @@ impl CodexShim {
|
||||
fn on_codex_notification(self: &Arc<Self>, method: &str, params: &Value) {
|
||||
let thread = params.get("threadId").and_then(Value::as_str).unwrap_or_default();
|
||||
match method {
|
||||
"configWarning" => {
|
||||
let Some(summary) = params.get("summary").and_then(Value::as_str).filter(|s| !s.trim().is_empty())
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let mut message = summary.trim().to_owned();
|
||||
for key in ["details", "path"] {
|
||||
if let Some(value) = params.get(key).and_then(Value::as_str).filter(|s| !s.trim().is_empty()) {
|
||||
message.push_str("\n\n");
|
||||
message.push_str(value.trim());
|
||||
}
|
||||
}
|
||||
self.warning(message);
|
||||
}
|
||||
"warning" => {
|
||||
if let Some(message) = params.get("message").and_then(Value::as_str).filter(|s| !s.trim().is_empty()) {
|
||||
self.warning(message);
|
||||
}
|
||||
}
|
||||
"skills/changed" => {
|
||||
let shim = self.clone();
|
||||
let sessions: Vec<String> = self
|
||||
@@ -985,12 +693,7 @@ impl CodexShim {
|
||||
t.last_chunk = None;
|
||||
Some(translate::plan(params))
|
||||
}),
|
||||
"thread/tokenUsage/updated" => self.with_thread(thread, |t, _| {
|
||||
if let Some(usage) = params.get("tokenUsage") {
|
||||
t.token_usage = Some(usage.clone());
|
||||
}
|
||||
translate::usage(params)
|
||||
}),
|
||||
"thread/tokenUsage/updated" => self.with_thread(thread, |_, _| translate::usage(params)),
|
||||
"thread/name/updated" => self.with_thread(thread, |t, _| {
|
||||
let title = params.get("threadName").and_then(Value::as_str)?;
|
||||
t.named = true;
|
||||
@@ -1082,11 +785,6 @@ impl CodexShim {
|
||||
}
|
||||
Some(t.chunk(kind, &id, &text))
|
||||
});
|
||||
if ty == "agentMessage"
|
||||
&& let Some(update) = translate::question_update(item)
|
||||
{
|
||||
self.emit(thread, update);
|
||||
}
|
||||
}
|
||||
"subAgentActivity" => {
|
||||
let child = item.get("agentThreadId").and_then(Value::as_str).unwrap_or_default();
|
||||
@@ -1484,114 +1182,3 @@ fn stop_reason(turn: &Value, last_error: Option<Value>, rate_limits: Option<&Val
|
||||
};
|
||||
Ok(json!({ "stopReason": stop }))
|
||||
}
|
||||
|
||||
/// The `review/start` target of a parsed review command.
|
||||
fn review_target(command: &ParsedCommand) -> Value {
|
||||
match command.command {
|
||||
BuiltinCommand::Review if command.rest.is_empty() => json!({ "type": "uncommittedChanges" }),
|
||||
BuiltinCommand::Review => json!({ "type": "custom", "instructions": command.rest }),
|
||||
BuiltinCommand::ReviewBranch => json!({ "type": "baseBranch", "branch": command.rest }),
|
||||
BuiltinCommand::ReviewCommit => json!({ "type": "commit", "sha": command.rest, "title": null }),
|
||||
_ => unreachable!("only review commands have review targets"),
|
||||
}
|
||||
}
|
||||
|
||||
fn command_usage(command: BuiltinCommand) -> String {
|
||||
match command {
|
||||
BuiltinCommand::Plan => "Command \"/plan\" accepts no arguments.".to_owned(),
|
||||
BuiltinCommand::Mcp => "Command \"/mcp\" accepts no arguments, or `reconnect`.".to_owned(),
|
||||
BuiltinCommand::ReviewBranch => "Command \"/review-branch\" requires branch name.".to_owned(),
|
||||
BuiltinCommand::ReviewCommit => "Command \"/review-commit\" requires commit sha.".to_owned(),
|
||||
BuiltinCommand::Goal => "Command \"/goal\" requires [<objective>|clear|pause|resume].".to_owned(),
|
||||
BuiltinCommand::Rename => "Command \"/rename\" requires new name.".to_owned(),
|
||||
_ => "This command does not accept arguments.".to_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
fn status_text(
|
||||
session: &str,
|
||||
settings: Option<&Settings>,
|
||||
cwd: Option<&str>,
|
||||
token_usage: Option<&Value>,
|
||||
rate_limits: Option<&Value>,
|
||||
) -> String {
|
||||
let mut lines = Vec::new();
|
||||
if let Some(settings) = settings {
|
||||
lines.push(format!("**Model:** {}", settings.model));
|
||||
lines.push(format!("**Collaboration:** {}", settings.collaboration_mode));
|
||||
lines.push(format!("**Approval:** {}", settings.mode.approval_policy()));
|
||||
lines.push(format!("**Sandbox:** {}", settings.mode.sandbox_mode()));
|
||||
}
|
||||
if let Some(cwd) = cwd {
|
||||
lines.push(format!("**Directory:** {cwd}"));
|
||||
}
|
||||
lines.push(format!("**Session:** `{session}`"));
|
||||
if let Some(usage) = token_usage {
|
||||
let total = usage.pointer("/total/totalTokens").and_then(Value::as_u64);
|
||||
let used = usage.pointer("/last/totalTokens").and_then(Value::as_u64);
|
||||
let window = usage.get("modelContextWindow").and_then(Value::as_u64).filter(|window| *window > 0);
|
||||
if let (Some(total), Some(used), Some(window)) = (total, used, window) {
|
||||
let percent = (used.saturating_mul(100) + window / 2) / window;
|
||||
lines.push(format!("**Token usage:** {total} total"));
|
||||
lines.push(format!("**Context window:** {used} / {window} ({percent}%)"));
|
||||
}
|
||||
}
|
||||
if let Some(primary) = rate_limits.and_then(|r| r.get("primary"))
|
||||
&& let Some(used) = primary.get("usedPercent").and_then(Value::as_f64)
|
||||
{
|
||||
lines.push(format!("**Rate limit:** {used:.0}% used"));
|
||||
}
|
||||
lines.join(" \n")
|
||||
}
|
||||
|
||||
fn skills_text(response: &Value) -> String {
|
||||
let mut seen = HashSet::new();
|
||||
let names: Vec<String> = response
|
||||
.get("data")
|
||||
.and_then(Value::as_array)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|entry| entry.get("skills").and_then(Value::as_array))
|
||||
.flatten()
|
||||
.filter(|skill| skill.get("enabled") != Some(&Value::Bool(false)))
|
||||
.filter_map(|skill| {
|
||||
let name = skill.get("name").and_then(Value::as_str)?.trim();
|
||||
if name.is_empty() || !seen.insert(name.to_owned()) {
|
||||
return None;
|
||||
}
|
||||
let description = skill
|
||||
.pointer("/interface/shortDescription")
|
||||
.or_else(|| skill.get("shortDescription"))
|
||||
.or_else(|| skill.get("description"))
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or_default();
|
||||
Some(if description.is_empty() { name.to_owned() } else { format!("{name}: {description}") })
|
||||
})
|
||||
.collect();
|
||||
if names.is_empty() {
|
||||
"No skills configured.".to_owned()
|
||||
} else {
|
||||
format!("Available skills:\n{}", names.iter().map(|name| format!("- {name}")).collect::<Vec<_>>().join("\n"))
|
||||
}
|
||||
}
|
||||
|
||||
fn mcp_text(response: &Value) -> String {
|
||||
let servers = response.get("data").and_then(Value::as_array).map(Vec::as_slice).unwrap_or_default();
|
||||
if servers.is_empty() {
|
||||
return "No MCP servers configured.".to_owned();
|
||||
}
|
||||
let lines = servers
|
||||
.iter()
|
||||
.filter_map(|server| {
|
||||
let name = server.get("name").and_then(Value::as_str)?;
|
||||
let status = server
|
||||
.get("runtimeStatus")
|
||||
.and_then(Value::as_str)
|
||||
.or_else(|| server.get("authStatus").and_then(Value::as_str))
|
||||
.unwrap_or("unknown");
|
||||
let tools = server.get("tools").and_then(Value::as_object).map_or(0, serde_json::Map::len);
|
||||
Some(format!("- {name}: {status}, {tools} tools"))
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
format!("MCP servers:\n{}", lines.join("\n"))
|
||||
}
|
||||
@@ -180,38 +180,24 @@ fn settings_follow_the_thread_and_the_models() {
|
||||
let result = json!({"model": "big", "reasoningEffort": null, "approvalPolicy": "untrusted",
|
||||
"sandbox": {"type": "workspaceWrite"}});
|
||||
let mut s = Settings::of(&result, &models);
|
||||
assert_eq!(
|
||||
s,
|
||||
Settings {
|
||||
model: "big".into(),
|
||||
effort: Some("low".into()),
|
||||
mode: Mode::Ask,
|
||||
collaboration_mode: DEFAULT_COLLABORATION_MODE.into(),
|
||||
collaboration_mode_override: None,
|
||||
}
|
||||
);
|
||||
assert_eq!(s, Settings { model: "big".into(), effort: Some("low".into()), mode: Mode::Ask });
|
||||
|
||||
let options = config_options(&models, &s);
|
||||
let ids: Vec<&str> = options.as_array().unwrap().iter().map(|o| o["id"].as_str().unwrap()).collect();
|
||||
assert_eq!(ids, [MODEL, EFFORT, MODE, COLLABORATION_MODE]);
|
||||
assert_eq!(ids, [MODEL, EFFORT, MODE]);
|
||||
assert_eq!(options[0]["options"].as_array().unwrap().len(), 2, "hidden models are left out");
|
||||
assert_eq!(options[1]["category"], "thought_level");
|
||||
assert_eq!(options[1]["options"][1]["name"], "Extra high");
|
||||
assert_eq!(options[2]["currentValue"], "ask");
|
||||
assert_eq!(options[3]["currentValue"], "default");
|
||||
|
||||
// A model without efforts drops the option; its slug is what codex gets.
|
||||
s.set(&models, MODEL, "plain").unwrap();
|
||||
assert_eq!((s.effort.as_deref(), s.model_slug(&models).as_str()), (None, "plain-slug"));
|
||||
assert_eq!(config_options(&models, &s).as_array().unwrap().len(), 3);
|
||||
assert_eq!(config_options(&models, &s).as_array().unwrap().len(), 2);
|
||||
assert!(s.set(&models, EFFORT, "low").is_err());
|
||||
assert!(s.set(&models, MODEL, "nope").is_err());
|
||||
s.set(&models, MODE, "full-access").unwrap();
|
||||
assert_eq!((s.mode.approval_policy(), s.mode.sandbox_policy()), ("never", json!({"type": "dangerFullAccess"})));
|
||||
s.set(&models, COLLABORATION_MODE, PLAN_COLLABORATION_MODE).unwrap();
|
||||
assert_eq!(collaboration_mode(&s, &models)["mode"], PLAN_COLLABORATION_MODE);
|
||||
s.set(&models, COLLABORATION_MODE, DEFAULT_COLLABORATION_MODE).unwrap();
|
||||
assert_eq!(collaboration_mode(&s, &models)["mode"], DEFAULT_COLLABORATION_MODE);
|
||||
|
||||
// A model codex runs that it doesn't list is still offered.
|
||||
let s = Settings::of(&json!({"model": "custom", "sandbox": {"type": "readOnly"}}), &models);
|
||||
@@ -240,18 +226,6 @@ fn prompts_become_user_input() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compact_is_recognized_with_completion_whitespace_and_attachments() {
|
||||
// Completion leaves trailing whitespace and images can remain in the prompt. The first
|
||||
// text block still names the command; unknown slash-shaped text continues normally.
|
||||
assert_eq!(commands::parse(&text("/compact")).unwrap().command, BuiltinCommand::Compact);
|
||||
assert_eq!(commands::parse(&text(" /compact \n")).unwrap().command, BuiltinCommand::Compact);
|
||||
assert_eq!(commands::parse(&text("/compact now")).unwrap().rest, "now");
|
||||
let prompt = json!([{"type": "text", "text": "/compact"}, {"type": "image", "data": "AA=="}]);
|
||||
assert_eq!(commands::parse(&prompt).unwrap().command, BuiltinCommand::Compact);
|
||||
assert!(commands::parse(&text("x/compact")).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn commands_are_titled_by_what_they_do() {
|
||||
let cmd = |actions: Value| {
|
||||
@@ -473,96 +447,12 @@ fn history_replays_turns() {
|
||||
assert_eq!(updates[4]["status"], "completed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn viewed_generated_and_attached_images_carry_their_pixels() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let png = dir.path().join("shot.png");
|
||||
std::fs::write(&png, b"\x89PNG\r\n").unwrap();
|
||||
let png_path = png.to_str().unwrap();
|
||||
let encoded = "iVBORw0K";
|
||||
let view = json!({"id": "v", "type": "imageView", "path": png_path});
|
||||
assert!(tool_call(&view, false, None, None).unwrap().get("content").is_none());
|
||||
let image = &tool_call(&view, true, None, None).unwrap()["content"][0]["content"];
|
||||
assert_eq!((image["type"].as_str(), image["data"].as_str()), (Some("image"), Some(encoded)));
|
||||
let missing = json!({"id": "v", "type": "imageView", "path": dir.path().join("gone.png")});
|
||||
assert!(tool_call(&missing, true, None, None).unwrap().get("content").is_none());
|
||||
let inline = json!({"id": "g", "type": "imageGeneration", "status": "completed", "result": encoded});
|
||||
let image = &tool_call(&inline, true, None, None).unwrap()["content"][0]["content"];
|
||||
assert_eq!((image["mimeType"].as_str(), image["data"].as_str()), (Some("image/png"), Some(encoded)));
|
||||
let saved =
|
||||
json!({"id": "g", "type": "imageGeneration", "status": "completed", "fileId": "f", "savedPath": png_path});
|
||||
assert_eq!(tool_call(&saved, true, None, None).unwrap()["content"][0]["content"]["data"], encoded);
|
||||
|
||||
let thread = json!({"turns": [{"items": [{"type": "userMessage", "id": "u", "content": [
|
||||
{"type": "image", "url": "data:image/jpeg;base64,/9j/"},
|
||||
{"type": "image", "url": "https://example.com/a.png"},
|
||||
{"type": "localImage", "path": png_path},
|
||||
{"type": "localImage", "path": "/gone.png"}
|
||||
]}]}]});
|
||||
let contents: Vec<Value> = history(&thread, None).into_iter().map(|u| u["content"].clone()).collect();
|
||||
assert_eq!(contents[0], json!({"type": "image", "mimeType": "image/jpeg", "data": "/9j/"}));
|
||||
assert_eq!(contents[1]["type"], "resource_link");
|
||||
assert_eq!(contents[2], json!({"type": "image", "mimeType": "image/png", "data": encoded}));
|
||||
assert_eq!(contents[3], json!({"type": "text", "text": "/gone.png"}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn history_preserves_async_questions_with_stable_answer_ids() {
|
||||
let updates = history(
|
||||
&json!({"turns": [{"items": [{
|
||||
"type": "agentMessage", "id": "call-1", "text": "Which?",
|
||||
"questions": [{"title": "Which?", "options": ["One", "Two"]}, {"title": "Why?"}]
|
||||
}]}]}),
|
||||
None,
|
||||
);
|
||||
let asked = updates.iter().find(|u| u["sessionUpdate"] == "user_question").expect("question update");
|
||||
assert_eq!(asked["id"], "call-1");
|
||||
assert_eq!(asked["questions"][0]["answerKey"], r#"["request_user_input_async","call-1",0]"#);
|
||||
assert_eq!(asked["questions"][0]["options"][1]["label"], "Two");
|
||||
assert_eq!(asked["questions"][1]["options"], json!([]));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn completing_a_streamed_message_still_delivers_its_async_questions() {
|
||||
let shim = Arc::new(CodexShim {
|
||||
runtime: tokio::runtime::Handle::current(),
|
||||
codex: OnceLock::new(),
|
||||
client: OnceLock::new(),
|
||||
state: Mutex::default(),
|
||||
models: tokio::sync::Mutex::new(None),
|
||||
skills: tokio::sync::Mutex::new(()),
|
||||
});
|
||||
shim.state.lock().threads.insert("thread".into(), Thread::default());
|
||||
let client = Arc::new(Client::default());
|
||||
let peer = crate::native::serve(shim.clone(), client.clone());
|
||||
shim.text("thread", &json!({"itemId":"call-1","delta":"Which?"}), "agent_message_chunk", false);
|
||||
shim.item(
|
||||
"thread",
|
||||
&json!({"type":"agentMessage","id":"call-1","text":"Which?",
|
||||
"questions":[{"title":"Which?","options":["One","Two"]}]}),
|
||||
true,
|
||||
);
|
||||
tokio::time::timeout(Duration::from_secs(2), async {
|
||||
while client.of("thread").len() < 2 {
|
||||
tokio::time::sleep(Duration::from_millis(5)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(client.text("thread", "agent_message_chunk"), "Which?");
|
||||
assert!(client.of("thread").iter().any(|u| u["sessionUpdate"] == "user_question"));
|
||||
assert!(client.asked.lock().is_empty(), "an asynchronous question must not block on a permission response");
|
||||
peer.kill();
|
||||
shim.client.get().unwrap().kill();
|
||||
}
|
||||
|
||||
// ---- Transcripts ---------------------------------------------------------------------
|
||||
|
||||
/// The ACP client: records updates and answers permission requests in order.
|
||||
#[derive(Default)]
|
||||
struct Client {
|
||||
updates: Mutex<Vec<Value>>,
|
||||
warnings: Mutex<Vec<Value>>,
|
||||
asked: Mutex<Vec<Value>>,
|
||||
/// Option ids to choose; `None` (or none left) cancels.
|
||||
answers: Mutex<VecDeque<Option<&'static str>>>,
|
||||
@@ -572,8 +462,6 @@ impl Handler for Client {
|
||||
fn on_notification(&self, method: &str, params: Value) {
|
||||
if method == "session/update" {
|
||||
self.updates.lock().push(params);
|
||||
} else if method == "_openidea/warning" {
|
||||
self.warnings.lock().push(params);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -639,10 +527,6 @@ async fn questions_share_one_card_and_keep_their_ids() {
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
enum Scenario {
|
||||
AuthFailure,
|
||||
Command(&'static str),
|
||||
Compact,
|
||||
PlanThenPrompt,
|
||||
PlanToggleThenPrompt,
|
||||
Interrupt,
|
||||
Resume,
|
||||
Steer,
|
||||
@@ -657,10 +541,6 @@ impl Scenario {
|
||||
fn file(self) -> &'static str {
|
||||
match self {
|
||||
Scenario::AuthFailure => "auth_failure",
|
||||
Scenario::Command(_) => "simple",
|
||||
Scenario::Compact => "simple",
|
||||
Scenario::PlanThenPrompt => "simple",
|
||||
Scenario::PlanToggleThenPrompt => "simple",
|
||||
Scenario::Interrupt => "interrupt",
|
||||
Scenario::Resume => "resume",
|
||||
Scenario::Steer => "steer",
|
||||
@@ -718,21 +598,6 @@ async fn drive(scenario: Scenario, acp: &Peer, client: &Client, cwd: &str, threa
|
||||
Scenario::AuthFailure | Scenario::Simple | Scenario::UsageLimit | Scenario::Subagent => {
|
||||
out.push(("prompt", request(acp, "session/prompt", prompt("Reply with the single word: hi")).await));
|
||||
}
|
||||
Scenario::Compact => {
|
||||
out.push(("prompt", request(acp, "session/prompt", prompt("/compact")).await));
|
||||
}
|
||||
Scenario::Command(command) => {
|
||||
out.push(("prompt", request(acp, "session/prompt", prompt(command)).await));
|
||||
}
|
||||
Scenario::PlanThenPrompt => {
|
||||
out.push(("plan", request(acp, "session/prompt", prompt("/plan")).await));
|
||||
out.push(("prompt", request(acp, "session/prompt", prompt("Reply with the single word: hi")).await));
|
||||
}
|
||||
Scenario::PlanToggleThenPrompt => {
|
||||
out.push(("plan", request(acp, "session/prompt", prompt("/plan")).await));
|
||||
out.push(("default", request(acp, "session/prompt", prompt("/plan")).await));
|
||||
out.push(("prompt", request(acp, "session/prompt", prompt("Reply with the single word: hi")).await));
|
||||
}
|
||||
Scenario::Interrupt => {
|
||||
out.push(("mode", request(acp, "session/set_config_option", set(MODE, "read-only")).await));
|
||||
let running = {
|
||||
@@ -800,37 +665,6 @@ fn load(name: &str) -> Transcript {
|
||||
Transcript { meta, frames }
|
||||
}
|
||||
|
||||
/// The simple fixture through session setup. Local commands add only the app-server calls
|
||||
/// they need after it; turn commands keep the fixture's turn notifications.
|
||||
fn command_transcript(calls: &[(&'static str, Value)]) -> Transcript {
|
||||
let mut transcript = load(Scenario::Simple.file());
|
||||
let prompt = transcript
|
||||
.frames
|
||||
.iter()
|
||||
.position(|(out, frame)| *out && frame["method"] == "turn/start")
|
||||
.expect("the scenario starts a turn");
|
||||
transcript.frames.truncate(prompt);
|
||||
transcript.frames.push((true, json!({ "id": 4, "method": "skills/list" })));
|
||||
transcript.frames.push((false, json!({ "id": 4, "result": { "data": [] } })));
|
||||
for (index, (method, result)) in calls.iter().enumerate() {
|
||||
let id = 10 + index;
|
||||
transcript.frames.push((true, json!({ "id": id, "method": method })));
|
||||
transcript.frames.push((false, json!({ "id": id, "result": result })));
|
||||
}
|
||||
transcript
|
||||
}
|
||||
|
||||
fn turn_command_transcript(method: &str) -> Transcript {
|
||||
let mut transcript = load(Scenario::Simple.file());
|
||||
let start = transcript
|
||||
.frames
|
||||
.iter_mut()
|
||||
.find(|(out, frame)| *out && frame["method"] == "turn/start")
|
||||
.expect("the scenario starts a turn");
|
||||
start.1["method"] = json!(method);
|
||||
transcript
|
||||
}
|
||||
|
||||
/// Plays codex: waits for each frame the shim should send, sends what codex sent.
|
||||
/// Returns the frames the shim sent.
|
||||
async fn play<R: AsyncRead + Unpin, W: AsyncWrite + Unpin>(
|
||||
@@ -850,10 +684,10 @@ async fn play<R: AsyncRead + Unpin, W: AsyncWrite + Unpin>(
|
||||
.unwrap()
|
||||
.unwrap_or_else(|| panic!("the shim closed before {frame}"));
|
||||
let actual: Value = serde_json::from_str(&line).unwrap();
|
||||
// Older recordings predate config inspection, skill discovery and thread naming; play an
|
||||
// Older recordings predate skill discovery and thread naming; play an
|
||||
// unsupported server.
|
||||
let method = actual["method"].as_str().unwrap_or_default();
|
||||
if matches!(method, "config/read" | "skills/list" | "thread/sample") && frame["method"] != method {
|
||||
if matches!(method, "skills/list" | "thread/sample") && frame["method"] != method {
|
||||
let reply = json!({ "id": actual["id"], "error": { "code": -32601, "message": "unsupported" } });
|
||||
write.write_all(format!("{reply}\n").as_bytes()).await.unwrap();
|
||||
continue;
|
||||
@@ -926,149 +760,6 @@ fn session_of(results: &Results, label: &str) -> String {
|
||||
result(results, label).as_ref().unwrap()["sessionId"].as_str().unwrap().to_owned()
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn configuration_warnings_before_a_session_and_runtime_warnings_reach_the_client() {
|
||||
let mut transcript = load(Scenario::Simple.file());
|
||||
transcript.frames.insert(
|
||||
0,
|
||||
(
|
||||
false,
|
||||
json!({"method": "configWarning", "params": {
|
||||
"summary": "Project-local config is disabled until the project is trusted.",
|
||||
"details": "Update the project's trust setting.", "path": "/work/.codex/config.toml"
|
||||
}}),
|
||||
),
|
||||
);
|
||||
let at = transcript.frames.iter().position(|(out, f)| *out && f["method"] == "turn/start").unwrap();
|
||||
transcript
|
||||
.frames
|
||||
.insert(at, (false, json!({"method": "warning", "params": {"message": "MCP server unavailable"}})));
|
||||
let (results, client, frames, _, _codex) = replay_transcript(Scenario::Simple, transcript).await;
|
||||
assert!(result(&results, "new").is_ok());
|
||||
assert_eq!(
|
||||
*client.warnings.lock(),
|
||||
[
|
||||
json!({"message": "Project-local config is disabled until the project is trusted.\n\nUpdate the project's trust setting.\n\n/work/.codex/config.toml"}),
|
||||
json!({"message": "MCP server unavailable"}),
|
||||
]
|
||||
);
|
||||
assert!(sent(&frames, "config/value/write").is_empty());
|
||||
assert!(sent(&frames, "config/batchWrite").is_empty());
|
||||
}
|
||||
|
||||
struct TrustServer {
|
||||
cwd: String,
|
||||
disabled: bool,
|
||||
other_project: bool,
|
||||
write_error: bool,
|
||||
overridden: bool,
|
||||
calls: Mutex<Vec<(String, Value)>>,
|
||||
}
|
||||
|
||||
impl Handler for TrustServer {
|
||||
fn on_notification(&self, _: &str, _: Value) {}
|
||||
|
||||
fn on_request(&self, method: &str, params: Value) -> Result<Value, (i64, String)> {
|
||||
self.calls.lock().push((method.to_owned(), params));
|
||||
match method {
|
||||
"initialize" => Ok(json!({})),
|
||||
"model/list" => Ok(json!({"data": []})),
|
||||
"config/read" => {
|
||||
let cwd =
|
||||
if self.other_project { Path::new(&self.cwd).join("other") } else { PathBuf::from(&self.cwd) };
|
||||
Ok(json!({"layers": [
|
||||
{"name": {"type": "user", "profile": null}, "version": "original"},
|
||||
{"name": {"type": "project", "dotCodexFolder": cwd.join(".codex")},
|
||||
"disabledReason": self.disabled.then_some("Project config is disabled until trusted.")}
|
||||
]}))
|
||||
}
|
||||
"config/value/write" if self.write_error => Err((-32001, "Config changed concurrently".into())),
|
||||
"config/value/write" => Ok(json!({"status": if self.overridden {"okOverridden"} else {"ok"}})),
|
||||
"thread/start" | "thread/resume" | "thread/fork" => {
|
||||
Ok(json!({"thread": {"id": "s", "turns": []}, "cwd": self.cwd}))
|
||||
}
|
||||
"skills/list" => Ok(json!({"data": []})),
|
||||
_ => Err((codes::METHOD_NOT_FOUND, method.to_owned())),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn project_trust_is_confirmed_before_new_resumed_and_forked_sessions() {
|
||||
for method in ["session/new", "session/load", "session/fork"] {
|
||||
for (answer, disabled, other_project, write_error, overridden) in [
|
||||
(Some("codex-trust-project"), true, false, false, false),
|
||||
(Some("codex-keep-untrusted"), true, false, false, false),
|
||||
(None, true, false, false, false),
|
||||
(Some("codex-trust-project"), false, false, false, false),
|
||||
(Some("codex-trust-project"), true, true, false, false),
|
||||
(Some("codex-trust-project"), true, false, true, false),
|
||||
(Some("codex-trust-project"), true, false, false, true),
|
||||
] {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let cwd = tmp.path().join("project.with.dots-项目").to_string_lossy().into_owned();
|
||||
let server = Arc::new(TrustServer {
|
||||
cwd: cwd.clone(),
|
||||
disabled,
|
||||
other_project,
|
||||
write_error,
|
||||
overridden,
|
||||
calls: Mutex::default(),
|
||||
});
|
||||
let client = Arc::new(Client::default());
|
||||
client.answers.lock().push_back(answer);
|
||||
let (ours, theirs) = tokio::io::duplex(1 << 16);
|
||||
let (read, write) = tokio::io::split(theirs);
|
||||
let native = Peer::connect_framed(read, write, server.clone(), Framing::Lines);
|
||||
let acp = attach(client.clone(), |events| {
|
||||
let (read, write) = tokio::io::split(ours);
|
||||
Ok(Peer::connect_framed(read, write, events, Framing::Lines))
|
||||
})
|
||||
.unwrap();
|
||||
request(&acp, "initialize", json!({})).await.unwrap();
|
||||
let params = json!({"cwd": cwd, "sessionId": "source", "mcpServers": []});
|
||||
request(&acp, method, params.clone()).await.unwrap();
|
||||
// The same connection must not ask repeatedly after a decline.
|
||||
request(&acp, method, params).await.unwrap();
|
||||
let approved = answer == Some("codex-trust-project") && disabled && !other_project;
|
||||
{
|
||||
let asked = client.asked.lock();
|
||||
assert_eq!(asked.len(), usize::from(disabled && !other_project));
|
||||
if let Some(permission) = asked.first() {
|
||||
assert!(permission["toolCall"]["title"].as_str().unwrap().contains(&cwd));
|
||||
assert_eq!(
|
||||
permission["toolCall"]["kind"], "edit",
|
||||
"side conversations must deny persistent trust changes"
|
||||
);
|
||||
assert_eq!(
|
||||
permission["options"][0]["kind"], "allow_always",
|
||||
"task bypass must not grant permanent trust"
|
||||
);
|
||||
}
|
||||
let calls = server.calls.lock();
|
||||
let writes: Vec<_> = calls.iter().filter(|(m, _)| m == "config/value/write").collect();
|
||||
assert_eq!(writes.len(), usize::from(approved));
|
||||
if let Some((_, write)) = writes.first() {
|
||||
assert_eq!(
|
||||
*write,
|
||||
json!({"keyPath": format!("projects.{}.trust_level", json!(cwd)), "value": "trusted", "mergeStrategy": "replace", "expectedVersion": "original"})
|
||||
);
|
||||
let written = calls.iter().position(|(m, _)| m == "config/value/write").unwrap();
|
||||
let started = calls.iter().position(|(m, _)| m.starts_with("thread/")).unwrap();
|
||||
assert!(written < started, "the session must load config after the write");
|
||||
}
|
||||
}
|
||||
// Drain notifications sent before the last response.
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
if approved && (write_error || overridden) {
|
||||
assert!(!client.warnings.lock().is_empty());
|
||||
}
|
||||
acp.kill();
|
||||
native.kill();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn auth_failure_names_auth() {
|
||||
let (results, _client, frames, _) = replay(Scenario::AuthFailure).await;
|
||||
@@ -1080,7 +771,7 @@ async fn auth_failure_names_auth() {
|
||||
let categories: Vec<&str> =
|
||||
new["configOptions"].as_array().unwrap().iter().map(|o| o["category"].as_str().unwrap()).collect();
|
||||
// The model the user's codex config names; codex doesn't list it, so its efforts are unknown.
|
||||
assert_eq!(categories, ["model", "mode", "collaboration_mode"]);
|
||||
assert_eq!(categories, ["model", "mode"]);
|
||||
let model = new["configOptions"][0]["currentValue"].as_str().unwrap();
|
||||
assert_eq!(model, "gpt-6-luna");
|
||||
assert!(new["configOptions"][0]["options"].as_array().unwrap().iter().any(|o| o["value"] == model));
|
||||
@@ -1320,7 +1011,6 @@ async fn settings_apply_to_the_next_turn() {
|
||||
(starts[0]["params"]["model"].as_str(), starts[0]["params"]["effort"].as_str()),
|
||||
(Some("gpt-5.6-luna"), Some("medium"))
|
||||
);
|
||||
assert!(starts[0]["params"].get("collaborationMode").is_none());
|
||||
assert_eq!(
|
||||
(starts[1]["params"]["model"].as_str(), starts[1]["params"]["effort"].as_str()),
|
||||
(Some("gpt-5.5"), Some("high"))
|
||||
@@ -1329,192 +1019,6 @@ async fn settings_apply_to_the_next_turn() {
|
||||
assert_eq!(client.text(&session, "agent_message_chunk"), "oneOn it.\n\ntwo");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn compact_is_started_through_its_app_server_method() {
|
||||
// Play the ordinary-turn fixture with the request swapped: the notifications are the
|
||||
// same, while this pins the user-visible command to `thread/compact/start`, not a prompt.
|
||||
let mut transcript = load(Scenario::Simple.file());
|
||||
let start = transcript
|
||||
.frames
|
||||
.iter_mut()
|
||||
.find(|(out, frame)| *out && frame["method"] == "turn/start")
|
||||
.expect("the scenario starts a turn");
|
||||
start.1["method"] = json!("thread/compact/start");
|
||||
let (results, _client, frames, _meta, _codex) = replay_transcript(Scenario::Compact, transcript).await;
|
||||
|
||||
assert_eq!(result(&results, "prompt").as_ref().unwrap(), &json!({"stopReason": "end_turn"}));
|
||||
assert!(sent(&frames, "turn/start").is_empty());
|
||||
assert_eq!(sent(&frames, "thread/compact/start").len(), 1);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn review_commands_start_the_matching_review_target() {
|
||||
for (prompt, target) in [
|
||||
("/review", json!({ "type": "uncommittedChanges" })),
|
||||
("/review focus on errors", json!({ "type": "custom", "instructions": "focus on errors" })),
|
||||
("/review-branch origin/main", json!({ "type": "baseBranch", "branch": "origin/main" })),
|
||||
("/review-commit abc123", json!({ "type": "commit", "sha": "abc123", "title": null })),
|
||||
] {
|
||||
let (results, _client, frames, _meta, _codex) =
|
||||
replay_transcript(Scenario::Command(prompt), turn_command_transcript("review/start")).await;
|
||||
assert_eq!(result(&results, "prompt").as_ref().unwrap(), &json!({ "stopReason": "end_turn" }), "{prompt}");
|
||||
assert!(sent(&frames, "turn/start").is_empty(), "{prompt}");
|
||||
assert_eq!(sent(&frames, "review/start")[0]["params"]["target"], target, "{prompt}");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn plan_toggles_collaboration_mode_and_updates_the_composer() {
|
||||
let (results, client, _frames, _meta, _codex) =
|
||||
replay_transcript(Scenario::Command("/plan"), command_transcript(&[])).await;
|
||||
let session = session_of(&results, "new");
|
||||
assert_eq!(result(&results, "prompt").as_ref().unwrap(), &json!({ "stopReason": "end_turn" }));
|
||||
let update = client.of(&session).into_iter().find(|u| u["sessionUpdate"] == "config_option_update").unwrap();
|
||||
let plan =
|
||||
update["configOptions"].as_array().unwrap().iter().find(|o| o["category"] == "collaboration_mode").unwrap();
|
||||
assert_eq!(plan["currentValue"], "plan");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn plan_applies_to_the_next_normal_turn() {
|
||||
let (results, _client, frames, _meta, _codex) =
|
||||
replay_transcript(Scenario::PlanThenPrompt, load(Scenario::Simple.file())).await;
|
||||
assert_eq!(result(&results, "plan").as_ref().unwrap(), &json!({ "stopReason": "end_turn" }));
|
||||
assert_eq!(result(&results, "prompt").as_ref().unwrap(), &json!({ "stopReason": "end_turn" }));
|
||||
let start = sent(&frames, "turn/start")[0];
|
||||
assert_eq!(start["params"]["collaborationMode"]["mode"], "plan");
|
||||
assert_eq!(start["params"]["collaborationMode"]["settings"]["model"], "gpt-5.6-luna");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn toggling_plan_off_sends_an_explicit_default_once() {
|
||||
let (results, _client, frames, _meta, _codex) =
|
||||
replay_transcript(Scenario::PlanToggleThenPrompt, load(Scenario::Simple.file())).await;
|
||||
assert_eq!(result(&results, "default").as_ref().unwrap(), &json!({ "stopReason": "end_turn" }));
|
||||
let start = sent(&frames, "turn/start")[0];
|
||||
assert_eq!(start["params"]["collaborationMode"]["mode"], "default");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn informational_commands_report_skills_mcp_and_status() {
|
||||
let skills = json!({ "data": [{ "skills": [
|
||||
{ "name": "review", "enabled": true, "description": "Review changes" },
|
||||
{ "name": "hidden", "enabled": false, "description": "Hidden" }
|
||||
] }] });
|
||||
let servers = json!({ "data": [
|
||||
{ "name": "github", "runtimeStatus": "connected", "authStatus": "oAuth", "tools": { "search": {} } },
|
||||
{ "name": "docs", "runtimeStatus": "failed", "authStatus": "unknown", "tools": {} }
|
||||
] });
|
||||
for (prompt, method, response, expected) in [
|
||||
("/skills", "skills/list", skills, "Available skills:\n- review: Review changes"),
|
||||
(
|
||||
"/mcp",
|
||||
"mcpServerStatus/list",
|
||||
servers,
|
||||
"MCP servers:\n- github: connected, 1 tools\n- docs: failed, 0 tools",
|
||||
),
|
||||
("/status", "", Value::Null, "**Session:**"),
|
||||
] {
|
||||
let calls: &[(&str, Value)] = if method.is_empty() { &[] } else { &[(method, response)] };
|
||||
let calls: Vec<(&'static str, Value)> = calls
|
||||
.iter()
|
||||
.map(|(method, response)| {
|
||||
let method = match *method {
|
||||
"skills/list" => "skills/list",
|
||||
"mcpServerStatus/list" => "mcpServerStatus/list",
|
||||
other => panic!("unexpected method {other}"),
|
||||
};
|
||||
(method, response.clone())
|
||||
})
|
||||
.collect();
|
||||
let (results, client, _frames, _meta, _codex) =
|
||||
replay_transcript(Scenario::Command(prompt), command_transcript(&calls)).await;
|
||||
let session = session_of(&results, "new");
|
||||
assert_eq!(result(&results, "prompt").as_ref().unwrap(), &json!({ "stopReason": "end_turn" }));
|
||||
assert!(client.text(&session, "agent_message_chunk").contains(expected), "{prompt}");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn rename_and_logout_use_their_app_server_actions() {
|
||||
let (results, client, frames, _meta, _codex) = replay_transcript(
|
||||
Scenario::Command("/rename Better name"),
|
||||
command_transcript(&[("thread/name/set", json!({}))]),
|
||||
)
|
||||
.await;
|
||||
let session = session_of(&results, "new");
|
||||
assert_eq!(sent(&frames, "thread/name/set")[0]["params"], json!({ "threadId": session, "name": "Better name" }));
|
||||
let info = client.of(&session).into_iter().find(|u| u["sessionUpdate"] == "session_info_update").unwrap();
|
||||
assert_eq!((info["title"].as_str(), info["userNamed"].as_bool()), (Some("Better name"), Some(true)));
|
||||
|
||||
let (results, client, frames, _meta, _codex) =
|
||||
replay_transcript(Scenario::Command("/logout"), command_transcript(&[("account/logout", json!({}))])).await;
|
||||
let session = session_of(&results, "new");
|
||||
assert_eq!(sent(&frames, "account/logout").len(), 1);
|
||||
assert_eq!(client.text(&session, "agent_message_chunk"), "Logged out from Codex account.");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn goal_commands_set_pause_resume_and_clear_through_app_server() {
|
||||
for (prompt, method, params, result) in [
|
||||
(
|
||||
"/goal fix the failing tests",
|
||||
"thread/goal/set",
|
||||
json!({ "threadId": "s", "objective": "fix the failing tests", "status": "active", "origin": "user" }),
|
||||
json!({ "goal": { "status": "active" } }),
|
||||
),
|
||||
(
|
||||
"/goal pause",
|
||||
"thread/goal/set",
|
||||
json!({ "threadId": "s", "status": "paused", "origin": "user" }),
|
||||
json!({ "goal": { "status": "paused" } }),
|
||||
),
|
||||
(
|
||||
"/goal resume",
|
||||
"thread/goal/set",
|
||||
json!({ "threadId": "s", "status": "active", "origin": "user" }),
|
||||
json!({ "goal": { "status": "active" } }),
|
||||
),
|
||||
("/goal clear", "thread/goal/clear", json!({ "threadId": "s" }), json!({ "cleared": true })),
|
||||
] {
|
||||
let (results, _client, frames, _meta, _codex) =
|
||||
replay_transcript(Scenario::Command(prompt), command_transcript(&[(method, result)])).await;
|
||||
let session = session_of(&results, "new");
|
||||
let sent = sent(&frames, method);
|
||||
assert_eq!(sent.len(), 1, "{prompt}");
|
||||
let mut expected = params;
|
||||
expected["threadId"] = json!(session);
|
||||
assert_eq!(sent[0]["params"], expected, "{prompt}");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn missing_review_arguments_print_usage_without_starting_a_turn() {
|
||||
for prompt in ["/review-branch", "/review-commit", "/rename", "/goal"] {
|
||||
let (results, client, frames, _meta, _codex) =
|
||||
replay_transcript(Scenario::Command(prompt), command_transcript(&[])).await;
|
||||
let session = session_of(&results, "new");
|
||||
assert_eq!(result(&results, "prompt").as_ref().unwrap(), &json!({ "stopReason": "end_turn" }));
|
||||
assert!(sent(&frames, "turn/start").is_empty());
|
||||
assert!(client.text(&session, "agent_message_chunk").starts_with("Command \""), "{prompt}");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn mcp_reconnect_reloads_before_reporting_status() {
|
||||
let servers =
|
||||
json!({ "data": [{ "name": "github", "runtimeStatus": "connected", "authStatus": "oAuth", "tools": {} }] });
|
||||
let (results, client, frames, _meta, _codex) = replay_transcript(
|
||||
Scenario::Command("/mcp reconnect"),
|
||||
command_transcript(&[("config/mcpServer/reload", json!({})), ("mcpServerStatus/list", servers)]),
|
||||
)
|
||||
.await;
|
||||
let session = session_of(&results, "new");
|
||||
assert_eq!(sent(&frames, "config/mcpServer/reload").len(), 1);
|
||||
assert_eq!(sent(&frames, "mcpServerStatus/list").len(), 1);
|
||||
assert!(client.text(&session, "agent_message_chunk").contains("github: connected"));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn approvals_are_asked_and_answered() {
|
||||
let (results, client, frames, _) = replay(Scenario::Approvals).await;
|
||||
@@ -1754,17 +1258,6 @@ fn session_mcp_servers_become_thread_configuration() {
|
||||
json!({"mcp_servers":{"OpenIDEA":{"command":"/app/openidea","args":["--mcp-stdio","--project","/project"],"env":{"K":"V"}}}})
|
||||
)
|
||||
);
|
||||
let external = std::collections::BTreeSet::from(["linear".to_owned()]);
|
||||
assert_eq!(
|
||||
super::translate::mcp_config_with_external(
|
||||
&json!({
|
||||
"mcpServers": [],
|
||||
"_meta": { "openidea": { "mcpServersOff": ["linear", "not-in-codex"] } }
|
||||
}),
|
||||
&external,
|
||||
),
|
||||
Some(json!({ "mcp_servers": { "linear": { "enabled": false } } }))
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
@@ -1880,14 +1373,3 @@ fn skills_become_commands_with_their_invocation_names() {
|
||||
assert!(skill_commands(&json!({"data": []})).unwrap()["availableCommands"].as_array().unwrap().is_empty());
|
||||
assert!(skill_commands(&json!({})).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn workspace_roots_join_the_thread_roots() {
|
||||
let params = json!({ "cwd": "/w/api", "mcpServers": [], "additionalDirectories": ["/w/web"] });
|
||||
let mut request = json!({});
|
||||
apply_thread_config(¶ms, &mut request);
|
||||
assert_eq!(request["runtimeWorkspaceRoots"], json!(["/w/api", "/w/web"]));
|
||||
let mut request = json!({});
|
||||
apply_thread_config(&json!({ "cwd": "/w/api", "mcpServers": [] }), &mut request);
|
||||
assert!(request.get("runtimeWorkspaceRoots").is_none());
|
||||
}
|
||||
@@ -138,12 +138,6 @@ pub(super) struct Settings {
|
||||
pub model: String,
|
||||
pub effort: Option<String>,
|
||||
pub mode: Mode,
|
||||
/// Codex's Default/Plan collaboration mode. It is sent with each turn because it is
|
||||
/// part of the turn contract rather than the sandbox permission mode above.
|
||||
pub collaboration_mode: String,
|
||||
/// A mode just chosen by the user, sent once even when it is Default so a resumed Plan
|
||||
/// thread is explicitly reset. Subsequent default turns can omit the field again.
|
||||
pub collaboration_mode_override: Option<String>,
|
||||
}
|
||||
|
||||
impl Settings {
|
||||
@@ -162,12 +156,6 @@ impl Settings {
|
||||
result.get("approvalPolicy").unwrap_or(&Value::Null),
|
||||
result.get("sandbox").unwrap_or(&Value::Null),
|
||||
),
|
||||
collaboration_mode: result
|
||||
.pointer("/collaborationMode/mode")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or(DEFAULT_COLLABORATION_MODE)
|
||||
.to_owned(),
|
||||
collaboration_mode_override: None,
|
||||
};
|
||||
s.fit_effort(models);
|
||||
s
|
||||
@@ -206,13 +194,6 @@ impl Settings {
|
||||
self.effort = Some(value.to_owned());
|
||||
}
|
||||
MODE => self.mode = Mode::parse(value).ok_or_else(|| format!("unknown mode {value}"))?,
|
||||
COLLABORATION_MODE => {
|
||||
if !matches!(value, DEFAULT_COLLABORATION_MODE | PLAN_COLLABORATION_MODE) {
|
||||
return Err(format!("unknown collaboration mode {value}"));
|
||||
}
|
||||
self.collaboration_mode = value.to_owned();
|
||||
self.collaboration_mode_override = Some(value.to_owned());
|
||||
}
|
||||
_ => return Err(format!("unknown setting {option}")),
|
||||
}
|
||||
Ok(())
|
||||
@@ -222,9 +203,6 @@ impl Settings {
|
||||
pub(super) const MODEL: &str = "model";
|
||||
pub(super) const EFFORT: &str = "reasoning_effort";
|
||||
pub(super) const MODE: &str = "mode";
|
||||
pub(super) const COLLABORATION_MODE: &str = "collaboration_mode";
|
||||
pub(super) const DEFAULT_COLLABORATION_MODE: &str = "default";
|
||||
pub(super) const PLAN_COLLABORATION_MODE: &str = "plan";
|
||||
|
||||
/// ACP `configOptions`: model, reasoning effort (for models that have it) and mode.
|
||||
pub(super) fn config_options(models: &[ModelInfo], s: &Settings) -> Value {
|
||||
@@ -257,32 +235,9 @@ pub(super) fn config_options(models: &[ModelInfo], s: &Settings) -> Value {
|
||||
"id": MODE, "name": "Mode", "category": "mode", "type": "select", "currentValue": s.mode.id(),
|
||||
"options": Mode::ALL.iter().map(|m| select_value(m.id(), m.name(), Some(m.description()))).collect::<Vec<_>>(),
|
||||
}));
|
||||
out.push(json!({
|
||||
"id": COLLABORATION_MODE,
|
||||
"name": "Collaboration mode",
|
||||
"category": "collaboration_mode",
|
||||
"type": "select",
|
||||
"currentValue": s.collaboration_mode,
|
||||
"options": [
|
||||
select_value(DEFAULT_COLLABORATION_MODE, "Default", Some("Execute changes directly")),
|
||||
select_value(PLAN_COLLABORATION_MODE, "Plan", Some("Plan before making changes")),
|
||||
],
|
||||
}));
|
||||
Value::Array(out)
|
||||
}
|
||||
|
||||
/// `turn/start.collaborationMode`: the preset plus the selected model settings.
|
||||
pub(super) fn collaboration_mode(settings: &Settings, models: &[ModelInfo]) -> Value {
|
||||
json!({
|
||||
"mode": settings.collaboration_mode_override.as_deref().unwrap_or(&settings.collaboration_mode),
|
||||
"settings": {
|
||||
"model": settings.model_slug(models),
|
||||
"reasoning_effort": settings.effort,
|
||||
"developer_instructions": null,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
fn select_value(value: &str, name: &str, description: Option<&str>) -> Value {
|
||||
let mut v = json!({ "value": value, "name": name });
|
||||
if let Some(d) = description {
|
||||
@@ -348,18 +303,36 @@ pub(super) fn user_input(prompt: &Value) -> Vec<Value> {
|
||||
}
|
||||
"resource" => {
|
||||
let r = b.get("resource")?;
|
||||
let path = crate::images::uri_path(r.get("uri").and_then(Value::as_str).unwrap_or_default());
|
||||
let path = uri_path(r.get("uri").and_then(Value::as_str).unwrap_or_default());
|
||||
let text = r.get("text").and_then(Value::as_str)?;
|
||||
Some(json!({ "type": "text", "text": format!("<file path=\"{path}\">\n{text}\n</file>") }))
|
||||
}
|
||||
"resource_link" => {
|
||||
Some(json!({ "type": "text", "text": crate::images::uri_path(b.get("uri")?.as_str()?) }))
|
||||
}
|
||||
"resource_link" => Some(json!({ "type": "text", "text": uri_path(b.get("uri")?.as_str()?) })),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The path of a `file://` URI (percent-decoded); other URIs as they are.
|
||||
fn uri_path(uri: &str) -> String {
|
||||
let Some(rest) = uri.strip_prefix("file://") else { return uri.to_owned() };
|
||||
let bytes = rest.as_bytes();
|
||||
let mut out = Vec::with_capacity(bytes.len());
|
||||
let mut i = 0;
|
||||
while i < bytes.len() {
|
||||
if bytes[i] == b'%'
|
||||
&& let Some(b) = rest.get(i + 1..i + 3).and_then(|h| u8::from_str_radix(h, 16).ok())
|
||||
{
|
||||
out.push(b);
|
||||
i += 3;
|
||||
} else {
|
||||
out.push(bytes[i]);
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
String::from_utf8_lossy(&out).into_owned()
|
||||
}
|
||||
|
||||
/// A `session/update` notification's `update` for content.
|
||||
pub(super) fn chunk(kind: &str, text: &str) -> Value {
|
||||
json!({ "sessionUpdate": kind, "content": { "type": "text", "text": text } })
|
||||
@@ -449,9 +422,6 @@ pub(super) fn tool_call(item: &Value, done: bool, cwd: Option<&str>, output: Opt
|
||||
"imageView" => {
|
||||
let path = item.get("path").and_then(Value::as_str).unwrap_or_default();
|
||||
call.insert("locations".into(), json!([{ "path": path }]));
|
||||
if done && let Some(image) = crate::images::from_file(std::path::Path::new(path)) {
|
||||
call.insert("content".into(), json!([image_content(&image)]));
|
||||
}
|
||||
(format!("View {}", display_path(path, cwd)), "read")
|
||||
}
|
||||
"collabAgentToolCall" => {
|
||||
@@ -467,12 +437,7 @@ pub(super) fn tool_call(item: &Value, done: bool, cwd: Option<&str>, output: Opt
|
||||
}
|
||||
"contextCompaction" => ("Compact the conversation".to_owned(), "other"),
|
||||
"sleep" => ("Wait".to_owned(), "other"),
|
||||
"imageGeneration" => {
|
||||
if done && let Some(image) = generated_image(item) {
|
||||
call.insert("content".into(), json!([image_content(&image)]));
|
||||
}
|
||||
("Generate an image".to_owned(), "other")
|
||||
}
|
||||
"imageGeneration" => ("Generate an image".to_owned(), "other"),
|
||||
_ => return None,
|
||||
};
|
||||
call.insert("sessionUpdate".into(), json!(if done { "tool_call_update" } else { "tool_call" }));
|
||||
@@ -483,19 +448,6 @@ pub(super) fn tool_call(item: &Value, done: bool, cwd: Option<&str>, output: Opt
|
||||
Some(Value::Object(call))
|
||||
}
|
||||
|
||||
fn image_content(image: &crate::model::AgentImage) -> Value {
|
||||
json!({ "type": "content", "content": crate::images::content(image) })
|
||||
}
|
||||
|
||||
/// A generated image: inline (base64 PNG) or, when codex saved it, the file.
|
||||
fn generated_image(item: &Value) -> Option<crate::model::AgentImage> {
|
||||
if let Some(data) = item.get("result").and_then(Value::as_str).filter(|d| !d.is_empty()) {
|
||||
let image = crate::model::AgentImage { mime_type: "image/png".into(), data: data.into(), name: None };
|
||||
return Some(crate::model::AgentImage { mime_type: image.media_type().into(), ..image });
|
||||
}
|
||||
crate::images::from_file(std::path::Path::new(item.get("savedPath")?.as_str()?))
|
||||
}
|
||||
|
||||
/// The output of a running command, as a `tool_call_update`.
|
||||
pub(super) fn command_output(id: &str, output: &str) -> Value {
|
||||
json!({ "sessionUpdate": "tool_call_update", "toolCallId": id, "content": [text_content(&tail(output))] })
|
||||
@@ -859,23 +811,9 @@ pub(super) fn history(thread: &Value, cwd: Option<&str>) -> Vec<Value> {
|
||||
"user_message_chunk",
|
||||
c.get("text").and_then(Value::as_str).unwrap_or_default(),
|
||||
)),
|
||||
Some("image") => {
|
||||
let url = c.get("url").and_then(Value::as_str).unwrap_or_default();
|
||||
let content = crate::images::from_uri(url).map_or_else(
|
||||
|| json!({ "type": "resource_link", "uri": url, "name": "image" }),
|
||||
|image| crate::images::content(&image),
|
||||
);
|
||||
out.push(json!({ "sessionUpdate": "user_message_chunk", "content": content }));
|
||||
}
|
||||
Some("localImage") => {
|
||||
let path = c.get("path").and_then(Value::as_str).unwrap_or_default();
|
||||
out.push(match crate::images::from_file(std::path::Path::new(path)) {
|
||||
Some(image) => json!({ "sessionUpdate": "user_message_chunk",
|
||||
"content": crate::images::content(&image) }),
|
||||
None => chunk("user_message_chunk", path),
|
||||
});
|
||||
}
|
||||
Some("mention" | "skill") => {
|
||||
Some("image") => out.push(json!({ "sessionUpdate": "user_message_chunk",
|
||||
"content": { "type": "resource_link", "uri": c.get("url"), "name": "image" } })),
|
||||
Some("localImage" | "mention" | "skill") => {
|
||||
let path = c.get("path").and_then(Value::as_str).unwrap_or_default();
|
||||
out.push(chunk("user_message_chunk", path));
|
||||
}
|
||||
@@ -888,7 +826,6 @@ pub(super) fn history(thread: &Value, cwd: Option<&str>) -> Vec<Value> {
|
||||
if !text.is_empty() {
|
||||
out.push(chunk("agent_message_chunk", text));
|
||||
}
|
||||
out.extend(question_update(item));
|
||||
}
|
||||
Some("reasoning") => {
|
||||
let text = reasoning_text(item);
|
||||
@@ -908,36 +845,6 @@ pub(super) fn history(thread: &Value, cwd: Option<&str>) -> Vec<Value> {
|
||||
out
|
||||
}
|
||||
|
||||
/// Structured async questions accompany a completed message, even when its text streamed already.
|
||||
pub(super) fn question_update(item: &Value) -> Option<Value> {
|
||||
let id = item.get("id")?.as_str().filter(|id| !id.is_empty())?;
|
||||
let questions: Vec<Value> = item
|
||||
.get("questions")?
|
||||
.as_array()?
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(index, q)| {
|
||||
let title = q.get("title")?.as_str().filter(|title| !title.trim().is_empty())?;
|
||||
let options: Vec<Value> = q
|
||||
.get("options")
|
||||
.and_then(Value::as_array)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(Value::as_str)
|
||||
.filter(|label| !label.trim().is_empty())
|
||||
.map(|label| json!({ "label": label, "description": "" }))
|
||||
.collect();
|
||||
Some(json!({ "answerKey": json!(["request_user_input_async", id, index]).to_string(),
|
||||
"question": title, "header": "", "multiSelect": false, "options": options }))
|
||||
})
|
||||
.collect();
|
||||
if questions.is_empty() {
|
||||
return None;
|
||||
}
|
||||
Some(json!({ "sessionUpdate": "user_question", "id": id,
|
||||
"title": questions[0]["question"], "questions": questions }))
|
||||
}
|
||||
|
||||
/// A reasoning item's summary (or, without one, its raw text).
|
||||
pub(super) fn reasoning_text(item: &Value) -> String {
|
||||
let parts = |k: &str| -> Vec<String> {
|
||||
@@ -971,18 +878,8 @@ fn str_of(v: &Value, key: &str) -> Option<String> {
|
||||
|
||||
/// Session-scoped MCP configuration, carried in thread/start, resume and fork.
|
||||
pub(super) fn mcp_config(params: &Value) -> Option<Value> {
|
||||
let home = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE")).map(std::path::PathBuf::from);
|
||||
let cwd = params.get("cwd").and_then(Value::as_str).map_or_else(|| std::path::Path::new("."), std::path::Path::new);
|
||||
let external = crate::mcp::codex_external_server_names(home.as_deref(), cwd);
|
||||
mcp_config_with_external(params, &external)
|
||||
}
|
||||
|
||||
pub(super) fn mcp_config_with_external(
|
||||
params: &Value,
|
||||
external_names: &std::collections::BTreeSet<String>,
|
||||
) -> Option<Value> {
|
||||
let mut servers = serde_json::Map::new();
|
||||
for server in params.get("mcpServers").and_then(Value::as_array).into_iter().flatten() {
|
||||
for server in params.get("mcpServers")?.as_array()? {
|
||||
if server.get("type").and_then(Value::as_str).is_some_and(|t| t != "stdio") {
|
||||
continue;
|
||||
}
|
||||
@@ -1004,16 +901,5 @@ pub(super) fn mcp_config_with_external(
|
||||
"args":server.get("args").cloned().unwrap_or_else(||json!([])),"env":env}),
|
||||
);
|
||||
}
|
||||
for name in params
|
||||
.pointer("/_meta/openidea/mcpServersOff")
|
||||
.and_then(Value::as_array)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(Value::as_str)
|
||||
{
|
||||
if !servers.contains_key(name) && external_names.contains(name) {
|
||||
servers.insert(name.to_owned(), json!({ "enabled": false }));
|
||||
}
|
||||
}
|
||||
(!servers.is_empty()).then(|| json!({"mcp_servers":servers}))
|
||||
}
|
||||
@@ -1,93 +0,0 @@
|
||||
//! A project trusted by the IDE may still be untrusted by Codex. Ask before changing
|
||||
//! Codex's own decision; only its config API writes the current project's trust entry.
|
||||
|
||||
use super::*;
|
||||
|
||||
fn disabled_project<'a>(config: &'a Value, cwd: &str) -> Option<&'a Value> {
|
||||
let folder = Path::new(cwd).join(".codex");
|
||||
config.get("layers")?.as_array()?.iter().find(|layer| {
|
||||
layer.pointer("/name/type").and_then(Value::as_str) == Some("project")
|
||||
&& layer
|
||||
.pointer("/name/dotCodexFolder")
|
||||
.and_then(Value::as_str)
|
||||
.is_some_and(|path| Path::new(path) == folder)
|
||||
&& layer.get("disabledReason").and_then(Value::as_str).is_some_and(|reason| !reason.trim().is_empty())
|
||||
})
|
||||
}
|
||||
|
||||
impl CodexShim {
|
||||
pub(super) async fn prepare_project_trust(&self, params: &Value) {
|
||||
let Some(cwd) = params.get("cwd").and_then(Value::as_str) else { return };
|
||||
if !self.state.lock().trust_checked.insert(cwd.to_owned()) {
|
||||
return;
|
||||
}
|
||||
// Old app-servers may not expose config layers. Their warnings still reach the UI.
|
||||
let Ok(Ok(config)) = tokio::time::timeout(
|
||||
Duration::from_secs(5),
|
||||
self.call("config/read", json!({ "cwd": cwd, "includeLayers": true })),
|
||||
)
|
||||
.await
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let Some(layer) = disabled_project(&config, cwd) else { return };
|
||||
let Some(client) = self.client.get() else { return };
|
||||
let title = format!(
|
||||
"Trust project in Codex: {cwd}? This saves trust in your Codex user configuration and allows \
|
||||
this project's MCP servers, hooks and exec policies to load."
|
||||
);
|
||||
let permission = json!({
|
||||
"sessionId": params.get("sessionId").and_then(Value::as_str).unwrap_or_default(),
|
||||
"toolCall": {
|
||||
"toolCallId": format!("codex-project-trust:{cwd}"),
|
||||
"title": title, "kind": "edit",
|
||||
"rawInput": { "project": cwd },
|
||||
},
|
||||
"options": [
|
||||
// Permanent trust must never be auto-approved by the task's allow-once bypass.
|
||||
{ "optionId": "codex-trust-project", "name": "Trust Project in Codex", "kind": "allow_always" },
|
||||
{ "optionId": "codex-keep-untrusted", "name": "Keep Untrusted", "kind": "reject_once" },
|
||||
],
|
||||
});
|
||||
let answer: Result<Value, RpcError> = client.request("session/request_permission", permission, None).await;
|
||||
let approved = answer.as_ref().is_ok_and(|answer| {
|
||||
answer.pointer("/outcome/outcome").and_then(Value::as_str) == Some("selected")
|
||||
&& answer.pointer("/outcome/optionId").and_then(Value::as_str) == Some("codex-trust-project")
|
||||
});
|
||||
if !approved {
|
||||
if let Some(reason) = layer.get("disabledReason").and_then(Value::as_str) {
|
||||
self.warning(reason);
|
||||
}
|
||||
return;
|
||||
}
|
||||
// Quote the path as one key segment: dots and Windows backslashes are literal.
|
||||
let mut write = json!({
|
||||
"keyPath": format!("projects.{}.trust_level", json!(cwd)),
|
||||
"value": "trusted", "mergeStrategy": "replace",
|
||||
});
|
||||
if let Some(version) = config["layers"]
|
||||
.as_array()
|
||||
.and_then(|layers| {
|
||||
layers.iter().find(|layer| {
|
||||
layer.pointer("/name/type").and_then(Value::as_str) == Some("user")
|
||||
&& layer.pointer("/name/profile").is_none_or(Value::is_null)
|
||||
})
|
||||
})
|
||||
.and_then(|layer| layer.get("version"))
|
||||
.filter(|version| version.is_string())
|
||||
{
|
||||
write["expectedVersion"] = version.clone();
|
||||
}
|
||||
match self.call("config/value/write", write).await {
|
||||
Err(error) => self.warning(format!("Codex could not save trust for {cwd}: {}", error.message)),
|
||||
Ok(reply) if reply["status"] == "okOverridden" => {
|
||||
self.warning(format!(
|
||||
"Codex saved trust for {cwd}, but a higher-priority configuration overrides it. \
|
||||
Project configuration may remain disabled; check the Codex configuration or contact your administrator."
|
||||
));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
// start/resume/fork now load the updated config before creating the thread.
|
||||
}
|
||||
}
|
||||
@@ -19,7 +19,6 @@ mod translate;
|
||||
mod tests;
|
||||
|
||||
use super::Shim;
|
||||
use crate::BACKGROUND_TASKS_UPDATE;
|
||||
use crate::acp::AUTH_REQUIRED;
|
||||
use crate::provider::ProviderSpec;
|
||||
use ide_jsonrpc::{Framing, Handler, Peer, RpcError, codes};
|
||||
@@ -144,8 +143,7 @@ async fn discover_once(spec: ProviderSpec, cwd: PathBuf, strip_ambient: bool) ->
|
||||
move || spec.resolve_for_launch_with_copilot_env(&cwd, strip_ambient)
|
||||
})
|
||||
.await
|
||||
.map_err(|e| DiscoverError { message: e.to_string(), allow_acp_fallback: false })?
|
||||
.map_err(|e| DiscoverError { message: e, allow_acp_fallback: false })?;
|
||||
.map_err(|e| DiscoverError { message: e.to_string(), allow_acp_fallback: false })?;
|
||||
let cwd = dunce::canonicalize(&cwd).unwrap_or(cwd);
|
||||
let args = headless_args(&launch.args);
|
||||
let peer = Peer::spawn_framed(
|
||||
@@ -298,25 +296,6 @@ struct SessionEntry {
|
||||
prompt: Option<oneshot::Sender<TurnTerminal>>,
|
||||
early_cancel: Option<Instant>,
|
||||
temp_files: Vec<PathBuf>,
|
||||
/// Copilot's main agent loop is processing. It goes idle (`assistant.idle`) before the
|
||||
/// turn ends (`session.idle`) while background shells or agents it started still run.
|
||||
main_busy: bool,
|
||||
/// Counts `session.tasks.list` requests, so only the latest answer is reported.
|
||||
tasks_seq: u64,
|
||||
}
|
||||
|
||||
impl SessionEntry {
|
||||
fn new(settings: Settings) -> Self {
|
||||
Self {
|
||||
settings,
|
||||
translator: EventTranslator::default(),
|
||||
prompt: None,
|
||||
early_cancel: None,
|
||||
temp_files: Vec::new(),
|
||||
main_busy: false,
|
||||
tasks_seq: 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct CopilotEvents(Weak<CopilotShim>);
|
||||
@@ -372,24 +351,6 @@ fn error(code: i64, message: impl Into<String>) -> ResponseError {
|
||||
ResponseError { code, message: message.into(), data: None }
|
||||
}
|
||||
|
||||
/// Adds the session's staged skills to a `session.create`/`session.resume` request:
|
||||
/// `skillDirectories` (the farm's `copilot` tree) and `disabledSkills` (the off and
|
||||
/// slash-only ones; Copilot invokes skills with the model only, so a slash-only skill has
|
||||
/// no other switch here).
|
||||
fn apply_skills(params: &Value, req: &mut Value) {
|
||||
let skills = params.pointer("/_meta/openidea/skills");
|
||||
if let Some(dirs) = skills.and_then(|s| s.get("copilotSkillDirectories")).and_then(Value::as_array)
|
||||
&& !dirs.is_empty()
|
||||
{
|
||||
req["skillDirectories"] = json!(dirs.iter().filter_map(Value::as_str).collect::<Vec<_>>());
|
||||
}
|
||||
if let Some(disabled) = skills.and_then(|s| s.get("copilotDisabledSkills")).and_then(Value::as_array)
|
||||
&& !disabled.is_empty()
|
||||
{
|
||||
req["disabledSkills"] = json!(disabled.iter().filter_map(Value::as_str).collect::<Vec<_>>());
|
||||
}
|
||||
}
|
||||
|
||||
fn invalid(message: impl Into<String>) -> ResponseError {
|
||||
error(codes::INVALID_PARAMS, message)
|
||||
}
|
||||
@@ -450,7 +411,6 @@ impl CopilotShim {
|
||||
"session/set_config_option" => self.set_config(¶ms).await,
|
||||
"session/prompt" => self.prompt(¶ms, false).await,
|
||||
"_openidea/steer" => self.prompt(¶ms, true).await,
|
||||
"_openidea/stop_task" => self.stop_task(¶ms).await,
|
||||
"session/close" => self.close_session(¶ms).await,
|
||||
_ => Err(error(codes::METHOD_NOT_FOUND, format!("unsupported method {method}"))),
|
||||
}
|
||||
@@ -465,7 +425,7 @@ impl CopilotShim {
|
||||
"promptCapabilities": { "image": true, "audio": false, "embeddedContext": true },
|
||||
"mcpCapabilities": { "http": true, "sse": true, "stdio": true },
|
||||
"sessionCapabilities": { "close": {}, "list": {} },
|
||||
"_meta": { "openidea": { "steer": true, "backgroundTasks": true } },
|
||||
"_meta": { "openidea": { "steer": true } },
|
||||
},
|
||||
"agentInfo": {
|
||||
"name": "copilot",
|
||||
@@ -511,10 +471,6 @@ impl CopilotShim {
|
||||
if let Some(mcp) = translate::wire_mcp_servers(params.get("mcpServers")) {
|
||||
req["mcpServers"] = mcp;
|
||||
}
|
||||
if let Some(disabled) = translate::wire_disabled_mcp_servers(params) {
|
||||
req["disabledMcpServers"] = disabled;
|
||||
}
|
||||
apply_skills(params, &mut req);
|
||||
|
||||
let created = self.call("session.create", req).await?;
|
||||
let session_id = created
|
||||
@@ -533,7 +489,16 @@ impl CopilotShim {
|
||||
}
|
||||
|
||||
let options = models::config_options(&catalog, &settings);
|
||||
self.state.lock().sessions.insert(session_id.clone(), SessionEntry::new(settings));
|
||||
self.state.lock().sessions.insert(
|
||||
session_id.clone(),
|
||||
SessionEntry {
|
||||
settings,
|
||||
translator: EventTranslator::default(),
|
||||
prompt: None,
|
||||
early_cancel: None,
|
||||
temp_files: Vec::new(),
|
||||
},
|
||||
);
|
||||
self.publish_commands(&session_id, cwd);
|
||||
Ok(json!({
|
||||
"sessionId": session_id,
|
||||
@@ -562,10 +527,6 @@ impl CopilotShim {
|
||||
if let Some(mcp) = translate::wire_mcp_servers(params.get("mcpServers")) {
|
||||
req["mcpServers"] = mcp;
|
||||
}
|
||||
if let Some(disabled) = translate::wire_disabled_mcp_servers(params) {
|
||||
req["disabledMcpServers"] = disabled;
|
||||
}
|
||||
apply_skills(params, &mut req);
|
||||
|
||||
let resumed = self.call("session.resume", req).await?;
|
||||
if let Ok(current) = self.call("session.model.getCurrent", json!({ "sessionId": session_id })).await {
|
||||
@@ -581,7 +542,16 @@ impl CopilotShim {
|
||||
}
|
||||
let actual_id = resumed.get("sessionId").and_then(Value::as_str).unwrap_or(&session_id).to_owned();
|
||||
let options = models::config_options(&catalog, &settings);
|
||||
self.state.lock().sessions.insert(actual_id.clone(), SessionEntry::new(settings));
|
||||
self.state.lock().sessions.insert(
|
||||
actual_id.clone(),
|
||||
SessionEntry {
|
||||
settings,
|
||||
translator: EventTranslator::default(),
|
||||
prompt: None,
|
||||
early_cancel: None,
|
||||
temp_files: Vec::new(),
|
||||
},
|
||||
);
|
||||
self.publish_commands(&actual_id, cwd);
|
||||
Ok(json!({
|
||||
"sessionId": actual_id,
|
||||
@@ -683,11 +653,7 @@ impl CopilotShim {
|
||||
let (text, attachments, temp_files) = build_prompt_payload(&session_id, blocks);
|
||||
|
||||
if steer {
|
||||
let (is_running, main_busy) = {
|
||||
let st = self.state.lock();
|
||||
let entry = st.sessions.get(&session_id);
|
||||
(entry.is_some_and(|e| e.prompt.is_some()), entry.is_some_and(|e| e.main_busy))
|
||||
};
|
||||
let is_running = self.state.lock().sessions.get(&session_id).is_some_and(|e| e.prompt.is_some());
|
||||
if !is_running {
|
||||
cleanup_files(&temp_files);
|
||||
return Err(error(codes::INVALID_PARAMS, "no turn running to steer"));
|
||||
@@ -695,25 +661,14 @@ impl CopilotShim {
|
||||
let mut send_req = json!({
|
||||
"sessionId": session_id,
|
||||
"prompt": text,
|
||||
"mode": "immediate",
|
||||
});
|
||||
// Joins the running loop; once it went idle (only background work is left), a plain
|
||||
// send starts the loop again with this message.
|
||||
if main_busy {
|
||||
send_req["mode"] = json!("immediate");
|
||||
}
|
||||
if !attachments.is_empty() {
|
||||
send_req["attachments"] = Value::Array(attachments);
|
||||
}
|
||||
if !main_busy && let Some(entry) = self.state.lock().sessions.get_mut(&session_id) {
|
||||
// Stop must abort the run this send starts, even before `assistant.turn_start`.
|
||||
entry.main_busy = true;
|
||||
}
|
||||
let res = self.call("session.send", send_req).await;
|
||||
if let Some(entry) = self.state.lock().sessions.get_mut(&session_id) {
|
||||
entry.temp_files.extend(temp_files);
|
||||
if res.is_err() && !main_busy {
|
||||
entry.main_busy = false;
|
||||
}
|
||||
}
|
||||
res?;
|
||||
return Ok(json!({}));
|
||||
@@ -730,7 +685,6 @@ impl CopilotShim {
|
||||
let mode = entry.settings.mode.wire();
|
||||
if !early {
|
||||
entry.prompt = Some(done_tx);
|
||||
entry.main_busy = true;
|
||||
}
|
||||
(mode, early)
|
||||
};
|
||||
@@ -780,24 +734,19 @@ impl CopilotShim {
|
||||
}
|
||||
|
||||
fn cancel(&self, session_id: &str) {
|
||||
let (has_turn, ended) = {
|
||||
let has_turn = {
|
||||
let mut st = self.state.lock();
|
||||
match st.sessions.get_mut(session_id) {
|
||||
Some(entry) if entry.prompt.is_none() => {
|
||||
if let Some(entry) = st.sessions.get_mut(session_id) {
|
||||
if entry.prompt.is_none() {
|
||||
entry.early_cancel = Some(Instant::now());
|
||||
(false, None)
|
||||
false
|
||||
} else {
|
||||
true
|
||||
}
|
||||
// The agent is done with the turn and only its background work runs, which
|
||||
// `session.idle` waits for: the turn ends now and that work keeps running
|
||||
// (it shows as background tasks, stoppable one by one).
|
||||
Some(entry) if !entry.main_busy => (false, entry.prompt.take()),
|
||||
Some(_) => (true, None),
|
||||
None => (false, None),
|
||||
} else {
|
||||
false
|
||||
}
|
||||
};
|
||||
if let Some(tx) = ended {
|
||||
let _ = tx.send(TurnTerminal::Idle { aborted: true });
|
||||
}
|
||||
if has_turn {
|
||||
let peer = self.copilot().clone();
|
||||
let sid = session_id.to_owned();
|
||||
@@ -841,23 +790,10 @@ impl CopilotShim {
|
||||
return;
|
||||
}
|
||||
|
||||
let main_agent = event.get("agentId").and_then(Value::as_str).is_none_or(str::is_empty);
|
||||
let event_type = event.get("type").and_then(Value::as_str).unwrap_or_default();
|
||||
if main_agent && event_type == "session.background_tasks_changed" {
|
||||
self.refresh_background_tasks(session_id);
|
||||
}
|
||||
|
||||
let catalog_snapshot = self.catalog.try_lock().ok().and_then(|g| g.clone());
|
||||
let (updates, done) = {
|
||||
let mut st = self.state.lock();
|
||||
let Some(entry) = st.sessions.get_mut(session_id) else { return };
|
||||
if main_agent {
|
||||
match event_type {
|
||||
"assistant.turn_start" => entry.main_busy = true,
|
||||
"assistant.idle" | "session.idle" | "session.error" => entry.main_busy = false,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let fallback_limit =
|
||||
catalog_snapshot.as_deref().and_then(|models| entry.settings.active_context_tokens(models));
|
||||
let translated = entry.translator.translate(session_id, event, fallback_limit);
|
||||
@@ -867,44 +803,11 @@ impl CopilotShim {
|
||||
for (target_session, update) in updates {
|
||||
self.send_update(&target_session, update);
|
||||
}
|
||||
if main_agent && event_type == "session.idle" {
|
||||
// Nothing runs in the background any more.
|
||||
self.send_update(session_id, json!({ "sessionUpdate": BACKGROUND_TASKS_UPDATE, "tasks": [] }));
|
||||
}
|
||||
if let Some((tx, outcome)) = done {
|
||||
let _ = tx.send(outcome);
|
||||
}
|
||||
}
|
||||
|
||||
/// Reports the session's running background shells and agents (`session.tasks.list`).
|
||||
fn refresh_background_tasks(self: &Arc<Self>, session_id: &str) {
|
||||
let seq = {
|
||||
let mut st = self.state.lock();
|
||||
let Some(entry) = st.sessions.get_mut(session_id) else { return };
|
||||
entry.tasks_seq += 1;
|
||||
entry.tasks_seq
|
||||
};
|
||||
let shim = self.clone();
|
||||
let sid = session_id.to_owned();
|
||||
self.runtime.spawn(async move {
|
||||
let Ok(list) = shim.call("session.tasks.list", json!({ "sessionId": sid })).await else { return };
|
||||
let latest = shim.state.lock().sessions.get(&sid).is_some_and(|e| e.tasks_seq == seq);
|
||||
if latest {
|
||||
let tasks = translate::background_tasks(&list);
|
||||
shim.send_update(&sid, json!({ "sessionUpdate": BACKGROUND_TASKS_UPDATE, "tasks": tasks }));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Stops one background shell or agent (`session.tasks.cancel`).
|
||||
async fn stop_task(self: &Arc<Self>, params: &Value) -> Result<Value, ResponseError> {
|
||||
let session_id = str_param(params, "sessionId")?;
|
||||
let task_id = str_param(params, "taskId")?;
|
||||
self.call("session.tasks.cancel", json!({ "sessionId": session_id, "id": task_id })).await?;
|
||||
self.refresh_background_tasks(session_id);
|
||||
Ok(json!({}))
|
||||
}
|
||||
|
||||
fn handle_permission_event(self: &Arc<Self>, session_id: &str, event: &Value) {
|
||||
let data = &event["data"];
|
||||
if data.get("resolvedByHook").and_then(Value::as_bool) == Some(true) {
|
||||
|
||||
@@ -312,7 +312,7 @@ impl Settings {
|
||||
}
|
||||
|
||||
/// Parses `models.list` + optional `models.listTokenPriceUnits` into catalog entries,
|
||||
/// prepending `"auto"` when direct models are present or Copilot advertises an enabled Auto tier.
|
||||
/// prepending `"auto"` when not already in the list.
|
||||
pub(super) fn parse_catalog(list: &Value, price_units: Option<&Value>) -> Vec<ModelEntry> {
|
||||
let units = parse_price_units(price_units);
|
||||
let raw = list
|
||||
@@ -322,7 +322,7 @@ pub(super) fn parse_catalog(list: &Value, price_units: Option<&Value>) -> Vec<Mo
|
||||
.map(Vec::as_slice)
|
||||
.unwrap_or_default();
|
||||
let mut out = Vec::new();
|
||||
if !raw.iter().any(|m| str_of(m, "id") == Some("auto")) && (!raw.is_empty() || auto_model_available(list)) {
|
||||
if !raw.iter().any(|m| str_of(m, "id") == Some("auto")) && !raw.is_empty() {
|
||||
out.push(ModelEntry {
|
||||
id: "auto".into(),
|
||||
name: "Auto".into(),
|
||||
@@ -344,18 +344,6 @@ pub(super) fn parse_catalog(list: &Value, price_units: Option<&Value>) -> Vec<Mo
|
||||
out
|
||||
}
|
||||
|
||||
fn auto_model_available(list: &Value) -> bool {
|
||||
let Some(auto) = list.get("auto") else { return false };
|
||||
if auto.get("enabled").or_else(|| auto.pointer("/status/enabled")).and_then(Value::as_bool) == Some(false) {
|
||||
return false;
|
||||
}
|
||||
let Some(tiers) = auto.get("tiers").and_then(Value::as_array) else { return auto.is_object() };
|
||||
tiers.is_empty()
|
||||
|| tiers.iter().any(|tier| {
|
||||
tier.get("enabled").or_else(|| tier.pointer("/status/enabled")).and_then(Value::as_bool) != Some(false)
|
||||
})
|
||||
}
|
||||
|
||||
fn parse_model(m: &Value, units: &HashMap<String, PriceUnit>) -> Option<ModelEntry> {
|
||||
let id = str_of(m, "id")?.to_owned();
|
||||
if m.get("model_picker_enabled").and_then(Value::as_bool) == Some(false)
|
||||
|
||||
@@ -6,7 +6,6 @@ use ide_jsonrpc::{Framing, Handler, Peer, codes};
|
||||
use parking_lot::Mutex;
|
||||
use serde_json::{Value, json};
|
||||
use std::sync::{Arc, OnceLock};
|
||||
use std::time::Duration;
|
||||
|
||||
fn sample_models_list() -> Value {
|
||||
json!({
|
||||
@@ -110,72 +109,6 @@ fn sample_price_units() -> Value {
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_an_enabled_auto_only_catalog() {
|
||||
let list = json!({
|
||||
"models": [],
|
||||
"auto": {
|
||||
"defaultTier": "balance",
|
||||
"tiers": [
|
||||
{
|
||||
"id": "balance",
|
||||
"displayName": "Standard",
|
||||
"type": "auto",
|
||||
"fusionTier": "standard",
|
||||
"status": { "enabled": true, "pickerVisible": true }
|
||||
},
|
||||
{
|
||||
"id": "hydrafusion",
|
||||
"displayName": "High",
|
||||
"type": "fusion",
|
||||
"fusionTier": "high",
|
||||
"status": {
|
||||
"enabled": false,
|
||||
"pickerVisible": true,
|
||||
"reason": "user_not_eligible"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "fast",
|
||||
"displayName": "Fast",
|
||||
"type": "auto",
|
||||
"status": { "enabled": true, "pickerVisible": false }
|
||||
}
|
||||
],
|
||||
"providerId": "copilot"
|
||||
},
|
||||
"imageModels": []
|
||||
});
|
||||
|
||||
let catalog = models::parse_catalog(&list, None);
|
||||
assert_eq!(catalog.iter().map(|m| m.id.as_str()).collect::<Vec<_>>(), ["auto"]);
|
||||
assert_eq!(Settings::new(&catalog, &UserDefaults::default()).model, "auto");
|
||||
|
||||
let options =
|
||||
config::parse_options(&models::config_options(&catalog, &Settings::new(&catalog, &UserDefaults::default())));
|
||||
let model = options.iter().find(|option| option.id == MODEL).unwrap();
|
||||
assert_eq!(model.current.as_deref(), Some("auto"));
|
||||
assert_eq!(model.values.iter().map(|value| value.value.as_str()).collect::<Vec<_>>(), ["auto"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_an_auto_only_catalog_when_every_tier_is_disabled() {
|
||||
let list = json!({
|
||||
"models": [],
|
||||
"auto": {
|
||||
"defaultTier": "balance",
|
||||
"tiers": [
|
||||
{
|
||||
"id": "balance",
|
||||
"status": { "enabled": false, "pickerVisible": true }
|
||||
}
|
||||
]
|
||||
}
|
||||
});
|
||||
|
||||
assert!(models::parse_catalog(&list, None).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_tiered_context_windows_pricing_and_uses_copilots_own_defaults() {
|
||||
let catalog = models::parse_catalog(&sample_models_list(), Some(&sample_price_units()));
|
||||
@@ -407,12 +340,6 @@ fn headless_and_acp_args_roundtrip_while_preserving_user_flags() {
|
||||
struct FakeCopilotServer {
|
||||
peer: OnceLock<Peer>,
|
||||
calls: Mutex<Vec<(String, Value)>>,
|
||||
/// `session.send` leaves a shell running: the main loop goes idle but the session doesn't.
|
||||
background_shell: bool,
|
||||
}
|
||||
|
||||
fn copilot_event(sid: &str, event: Value) -> Value {
|
||||
json!({ "sessionId": sid, "event": event })
|
||||
}
|
||||
|
||||
impl Handler for FakeCopilotServer {
|
||||
@@ -428,36 +355,12 @@ impl Handler for FakeCopilotServer {
|
||||
"commands.list" => Ok(json!({ "commands": [{ "name": "compact", "description": "Compact context" }] })),
|
||||
"skills.discover" => Ok(json!({ "skills": [] })),
|
||||
"session.create" => Ok(json!({ "sessionId": "cop-sess-1" })),
|
||||
"session.resume" => Ok(json!({ "sessionId": params["sessionId"] })),
|
||||
"session.model.getCurrent" => Ok(json!({ "modelId": "gemini-4-carbon" })),
|
||||
"session.model.switchTo" => Ok(json!({ "modelId": params["modelId"] })),
|
||||
"session.mode.set" => Ok(json!({})),
|
||||
"session.permissions.setApproveAll" => {
|
||||
assert!(params.get("enabled").and_then(Value::as_bool).is_some());
|
||||
Ok(json!({ "success": true }))
|
||||
}
|
||||
"session.tasks.list" => Ok(json!({ "tasks": [
|
||||
{ "id": "shell-1", "type": "shell", "status": "running", "description": "",
|
||||
"command": "gh pr checks 3819 --watch", "attachmentMode": "attached" },
|
||||
{ "id": "shell-0", "type": "shell", "status": "completed", "description": "ls", "command": "ls" },
|
||||
] })),
|
||||
"session.tasks.cancel" => Ok(json!({ "cancelled": true })),
|
||||
"session.abort" => Ok(json!({})),
|
||||
"session.send" if self.background_shell => {
|
||||
if let Some(peer) = self.peer.get().cloned() {
|
||||
let sid = params["sessionId"].as_str().unwrap_or("cop-sess-1").to_owned();
|
||||
std::thread::spawn(move || {
|
||||
for event in [
|
||||
json!({ "id": "b1", "type": "assistant.turn_start", "data": { "turnId": "t1" } }),
|
||||
json!({ "id": "b2", "type": "assistant.idle", "data": {} }),
|
||||
json!({ "id": "b3", "type": "session.background_tasks_changed", "data": {} }),
|
||||
] {
|
||||
let _ = peer.notify("session.event", copilot_event(&sid, event));
|
||||
}
|
||||
});
|
||||
}
|
||||
Ok(json!({ "messageId": "msg-1" }))
|
||||
}
|
||||
"session.send" => {
|
||||
if let Some(peer) = self.peer.get().cloned() {
|
||||
let sid = params["sessionId"].as_str().unwrap_or("cop-sess-1").to_owned();
|
||||
@@ -520,8 +423,7 @@ impl Handler for CollectUpdates {
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn shim_creates_session_with_copilot_defaults_switches_tiers_and_streams_turns() {
|
||||
let server =
|
||||
Arc::new(FakeCopilotServer { peer: OnceLock::new(), calls: Mutex::new(Vec::new()), background_shell: false });
|
||||
let server = Arc::new(FakeCopilotServer { peer: OnceLock::new(), calls: Mutex::new(Vec::new()) });
|
||||
let updates = Arc::new(CollectUpdates(Mutex::new(Vec::new())));
|
||||
let server_clone = server.clone();
|
||||
let client = attach(updates.clone(), move |events| {
|
||||
@@ -636,118 +538,3 @@ async fn shim_creates_session_with_copilot_defaults_switches_tiers_and_streams_t
|
||||
.any(|u| u["sessionUpdate"] == "usage_update" && u["size"] == 200_000 && u["used"] == 42_000)
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn shim_forwards_disabled_mcp_servers_on_create_and_resume() {
|
||||
let server =
|
||||
Arc::new(FakeCopilotServer { peer: OnceLock::new(), calls: Mutex::new(Vec::new()), background_shell: false });
|
||||
let updates = Arc::new(CollectUpdates(Mutex::new(Vec::new())));
|
||||
let server_clone = server.clone();
|
||||
let client = attach(updates, move |events| {
|
||||
let (a, b) = tokio::io::duplex(1 << 16);
|
||||
let (ar, aw) = tokio::io::split(a);
|
||||
let (br, bw) = tokio::io::split(b);
|
||||
let srv_peer = Peer::connect_framed(br, bw, server_clone.clone(), Framing::ContentLength);
|
||||
let _ = server_clone.peer.set(srv_peer);
|
||||
Ok(Peer::connect_framed(ar, aw, events, Framing::ContentLength))
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
let _: Value = client.request("initialize", json!({}), None).await.unwrap();
|
||||
let disabled = json!(["datadog", "github-mcp-server", "linear", "playwright", "slack-official"]);
|
||||
let _: Value = client
|
||||
.request(
|
||||
"session/new",
|
||||
json!({
|
||||
"cwd": "/tmp",
|
||||
"mcpServers": [],
|
||||
"_meta": { "openidea": { "mcpServersOff": disabled } }
|
||||
}),
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let _: Value = client
|
||||
.request(
|
||||
"session/load",
|
||||
json!({
|
||||
"sessionId": "cop-sess-1",
|
||||
"cwd": "/tmp",
|
||||
"mcpServers": [],
|
||||
"_meta": { "openidea": { "mcpServersOff": disabled } }
|
||||
}),
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let calls = server.calls.lock();
|
||||
let (_, create_params) = calls.iter().find(|(m, _)| m == "session.create").unwrap();
|
||||
assert_eq!(create_params["disabledMcpServers"], disabled);
|
||||
let (_, resume_params) = calls.iter().find(|(m, _)| m == "session.resume").unwrap();
|
||||
assert_eq!(resume_params["disabledMcpServers"], disabled);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn stop_ends_a_turn_left_running_only_by_background_shells() {
|
||||
let server =
|
||||
Arc::new(FakeCopilotServer { peer: OnceLock::new(), calls: Mutex::new(Vec::new()), background_shell: true });
|
||||
let updates = Arc::new(CollectUpdates(Mutex::new(Vec::new())));
|
||||
let server_clone = server.clone();
|
||||
let client = attach(updates.clone(), move |events| {
|
||||
let (a, b) = tokio::io::duplex(1 << 16);
|
||||
let (ar, aw) = tokio::io::split(a);
|
||||
let (br, bw) = tokio::io::split(b);
|
||||
let srv_peer = Peer::connect_framed(br, bw, server_clone.clone(), Framing::ContentLength);
|
||||
let _ = server_clone.peer.set(srv_peer);
|
||||
Ok(Peer::connect_framed(ar, aw, events, Framing::ContentLength))
|
||||
})
|
||||
.unwrap();
|
||||
let init: Value = client.request("initialize", json!({}), None).await.unwrap();
|
||||
assert_eq!(init["agentCapabilities"]["_meta"]["openidea"]["backgroundTasks"], true);
|
||||
let _: Value = client.request("session/new", json!({ "cwd": "/tmp", "mcpServers": [] }), None).await.unwrap();
|
||||
|
||||
let prompt_client = client.clone();
|
||||
let turn = tokio::spawn(async move {
|
||||
prompt_client
|
||||
.request::<_, Value>(
|
||||
"session/prompt",
|
||||
json!({ "sessionId": "cop-sess-1", "prompt": [{ "type": "text", "text": "watch CI" }] }),
|
||||
None,
|
||||
)
|
||||
.await
|
||||
});
|
||||
|
||||
// The running shell shows as a background task.
|
||||
let mut shown = None;
|
||||
for _ in 0..500 {
|
||||
shown = updates.0.lock().iter().find(|u| u["sessionUpdate"] == crate::BACKGROUND_TASKS_UPDATE).cloned();
|
||||
if shown.is_some() {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
assert_eq!(
|
||||
shown.unwrap()["tasks"],
|
||||
json!([{ "task_id": "shell-1", "task_type": "local_bash", "description": "gh pr checks 3819 --watch" }])
|
||||
);
|
||||
|
||||
let _: Value = client
|
||||
.request("_openidea/stop_task", json!({ "sessionId": "cop-sess-1", "taskId": "shell-1" }), None)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
server
|
||||
.calls
|
||||
.lock()
|
||||
.iter()
|
||||
.any(|(m, p)| m == "session.tasks.cancel" && p["sessionId"] == "cop-sess-1" && p["id"] == "shell-1")
|
||||
);
|
||||
|
||||
// The main loop is idle, so Stop ends the turn even though `session.idle` never comes.
|
||||
assert!(!turn.is_finished());
|
||||
client.notify("session/cancel", json!({ "sessionId": "cop-sess-1" })).unwrap();
|
||||
let res = tokio::time::timeout(Duration::from_secs(5), turn).await.unwrap().unwrap().unwrap();
|
||||
assert_eq!(res["stopReason"], "cancelled");
|
||||
assert!(!server.calls.lock().iter().any(|(m, _)| m == "session.abort"));
|
||||
}
|
||||
@@ -522,14 +522,6 @@ pub(super) fn wire_mcp_servers(acp_servers: Option<&Value>) -> Option<Value> {
|
||||
(!out.is_empty()).then_some(Value::Object(out))
|
||||
}
|
||||
|
||||
/// Extracts `_meta.openidea.mcpServersOff` into Copilot's `disabledMcpServers` string array.
|
||||
pub(super) fn wire_disabled_mcp_servers(params: &Value) -> Option<Value> {
|
||||
let list = params.pointer("/_meta/openidea/mcpServersOff")?.as_array()?;
|
||||
let names: Vec<Value> =
|
||||
list.iter().filter_map(|v| v.as_str().map(str::trim).filter(|s| !s.is_empty()).map(|s| json!(s))).collect();
|
||||
(!names.is_empty()).then_some(Value::Array(names))
|
||||
}
|
||||
|
||||
/// Converts `commands.list` + `skills.discover` results into ACP `availableCommands`.
|
||||
pub(super) fn available_commands(commands_res: Option<&Value>, skills_res: Option<&Value>) -> Vec<Value> {
|
||||
let mut seen = HashSet::new();
|
||||
@@ -576,28 +568,6 @@ pub(super) fn available_commands(commands_res: Option<&Value>, skills_res: Optio
|
||||
out
|
||||
}
|
||||
|
||||
/// The running entries of a `session.tasks.list` result, in the background-task shape the
|
||||
/// app shows (`task_id`, `task_type`, `description`).
|
||||
pub(super) fn background_tasks(list: &Value) -> Vec<Value> {
|
||||
let tasks = list.get("tasks").and_then(Value::as_array).map(Vec::as_slice).unwrap_or_default();
|
||||
tasks
|
||||
.iter()
|
||||
.filter(|t| matches!(str_of(t, "status"), Some("running" | "idle")))
|
||||
.filter_map(|t| {
|
||||
let id = str_of(t, "id")?;
|
||||
let kind = str_of(t, "type").unwrap_or_default();
|
||||
let task_type = match kind {
|
||||
"shell" => "local_bash",
|
||||
"agent" => "local_agent",
|
||||
other => other,
|
||||
};
|
||||
let description =
|
||||
str_of(t, "description").filter(|d| !d.is_empty()).or_else(|| str_of(t, "command")).unwrap_or(kind);
|
||||
Some(json!({ "task_id": id, "task_type": task_type, "description": description }))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn trim_tail(text: &mut String) {
|
||||
if text.len() > MAX_OUTPUT {
|
||||
let mut cut = text.len() - MAX_OUTPUT;
|
||||
|
||||
@@ -9,8 +9,6 @@ use serde_json::Value;
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
pub(crate) const COPILOT_GITHUB_ACCOUNT_ENV: &str = "OPENIDEA_COPILOT_GITHUB_ACCOUNT";
|
||||
|
||||
/// The protocol an agent speaks. Native ones run behind an in-process ACP endpoint
|
||||
/// (`native`), so tasks see every agent as ACP and read features from its capabilities.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
@@ -58,13 +56,6 @@ const BUILTIN: &[(&str, &str, Driver, &[&str], &str)] = &[
|
||||
&["npx", "-y", "@agentclientprotocol/[email protected]"],
|
||||
"Run `codex login` in a terminal.",
|
||||
),
|
||||
(
|
||||
"deepseek-harness",
|
||||
"DeepSeek Harness",
|
||||
Driver::Acp,
|
||||
&["dsh", "--profile", "acp"],
|
||||
"Run `dsh` in a terminal and sign in.",
|
||||
),
|
||||
("gemini", "Gemini CLI", Driver::Acp, &["gemini", "--experimental-acp"], "Run `gemini` in a terminal and sign in."),
|
||||
(
|
||||
"copilot",
|
||||
@@ -84,7 +75,6 @@ const BUILTIN: &[(&str, &str, Driver, &[&str], &str)] = &[
|
||||
("kiro", "Kiro", Driver::Acp, &["kiro-cli", "acp"], "Run `kiro-cli login` in a terminal."),
|
||||
("vibe", "Mistral Vibe", Driver::Acp, &["vibe-acp"], "Run `vibe` in a terminal and sign in."),
|
||||
("omp", "OMP", Driver::Acp, &["omp", "acp"], "Run `omp` in a terminal and sign in."),
|
||||
("hermes", "Hermes Agent", Driver::Acp, &["hermes", "acp"], "Run `hermes model` in a terminal."),
|
||||
];
|
||||
|
||||
fn builtins() -> Vec<ProviderSpec> {
|
||||
@@ -140,31 +130,15 @@ impl ProviderSpec {
|
||||
/// Resolve once before connecting, so authentication guidance names that same install.
|
||||
pub(crate) fn resolve_for_launch(self, cwd: &Path) -> Self {
|
||||
let strip = prefer_stored_copilot_auth();
|
||||
self.resolve_for_launch_base(cwd, strip)
|
||||
self.resolve_for_launch_with_copilot_env(cwd, strip)
|
||||
}
|
||||
|
||||
pub(crate) fn resolve_for_launch_with_copilot_env(
|
||||
self,
|
||||
cwd: &Path,
|
||||
strip_ambient_tokens: bool,
|
||||
) -> Result<Self, String> {
|
||||
let account = is_copilot_provider(&self.id).then(|| copilot_github_account(&self.env)).flatten();
|
||||
let mut resolved = self.resolve_for_launch_base(cwd, strip_ambient_tokens || account.is_some());
|
||||
if let Some(account) = account {
|
||||
let token = github_token_for_account(&account)?;
|
||||
resolved.env.retain(|(name, _)| !AMBIENT_COPILOT_AUTH_VARS.contains(&name.as_str()));
|
||||
resolved.env.push(("COPILOT_GITHUB_TOKEN".into(), token));
|
||||
}
|
||||
Ok(resolved)
|
||||
}
|
||||
|
||||
fn resolve_for_launch_base(mut self, cwd: &Path, strip_ambient_tokens: bool) -> Self {
|
||||
pub(crate) fn resolve_for_launch_with_copilot_env(mut self, cwd: &Path, strip_ambient_tokens: bool) -> Self {
|
||||
if self.driver != Driver::Acp {
|
||||
self.command = crate::native::newest_install(&self.command);
|
||||
}
|
||||
if is_copilot_provider(&self.id) {
|
||||
self.env = sanitized_copilot_env(&self.env, strip_ambient_tokens);
|
||||
self.env.retain(|(name, _)| name != COPILOT_GITHUB_ACCOUNT_ENV);
|
||||
}
|
||||
let program = ide_jsonrpc::resolve_spawn_program(&self.command, &self.env);
|
||||
self.command =
|
||||
@@ -182,50 +156,6 @@ pub(crate) fn is_copilot_provider(id: &str) -> bool {
|
||||
id == "copilot" || id.starts_with("copilot-")
|
||||
}
|
||||
|
||||
pub(crate) fn copilot_github_account(env: &[(String, String)]) -> Option<String> {
|
||||
env.iter()
|
||||
.rev()
|
||||
.find(|(name, _)| name == COPILOT_GITHUB_ACCOUNT_ENV)
|
||||
.map(|(_, value)| value.trim())
|
||||
.filter(|value| !value.is_empty())
|
||||
.map(str::to_owned)
|
||||
}
|
||||
|
||||
fn github_token_for_account(account: &str) -> Result<String, String> {
|
||||
let path = ide_core::process::shell_env()
|
||||
.find(|(name, _)| name == "PATH")
|
||||
.map(|(_, value)| value)
|
||||
.or_else(|| ide_core::process::host_var_os("PATH"));
|
||||
let program = path
|
||||
.as_deref()
|
||||
.and_then(|path| ide_core::process::find_executable("gh", path))
|
||||
.ok_or_else(|| "GitHub CLI (`gh`) is required to select a Copilot GitHub account".to_owned())?;
|
||||
let mut command = std::process::Command::new(program);
|
||||
command.args(["auth", "token", "--hostname", "github.com", "--user", account]).envs(ide_core::process::shell_env());
|
||||
for name in AMBIENT_COPILOT_AUTH_VARS {
|
||||
command.env_remove(name);
|
||||
}
|
||||
let output = command
|
||||
.output()
|
||||
.map_err(|error| format!("Couldn't read GitHub authentication for account {account}: {error}"))?;
|
||||
if !output.status.success() {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
let detail = stderr.trim();
|
||||
return Err(if detail.is_empty() {
|
||||
format!("GitHub CLI has no authenticated account named {account}")
|
||||
} else {
|
||||
format!("Couldn't use GitHub account {account}: {detail}")
|
||||
});
|
||||
}
|
||||
let token = String::from_utf8(output.stdout)
|
||||
.map_err(|_| format!("GitHub CLI returned a non-text token for account {account}"))?;
|
||||
let token = token.trim();
|
||||
if token.is_empty() {
|
||||
return Err(format!("GitHub CLI returned no token for account {account}"));
|
||||
}
|
||||
Ok(token.to_owned())
|
||||
}
|
||||
|
||||
pub(crate) fn prefer_stored_copilot_auth() -> bool {
|
||||
PREFER_STORED_COPILOT_AUTH.load(std::sync::atomic::Ordering::Acquire)
|
||||
}
|
||||
@@ -373,7 +303,6 @@ pub(crate) fn describe(spec: &ProviderSpec) -> AgentProvider {
|
||||
command_editable: reason.is_none(),
|
||||
command_read_only_reason: reason,
|
||||
installed: installed(&spec.command),
|
||||
can_check_cli_update: spec.source == AgentSource::Builtin && crate::cli_update::package(&spec.id).is_some(),
|
||||
env: spec.env.iter().cloned().collect(),
|
||||
config: vec![],
|
||||
thought_levels: BTreeMap::new(),
|
||||
@@ -402,31 +331,6 @@ pub(crate) fn set_builtin_env(
|
||||
id: &str,
|
||||
env: BTreeMap<String, String>,
|
||||
) -> IdeResult<()> {
|
||||
if id == "copilot" {
|
||||
let file = custom_dir.join("copilot.toml");
|
||||
if file.try_exists()?
|
||||
&& let mut agent = CustomAgent::read_with(&file, id, secrets).map_err(IdeError::invalid)?
|
||||
&& agent.registry.is_some()
|
||||
{
|
||||
let existing = agent.env.clone();
|
||||
let mut existing_launch_env = existing.clone();
|
||||
let mut next_launch_env = env.clone();
|
||||
existing_launch_env.remove(COPILOT_GITHUB_ACCOUNT_ENV);
|
||||
next_launch_env.remove(COPILOT_GITHUB_ACCOUNT_ENV);
|
||||
if existing_launch_env != next_launch_env {
|
||||
return Err(IdeError::invalid(format!("{id} is installed from the ACP Registry")));
|
||||
}
|
||||
match env.get(COPILOT_GITHUB_ACCOUNT_ENV).filter(|value| !value.trim().is_empty()) {
|
||||
Some(account) => {
|
||||
agent.env.insert(COPILOT_GITHUB_ACCOUNT_ENV.into(), account.trim().into());
|
||||
}
|
||||
None => {
|
||||
agent.env.remove(COPILOT_GITHUB_ACCOUNT_ENV);
|
||||
}
|
||||
}
|
||||
return agent.write(&file).map_err(Into::into);
|
||||
}
|
||||
}
|
||||
update_builtin(custom_dir, secrets, id, |agent, _| agent.env = env)
|
||||
}
|
||||
|
||||
@@ -592,7 +496,7 @@ fn validated_custom_id(id: &str) -> IdeResult<String> {
|
||||
}
|
||||
|
||||
/// Turns an `acp.json` server name into a file-stem id (`"My Agent!"` → `"my-agent"`).
|
||||
pub(crate) fn slugify_id(name: &str) -> String {
|
||||
fn slugify_id(name: &str) -> String {
|
||||
let mut id = String::with_capacity(name.len());
|
||||
for c in name.chars() {
|
||||
if c.is_ascii_alphanumeric() {
|
||||
@@ -805,15 +709,6 @@ mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn hermes_is_built_in_over_acp() {
|
||||
let spec = builtin_spec("hermes").unwrap();
|
||||
assert_eq!(spec.driver, Driver::Acp);
|
||||
let info = describe(&spec);
|
||||
assert_eq!((info.name.as_str(), info.command.as_str()), ("Hermes Agent", "hermes acp"));
|
||||
assert_eq!(info.login_hint.as_deref(), Some("Run `hermes model` in a terminal."));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qoder_global_and_cn_editions_are_both_built_in() {
|
||||
let info = |id: &str| describe(&load(None, None).into_iter().find(|s| s.id == id).unwrap());
|
||||
@@ -1043,46 +938,6 @@ mod tests {
|
||||
set_builtin_env(dir.path(), None, "not-a-builtin", env).unwrap_err();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn registry_copilot_allows_only_the_github_account_override() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let file = dir.path().join("copilot.toml");
|
||||
CustomAgent {
|
||||
name: Some("GitHub Copilot".into()),
|
||||
driver: Driver::Acp,
|
||||
command: "/tools/copilot".into(),
|
||||
args: vec!["--acp".into()],
|
||||
env: BTreeMap::from([("REGISTRY_SETTING".into(), "kept".into())]),
|
||||
registry: Some(RegistryRef { id: "copilot".into(), version: "1.0.0".into() }),
|
||||
}
|
||||
.write(&file)
|
||||
.unwrap();
|
||||
|
||||
set_builtin_env(
|
||||
dir.path(),
|
||||
None,
|
||||
"copilot",
|
||||
BTreeMap::from([
|
||||
("REGISTRY_SETTING".into(), "kept".into()),
|
||||
(COPILOT_GITHUB_ACCOUNT_ENV.into(), "dengliu_microsoft".into()),
|
||||
]),
|
||||
)
|
||||
.unwrap();
|
||||
let spec = load(Some(dir.path()), None).into_iter().find(|spec| spec.id == "copilot").unwrap();
|
||||
assert_eq!(copilot_github_account(&spec.env).as_deref(), Some("dengliu_microsoft"));
|
||||
|
||||
set_builtin_env(dir.path(), None, "copilot", BTreeMap::from([("REGISTRY_SETTING".into(), "changed".into())]))
|
||||
.unwrap_err();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn launch_metadata_never_passes_the_github_account_control_to_copilot() {
|
||||
let mut spec = builtin_spec("copilot").unwrap();
|
||||
spec.env.push((COPILOT_GITHUB_ACCOUNT_ENV.into(), "dengliu_microsoft".into()));
|
||||
let resolved = spec.resolve_for_launch(Path::new("."));
|
||||
assert!(resolved.env.iter().all(|(name, _)| name != COPILOT_GITHUB_ACCOUNT_ENV));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn acp_adapters_of_native_agents_are_unlisted_until_customized() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -24,9 +24,7 @@ use std::process::Command;
|
||||
use std::time::Duration;
|
||||
|
||||
pub const REGISTRY_URL: &str = "https://cdn.agentclientprotocol.com/registry/v1/latest/registry.json";
|
||||
const COPILOT_RELEASE_BASE: &str = "https://github.com/github/copilot-cli/releases/download";
|
||||
const MAX_REGISTRY_BYTES: u64 = 1024 * 1024;
|
||||
const MAX_CHECKSUM_BYTES: u64 = 64 * 1024;
|
||||
/// [`maintain`] refreshes a saved index older than this, so updates show without opening
|
||||
/// the registry.
|
||||
const REFRESH_AFTER: Duration = Duration::from_secs(24 * 60 * 60);
|
||||
@@ -144,9 +142,6 @@ struct Binary {
|
||||
env: BTreeMap<String, String>,
|
||||
#[serde(default)]
|
||||
sha256: Option<String>,
|
||||
/// Checksum manifest (`SHA256SUMS.txt`) naming `archive`'s filename when `sha256` is not inline.
|
||||
#[serde(skip)]
|
||||
sha256_url: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize)]
|
||||
@@ -177,48 +172,11 @@ fn parse(text: &str) -> IdeResult<Vec<Entry>> {
|
||||
if let Some(name) = provider::builtin_name(&e.id) {
|
||||
e.name = name.to_owned();
|
||||
}
|
||||
if e.id == "copilot" {
|
||||
add_copilot_release_binaries(&mut e, COPILOT_RELEASE_BASE);
|
||||
}
|
||||
e
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// Upstream `github-copilot-cli` lists only an `npx` wrapper in the ACP Registry, while
|
||||
/// `github/copilot-cli` publishes standalone archives and `SHA256SUMS.txt` on every GitHub
|
||||
/// release. Supplying them installs Copilot without Node.js, npm, `~/.npmrc`, or mirror lag.
|
||||
fn add_copilot_release_binaries(entry: &mut Entry, release_base: &str) {
|
||||
let tag = format!("v{}", entry.version.trim_start_matches('v'));
|
||||
let base = format!("{}/{}", release_base.trim_end_matches('/'), tag);
|
||||
let sha256_url = format!("{base}/SHA256SUMS.txt");
|
||||
let (args, env) = match &entry.distribution.npx {
|
||||
Some(p) => (p.args.clone(), p.env.clone()),
|
||||
None => (vec!["--acp".into()], BTreeMap::new()),
|
||||
};
|
||||
let linux = if cfg!(target_env = "musl") { "linuxmusl" } else { "linux" };
|
||||
let linux_arm = format!("copilot-{linux}-arm64.tar.gz");
|
||||
let linux_x64 = format!("copilot-{linux}-x64.tar.gz");
|
||||
let targets = [
|
||||
("darwin-aarch64", "copilot-darwin-arm64.tar.gz", "./copilot"),
|
||||
("darwin-x86_64", "copilot-darwin-x64.tar.gz", "./copilot"),
|
||||
("linux-aarch64", linux_arm.as_str(), "./copilot"),
|
||||
("linux-x86_64", linux_x64.as_str(), "./copilot"),
|
||||
("windows-aarch64", "copilot-win32-arm64.zip", "copilot.exe"),
|
||||
("windows-x86_64", "copilot-win32-x64.zip", "copilot.exe"),
|
||||
];
|
||||
for (key, asset, cmd) in targets {
|
||||
entry.distribution.binary.entry(key.to_owned()).or_insert_with(|| Binary {
|
||||
archive: format!("{base}/{asset}"),
|
||||
cmd: cmd.to_owned(),
|
||||
args: args.clone(),
|
||||
env: env.clone(),
|
||||
sha256: None,
|
||||
sha256_url: Some(sha256_url.clone()),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn safe_segment(s: &str) -> bool {
|
||||
!s.is_empty()
|
||||
&& !s.starts_with('.')
|
||||
@@ -358,7 +316,7 @@ fn visible(
|
||||
None
|
||||
};
|
||||
let choice = choose(e, platform, on_path);
|
||||
let no_checksum = matches!(choice, Some(Choice::Binary(b)) if b.sha256.is_none() && b.sha256_url.is_none());
|
||||
let no_checksum = matches!(choice, Some(Choice::Binary(b)) if b.sha256.is_none());
|
||||
let distribution = choice.map(|c| c.kind());
|
||||
if distribution.is_none() && installed.is_none() {
|
||||
return None;
|
||||
@@ -465,20 +423,6 @@ fn install_entry(
|
||||
on_path: &dyn Fn(&str) -> bool,
|
||||
cancel: &CancellationToken,
|
||||
emit: Emit,
|
||||
) -> IdeResult<()> {
|
||||
install_entry_with(paths, entry, platform, on_path, &install_npm, cancel, emit)
|
||||
}
|
||||
|
||||
type NpmInstaller = dyn Fn(&Package, &Entry, &Path, Platform, &CancellationToken, Emit) -> IdeResult<PathBuf>;
|
||||
|
||||
fn install_entry_with(
|
||||
paths: &RegistryPaths,
|
||||
entry: &Entry,
|
||||
platform: Platform,
|
||||
on_path: &dyn Fn(&str) -> bool,
|
||||
npm_installer: &NpmInstaller,
|
||||
cancel: &CancellationToken,
|
||||
emit: Emit,
|
||||
) -> IdeResult<()> {
|
||||
if is_builtin(&entry.id) {
|
||||
return Err(IdeError::invalid(format!("{} is built in", entry.name)));
|
||||
@@ -499,32 +443,9 @@ fn install_entry_with(
|
||||
}
|
||||
fs::create_dir_all(&dir)?;
|
||||
let installed = match &choice {
|
||||
Choice::Binary(b) => match install_binary(b, &dir, cancel, emit) {
|
||||
Ok(exe) => Ok((exe, b.args.clone(), b.env.clone())),
|
||||
Err(e)
|
||||
if !cancel.is_cancelled()
|
||||
&& e.kind != ErrorKind::Cancelled
|
||||
&& !e.message.starts_with("checksum mismatch:")
|
||||
&& entry.distribution.npx.is_some()
|
||||
&& on_path("npm")
|
||||
&& on_path("node") =>
|
||||
{
|
||||
let p = entry.distribution.npx.as_ref().expect("checked");
|
||||
emit(InstallEvent::Line {
|
||||
text: format!("Binary download failed ({}); falling back to npm…", e.message),
|
||||
});
|
||||
fs::remove_dir_all(&dir)?;
|
||||
fs::create_dir_all(&dir)?;
|
||||
npm_installer(p, entry, &dir, platform, cancel, emit)
|
||||
.map(|exe| (exe, p.args.clone(), p.env.clone()))
|
||||
.map_err(|npm_err| {
|
||||
IdeError::new(npm_err.kind, format!("{}; npm fallback failed: {}", e.message, npm_err.message))
|
||||
})
|
||||
}
|
||||
Err(e) => Err(e),
|
||||
},
|
||||
Choice::Binary(b) => install_binary(b, &dir, cancel, emit).map(|exe| (exe, b.args.clone(), b.env.clone())),
|
||||
Choice::Npx(p) => {
|
||||
npm_installer(p, entry, &dir, platform, cancel, emit).map(|exe| (exe, p.args.clone(), p.env.clone()))
|
||||
install_npm(p, entry, &dir, platform, cancel, emit).map(|exe| (exe, p.args.clone(), p.env.clone()))
|
||||
}
|
||||
Choice::Uvx(p) => {
|
||||
install_uv(p, entry, &dir, platform, cancel, emit).map(|exe| (exe, p.args.clone(), p.env.clone()))
|
||||
@@ -537,14 +458,6 @@ fn install_entry_with(
|
||||
return Err(e);
|
||||
}
|
||||
};
|
||||
let github_account = (entry.id == "copilot")
|
||||
.then(|| CustomAgent::read(&file).ok())
|
||||
.flatten()
|
||||
.and_then(|agent| agent.env.get(provider::COPILOT_GITHUB_ACCOUNT_ENV).cloned());
|
||||
let mut env = env;
|
||||
if let Some(account) = github_account {
|
||||
env.insert(provider::COPILOT_GITHUB_ACCOUNT_ENV.into(), account);
|
||||
}
|
||||
let agent = CustomAgent {
|
||||
name: Some(entry.name.clone()),
|
||||
driver: Driver::Acp,
|
||||
@@ -595,23 +508,13 @@ fn install_binary(b: &Binary, dir: &Path, cancel: &CancellationToken, emit: Emit
|
||||
fs::create_dir_all(&downloads)?;
|
||||
let file = downloads.join(name);
|
||||
emit(InstallEvent::Line { text: format!("Downloading {}", b.archive) });
|
||||
let http = http()?;
|
||||
http.download(&b.archive, &file, None, cancel, emit)?;
|
||||
match (&b.sha256, &b.sha256_url) {
|
||||
(Some(expected), _) => {
|
||||
http()?.download(&b.archive, &file, None, cancel, emit)?;
|
||||
match &b.sha256 {
|
||||
Some(expected) => {
|
||||
verify_sha256(&file, expected)?;
|
||||
emit(InstallEvent::Line { text: "SHA-256 checksum verified".into() });
|
||||
}
|
||||
(None, Some(checksum_url)) => {
|
||||
check_url(checksum_url)?;
|
||||
let text = http.get_text_limited(checksum_url, Some(MAX_CHECKSUM_BYTES), cancel)?;
|
||||
let expected = ide_tools::sources::parse_checksum(&text, name).ok_or_else(|| {
|
||||
IdeError::new(ErrorKind::Protocol, format!("no SHA-256 checksum for {name} in {checksum_url}"))
|
||||
})?;
|
||||
verify_sha256(&file, &expected)?;
|
||||
emit(InstallEvent::Line { text: "SHA-256 checksum verified".into() });
|
||||
}
|
||||
(None, None) => emit(InstallEvent::Line { text: "The registry gives no checksum for this download".into() }),
|
||||
None => emit(InstallEvent::Line { text: "The registry gives no checksum for this download".into() }),
|
||||
}
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
@@ -664,20 +567,6 @@ fn install_npm(
|
||||
platform: Platform,
|
||||
cancel: &CancellationToken,
|
||||
emit: Emit,
|
||||
) -> IdeResult<PathBuf> {
|
||||
let (name, _) = split_npm_spec(&p.package);
|
||||
let npm = which::which("npm").map_err(|_| IdeError::unavailable(format!("npm is required to install {name}")))?;
|
||||
install_npm_with(&npm, p, entry, dir, platform, cancel, emit)
|
||||
}
|
||||
|
||||
fn install_npm_with(
|
||||
npm: &Path,
|
||||
p: &Package,
|
||||
entry: &Entry,
|
||||
dir: &Path,
|
||||
platform: Platform,
|
||||
cancel: &CancellationToken,
|
||||
emit: Emit,
|
||||
) -> IdeResult<PathBuf> {
|
||||
let (name, version) = split_npm_spec(&p.package);
|
||||
let spec = match version {
|
||||
@@ -685,27 +574,10 @@ fn install_npm_with(
|
||||
_ => format!("{name}@{}", entry.version),
|
||||
};
|
||||
check_spec(&spec)?;
|
||||
let specs = [spec.clone()];
|
||||
ide_tools::run_npm_with_public_fallback(
|
||||
|extra| {
|
||||
if !extra.is_empty() {
|
||||
let _ = fs::remove_dir_all(dir.join("node_modules"));
|
||||
}
|
||||
let mut cmd = Command::new(npm);
|
||||
cmd.arg("install")
|
||||
.arg("--prefix")
|
||||
.arg(dir)
|
||||
.args(["--no-audit", "--no-fund"])
|
||||
.args(extra)
|
||||
.arg(&spec)
|
||||
.current_dir(dir);
|
||||
cmd
|
||||
},
|
||||
&specs,
|
||||
false,
|
||||
cancel,
|
||||
emit,
|
||||
)?;
|
||||
let npm = which::which("npm").map_err(|_| IdeError::unavailable(format!("npm is required to install {name}")))?;
|
||||
let mut cmd = Command::new(npm);
|
||||
cmd.arg("install").arg("--prefix").arg(dir).args(["--no-audit", "--no-fund"]).arg(&spec).current_dir(dir);
|
||||
ide_tools::run_streamed(cmd, cancel, emit)?;
|
||||
let modules = dir.join("node_modules");
|
||||
let manifest: serde_json::Value = fs::read_to_string(modules.join(name).join("package.json"))
|
||||
.ok()
|
||||
@@ -1000,58 +872,6 @@ mod tests {
|
||||
assert!(check_url("ftp://x/a").is_err());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn npm_registry_agent_retries_against_public_npmjs_on_mirror_miss() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let install_dir = dir.path().join("acme/1.2.0");
|
||||
fs::create_dir_all(&install_dir).unwrap();
|
||||
let log = dir.path().join("npm-calls.log");
|
||||
let npm = dir.path().join("npm");
|
||||
fs::write(
|
||||
&npm,
|
||||
format!(
|
||||
r#"#!/bin/sh
|
||||
echo "$@" >> '{}'
|
||||
case " $* " in
|
||||
*" --registry=https://registry.npmjs.org/ --@acme:registry=https://registry.npmjs.org/ "*)
|
||||
prefix=""; while [ $# -gt 0 ]; do [ "$1" = "--prefix" ] && prefix="$2"; shift; done
|
||||
mkdir -p "$prefix/node_modules/.bin" "$prefix/node_modules/@acme/agent-acp"
|
||||
printf '#!/bin/sh\necho 1.2.0\n' > "$prefix/node_modules/.bin/agent-acp"
|
||||
chmod +x "$prefix/node_modules/.bin/agent-acp"
|
||||
printf '{{"bin":"cli.js"}}\n' > "$prefix/node_modules/@acme/agent-acp/package.json"
|
||||
exit 0
|
||||
;;
|
||||
*)
|
||||
echo "npm error code ETARGET" >&2
|
||||
echo "npm error notarget No matching version found for @acme/[email protected]." >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
"#,
|
||||
log.display()
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
archive::make_executable(&npm).unwrap();
|
||||
|
||||
let index = r#"{"agents":[
|
||||
{"id":"acme","name":"Acme","version":"1.2.0",
|
||||
"distribution":{"npx":{"package":"@acme/[email protected]","args":["--acp"]}}}
|
||||
]}"#;
|
||||
let entry = parse(index).unwrap().remove(0);
|
||||
let pkg = entry.distribution.npx.as_ref().unwrap();
|
||||
let exe =
|
||||
install_npm_with(&npm, pkg, &entry, &install_dir, MAC_ARM, &CancellationToken::new(), &|_| {}).unwrap();
|
||||
let calls: Vec<String> = fs::read_to_string(&log).unwrap().lines().map(str::to_owned).collect();
|
||||
assert_eq!(calls.len(), 2, "{calls:?}");
|
||||
assert!(!calls[0].contains("--registry="), "{calls:?}");
|
||||
assert!(calls[1].contains("--registry=https://registry.npmjs.org/"), "{calls:?}");
|
||||
assert!(calls[1].contains("--@acme:registry=https://registry.npmjs.org/"), "{calls:?}");
|
||||
assert_eq!(exe, install_dir.join("node_modules/.bin/agent-acp"));
|
||||
assert!(exe.is_file());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn checksums_are_verified() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
@@ -1149,18 +969,11 @@ esac
|
||||
assert_eq!(entries.len(), 1);
|
||||
assert_eq!((entries[0].id.as_str(), entries[0].name.as_str()), ("copilot", "GitHub Copilot"));
|
||||
|
||||
// Copilot installs as a verified GitHub Release binary even without Node.js or npm.
|
||||
let shown = visible(&p, &entries, MAC_ARM, &|_| false);
|
||||
let shown = visible(&p, &entries, MAC_ARM, &|c| c == "npm" || c == "node");
|
||||
assert_eq!(shown.len(), 1);
|
||||
assert_eq!(
|
||||
(
|
||||
shown[0].id.as_str(),
|
||||
shown[0].name.as_str(),
|
||||
shown[0].installed.as_deref(),
|
||||
shown[0].distribution,
|
||||
shown[0].no_checksum,
|
||||
),
|
||||
("copilot", "GitHub Copilot", None, Some(RegistryDistribution::Binary), false)
|
||||
(shown[0].id.as_str(), shown[0].name.as_str(), shown[0].installed.as_deref()),
|
||||
("copilot", "GitHub Copilot", None)
|
||||
);
|
||||
|
||||
CustomAgent {
|
||||
@@ -1174,7 +987,7 @@ esac
|
||||
.write(&p.agent_file("copilot"))
|
||||
.unwrap();
|
||||
|
||||
let shown = visible(&p, &entries, MAC_ARM, &|_| false);
|
||||
let shown = visible(&p, &entries, MAC_ARM, &|c| c == "npm" || c == "node");
|
||||
assert_eq!((shown[0].installed.as_deref(), shown[0].update), (Some("1.0.104"), true));
|
||||
|
||||
write_atomic(&p.cache_file, index.as_bytes()).unwrap();
|
||||
@@ -1194,82 +1007,4 @@ esac
|
||||
let fallback = provider::load(Some(&p.agents_dir), None).into_iter().find(|s| s.id == "copilot").unwrap();
|
||||
assert_eq!(fallback.source, AgentSource::Builtin);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn installs_copilot_from_verified_release_archive_and_falls_back_to_npm_when_unavailable() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let p = paths(dir.path());
|
||||
let served = dir.path().join("releases/v1.0.114");
|
||||
fs::create_dir_all(&served).unwrap();
|
||||
let archive = served.join("copilot-darwin-arm64.tar.gz");
|
||||
let stage = dir.path().join("archive-stage");
|
||||
fs::create_dir_all(&stage).unwrap();
|
||||
let staged_exe = stage.join("copilot");
|
||||
fs::write(&staged_exe, "#!/bin/sh\necho 1.0.114\n").unwrap();
|
||||
archive::make_executable(&staged_exe).unwrap();
|
||||
assert!(
|
||||
Command::new("tar")
|
||||
.arg("-czf")
|
||||
.arg(&archive)
|
||||
.arg("-C")
|
||||
.arg(&stage)
|
||||
.arg("copilot")
|
||||
.status()
|
||||
.unwrap()
|
||||
.success()
|
||||
);
|
||||
let sha = ide_tools::sources::sha256_file(&archive).unwrap();
|
||||
let sums = served.join("SHA256SUMS.txt");
|
||||
fs::write(&sums, format!("{sha} copilot-darwin-arm64.tar.gz\n")).unwrap();
|
||||
|
||||
let index = r#"{"agents":[
|
||||
{"id":"github-copilot-cli","name":"Copilot","version":"1.0.114",
|
||||
"distribution":{"npx":{"package":"@github/[email protected]","args":["--acp"]}}}
|
||||
]}"#;
|
||||
let mut entry = parse(index).unwrap().remove(0);
|
||||
entry.distribution.binary.clear();
|
||||
add_copilot_release_binaries(&mut entry, &format!("file://{}", dir.path().join("releases").display()));
|
||||
|
||||
let fake_npm = |_: &Package, _: &Entry, dest: &Path, _: Platform, _: &CancellationToken, _: Emit| {
|
||||
let exe = dest.join("node_modules/.bin/copilot");
|
||||
fs::create_dir_all(exe.parent().unwrap())?;
|
||||
fs::write(&exe, "#!/bin/sh\necho npm-1.0.114\n")?;
|
||||
archive::make_executable(&exe)?;
|
||||
Ok(exe)
|
||||
};
|
||||
let node_on_path = |cmd: &str| matches!(cmd, "npm" | "node");
|
||||
|
||||
let cancel = CancellationToken::new();
|
||||
let lines = std::sync::Mutex::new(Vec::new());
|
||||
let emit = |e: InstallEvent| {
|
||||
if let InstallEvent::Line { text } = e {
|
||||
lines.lock().unwrap().push(text);
|
||||
}
|
||||
};
|
||||
|
||||
// 1. Verified GitHub Release archive installs directly without invoking npm.
|
||||
install_entry_with(&p, &entry, MAC_ARM, &|_| false, &fake_npm, &cancel, &emit).unwrap();
|
||||
assert!(lines.lock().unwrap().iter().any(|l| l == "SHA-256 checksum verified"));
|
||||
let installed_bin = p.tools_dir.join("copilot/1.0.114/copilot");
|
||||
assert!(installed_bin.is_file());
|
||||
let saved = CustomAgent::read(&p.agent_file("copilot")).unwrap();
|
||||
assert_eq!(saved.command, installed_bin.to_string_lossy());
|
||||
assert_eq!(saved.args, ["--acp"]);
|
||||
|
||||
// 2. A tampered binary fails checksum verification and never falls back to npm.
|
||||
fs::write(&sums, format!("{} copilot-darwin-arm64.tar.gz\n", "0".repeat(64))).unwrap();
|
||||
let err = install_entry_with(&p, &entry, MAC_ARM, &node_on_path, &fake_npm, &cancel, &emit).unwrap_err();
|
||||
assert!(err.message.contains("checksum mismatch"), "{err:?}");
|
||||
assert!(!p.tools_dir.join("copilot/1.0.114").exists());
|
||||
|
||||
// 3. When the release download itself is unreachable, npm fallback installs it.
|
||||
fs::remove_file(&archive).unwrap();
|
||||
lines.lock().unwrap().clear();
|
||||
install_entry_with(&p, &entry, MAC_ARM, &node_on_path, &fake_npm, &cancel, &emit).unwrap();
|
||||
assert!(lines.lock().unwrap().iter().any(|l| l.contains("falling back to npm")));
|
||||
let npm_bin = p.tools_dir.join("copilot/1.0.114/node_modules/.bin/copilot");
|
||||
assert!(npm_bin.is_file());
|
||||
assert_eq!(CustomAgent::read(&p.agent_file("copilot")).unwrap().command, npm_bin.to_string_lossy());
|
||||
}
|
||||
}
|
||||
@@ -1,160 +0,0 @@
|
||||
//! `!` commands from the composer: run in the task's folder with the user's shell, outside
|
||||
//! any turn, and handed to the agent with the next message as Claude Code's bash mode does.
|
||||
|
||||
use ide_core::CancellationToken;
|
||||
use std::path::Path;
|
||||
use std::process::Stdio;
|
||||
use tokio::io::AsyncReadExt;
|
||||
use tokio::process::Command;
|
||||
|
||||
/// Output kept from each stream; longer output keeps its tail.
|
||||
const MAX_STREAM: usize = 32 * 1024;
|
||||
|
||||
#[derive(Debug, Default, PartialEq)]
|
||||
pub(crate) struct Ran {
|
||||
/// The exit code; `None` when it didn't start, was stopped or ended by a signal.
|
||||
pub code: Option<i32>,
|
||||
pub stdout: String,
|
||||
pub stderr: String,
|
||||
/// Why it didn't finish: it couldn't start, or it was stopped.
|
||||
pub error: Option<String>,
|
||||
}
|
||||
|
||||
impl Ran {
|
||||
/// What the conversation shows: the output, then how it ended unless it succeeded.
|
||||
pub fn shown(&self) -> String {
|
||||
let mut text = [self.stdout.trim_end(), self.stderr.trim_end()]
|
||||
.into_iter()
|
||||
.filter(|t| !t.is_empty())
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
let end = match (&self.error, self.code) {
|
||||
(Some(error), _) => Some(error.clone()),
|
||||
(None, Some(0)) => None,
|
||||
(None, Some(code)) => Some(format!("Exit code {code}")),
|
||||
(None, None) => Some("Terminated".into()),
|
||||
};
|
||||
if let Some(end) = end {
|
||||
if !text.is_empty() {
|
||||
text.push('\n');
|
||||
}
|
||||
text.push_str(&end);
|
||||
}
|
||||
text
|
||||
}
|
||||
|
||||
/// The block that goes to the agent ahead of the next message.
|
||||
pub fn context(&self, command: &str) -> String {
|
||||
let mut stderr = self.stderr.trim_end().to_owned();
|
||||
if let Some(error) = &self.error {
|
||||
if !stderr.is_empty() {
|
||||
stderr.push('\n');
|
||||
}
|
||||
stderr.push_str(error);
|
||||
} else if let Some(code) = self.code.filter(|c| *c != 0) {
|
||||
if !stderr.is_empty() {
|
||||
stderr.push('\n');
|
||||
}
|
||||
stderr.push_str(&format!("Exit code {code}"));
|
||||
}
|
||||
format!(
|
||||
"<bash-input>{command}</bash-input>\n<bash-stdout>{}</bash-stdout><bash-stderr>{stderr}</bash-stderr>",
|
||||
self.stdout.trim_end()
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs `command` with the user's shell in `cwd` until it ends or `cancel` stops it.
|
||||
pub(crate) async fn run(command: &str, cwd: &Path, cancel: &CancellationToken) -> Ran {
|
||||
let mut cmd = shell(command);
|
||||
ide_core::process::prepare(cmd.as_std_mut());
|
||||
cmd.current_dir(cwd).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped()).kill_on_drop(true);
|
||||
let mut child = match cmd.spawn() {
|
||||
Ok(child) => child,
|
||||
Err(e) => return Ran { error: Some(format!("Cannot run it: {e}")), ..Ran::default() },
|
||||
};
|
||||
let (Some(mut out), Some(mut err)) = (child.stdout.take(), child.stderr.take()) else {
|
||||
return Ran { error: Some("Cannot read its output".into()), ..Ran::default() };
|
||||
};
|
||||
let finished = async move {
|
||||
let (mut stdout, mut stderr) = (Vec::new(), Vec::new());
|
||||
let _ = tokio::join!(out.read_to_end(&mut stdout), err.read_to_end(&mut stderr));
|
||||
let code = child.wait().await.ok().and_then(|s| s.code());
|
||||
Ran { code, stdout: tail(&stdout), stderr: tail(&stderr), error: None }
|
||||
};
|
||||
tokio::select! {
|
||||
ran = finished => ran,
|
||||
// Dropping the child kills it.
|
||||
() = cancel.cancelled() => Ran { error: Some("Stopped".into()), ..Ran::default() },
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
fn shell(command: &str) -> Command {
|
||||
let shell = std::env::var("SHELL").ok().filter(|s| !s.trim().is_empty()).unwrap_or_else(|| "/bin/sh".into());
|
||||
let mut cmd = Command::new(shell);
|
||||
cmd.arg("-c").arg(command);
|
||||
cmd
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn shell(command: &str) -> Command {
|
||||
let mut cmd = Command::new(std::env::var("COMSPEC").unwrap_or_else(|_| "cmd.exe".into()));
|
||||
// `/S /C "…"` runs the line as typed: cmd strips only the outer quotes.
|
||||
cmd.raw_arg("/D /S /C \"").raw_arg(command).raw_arg("\"");
|
||||
cmd
|
||||
}
|
||||
|
||||
fn tail(bytes: &[u8]) -> String {
|
||||
let text = String::from_utf8_lossy(bytes);
|
||||
if text.len() <= MAX_STREAM {
|
||||
return text.into_owned();
|
||||
}
|
||||
let mut cut = text.len() - MAX_STREAM;
|
||||
while !text.is_char_boundary(cut) {
|
||||
cut += 1;
|
||||
}
|
||||
format!("…{}", &text[cut..])
|
||||
}
|
||||
|
||||
#[cfg(all(test, not(windows)))]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn runs_in_the_folder_and_reports_output_and_exit_code() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
std::fs::write(dir.path().join("marker.txt"), "").unwrap();
|
||||
let ran = run("ls; echo oops >&2; exit 3", dir.path(), &CancellationToken::new()).await;
|
||||
assert_eq!(ran.code, Some(3));
|
||||
assert_eq!(ran.stdout.trim(), "marker.txt");
|
||||
assert_eq!(ran.stderr.trim(), "oops");
|
||||
assert_eq!(ran.shown(), "marker.txt\noops\nExit code 3");
|
||||
assert_eq!(
|
||||
ran.context("ls"),
|
||||
"<bash-input>ls</bash-input>\n<bash-stdout>marker.txt</bash-stdout><bash-stderr>oops\nExit code 3</bash-stderr>"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_stopped_command_is_killed() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let cancel = CancellationToken::new();
|
||||
let stop = cancel.clone();
|
||||
tokio::spawn(async move {
|
||||
tokio::time::sleep(std::time::Duration::from_millis(200)).await;
|
||||
stop.cancel();
|
||||
});
|
||||
let started = std::time::Instant::now();
|
||||
let ran = run("sleep 30", dir.path(), &cancel).await;
|
||||
assert!(started.elapsed() < std::time::Duration::from_secs(5));
|
||||
assert_eq!(ran.shown(), "Stopped");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn long_output_keeps_its_tail() {
|
||||
let long = "x".repeat(MAX_STREAM + 10) + "end";
|
||||
let kept = tail(long.as_bytes());
|
||||
assert!(kept.starts_with('…') && kept.ends_with("end"));
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
+14
-1235
File diff suppressed because it is too large.
Load diff
+498
-2089
File diff suppressed because it is too large.
Load diff
@@ -1,6 +1,6 @@
|
||||
//! Folds ACP `session/update` notifications into a task's entries.
|
||||
|
||||
use crate::model::{AgentEntry, AgentImage, AgentPlanItem, AgentSubagentStatus, AgentToolDiff, AgentToolStatus};
|
||||
use crate::model::{AgentEntry, AgentPlanItem, AgentSubagentStatus, AgentToolDiff, AgentToolStatus};
|
||||
use ide_core::IpcPath;
|
||||
use serde_json::Value;
|
||||
use std::collections::HashMap;
|
||||
@@ -8,9 +8,6 @@ use std::collections::HashMap;
|
||||
/// Tool output kept per call; longer output keeps its tail.
|
||||
const MAX_OUTPUT: usize = 64 * 1024;
|
||||
|
||||
/// Image files a read tool names that are shown when it reports none itself.
|
||||
const MAX_READ_IMAGES: usize = 4;
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Timeline {
|
||||
pub entries: Vec<AgentEntry>,
|
||||
@@ -57,23 +54,6 @@ impl Timeline {
|
||||
let mut out = Applied::default();
|
||||
let kind = update.get("sessionUpdate").and_then(Value::as_str).unwrap_or_default();
|
||||
match kind {
|
||||
"user_question" => {
|
||||
let id = str_field(update, "id");
|
||||
let Ok(questions) = serde_json::from_value::<Vec<crate::model::AgentQuestion>>(
|
||||
update.get("questions").cloned().unwrap_or(Value::Null),
|
||||
) else {
|
||||
return out;
|
||||
};
|
||||
if id.is_empty()
|
||||
|| questions.is_empty()
|
||||
|| self.entries.iter().any(|e| matches!(e, AgentEntry::Question { id: known, .. } if known == &id))
|
||||
{
|
||||
return out;
|
||||
}
|
||||
let index =
|
||||
self.push(AgentEntry::Question { id, title: str_field(update, "title"), questions, chosen: None });
|
||||
out.changed.push(index);
|
||||
}
|
||||
"agent_message_chunk" | "agent_thought_chunk" => {
|
||||
let Some(text) = content_text(update.get("content")) else { return out };
|
||||
out.changed.push(self.append_text(kind == "agent_thought_chunk", &text));
|
||||
@@ -87,10 +67,7 @@ impl Timeline {
|
||||
status: tool_status(update.get("status")).unwrap_or(AgentToolStatus::Pending),
|
||||
locations: locations(update.get("locations")),
|
||||
output: None,
|
||||
images: Vec::new(),
|
||||
diffs: Vec::new(),
|
||||
started_ms: Some(crate::now_ms()),
|
||||
ended_ms: None,
|
||||
};
|
||||
let index = match self.tools.get(&id) {
|
||||
Some(&i) => {
|
||||
@@ -140,22 +117,17 @@ impl Timeline {
|
||||
fn append_text(&mut self, thought: bool, text: &str) -> usize {
|
||||
match self.entries.last_mut() {
|
||||
Some(AgentEntry::Agent { text: t }) if !thought => t.push_str(text),
|
||||
Some(AgentEntry::Thought { text: t, .. }) if thought => t.push_str(text),
|
||||
Some(AgentEntry::Thought { text: t }) if thought => t.push_str(text),
|
||||
_ => {
|
||||
let text = text.to_owned();
|
||||
return self.push(if thought {
|
||||
AgentEntry::Thought { text, started_ms: Some(crate::now_ms()) }
|
||||
} else {
|
||||
AgentEntry::Agent { text }
|
||||
});
|
||||
return self.push(if thought { AgentEntry::Thought { text } } else { AgentEntry::Agent { text } });
|
||||
}
|
||||
}
|
||||
self.entries.len() - 1
|
||||
}
|
||||
|
||||
fn merge_tool(&mut self, index: usize, update: &Value) {
|
||||
let AgentEntry::Tool { title, kind, status, locations: locs, output, images, diffs, ended_ms, .. } =
|
||||
&mut self.entries[index]
|
||||
let AgentEntry::Tool { title, kind, status, locations: locs, output, diffs, .. } = &mut self.entries[index]
|
||||
else {
|
||||
return;
|
||||
};
|
||||
@@ -167,24 +139,37 @@ impl Timeline {
|
||||
}
|
||||
if let Some(s) = tool_status(update.get("status")) {
|
||||
*status = s;
|
||||
if matches!(s, AgentToolStatus::Completed | AgentToolStatus::Failed) && ended_ms.is_none() {
|
||||
*ended_ms = Some(crate::now_ms());
|
||||
}
|
||||
}
|
||||
if update.get("locations").is_some_and(Value::is_array) {
|
||||
*locs = locations(update.get("locations"));
|
||||
}
|
||||
if let Some(content) = update.get("content").and_then(Value::as_array) {
|
||||
merge_content(content, output, images, diffs);
|
||||
let Some(content) = update.get("content").and_then(Value::as_array) else { return };
|
||||
let mut text = String::new();
|
||||
let mut new_diffs = Vec::new();
|
||||
for item in content {
|
||||
match item.get("type").and_then(Value::as_str) {
|
||||
Some("content") => {
|
||||
if let Some(t) = content_text(item.get("content")) {
|
||||
if !text.is_empty() {
|
||||
text.push('\n');
|
||||
}
|
||||
text.push_str(&t);
|
||||
}
|
||||
}
|
||||
Some("diff") => {
|
||||
let old = item.get("oldText").and_then(Value::as_str).unwrap_or_default();
|
||||
let new = item.get("newText").and_then(Value::as_str).unwrap_or_default();
|
||||
let (added, removed) = line_stats(old, new);
|
||||
new_diffs.push(AgentToolDiff { path: IpcPath(str_field(item, "path").into()), added, removed });
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
// Agents that only name the image a read tool opened (Cursor): show the file itself.
|
||||
if *status == AgentToolStatus::Completed && kind == "read" && images.is_empty() {
|
||||
images.extend(
|
||||
locs.iter()
|
||||
.filter(|p| p.0.is_absolute())
|
||||
.take(MAX_READ_IMAGES)
|
||||
.filter_map(|p| crate::images::from_file(&p.0)),
|
||||
);
|
||||
if !text.is_empty() {
|
||||
*output = Some(tail(text));
|
||||
}
|
||||
if !new_diffs.is_empty() {
|
||||
*diffs = new_diffs;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -351,54 +336,6 @@ fn subagent_status(state: &Value) -> Option<(AgentSubagentStatus, Option<String>
|
||||
})
|
||||
}
|
||||
|
||||
/// Folds a tool update's content into its output, diffs and images.
|
||||
fn merge_content(
|
||||
content: &[Value],
|
||||
output: &mut Option<String>,
|
||||
images: &mut Vec<AgentImage>,
|
||||
diffs: &mut Vec<AgentToolDiff>,
|
||||
) {
|
||||
let mut text = String::new();
|
||||
let mut new_diffs = Vec::new();
|
||||
let mut new_images = Vec::new();
|
||||
for item in content {
|
||||
match item.get("type").and_then(Value::as_str) {
|
||||
Some("content") => {
|
||||
let content = item.get("content");
|
||||
if let Some(image) = content.and_then(crate::images::from_content) {
|
||||
new_images.push(image);
|
||||
} else if let Some(t) = content_text(content) {
|
||||
if !text.is_empty() {
|
||||
text.push('\n');
|
||||
}
|
||||
text.push_str(&t);
|
||||
}
|
||||
}
|
||||
Some("diff") => {
|
||||
let old = item.get("oldText").and_then(Value::as_str).unwrap_or_default();
|
||||
let new = item.get("newText").and_then(Value::as_str).unwrap_or_default();
|
||||
let (added, removed) = line_stats(old, new);
|
||||
new_diffs.push(AgentToolDiff { path: IpcPath(str_field(item, "path").into()), added, removed });
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if !text.is_empty() {
|
||||
// The command a call announced (`$ cmd`) stays above the result that replaces it.
|
||||
let command = output.as_deref().and_then(|o| o.lines().next()).filter(|l| l.starts_with("$ "));
|
||||
if let Some(command) = command.filter(|c| !text.starts_with(c)) {
|
||||
text = format!("{command}\n{text}");
|
||||
}
|
||||
*output = Some(tail(text));
|
||||
}
|
||||
if !new_diffs.is_empty() {
|
||||
*diffs = new_diffs;
|
||||
}
|
||||
if !new_images.is_empty() {
|
||||
*images = new_images;
|
||||
}
|
||||
}
|
||||
|
||||
/// The text of a list of content blocks, one per line.
|
||||
pub(crate) fn blocks_text(content: Option<&Value>) -> String {
|
||||
let blocks = content.and_then(Value::as_array).map(Vec::as_slice).unwrap_or_default();
|
||||
@@ -449,94 +386,8 @@ fn tail(mut text: String) -> String {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::model::AgentImage;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn asynchronous_questions_survive_turn_end_restart_and_duplicate_notifications() {
|
||||
let mut t = Timeline::default();
|
||||
let update = json!({"sessionUpdate":"user_question","id":"call-1","title":"Which?",
|
||||
"questions":[{"answerKey":"q1","question":"Which?","options":[]}]});
|
||||
assert_eq!(t.apply(&update).changed, vec![0]);
|
||||
assert!(t.end_turn(None).is_empty());
|
||||
assert!(matches!(&t.entries[0], AgentEntry::Question { chosen: None, .. }));
|
||||
let saved = serde_json::to_string(&t.entries).unwrap();
|
||||
let mut t = Timeline::from_entries(serde_json::from_str(&saved).unwrap());
|
||||
assert!(t.apply(&update).changed.is_empty());
|
||||
assert_eq!(t.entries.len(), 1);
|
||||
if let AgentEntry::Question { chosen, .. } = &mut t.entries[0] {
|
||||
*chosen = Some("One".into());
|
||||
}
|
||||
assert!(t.apply(&update).changed.is_empty());
|
||||
assert!(matches!(&t.entries[0], AgentEntry::Question { chosen: Some(answer), .. } if answer == "One"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tool_images_survive_updates_text_truncation_and_serialization() {
|
||||
use base64::Engine;
|
||||
let mut t = Timeline::default();
|
||||
t.apply(&json!({"sessionUpdate": "tool_call", "toolCallId": "preview", "title": "Render", "kind": "execute"}));
|
||||
let mut old = serde_json::to_value(&t.entries[0]).unwrap();
|
||||
old.as_object_mut().unwrap().remove("images");
|
||||
let legacy: AgentEntry = serde_json::from_value(old).unwrap();
|
||||
assert!(matches!(legacy, AgentEntry::Tool { images, .. } if images.is_empty()));
|
||||
let data = base64::engine::general_purpose::STANDARD.encode(vec![0; MAX_OUTPUT]);
|
||||
let update = json!({"sessionUpdate": "tool_call_update", "toolCallId": "preview", "content": [
|
||||
{"type": "content", "content": {"type": "text", "text": "x".repeat(MAX_OUTPUT + 100)}},
|
||||
{"type": "content", "content": {"type": "image", "mimeType": "image/png", "data": data}}
|
||||
]});
|
||||
t.apply(&update);
|
||||
t.apply(&update);
|
||||
t.apply(&json!({"sessionUpdate": "tool_call_update", "toolCallId": "preview", "status": "completed"}));
|
||||
let AgentEntry::Tool { images, output, status, .. } = &t.entries[0] else { panic!() };
|
||||
assert_eq!(images, &vec![AgentImage { mime_type: "image/png".into(), data, name: None }]);
|
||||
assert!(output.as_ref().unwrap().len() < MAX_OUTPUT + 100);
|
||||
assert_eq!(*status, AgentToolStatus::Completed);
|
||||
let saved = serde_json::to_string(&t.entries[0]).unwrap();
|
||||
assert_eq!(serde_json::from_str::<AgentEntry>(&saved).unwrap(), t.entries[0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tool_images_come_from_linked_files_and_resource_blobs() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let png = dir.path().join("out.png");
|
||||
std::fs::write(&png, b"\x89PNG\r\n").unwrap();
|
||||
let mut t = Timeline::default();
|
||||
t.apply(&json!({"sessionUpdate": "tool_call", "toolCallId": "r", "title": "Read", "kind": "read"}));
|
||||
t.apply(&json!({"sessionUpdate": "tool_call_update", "toolCallId": "r", "content": [
|
||||
{"type": "content", "content": {"type": "text", "text": "Read the image"}},
|
||||
{"type": "content", "content": {"type": "resource_link", "uri": crate::file_uri(&png), "name": "out.png"}},
|
||||
{"type": "content", "content": {"type": "resource", "resource": {"uri": "mem:1", "mimeType": "image/gif", "blob": "R0lG"}}}
|
||||
]}));
|
||||
let AgentEntry::Tool { images, output, .. } = &t.entries[0] else { panic!() };
|
||||
let types: Vec<&str> = images.iter().map(|i| i.mime_type.as_str()).collect();
|
||||
assert_eq!(types, ["image/png", "image/gif"]);
|
||||
assert_eq!(output.as_deref(), Some("Read the image"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_completed_read_shows_the_image_file_it_names() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let png = dir.path().join("icon.png");
|
||||
std::fs::write(&png, b"\x89PNG\r\n").unwrap();
|
||||
let text = dir.path().join("a.rs");
|
||||
std::fs::write(&text, b"fn main() {}").unwrap();
|
||||
let mut t = Timeline::default();
|
||||
for (id, path) in [("img", &png), ("src", &text)] {
|
||||
t.apply(&json!({"sessionUpdate": "tool_call", "toolCallId": id, "title": "Read", "kind": "read",
|
||||
"locations": [{"path": path}]}));
|
||||
}
|
||||
let images = |t: &Timeline, i: usize| match &t.entries[i] {
|
||||
AgentEntry::Tool { images, .. } => images.len(),
|
||||
_ => panic!(),
|
||||
};
|
||||
assert_eq!(images(&t, 0), 0, "not before the read completes");
|
||||
for id in ["img", "src"] {
|
||||
t.apply(&json!({"sessionUpdate": "tool_call_update", "toolCallId": id, "status": "completed"}));
|
||||
}
|
||||
assert_eq!((images(&t, 0), images(&t, 1)), (1, 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chunks_merge_into_one_message_until_another_entry_comes() {
|
||||
let mut t = Timeline::default();
|
||||
@@ -545,14 +396,11 @@ mod tests {
|
||||
assert_eq!(t.apply(&chunk("lo")).changed, vec![0]);
|
||||
t.apply(&json!({"sessionUpdate": "agent_thought_chunk", "content": {"type": "text", "text": "hmm"}}));
|
||||
t.apply(&chunk("again"));
|
||||
// The thought's start is the clock's: it is there, and the rest compares exactly.
|
||||
let AgentEntry::Thought { started_ms, .. } = &mut t.entries[1] else { panic!("{:?}", t.entries) };
|
||||
assert!(started_ms.take().is_some());
|
||||
assert_eq!(
|
||||
t.entries,
|
||||
vec![
|
||||
AgentEntry::Agent { text: "Hello".into() },
|
||||
AgentEntry::Thought { text: "hmm".into(), started_ms: None },
|
||||
AgentEntry::Thought { text: "hmm".into() },
|
||||
AgentEntry::Agent { text: "again".into() },
|
||||
]
|
||||
);
|
||||
@@ -644,25 +492,6 @@ mod tests {
|
||||
assert!(matches!(t.entries[2], AgentEntry::User { done_ms: None, .. }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_hermes_terminal_call_keeps_its_command_and_times() {
|
||||
let text = |t: &str| serde_json::json!([{"type": "content", "content": {"type": "text", "text": t}}]);
|
||||
let mut t = Timeline::default();
|
||||
t.apply(&serde_json::json!({"sessionUpdate": "tool_call", "toolCallId": "tc-0b98b5e30a28",
|
||||
"kind": "execute", "title": "terminal: echo ok + 2 commands", "locations": [],
|
||||
"content": text("$ echo ok >> notes.txt && wc -l notes.txt")}));
|
||||
let AgentEntry::Tool { started_ms, ended_ms, .. } = &t.entries[0] else { panic!() };
|
||||
assert!(started_ms.is_some() && ended_ms.is_none());
|
||||
t.apply(&serde_json::json!({"sessionUpdate": "tool_call_update", "toolCallId": "tc-0b98b5e30a28",
|
||||
"kind": "execute", "status": "completed",
|
||||
"content": text("terminal result\n- **output:** 3 notes.txt\n- **exit_code:** 0")}));
|
||||
let AgentEntry::Tool { output, status, ended_ms, .. } = &t.entries[0] else { panic!() };
|
||||
assert_eq!(*status, AgentToolStatus::Completed);
|
||||
assert!(ended_ms.is_some());
|
||||
let expected = "$ echo ok >> notes.txt && wc -l notes.txt\nterminal result\n- **output:** 3 notes.txt\n";
|
||||
assert_eq!(output.as_deref(), Some(format!("{expected}- **exit_code:** 0").as_str()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn long_output_keeps_its_tail() {
|
||||
let s = tail("é".repeat(MAX_OUTPUT));
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
use crate::model::{AgentChange, AgentChanges, AgentCommit};
|
||||
use ide_core::{IdeError, IdeResult, IpcPath};
|
||||
use ide_vcs::{ChangeKind, LogQuery, Repo};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::{Duration, UNIX_EPOCH};
|
||||
@@ -25,116 +24,6 @@ fn discover(path: &Path) -> IdeResult<Option<Repo>> {
|
||||
Ok(repo)
|
||||
}
|
||||
|
||||
/// The repositories of a project with nested ones (an own `.git` under the project root, not a
|
||||
/// submodule), with the folder their files are named from: the root of the repository holding
|
||||
/// `cwd`, else `cwd`. `None` when only the repository holding `cwd` (if any) is there.
|
||||
fn nested_repos(cwd: &Path) -> IdeResult<Option<(PathBuf, Vec<Repo>)>> {
|
||||
let Ok(cwd) = dunce::canonicalize(cwd) else { return Ok(None) };
|
||||
let found = ide_vcs::Repos::discover(&cwd, &|_| false)?;
|
||||
if found.all().iter().all(|r| cwd.starts_with(r.root())) {
|
||||
return Ok(None);
|
||||
}
|
||||
let base = found.all().iter().map(|r| r.root()).filter(|r| cwd.starts_with(r)).max().unwrap_or(&cwd).to_path_buf();
|
||||
let mut repos = Vec::new();
|
||||
for r in found.all() {
|
||||
repos.extend(discover(r.root())?);
|
||||
}
|
||||
Ok(Some((base, repos)))
|
||||
}
|
||||
|
||||
/// Whether the project at `cwd` holds repositories nested in it: its changes are each one's.
|
||||
pub(crate) fn spans_repos(cwd: &Path) -> bool {
|
||||
nested_repos(cwd).is_ok_and(|r| r.is_some())
|
||||
}
|
||||
|
||||
/// The repositories a turn's files are in, and the folder those files are named from.
|
||||
struct TurnRepos {
|
||||
base: PathBuf,
|
||||
repos: Vec<Repo>,
|
||||
/// The project holds nested repositories: each one's `HEAD` is recorded on its own.
|
||||
nested: bool,
|
||||
}
|
||||
|
||||
impl TurnRepos {
|
||||
fn of(cwd: &Path) -> IdeResult<Option<Self>> {
|
||||
if let Some((base, repos)) = nested_repos(cwd)? {
|
||||
return Ok(Some(Self { base, repos, nested: true }));
|
||||
}
|
||||
Ok(discover(cwd)?.map(|repo| Self { base: repo.root().to_path_buf(), repos: vec![repo], nested: false }))
|
||||
}
|
||||
|
||||
/// The innermost repository holding `path`.
|
||||
fn owner(&self, path: &Path) -> Option<&Repo> {
|
||||
owning_repo(&self.repos, path)
|
||||
}
|
||||
|
||||
/// `repo`'s `HEAD` as the turn `start` began.
|
||||
fn head_then<'a>(&self, start: &'a TurnStart, repo: &Repo) -> Option<&'a str> {
|
||||
if self.nested { start.heads.get(&root_key(repo.root())) } else { start.head.as_ref() }.map(String::as_str)
|
||||
}
|
||||
}
|
||||
|
||||
fn root_key(root: &Path) -> String {
|
||||
root.to_string_lossy().into_owned()
|
||||
}
|
||||
|
||||
fn owning_repo<'a>(repos: &'a [Repo], path: &Path) -> Option<&'a Repo> {
|
||||
repos.iter().filter(|r| path.starts_with(r.root())).max_by_key(|r| r.root().as_os_str().len())
|
||||
}
|
||||
|
||||
/// `path` as a task in `base` names it, if it is not in a repository nested below `repo` (that
|
||||
/// one lists it itself; to `repo` its folder is untracked).
|
||||
fn nested_rel(base: &Path, repo: &Repo, roots: &[PathBuf], path: &Path) -> Option<String> {
|
||||
let rel = path.strip_prefix(base).ok()?;
|
||||
if path.is_dir()
|
||||
|| roots.iter().any(|n| n.as_path() != repo.root() && n.starts_with(repo.root()) && path.starts_with(n))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
Some(rel.to_string_lossy().replace('\\', "/"))
|
||||
}
|
||||
|
||||
/// The uncommitted changes in every repository of the project, against each one's `HEAD`.
|
||||
fn nested_changes(base: &Path, repos: &[Repo], touched: Option<&BTreeSet<String>>) -> IdeResult<Vec<AgentChange>> {
|
||||
let roots: Vec<PathBuf> = repos.iter().map(|r| r.root().to_path_buf()).collect();
|
||||
// Match deletions too: find the owner by path components, not by opening the file.
|
||||
// Display paths use slash separators and lossy Unicode (see nested_rel). If a checkout's
|
||||
// name cannot round-trip from that representation, keep the full-read fallback.
|
||||
let owners = touched
|
||||
.filter(|_| {
|
||||
roots.iter().all(|root| {
|
||||
root.strip_prefix(base).is_ok_and(|rel| base.join(rel.to_string_lossy().replace('\\', "/")) == *root)
|
||||
})
|
||||
})
|
||||
.map(|paths| {
|
||||
paths.iter().filter_map(|rel| owning_repo(repos, &base.join(rel)).map(Repo::root)).collect::<BTreeSet<_>>()
|
||||
});
|
||||
let mut out: Vec<AgentChange> = Vec::new();
|
||||
for repo in repos {
|
||||
if owners.as_ref().is_some_and(|owners| !owners.contains(repo.root())) {
|
||||
continue;
|
||||
}
|
||||
let listed = match repo.head()?.1 {
|
||||
Some(head) => changes(repo.root(), &head)?,
|
||||
None => {
|
||||
repo.status()?.into_iter().filter(|s| s.path.is_file()).map(|s| added(s.path, s.rel_path)).collect()
|
||||
}
|
||||
};
|
||||
for mut c in listed {
|
||||
let Some(rel) = nested_rel(base, repo, &roots, &c.path.0) else { continue };
|
||||
if out.iter().any(|o| o.path == c.path) {
|
||||
continue;
|
||||
}
|
||||
c.rel_path = rel;
|
||||
c.old_path = None;
|
||||
c.repo = Some(IpcPath(repo.root().to_path_buf()));
|
||||
out.push(c);
|
||||
}
|
||||
}
|
||||
out.sort_by(|a, b| a.rel_path.cmp(&b.rel_path));
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn repo_at(path: &Path) -> IdeResult<Repo> {
|
||||
discover(path)?.ok_or_else(|| IdeError::unavailable(format!("{} is not in a git repository", path.display())))
|
||||
}
|
||||
@@ -148,9 +37,6 @@ pub(crate) fn head_of(path: &Path) -> IdeResult<(String, String)> {
|
||||
|
||||
/// `HEAD`'s commit in `cwd`, `None` outside a repository or before its first commit.
|
||||
pub(crate) fn head_commit(cwd: &Path) -> IdeResult<Option<String>> {
|
||||
if spans_repos(cwd) {
|
||||
return Ok(Some("HEAD".to_owned()));
|
||||
}
|
||||
match discover(cwd)? {
|
||||
Some(repo) => Ok(repo.head()?.1),
|
||||
None => Ok(None),
|
||||
@@ -240,7 +126,6 @@ pub(crate) fn changes(cwd: &Path, base: &str) -> IdeResult<Vec<AgentChange>> {
|
||||
added,
|
||||
removed,
|
||||
old_path: f.old_path,
|
||||
repo: None,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
@@ -257,9 +142,6 @@ pub(crate) fn changes(cwd: &Path, base: &str) -> IdeResult<Vec<AgentChange>> {
|
||||
/// Files renamed since `rev`, by their new repository-relative path: the old path, as a deletion
|
||||
/// to roll back along with the rename.
|
||||
pub(crate) fn rename_sources(cwd: &Path, rev: &str) -> IdeResult<BTreeMap<String, AgentChange>> {
|
||||
if spans_repos(cwd) {
|
||||
return Ok(BTreeMap::new());
|
||||
}
|
||||
let Some(repo) = discover(cwd)? else { return Ok(BTreeMap::new()) };
|
||||
let root = repo.root().to_path_buf();
|
||||
Ok(repo
|
||||
@@ -274,7 +156,6 @@ pub(crate) fn rename_sources(cwd: &Path, rev: &str) -> IdeResult<BTreeMap<String
|
||||
added: 0,
|
||||
removed: 0,
|
||||
old_path: None,
|
||||
repo: None,
|
||||
};
|
||||
Some((f.path, source))
|
||||
})
|
||||
@@ -283,7 +164,7 @@ pub(crate) fn rename_sources(cwd: &Path, rev: &str) -> IdeResult<BTreeMap<String
|
||||
|
||||
fn added(path: IpcPath, rel_path: String) -> AgentChange {
|
||||
let added = std::fs::read_to_string(&*path).map_or(0, |t| t.lines().count() as u32);
|
||||
AgentChange { path, rel_path, kind: ChangeKind::Added, added, removed: 0, old_path: None, repo: None }
|
||||
AgentChange { path, rel_path, kind: ChangeKind::Added, added, removed: 0, old_path: None }
|
||||
}
|
||||
|
||||
/// The commits from `base` (exclusive) to `head` (inclusive) in `cwd`, newest first, each
|
||||
@@ -319,7 +200,6 @@ pub(crate) fn commits(cwd: &Path, base: &str, head: &str) -> IdeResult<Vec<Agent
|
||||
added,
|
||||
removed,
|
||||
old_path: f.old_path,
|
||||
repo: None,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
@@ -382,30 +262,10 @@ impl TaskBase {
|
||||
}
|
||||
|
||||
/// The files the task changed, less those changed before it started and untouched since.
|
||||
pub(crate) fn changes(
|
||||
&self,
|
||||
before: &BTreeMap<String, Stamp>,
|
||||
touched: Option<&BTreeSet<String>>,
|
||||
) -> IdeResult<Vec<AgentChange>> {
|
||||
if touched.is_some_and(BTreeSet::is_empty) {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
Ok(made_by_task(self.read_changes(before, touched)?, touched))
|
||||
}
|
||||
|
||||
fn read_changes(
|
||||
&self,
|
||||
before: &BTreeMap<String, Stamp>,
|
||||
touched: Option<&BTreeSet<String>>,
|
||||
) -> IdeResult<Vec<AgentChange>> {
|
||||
pub(crate) fn changes(&self, before: &BTreeMap<String, Stamp>) -> IdeResult<Vec<AgentChange>> {
|
||||
let (cwd, start) = match self {
|
||||
Self::Worktree { cwd, base } => return Ok(without_untouched(changes(cwd, base)?, before)),
|
||||
Self::Local { cwd, start } => {
|
||||
if let Some((base, repos)) = nested_repos(cwd)? {
|
||||
return Ok(without_untouched(nested_changes(&base, &repos, touched)?, before));
|
||||
}
|
||||
(cwd, start.as_deref())
|
||||
}
|
||||
Self::Local { cwd, start } => (cwd, start.as_deref()),
|
||||
};
|
||||
let Some(repo) = discover(cwd)? else { return Ok(Vec::new()) };
|
||||
// What is uncommitted, as the Commit tool window lists it: commits made since the task
|
||||
@@ -463,9 +323,6 @@ impl TaskBase {
|
||||
/// reads cannot put a file in both lists.
|
||||
pub(crate) fn grouped_changes(&self, before: &BTreeMap<String, Stamp>) -> IdeResult<AgentChanges> {
|
||||
let cwd = self.cwd();
|
||||
if spans_repos(cwd) {
|
||||
return Ok(AgentChanges { uncommitted: self.changes(before, None)?, commits: Vec::new() });
|
||||
}
|
||||
let Some(repo) = discover(cwd)? else { return Ok(AgentChanges::default()) };
|
||||
let head = repo.head()?.1;
|
||||
let uncommitted = match &head {
|
||||
@@ -495,8 +352,6 @@ impl TaskBase {
|
||||
pub(crate) fn rev(&self) -> IdeResult<Option<String>> {
|
||||
let (cwd, start) = match self {
|
||||
Self::Worktree { base, .. } => return Ok(Some(base.clone())),
|
||||
// Each repository goes back to its own `HEAD`.
|
||||
Self::Local { cwd, .. } if spans_repos(cwd) => return Ok(Some("HEAD".to_owned())),
|
||||
Self::Local { cwd, start } => (cwd, start.as_deref()),
|
||||
};
|
||||
let Some(repo) = discover(cwd)? else { return Ok(None) };
|
||||
@@ -689,32 +544,8 @@ pub(crate) fn stamp(path: &Path) -> Stamp {
|
||||
pub(crate) fn snapshot(cwd: &Path) -> IdeResult<BTreeMap<String, Stamp>> {
|
||||
// Paths and stamps only: no diff and no line counts, which read every untracked file
|
||||
// and held up starting a task in a checkout with many of them.
|
||||
if let Some((base, repos)) = nested_repos(cwd)? {
|
||||
let roots: Vec<PathBuf> = repos.iter().map(|r| r.root().to_path_buf()).collect();
|
||||
let mut out = BTreeMap::new();
|
||||
for repo in &repos {
|
||||
for s in repo.status()? {
|
||||
if let Some(rel) = nested_rel(&base, repo, &roots, &s.path) {
|
||||
out.insert(rel, stamp(&s.path));
|
||||
}
|
||||
if let Some(old) = &s.renamed_from
|
||||
&& let Some(rel) = nested_rel(&base, repo, &roots, &repo.root().join(old))
|
||||
{
|
||||
out.entry(rel).or_insert(None);
|
||||
}
|
||||
}
|
||||
}
|
||||
return Ok(out);
|
||||
}
|
||||
let Some(repo) = Repo::discover(cwd)? else { return Ok(BTreeMap::new()) };
|
||||
let mut out = BTreeMap::new();
|
||||
for s in repo.status()? {
|
||||
out.insert(s.rel_path, stamp(&s.path));
|
||||
if let Some(old) = s.renamed_from {
|
||||
out.entry(old).or_insert(None);
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
Ok(repo.status()?.into_iter().map(|s| (s.rel_path, stamp(&s.path))).collect())
|
||||
}
|
||||
|
||||
/// The files whose state changed between two snapshots of a checkout: edited, new, deleted,
|
||||
@@ -755,16 +586,10 @@ fn saved_name(rel: &str) -> String {
|
||||
/// into `dir`, so rolling back the task's changes to them restores the user's own edits.
|
||||
/// Whether anything was saved.
|
||||
pub(crate) fn save_before(cwd: &Path, before: &BTreeMap<String, Stamp>, dir: &Path) -> IdeResult<bool> {
|
||||
let root = match nested_repos(cwd)? {
|
||||
Some((base, _)) => base,
|
||||
None => match Repo::discover(cwd)? {
|
||||
Some(repo) => repo.root().to_path_buf(),
|
||||
None => return Ok(false),
|
||||
},
|
||||
};
|
||||
let Some(repo) = Repo::discover(cwd)? else { return Ok(false) };
|
||||
let mut saved = false;
|
||||
for (rel, stamp) in before {
|
||||
let path = root.join(rel);
|
||||
let path = repo.root().join(rel);
|
||||
if stamp.is_none() || !std::fs::metadata(&path).is_ok_and(|m| m.is_file() && m.len() <= SAVED_MAX) {
|
||||
continue;
|
||||
}
|
||||
@@ -775,36 +600,6 @@ pub(crate) fn save_before(cwd: &Path, before: &BTreeMap<String, Stamp>, dir: &Pa
|
||||
Ok(saved)
|
||||
}
|
||||
|
||||
fn restore_content(
|
||||
cwd: &Path,
|
||||
rev: Option<&str>,
|
||||
change: &AgentChange,
|
||||
before: &BTreeMap<String, Stamp>,
|
||||
saved: Option<&Path>,
|
||||
) -> IdeResult<Option<Vec<u8>>> {
|
||||
match before.get(&change.rel_path) {
|
||||
Some(None) => Ok(None),
|
||||
Some(Some(_)) => {
|
||||
let copy =
|
||||
saved.map(|d| d.join(saved_name(&change.rel_path))).filter(|p| p.is_file()).ok_or_else(|| {
|
||||
IdeError::invalid(format!(
|
||||
"{} had changes of yours when the task started that weren't saved; roll it back in Git instead",
|
||||
change.rel_path
|
||||
))
|
||||
})?;
|
||||
Ok(Some(std::fs::read(copy)?))
|
||||
}
|
||||
None => match rev {
|
||||
Some(rev) => {
|
||||
let at = change.repo.as_ref().map_or(cwd, |r| r.0.as_path());
|
||||
let repo = Repo::discover(at)?.ok_or_else(|| IdeError::invalid("not in a git repository"))?;
|
||||
repo.file_bytes_at(&change.path.0, Some(rev))
|
||||
}
|
||||
None => Ok(None),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Rolls `change` back: to the copy saved when the task started when the file had changes
|
||||
/// then (`before`, `saved` holding the copies), otherwise to `rev` (removed when `rev` lacks
|
||||
/// it, or when there is no `rev`: the repository had no commits).
|
||||
@@ -815,39 +610,27 @@ pub(crate) fn restore(
|
||||
before: &BTreeMap<String, Stamp>,
|
||||
saved: Option<&Path>,
|
||||
) -> IdeResult<()> {
|
||||
put(&change.path.0, restore_content(cwd, rev, change, before, saved)?)
|
||||
}
|
||||
|
||||
/// The files the task changed since it started, with what to put back. Fails, changing
|
||||
/// nothing, when one can't be put back.
|
||||
pub(crate) fn plan_restore(
|
||||
at: &TaskBase,
|
||||
before: &BTreeMap<String, Stamp>,
|
||||
saved: Option<&Path>,
|
||||
touched: Option<&BTreeSet<String>>,
|
||||
) -> IdeResult<Vec<PutBack>> {
|
||||
let changes = made_by_task(at.changes(before, None)?, touched);
|
||||
let rev = at.rev()?;
|
||||
let sources = match rev.as_deref() {
|
||||
Some(rev) => rename_sources(at.cwd(), rev)?,
|
||||
None => Default::default(),
|
||||
};
|
||||
let mut seen = BTreeSet::new();
|
||||
let mut out = Vec::new();
|
||||
for change in &changes {
|
||||
for change in std::iter::once(change).chain(sources.get(&change.rel_path)) {
|
||||
if !seen.insert(change.rel_path.clone()) {
|
||||
continue;
|
||||
}
|
||||
let content = restore_content(at.cwd(), rev.as_deref(), change, before, saved)?;
|
||||
out.push(PutBack { rel: change.rel_path.clone(), path: change.path.0.clone(), content });
|
||||
let path = &change.path.0;
|
||||
let content = match before.get(&change.rel_path) {
|
||||
Some(None) => None,
|
||||
Some(Some(_)) => {
|
||||
let copy =
|
||||
saved.map(|d| d.join(saved_name(&change.rel_path))).filter(|p| p.is_file()).ok_or_else(|| {
|
||||
IdeError::invalid(format!(
|
||||
"{} had changes of yours when the task started that weren't saved; roll it back in Git instead",
|
||||
change.rel_path
|
||||
))
|
||||
})?;
|
||||
Some(std::fs::read(copy)?)
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Writes `content` to `path`, or removes the file when there is none.
|
||||
fn put(path: &Path, content: Option<Vec<u8>>) -> IdeResult<()> {
|
||||
None => match rev {
|
||||
Some(rev) => {
|
||||
let repo = Repo::discover(cwd)?.ok_or_else(|| IdeError::invalid("not in a git repository"))?;
|
||||
repo.file_bytes_at(path, Some(rev))?
|
||||
}
|
||||
None => None,
|
||||
},
|
||||
};
|
||||
match content {
|
||||
Some(bytes) => {
|
||||
if let Some(parent) = path.parent() {
|
||||
@@ -863,316 +646,8 @@ fn put(path: &Path, content: Option<Vec<u8>>) -> IdeResult<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The bytes of the copy of `rel` saved in `dir`, if there is one.
|
||||
pub(crate) fn saved_copy(dir: &Path, rel: &str) -> Option<Vec<u8>> {
|
||||
std::fs::read(dir.join(saved_name(rel))).ok()
|
||||
}
|
||||
|
||||
/// The checkout as one of the task's turns started: what that turn's changes are compared with
|
||||
/// and rolled back to. Recorded like the task's own start: `HEAD`, the files already changed,
|
||||
/// and copies of those.
|
||||
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub(crate) struct TurnStart {
|
||||
/// `HEAD` then (`None` outside a repository or before its first commit).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub head: Option<String>,
|
||||
/// With nested repositories, each one's `HEAD` then, by its root.
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub heads: BTreeMap<String, String>,
|
||||
/// The files already changed then, stamped.
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub before: BTreeMap<String, Stamp>,
|
||||
/// The files among `before` with a copy in the task's turn folder.
|
||||
#[serde(default, skip_serializing_if = "BTreeSet::is_empty")]
|
||||
pub saved: BTreeSet<String>,
|
||||
/// The files that changed while the turn ran, recorded as it ended (`None` while it runs).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub changed: Option<BTreeSet<String>>,
|
||||
/// The copies are named by file and stamp, so the turns share them; the turn recorded
|
||||
/// before that named them by file alone.
|
||||
#[serde(default, skip_serializing_if = "is_false")]
|
||||
pub stamped: bool,
|
||||
}
|
||||
|
||||
fn is_false(b: &bool) -> bool {
|
||||
!*b
|
||||
}
|
||||
|
||||
/// The name of the copy of `rel` as stamped `stamp`: the same while the file is unchanged.
|
||||
fn turn_copy_name(rel: &str, stamp: &Stamp) -> String {
|
||||
let mut hasher = blake3::Hasher::new();
|
||||
hasher.update(rel.as_bytes());
|
||||
hasher.update(&[0]);
|
||||
if let Some((len, modified)) = stamp {
|
||||
hasher.update(&[1]);
|
||||
hasher.update(&len.to_le_bytes());
|
||||
hasher.update(&modified.to_le_bytes());
|
||||
}
|
||||
let hex = hasher.finalize().to_hex();
|
||||
format!("t{}", &hex[..16])
|
||||
}
|
||||
|
||||
impl TurnStart {
|
||||
/// The name of the copy saved of `rel` as the turn began.
|
||||
fn copy_name(&self, rel: &str) -> Option<String> {
|
||||
if !self.stamped {
|
||||
return Some(saved_name(rel));
|
||||
}
|
||||
Some(turn_copy_name(rel, self.before.get(rel)?))
|
||||
}
|
||||
}
|
||||
|
||||
/// Records the checkout at `cwd` as a turn starts, with copies of its changed files in `dir`.
|
||||
/// A copy an earlier turn saved of a file unchanged since is used rather than made again, so
|
||||
/// starting a turn copies little more than what the turn before it changed.
|
||||
pub(crate) fn start_turn(cwd: &Path, dir: &Path) -> IdeResult<TurnStart> {
|
||||
let Some(at) = TurnRepos::of(cwd)? else { return Ok(TurnStart { stamped: true, ..Default::default() }) };
|
||||
let mut heads = BTreeMap::new();
|
||||
let head = if at.nested {
|
||||
for repo in &at.repos {
|
||||
heads.extend(repo.head()?.1.map(|h| (root_key(repo.root()), h)));
|
||||
}
|
||||
None
|
||||
} else {
|
||||
at.repos[0].head()?.1
|
||||
};
|
||||
// As the turn's end is read, so the two compare.
|
||||
let before = snapshot(cwd)?;
|
||||
let mut saved = BTreeSet::new();
|
||||
for (rel, stamp) in &before {
|
||||
let path = at.base.join(rel);
|
||||
if stamp.is_none() || !std::fs::metadata(&path).is_ok_and(|m| m.is_file() && m.len() <= SAVED_MAX) {
|
||||
continue;
|
||||
}
|
||||
let copy = dir.join(turn_copy_name(rel, stamp));
|
||||
if copy.is_file() {
|
||||
saved.insert(rel.clone());
|
||||
continue;
|
||||
}
|
||||
std::fs::create_dir_all(dir)?;
|
||||
// One that can't be copied is listed but can't be rolled back, as a large one.
|
||||
if std::fs::copy(&path, ©).is_ok() {
|
||||
saved.insert(rel.clone());
|
||||
}
|
||||
}
|
||||
Ok(TurnStart { head, heads, before, saved, changed: None, stamped: true })
|
||||
}
|
||||
|
||||
/// Removes the copies in `dir` that none of `turns` uses any more.
|
||||
pub(crate) fn prune_turn_copies<'a>(dir: &Path, turns: impl IntoIterator<Item = &'a TurnStart>) {
|
||||
let used: BTreeSet<String> =
|
||||
turns.into_iter().flat_map(|t| t.saved.iter().filter_map(move |rel| t.copy_name(rel))).collect();
|
||||
let Ok(read) = std::fs::read_dir(dir) else { return };
|
||||
for entry in read.flatten() {
|
||||
if !used.contains(&*entry.file_name().to_string_lossy()) {
|
||||
let _ = std::fs::remove_file(entry.path());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A file to put back as it was.
|
||||
pub(crate) struct PutBack {
|
||||
/// Relative to the checkout, as the task names it.
|
||||
pub rel: String,
|
||||
pub path: PathBuf,
|
||||
/// `None`: there was no file.
|
||||
pub content: Option<Vec<u8>>,
|
||||
}
|
||||
|
||||
/// The files among `rels` that differ from how they were as the turn `start` began, with what
|
||||
/// to put back. Fails, changing nothing, when one can't be put back.
|
||||
pub(crate) fn rewind(cwd: &Path, start: &TurnStart, dir: &Path, rels: &BTreeSet<String>) -> IdeResult<Vec<PutBack>> {
|
||||
let Some(at) = TurnRepos::of(cwd)? else { return Ok(Vec::new()) };
|
||||
let mut lower_counts: BTreeMap<String, usize> = BTreeMap::new();
|
||||
for rel in rels {
|
||||
*lower_counts.entry(rel.to_lowercase()).or_default() += 1;
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
for rel in rels {
|
||||
let path = at.base.join(rel);
|
||||
// A folder (a submodule, say) has nothing to put back.
|
||||
if path.is_dir() {
|
||||
continue;
|
||||
}
|
||||
let then = at_turn_start(&at, rel, start, dir)?;
|
||||
// On a case-insensitive disk, `existing(&path)` can read a case-only rename's new name;
|
||||
// keep the write so `put_back` deletes the new name and recreates the old one.
|
||||
let case_collision = lower_counts.get(&rel.to_lowercase()).is_some_and(|&n| n > 1);
|
||||
if !case_collision && existing(&path).is_some_and(|now| now == then) {
|
||||
continue;
|
||||
}
|
||||
out.push(PutBack { rel: rel.clone(), path, content: then });
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Writes what `rewind` or `plan_restore` planned, returning the files back to their saved
|
||||
/// pre-task copy so `before` can be restamped.
|
||||
pub(crate) fn put_back(
|
||||
mut planned: Vec<PutBack>,
|
||||
before: &BTreeMap<String, Stamp>,
|
||||
saved: Option<&Path>,
|
||||
) -> IdeResult<Vec<(String, Stamp)>> {
|
||||
// Removals first so a case-only rename on a case-insensitive disk ends at its old name.
|
||||
planned.sort_by_key(|f| f.content.is_some());
|
||||
let mut restamped = Vec::new();
|
||||
for file in planned {
|
||||
let should_restamp = matches!(before.get(&file.rel), Some(Some(_)))
|
||||
&& file
|
||||
.content
|
||||
.as_deref()
|
||||
.is_some_and(|bytes| saved.and_then(|d| saved_copy(d, &file.rel)).as_deref() == Some(bytes));
|
||||
put(&file.path, file.content)?;
|
||||
if should_restamp {
|
||||
restamped.push((file.rel, stamp(&file.path)));
|
||||
}
|
||||
}
|
||||
Ok(restamped)
|
||||
}
|
||||
|
||||
/// The files that changed in `cwd` since the turn `start` began: in the working tree (as
|
||||
/// `changed_between` sees them), and in the commits made since.
|
||||
pub(crate) fn changed_in_turn(cwd: &Path, start: &TurnStart) -> IdeResult<(Vec<String>, BTreeSet<String>)> {
|
||||
let end = snapshot(cwd)?;
|
||||
let worktree = changed_between(&start.before, &end);
|
||||
let mut all: BTreeSet<String> = worktree.iter().cloned().collect();
|
||||
let Some(at) = TurnRepos::of(cwd)? else { return Ok((worktree, all)) };
|
||||
for repo in &at.repos {
|
||||
let (Some(from), Some(to)) = (at.head_then(start, repo), repo.head()?.1) else { continue };
|
||||
if from == to {
|
||||
continue;
|
||||
}
|
||||
// Named from the base, as the working tree's files are.
|
||||
let prefix = rel_in(&at.base, repo.root())?;
|
||||
let named = |rel: String| if prefix.is_empty() { rel } else { format!("{prefix}/{rel}") };
|
||||
for f in repo.diff_revisions(from, &to)? {
|
||||
all.extend(f.old_path.map(named));
|
||||
all.insert(named(f.path));
|
||||
}
|
||||
}
|
||||
Ok((worktree, all))
|
||||
}
|
||||
|
||||
/// The content of `rel` as the turn `start` began (`None`: no file), its copies in `dir`.
|
||||
fn at_turn_start(at: &TurnRepos, rel: &str, start: &TurnStart, dir: &Path) -> IdeResult<Option<Vec<u8>>> {
|
||||
match start.before.get(rel) {
|
||||
Some(None) => Ok(None),
|
||||
Some(Some(_)) => match start
|
||||
.saved
|
||||
.contains(rel)
|
||||
.then(|| start.copy_name(rel).and_then(|name| std::fs::read(dir.join(name)).ok()))
|
||||
.flatten()
|
||||
{
|
||||
Some(bytes) => Ok(Some(bytes)),
|
||||
None => Err(IdeError::invalid(format!(
|
||||
"{rel} had changes when the turn started that weren't saved; roll it back in Git instead"
|
||||
))),
|
||||
},
|
||||
None => {
|
||||
let path = at.base.join(rel);
|
||||
match at.owner(&path).and_then(|repo| Some((repo, at.head_then(start, repo)?))) {
|
||||
Some((repo, head)) => repo.file_bytes_at(&path, Some(head)),
|
||||
None => Ok(None),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Added and removed lines from `old` to `new`; none for binary content.
|
||||
fn line_stats(old: Option<&[u8]>, new: Option<&[u8]>) -> (u32, u32) {
|
||||
if [old, new].iter().flatten().any(|b| b.contains(&0)) {
|
||||
return (0, 0);
|
||||
}
|
||||
let text = |b: Option<&[u8]>| b.map(|b| String::from_utf8_lossy(b).into_owned()).unwrap_or_default();
|
||||
ide_vcs::diff_hunks(&text(old), &text(new))
|
||||
.iter()
|
||||
.fold((0, 0), |(added, removed), h| (added + h.lines, removed + h.old_lines))
|
||||
}
|
||||
|
||||
/// The files among `changed` that differ from how they were as the turn `start` began.
|
||||
pub(crate) fn turn_changes(
|
||||
cwd: &Path,
|
||||
start: &TurnStart,
|
||||
dir: &Path,
|
||||
changed: &BTreeSet<String>,
|
||||
) -> IdeResult<Vec<AgentChange>> {
|
||||
let Some(at) = TurnRepos::of(cwd)? else { return Ok(Vec::new()) };
|
||||
let mut out = Vec::new();
|
||||
for rel in changed {
|
||||
let path = at.base.join(rel);
|
||||
// A folder (a submodule, say) or a file that can't be read has nothing to compare.
|
||||
let Some(now) = existing(&path) else { continue };
|
||||
let (kind, (added, removed)) = match at_turn_start(&at, rel, start, dir) {
|
||||
Ok(then) if then == now => continue,
|
||||
Ok(then) => {
|
||||
let kind = match (&then, &now) {
|
||||
(None, _) => ChangeKind::Added,
|
||||
(_, None) => ChangeKind::Deleted,
|
||||
_ => ChangeKind::Modified,
|
||||
};
|
||||
(kind, line_stats(then.as_deref(), now.as_deref()))
|
||||
}
|
||||
// Its start wasn't saved: listed, without counts.
|
||||
Err(_) => (ChangeKind::Modified, (0, 0)),
|
||||
};
|
||||
out.push(AgentChange {
|
||||
rel_path: rel.clone(),
|
||||
kind,
|
||||
added,
|
||||
removed,
|
||||
old_path: None,
|
||||
repo: at.nested.then(|| at.owner(&path).map(|r| IpcPath(r.root().to_path_buf()))).flatten(),
|
||||
path: IpcPath(path),
|
||||
});
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The text of `path` as the turn `start` began, `None` when there was no file.
|
||||
pub(crate) fn turn_text(cwd: &Path, path: &Path, start: &TurnStart, dir: &Path) -> IdeResult<Option<String>> {
|
||||
let Some(at) = TurnRepos::of(cwd)? else { return Ok(None) };
|
||||
let rel = rel_in(&at.base, path)?;
|
||||
if !start.before.contains_key(&rel)
|
||||
&& let Some(head) = at.owner(&at.base.join(&rel)).and_then(|repo| at.head_then(start, repo))
|
||||
{
|
||||
return file_at(cwd, path, head);
|
||||
}
|
||||
let Some(bytes) = at_turn_start(&at, &rel, start, dir)? else { return Ok(None) };
|
||||
let encoding = match ide_vfs::load_text(path) {
|
||||
Ok(loaded) => encoding_rs::Encoding::for_label(loaded.encoding.as_bytes()).unwrap_or(encoding_rs::UTF_8),
|
||||
Err(_) => ide_vfs::detect_encoding(&bytes, None),
|
||||
};
|
||||
Ok(Some(encoding.decode(&bytes).0.into_owned()))
|
||||
}
|
||||
|
||||
/// `path` relative to the repository at `root`, with `/` separators.
|
||||
fn rel_in(root: &Path, path: &Path) -> IdeResult<String> {
|
||||
let rel = path
|
||||
.strip_prefix(root)
|
||||
.map(Path::to_path_buf)
|
||||
.ok()
|
||||
.or_else(|| {
|
||||
// Another spelling of the same place (a link, `/var` and `/private/var`); the file may be gone.
|
||||
let root = dunce::canonicalize(root).ok()?;
|
||||
let parent = dunce::canonicalize(path.parent()?).ok()?;
|
||||
Some(parent.strip_prefix(&root).ok()?.join(path.file_name()?))
|
||||
})
|
||||
.ok_or_else(|| IdeError::invalid(format!("{} is outside the repository", path.display())))?;
|
||||
Ok(rel.components().map(|c| c.as_os_str().to_string_lossy()).collect::<Vec<_>>().join("/"))
|
||||
}
|
||||
|
||||
/// Puts `change` back as it was when the turn `start` began.
|
||||
pub(crate) fn restore_turn(cwd: &Path, start: &TurnStart, dir: &Path, change: &AgentChange) -> IdeResult<()> {
|
||||
let at = TurnRepos::of(cwd)?
|
||||
.ok_or_else(|| IdeError::unavailable(format!("{} is not in a git repository", cwd.display())))?;
|
||||
put(&change.path.0, at_turn_start(&at, &change.rel_path, start, dir)?)
|
||||
}
|
||||
|
||||
pub(crate) fn file_at(cwd: &Path, path: &Path, rev: &str) -> IdeResult<Option<String>> {
|
||||
// With nested repositories, the file's own one.
|
||||
let at = if spans_repos(cwd) { path.parent().unwrap_or(cwd) } else { cwd };
|
||||
let Some(repo) = discover(at)? else { return Ok(None) };
|
||||
let Some(repo) = discover(cwd)? else { return Ok(None) };
|
||||
let encoding = match ide_vfs::load_text(path) {
|
||||
Ok(loaded) => encoding_rs::Encoding::for_label(loaded.encoding.as_bytes()).unwrap_or(encoding_rs::UTF_8),
|
||||
Err(_) => ide_vfs::detect_encoding(&repo.file_bytes_at(path, Some(rev))?.unwrap_or_default(), None),
|
||||
@@ -1301,111 +776,6 @@ mod tests {
|
||||
assert!(ok, "git {args:?}");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn attributed_changes_only_diff_the_owning_checkout() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap().join("project");
|
||||
for n in 0..15 {
|
||||
let repo = root.join(format!("repo{n:02}"));
|
||||
std::fs::create_dir_all(&repo).unwrap();
|
||||
git(&repo, &["init", "-q", "-b", "main"]);
|
||||
std::fs::write(repo.join("a.txt"), "one\n").unwrap();
|
||||
git(&repo, &["add", "a.txt"]);
|
||||
git(&repo, &["commit", "-q", "-m", "initial"]);
|
||||
std::fs::write(repo.join("a.txt"), "two\n").unwrap();
|
||||
}
|
||||
// Count real Git diff processes, not walks to discover the topology.
|
||||
let git = tmp.path().join("count-git");
|
||||
let log = tmp.path().join("count-git.log");
|
||||
std::fs::write(
|
||||
&git,
|
||||
"#!/bin/sh\nfor arg do\nif [ \"$arg\" = diff ]; then pwd >> \"$0.log\"; break; fi\ndone\nexec git \"$@\"\n",
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::set_permissions(&git, std::fs::Permissions::from_mode(0o700)).unwrap();
|
||||
let at = TaskBase::Local { cwd: root, start: None };
|
||||
let before = BTreeMap::new();
|
||||
let one = BTreeSet::from(["repo07/a.txt".to_owned()]);
|
||||
let read = |touched: Option<&BTreeSet<String>>| {
|
||||
std::fs::write(&log, "").unwrap();
|
||||
let start = std::time::Instant::now();
|
||||
let changes = ide_vcs::with_git_executable(Some(&git), || at.changes(&before, touched).unwrap());
|
||||
let elapsed = start.elapsed();
|
||||
let calls = std::fs::read_to_string(&log).unwrap();
|
||||
eprintln!("change read: touched={:?} elapsed={elapsed:?}", touched.map(BTreeSet::len));
|
||||
(changes, calls.lines().count())
|
||||
};
|
||||
let (all, full_calls) = read(None);
|
||||
let (selected, selected_calls) = read(Some(&one));
|
||||
let (empty, empty_calls) = read(Some(&BTreeSet::new()));
|
||||
assert_eq!(all.len(), 15);
|
||||
assert_eq!(
|
||||
serde_json::to_value(selected).unwrap(),
|
||||
serde_json::to_value(made_by_task(all, Some(&one))).unwrap()
|
||||
);
|
||||
assert!(empty.is_empty());
|
||||
eprintln!("git diff children: full {full_calls}, one touched {selected_calls}, none touched {empty_calls}");
|
||||
assert!(selected_calls > 0);
|
||||
assert_eq!(selected_calls * 15, full_calls);
|
||||
assert_eq!(empty_calls, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_project_with_nested_repositories_sees_changes_in_each_one() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let (nested, deeper) = (root.join("libs/validation"), root.join("libs/validation/pkg/sdk"));
|
||||
for repo in [&root, &nested, &deeper] {
|
||||
std::fs::create_dir_all(repo).unwrap();
|
||||
git(repo, &["init", "-q", "-b", "main"]);
|
||||
std::fs::write(repo.join("a.txt"), "one\n").unwrap();
|
||||
git(repo, &["add", "a.txt"]);
|
||||
git(repo, &["commit", "-q", "-m", "init"]);
|
||||
}
|
||||
assert!(spans_repos(&root));
|
||||
std::fs::write(root.join("mine.txt"), "the user's\n").unwrap();
|
||||
let before = snapshot(&root).unwrap();
|
||||
assert_eq!(before.keys().collect::<Vec<_>>(), ["mine.txt"]);
|
||||
|
||||
std::fs::write(root.join("a.txt"), "two\n").unwrap();
|
||||
std::fs::write(nested.join("a.txt"), "two\n").unwrap();
|
||||
std::fs::write(nested.join("b.txt"), "new\n").unwrap();
|
||||
std::fs::write(deeper.join("a.txt"), "two\n").unwrap();
|
||||
let at = TaskBase::Local { cwd: root.clone(), start: None };
|
||||
let changed = at.changes(&before, None).unwrap();
|
||||
let listed: Vec<(&str, &Path)> =
|
||||
changed.iter().map(|c| (c.rel_path.as_str(), c.repo.as_ref().unwrap().0.as_path())).collect();
|
||||
assert_eq!(
|
||||
listed,
|
||||
[
|
||||
("a.txt", root.as_path()),
|
||||
("libs/validation/a.txt", nested.as_path()),
|
||||
("libs/validation/b.txt", nested.as_path()),
|
||||
("libs/validation/pkg/sdk/a.txt", deeper.as_path()),
|
||||
]
|
||||
);
|
||||
assert_eq!(at.grouped_changes(&before).unwrap().uncommitted.len(), 4);
|
||||
assert_eq!(file_at(&root, &nested.join("a.txt"), "HEAD").unwrap().as_deref(), Some("one\n"));
|
||||
|
||||
let rev = at.rev().unwrap();
|
||||
for change in &changed {
|
||||
restore(&root, rev.as_deref(), change, &before, None).unwrap();
|
||||
}
|
||||
for repo in [&root, &nested, &deeper] {
|
||||
assert_eq!(std::fs::read_to_string(repo.join("a.txt")).unwrap(), "one\n");
|
||||
}
|
||||
assert!(!nested.join("b.txt").exists());
|
||||
assert!(root.join("mine.txt").exists(), "the user's own change stays");
|
||||
// A deleted file cannot be canonicalized, but still belongs to its innermost repo.
|
||||
std::fs::remove_file(deeper.join("a.txt")).unwrap();
|
||||
let removed = at.changes(&before, Some(&BTreeSet::from(["libs/validation/pkg/sdk/a.txt".into()]))).unwrap();
|
||||
assert_eq!(removed.len(), 1);
|
||||
assert_eq!(removed[0].repo.as_ref().unwrap().0, deeper);
|
||||
assert_eq!(removed[0].kind, ChangeKind::Deleted);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn worktree_changes_are_listed_against_the_base() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
@@ -1445,101 +815,6 @@ mod tests {
|
||||
assert!(!created.path.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_turn_copies_only_what_changed_since_the_last_one() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let repo = tmp.path().join("repo");
|
||||
std::fs::create_dir(&repo).unwrap();
|
||||
git(&repo, &["init", "-q", "-b", "main"]);
|
||||
std::fs::write(repo.join("a.txt"), "base\n").unwrap();
|
||||
git(&repo, &["add", "."]);
|
||||
git(&repo, &["commit", "-q", "-m", "init"]);
|
||||
let dir = tmp.path().join("turn");
|
||||
let set = |names: &[&str]| names.iter().map(|n| (*n).to_owned()).collect::<BTreeSet<_>>();
|
||||
let copy = |turn: &TurnStart, rel: &str| std::fs::read(dir.join(turn.copy_name(rel).unwrap())).ok();
|
||||
let at = |turn: &TurnStart, rel: &str| {
|
||||
at_turn_start(&TurnRepos::of(&repo).unwrap().unwrap(), rel, turn, &dir).unwrap()
|
||||
};
|
||||
|
||||
std::fs::write(repo.join("a.txt"), "turn 1\n").unwrap();
|
||||
std::fs::write(repo.join("b.txt"), "b\n").unwrap();
|
||||
let first = start_turn(&repo, &dir).unwrap();
|
||||
assert_eq!(first.saved, set(&["a.txt", "b.txt"]));
|
||||
// A copy made again would replace this mark.
|
||||
std::fs::write(dir.join(first.copy_name("b.txt").unwrap()), "kept\n").unwrap();
|
||||
|
||||
std::thread::sleep(std::time::Duration::from_millis(10));
|
||||
std::fs::write(repo.join("a.txt"), "turn two\n").unwrap();
|
||||
let second = start_turn(&repo, &dir).unwrap();
|
||||
assert_eq!(second.saved, set(&["a.txt", "b.txt"]));
|
||||
assert_eq!(copy(&second, "a.txt").as_deref(), Some(&b"turn two\n"[..]));
|
||||
assert_eq!(copy(&second, "b.txt").as_deref(), Some(&b"kept\n"[..]));
|
||||
// The first turn keeps its own copy of the file changed since.
|
||||
assert_eq!(at(&first, "a.txt").as_deref(), Some(&b"turn 1\n"[..]));
|
||||
|
||||
// Back as committed: nothing to keep a copy of, and the committed text is the start.
|
||||
git(&repo, &["checkout", "--", "a.txt"]);
|
||||
let third = start_turn(&repo, &dir).unwrap();
|
||||
assert_eq!(third.saved, set(&["b.txt"]));
|
||||
assert_eq!(at(&third, "a.txt").as_deref(), Some(&b"base\n"[..]));
|
||||
|
||||
// Dropping the earlier turns drops the copies only they used.
|
||||
prune_turn_copies(&dir, [&third]);
|
||||
assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 1);
|
||||
assert_eq!(copy(&third, "b.txt").as_deref(), Some(&b"kept\n"[..]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn put_back_removes_new_name_before_writing_old_name_for_case_only_rename() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let repo = tmp.path().join("repo");
|
||||
std::fs::create_dir(&repo).unwrap();
|
||||
git(&repo, &["init", "-q", "-b", "main"]);
|
||||
std::fs::write(repo.join("A.txt"), "upper\n").unwrap();
|
||||
git(&repo, &["add", "."]);
|
||||
git(&repo, &["commit", "-q", "-m", "init"]);
|
||||
|
||||
let dir = tmp.path().join("turn");
|
||||
let start = start_turn(&repo, &dir).unwrap();
|
||||
git(&repo, &["mv", "A.txt", "a.txt"]);
|
||||
let changed = changed_in_turn(&repo, &start).unwrap().1;
|
||||
let planned = rewind(&repo, &start, &dir, &changed).unwrap();
|
||||
put_back(planned, &BTreeMap::new(), None).unwrap();
|
||||
|
||||
assert_eq!(std::fs::read_to_string(repo.join("A.txt")).unwrap(), "upper\n");
|
||||
let entries: Vec<String> = std::fs::read_dir(&repo)
|
||||
.unwrap()
|
||||
.filter_map(|e| e.ok())
|
||||
.map(|e| e.file_name().to_string_lossy().into_owned())
|
||||
.filter(|n| n != ".git")
|
||||
.collect();
|
||||
assert_eq!(entries, ["A.txt"]);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_turns_start_is_found_through_another_spelling_of_the_checkout() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let repo = dunce::canonicalize(tmp.path()).unwrap().join("repo");
|
||||
std::fs::create_dir(&repo).unwrap();
|
||||
git(&repo, &["init", "-q", "-b", "main"]);
|
||||
std::fs::write(repo.join("a.txt"), "base\n").unwrap();
|
||||
git(&repo, &["add", "."]);
|
||||
git(&repo, &["commit", "-q", "-m", "init"]);
|
||||
std::fs::write(repo.join("a.txt"), "turn 1\n").unwrap();
|
||||
let dir = tmp.path().join("turn");
|
||||
let start = start_turn(&repo, &dir).unwrap();
|
||||
std::fs::write(repo.join("a.txt"), "turn 2\n").unwrap();
|
||||
std::fs::write(repo.join("new.txt"), "new\n").unwrap();
|
||||
let link = tmp.path().join("link");
|
||||
std::os::unix::fs::symlink(&repo, &link).unwrap();
|
||||
for at in [&repo, &link] {
|
||||
assert_eq!(turn_text(&repo, &at.join("a.txt"), &start, &dir).unwrap().as_deref(), Some("turn 1\n"));
|
||||
assert_eq!(turn_text(&repo, &at.join("new.txt"), &start, &dir).unwrap(), None);
|
||||
}
|
||||
assert!(turn_text(&repo, &tmp.path().join("elsewhere.txt"), &start, &dir).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn commits_since_the_base_are_listed_with_their_files() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -10,6 +10,8 @@ ide-core.workspace = true
|
||||
ide-language.workspace = true
|
||||
serde.workspace = true
|
||||
specta.workspace = true
|
||||
tree-sitter.workspace = true
|
||||
rayon.workspace = true
|
||||
tracing.workspace = true
|
||||
# Pinned: 0.40.2+ moves to tree-sitter 0.26, the workspace is on 0.25.
|
||||
ast-grep-core = "=0.40.1"
|
||||
@@ -12,12 +12,11 @@ mod process;
|
||||
|
||||
pub use model::*;
|
||||
|
||||
use ide_core::process::{own_group, prepare};
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Stdio};
|
||||
use std::process::Command;
|
||||
use std::sync::OnceLock;
|
||||
use std::time::{Duration, Instant};
|
||||
use std::time::Duration;
|
||||
|
||||
/// `adb devices` is quick unless it starts the daemon, which can take a moment.
|
||||
const DEVICES: Duration = Duration::from_secs(20);
|
||||
@@ -29,8 +28,6 @@ const TAIL_LINES: u32 = 200;
|
||||
/// while `IDLE` makes sure a quiet stream still shows its last line promptly.
|
||||
const BATCH_IDLE: Duration = Duration::from_millis(60);
|
||||
const BATCH_MAX: usize = 300;
|
||||
/// How long a started emulator gets to fail: a locked or broken AVD exits within it.
|
||||
const EMULATOR_STARTUP: Duration = Duration::from_secs(3);
|
||||
|
||||
fn exe(name: &str) -> String {
|
||||
if cfg!(windows) { format!("{name}.exe") } else { name.to_owned() }
|
||||
@@ -94,49 +91,10 @@ fn executable() -> IdeResult<PathBuf> {
|
||||
})
|
||||
}
|
||||
|
||||
/// The SDK's `emulator` executable, which starts AVDs.
|
||||
pub fn emulator_executable() -> Option<PathBuf> {
|
||||
let name = exe("emulator");
|
||||
sdk_roots().into_iter().map(|root| root.join("emulator").join(&name)).find(|p| p.is_file())
|
||||
}
|
||||
|
||||
/// Starts AVD `avd` in its own process group, so it
|
||||
/// outlives whoever asked: a restarted `flutter daemon`, a closed project, the IDE. Fails when
|
||||
/// the emulator exits within its first seconds, with what it printed.
|
||||
pub fn launch_emulator(avd: &str) -> IdeResult<()> {
|
||||
let emulator = emulator_executable().ok_or_else(|| {
|
||||
IdeError::unavailable(
|
||||
"the Android emulator was not found: install it with the Android SDK Manager, or set ANDROID_HOME",
|
||||
)
|
||||
})?;
|
||||
start_emulator(&emulator, avd)
|
||||
}
|
||||
|
||||
fn start_emulator(emulator: &Path, avd: &str) -> IdeResult<()> {
|
||||
let name: String = avd.chars().map(|c| if c.is_ascii_alphanumeric() { c } else { '_' }).collect();
|
||||
let log_path = std::env::temp_dir().join(format!("openidea-emulator-{name}.log"));
|
||||
let log = std::fs::File::create(&log_path)?;
|
||||
let mut cmd = Command::new(emulator);
|
||||
cmd.arg("-avd").arg(avd);
|
||||
cmd.stdin(Stdio::null()).stdout(log.try_clone()?).stderr(log);
|
||||
let mut child = prepare(own_group(&mut cmd)).spawn()?;
|
||||
let deadline = Instant::now() + EMULATOR_STARTUP;
|
||||
while Instant::now() < deadline {
|
||||
if let Some(status) = child.try_wait()? {
|
||||
let output = std::fs::read_to_string(&log_path).unwrap_or_default();
|
||||
let tail: Vec<&str> = output.lines().filter(|l| !l.trim().is_empty()).collect();
|
||||
let tail = tail[tail.len().saturating_sub(8)..].join("\n");
|
||||
return Err(IdeError::unavailable(if tail.is_empty() {
|
||||
format!("the emulator exited ({status})")
|
||||
} else {
|
||||
tail
|
||||
}));
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(100));
|
||||
}
|
||||
// Reaps it whenever it ends.
|
||||
std::thread::spawn(move || child.wait());
|
||||
Ok(())
|
||||
/// The directory holding adb, for command lines that expect `adb` on `PATH`.
|
||||
pub fn platform_tools_dir() -> Option<&'static Path> {
|
||||
static DIR: OnceLock<Option<PathBuf>> = OnceLock::new();
|
||||
DIR.get_or_init(|| adb_executable().as_deref().and_then(Path::parent).map(Path::to_path_buf)).as_deref()
|
||||
}
|
||||
|
||||
/// Connected devices, online ones first; starting the adb daemon when needed.
|
||||
@@ -254,30 +212,6 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn an_emulator_that_fails_at_once_says_why_and_one_that_runs_is_left_running() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let script = |name: &str, body: &str| {
|
||||
let path = dir.path().join(name);
|
||||
std::fs::write(&path, format!("#!/bin/sh\n{body}")).unwrap();
|
||||
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
path
|
||||
};
|
||||
let broken = script("broken", "echo \"PANIC: Missing emulator engine for $2\" >&2\nexit 1\n");
|
||||
let e = start_emulator(&broken, "Pixel_9").unwrap_err();
|
||||
assert_eq!(e.message, "PANIC: Missing emulator engine for Pixel_9");
|
||||
|
||||
let args = dir.path().join("args");
|
||||
let running =
|
||||
script("running", &format!("echo $$ > '{0}.pid'\necho \"$@\" > '{0}'\nexec sleep 30\n", args.display()));
|
||||
start_emulator(&running, "Pixel_9").unwrap();
|
||||
assert_eq!(std::fs::read_to_string(&args).unwrap().trim(), "-avd Pixel_9");
|
||||
let pid = std::fs::read_to_string(dir.path().join("args.pid")).unwrap();
|
||||
assert!(Command::new("kill").arg(pid.trim()).status().unwrap().success(), "still running");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn executable_is_absolute_when_found() {
|
||||
if let Some(adb) = adb_executable() {
|
||||
|
||||
+134
-216
@@ -1,18 +1,101 @@
|
||||
//! The `adb` CLI as a child process: bounded runs, and cancellable line streams
|
||||
//! Child processes of the `adb` CLI: bounded runs, and cancellable line streams
|
||||
//! that are handed over in batches (logcat is far too chatty for one message a line).
|
||||
|
||||
pub(crate) use ide_core::cli_process::Output;
|
||||
use ide_core::cli_process::{CarriageReturn, CliTool, Decoding, Poll, Stream, keep_stderr_line};
|
||||
use ide_core::{CancellationToken, IdeResult};
|
||||
use std::process::Command;
|
||||
use ide_core::process::terminate_tree;
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult};
|
||||
use std::io::Read;
|
||||
use std::process::{Child, Command, Stdio};
|
||||
use std::sync::mpsc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
const ADB: CliTool = CliTool::new("adb", Decoding::ToolOutput);
|
||||
/// How long a cancelled child gets to exit on `SIGTERM` (and flush) before `SIGKILL`.
|
||||
const KILL_GRACE: Duration = Duration::from_millis(20);
|
||||
|
||||
pub(crate) struct Output {
|
||||
pub stdout: String,
|
||||
pub stderr: String,
|
||||
pub success: bool,
|
||||
}
|
||||
|
||||
fn prepare(cmd: &mut Command) {
|
||||
cmd.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped());
|
||||
ide_core::process::prepare(ide_core::process::own_group(cmd));
|
||||
}
|
||||
|
||||
fn spawn(cmd: &mut Command) -> IdeResult<Child> {
|
||||
cmd.spawn().map_err(|e| IdeError::unavailable(format!("could not run adb: {e}")))
|
||||
}
|
||||
|
||||
fn read_all(mut pipe: impl Read + Send + 'static) -> std::thread::JoinHandle<String> {
|
||||
std::thread::spawn(move || {
|
||||
let mut buf = Vec::new();
|
||||
let _ = pipe.read_to_end(&mut buf);
|
||||
ide_core::output_encoding::decode_tool_output(&buf)
|
||||
})
|
||||
}
|
||||
|
||||
/// Runs `cmd` to completion. Fails when it outlives `timeout` or `cancel` fires;
|
||||
/// a non-zero exit is reported in [`Output::success`], not as an error.
|
||||
pub(crate) fn run(cmd: Command, timeout: Duration, cancel: Option<&CancellationToken>) -> IdeResult<Output> {
|
||||
ADB.run(cmd, timeout, cancel)
|
||||
pub(crate) fn run(mut cmd: Command, timeout: Duration, cancel: Option<&CancellationToken>) -> IdeResult<Output> {
|
||||
prepare(&mut cmd);
|
||||
let mut child = spawn(&mut cmd)?;
|
||||
let out = child.stdout.take().map(read_all);
|
||||
let err = child.stderr.take().map(read_all);
|
||||
let deadline = Instant::now() + timeout;
|
||||
let status = loop {
|
||||
if let Some(status) = child.try_wait()? {
|
||||
break status;
|
||||
}
|
||||
if cancel.is_some_and(CancellationToken::is_cancelled) {
|
||||
terminate_tree(&mut child, KILL_GRACE);
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
if Instant::now() >= deadline {
|
||||
terminate_tree(&mut child, KILL_GRACE);
|
||||
return Err(IdeError::unavailable("adb did not respond in time"));
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
};
|
||||
Ok(Output {
|
||||
stdout: out.map(|t| t.join().unwrap_or_default()).unwrap_or_default(),
|
||||
stderr: err.map(|t| t.join().unwrap_or_default()).unwrap_or_default(),
|
||||
success: status.success(),
|
||||
})
|
||||
}
|
||||
|
||||
enum Event {
|
||||
Line(bool, String),
|
||||
Closed,
|
||||
}
|
||||
|
||||
fn spawn_reader(mut pipe: impl Read + Send + 'static, tx: mpsc::Sender<Event>, stdout: bool) {
|
||||
std::thread::spawn(move || {
|
||||
let mut buf = [0u8; 8192];
|
||||
let mut pending: Vec<u8> = Vec::new();
|
||||
let flush = |pending: &mut Vec<u8>| {
|
||||
if !pending.is_empty() {
|
||||
let line = ide_core::output_encoding::decode_tool_output(pending);
|
||||
pending.clear();
|
||||
let _ = tx.send(Event::Line(stdout, line.trim_end().to_string()));
|
||||
}
|
||||
};
|
||||
loop {
|
||||
match pipe.read(&mut buf) {
|
||||
Ok(0) | Err(_) => break,
|
||||
Ok(n) => {
|
||||
for &b in &buf[..n] {
|
||||
if b == b'\n' {
|
||||
flush(&mut pending);
|
||||
} else if b != b'\r' {
|
||||
pending.push(b);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
flush(&mut pending);
|
||||
let _ = tx.send(Event::Closed);
|
||||
});
|
||||
}
|
||||
|
||||
fn flush<T>(batch: &mut Vec<T>, on_batch: &mut dyn FnMut(Vec<T>)) {
|
||||
@@ -26,22 +109,41 @@ fn flush<T>(batch: &mut Vec<T>, on_batch: &mut dyn FnMut(Vec<T>)) {
|
||||
/// old, so neither a quiet nor a steady stream holds lines back. Stderr is kept as a
|
||||
/// tail for the error message. Returns whether the child exited successfully.
|
||||
pub(crate) fn stream_batched<T>(
|
||||
cmd: Command,
|
||||
mut cmd: Command,
|
||||
cancel: &CancellationToken,
|
||||
idle: Duration,
|
||||
max: usize,
|
||||
mut parse: impl FnMut(&str) -> Option<T>,
|
||||
on_batch: &mut dyn FnMut(Vec<T>),
|
||||
) -> IdeResult<(bool, Vec<String>)> {
|
||||
let mut lines = ADB.lines(cmd, cancel, CarriageReturn::Dropped)?;
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
prepare(&mut cmd);
|
||||
let mut child = spawn(&mut cmd)?;
|
||||
let (tx, rx) = mpsc::channel::<Event>();
|
||||
let mut open = 0;
|
||||
if let Some(out) = child.stdout.take() {
|
||||
spawn_reader(out, tx.clone(), true);
|
||||
open += 1;
|
||||
}
|
||||
if let Some(err) = child.stderr.take() {
|
||||
spawn_reader(err, tx.clone(), false);
|
||||
open += 1;
|
||||
}
|
||||
drop(tx);
|
||||
let mut stderr_tail: Vec<String> = Vec::new();
|
||||
let mut batch: Vec<T> = Vec::with_capacity(max);
|
||||
// When the first line of the waiting batch arrived.
|
||||
let mut since = Instant::now();
|
||||
loop {
|
||||
while open > 0 {
|
||||
if cancel.is_cancelled() {
|
||||
terminate_tree(&mut child, KILL_GRACE);
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
let wait = if batch.is_empty() { idle } else { idle.saturating_sub(since.elapsed()) };
|
||||
match lines.poll(cancel, wait)? {
|
||||
Poll::Line(Stream::Stdout, line) => {
|
||||
match rx.recv_timeout(wait) {
|
||||
Ok(Event::Line(true, line)) => {
|
||||
if let Some(item) = parse(&line) {
|
||||
if batch.is_empty() {
|
||||
since = Instant::now();
|
||||
@@ -52,25 +154,36 @@ pub(crate) fn stream_batched<T>(
|
||||
}
|
||||
}
|
||||
}
|
||||
Poll::Line(Stream::Stderr, line) => {
|
||||
Ok(Event::Line(false, line)) => {
|
||||
if !line.trim().is_empty() {
|
||||
keep_stderr_line(&mut stderr_tail, line);
|
||||
stderr_tail.push(line);
|
||||
if stderr_tail.len() > 20 {
|
||||
stderr_tail.remove(0);
|
||||
}
|
||||
}
|
||||
}
|
||||
Poll::Closed => {}
|
||||
Poll::Timeout => flush(&mut batch, on_batch),
|
||||
Poll::Finished => break,
|
||||
Ok(Event::Closed) => open -= 1,
|
||||
Err(mpsc::RecvTimeoutError::Timeout) => flush(&mut batch, on_batch),
|
||||
Err(mpsc::RecvTimeoutError::Disconnected) => break,
|
||||
}
|
||||
}
|
||||
flush(&mut batch, on_batch);
|
||||
Ok((lines.finish(cancel)?, stderr_tail))
|
||||
let status = loop {
|
||||
if let Some(status) = child.try_wait()? {
|
||||
break status;
|
||||
}
|
||||
if cancel.is_cancelled() {
|
||||
terminate_tree(&mut child, KILL_GRACE);
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
};
|
||||
Ok((status.success(), stderr_tail))
|
||||
}
|
||||
|
||||
#[cfg(all(test, unix))]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use ide_core::error::ErrorKind;
|
||||
use ide_core::process::process_alive;
|
||||
|
||||
#[test]
|
||||
fn a_steady_stream_is_handed_over_while_it_runs() {
|
||||
@@ -90,199 +203,4 @@ mod tests {
|
||||
assert_eq!(sizes.iter().sum::<usize>(), 20);
|
||||
assert!(sizes.len() >= 3, "lines arriving every 20 ms waited for the end: {sizes:?}");
|
||||
}
|
||||
|
||||
const LONG: Duration = Duration::from_secs(30);
|
||||
|
||||
fn sh(script: &str) -> Command {
|
||||
let mut cmd = Command::new("sh");
|
||||
cmd.args(["-c", script]);
|
||||
cmd
|
||||
}
|
||||
|
||||
/// A script that records its pid in `name`'s file, then runs `rest`.
|
||||
fn recording_pid(name: &str, rest: &str) -> (Command, std::path::PathBuf) {
|
||||
let file = std::env::temp_dir().join(format!("openidea-process-{}-{name}", std::process::id()));
|
||||
let _ = std::fs::remove_file(&file);
|
||||
(sh(&format!("echo $$ > '{0}.tmp' && mv '{0}.tmp' '{0}'; {rest}", file.display())), file)
|
||||
}
|
||||
|
||||
fn recorded_pid(file: &std::path::Path) -> u32 {
|
||||
let pid = std::fs::read_to_string(file).unwrap().trim().parse().unwrap();
|
||||
let _ = std::fs::remove_file(file);
|
||||
pid
|
||||
}
|
||||
|
||||
/// Cancels `cancel` once the script has recorded its pid.
|
||||
fn cancel_when_recorded(file: &std::path::Path, cancel: &CancellationToken) {
|
||||
let (file, cancel) = (file.to_owned(), cancel.clone());
|
||||
std::thread::spawn(move || {
|
||||
while !file.exists() {
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
}
|
||||
cancel.cancel();
|
||||
});
|
||||
}
|
||||
|
||||
fn assert_gone(pid: u32) {
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
while process_alive(pid) {
|
||||
assert!(Instant::now() < deadline, "process {pid} survived");
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_exit_status_is_reported_not_raised() {
|
||||
assert!(run(sh("exit 0"), LONG, None).unwrap().success);
|
||||
assert!(!run(sh("exit 3"), LONG, None).unwrap().success);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn both_streams_are_captured_separately_and_in_order() {
|
||||
let out = run(sh("printf 'a\\nb\\nc\\n'; printf 'x\\ny\\n' >&2"), LONG, None).unwrap();
|
||||
assert_eq!(out.stdout, "a\nb\nc\n");
|
||||
assert_eq!(out.stderr, "x\ny\n");
|
||||
assert!(out.success);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_utf8_is_replaced_in_collected_output() {
|
||||
let out = run(sh("printf 'ok\\n\\377\\n'; printf 'a\\377b' >&2"), LONG, None).unwrap();
|
||||
assert_eq!(out.stdout, "ok\n\u{FFFD}\n");
|
||||
assert_eq!(out.stderr, "a\u{FFFD}b");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stdin_is_closed() {
|
||||
assert_eq!(run(sh("cat; echo done"), LONG, None).unwrap().stdout, "done\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_missing_program_is_unavailable() {
|
||||
let err = run(Command::new("/nonexistent/openidea-adb"), LONG, None).err().unwrap();
|
||||
assert_eq!(err.kind, ErrorKind::Unavailable);
|
||||
assert_eq!(err.message, "could not run adb: No such file or directory (os error 2)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_run_past_its_timeout_fails_and_the_child_is_killed() {
|
||||
let (cmd, file) = recording_pid("adb-timeout", "exec sleep 30");
|
||||
let err = run(cmd, Duration::from_secs(1), None).err().unwrap();
|
||||
assert_eq!(err.kind, ErrorKind::Unavailable);
|
||||
assert_eq!(err.message, "adb did not respond in time");
|
||||
assert_gone(recorded_pid(&file));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cancelled_run_fails_and_the_child_is_killed() {
|
||||
let (cmd, file) = recording_pid("adb-cancel", "exec sleep 30");
|
||||
let cancel = CancellationToken::new();
|
||||
cancel_when_recorded(&file, &cancel);
|
||||
let err = run(cmd, LONG, Some(&cancel)).err().unwrap();
|
||||
assert_eq!(err.kind, ErrorKind::Cancelled);
|
||||
assert_eq!(err.message, "cancelled");
|
||||
assert_gone(recorded_pid(&file));
|
||||
}
|
||||
|
||||
/// Runs `script` batched by `max` lines (a long `idle`, so only `max` and the end flush),
|
||||
/// parsing stdout lines unless they are `skip`.
|
||||
fn batches(script: &str, max: usize) -> (bool, Vec<Vec<String>>, Vec<String>) {
|
||||
let mut batches = Vec::new();
|
||||
let (ok, tail) = stream_batched(
|
||||
sh(script),
|
||||
&CancellationToken::new(),
|
||||
LONG,
|
||||
max,
|
||||
|line| (line != "skip").then(|| line.to_owned()),
|
||||
&mut |batch| batches.push(batch),
|
||||
)
|
||||
.unwrap();
|
||||
(ok, batches, tail)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_batch_is_handed_over_as_soon_as_max_lines_are_ready() {
|
||||
let (ok, batches, _) = batches("printf '1\\n2\\n3\\n4\\n5\\n'", 2);
|
||||
assert!(ok);
|
||||
assert_eq!(batches, [vec!["1", "2"], vec!["3", "4"], vec!["5"]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lines_the_parser_rejects_are_dropped() {
|
||||
let (_, batches, _) = batches("printf '1\\nskip\\n2\\n'", 10);
|
||||
assert_eq!(batches, [vec!["1", "2"]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn carriage_returns_are_dropped_not_split_on_and_line_ends_are_trimmed() {
|
||||
let (_, batches, _) = batches("printf 'a\\r\\nb\\rc \\n\\n\\nd'", 10);
|
||||
assert_eq!(batches, [vec!["a", "bc", "d"]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stream_replaces_invalid_utf8() {
|
||||
let (_, batches, _) = batches("printf 'a\\377b\\n'", 10);
|
||||
assert_eq!(batches, [vec!["a\u{FFFD}b"]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stream_reports_the_exit_status() {
|
||||
assert!(batches("exit 0", 10).0);
|
||||
assert!(!batches("exit 2", 10).0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stderr_is_not_parsed_and_its_last_twenty_non_blank_lines_are_kept() {
|
||||
let (_, batches, tail) =
|
||||
batches("echo ' ' >&2; i=1; while [ $i -le 25 ]; do echo e$i >&2; i=$((i+1)); done; echo out", 10);
|
||||
assert_eq!(batches, [vec!["out"]]);
|
||||
let expected: Vec<String> = (6..=25).map(|i| format!("e{i}")).collect();
|
||||
assert_eq!(tail, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stream_cancelled_before_it_starts_does_not_spawn() {
|
||||
let cancel = CancellationToken::new();
|
||||
cancel.cancel();
|
||||
let err = stream_batched(
|
||||
Command::new("/nonexistent/openidea-adb"),
|
||||
&cancel,
|
||||
LONG,
|
||||
10,
|
||||
|line| Some(line.to_owned()),
|
||||
&mut |_| {},
|
||||
)
|
||||
.err()
|
||||
.unwrap();
|
||||
assert_eq!(err.kind, ErrorKind::Cancelled);
|
||||
assert_eq!(err.message, "cancelled");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stream_cancelled_while_running_fails_and_the_child_is_killed() {
|
||||
let (cmd, file) = recording_pid("adb-stream-cancel", "echo started; exec sleep 30");
|
||||
let cancel = CancellationToken::new();
|
||||
let err = stream_batched(cmd, &cancel, LONG, 1, |line| Some(line.to_owned()), &mut |_| cancel.cancel())
|
||||
.err()
|
||||
.unwrap();
|
||||
assert_eq!(err.kind, ErrorKind::Cancelled);
|
||||
assert_eq!(err.message, "cancelled");
|
||||
assert_gone(recorded_pid(&file));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_missing_program_cannot_be_streamed() {
|
||||
let err = stream_batched(
|
||||
Command::new("/nonexistent/openidea-adb"),
|
||||
&CancellationToken::new(),
|
||||
LONG,
|
||||
10,
|
||||
|line| Some(line.to_owned()),
|
||||
&mut |_| {},
|
||||
)
|
||||
.err()
|
||||
.unwrap();
|
||||
assert_eq!(err.kind, ErrorKind::Unavailable);
|
||||
assert_eq!(err.message, "could not run adb: No such file or directory (os error 2)");
|
||||
}
|
||||
}
|
||||
@@ -17,4 +17,6 @@ serde_json.workspace = true
|
||||
specta.workspace = true
|
||||
tracing.workspace = true
|
||||
dirs.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile.workspace = true
|
||||
@@ -26,10 +26,9 @@ pub fn plan(root: &Path, model: &BuildModel, module: &Path, cache: &Path) -> Ide
|
||||
let module = dunce::canonicalize(root.join(module))?;
|
||||
if let Some(p) = model.maven.as_ref().and_then(|m| m.projects.iter().find(|p| root.join(&p.dir) == module)) {
|
||||
let mut args = p.options.clone();
|
||||
let repo = crate::maven::local_repository_for(&p.options);
|
||||
args.extend([
|
||||
"process-resources".into(),
|
||||
crate::maven::plugin_goal("help:evaluate", repo.as_deref()),
|
||||
"help:evaluate".into(),
|
||||
"-Dexpression=project.build.outputDirectory".into(),
|
||||
format!("-Doutput={}", manifest.display()),
|
||||
]);
|
||||
@@ -48,20 +47,13 @@ pub fn plan(root: &Path, model: &BuildModel, module: &Path, cache: &Path) -> Ide
|
||||
fs::write(
|
||||
&script,
|
||||
format!(
|
||||
r#"import org.gradle.util.GradleVersion
|
||||
|
||||
gradle.projectsEvaluated {{
|
||||
r#"gradle.projectsEvaluated {{
|
||||
def p = gradle.rootProject.project({})
|
||||
def update = {{ t ->
|
||||
t.dependsOn 'processResources'
|
||||
// Resolved here so the action holds no task or project (configuration cache).
|
||||
def dir = p.tasks.getByName('processResources').destinationDir
|
||||
def manifest = new File({})
|
||||
t.doLast {{ manifest.setText(dir.absolutePath, 'UTF-8') }}
|
||||
def resources = p.tasks.named('processResources')
|
||||
p.tasks.register('openideaUpdateResources') {{
|
||||
dependsOn resources
|
||||
doLast {{ new File({}).setText(resources.get().destinationDir.absolutePath, 'UTF-8') }}
|
||||
}}
|
||||
// `register` is Gradle 4.9+.
|
||||
if (GradleVersion.current() >= GradleVersion.version('4.9')) p.tasks.register('openideaUpdateResources', update)
|
||||
else p.tasks.create('openideaUpdateResources', update)
|
||||
}}
|
||||
"#,
|
||||
literal(&p.path),
|
||||
@@ -180,16 +172,7 @@ mod tests {
|
||||
assert_eq!(gradle.command, "/tools/gradlew");
|
||||
assert_eq!(gradle.args.last().unwrap(), ":app:openideaUpdateResources");
|
||||
let script = fs::read_to_string(cache.join("resources.init.gradle")).unwrap();
|
||||
assert!(
|
||||
script.contains("processResources")
|
||||
&& script.contains(".destinationDir\n")
|
||||
&& script.contains("setText(dir.absolutePath")
|
||||
);
|
||||
// `register` is Gradle 4.9+ (#3864).
|
||||
assert!(script.contains("else p.tasks.create('openideaUpdateResources', update)"), "{script}");
|
||||
// The configuration cache can't serialize a task or project the action refers to.
|
||||
let action = &script[script.find("doLast").unwrap()..script.find("// `register`").unwrap()];
|
||||
assert!(!action.contains("p.") && !action.contains("tasks"), "{action}");
|
||||
assert!(script.contains("processResources") && script.contains("destinationDir.absolutePath"));
|
||||
assert!(!script.contains("build/resources/main")); // The task owns custom output locations.
|
||||
}
|
||||
|
||||
|
||||
@@ -120,7 +120,7 @@ fn collect(
|
||||
break;
|
||||
}
|
||||
}
|
||||
let program = process::program_path(&step.program, &step.env, &step.cwd);
|
||||
let program = process::program_path(&step.program, &step.env);
|
||||
inputs.push(program.clone());
|
||||
// Maven installed via a symlink still reads conf from its distribution.
|
||||
if let Ok(program) = dunce::canonicalize(program)
|
||||
@@ -131,7 +131,7 @@ fn collect(
|
||||
}
|
||||
}
|
||||
if !environment.contains_key("JAVA_HOME") {
|
||||
let java = process::program_path(if cfg!(windows) { "java.exe" } else { "java" }, &step.env, &step.cwd);
|
||||
let java = process::program_path(if cfg!(windows) { "java.exe" } else { "java" }, &step.env);
|
||||
inputs.push(java.clone());
|
||||
if let Ok(java) = dunce::canonicalize(java)
|
||||
&& let Some(home) = java.parent().and_then(Path::parent)
|
||||
@@ -171,7 +171,7 @@ fn collect(
|
||||
let steps = plan
|
||||
.steps
|
||||
.iter()
|
||||
.map(|s| (process::program_path(&s.program, &s.env, &s.cwd), s.args.clone(), s.cwd.clone(), s.env.clone()))
|
||||
.map(|s| (process::program_path(&s.program, &s.env), s.args.clone(), s.cwd.clone(), s.env.clone()))
|
||||
.collect();
|
||||
// Profiles and plugins can read arbitrary environment variables. Keep a signature
|
||||
// of the inherited environment without persisting unrelated credentials.
|
||||
@@ -182,7 +182,7 @@ fn collect(
|
||||
}
|
||||
|
||||
/// Scans every input, storing project inputs relative to the project.
|
||||
pub(super) fn scan_all(
|
||||
fn scan_all(
|
||||
root: &Path,
|
||||
inputs: Vec<PathBuf>,
|
||||
cancel: &CancellationToken,
|
||||
@@ -210,7 +210,7 @@ pub fn launch_fingerprint(
|
||||
if projects.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
let plan = launch_plan(root, model, module, test, BuildKind::Build, cancel)?;
|
||||
let plan = launch_plan(root, model, module, test, BuildKind::Build)?;
|
||||
let Some(collected) = collect(root, &projects, &plan, local_repo)? else { return Ok(None) };
|
||||
let Collected { inputs, environment, steps, inherited_hash } = collected;
|
||||
let parameters = serde_json::to_string(&(root, module, test, steps, environment, inherited_hash, projects))
|
||||
@@ -229,7 +229,7 @@ pub fn menu_fingerprint(
|
||||
file: Option<&Path>,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<Option<LaunchFingerprint>> {
|
||||
let plan = plan(root, model, BuildKind::Build, file, None, None, cancel)?;
|
||||
let plan = plan(root, model, BuildKind::Build, file, None)?;
|
||||
if plan.system != BuildSystem::Maven {
|
||||
return Ok(None);
|
||||
}
|
||||
@@ -264,23 +264,6 @@ pub fn menu_fingerprint(
|
||||
Ok(Some(LaunchFingerprint { version: 2, parameters, files: scan_all(root, inputs, cancel)? }))
|
||||
}
|
||||
|
||||
/// Input fingerprint of one Maven module's menu build (#4078): its POM chain,
|
||||
/// source and resource trees plus the launcher settings that shape the build.
|
||||
/// `None` disables the module-scoped reuse (unresolved custom roots).
|
||||
/// All filesystem work belongs on the caller's blocking thread.
|
||||
pub(super) fn module_fingerprint(
|
||||
root: &Path,
|
||||
project: &maven::MavenProject,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<Option<LaunchFingerprint>> {
|
||||
let projects = [project];
|
||||
let Some(inputs) = maven::launch_inputs(root, &projects, None) else { return Ok(None) };
|
||||
let parameters =
|
||||
serde_json::to_string(&("module-build", &project.dir, &project.command, &project.options, &project.env))
|
||||
.map_err(|e| IdeError::internal(e.to_string()))?;
|
||||
Ok(Some(LaunchFingerprint { version: 2, parameters, files: scan_all(root, inputs, cancel)? }))
|
||||
}
|
||||
|
||||
impl LaunchFingerprint {
|
||||
/// Folders (relative to the project) of the Maven projects whose POM is an input.
|
||||
pub(super) fn project_dirs(&self) -> impl Iterator<Item = &Path> {
|
||||
|
||||
@@ -5,7 +5,6 @@
|
||||
|
||||
mod fingerprint;
|
||||
mod launch_resources;
|
||||
mod modules;
|
||||
mod parse;
|
||||
mod single;
|
||||
mod structure;
|
||||
@@ -13,14 +12,13 @@ mod up_to_date;
|
||||
|
||||
pub use fingerprint::{LaunchFingerprint, launch_fingerprint, menu_fingerprint};
|
||||
pub use launch_resources::process_launch_resources;
|
||||
pub use modules::record_module_build;
|
||||
pub use single::{
|
||||
SingleFileTarget, compile_file_plan, compile_file_plan_cancellable, find_javac, gradle_compile_file_plan,
|
||||
has_gradle_file_target, javac_step, module_classpath, module_classpaths, single_file_classpath, single_file_target,
|
||||
SingleFileTarget, compile_file_plan, find_javac, javac_step, module_classpath, single_file_classpath,
|
||||
single_file_target,
|
||||
};
|
||||
pub use structure::{
|
||||
StructureJdk, StructureRoots, artifact_file, artifact_output, language_release, structure_compile_file_plan,
|
||||
structure_outputs, structure_plan, structure_war_plan, structure_web_artifacts,
|
||||
StructureJdk, StructureRoots, artifact_file, artifact_output, language_release, structure_outputs, structure_plan,
|
||||
structure_war_plan, structure_web_artifacts,
|
||||
};
|
||||
pub use up_to_date::{menu_up_to_date, record_menu_build};
|
||||
|
||||
@@ -222,16 +220,12 @@ fn ancestors_within<'a>(root: &'a Path, file: &'a Path) -> impl Iterator<Item =
|
||||
|
||||
/// The build of `root`, or of the module containing `file` (Build Module / Recompile).
|
||||
/// `cmake`: the CMake profiles of the settings (the first one is built), if any.
|
||||
/// `cache` enables the module-scoped Maven narrowing of `Build` project builds;
|
||||
/// `None` plans every build exactly as before.
|
||||
pub fn plan(
|
||||
root: &Path,
|
||||
model: &BuildModel,
|
||||
kind: BuildKind,
|
||||
file: Option<&Path>,
|
||||
cmake: Option<&[CMakeProfile]>,
|
||||
cache: Option<&Path>,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<BuildPlan> {
|
||||
let project_name = root.file_name().map_or_else(|| "project".to_owned(), |n| n.to_string_lossy().into_owned());
|
||||
let module_dir = match file {
|
||||
@@ -268,7 +262,7 @@ pub fn plan(
|
||||
None => project_name,
|
||||
};
|
||||
let steps = match system {
|
||||
BuildSystem::Maven => maven_steps(root, model, kind, module_dir.as_deref(), cache, cancel)?,
|
||||
BuildSystem::Maven => maven_steps(root, model, kind, module_dir.as_deref())?,
|
||||
BuildSystem::Gradle => gradle_steps(root, model, kind, module_dir.as_deref())?,
|
||||
BuildSystem::Cargo => cargo_steps(&dir, kind),
|
||||
// Go builds the file's package (a module holds many).
|
||||
@@ -287,8 +281,6 @@ pub(super) fn maven_steps(
|
||||
model: &BuildModel,
|
||||
kind: BuildKind,
|
||||
module: Option<&Path>,
|
||||
cache: Option<&Path>,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<Vec<BuildStep>> {
|
||||
let fallback;
|
||||
let m = match &model.maven {
|
||||
@@ -328,15 +320,7 @@ pub(super) fn maven_steps(
|
||||
s.env = p.env.clone();
|
||||
s
|
||||
};
|
||||
let Some(module) = module else {
|
||||
if kind == BuildKind::Build
|
||||
&& let Some(cache) = cache
|
||||
&& let Some(steps) = modules::narrowed_maven_steps(cache, root, m, &step, cancel)?
|
||||
{
|
||||
return Ok(steps);
|
||||
}
|
||||
return Ok(tops.iter().map(|p| step(p, &[])).collect());
|
||||
};
|
||||
let Some(module) = module else { return Ok(tops.iter().map(|p| step(p, &[])).collect()) };
|
||||
// The reactor root containing the module builds it with what it depends on (`-pl … -am`).
|
||||
let rel = rel_str(root, module);
|
||||
if !m.projects.iter().any(|p| p.dir == rel) {
|
||||
@@ -483,6 +467,11 @@ fn go_module_steps(dir: &Path, kind: BuildKind) -> Vec<BuildStep> {
|
||||
vec![s]
|
||||
}
|
||||
|
||||
/// `pnpm` / `yarn` / `bun` / `npm`, from the lock file next to `package.json` or above it.
|
||||
fn package_manager(dir: &Path) -> &'static str {
|
||||
ide_core::project_roots::package_manager(dir)
|
||||
}
|
||||
|
||||
fn has_build_script(dir: &Path) -> bool {
|
||||
std::fs::read(dir.join("package.json"))
|
||||
.ok()
|
||||
@@ -520,12 +509,7 @@ fn dotnet_steps(dir: &Path, kind: BuildKind) -> IdeResult<Vec<BuildStep>> {
|
||||
fn ts_steps(dir: &Path, kind: BuildKind) -> Vec<BuildStep> {
|
||||
let script = has_build_script(dir);
|
||||
if script && (kind == BuildKind::Artifacts || !dir.join("tsconfig.json").is_file()) {
|
||||
return vec![BuildStep::new(
|
||||
ide_core::project_roots::package_manager(dir),
|
||||
&["run", "build"],
|
||||
dir,
|
||||
Format::Tsc,
|
||||
)];
|
||||
return vec![BuildStep::new(package_manager(dir), &["run", "build"], dir, Format::Tsc)];
|
||||
}
|
||||
let local = dir.ancestors().map(|d| d.join("node_modules/.bin/tsc")).find(|p| p.is_file());
|
||||
let program = local.map_or_else(|| "tsc".to_owned(), |p| p.to_string_lossy().into_owned());
|
||||
@@ -552,9 +536,7 @@ impl PathMap {
|
||||
let abs = if p.is_absolute() {
|
||||
p.to_path_buf()
|
||||
} else {
|
||||
// rustc prints workspace members' files relative to the workspace root, above
|
||||
// the member's manifest directory (`base`) when a member is built on its own.
|
||||
let in_base = base.and_then(|b| Path::new(b).ancestors().map(|a| a.join(p)).find(|c| c.exists()));
|
||||
let in_base = base.map(|b| Path::new(b).join(p)).filter(|c| c.exists());
|
||||
in_base.unwrap_or_else(|| cwd.join(p))
|
||||
};
|
||||
let abs = normalize(&abs);
|
||||
@@ -566,7 +548,7 @@ impl PathMap {
|
||||
}
|
||||
|
||||
/// Removes `.` and resolvable `..` components without touching the file system.
|
||||
pub(crate) fn normalize(p: &Path) -> PathBuf {
|
||||
fn normalize(p: &Path) -> PathBuf {
|
||||
use std::path::Component;
|
||||
let mut out = PathBuf::new();
|
||||
for c in p.components() {
|
||||
@@ -731,7 +713,7 @@ pub fn run(
|
||||
}
|
||||
}
|
||||
};
|
||||
let out = process::run_bounded(&step.program, &step.args, &step.cwd, &step.env, cancel, |stream, line| {
|
||||
let out = process::run(&step.program, &step.args, &step.cwd, &step.env, cancel, |stream, line| {
|
||||
let parsed = parser.feed(line);
|
||||
match parsed.console {
|
||||
Some(text) if text.is_empty() => {}
|
||||
@@ -773,7 +755,7 @@ pub fn run(
|
||||
if !out.success {
|
||||
success = false;
|
||||
if !messages.iter().any(|m| m.severity == Severity::Error) {
|
||||
let summary = crate::sync::error_summary(&out);
|
||||
let summary = crate::sync::error_summary(&out.text);
|
||||
let text = if summary.is_empty() { last_error_line.clone() } else { summary };
|
||||
let m = BuildMessage { severity: Severity::Error, text, path: None, range: None, code: None };
|
||||
on_event(BuildEvent::Message { message: m.clone() });
|
||||
@@ -897,15 +879,8 @@ pub fn launch_has_non_java_sources(root: &Path, model: &BuildModel, module: &Pat
|
||||
has_non_java_sources(module)
|
||||
}
|
||||
|
||||
fn launch_plan(
|
||||
root: &Path,
|
||||
model: &BuildModel,
|
||||
module: &Path,
|
||||
test: bool,
|
||||
kind: BuildKind,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<BuildPlan> {
|
||||
let mut plan = plan(root, model, kind, Some(module), None, None, cancel)?;
|
||||
fn launch_plan(root: &Path, model: &BuildModel, module: &Path, test: bool, kind: BuildKind) -> IdeResult<BuildPlan> {
|
||||
let mut plan = plan(root, model, kind, Some(module), None)?;
|
||||
if plan.system == BuildSystem::Maven && !test {
|
||||
for step in &mut plan.steps {
|
||||
if let Some(goal) = step.args.last_mut() {
|
||||
@@ -916,47 +891,6 @@ fn launch_plan(
|
||||
Ok(plan)
|
||||
}
|
||||
|
||||
/// Directory of the linked Maven reactor that builds the launch module at `module`;
|
||||
/// launches of one reactor can share a build ([`build_for_launches`]).
|
||||
pub fn launch_reactor(root: &Path, model: &BuildModel, module: &Path) -> Option<String> {
|
||||
maven_reactor(model.maven.as_ref()?, &rel_str(root, module)).map(|top| top.dir.clone())
|
||||
}
|
||||
|
||||
/// One Maven step building every module of `modules` (all of one reactor) with what they
|
||||
/// depend on: `-pl a,b -am`, so their shared upstream modules build once (#3971).
|
||||
fn merged_launch_plan(
|
||||
root: &Path,
|
||||
model: &BuildModel,
|
||||
modules: &[PathBuf],
|
||||
test: bool,
|
||||
kind: BuildKind,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<BuildPlan> {
|
||||
let mut plan = launch_plan(root, model, &modules[0], test, kind, cancel)?;
|
||||
if plan.system != BuildSystem::Maven || modules.len() == 1 {
|
||||
return Ok(plan);
|
||||
}
|
||||
let mut selection = Vec::new();
|
||||
for module in modules {
|
||||
let one = launch_plan(root, model, module, test, kind, cancel)?;
|
||||
if one.steps.len() != 1 || one.steps[0].cwd != plan.steps[0].cwd {
|
||||
return Err(IdeError::invalid("launch modules belong to different Maven reactors"));
|
||||
}
|
||||
match one.steps[0].args.iter().position(|a| a == "-pl") {
|
||||
Some(i) => selection.push(one.steps[0].args[i + 1].clone()),
|
||||
// The reactor root itself builds every module.
|
||||
None => return Ok(one),
|
||||
}
|
||||
}
|
||||
selection.sort();
|
||||
selection.dedup();
|
||||
let step = &mut plan.steps[0];
|
||||
if let Some(i) = step.args.iter().position(|a| a == "-pl") {
|
||||
step.args[i + 1] = selection.join(",");
|
||||
}
|
||||
Ok(plan)
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct LaunchBuild {
|
||||
pub class_dirs: Vec<PathBuf>,
|
||||
@@ -965,7 +899,6 @@ pub struct LaunchBuild {
|
||||
|
||||
/// Compiles the module at `module` with its build system before a JVM launch and
|
||||
/// returns the class directories it wrote, to put ahead of the jdtls classpath.
|
||||
/// The build's console, messages and progress stream to `on_event` as it runs.
|
||||
pub fn build_for_launch(
|
||||
root: &Path,
|
||||
model: &BuildModel,
|
||||
@@ -973,25 +906,9 @@ pub fn build_for_launch(
|
||||
test: bool,
|
||||
kind: BuildKind,
|
||||
cancel: &CancellationToken,
|
||||
on_event: &(dyn Fn(BuildEvent) + Sync),
|
||||
) -> IdeResult<LaunchBuild> {
|
||||
let mut built = build_for_launches(root, model, &[module.to_path_buf()], test, kind, cancel, on_event)?;
|
||||
Ok(built.pop().unwrap())
|
||||
}
|
||||
|
||||
/// [`build_for_launch`] of several modules of one Maven reactor in a single Maven run:
|
||||
/// one result per module, in order, sharing the build's failure.
|
||||
pub fn build_for_launches(
|
||||
root: &Path,
|
||||
model: &BuildModel,
|
||||
modules: &[PathBuf],
|
||||
test: bool,
|
||||
kind: BuildKind,
|
||||
cancel: &CancellationToken,
|
||||
on_event: &(dyn Fn(BuildEvent) + Sync),
|
||||
) -> IdeResult<Vec<LaunchBuild>> {
|
||||
let plan = merged_launch_plan(root, model, modules, test, kind, cancel)?;
|
||||
let result = run(root, &plan, cancel, on_event)?;
|
||||
let plan = launch_plan(root, model, module, test, kind)?;
|
||||
let result = run(root, &plan, cancel, &|_| {})?;
|
||||
let failure = if !result.success {
|
||||
let errors: Vec<String> = result
|
||||
.messages
|
||||
@@ -1007,70 +924,17 @@ pub fn build_for_launches(
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let class_dirs = |module: &Path| {
|
||||
if plan.system == BuildSystem::Maven
|
||||
&& let Some(m) = &model.maven
|
||||
{
|
||||
maven_launch_output_dirs(root, m, module, test).into_iter().filter(|dir| dir.is_dir()).collect()
|
||||
} else {
|
||||
launch_class_dirs(plan.system, module, test)
|
||||
}
|
||||
let class_dirs = if plan.system == BuildSystem::Maven
|
||||
&& let Some(m) = &model.maven
|
||||
{
|
||||
maven_launch_projects(root, m, module, test)
|
||||
.iter()
|
||||
.flat_map(|p| launch_class_dirs(plan.system, &subdir(root, &p.dir), test && subdir(root, &p.dir) == module))
|
||||
.collect()
|
||||
} else {
|
||||
launch_class_dirs(plan.system, module, test)
|
||||
};
|
||||
Ok(modules.iter().map(|m| LaunchBuild { class_dirs: class_dirs(m), failure: failure.clone() }).collect())
|
||||
}
|
||||
|
||||
/// Maven output directories for a launch, including directories that have yet to be created.
|
||||
pub fn maven_launch_output_dirs(root: &Path, model: &maven::MavenModel, module: &Path, test: bool) -> Vec<PathBuf> {
|
||||
maven_launch_projects(root, model, module, test)
|
||||
.into_iter()
|
||||
.flat_map(|p| {
|
||||
let dir = subdir(root, &p.dir);
|
||||
maven_output_dirs(&dir, test && dir == module)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The class directories of a Maven launch that must hold classes after its build: those of
|
||||
/// the launch projects with sources in a conventional JVM source root. One that is missing
|
||||
/// or holds no class was caught mid-rewrite, e.g. cleaned by a concurrent `mvn` (#5404).
|
||||
pub fn launch_required_class_dirs(root: &Path, model: &BuildModel, module: &Path, test: bool) -> Vec<PathBuf> {
|
||||
fn has_sources(dir: &Path, depth: u32) -> bool {
|
||||
let Ok(entries) = std::fs::read_dir(dir) else { return false };
|
||||
entries.flatten().any(|e| {
|
||||
let p = e.path();
|
||||
if p.is_dir() {
|
||||
depth > 0 && has_sources(&p, depth - 1)
|
||||
} else {
|
||||
// A package-info.java without annotations compiles to nothing.
|
||||
p.file_name() != Some("package-info.java".as_ref())
|
||||
&& p.extension().is_some_and(|x| x == "java" || x == "kt" || x == "groovy" || x == "scala")
|
||||
}
|
||||
})
|
||||
}
|
||||
let compiles = |dir: &Path, set: &str| {
|
||||
["java", "kotlin", "groovy", "scala"].iter().any(|lang| has_sources(&dir.join("src").join(set).join(lang), 32))
|
||||
};
|
||||
let Some(m) = &model.maven else { return Vec::new() };
|
||||
let mut dirs = Vec::new();
|
||||
for p in maven_launch_projects(root, m, module, test) {
|
||||
let dir = subdir(root, &p.dir);
|
||||
if test && dir == module && compiles(&dir, "test") {
|
||||
dirs.push(subdir(&dir, "target/test-classes"));
|
||||
}
|
||||
if compiles(&dir, "main") {
|
||||
dirs.push(subdir(&dir, "target/classes"));
|
||||
}
|
||||
}
|
||||
dirs
|
||||
}
|
||||
|
||||
fn maven_output_dirs(module: &Path, test: bool) -> Vec<PathBuf> {
|
||||
let mut dirs = Vec::new();
|
||||
if test {
|
||||
dirs.push(subdir(module, "target/test-classes"));
|
||||
}
|
||||
dirs.push(subdir(module, "target/classes"));
|
||||
dirs
|
||||
Ok(LaunchBuild { class_dirs, failure })
|
||||
}
|
||||
|
||||
fn launch_class_dirs(system: BuildSystem, module: &Path, test: bool) -> Vec<PathBuf> {
|
||||
@@ -1083,7 +947,8 @@ fn launch_class_dirs(system: BuildSystem, module: &Path, test: bool) -> Vec<Path
|
||||
.map(|d| subdir(module, &format!("build/{d}/{s}")))
|
||||
})
|
||||
.collect(),
|
||||
BuildSystem::Maven => maven_output_dirs(module, test),
|
||||
BuildSystem::Maven if test => vec![subdir(module, "target/test-classes"), subdir(module, "target/classes")],
|
||||
BuildSystem::Maven => vec![subdir(module, "target/classes")],
|
||||
_ => Vec::new(),
|
||||
};
|
||||
dirs.into_iter().filter(|d| d.is_dir()).collect()
|
||||
@@ -1107,9 +972,7 @@ mod tests {
|
||||
write(root, "../external/main.go", "package main\nimport \"example.com/lib\"\nfunc main(){_ = lib.Value()}\n");
|
||||
// std canonicalization also exercises verbatim paths on Windows.
|
||||
for root in [root.to_path_buf(), std::fs::canonicalize(root).unwrap()] {
|
||||
let plan =
|
||||
plan(&root, &BuildModel::default(), BuildKind::Build, None, None, None, &CancellationToken::new())
|
||||
.unwrap();
|
||||
let plan = plan(&root, &BuildModel::default(), BuildKind::Build, None, None).unwrap();
|
||||
for step in plan.steps {
|
||||
let result = std::process::Command::new(&go)
|
||||
.args(&step.args)
|
||||
@@ -1135,7 +998,7 @@ mod tests {
|
||||
let canonical = std::fs::canonicalize(&root).unwrap();
|
||||
for root in [&root, &canonical, &canonical.join("..").join("workspace")] {
|
||||
for kind in [BuildKind::Build, BuildKind::Rebuild, BuildKind::Artifacts] {
|
||||
let p = plan(root, &BuildModel::default(), kind, None, None, None, &CancellationToken::new()).unwrap();
|
||||
let p = plan(root, &BuildModel::default(), kind, None, None).unwrap();
|
||||
assert_eq!(p.system, BuildSystem::Go);
|
||||
assert_eq!(p.steps.len(), 3);
|
||||
for (step, module) in p.steps.iter().zip(["api", "lib with spaces", "../shared"]) {
|
||||
@@ -1150,30 +1013,20 @@ mod tests {
|
||||
}
|
||||
}
|
||||
}
|
||||
let member = plan(
|
||||
&root,
|
||||
&BuildModel::default(),
|
||||
BuildKind::Build,
|
||||
Some(&root.join("api/pkg/a.go")),
|
||||
None,
|
||||
None,
|
||||
&CancellationToken::new(),
|
||||
)
|
||||
.unwrap();
|
||||
let member =
|
||||
plan(&root, &BuildModel::default(), BuildKind::Build, Some(&root.join("api/pkg/a.go")), None).unwrap();
|
||||
assert_eq!(member.steps.len(), 1);
|
||||
assert_eq!(member.steps[0].cwd, root.join("api"));
|
||||
assert_eq!(member.steps[0].args, ["build", "./pkg/..."]);
|
||||
write(&root, "go.work", "use ./missing\n");
|
||||
assert!(
|
||||
plan(&root, &BuildModel::default(), BuildKind::Build, None, None, None, &CancellationToken::new())
|
||||
plan(&root, &BuildModel::default(), BuildKind::Build, None, None)
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("go.mod")
|
||||
);
|
||||
write(&root, "go.work", "go 1.22\n");
|
||||
assert!(
|
||||
plan(&root, &BuildModel::default(), BuildKind::Build, None, None, None, &CancellationToken::new()).is_err()
|
||||
);
|
||||
assert!(plan(&root, &BuildModel::default(), BuildKind::Build, None, None).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1194,21 +1047,11 @@ mod tests {
|
||||
let mut model = crate::load_linked(root, &root.join("cache"), None, &Default::default(), &settings);
|
||||
model.gradle[0].env.insert("JAVA_HOME".into(), "/jdk-a".into());
|
||||
model.gradle[1].env.insert("JAVA_HOME".into(), "/jdk-b".into());
|
||||
let all =
|
||||
super::plan(root, &model, super::BuildKind::Build, None, None, None, &CancellationToken::new()).unwrap();
|
||||
let all = super::plan(root, &model, super::BuildKind::Build, None, None).unwrap();
|
||||
assert_eq!(all.steps.len(), 2);
|
||||
assert_eq!(all.steps[0].cwd, root.join("a"));
|
||||
assert_eq!(all.steps[1].cwd, root.join("b"));
|
||||
let module = super::plan(
|
||||
root,
|
||||
&model,
|
||||
super::BuildKind::Rebuild,
|
||||
Some(&root.join("b/app")),
|
||||
None,
|
||||
None,
|
||||
&CancellationToken::new(),
|
||||
)
|
||||
.unwrap();
|
||||
let module = super::plan(root, &model, super::BuildKind::Rebuild, Some(&root.join("b/app")), None).unwrap();
|
||||
assert_eq!(module.steps.len(), 1);
|
||||
assert_eq!(module.steps[0].program, root.join("b").join(wrapper).to_string_lossy());
|
||||
assert_eq!(module.steps[0].cwd, root.join("b"));
|
||||
@@ -1221,31 +1064,11 @@ mod tests {
|
||||
let mut nested = model.gradle[1].projects[1].clone();
|
||||
nested.path = ":b:app".into();
|
||||
model.gradle[0].projects.push(nested);
|
||||
let nested = super::plan(
|
||||
root,
|
||||
&model,
|
||||
super::BuildKind::Build,
|
||||
Some(&root.join("b/app")),
|
||||
None,
|
||||
None,
|
||||
&CancellationToken::new(),
|
||||
)
|
||||
.unwrap();
|
||||
let nested = super::plan(root, &model, super::BuildKind::Build, Some(&root.join("b/app")), None).unwrap();
|
||||
assert_eq!(nested.steps[0].program, root.join("b").join(wrapper).to_string_lossy());
|
||||
assert_eq!(nested.steps[0].args, ["--console=plain", ":app:classes", ":app:testClasses"]);
|
||||
model.gradle.clear();
|
||||
assert!(
|
||||
super::plan(
|
||||
root,
|
||||
&model,
|
||||
super::BuildKind::Build,
|
||||
Some(&root.join("b/app")),
|
||||
None,
|
||||
None,
|
||||
&CancellationToken::new()
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
assert!(super::plan(root, &model, super::BuildKind::Build, Some(&root.join("b/app")), None).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1267,24 +1090,18 @@ mod tests {
|
||||
};
|
||||
let mut model = crate::load_linked(&root, &base.join("cache"), None, &Default::default(), &settings);
|
||||
model.gradle[0].env.insert("JAVA_HOME".into(), "/external-jdk".into());
|
||||
let all =
|
||||
super::plan(&root, &model, super::BuildKind::Build, None, None, None, &CancellationToken::new()).unwrap();
|
||||
let all = super::plan(&root, &model, super::BuildKind::Build, None, None).unwrap();
|
||||
assert_eq!(all.steps[0].cwd, external);
|
||||
// Linked roots are saved with forward slashes, so on Windows the program mixes separators.
|
||||
assert_eq!(std::path::Path::new(&all.steps[0].program), external.join(wrapper));
|
||||
let module =
|
||||
super::plan(&root, &model, super::BuildKind::Rebuild, Some(&source), None, None, &CancellationToken::new())
|
||||
.unwrap();
|
||||
let module = super::plan(&root, &model, super::BuildKind::Rebuild, Some(&source), None).unwrap();
|
||||
assert_eq!(module.steps[0].cwd, external);
|
||||
assert_eq!(module.steps[0].env["JAVA_HOME"], "/external-jdk");
|
||||
assert_eq!(module.steps[0].args, ["--console=plain", ":app:clean", ":app:classes", ":app:testClasses"]);
|
||||
let other = base.join("unlinked");
|
||||
std::fs::create_dir(&other).unwrap();
|
||||
std::fs::write(other.join("build.gradle"), "").unwrap();
|
||||
assert!(
|
||||
super::plan(&root, &model, super::BuildKind::Build, Some(&other), None, None, &CancellationToken::new())
|
||||
.is_err()
|
||||
);
|
||||
assert!(super::plan(&root, &model, super::BuildKind::Build, Some(&other), None).is_err());
|
||||
}
|
||||
use super::*;
|
||||
|
||||
@@ -1325,7 +1142,7 @@ mod tests {
|
||||
write(&root, "pom.xml", "<project><artifactId>demo</artifactId></project>");
|
||||
let model = crate::load(&root, &tmp.path().join("cache"), None);
|
||||
for (kind, expected) in [(BuildKind::Build, true), (BuildKind::Rebuild, true), (BuildKind::Artifacts, false)] {
|
||||
let plan = plan(&root, &model, kind, None, None, None, &CancellationToken::new()).unwrap();
|
||||
let plan = plan(&root, &model, kind, None, None).unwrap();
|
||||
assert_eq!(
|
||||
plan.steps[0].args.iter().any(|arg| arg == "-Djacoco.skip=true"),
|
||||
expected,
|
||||
@@ -1346,7 +1163,7 @@ mod tests {
|
||||
write(&root, "core/pom.xml", "<project><artifactId>core</artifactId></project>");
|
||||
write(&root, "core/src/main/java/A.java", "class A {}");
|
||||
let model = crate::load(&root, &tmp.path().join("cache"), None);
|
||||
let p = plan(&root, &model, BuildKind::Build, None, None, None, &CancellationToken::new()).unwrap();
|
||||
let p = plan(&root, &model, BuildKind::Build, None, None).unwrap();
|
||||
assert_eq!(p.system, BuildSystem::Maven);
|
||||
assert_eq!(p.title, "demo");
|
||||
assert_eq!(p.steps.len(), 1);
|
||||
@@ -1354,16 +1171,7 @@ mod tests {
|
||||
p.steps[0].args,
|
||||
["-B", "-Dstyle.color=never", maven::LOCAL_REPO_TRACKING_ARG, "-Djacoco.skip=true", "test-compile"]
|
||||
);
|
||||
let p = plan(
|
||||
&root,
|
||||
&model,
|
||||
BuildKind::Rebuild,
|
||||
Some(&root.join("core/src/main/java/A.java")),
|
||||
None,
|
||||
None,
|
||||
&CancellationToken::new(),
|
||||
)
|
||||
.unwrap();
|
||||
let p = plan(&root, &model, BuildKind::Rebuild, Some(&root.join("core/src/main/java/A.java")), None).unwrap();
|
||||
assert_eq!(
|
||||
p.steps[0].args,
|
||||
[
|
||||
@@ -1385,36 +1193,24 @@ mod tests {
|
||||
write(&g, "settings.gradle", "include 'app'");
|
||||
write(&g, "app/build.gradle", "apply plugin: 'java'");
|
||||
let model = crate::load(&g, &tmp.path().join("cache2"), None);
|
||||
let p =
|
||||
plan(&g, &model, BuildKind::Build, Some(&g.join("app/src/A.java")), None, None, &CancellationToken::new())
|
||||
.unwrap();
|
||||
let p = plan(&g, &model, BuildKind::Build, Some(&g.join("app/src/A.java")), None).unwrap();
|
||||
assert_eq!(p.system, BuildSystem::Gradle);
|
||||
assert_eq!(p.steps[0].args, ["--console=plain", ":app:classes", ":app:testClasses"]);
|
||||
assert_eq!(
|
||||
plan(&g, &model, BuildKind::Artifacts, None, None, None, &CancellationToken::new()).unwrap().steps[0].args,
|
||||
plan(&g, &model, BuildKind::Artifacts, None, None).unwrap().steps[0].args,
|
||||
["--console=plain", "assemble"]
|
||||
);
|
||||
|
||||
let c = tmp.path().join("c");
|
||||
write(&c, "Cargo.toml", "[package]\nname='c'");
|
||||
let p =
|
||||
plan(&c, &BuildModel::default(), BuildKind::Rebuild, None, None, None, &CancellationToken::new()).unwrap();
|
||||
let p = plan(&c, &BuildModel::default(), BuildKind::Rebuild, None, None).unwrap();
|
||||
assert_eq!(p.system, BuildSystem::Cargo);
|
||||
assert_eq!(p.steps.len(), 2);
|
||||
assert_eq!(p.steps[0].args[0], "clean");
|
||||
|
||||
let go = tmp.path().join("go");
|
||||
write(&go, "go.mod", "module x");
|
||||
let p = plan(
|
||||
&go,
|
||||
&BuildModel::default(),
|
||||
BuildKind::Build,
|
||||
Some(&go.join("pkg/a/a.go")),
|
||||
None,
|
||||
None,
|
||||
&CancellationToken::new(),
|
||||
)
|
||||
.unwrap();
|
||||
let p = plan(&go, &BuildModel::default(), BuildKind::Build, Some(&go.join("pkg/a/a.go")), None).unwrap();
|
||||
assert_eq!(p.steps[0].args, ["build", "./pkg/a/..."]);
|
||||
assert_eq!(p.steps[0].cwd, go);
|
||||
|
||||
@@ -1422,11 +1218,9 @@ mod tests {
|
||||
write(&ts, "package.json", r#"{"scripts":{"build":"vite build"}}"#);
|
||||
write(&ts, "tsconfig.json", "{}");
|
||||
write(&ts, "pnpm-lock.yaml", "");
|
||||
let p =
|
||||
plan(&ts, &BuildModel::default(), BuildKind::Build, None, None, None, &CancellationToken::new()).unwrap();
|
||||
let p = plan(&ts, &BuildModel::default(), BuildKind::Build, None, None).unwrap();
|
||||
assert_eq!(p.steps[0].args, ["--noEmit", "--pretty", "false", "-p", "."]);
|
||||
let p = plan(&ts, &BuildModel::default(), BuildKind::Artifacts, None, None, None, &CancellationToken::new())
|
||||
.unwrap();
|
||||
let p = plan(&ts, &BuildModel::default(), BuildKind::Artifacts, None, None).unwrap();
|
||||
assert_eq!(
|
||||
(p.steps[0].program.as_str(), p.steps[0].args.as_slice()),
|
||||
("pnpm", &["run".to_owned(), "build".to_owned()][..])
|
||||
@@ -1439,32 +1233,21 @@ mod tests {
|
||||
write(&net, "src/Api/Api.csproj", "<Project/>");
|
||||
write(&net, "src/Api/package.json", "{}");
|
||||
write(&net, "src/Api/Program.cs", "");
|
||||
let p =
|
||||
plan(&net, &BuildModel::default(), BuildKind::Build, None, None, None, &CancellationToken::new()).unwrap();
|
||||
let p = plan(&net, &BuildModel::default(), BuildKind::Build, None, None).unwrap();
|
||||
assert_eq!(p.system, BuildSystem::Dotnet);
|
||||
assert_eq!(p.steps[0].args, ["build", "App.sln", "-nologo", "-clp:NoSummary"]);
|
||||
assert_eq!(p.steps[0].env["MSBUILDTERMINALLOGGER"], "off");
|
||||
let p = plan(
|
||||
&net,
|
||||
&BuildModel::default(),
|
||||
BuildKind::Rebuild,
|
||||
Some(&net.join("src/Api/Program.cs")),
|
||||
None,
|
||||
None,
|
||||
&CancellationToken::new(),
|
||||
)
|
||||
.unwrap();
|
||||
let p = plan(&net, &BuildModel::default(), BuildKind::Rebuild, Some(&net.join("src/Api/Program.cs")), None)
|
||||
.unwrap();
|
||||
assert_eq!(p.steps[0].args, ["build", "Api.csproj", "-nologo", "-clp:NoSummary", "--no-incremental"]);
|
||||
assert_eq!(p.steps[0].cwd, net.join("src/Api"));
|
||||
let p = plan(&net, &BuildModel::default(), BuildKind::Artifacts, None, None, None, &CancellationToken::new())
|
||||
.unwrap();
|
||||
let p = plan(&net, &BuildModel::default(), BuildKind::Artifacts, None, None).unwrap();
|
||||
assert_eq!(p.steps[0].args[0], "publish");
|
||||
|
||||
let cm = tmp.path().join("cm");
|
||||
write(&cm, "CMakeLists.txt", "project(app)");
|
||||
let args = |p: &BuildPlan| p.steps.iter().map(|s| s.args.join(" ")).collect::<Vec<_>>();
|
||||
let p =
|
||||
plan(&cm, &BuildModel::default(), BuildKind::Build, None, None, None, &CancellationToken::new()).unwrap();
|
||||
let p = plan(&cm, &BuildModel::default(), BuildKind::Build, None, None).unwrap();
|
||||
assert_eq!(p.system, BuildSystem::CMake);
|
||||
assert_eq!(
|
||||
args(&p),
|
||||
@@ -1475,8 +1258,7 @@ mod tests {
|
||||
"an unconfigured project is configured first"
|
||||
);
|
||||
write(&cm, "cmake-build-release/CMakeCache.txt", "");
|
||||
let p =
|
||||
plan(&cm, &BuildModel::default(), BuildKind::Rebuild, None, None, None, &CancellationToken::new()).unwrap();
|
||||
let p = plan(&cm, &BuildModel::default(), BuildKind::Rebuild, None, None).unwrap();
|
||||
assert_eq!(
|
||||
args(&p),
|
||||
["--build cmake-build-release --config Debug --clean-first"],
|
||||
@@ -1488,34 +1270,17 @@ mod tests {
|
||||
build_args: vec!["-j".into(), "8".into()],
|
||||
..CMakeProfile::default()
|
||||
};
|
||||
let p = plan(
|
||||
&cm,
|
||||
&BuildModel::default(),
|
||||
BuildKind::Build,
|
||||
None,
|
||||
Some(std::slice::from_ref(&profile)),
|
||||
None,
|
||||
&CancellationToken::new(),
|
||||
)
|
||||
.unwrap();
|
||||
let p =
|
||||
plan(&cm, &BuildModel::default(), BuildKind::Build, None, Some(std::slice::from_ref(&profile))).unwrap();
|
||||
assert_eq!(args(&p), ["--build cmake-build-release --config Release -j 8"]);
|
||||
let p = plan(
|
||||
&cm,
|
||||
&BuildModel::default(),
|
||||
BuildKind::Build,
|
||||
None,
|
||||
Some(&[CMakeProfile::default()]),
|
||||
None,
|
||||
&CancellationToken::new(),
|
||||
)
|
||||
.unwrap();
|
||||
let p = plan(&cm, &BuildModel::default(), BuildKind::Build, None, Some(&[CMakeProfile::default()])).unwrap();
|
||||
assert_eq!(p.steps[0].args[..4], ["-S", ".", "-B", "cmake-build-debug"]);
|
||||
|
||||
let siblings = tmp.path().join("siblings");
|
||||
write(&siblings, "core/pom.xml", "<project><artifactId>core</artifactId></project>");
|
||||
write(&siblings, "system/pom.xml", "<project><artifactId>system</artifactId></project>");
|
||||
let model = crate::load(&siblings, &tmp.path().join("cache3"), None);
|
||||
let p = plan(&siblings, &model, BuildKind::Build, None, None, None, &CancellationToken::new()).unwrap();
|
||||
let p = plan(&siblings, &model, BuildKind::Build, None, None).unwrap();
|
||||
assert_eq!(p.system, BuildSystem::Maven);
|
||||
assert_eq!(
|
||||
p.steps.iter().map(|s| s.cwd.clone()).collect::<Vec<_>>(),
|
||||
@@ -1524,9 +1289,7 @@ mod tests {
|
||||
|
||||
let none = tmp.path().join("none");
|
||||
std::fs::create_dir_all(&none).unwrap();
|
||||
assert!(
|
||||
plan(&none, &BuildModel::default(), BuildKind::Build, None, None, None, &CancellationToken::new()).is_err()
|
||||
);
|
||||
assert!(plan(&none, &BuildModel::default(), BuildKind::Build, None, None).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1540,22 +1303,6 @@ mod tests {
|
||||
assert_eq!(identifier_len("x é_1 c", 2), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolves_a_member_build_s_workspace_relative_paths() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path().to_path_buf();
|
||||
write(&root, "client/src/main.rs", "fn main() {}\n");
|
||||
write(&root, "client/src/lib.rs", "\n");
|
||||
write(&root, "src/lib.rs", "\n");
|
||||
let map = PathMap { root: root.clone(), canonical: None };
|
||||
let member = root.join("client");
|
||||
let base = member.to_str();
|
||||
// Build Module runs in the member; rustc names its files from the workspace root.
|
||||
assert_eq!(map.resolve("client/src/main.rs", &member, base), root.join("client/src/main.rs"));
|
||||
// A crate built from its own directory names them from there.
|
||||
assert_eq!(map.resolve("src/lib.rs", &member, base), member.join("src/lib.rs"));
|
||||
}
|
||||
|
||||
// Uses Unix absolute paths for the canonical root.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
@@ -1725,8 +1472,7 @@ mod tests {
|
||||
let model = reactor_model();
|
||||
for (test, goal) in [(false, "compile"), (true, "test-compile")] {
|
||||
// A normal launch is incremental: no `clean` (IDEA's Make, not Rebuild).
|
||||
let plan = launch_plan(root, &model, &root.join("app"), test, BuildKind::Build, &CancellationToken::new())
|
||||
.unwrap();
|
||||
let plan = launch_plan(root, &model, &root.join("app"), test, BuildKind::Build).unwrap();
|
||||
let step = &plan.steps[0];
|
||||
assert_eq!(step.cwd, root);
|
||||
assert_eq!(step.program, "mvnw");
|
||||
@@ -1747,9 +1493,7 @@ mod tests {
|
||||
]
|
||||
);
|
||||
// Rebuild cleans first, as IDEA's Rebuild does.
|
||||
let plan =
|
||||
launch_plan(root, &model, &root.join("app"), test, BuildKind::Rebuild, &CancellationToken::new())
|
||||
.unwrap();
|
||||
let plan = launch_plan(root, &model, &root.join("app"), test, BuildKind::Rebuild).unwrap();
|
||||
assert_eq!(
|
||||
plan.steps[0].args,
|
||||
[
|
||||
@@ -1769,46 +1513,6 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn launches_of_one_reactor_merge_into_one_module_selection() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
for dir in ["app", "lib", "unrelated"] {
|
||||
write(root, &format!("{dir}/pom.xml"), "<project/>");
|
||||
}
|
||||
let mut model = reactor_model();
|
||||
let cancel = CancellationToken::new();
|
||||
let modules = |dirs: &[&str]| dirs.iter().map(|d| root.join(d)).collect::<Vec<_>>();
|
||||
let selection = |plan: BuildPlan| {
|
||||
let args = &plan.steps[0].args;
|
||||
args.iter().position(|a| a == "-pl").map(|i| (args[i + 1].clone(), args[i + 2].clone(), args.len()))
|
||||
};
|
||||
assert_eq!(launch_reactor(root, &model, &root.join("lib")).as_deref(), Some(""));
|
||||
let plan = merged_launch_plan(root, &model, &modules(&["lib", "app", "lib"]), false, BuildKind::Build, &cancel)
|
||||
.unwrap();
|
||||
assert_eq!(plan.steps.len(), 1);
|
||||
assert_eq!(plan.steps[0].args.last().unwrap(), "compile");
|
||||
assert_eq!(selection(plan), Some(("app,lib".into(), "-am".into(), 10)));
|
||||
// One module: exactly the single launch's step.
|
||||
let single = merged_launch_plan(root, &model, &modules(&["app"]), true, BuildKind::Rebuild, &cancel).unwrap();
|
||||
let expected = launch_plan(root, &model, &root.join("app"), true, BuildKind::Rebuild, &cancel).unwrap();
|
||||
assert_eq!(single.steps[0].args, expected.steps[0].args);
|
||||
// The reactor root among them builds the whole reactor.
|
||||
model.maven.as_mut().unwrap().projects[0].packaging = "jar".into();
|
||||
let whole = merged_launch_plan(root, &model, &modules(&["app", ""]), false, BuildKind::Build, &cancel).unwrap();
|
||||
assert_eq!(selection(whole), None);
|
||||
// Another linked reactor can't join the step.
|
||||
let m = model.maven.as_mut().unwrap();
|
||||
m.projects[4].aggregated = false;
|
||||
m.projects[4].command = "other".into();
|
||||
m.projects[0].modules.retain(|p| p != "unrelated/pom.xml");
|
||||
assert_eq!(launch_reactor(root, &model, &root.join("unrelated")).as_deref(), Some("unrelated"));
|
||||
assert!(
|
||||
merged_launch_plan(root, &model, &modules(&["app", "unrelated"]), false, BuildKind::Build, &cancel)
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn external_launch_returns_upstream_outputs_and_blocks_failure_or_cancellation() {
|
||||
@@ -1825,16 +1529,8 @@ mod tests {
|
||||
std::fs::set_permissions(&wrapper, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
let mut model = reactor_model();
|
||||
model.maven.as_mut().unwrap().projects[0].command = wrapper.to_string_lossy().into_owned();
|
||||
let dirs = build_for_launch(
|
||||
root,
|
||||
&model,
|
||||
&root.join("app"),
|
||||
true,
|
||||
BuildKind::Build,
|
||||
&CancellationToken::new(),
|
||||
&|_| {},
|
||||
)
|
||||
.unwrap();
|
||||
let dirs = build_for_launch(root, &model, &root.join("app"), true, BuildKind::Build, &CancellationToken::new())
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
dirs.class_dirs,
|
||||
["app/target/test-classes", "app/target/classes", "middle/target/classes", "lib/target/classes"]
|
||||
@@ -1845,25 +1541,16 @@ mod tests {
|
||||
"mvnw",
|
||||
"#!/bin/sh\necho '[ERROR] Kotlin compilation failed: unresolved reference broken' >&2\nexit 1\n",
|
||||
);
|
||||
let error = build_for_launch(
|
||||
root,
|
||||
&model,
|
||||
&root.join("app"),
|
||||
false,
|
||||
BuildKind::Build,
|
||||
&CancellationToken::new(),
|
||||
&|_| {},
|
||||
)
|
||||
.unwrap()
|
||||
.failure
|
||||
.unwrap();
|
||||
let error =
|
||||
build_for_launch(root, &model, &root.join("app"), false, BuildKind::Build, &CancellationToken::new())
|
||||
.unwrap()
|
||||
.failure
|
||||
.unwrap();
|
||||
assert!(error.contains("Kotlin compilation failed"), "{error}");
|
||||
let cancel = CancellationToken::new();
|
||||
cancel.cancel();
|
||||
assert_eq!(
|
||||
build_for_launch(root, &model, &root.join("app"), false, BuildKind::Build, &cancel, &|_| {})
|
||||
.unwrap_err()
|
||||
.kind,
|
||||
build_for_launch(root, &model, &root.join("app"), false, BuildKind::Build, &cancel).unwrap_err().kind,
|
||||
ide_core::error::ErrorKind::Cancelled
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,408 +0,0 @@
|
||||
//! Module-scoped Maven menu builds (`Build Project` on a multi-module reactor, #4078).
|
||||
//!
|
||||
//! A project build used to run every linked reactor from end to end; only the
|
||||
//! all-or-nothing up-to-date check could skip it, so one edited file anywhere
|
||||
//! paid a full reactor build. This module narrows the scope: per-module input
|
||||
//! fingerprints recorded after the last successful build tell which modules'
|
||||
//! sources, resources, POM chain or outputs changed, the module dependency graph
|
||||
//! spreads that to the modules depending on them, and the reactor runs
|
||||
//! `mvn -pl <modules> -am` over just that set. Maven still decides what
|
||||
//! recompiles inside the selected modules; `-am` keeps the upstream modules a
|
||||
//! changed module was built against. Reactors without a usable record, and any
|
||||
//! analysis that cannot resolve its inputs, build everything as before.
|
||||
|
||||
use super::up_to_date::restamp;
|
||||
use super::*;
|
||||
use std::fs;
|
||||
|
||||
/// The per-module input fingerprints of one reactor's last successful build.
|
||||
#[derive(serde::Serialize, serde::Deserialize)]
|
||||
struct ReactorRecord {
|
||||
/// Module directory (project-relative, `/`-separated) → its record.
|
||||
modules: BTreeMap<String, ModuleRecord>,
|
||||
}
|
||||
|
||||
#[derive(serde::Serialize, serde::Deserialize)]
|
||||
struct ModuleRecord {
|
||||
fingerprint: LaunchFingerprint,
|
||||
/// Output folders of the module that existed after the build, relative to the
|
||||
/// project. Deleting one outside the IDE (`mvn clean` in a terminal) leaves every
|
||||
/// input unchanged, so the module is rebuilt only while they are gone.
|
||||
outputs: Vec<PathBuf>,
|
||||
}
|
||||
|
||||
fn record_path(cache: &Path, top_dir: &str) -> PathBuf {
|
||||
let base = cache.join("menu-build").join("modules");
|
||||
if top_dir.is_empty() { base.join("root.json") } else { base.join(format!("{top_dir}.json")) }
|
||||
}
|
||||
|
||||
fn load_record(cache: &Path, top_dir: &str) -> Option<ReactorRecord> {
|
||||
let bytes = fs::read(record_path(cache, top_dir)).ok()?;
|
||||
serde_json::from_slice(&bytes).ok()
|
||||
}
|
||||
|
||||
/// Projects of `reactor` that (transitively) depend on one of `changed`, through
|
||||
/// dependencies whose version matches the provider. The reverse of the launch
|
||||
/// upstream walk: a changed module's new classes force its consumers to recompile,
|
||||
/// `test`-scoped ones included, since the project build compiles every module's tests.
|
||||
fn affected_projects(reactor: &[&maven::MavenProject], changed: &HashSet<String>) -> HashSet<String> {
|
||||
let mut affected = changed.clone();
|
||||
let mut pending: Vec<&str> = changed.iter().map(String::as_str).collect();
|
||||
while let Some(dir) = pending.pop() {
|
||||
let Some(upstream) = reactor.iter().find(|p| p.dir == dir) else { continue };
|
||||
for consumer in reactor {
|
||||
if affected.contains(&consumer.dir) {
|
||||
continue;
|
||||
}
|
||||
let depends = consumer.dependencies.iter().any(|d| {
|
||||
d.resolved()
|
||||
&& upstream.group_id == d.group_id
|
||||
&& upstream.artifact_id == d.artifact_id
|
||||
&& d.version.as_ref().is_none_or(|v| *v == upstream.version)
|
||||
});
|
||||
if depends {
|
||||
affected.insert(consumer.dir.clone());
|
||||
pending.push(consumer.dir.as_str());
|
||||
}
|
||||
}
|
||||
}
|
||||
affected
|
||||
}
|
||||
|
||||
/// `-pl` entries of the affected modules, relative to the reactor root the step
|
||||
/// runs in, sorted so the command line does not depend on the model's project
|
||||
/// order (Maven reorders the selection into its own reactor order anyway).
|
||||
fn selection(reactor: &[&maven::MavenProject], top_dir: &str, affected: &HashSet<String>) -> String {
|
||||
let mut entries: Vec<String> = reactor
|
||||
.iter()
|
||||
.filter(|p| affected.contains(&p.dir))
|
||||
.map(|p| {
|
||||
Path::new(&p.dir).strip_prefix(top_dir).unwrap_or(Path::new(&p.dir)).to_string_lossy().replace('\\', "/")
|
||||
})
|
||||
.collect();
|
||||
entries.sort();
|
||||
entries.join(",")
|
||||
}
|
||||
|
||||
/// Narrowed `Build Project` steps: per reactor, one full step when the reactor
|
||||
/// or most of it is affected, one `-pl <modules> -am` step for the affected
|
||||
/// subset, or no step at all when nothing changed since the last successful
|
||||
/// build. `None` = some module's inputs cannot be fingerprinted, so the caller
|
||||
/// falls back to the unscoped build. The `step` closure builds a reactor step
|
||||
/// with the caller's goals and options.
|
||||
pub(super) fn narrowed_maven_steps(
|
||||
cache: &Path,
|
||||
root: &Path,
|
||||
m: &maven::MavenModel,
|
||||
step: &impl Fn(&maven::MavenProject, &[String]) -> BuildStep,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<Option<Vec<BuildStep>>> {
|
||||
let mut steps = Vec::new();
|
||||
for top in m.projects.iter().filter(|p| !p.aggregated) {
|
||||
let Some(record) = load_record(cache, &top.dir) else {
|
||||
steps.push(step(top, &[]));
|
||||
continue;
|
||||
};
|
||||
let reactor = reactor_projects(m, top);
|
||||
let mut changed = HashSet::new();
|
||||
let mut lying: Vec<PathBuf> = Vec::new();
|
||||
for project in &reactor {
|
||||
let Some(current) = fingerprint::module_fingerprint(root, project, cancel)? else {
|
||||
return Ok(None);
|
||||
};
|
||||
let Some(recorded) = record.modules.get(&project.dir) else {
|
||||
changed.insert(project.dir.clone());
|
||||
continue;
|
||||
};
|
||||
if recorded.fingerprint != current {
|
||||
changed.insert(project.dir.clone());
|
||||
lying.extend(recorded.fingerprint.mtime_preserved_edits(¤t));
|
||||
}
|
||||
if !recorded.outputs.iter().all(|out| root.join(out).is_dir()) {
|
||||
changed.insert(project.dir.clone());
|
||||
}
|
||||
}
|
||||
if changed.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let affected = affected_projects(&reactor, &changed);
|
||||
restamp(root, &lying);
|
||||
if affected.len() >= reactor.len() || affected.contains(&top.dir) {
|
||||
steps.push(step(top, &[]));
|
||||
} else {
|
||||
let pl = selection(&reactor, &top.dir, &affected);
|
||||
steps.push(step(top, &["-pl".into(), pl, "-am".into()]));
|
||||
}
|
||||
}
|
||||
Ok(Some(steps))
|
||||
}
|
||||
|
||||
/// Records the per-module inputs of every linked reactor as the baseline of the
|
||||
/// next narrowed build. Failures are swallowed: a missing record only costs one
|
||||
/// unscoped Maven run. Called after a successful project build.
|
||||
pub fn record_module_build(cache: &Path, root: &Path, model: &BuildModel, cancel: &CancellationToken) {
|
||||
let Some(m) = &model.maven else { return };
|
||||
for top in m.projects.iter().filter(|p| !p.aggregated) {
|
||||
let mut modules = BTreeMap::new();
|
||||
for project in reactor_projects(m, top) {
|
||||
let Ok(Some(fingerprint)) = fingerprint::module_fingerprint(root, project, cancel) else { continue };
|
||||
let outputs = ["target/classes", "target/test-classes"]
|
||||
.iter()
|
||||
.map(|out| Path::new(&project.dir).join(out))
|
||||
.filter(|rel| root.join(rel).is_dir())
|
||||
.collect();
|
||||
modules.insert(project.dir.clone(), ModuleRecord { fingerprint, outputs });
|
||||
}
|
||||
let path = record_path(cache, &top.dir);
|
||||
if path.parent().is_some_and(|p| fs::create_dir_all(p).is_err()) {
|
||||
continue;
|
||||
}
|
||||
let Ok(bytes) = serde_json::to_vec(&ReactorRecord { modules }) else { continue };
|
||||
let _ = fs::write(&path, bytes);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn write(root: &Path, rel: &str, value: &str) {
|
||||
let path = root.join(rel);
|
||||
fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
fs::write(path, value).unwrap();
|
||||
}
|
||||
|
||||
/// `other` ← nothing, `app` ← `mid` ← `lib`, all under one reactor root.
|
||||
fn fixture(root: &Path) -> BuildModel {
|
||||
write(
|
||||
root,
|
||||
"pom.xml",
|
||||
r#"<project><modelVersion>4.0.0</modelVersion><groupId>t</groupId><artifactId>root</artifactId><version>1</version><packaging>pom</packaging><modules><module>lib</module><module>mid</module><module>app</module><module>other</module></modules></project>"#,
|
||||
);
|
||||
for (dir, class, deps) in [
|
||||
("lib", "L", ""),
|
||||
(
|
||||
"mid",
|
||||
"M",
|
||||
"<dependencies><dependency><groupId>t</groupId><artifactId>lib</artifactId><version>1</version></dependency></dependencies>",
|
||||
),
|
||||
(
|
||||
"app",
|
||||
"A",
|
||||
"<dependencies><dependency><groupId>t</groupId><artifactId>mid</artifactId><version>1</version></dependency></dependencies>",
|
||||
),
|
||||
("other", "O", ""),
|
||||
] {
|
||||
write(
|
||||
root,
|
||||
&format!("{dir}/pom.xml"),
|
||||
&format!(
|
||||
r#"<project><modelVersion>4.0.0</modelVersion><parent><groupId>t</groupId><artifactId>root</artifactId><version>1</version></parent><artifactId>{dir}</artifactId>{deps}</project>"#
|
||||
),
|
||||
);
|
||||
write(
|
||||
root,
|
||||
&format!("{dir}/src/main/java/t/{class}.java"),
|
||||
&format!("package t; public class {class} {{}}"),
|
||||
);
|
||||
}
|
||||
BuildModel { maven: Some(maven::load(root)), ..Default::default() }
|
||||
}
|
||||
|
||||
fn steps(cache: &Path, root: &Path, model: &BuildModel) -> Option<Vec<BuildStep>> {
|
||||
narrowed_maven_steps(
|
||||
cache,
|
||||
root,
|
||||
model.maven.as_ref().unwrap(),
|
||||
&|p, extra| {
|
||||
let mut s = BuildStep::new(&p.command, &["-B"], &subdir(root, &p.dir), Format::Maven);
|
||||
s.args.extend(extra.iter().cloned());
|
||||
s.args.push("test-compile".into());
|
||||
s
|
||||
},
|
||||
&CancellationToken::new(),
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn pl_arg(step: &BuildStep) -> String {
|
||||
let i = step.args.iter().position(|a| a == "-pl").unwrap();
|
||||
step.args[i + 1].clone()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn changed_module_selects_itself_and_transitive_dependents() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
let model = fixture(root);
|
||||
let cache = root.join("cache");
|
||||
record_module_build(&cache, root, &model, &CancellationToken::new());
|
||||
write(root, "lib/src/main/java/t/L.java", "package t; public class L { int x; }");
|
||||
let steps = steps(&cache, root, &model).unwrap();
|
||||
assert_eq!(steps.len(), 1);
|
||||
assert_eq!(pl_arg(&steps[0]), "app,lib,mid");
|
||||
assert!(steps[0].args.contains(&"-am".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unchanged_reactor_runs_nothing() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
let model = fixture(root);
|
||||
let cache = root.join("cache");
|
||||
record_module_build(&cache, root, &model, &CancellationToken::new());
|
||||
assert!(steps(&cache, root, &model).unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_or_corrupt_record_builds_everything() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
let model = fixture(root);
|
||||
let cache = root.join("cache");
|
||||
assert_eq!(steps(&cache, root, &model).unwrap().len(), 1);
|
||||
record_module_build(&cache, root, &model, &CancellationToken::new());
|
||||
fs::create_dir_all(cache.join("menu-build").join("modules")).unwrap();
|
||||
fs::write(cache.join("menu-build").join("modules").join("root.json"), b"{not json").unwrap();
|
||||
assert_eq!(steps(&cache, root, &model).unwrap().len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deleted_output_rebuilds_the_module_without_spreading() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
let model = fixture(root);
|
||||
let cache = root.join("cache");
|
||||
for out in ["mid/target/classes/t", "other/target/classes"] {
|
||||
fs::create_dir_all(root.join(out)).unwrap();
|
||||
}
|
||||
record_module_build(&cache, root, &model, &CancellationToken::new());
|
||||
fs::remove_dir_all(root.join("mid/target")).unwrap();
|
||||
let steps = steps(&cache, root, &model).unwrap();
|
||||
assert_eq!(pl_arg(&steps[0]), "app,mid");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mtime_preserved_edit_is_restamped_before_the_build() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
let model = fixture(root);
|
||||
let cache = root.join("cache");
|
||||
let rel = "lib/src/main/java/t/L.java";
|
||||
write(root, rel, "package t; public class L { int x; }");
|
||||
let mtime = fs::metadata(root.join(rel)).unwrap().modified().unwrap();
|
||||
record_module_build(&cache, root, &model, &CancellationToken::new());
|
||||
write(root, rel, "package t; public class L { int z; }");
|
||||
fs::File::options().write(true).open(root.join(rel)).unwrap().set_modified(mtime).unwrap();
|
||||
assert!(!steps(&cache, root, &model).unwrap().is_empty());
|
||||
assert!(fs::metadata(root.join(rel)).unwrap().modified().unwrap() > mtime);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_scoped_consumers_are_rebuilt_and_version_mismatch_does_not_spread() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
write(
|
||||
root,
|
||||
"pom.xml",
|
||||
r#"<project><modelVersion>4.0.0</modelVersion><groupId>t</groupId><artifactId>root</artifactId><version>1</version><packaging>pom</packaging><modules><module>lib</module><module>tester</module><module>v2</module></modules></project>"#,
|
||||
);
|
||||
write(
|
||||
root,
|
||||
"lib/pom.xml",
|
||||
r#"<project><modelVersion>4.0.0</modelVersion><parent><groupId>t</groupId><artifactId>root</artifactId><version>1</version></parent><artifactId>lib</artifactId></project>"#,
|
||||
);
|
||||
write(
|
||||
root,
|
||||
"tester/pom.xml",
|
||||
r#"<project><modelVersion>4.0.0</modelVersion><parent><groupId>t</groupId><artifactId>root</artifactId><version>1</version></parent><artifactId>tester</artifactId><dependencies><dependency><groupId>t</groupId><artifactId>lib</artifactId><version>1</version><scope>test</scope></dependency></dependencies></project>"#,
|
||||
);
|
||||
write(
|
||||
root,
|
||||
"v2/pom.xml",
|
||||
r#"<project><modelVersion>4.0.0</modelVersion><parent><groupId>t</groupId><artifactId>root</artifactId><version>1</version></parent><artifactId>v2</artifactId><dependencies><dependency><groupId>t</groupId><artifactId>lib</artifactId><version>2</version></dependency></dependencies></project>"#,
|
||||
);
|
||||
for module in ["lib", "tester", "v2"] {
|
||||
write(root, &format!("{module}/src/main/java/t/{module}.java"), "package t;");
|
||||
}
|
||||
let model = BuildModel { maven: Some(maven::load(root)), ..Default::default() };
|
||||
let cache = root.join("cache");
|
||||
record_module_build(&cache, root, &model, &CancellationToken::new());
|
||||
write(root, "lib/src/main/java/t/L.java", "package t; public class L {}");
|
||||
let steps = steps(&cache, root, &model).unwrap();
|
||||
// `tester`'s tests compile against `lib`.
|
||||
assert_eq!(pl_arg(&steps[0]), "lib,tester");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn root_pom_change_selects_the_whole_reactor() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
let model = fixture(root);
|
||||
let cache = root.join("cache");
|
||||
record_module_build(&cache, root, &model, &CancellationToken::new());
|
||||
write(
|
||||
root,
|
||||
"pom.xml",
|
||||
fs::read_to_string(root.join("pom.xml")).unwrap().replace("<modules>", "<!-- x --><modules>").as_str(),
|
||||
);
|
||||
let steps = steps(&cache, root, &model).unwrap();
|
||||
assert_eq!(steps.len(), 1);
|
||||
assert!(!steps[0].args.contains(&"-pl".into()));
|
||||
}
|
||||
|
||||
/// A folder of two sibling reactors: `chain` (lib ← mid ← app) and `solo`.
|
||||
fn two_reactors(root: &Path) -> BuildModel {
|
||||
write(
|
||||
root,
|
||||
"chain/pom.xml",
|
||||
r#"<project><modelVersion>4.0.0</modelVersion><groupId>t</groupId><artifactId>chain</artifactId><version>1</version><packaging>pom</packaging><modules><module>lib</module><module>mid</module><module>app</module></modules></project>"#,
|
||||
);
|
||||
for (dir, class, deps) in [
|
||||
("lib", "L", ""),
|
||||
(
|
||||
"mid",
|
||||
"M",
|
||||
"<dependencies><dependency><groupId>t</groupId><artifactId>lib</artifactId><version>1</version></dependency></dependencies>",
|
||||
),
|
||||
(
|
||||
"app",
|
||||
"A",
|
||||
"<dependencies><dependency><groupId>t</groupId><artifactId>mid</artifactId><version>1</version></dependency></dependencies>",
|
||||
),
|
||||
] {
|
||||
write(
|
||||
root,
|
||||
&format!("chain/{dir}/pom.xml"),
|
||||
&format!(
|
||||
r#"<project><modelVersion>4.0.0</modelVersion><parent><groupId>t</groupId><artifactId>chain</artifactId><version>1</version></parent><artifactId>{dir}</artifactId>{deps}</project>"#
|
||||
),
|
||||
);
|
||||
write(
|
||||
root,
|
||||
&format!("chain/{dir}/src/main/java/t/{class}.java"),
|
||||
&format!("package t; public class {class} {{}}"),
|
||||
);
|
||||
}
|
||||
write(
|
||||
root,
|
||||
"solo/pom.xml",
|
||||
r#"<project><modelVersion>4.0.0</modelVersion><groupId>t</groupId><artifactId>solo</artifactId><version>1</version></project>"#,
|
||||
);
|
||||
write(root, "solo/src/main/java/t/S.java", "package t;");
|
||||
BuildModel { maven: Some(maven::load(root)), ..Default::default() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unrelated_reactors_are_judged_separately() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
let model = two_reactors(root);
|
||||
let cache = root.join("cache");
|
||||
record_module_build(&cache, root, &model, &CancellationToken::new());
|
||||
write(root, "solo/src/main/java/t/S.java", "package t; public class S {}");
|
||||
let steps = steps(&cache, root, &model).unwrap();
|
||||
assert_eq!(steps.len(), 1);
|
||||
assert_eq!(steps[0].cwd, subdir(root, "solo"));
|
||||
}
|
||||
}
|
||||
@@ -200,22 +200,19 @@ fn kotlin_line(line: &str) -> Option<RawMessage> {
|
||||
kotlin_location(rest, severity)
|
||||
}
|
||||
|
||||
/// javac: `A.java:12: error: msg` / `A.java:12: warning: [deprecation] msg`
|
||||
/// (and localized javac prefixes such as Chinese/Japanese `错误:` / `錯誤:` / `エラー:` / `警告:`).
|
||||
/// javac: `A.java:12: error: msg` / `A.java:12: warning: [deprecation] msg`.
|
||||
fn javac_header(line: &str) -> Option<RawMessage> {
|
||||
let (path, ln, col, rest) = path_line_col(line)?;
|
||||
if !looks_like_source_path(path) {
|
||||
return None;
|
||||
}
|
||||
let rest = rest.trim_start_matches(':').trim_start();
|
||||
let (severity, msg) = ["error:", "错误:", "錯誤:", "エラー:"]
|
||||
.into_iter()
|
||||
.find_map(|prefix| rest.strip_prefix(prefix).map(|m| (Severity::Error, m)))
|
||||
.or_else(|| {
|
||||
["warning:", "警告:"]
|
||||
.into_iter()
|
||||
.find_map(|prefix| rest.strip_prefix(prefix).map(|m| (Severity::Warning, m)))
|
||||
})?;
|
||||
let (severity, msg) = if let Some(m) = rest.strip_prefix("error:") {
|
||||
(Severity::Error, m)
|
||||
} else {
|
||||
let m = rest.strip_prefix("warning:")?;
|
||||
(Severity::Warning, m)
|
||||
};
|
||||
Some(RawMessage::new(severity, msg.trim(), ColUnit::Char).at(path, ln, col))
|
||||
}
|
||||
|
||||
@@ -558,31 +555,6 @@ mod tests {
|
||||
assert_eq!(out[1].text, "[removal] finalize() has been deprecated");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn localized_javac_errors_and_warnings() {
|
||||
let out = parse(
|
||||
Format::Gradle,
|
||||
"/p/src/A.java:12: 错误: 找不到符号\n\
|
||||
\x20 Foo foo = new Foo();\n\
|
||||
\x20 ^\n\
|
||||
\x20 符号: 类 Foo\n\
|
||||
\x20 位置: 类 A\n\
|
||||
/p/src/B.java:5: 錯誤: 需要 ';'\n\
|
||||
\x20 int x = 1\n\
|
||||
\x20 ^\n\
|
||||
/p/src/C.java:8: 警告: [deprecation] old() 已过时\n\
|
||||
\x20 old();\n\
|
||||
\x20 ^\n",
|
||||
);
|
||||
assert_eq!(out.len(), 3, "{out:?}");
|
||||
assert_eq!(pos(&out[0]), (Severity::Error, "/p/src/A.java", 12, Some(9)));
|
||||
assert_eq!(out[0].text, "找不到符号\n符号: 类 Foo\n位置: 类 A");
|
||||
assert_eq!(pos(&out[1]), (Severity::Error, "/p/src/B.java", 5, Some(14)));
|
||||
assert_eq!(out[1].text, "需要 ';'");
|
||||
assert_eq!(pos(&out[2]), (Severity::Warning, "/p/src/C.java", 8, Some(5)));
|
||||
assert_eq!(out[2].text, "[deprecation] old() 已过时");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gradle_kotlin() {
|
||||
let out = parse(
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! Single-file Java compilation with `javac` for the Recompile action (#2476).
|
||||
//! Single-file Java compilation with `javac` for the Compile File action (#2476).
|
||||
//!
|
||||
//! A module build (`-pl … -am`) still walks every upstream module, and packaging
|
||||
//! walks the whole reactor; compiling one file only needs that file's module
|
||||
@@ -6,99 +6,15 @@
|
||||
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.
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
struct CachedClasspath {
|
||||
version: u32,
|
||||
fingerprint: LaunchFingerprint,
|
||||
classpath: String,
|
||||
}
|
||||
@@ -122,7 +38,12 @@ pub struct SingleFileTarget {
|
||||
|
||||
/// Locates the linked Maven module owning a `.java` source file.
|
||||
pub fn single_file_target(root: &Path, model: &BuildModel, file: &Path) -> IdeResult<SingleFileTarget> {
|
||||
is_java_file(file)?;
|
||||
if file.extension().is_none_or(|ext| ext != "java") {
|
||||
return Err(IdeError::invalid("only Java sources can be compiled as a single file"));
|
||||
}
|
||||
if !file.is_file() {
|
||||
return Err(IdeError::not_found("no Java source found for single-file compilation"));
|
||||
}
|
||||
let Some(m) = &model.maven else {
|
||||
return Err(IdeError::not_found("no linked Maven project found for module"));
|
||||
};
|
||||
@@ -146,7 +67,8 @@ pub fn single_file_target(root: &Path, model: &BuildModel, file: &Path) -> IdeRe
|
||||
let top_dir = subdir(root, &top.dir);
|
||||
let pl = module.strip_prefix(&top_dir).map(|r| r.to_string_lossy().replace('\\', "/")).unwrap_or_default();
|
||||
// Test sources see the test classpath and compile into test classes.
|
||||
let test = is_test_source(&rel);
|
||||
let parts: Vec<&str> = rel.split('/').collect();
|
||||
let test = parts.windows(2).any(|w| w == ["src", "test"]);
|
||||
let out_dir = module.join("target").join(if test { "test-classes" } else { "classes" });
|
||||
Ok(SingleFileTarget { module, test, out_dir, top: top.clone(), pl, java_version: project.java_version })
|
||||
}
|
||||
@@ -187,17 +109,7 @@ pub fn find_javac(env: &BTreeMap<String, String>) -> String {
|
||||
/// `mvn dependency:build-classpath` (which resolves without compiling anything,
|
||||
/// so `-am` stays cheap). Entries are platform-separated (`;` on Windows).
|
||||
pub fn single_file_classpath(root: &Path, model: &BuildModel, target: &SingleFileTarget) -> IdeResult<String> {
|
||||
single_file_classpath_cancellable(root, model, target, &CancellationToken::new())
|
||||
}
|
||||
|
||||
fn single_file_classpath_cancellable(
|
||||
root: &Path,
|
||||
model: &BuildModel,
|
||||
target: &SingleFileTarget,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<String> {
|
||||
let scope = if target.test { "test" } else { "compile" };
|
||||
classpath(root, model, target, scope, false, cancel)
|
||||
classpath(root, model, target, "test", false)
|
||||
}
|
||||
|
||||
/// Runtime (or test) dependency classpath for a launch module.
|
||||
@@ -214,75 +126,30 @@ pub fn module_classpath(
|
||||
cache: &Path,
|
||||
cancel: &ide_core::CancellationToken,
|
||||
) -> IdeResult<String> {
|
||||
module_classpaths(root, model, &[module.to_path_buf()], test, local_repo, cache, cancel)
|
||||
}
|
||||
|
||||
/// [`module_classpath`] of `modules[0]`. The other modules, launched together with it
|
||||
/// (#3971), share its Maven probe when they have no cached classpath, which leaves
|
||||
/// theirs cached for their own launches.
|
||||
pub fn module_classpaths(
|
||||
root: &Path,
|
||||
model: &BuildModel,
|
||||
modules: &[PathBuf],
|
||||
test: bool,
|
||||
local_repo: Option<PathBuf>,
|
||||
cache: &Path,
|
||||
cancel: &ide_core::CancellationToken,
|
||||
) -> IdeResult<String> {
|
||||
let mut probes: Vec<Probe> = Vec::new();
|
||||
for (i, module) in modules.iter().enumerate() {
|
||||
let target = match module_target(root, model, module, test) {
|
||||
Ok(target) => target,
|
||||
Err(e) if i == 0 => return Err(e),
|
||||
Err(_) => continue,
|
||||
};
|
||||
if i > 0 && (target.top.dir != probes[0].0.top.dir || probes.iter().any(|p| p.0.module == target.module)) {
|
||||
continue;
|
||||
}
|
||||
let fingerprint = launch_fingerprint(root, model, &target.module, test, local_repo.clone(), cancel)?;
|
||||
let cache_path = classpath_cache_path(root, cache, &target.module, test);
|
||||
if let (Some(fingerprint), Some(path)) = (&fingerprint, &cache_path)
|
||||
&& let Ok(bytes) = fs::read(path)
|
||||
&& let Ok(cached) = serde_json::from_slice::<CachedClasspath>(&bytes)
|
||||
&& cached.version == CLASSPATH_CACHE_VERSION
|
||||
&& cached.fingerprint == *fingerprint
|
||||
&& classpath_entries_exist(root, &cached.classpath)
|
||||
{
|
||||
if i == 0 {
|
||||
return Ok(cached.classpath);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
probes.push(Probe(target, fingerprint, cache_path));
|
||||
let target = module_target(root, model, module, test)?;
|
||||
let fingerprint = launch_fingerprint(root, model, &target.module, test, local_repo, cancel)?;
|
||||
let cache_path = classpath_cache_path(root, cache, &target.module, test);
|
||||
if let (Some(fingerprint), Some(path)) = (&fingerprint, &cache_path)
|
||||
&& let Ok(bytes) = fs::read(path)
|
||||
&& let Ok(cached) = serde_json::from_slice::<CachedClasspath>(&bytes)
|
||||
&& cached.fingerprint == *fingerprint
|
||||
&& classpath_entries_exist(root, &cached.classpath)
|
||||
{
|
||||
return Ok(cached.classpath);
|
||||
}
|
||||
let scope = if test { "test" } else { "runtime" };
|
||||
let targets: Vec<&SingleFileTarget> = probes.iter().map(|p| &p.0).collect();
|
||||
let classpaths = match classpaths(root, model, &targets, scope, true, cancel) {
|
||||
Ok(classpaths) => classpaths,
|
||||
// Another module's failure must not cost this launch its own probe.
|
||||
Err(_) if targets.len() > 1 && !cancel.is_cancelled() => {
|
||||
classpaths(root, model, &targets[..1], scope, true, cancel)?
|
||||
}
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
let classpath = classpath(root, model, &target, if test { "test" } else { "runtime" }, true)?;
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
for (Probe(_, fingerprint, cache_path), classpath) in probes.into_iter().zip(&classpaths) {
|
||||
if let (Some(fingerprint), Some(path)) = (fingerprint, cache_path) {
|
||||
let cached =
|
||||
CachedClasspath { version: CLASSPATH_CACHE_VERSION, fingerprint, classpath: classpath.clone() };
|
||||
if let Err(error) = cache_classpath(&path, &cached) {
|
||||
tracing::debug!(path = %path.display(), %error, "Cannot cache the Java launch classpath");
|
||||
}
|
||||
if let (Some(fingerprint), Some(path)) = (fingerprint, cache_path) {
|
||||
let cached = CachedClasspath { fingerprint, classpath: classpath.clone() };
|
||||
if let Err(error) = cache_classpath(&path, &cached) {
|
||||
tracing::debug!(path = %path.display(), %error, "Cannot cache the Java launch classpath");
|
||||
}
|
||||
}
|
||||
Ok(classpaths.into_iter().next().unwrap())
|
||||
Ok(classpath)
|
||||
}
|
||||
|
||||
/// A module whose classpath the Maven probe resolves, with its cache key and file.
|
||||
struct Probe(SingleFileTarget, Option<LaunchFingerprint>, Option<PathBuf>);
|
||||
|
||||
/// One cache file per module and scope. Mirroring the module path keeps nested
|
||||
/// modules and their different dependency scopes from overwriting each other.
|
||||
fn classpath_cache_path(root: &Path, cache: &Path, module: &Path, test: bool) -> Option<PathBuf> {
|
||||
@@ -323,68 +190,7 @@ fn classpath(
|
||||
target: &SingleFileTarget,
|
||||
scope: &str,
|
||||
compile_first: bool,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<String> {
|
||||
Ok(classpaths(root, model, &[target], scope, compile_first, cancel)?.pop().unwrap())
|
||||
}
|
||||
|
||||
/// The classpath of each of `targets` (modules of one reactor) from one Maven probe.
|
||||
fn classpaths(
|
||||
root: &Path,
|
||||
model: &BuildModel,
|
||||
targets: &[&SingleFileTarget],
|
||||
scope: &str,
|
||||
compile_first: bool,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<Vec<String>> {
|
||||
let top = &targets[0].top;
|
||||
let probe = CP_FILE;
|
||||
let mut args = vec!["-B", "-Dstyle.color=never", maven::LOCAL_REPO_TRACKING_ARG];
|
||||
args.extend(top.options.iter().map(String::as_str));
|
||||
// The reactor root among them builds every module.
|
||||
let selection = if targets.iter().any(|t| t.pl.is_empty()) {
|
||||
String::new()
|
||||
} else {
|
||||
let mut pl: Vec<&str> = targets.iter().map(|t| t.pl.as_str()).collect();
|
||||
pl.sort();
|
||||
pl.dedup();
|
||||
pl.join(",")
|
||||
};
|
||||
if !selection.is_empty() {
|
||||
args.extend(["-pl", selection.as_str(), "-am"]);
|
||||
}
|
||||
let output_arg = format!("-Dmdep.outputFile={probe}");
|
||||
let scope_arg = format!("-Dmdep.includeScope={scope}");
|
||||
// A launch build may only have reached `compile`. Running `compile` in this
|
||||
// same Maven session lets the dependency plugin resolve Reactor siblings from
|
||||
// their target/classes without paying for package-phase plugins.
|
||||
if compile_first {
|
||||
args.push("compile");
|
||||
}
|
||||
let build_classpath =
|
||||
maven::plugin_goal("dependency:build-classpath", maven::local_repository_for(&top.options).as_deref());
|
||||
args.extend([build_classpath.as_str(), output_arg.as_str(), scope_arg.as_str(), "-q"]);
|
||||
let top_dir = subdir(root, &top.dir);
|
||||
let owned_args: Vec<String> = args.into_iter().map(str::to_owned).collect();
|
||||
let out = process::run_bounded(&top.command, &owned_args, &top_dir, &top.env, cancel, |_, _| {}).map_err(|e| {
|
||||
if e.kind == ide_core::error::ErrorKind::Cancelled {
|
||||
e
|
||||
} else {
|
||||
IdeError::internal(format!("cannot resolve the compile classpath: {}", e.message))
|
||||
}
|
||||
})?;
|
||||
if !out.success {
|
||||
// Maven reports reactor/dependency failures on stdout, not only stderr.
|
||||
let tail: Vec<&str> = out.text.lines().filter(|l| !l.trim().is_empty()).collect();
|
||||
let tail = tail.iter().rev().take(5).rev().cloned().collect::<Vec<_>>().join("\n");
|
||||
return Err(IdeError::internal(format!("cannot resolve the compile classpath:\n{tail}")));
|
||||
}
|
||||
targets.iter().map(|target| target_classpath(root, model, target)).collect()
|
||||
}
|
||||
|
||||
/// The classpath of `target` after a probe: its reactor class directories, then
|
||||
/// the dependencies Maven wrote to the module's probe file.
|
||||
fn target_classpath(root: &Path, model: &BuildModel, target: &SingleFileTarget) -> IdeResult<String> {
|
||||
let mut entries: Vec<String> = Vec::new();
|
||||
// The module's own classes first: the file almost always uses classes next to it.
|
||||
let own: &[&str] = if target.test { &["target/test-classes", "target/classes"] } else { &["target/classes"] };
|
||||
@@ -402,29 +208,84 @@ fn target_classpath(root: &Path, model: &BuildModel, target: &SingleFileTarget)
|
||||
if dir == target.module {
|
||||
continue;
|
||||
}
|
||||
// A dependency's tests are not exported with its main artifact. Any explicitly
|
||||
// declared test artifact is supplied by Maven's resolved classpath below.
|
||||
let path = dir.join("target/classes");
|
||||
if path.is_dir() {
|
||||
entries.push(path.to_string_lossy().into_owned());
|
||||
for classes in ["target/classes", "target/test-classes"] {
|
||||
let path = dir.join(classes);
|
||||
if path.is_dir() {
|
||||
entries.push(path.to_string_lossy().into_owned());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let probe = CP_FILE;
|
||||
let mut args = vec!["-B", "-Dstyle.color=never", maven::LOCAL_REPO_TRACKING_ARG];
|
||||
args.extend(target.top.options.iter().map(String::as_str));
|
||||
if !target.pl.is_empty() {
|
||||
args.extend(["-pl", target.pl.as_str(), "-am"]);
|
||||
}
|
||||
let output_arg = format!("-Dmdep.outputFile={probe}");
|
||||
let scope_arg = format!("-Dmdep.includeScope={scope}");
|
||||
// A launch build may only have reached `compile`. Running `compile` in this
|
||||
// same Maven session lets the dependency plugin resolve Reactor siblings from
|
||||
// their target/classes without paying for package-phase plugins.
|
||||
if compile_first {
|
||||
args.push("compile");
|
||||
}
|
||||
args.extend(["dependency:build-classpath", output_arg.as_str(), scope_arg.as_str(), "-q"]);
|
||||
let top_dir = subdir(root, &target.top.dir);
|
||||
let status = ProcCommand::new(&target.top.command)
|
||||
.args(&args)
|
||||
.envs(&target.top.env)
|
||||
.current_dir(&top_dir)
|
||||
.output()
|
||||
.map_err(|e| IdeError::internal(format!("cannot resolve the compile classpath: {e}")))?;
|
||||
if !status.status.success() {
|
||||
let stdout = String::from_utf8_lossy(&status.stdout);
|
||||
let stderr = String::from_utf8_lossy(&status.stderr);
|
||||
// Maven reports reactor/dependency failures on stdout, not only stderr.
|
||||
let tail: Vec<&str> = stdout.lines().chain(stderr.lines()).filter(|l| !l.trim().is_empty()).collect();
|
||||
let tail = tail.iter().rev().take(5).rev().cloned().collect::<Vec<_>>().join("\n");
|
||||
return Err(IdeError::internal(format!("cannot resolve the compile classpath:\n{tail}")));
|
||||
}
|
||||
// With `-am` every visited module writes its own file; only this module's counts.
|
||||
let cp_file = target.module.join(CP_FILE);
|
||||
let cp_file = target.module.join(probe);
|
||||
let content = fs::read_to_string(&cp_file).map_err(|e| {
|
||||
IdeError::internal(format!("cannot resolve the compile classpath: {} ({e})", cp_file.display()))
|
||||
})?;
|
||||
let separator = if cfg!(windows) { ';' } else { ':' };
|
||||
entries.extend(content.split([separator, '\n', '\r']).map(str::trim).filter(|e| !e.is_empty()).map(str::to_owned));
|
||||
Ok(join_classpath(entries))
|
||||
entries.dedup();
|
||||
Ok(entries.join(&separator.to_string()))
|
||||
}
|
||||
|
||||
/// The `javac` step compiling `file` into `target`'s output directory.
|
||||
pub fn javac_step(target: &SingleFileTarget, file: &Path, classpath: &str, javac: &str) -> IdeResult<BuildStep> {
|
||||
fs::create_dir_all(&target.out_dir)
|
||||
.map_err(|e| IdeError::internal(format!("cannot create {} ({e})", target.out_dir.display())))?;
|
||||
let mut step = BuildStep::new(javac, &[], &target.module, Format::Gradle);
|
||||
// Raw `javac` prints `path:line: error: …`, the same form Gradle forwards.
|
||||
step.args.push("-encoding".into());
|
||||
step.args.push("UTF-8".into());
|
||||
step.args.push("-d".into());
|
||||
step.args.push(target.out_dir.to_string_lossy().into_owned());
|
||||
step.args.push("-cp".into());
|
||||
step.args.push(classpath.to_owned());
|
||||
// Classes of the module that were never built (or are older than their source) are read
|
||||
// from its sources; only `file` is written, so a test compile never puts main classes
|
||||
// into test-classes.
|
||||
let sources = source_roots(target);
|
||||
let release = release_args(target.java_version, java_home_major(&target.top.env));
|
||||
build_javac_step(javac, &target.module, &target.out_dir, classpath, &sources, release, file, target.top.env.clone())
|
||||
if !sources.is_empty() {
|
||||
let separator = if cfg!(windows) { ";" } else { ":" };
|
||||
step.args.push("-sourcepath".into());
|
||||
step.args.push(sources.iter().map(|p| p.to_string_lossy()).collect::<Vec<_>>().join(separator));
|
||||
step.args.push("-implicit:none".into());
|
||||
}
|
||||
if let Some(version) = target.java_version {
|
||||
step.args.push("--release".into());
|
||||
step.args.push(version.to_string());
|
||||
}
|
||||
step.args.push(file.to_string_lossy().into_owned());
|
||||
step.env = target.top.env.clone();
|
||||
Ok(step)
|
||||
}
|
||||
|
||||
/// The module's Java source folders that exist, generated ones included; test sources see
|
||||
@@ -450,18 +311,8 @@ fn source_roots(target: &SingleFileTarget) -> Vec<PathBuf> {
|
||||
|
||||
/// Resolves the classpath and plans the `javac` invocation for one Java source.
|
||||
pub fn compile_file_plan(root: &Path, model: &BuildModel, file: &Path) -> IdeResult<BuildPlan> {
|
||||
compile_file_plan_cancellable(root, model, file, &CancellationToken::new())
|
||||
}
|
||||
|
||||
/// Cancellable [`compile_file_plan`].
|
||||
pub fn compile_file_plan_cancellable(
|
||||
root: &Path,
|
||||
model: &BuildModel,
|
||||
file: &Path,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<BuildPlan> {
|
||||
let target = single_file_target(root, model, file)?;
|
||||
let classpath = single_file_classpath_cancellable(root, model, &target, cancel)?;
|
||||
let classpath = single_file_classpath(root, model, &target)?;
|
||||
let javac = find_javac(&target.top.env);
|
||||
let name = file.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
Ok(BuildPlan {
|
||||
@@ -471,140 +322,6 @@ pub fn compile_file_plan_cancellable(
|
||||
})
|
||||
}
|
||||
|
||||
fn gradle_for_file<'a>(
|
||||
root: &Path,
|
||||
model: &'a BuildModel,
|
||||
file: &Path,
|
||||
) -> Option<(&'a crate::GradleModel, &'a crate::GradleProject, PathBuf)> {
|
||||
let file = normalize(file);
|
||||
let file_ref = &file;
|
||||
model
|
||||
.gradle
|
||||
.iter()
|
||||
.flat_map(|g| {
|
||||
let g_dir = normalize(&subdir(root, &g.dir));
|
||||
let g_depth = g_dir.components().count();
|
||||
g.projects.iter().filter_map(move |p| {
|
||||
let p_dir = normalize(&subdir(root, &p.dir));
|
||||
file_ref.starts_with(&p_dir).then_some((g, p, p_dir, g_depth))
|
||||
})
|
||||
})
|
||||
.max_by_key(|(_, _, p_dir, g_depth)| (p_dir.components().count(), *g_depth))
|
||||
.map(|(g, p, p_dir, _)| (g, p, p_dir))
|
||||
}
|
||||
|
||||
/// Whether `file` lies inside a linked Gradle project of `model`.
|
||||
pub fn has_gradle_file_target(root: &Path, model: &BuildModel, file: &Path) -> bool {
|
||||
gradle_for_file(root, model, file).is_some()
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct GradleCompileCp {
|
||||
out_dir: Option<String>,
|
||||
#[serde(default)]
|
||||
classpath: Vec<String>,
|
||||
#[serde(default)]
|
||||
src_dirs: Vec<String>,
|
||||
release: Option<u32>,
|
||||
}
|
||||
|
||||
/// Resolves the compile classpath from Gradle and plans a single-file `javac` step.
|
||||
pub fn gradle_compile_file_plan(
|
||||
root: &Path,
|
||||
model: &BuildModel,
|
||||
file: &Path,
|
||||
cache: &Path,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<BuildPlan> {
|
||||
let name = is_java_file(file)?;
|
||||
let (gradle, project, module_dir) = gradle_for_file(root, model, file)
|
||||
.ok_or_else(|| IdeError::not_found("no linked Gradle project found for file"))?;
|
||||
let rel = rel_str(&module_dir, file);
|
||||
let test = is_test_source(&rel);
|
||||
let scope = if test { "test" } else { "main" };
|
||||
|
||||
fs::create_dir_all(cache)?;
|
||||
let init_script = cache.join("gradle-compile-cp.init.gradle");
|
||||
fs::write(&init_script, GRADLE_COMPILE_CP_INIT_SCRIPT)?;
|
||||
let args = vec![
|
||||
"--console=plain".into(),
|
||||
"-q".into(),
|
||||
"-Dorg.gradle.configuration-cache=false".into(),
|
||||
"--init-script".into(),
|
||||
init_script.to_string_lossy().into_owned(),
|
||||
format!("-Popenidea.target={}", project.path),
|
||||
format!("-Popenidea.scope={scope}"),
|
||||
"help".into(),
|
||||
];
|
||||
let gradle_dir = subdir(root, &gradle.dir);
|
||||
let mut reported: Option<String> = None;
|
||||
let out = process::run_bounded(&gradle.command, &args, &gradle_dir, &gradle.env, cancel, |_, line| {
|
||||
if let Some(json) = line.strip_prefix("@openidea-compile-cp\t") {
|
||||
reported = Some(json.to_owned());
|
||||
}
|
||||
})
|
||||
.map_err(|e| {
|
||||
if e.kind == ide_core::error::ErrorKind::Cancelled {
|
||||
e
|
||||
} else {
|
||||
IdeError::internal(format!("cannot resolve the compile classpath: {}", e.message))
|
||||
}
|
||||
})?;
|
||||
if !out.success {
|
||||
let tail: Vec<&str> = out.text.lines().filter(|l| !l.trim().is_empty()).collect();
|
||||
let tail = tail.iter().rev().take(5).rev().cloned().collect::<Vec<_>>().join("\n");
|
||||
return Err(IdeError::internal(format!("cannot resolve the compile classpath:\n{tail}")));
|
||||
}
|
||||
let json = reported.ok_or_else(|| {
|
||||
IdeError::internal(format!(
|
||||
"cannot resolve the compile classpath: Gradle did not report source set '{scope}' for {}",
|
||||
project.path
|
||||
))
|
||||
})?;
|
||||
let cp: GradleCompileCp = serde_json::from_str(&json)
|
||||
.map_err(|e| IdeError::internal(format!("cannot parse Gradle compile classpath: {e}")))?;
|
||||
|
||||
let out_dir = cp
|
||||
.out_dir
|
||||
.filter(|d| !d.trim().is_empty())
|
||||
.map(PathBuf::from)
|
||||
.unwrap_or_else(|| module_dir.join("build/classes/java").join(scope));
|
||||
let mut cp_entries: Vec<String> = Vec::new();
|
||||
if out_dir.is_dir() {
|
||||
cp_entries.push(out_dir.to_string_lossy().into_owned());
|
||||
}
|
||||
if test {
|
||||
let main_out = module_dir.join("build/classes/java/main");
|
||||
if main_out.is_dir() {
|
||||
cp_entries.push(main_out.to_string_lossy().into_owned());
|
||||
}
|
||||
}
|
||||
for sibling in &gradle.projects {
|
||||
let sibling_dir = subdir(root, &sibling.dir);
|
||||
if sibling_dir == module_dir {
|
||||
continue;
|
||||
}
|
||||
let classes = sibling_dir.join("build/classes/java/main");
|
||||
if classes.is_dir() {
|
||||
cp_entries.push(classes.to_string_lossy().into_owned());
|
||||
}
|
||||
}
|
||||
cp_entries.extend(cp.classpath);
|
||||
let classpath = join_classpath(cp_entries);
|
||||
|
||||
let mut sources: Vec<PathBuf> = cp.src_dirs.into_iter().map(PathBuf::from).filter(|p| p.is_dir()).collect();
|
||||
if sources.is_empty() {
|
||||
let fallback: &[&str] = if test { &["src/test/java", "src/main/java"] } else { &["src/main/java"] };
|
||||
sources.extend(fallback.iter().map(|s| module_dir.join(s)).filter(|p| p.is_dir()));
|
||||
}
|
||||
let javac = find_javac(&gradle.env);
|
||||
let release = release_args(cp.release.or(gradle.java_version), java_home_major(&gradle.env));
|
||||
let step =
|
||||
build_javac_step(&javac, &module_dir, &out_dir, &classpath, &sources, release, file, gradle.env.clone())?;
|
||||
Ok(BuildPlan { system: BuildSystem::Gradle, title: format!("Compile {name}"), steps: vec![step] })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -620,19 +337,13 @@ mod tests {
|
||||
root,
|
||||
"pom.xml",
|
||||
r#"<project><groupId>demo</groupId><artifactId>parent</artifactId><version>1</version>
|
||||
<packaging>pom</packaging><modules><module>shared</module><module>lib</module><module>app</module></modules></project>"#,
|
||||
<packaging>pom</packaging><modules><module>lib</module><module>app</module></modules></project>"#,
|
||||
);
|
||||
write(
|
||||
root,
|
||||
"lib/pom.xml",
|
||||
r#"<project><parent><groupId>demo</groupId><artifactId>parent</artifactId><version>1</version></parent>
|
||||
<artifactId>lib</artifactId><dependencies><dependency><groupId>demo</groupId><artifactId>shared</artifactId><version>1</version></dependency></dependencies></project>"#,
|
||||
);
|
||||
write(
|
||||
root,
|
||||
"shared/pom.xml",
|
||||
r#"<project><parent><groupId>demo</groupId><artifactId>parent</artifactId><version>1</version></parent>
|
||||
<artifactId>shared</artifactId></project>"#,
|
||||
<artifactId>lib</artifactId></project>"#,
|
||||
);
|
||||
write(
|
||||
root,
|
||||
@@ -643,15 +354,13 @@ mod tests {
|
||||
write(root, "app/src/main/java/demo/Main.java", "class Main {}");
|
||||
write(root, "app/src/test/java/demo/MainTest.java", "class MainTest {}");
|
||||
write(root, "lib/target/classes/Lib.class", "built");
|
||||
write(root, "shared/target/classes/Shared.class", "built");
|
||||
crate::load(root, &root.join("cache"), None)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn target_finds_the_owning_module_and_the_test_scope() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root_buf = dunce::canonicalize(dir.path()).unwrap();
|
||||
let root = root_buf.as_path();
|
||||
let root = dir.path();
|
||||
let model = fixture(root);
|
||||
let main = single_file_target(root, &model, &root.join("app/src/main/java/demo/Main.java")).unwrap();
|
||||
assert_eq!(main.module, root.join("app"));
|
||||
@@ -665,8 +374,7 @@ mod tests {
|
||||
#[test]
|
||||
fn target_rejects_non_java_missing_and_unlinked_files() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root_buf = dunce::canonicalize(dir.path()).unwrap();
|
||||
let root = root_buf.as_path();
|
||||
let root = dir.path();
|
||||
let model = fixture(root);
|
||||
write(root, "app/pom.xml", "<project/>");
|
||||
assert!(single_file_target(root, &model, &root.join("app/pom.xml")).is_err());
|
||||
@@ -678,8 +386,7 @@ mod tests {
|
||||
#[test]
|
||||
fn javac_prefers_the_module_jdk_and_scopes_test_sources() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root_buf = dunce::canonicalize(dir.path()).unwrap();
|
||||
let root = root_buf.as_path();
|
||||
let root = dir.path();
|
||||
let model = fixture(root);
|
||||
let file = root.join("app/src/test/java/demo/MainTest.java");
|
||||
let target = single_file_target(root, &model, &file).unwrap();
|
||||
@@ -715,8 +422,7 @@ mod tests {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root_buf = dunce::canonicalize(dir.path()).unwrap();
|
||||
let root = root_buf.as_path();
|
||||
let root = dir.path();
|
||||
fixture(root);
|
||||
let script = root.join("mvnw");
|
||||
fs::write(
|
||||
@@ -730,9 +436,7 @@ mod tests {
|
||||
let target = single_file_target(root, &model, &file).unwrap();
|
||||
assert!(target.top.command.ends_with("mvnw"));
|
||||
assert_eq!(target.pl, "app");
|
||||
fs::create_dir_all(root.join("lib/target/test-classes")).unwrap();
|
||||
let cp = single_file_classpath(root, &model, &target).unwrap();
|
||||
assert!(!std::env::split_paths(&cp).any(|p| p == root.join("lib/target/test-classes")), "{cp}");
|
||||
let separator = ':';
|
||||
// Reactor class directories first, so fresh outputs shadow installed snapshots.
|
||||
let lib = root.join("lib/target/classes").to_string_lossy().into_owned();
|
||||
@@ -747,54 +451,29 @@ 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();
|
||||
let paths: Vec<_> = std::env::split_paths(&cp).collect();
|
||||
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.
|
||||
/// A launch uses runtime dependencies, while tests additionally see test-scope ones.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn launch_module_classpath_uses_the_matching_dependency_scope() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root_buf = dunce::canonicalize(dir.path()).unwrap();
|
||||
let root = root_buf.as_path();
|
||||
let root = dir.path();
|
||||
fixture(root);
|
||||
let script = root.join("mvnw");
|
||||
fs::write(
|
||||
&script,
|
||||
"#!/bin/sh\nprintf '%s\\n' \"$@\" > args.txt\npl='.'\nwhile [ $# -gt 0 ]; do\nif [ \"$1\" = \"-pl\" ]; then pl=\"$2\"; shift 2; else shift; fi\ndone\nmkdir -p \"$pl/target\"\nprintf '/repo/runtime.jar:/repo/fixture-tests.jar:/repo/fixture/target/test-classes' > \"$pl/target/ide-compile-cp.txt\"\n",
|
||||
"#!/bin/sh\nprintf '%s\\n' \"$@\" > args.txt\npl='.'\nwhile [ $# -gt 0 ]; do\nif [ \"$1\" = \"-pl\" ]; then pl=\"$2\"; shift 2; else shift; fi\ndone\nmkdir -p \"$pl/target\"\nprintf '/repo/runtime.jar:/repo/test.jar' > \"$pl/target/ide-compile-cp.txt\"\n",
|
||||
)
|
||||
.unwrap();
|
||||
fs::set_permissions(&script, fs::Permissions::from_mode(0o755)).unwrap();
|
||||
let model = crate::load(root, &root.join("cache"), None);
|
||||
|
||||
for dir in
|
||||
["app/target/classes", "app/target/test-classes", "lib/target/test-classes", "shared/target/test-classes"]
|
||||
{
|
||||
fs::create_dir_all(root.join(dir)).unwrap();
|
||||
}
|
||||
let cache = root.join("cache");
|
||||
let runtime =
|
||||
module_classpath(root, &model, &root.join("app"), false, None, &cache, &CancellationToken::new()).unwrap();
|
||||
let paths: Vec<_> = std::env::split_paths(&runtime).collect();
|
||||
assert!(paths.contains(&root.join("app/target/classes")), "{runtime}");
|
||||
assert!(paths.contains(&root.join("lib/target/classes")), "{runtime}");
|
||||
assert!(!paths.contains(&root.join("app/target/test-classes")), "{runtime}");
|
||||
assert!(!paths.contains(&root.join("lib/target/test-classes")), "{runtime}");
|
||||
assert!(paths.contains(&root.join("shared/target/classes")), "{runtime}");
|
||||
assert!(!paths.contains(&root.join("shared/target/test-classes")), "{runtime}");
|
||||
assert!(paths.contains(&PathBuf::from("/repo/fixture-tests.jar")), "{runtime}");
|
||||
assert!(paths.contains(&PathBuf::from("/repo/fixture/target/test-classes")), "{runtime}");
|
||||
assert!(runtime.contains("/repo/runtime.jar"), "{runtime}");
|
||||
let args = fs::read_to_string(root.join("args.txt")).unwrap();
|
||||
assert!(args.lines().any(|a| a == "compile"), "{args}");
|
||||
@@ -803,71 +482,20 @@ mod tests {
|
||||
|
||||
let test =
|
||||
module_classpath(root, &model, &root.join("app"), true, None, &cache, &CancellationToken::new()).unwrap();
|
||||
assert!(test.contains("/repo/fixture-tests.jar"), "{test}");
|
||||
let paths: Vec<_> = std::env::split_paths(&test).collect();
|
||||
assert!(paths.contains(&root.join("app/target/test-classes")), "{test}");
|
||||
assert!(paths.contains(&root.join("app/target/classes")), "{test}");
|
||||
assert!(paths.contains(&root.join("lib/target/classes")), "{test}");
|
||||
assert!(!paths.contains(&root.join("lib/target/test-classes")), "{test}");
|
||||
assert!(paths.contains(&root.join("shared/target/classes")), "{test}");
|
||||
assert!(!paths.contains(&root.join("shared/target/test-classes")), "{test}");
|
||||
assert!(paths.contains(&PathBuf::from("/repo/fixture/target/test-classes")), "{test}");
|
||||
assert!(test.contains("/repo/test.jar"), "{test}");
|
||||
let args = fs::read_to_string(root.join("args.txt")).unwrap();
|
||||
assert!(args.lines().any(|a| a == "-Dmdep.includeScope=test"), "{args}");
|
||||
}
|
||||
|
||||
/// Modules launched together resolve their classpaths in one Maven probe and leave
|
||||
/// the others' cached; a probe another module breaks still resolves the first one.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn launch_modules_share_one_classpath_probe() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root_buf = dunce::canonicalize(dir.path()).unwrap();
|
||||
let root = root_buf.as_path();
|
||||
fixture(root);
|
||||
write(root, "lib/src/main/java/demo/Lib.java", "class Lib {}");
|
||||
let script = root.join("mvnw");
|
||||
fs::write(
|
||||
&script,
|
||||
"#!/bin/sh\necho \"$@\" >> calls.txt\npl='.'\nwhile [ $# -gt 0 ]; do\nif [ \"$1\" = \"-pl\" ]; then pl=\"$2\"; shift 2; else shift; fi\ndone\ncase \"$pl\" in *lib*) [ -f lib/broken ] && exit 1;; esac\nfor m in $(echo \"$pl\" | tr ',' ' '); do mkdir -p \"$m/target\" repo; touch \"repo/$m.jar\"; printf \"$PWD/repo/$m.jar\" > \"$m/target/ide-compile-cp.txt\"; done\n",
|
||||
)
|
||||
.unwrap();
|
||||
fs::set_permissions(&script, fs::Permissions::from_mode(0o755)).unwrap();
|
||||
let model = crate::load(root, &root.join("cache"), None);
|
||||
let cache = root.join("cache");
|
||||
let cancel = CancellationToken::new();
|
||||
let calls = || fs::read_to_string(root.join("calls.txt")).unwrap_or_default().lines().count();
|
||||
let modules = [root.join("app"), root.join("lib"), root.join("app")];
|
||||
let app = module_classpaths(root, &model, &modules, false, None, &cache, &cancel).unwrap();
|
||||
assert!(app.contains("/repo/app.jar") && !app.contains("repo/lib.jar"), "{app}");
|
||||
assert_eq!(calls(), 1);
|
||||
assert!(fs::read_to_string(root.join("calls.txt")).unwrap().contains("-pl app,lib -am compile"));
|
||||
let lib = module_classpath(root, &model, &root.join("lib"), false, None, &cache, &cancel).unwrap();
|
||||
assert!(lib.contains("/repo/lib.jar"), "{lib}");
|
||||
assert_eq!(calls(), 1, "lib's classpath came from the shared probe");
|
||||
// A probe another module breaks is retried for the first module alone.
|
||||
write(root, "lib/src/main/java/demo/Lib.java", "class Lib { int changed; }");
|
||||
write(root, "lib/broken", "");
|
||||
let app = module_classpaths(root, &model, &[root.join("app"), root.join("lib")], false, None, &cache, &cancel)
|
||||
.unwrap();
|
||||
assert!(app.contains("/repo/app.jar"), "{app}");
|
||||
assert_eq!(calls(), 3, "the shared probe failed, then app was probed alone");
|
||||
// The first module's own failure stays its failure.
|
||||
assert!(module_classpath(root, &model, &root.join("lib"), false, None, &cache, &cancel).is_err());
|
||||
}
|
||||
|
||||
/// The launch classpath follows the Maven runner JDK and is reused until that
|
||||
/// build input changes; the probe does not run packaging plugins.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn launch_classpath_cache_follows_the_runner_jdk_and_format() {
|
||||
fn launch_classpath_cache_follows_the_runner_jdk() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root_buf = dunce::canonicalize(dir.path()).unwrap();
|
||||
let root = root_buf.as_path();
|
||||
let root = dir.path();
|
||||
fixture(root);
|
||||
let script = root.join("mvnw");
|
||||
// `dependency:build-classpath` reports reactor outputs as absolute paths. Keep
|
||||
@@ -885,7 +513,6 @@ mod tests {
|
||||
fs::write(home.join("release"), format!("JAVA_VERSION=\"{version}\"\n")).unwrap();
|
||||
fs::write(home.join("bin/java"), "").unwrap();
|
||||
}
|
||||
fs::create_dir_all(root.join("app/target/classes")).unwrap();
|
||||
let cache = root.join("classpath-cache");
|
||||
let cancel = CancellationToken::new();
|
||||
let jdk21 = root.join("jdk21");
|
||||
@@ -899,30 +526,6 @@ mod tests {
|
||||
assert_eq!(second, first);
|
||||
assert_eq!(fs::read_to_string(root.join("calls.txt")).unwrap(), "x");
|
||||
|
||||
let record = classpath_cache_path(root, &cache, &root.join("app"), false).unwrap();
|
||||
let current: serde_json::Value = serde_json::from_slice(&fs::read(&record).unwrap()).unwrap();
|
||||
let test_output = root.join("lib/target/test-classes");
|
||||
fs::create_dir_all(&test_output).unwrap();
|
||||
let polluted = std::env::join_paths(std::env::split_paths(&first).chain([test_output])).unwrap();
|
||||
let mut calls = "x".to_owned();
|
||||
for version in [None, Some(0), Some(u32::MAX)] {
|
||||
let mut stale = current.clone();
|
||||
stale["classpath"] = polluted.to_string_lossy().as_ref().into();
|
||||
if let Some(version) = version {
|
||||
stale["version"] = version.into();
|
||||
} else {
|
||||
stale.as_object_mut().unwrap().remove("version");
|
||||
}
|
||||
fs::write(&record, serde_json::to_vec(&stale).unwrap()).unwrap();
|
||||
let rebuilt = module_classpath(root, &model, &root.join("app"), false, None, &cache, &cancel).unwrap();
|
||||
assert_eq!(rebuilt, first, "incompatible cache format {version:?} must be rebuilt");
|
||||
calls.push('x');
|
||||
assert_eq!(fs::read_to_string(root.join("calls.txt")).unwrap(), calls);
|
||||
let reused = module_classpath(root, &model, &root.join("app"), false, None, &cache, &cancel).unwrap();
|
||||
assert_eq!(reused, rebuilt);
|
||||
assert_eq!(fs::read_to_string(root.join("calls.txt")).unwrap(), calls);
|
||||
}
|
||||
|
||||
let jdk8 = root.join("jdk8");
|
||||
for project in &mut model.maven.as_mut().unwrap().projects {
|
||||
project.env.insert("JAVA_HOME".into(), jdk8.to_string_lossy().into_owned());
|
||||
@@ -930,82 +533,6 @@ mod tests {
|
||||
let switched = module_classpath(root, &model, &root.join("app"), false, None, &cache, &cancel).unwrap();
|
||||
assert!(switched.contains("jdk8/classpath/jdk.jar"), "{switched}");
|
||||
assert!(!switched.contains("jdk21/classpath/jdk.jar"), "{switched}");
|
||||
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()])
|
||||
);
|
||||
assert_eq!(fs::read_to_string(root.join("calls.txt")).unwrap(), "xx");
|
||||
}
|
||||
}
|
||||
@@ -40,18 +40,6 @@ pub fn structure_outputs(root: &Path, ps: &ProjectStructureSettings) -> (PathBuf
|
||||
(main, test)
|
||||
}
|
||||
|
||||
/// Whether Rebuild may delete the output folder `dir`: never the project folder or one above
|
||||
/// it, nor a folder that holds or lies inside a source, test or resource root.
|
||||
fn deletable_output(dir: &Path, root: &Path, roots: &StructureRoots) -> bool {
|
||||
let dir = normalize(dir);
|
||||
let overlaps = |r: &PathBuf| {
|
||||
let r = normalize(r);
|
||||
r.starts_with(&dir) || dir.starts_with(&r)
|
||||
};
|
||||
!normalize(root).starts_with(&dir)
|
||||
&& !roots.sources.iter().chain(&roots.tests).chain(&roots.resources).chain(&roots.test_resources).any(overlaps)
|
||||
}
|
||||
|
||||
fn module_name(root: &Path) -> String {
|
||||
root.file_name().map_or_else(|| "project".to_owned(), |n| n.to_string_lossy().into_owned())
|
||||
}
|
||||
@@ -162,6 +150,16 @@ fn classpath(entries: &[String]) -> String {
|
||||
entries.join(if cfg!(windows) { ";" } else { ":" })
|
||||
}
|
||||
|
||||
/// `--release N` from JDK 9 on; older compilers only know `-source` / `-target`.
|
||||
fn release_args(level: Option<u32>, jdk: Option<&StructureJdk>) -> Vec<String> {
|
||||
let Some(level) = level else { return Vec::new() };
|
||||
if jdk.is_none_or(|j| j.major >= 9) {
|
||||
vec!["--release".into(), level.to_string()]
|
||||
} else {
|
||||
vec!["-source".into(), format!("1.{level}"), "-target".into(), format!("1.{level}")]
|
||||
}
|
||||
}
|
||||
|
||||
/// `"17"`, `"1.8"`, `"JDK_17"` → the release number.
|
||||
pub fn language_release(level: &str) -> Option<u32> {
|
||||
let digits = level.trim().trim_start_matches("JDK_").trim_start_matches("jdk").replace('_', ".");
|
||||
@@ -169,25 +167,6 @@ pub fn language_release(level: &str) -> Option<u32> {
|
||||
digits.split(['.', ' ']).next()?.parse().ok().filter(|n| *n > 0)
|
||||
}
|
||||
|
||||
fn structure_compiler(
|
||||
root: &Path,
|
||||
ps: &ProjectStructureSettings,
|
||||
jdk: Option<&StructureJdk>,
|
||||
language_level: &str,
|
||||
) -> (Option<u32>, BTreeMap<String, String>, String) {
|
||||
let module = root_module(root, ps);
|
||||
let level = module
|
||||
.map(|m| m.language_level.as_str())
|
||||
.filter(|l| !l.trim().is_empty())
|
||||
.or(Some(language_level))
|
||||
.and_then(language_release);
|
||||
let env: BTreeMap<String, String> = jdk
|
||||
.map(|j| BTreeMap::from([("JAVA_HOME".to_owned(), j.home.to_string_lossy().into_owned())]))
|
||||
.unwrap_or_default();
|
||||
let javac = find_javac(&env);
|
||||
(level, env, javac)
|
||||
}
|
||||
|
||||
/// The Build / Rebuild plan of a project without a build tool, or `None` when it has no
|
||||
/// Java sources under its source roots. `language_level`: the project's, unless the module
|
||||
/// overrides it. Writes the javac argument files below `cache`.
|
||||
@@ -212,18 +191,23 @@ pub fn structure_plan(
|
||||
return Ok(None);
|
||||
}
|
||||
let (main_out, test_out) = structure_outputs(root, ps);
|
||||
let (level, env, javac) = structure_compiler(root, ps, jdk, language_level);
|
||||
let module = root_module(root, ps);
|
||||
let level = module
|
||||
.map(|m| m.language_level.as_str())
|
||||
.filter(|l| !l.trim().is_empty())
|
||||
.or(Some(language_level))
|
||||
.and_then(language_release);
|
||||
let env: BTreeMap<String, String> = jdk
|
||||
.map(|j| BTreeMap::from([("JAVA_HOME".to_owned(), j.home.to_string_lossy().into_owned())]))
|
||||
.unwrap_or_default();
|
||||
let javac = find_javac(&env);
|
||||
let args_dir = cache.join("javac");
|
||||
fs::create_dir_all(&args_dir)
|
||||
.map_err(|e| IdeError::internal(format!("cannot create {} ({e})", args_dir.display())))?;
|
||||
|
||||
let mut steps = Vec::new();
|
||||
if kind == BuildKind::Rebuild {
|
||||
let dirs: Vec<PathBuf> =
|
||||
[&main_out, &test_out].into_iter().filter(|d| deletable_output(d, root, roots)).cloned().collect();
|
||||
if !dirs.is_empty() {
|
||||
steps.push(BuildStep::action(Action::Clean(dirs), root));
|
||||
}
|
||||
steps.push(BuildStep::action(Action::Clean(vec![main_out.clone(), test_out.clone()]), root));
|
||||
}
|
||||
let main_cp = library_entries(root, ps, false);
|
||||
let compile = |name: &str, sources: &[PathBuf], out: &Path, cp: &[String]| -> IdeResult<BuildStep> {
|
||||
@@ -241,7 +225,7 @@ pub fn structure_plan(
|
||||
if !cp.is_empty() {
|
||||
step.args.extend(["-cp".into(), classpath(cp)]);
|
||||
}
|
||||
step.args.extend(single::release_args(level, jdk.map(|j| j.major)));
|
||||
step.args.extend(release_args(level, jdk));
|
||||
step.args.push(format!("@{}", args_file.to_string_lossy()));
|
||||
step.env = env.clone();
|
||||
step.mkdirs = vec![out.to_path_buf()];
|
||||
@@ -281,47 +265,6 @@ pub fn structure_plan(
|
||||
Ok(Some(BuildPlan { system: BuildSystem::Javac, title: module_name(root), steps }))
|
||||
}
|
||||
|
||||
/// Single-file `javac` plan for a Java project without a build tool (Project Structure).
|
||||
pub fn structure_compile_file_plan(
|
||||
root: &Path,
|
||||
ps: &ProjectStructureSettings,
|
||||
roots: &StructureRoots,
|
||||
jdk: Option<&StructureJdk>,
|
||||
language_level: &str,
|
||||
file: &Path,
|
||||
) -> IdeResult<BuildPlan> {
|
||||
let name = single::is_java_file(file)?;
|
||||
let rel = rel_str(root, file);
|
||||
let test = if roots.tests.is_empty() {
|
||||
single::is_test_source(&rel)
|
||||
} else {
|
||||
let file_norm = normalize(file);
|
||||
roots.tests.iter().any(|t| file_norm.starts_with(normalize(t)))
|
||||
};
|
||||
let (main_out, test_out) = structure_outputs(root, ps);
|
||||
let out_dir = if test { &test_out } else { &main_out };
|
||||
let mut cp: Vec<String> = Vec::new();
|
||||
if test && test_out.is_dir() {
|
||||
cp.push(test_out.to_string_lossy().into_owned());
|
||||
}
|
||||
if main_out.is_dir() {
|
||||
cp.push(main_out.to_string_lossy().into_owned());
|
||||
}
|
||||
cp.extend(library_entries(root, ps, test));
|
||||
let cp = single::join_classpath(cp);
|
||||
|
||||
let mut src_roots: Vec<PathBuf> = Vec::new();
|
||||
if test {
|
||||
src_roots.extend(roots.tests.iter().filter(|p| p.is_dir()).cloned());
|
||||
}
|
||||
src_roots.extend(roots.sources.iter().filter(|p| p.is_dir()).cloned());
|
||||
|
||||
let (level, env, javac) = structure_compiler(root, ps, jdk, language_level);
|
||||
let release = single::release_args(level, jdk.map(|j| j.major));
|
||||
let step = single::build_javac_step(&javac, root, out_dir, &cp, &src_roots, release, file, env)?;
|
||||
Ok(BuildPlan { system: BuildSystem::Javac, title: format!("Compile {name}"), steps: vec![step] })
|
||||
}
|
||||
|
||||
/// Where an artifact goes: its output folder, else `out/artifacts/<name>`.
|
||||
pub fn artifact_output(root: &Path, artifact: &ArtifactConfig) -> PathBuf {
|
||||
resolve_dir(root, &artifact.output_directory)
|
||||
@@ -367,8 +310,6 @@ fn artifact_steps(
|
||||
.find(|f| f.module == artifact.module || f.module.is_empty() && artifact.module == ".")
|
||||
.or_else(|| ps.facets.iter().find(|f| f.kind == "web"));
|
||||
let staging = cache.join("artifacts").join(file_name(&artifact.name));
|
||||
// What the last build laid out in a folder the user chose, so the next one replaces only that.
|
||||
let record = cache.join("artifacts").join(format!("{}.files", file_name(&artifact.name)));
|
||||
let mut steps = Vec::new();
|
||||
match (artifact.kind, war) {
|
||||
(ArtifactKind::Jar, None) => {
|
||||
@@ -383,11 +324,7 @@ fn artifact_steps(
|
||||
manifest.push_str(&format!("Class-Path: {}\r\n", names.join(" ")));
|
||||
}
|
||||
steps.push(BuildStep::action(
|
||||
Action::Layout {
|
||||
into: staging.clone(),
|
||||
entries: vec![(classes.to_path_buf(), PathBuf::new())],
|
||||
record: None,
|
||||
},
|
||||
Action::Layout { into: staging.clone(), entries: vec![(classes.to_path_buf(), PathBuf::new())] },
|
||||
root,
|
||||
));
|
||||
// The jar's Class-Path names the libraries next to it.
|
||||
@@ -395,7 +332,6 @@ fn artifact_steps(
|
||||
Action::Layout {
|
||||
into: out.clone(),
|
||||
entries: libraries.iter().map(|l| (l.clone(), file_of(l))).collect(),
|
||||
record: Some(record),
|
||||
},
|
||||
root,
|
||||
));
|
||||
@@ -417,9 +353,7 @@ fn artifact_steps(
|
||||
for lib in &libraries {
|
||||
entries.push((lib.clone(), Path::new("WEB-INF/lib").join(file_of(lib))));
|
||||
}
|
||||
// The exploded output may be a folder the user chose; the staging folder is the IDE's own.
|
||||
let record = (exploded != staging).then_some(record);
|
||||
steps.push(BuildStep::action(Action::Layout { into: exploded.clone(), entries, record }, root));
|
||||
steps.push(BuildStep::action(Action::Layout { into: exploded.clone(), entries }, root));
|
||||
let archive = war
|
||||
.map(Path::to_path_buf)
|
||||
.or_else(|| (kind != ArtifactKind::WarExploded).then(|| artifact_file(root, artifact)));
|
||||
@@ -473,10 +407,8 @@ pub(crate) enum Action {
|
||||
/// relative paths; files that are already up to date are left alone.
|
||||
CopyResources { from: Vec<PathBuf>, to: PathBuf },
|
||||
/// Lays out an artifact in `into`: each folder's content or file goes to its relative
|
||||
/// place (`""` = the top). What is no longer laid out is removed: without `record`, `into`
|
||||
/// is the IDE's own folder and is laid out afresh; with it, `into` is a folder the user chose
|
||||
/// and only the files the previous layout recorded there are removed, never anything else.
|
||||
Layout { into: PathBuf, entries: Vec<(PathBuf, PathBuf)>, record: Option<PathBuf> },
|
||||
/// place (`""` = the top). What is no longer laid out is removed.
|
||||
Layout { into: PathBuf, entries: Vec<(PathBuf, PathBuf)> },
|
||||
/// Zips the folder `from` into the archive `to`, with this manifest first.
|
||||
Archive { from: PathBuf, to: PathBuf, manifest: Option<String> },
|
||||
}
|
||||
@@ -509,39 +441,29 @@ impl Action {
|
||||
}
|
||||
Ok(format!("{copied} resource file(s) copied"))
|
||||
}
|
||||
Action::Layout { into, entries, record } => {
|
||||
Action::Layout { into, entries } => {
|
||||
// A fresh layout: files dropped from the sources must not linger in the artifact.
|
||||
if entries.iter().any(|(from, _)| from.starts_with(into)) {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"The artifact output folder {} holds files the artifact is made of",
|
||||
into.display()
|
||||
)));
|
||||
}
|
||||
if record.is_none() && into.exists() {
|
||||
if into.exists() {
|
||||
fs::remove_dir_all(into)
|
||||
.map_err(|e| IdeError::internal(format!("cannot delete {} ({e})", into.display())))?;
|
||||
}
|
||||
let mut written = Vec::new();
|
||||
let mut copied = 0;
|
||||
for (from, to) in entries {
|
||||
let target = into.join(to);
|
||||
// The folders of the output it goes into (and a folder entry's own) are
|
||||
// never links; a file in a link's place replaces the link.
|
||||
let mut at = into.to_path_buf();
|
||||
let folders = to.components().count().saturating_sub(usize::from(!from.is_dir()));
|
||||
for c in to.components().take(folders) {
|
||||
at.push(c);
|
||||
refuse_link(&at)?;
|
||||
}
|
||||
if from.is_dir() {
|
||||
copy_tree(from, &target, &mut written, cancel)?;
|
||||
copied += copy_tree(from, &target, cancel)?;
|
||||
} else if from.is_file() {
|
||||
copy_file(from, &target)?;
|
||||
written.push(target);
|
||||
copied += 1;
|
||||
}
|
||||
}
|
||||
if let Some(record) = record {
|
||||
replace_recorded(into, record, &written)?;
|
||||
}
|
||||
Ok(format!("{} file(s) laid out", written.len()))
|
||||
Ok(format!("{copied} file(s) laid out"))
|
||||
}
|
||||
Action::Archive { from, to, manifest } => {
|
||||
archive(from, to, manifest.as_deref(), cancel)?;
|
||||
@@ -552,10 +474,6 @@ impl Action {
|
||||
}
|
||||
|
||||
fn copy_file(from: &Path, to: &Path) -> IdeResult<()> {
|
||||
// A link in the artifact's place is replaced, not written through.
|
||||
if fs::symlink_metadata(to).is_ok_and(|m| m.file_type().is_symlink()) {
|
||||
fs::remove_file(to).map_err(|e| IdeError::internal(format!("cannot replace {} ({e})", to.display())))?;
|
||||
}
|
||||
if let Some(parent) = to.parent() {
|
||||
fs::create_dir_all(parent)
|
||||
.map_err(|e| IdeError::internal(format!("cannot create {} ({e})", parent.display())))?;
|
||||
@@ -564,80 +482,23 @@ fn copy_file(from: &Path, to: &Path) -> IdeResult<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn refuse_link(folder: &Path) -> IdeResult<()> {
|
||||
if fs::symlink_metadata(folder).is_ok_and(|m| m.file_type().is_symlink()) {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"{} links to another folder; the artifact is not laid out through it",
|
||||
folder.display()
|
||||
)));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn copy_tree(from: &Path, to: &Path, written: &mut Vec<PathBuf>, cancel: &CancellationToken) -> IdeResult<()> {
|
||||
fn copy_tree(from: &Path, to: &Path, cancel: &CancellationToken) -> IdeResult<usize> {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
let Ok(entries) = fs::read_dir(from) else { return Ok(()) };
|
||||
let Ok(entries) = fs::read_dir(from) else { return Ok(0) };
|
||||
let mut copied = 0;
|
||||
for e in entries.flatten() {
|
||||
let Ok(t) = e.file_type() else { continue };
|
||||
let target = to.join(e.file_name());
|
||||
if t.is_dir() {
|
||||
refuse_link(&target)?;
|
||||
copy_tree(&e.path(), &target, written, cancel)?;
|
||||
copied += copy_tree(&e.path(), &target, cancel)?;
|
||||
} else if t.is_file() {
|
||||
copy_file(&e.path(), &target)?;
|
||||
written.push(target);
|
||||
copied += 1;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Removes the files the previous layout recorded in `into` that this one didn't write
|
||||
/// (and the folders that leaves empty), then records `written` for the next layout.
|
||||
fn replace_recorded(into: &Path, record: &Path, written: &[PathBuf]) -> IdeResult<()> {
|
||||
let now: std::collections::HashSet<PathBuf> =
|
||||
written.iter().filter_map(|p| p.strip_prefix(into).ok().map(Path::to_path_buf)).collect();
|
||||
let before = fs::read_to_string(record).unwrap_or_default();
|
||||
let mut lines = before.lines();
|
||||
// The record names its folder first: one made for another output folder removes nothing.
|
||||
let same = lines.next().is_some_and(|dir| Path::new(dir) == into);
|
||||
for rel in lines.filter(|_| same).map(PathBuf::from) {
|
||||
// Only plain relative paths inside `into`: a damaged record must not reach elsewhere.
|
||||
if rel.as_os_str().is_empty()
|
||||
|| now.contains(&rel)
|
||||
|| rel.components().any(|c| !matches!(c, std::path::Component::Normal(_)))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let file = into.join(&rel);
|
||||
// Never through a link: a folder of the output that now links elsewhere (or a file that
|
||||
// is a link) leads out of what the layout wrote.
|
||||
let mut at = into.to_path_buf();
|
||||
let linked = rel.components().any(|c| {
|
||||
at.push(c);
|
||||
fs::symlink_metadata(&at).is_ok_and(|m| m.file_type().is_symlink())
|
||||
});
|
||||
if !linked && file.is_file() {
|
||||
let _ = fs::remove_file(&file);
|
||||
let mut dir = file.parent();
|
||||
while let Some(d) = dir.filter(|d| *d != into && d.starts_with(into)) {
|
||||
if fs::remove_dir(d).is_err() {
|
||||
break;
|
||||
}
|
||||
dir = d.parent();
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut list: Vec<String> = now.iter().map(|p| p.to_string_lossy().into_owned()).collect();
|
||||
list.sort();
|
||||
list.insert(0, into.to_string_lossy().into_owned());
|
||||
if let Some(parent) = record.parent() {
|
||||
fs::create_dir_all(parent)
|
||||
.map_err(|e| IdeError::internal(format!("cannot create {} ({e})", parent.display())))?;
|
||||
}
|
||||
fs::write(record, list.join("\n"))
|
||||
.map_err(|e| IdeError::internal(format!("cannot write {} ({e})", record.display())))
|
||||
Ok(copied)
|
||||
}
|
||||
|
||||
fn archive(from: &Path, to: &Path, manifest: Option<&str>, cancel: &CancellationToken) -> IdeResult<()> {
|
||||
@@ -837,37 +698,6 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rebuild_never_cleans_an_output_folder_over_the_project_or_its_sources() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path().join("p");
|
||||
write(&root.join("src/A.java"), "class A {}");
|
||||
let roots = StructureRoots { sources: vec![root.join("src")], ..Default::default() };
|
||||
for (main, test) in [(".", "bin"), ("src", "src/../test-out"), ("src/classes", ".."), ("", "")] {
|
||||
let mut ps = ProjectStructureSettings::default();
|
||||
ps.modules.insert(
|
||||
".".into(),
|
||||
ModuleStructureSettings {
|
||||
compiler_output: main.into(),
|
||||
test_compiler_output: test.into(),
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
let plan = structure_plan(&root, &ps, &roots, None, "17", BuildKind::Rebuild, &tmp.path().join("c"))
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let clean: Vec<String> =
|
||||
plan.steps.iter().map(BuildStep::display).filter(|s| s.starts_with("Clean")).collect();
|
||||
let expected: &[&str] = match main {
|
||||
"." => &["Clean bin"],
|
||||
"src" => &["Clean src/../test-out"],
|
||||
"src/classes" => &[],
|
||||
_ => &["Clean out/production/p, out/test/p"],
|
||||
};
|
||||
assert_eq!(clean, expected, "{main} / {test}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_plan_without_java_sources() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
@@ -982,166 +812,8 @@ mod tests {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let web = tmp.path().join("WebRoot");
|
||||
write(&web.join("a.jsp"), "");
|
||||
let action = Action::Layout {
|
||||
into: tmp.path().to_path_buf(),
|
||||
entries: vec![(web.clone(), PathBuf::new())],
|
||||
record: None,
|
||||
};
|
||||
let action = Action::Layout { into: tmp.path().to_path_buf(), entries: vec![(web.clone(), PathBuf::new())] };
|
||||
assert!(action.run(&CancellationToken::new()).is_err());
|
||||
assert!(web.join("a.jsp").is_file());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_chosen_output_folder_keeps_what_the_artifact_did_not_put_there() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let project = tmp.path().join("project");
|
||||
write(&project.join("src/A.java"), "class A {}");
|
||||
write(&project.join(".git/HEAD"), "ref: refs/heads/main");
|
||||
let libs = tmp.path().join("libs");
|
||||
write(&libs.join("a.jar"), "a");
|
||||
write(&libs.join("b.jar"), "b");
|
||||
let record = tmp.path().join("cache/artifacts/app.files");
|
||||
let layout = |names: &[&str]| Action::Layout {
|
||||
into: project.clone(),
|
||||
entries: names.iter().map(|n| (libs.join(n), PathBuf::from(n))).collect(),
|
||||
record: Some(record.clone()),
|
||||
};
|
||||
layout(&["a.jar", "b.jar"]).run(&CancellationToken::new()).unwrap();
|
||||
assert!(project.join("a.jar").is_file() && project.join("b.jar").is_file());
|
||||
// A library dropped from the artifact goes; the project's own files stay.
|
||||
layout(&["a.jar"]).run(&CancellationToken::new()).unwrap();
|
||||
assert!(project.join("a.jar").is_file() && !project.join("b.jar").exists());
|
||||
assert!(project.join("src/A.java").is_file() && project.join(".git/HEAD").is_file());
|
||||
// A damaged record never reaches outside the folder.
|
||||
write(&record, &format!("{}\n../outside.txt", project.display()));
|
||||
write(&tmp.path().join("outside.txt"), "x");
|
||||
layout(&["a.jar"]).run(&CancellationToken::new()).unwrap();
|
||||
assert!(tmp.path().join("outside.txt").is_file());
|
||||
// Nor through a folder of the output that now links elsewhere.
|
||||
#[cfg(unix)]
|
||||
{
|
||||
write(&project.join("assets/x.txt"), "laid out");
|
||||
write(&record, &format!("{}\nassets/x.txt", project.display()));
|
||||
fs::remove_dir_all(project.join("assets")).unwrap();
|
||||
std::os::unix::fs::symlink(project.join("src"), project.join("assets")).unwrap();
|
||||
write(&project.join("src/x.txt"), "source");
|
||||
layout(&["a.jar"]).run(&CancellationToken::new()).unwrap();
|
||||
assert!(project.join("src/x.txt").is_file());
|
||||
}
|
||||
// An entry's own folder that links elsewhere stops the layout instead of copying through it.
|
||||
#[cfg(unix)]
|
||||
{
|
||||
fs::remove_file(project.join("assets")).unwrap();
|
||||
std::os::unix::fs::symlink(project.join("src"), project.join("classes")).unwrap();
|
||||
write(&tmp.path().join("out/A.class"), "compiled");
|
||||
let into_link = Action::Layout {
|
||||
into: project.clone(),
|
||||
entries: vec![(tmp.path().join("out"), PathBuf::from("classes"))],
|
||||
record: Some(record.clone()),
|
||||
};
|
||||
assert!(into_link.run(&CancellationToken::new()).is_err());
|
||||
assert!(!project.join("src/A.class").exists());
|
||||
fs::remove_file(project.join("classes")).unwrap();
|
||||
}
|
||||
// Nor does one made for another output folder.
|
||||
write(&project.join("c.jar"), "mine");
|
||||
write(&record, "/elsewhere\nc.jar");
|
||||
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
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -41,7 +41,7 @@ fn record_path(cache: &Path, root: &Path, file: Option<&Path>) -> PathBuf {
|
||||
/// Re-stamps files whose content changed without advancing mtime (git
|
||||
/// checkout, external sync): timestamp-incremental Maven would otherwise skip
|
||||
/// them as "unchanged" and the rebuild would compile nothing.
|
||||
pub(super) fn restamp(root: &Path, edits: &[PathBuf]) {
|
||||
fn restamp(root: &Path, edits: &[PathBuf]) {
|
||||
let now = std::time::SystemTime::now();
|
||||
for rel in edits {
|
||||
let path = root.join(rel);
|
||||
|
||||
@@ -1,58 +0,0 @@
|
||||
// OpenIDEA single-file javac classpath probe for Gradle projects.
|
||||
// Prints the target source set's output directory, compile classpath, source dirs and release version.
|
||||
import groovy.json.JsonOutput
|
||||
|
||||
def identity = { Project p -> try { p.identityPath.toString() } catch (ignored) { p.path } }
|
||||
|
||||
gradle.projectsEvaluated { g ->
|
||||
def wantedTarget = g.rootProject.findProperty('openidea.target')?.toString() ?: ':'
|
||||
def scope = g.rootProject.findProperty('openidea.scope')?.toString() ?: 'main'
|
||||
def project = g.rootProject.allprojects.find { identity(it) == wantedTarget }
|
||||
if (project == null && g.parent == null) {
|
||||
project = g.rootProject.allprojects.find { it.path == wantedTarget }
|
||||
}
|
||||
if (project == null) return
|
||||
|
||||
def sets = project.extensions.findByName('sourceSets') ?: project.findProperty('sourceSets')
|
||||
def ss = sets?.findByName(scope)
|
||||
if (ss == null) return
|
||||
|
||||
def outDir = null
|
||||
try { outDir = ss.java.destinationDirectory.get().asFile.canonicalPath } catch (ignored) {}
|
||||
if (outDir == null) {
|
||||
try { outDir = ss.output.classesDirs.files.iterator().next().canonicalPath } catch (ignored) {}
|
||||
}
|
||||
|
||||
def cp = []
|
||||
if (scope == 'test') {
|
||||
def mainSet = sets.findByName('main')
|
||||
try { mainSet?.output?.classesDirs?.files?.each { cp << it.canonicalPath } } catch (ignored) {}
|
||||
}
|
||||
try { ss.compileClasspath.files.each { cp << it.canonicalPath } } catch (ignored) {}
|
||||
cp = cp.unique()
|
||||
|
||||
def srcDirs = []
|
||||
try { ss.java.srcDirs.each { srcDirs << it.canonicalPath } } catch (ignored) {}
|
||||
if (scope == 'test') {
|
||||
def mainSet = sets.findByName('main')
|
||||
try { mainSet?.java?.srcDirs?.each { srcDirs << it.canonicalPath } } catch (ignored) {}
|
||||
}
|
||||
srcDirs = srcDirs.unique()
|
||||
|
||||
def release = null
|
||||
try {
|
||||
def compileTask = project.tasks.findByName(ss.compileJavaTaskName)
|
||||
release = compileTask?.options?.release?.getOrNull()
|
||||
} catch (ignored) {}
|
||||
if (release == null) {
|
||||
try {
|
||||
def java = project.extensions.findByName('java')
|
||||
def lv = null
|
||||
try { lv = java?.toolchain?.languageVersion?.getOrNull() } catch (ignored) {}
|
||||
def target = java != null ? java.targetCompatibility : project.findProperty('targetCompatibility')
|
||||
release = lv != null ? lv.asInt() : (target?.majorVersion as Integer)
|
||||
} catch (ignored) {}
|
||||
}
|
||||
|
||||
println '@openidea-compile-cp\t' + JsonOutput.toJson([outDir: outDir, classpath: cp, srcDirs: srcDirs, release: release])
|
||||
}
|
||||
@@ -30,9 +30,7 @@ def processedResources = { Project p, s ->
|
||||
def describe = { Project p ->
|
||||
def m = [path: identity(p), dir: canon(p.projectDir), buildDir: canon(p.layout.buildDirectory.get().asFile)]
|
||||
if (p.gradle.parent != null) m.build = identity(p.rootProject)
|
||||
m.resolvableConfigurations = p.configurations.findAll { it.canBeResolved }.collect { it.name }.sort()
|
||||
// Gradle 4.x has it as a convention property, not an extension.
|
||||
def sets = p.extensions.findByName('sourceSets') ?: p.findProperty('sourceSets')
|
||||
def sets = p.extensions.findByName('sourceSets')
|
||||
if (sets != null) {
|
||||
// Test source sets as IDEA classifies them: `test`, test fixtures, JVM test suites,
|
||||
// and sets whose folders the `idea` plugin lists as test sources.
|
||||
@@ -53,12 +51,9 @@ def describe = { Project p ->
|
||||
}
|
||||
}
|
||||
try {
|
||||
// `java` is Gradle 4.10+ (a convention before), its toolchain 6.7+.
|
||||
def java = p.extensions.findByName('java')
|
||||
def lv = null
|
||||
try { lv = java?.toolchain?.languageVersion?.getOrNull() } catch (ignored) {}
|
||||
def target = java != null ? java.targetCompatibility : p.findProperty('targetCompatibility')
|
||||
m.java = lv != null ? lv.asInt() : (target?.majorVersion as Integer)
|
||||
def lv = java?.toolchain?.languageVersion?.getOrNull()
|
||||
m.java = lv != null ? lv.asInt() : (java?.targetCompatibility?.majorVersion as Integer)
|
||||
} catch (ignored) {}
|
||||
println '@openidea-model\t' + JsonOutput.toJson(m)
|
||||
}
|
||||
|
||||
@@ -41,10 +41,6 @@ pub struct GradleProject {
|
||||
/// Project-relative build script, if any.
|
||||
pub build_file: Option<String>,
|
||||
pub tasks: Vec<GradleTask>,
|
||||
/// Configurations Gradle can resolve, or null before Gradle reports the project.
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub resolvable_configurations: Option<Vec<String>>,
|
||||
/// Identity path of the nested build holding the project (`:lib` for `includeBuild`,
|
||||
/// `:buildSrc`); null for the opened build.
|
||||
#[serde(default)]
|
||||
@@ -305,7 +301,6 @@ fn project_at(root: &Path, path: String, name: String, pdir: &Path) -> GradlePro
|
||||
path,
|
||||
name,
|
||||
tasks,
|
||||
resolvable_configurations: None,
|
||||
build: None,
|
||||
}
|
||||
}
|
||||
@@ -322,8 +317,6 @@ pub struct ReportedProject {
|
||||
pub build_dir: Option<String>,
|
||||
#[serde(default)]
|
||||
pub source_sets: Vec<ReportedSourceSet>,
|
||||
#[serde(default)]
|
||||
pub resolvable_configurations: Option<Vec<String>>,
|
||||
/// Toolchain language version, else target compatibility.
|
||||
#[serde(default)]
|
||||
pub java: Option<u32>,
|
||||
@@ -419,7 +412,6 @@ pub fn merge_reported_projects(root: &Path, model: &mut GradleModel, reported: &
|
||||
if p.build.as_deref().is_some_and(|b| b.ends_with(":buildSrc")) {
|
||||
project.tasks.clear();
|
||||
}
|
||||
project.resolvable_configurations = p.resolvable_configurations.clone();
|
||||
project.build = p.build.clone();
|
||||
project
|
||||
})
|
||||
@@ -1638,11 +1630,6 @@ Pattern: clean<TaskName>: Cleans the output files of a task.
|
||||
path: path.into(),
|
||||
dir: ws.join(d).to_string_lossy().into_owned(),
|
||||
build: build.map(Into::into),
|
||||
resolvable_configurations: match path {
|
||||
":" => Some(vec!["reviewTools".into(), "runtimeClasspath".into()]),
|
||||
":lib:core" => Some(Vec::new()),
|
||||
_ => None,
|
||||
},
|
||||
..ReportedProject::default()
|
||||
};
|
||||
format!("{MODEL_LINE}{}\n", serde_json::to_string(&project).unwrap())
|
||||
@@ -1671,12 +1658,6 @@ Pattern: clean<TaskName>: Cleans the output files of a task.
|
||||
);
|
||||
let build_src = &model.projects[2];
|
||||
assert!(build_src.tasks.is_empty(), "buildSrc tasks cannot run from the root build");
|
||||
assert_eq!(
|
||||
model.projects[0].resolvable_configurations,
|
||||
Some(vec!["reviewTools".into(), "runtimeClasspath".into()])
|
||||
);
|
||||
assert_eq!(model.projects[1].resolvable_configurations, None);
|
||||
assert_eq!(model.projects[4].resolvable_configurations, Some(Vec::new()));
|
||||
assert!(!model.projects[4].tasks.is_empty());
|
||||
assert!(build_files(&root, &model).contains(&ws.join("lib/settings.gradle")));
|
||||
}
|
||||
|
||||
@@ -1,16 +1,13 @@
|
||||
//! A Gradle project's resolved dependencies for the Dependency Analyzer:
|
||||
//! `gradle <project>:dependencies --configuration <name>`, parsed from its tree report.
|
||||
//! The reports it read are kept per build ([`save_gradle_report`]) until a build file
|
||||
//! changes, for readers that must not run Gradle themselves (plugins).
|
||||
|
||||
use crate::gradle;
|
||||
use crate::process;
|
||||
use crate::sync::{self, SyncOptions, error_summary};
|
||||
use crate::sync::{SyncOptions, error_summary};
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::path::Path;
|
||||
use std::sync::Mutex;
|
||||
|
||||
/// One line of the report: an occurrence of a dependency where it is requested.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
@@ -135,7 +132,7 @@ pub fn gradle_dependencies(
|
||||
configuration: &str,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<Vec<GradleDependency>> {
|
||||
if configuration.is_empty() || !configuration.chars().all(|c| c.is_alphanumeric() || matches!(c, '_' | '-' | '.')) {
|
||||
if !configuration.chars().all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-') || configuration.is_empty() {
|
||||
return Err(IdeError::invalid(format!("not a configuration name: {configuration}")));
|
||||
}
|
||||
if !project.starts_with(':') || project.chars().any(char::is_whitespace) {
|
||||
@@ -143,7 +140,7 @@ pub fn gradle_dependencies(
|
||||
}
|
||||
let task = if project == ":" { ":dependencies".to_owned() } else { format!("{project}:dependencies") };
|
||||
let mut args: Vec<String> =
|
||||
vec!["--console=plain".into(), "-q".into(), task, format!("--configuration={configuration}")];
|
||||
vec!["--console=plain".into(), "-q".into(), task, "--configuration".into(), configuration.into()];
|
||||
if options.offline {
|
||||
args.push("--offline".into());
|
||||
}
|
||||
@@ -156,62 +153,11 @@ pub fn gradle_dependencies(
|
||||
|_, _| {},
|
||||
)?;
|
||||
if !out.success {
|
||||
return Err(IdeError::unavailable(error_summary(&out)));
|
||||
}
|
||||
if let Some(note) = sync::truncation_note(&out) {
|
||||
return Err(IdeError::unavailable(note));
|
||||
return Err(IdeError::unavailable(error_summary(&out.text)));
|
||||
}
|
||||
Ok(parse_report(&out.text))
|
||||
}
|
||||
|
||||
/// A `dependencies` report of one project of a build for one configuration.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct GradleReport {
|
||||
/// Gradle path of the project (`:`, `:app`).
|
||||
pub project: String,
|
||||
pub configuration: String,
|
||||
pub dependencies: Vec<GradleDependency>,
|
||||
}
|
||||
|
||||
#[derive(Default, Serialize, Deserialize)]
|
||||
struct ReportCache {
|
||||
/// The build files the reports were read with ([`sync::hash_gradle_files`]).
|
||||
hash: String,
|
||||
reports: Vec<GradleReport>,
|
||||
}
|
||||
|
||||
const REPORT_CACHE: &str = "gradle-dependencies.json";
|
||||
|
||||
/// Keeps `report` with the build's other reports (`cache_dir` is the build's cache
|
||||
/// directory), replacing an earlier one of the same project and configuration. Reports
|
||||
/// read before a build file changed are dropped.
|
||||
pub fn save_gradle_report(
|
||||
root: &Path,
|
||||
cache_dir: &Path,
|
||||
model: &gradle::GradleModel,
|
||||
report: &GradleReport,
|
||||
) -> IdeResult<()> {
|
||||
// Reports of several configurations may finish together: one read-modify-write at a time.
|
||||
static SAVING: Mutex<()> = Mutex::new(());
|
||||
let _saving = SAVING.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let hash = sync::hash_gradle_files(&gradle::build_files(root, model));
|
||||
let mut cache = sync::read_cache::<ReportCache>(cache_dir, REPORT_CACHE)
|
||||
.filter(|c| c.hash == hash)
|
||||
.unwrap_or_else(|| ReportCache { hash, reports: Vec::new() });
|
||||
cache.reports.retain(|r| (&r.project, &r.configuration) != (&report.project, &report.configuration));
|
||||
cache.reports.push(report.clone());
|
||||
sync::write_cache(cache_dir, REPORT_CACHE, &cache)
|
||||
}
|
||||
|
||||
/// The reports kept for the build, unless a build file changed since they were read.
|
||||
pub fn gradle_reports(root: &Path, cache_dir: &Path, model: &gradle::GradleModel) -> Vec<GradleReport> {
|
||||
let Some(cache) = sync::read_cache::<ReportCache>(cache_dir, REPORT_CACHE) else { return Vec::new() };
|
||||
if cache.hash != sync::hash_gradle_files(&gradle::build_files(root, model)) {
|
||||
return Vec::new();
|
||||
}
|
||||
cache.reports
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -288,37 +234,6 @@ runtimeClasspath - Runtime classpath of source set 'main'.
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reports_are_kept_per_project_and_configuration_until_a_build_file_changes() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
let cache = root.join("cache");
|
||||
std::fs::write(root.join("settings.gradle"), "include 'app'").unwrap();
|
||||
std::fs::write(root.join("build.gradle"), "").unwrap();
|
||||
let model = gradle::load(root).unwrap();
|
||||
assert!(gradle_reports(root, &cache, &model).is_empty());
|
||||
let report = |project: &str, configuration: &str, version: &str| GradleReport {
|
||||
project: project.into(),
|
||||
configuration: configuration.into(),
|
||||
dependencies: vec![dep("org.a", "b", Some(version))],
|
||||
};
|
||||
save_gradle_report(root, &cache, &model, &report(":app", "runtimeClasspath", "1.0")).unwrap();
|
||||
save_gradle_report(root, &cache, &model, &report(":app", "compileClasspath", "1.0")).unwrap();
|
||||
// Reading a report again replaces what was read before.
|
||||
save_gradle_report(root, &cache, &model, &report(":app", "runtimeClasspath", "2.0")).unwrap();
|
||||
assert_eq!(
|
||||
gradle_reports(root, &cache, &model),
|
||||
[report(":app", "compileClasspath", "1.0"), report(":app", "runtimeClasspath", "2.0")]
|
||||
);
|
||||
// A comment changes nothing Gradle reads; a dependency does.
|
||||
std::fs::write(root.join("build.gradle"), "// notes").unwrap();
|
||||
assert_eq!(gradle_reports(root, &cache, &model).len(), 2);
|
||||
std::fs::write(root.join("build.gradle"), "dependencies { implementation 'org.a:b:3.0' }").unwrap();
|
||||
assert!(gradle_reports(root, &cache, &model).is_empty());
|
||||
save_gradle_report(root, &cache, &model, &report(":", "compileClasspath", "3.0")).unwrap();
|
||||
assert_eq!(gradle_reports(root, &cache, &model), [report(":", "compileClasspath", "3.0")]);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn runs_the_report_of_the_project_and_configuration() {
|
||||
@@ -340,14 +255,14 @@ runtimeClasspath - Runtime classpath of source set 'main'.
|
||||
&gradle::load(root).unwrap(),
|
||||
&options,
|
||||
":app",
|
||||
"review.tools",
|
||||
"testRuntimeClasspath",
|
||||
&CancellationToken::new(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(tree, vec![dep("org.a", "b", Some("1.0"))]);
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(root.join("args")).unwrap().trim(),
|
||||
"--console=plain -q :app:dependencies --configuration=review.tools --offline"
|
||||
"--console=plain -q :app:dependencies --configuration testRuntimeClasspath --offline"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -78,14 +78,14 @@ fn has_kotlin_sources(root: &Path) -> bool {
|
||||
})
|
||||
}
|
||||
|
||||
fn plan(root: &Path, model: &BuildModel, cancel: &CancellationToken) -> IdeResult<compile::BuildPlan> {
|
||||
fn plan(root: &Path, model: &BuildModel) -> IdeResult<compile::BuildPlan> {
|
||||
if model.maven.as_ref().is_none_or(|m| m.projects.is_empty()) {
|
||||
return Err(IdeError::invalid("Kotlin bridge requires a Maven build root"));
|
||||
}
|
||||
Ok(compile::BuildPlan {
|
||||
system: compile::BuildSystem::Maven,
|
||||
title: root.file_name().unwrap_or_default().to_string_lossy().into_owned(),
|
||||
steps: compile::maven_steps(root, model, BuildKind::Build, None, None, cancel)?,
|
||||
steps: compile::maven_steps(root, model, BuildKind::Build, None)?,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -99,7 +99,7 @@ pub fn build(
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<Outcome> {
|
||||
std::fs::create_dir_all(generation)?;
|
||||
let mut plan = plan(root, model, cancel)?;
|
||||
let mut plan = plan(root, model)?;
|
||||
let mut manifests = Vec::new();
|
||||
for (index, step) in plan.steps.iter_mut().enumerate() {
|
||||
step.args.push("--fail-at-end".into());
|
||||
@@ -522,7 +522,7 @@ mod tests {
|
||||
}
|
||||
std::fs::write(root.join("kotlin/App.kt"), "class App").unwrap();
|
||||
assert!(has_kotlin(root, &model), "{marker}");
|
||||
let plan = plan(root, &model, &CancellationToken::new()).unwrap();
|
||||
let plan = plan(root, &model).unwrap();
|
||||
assert_eq!(plan.system, compile::BuildSystem::Maven);
|
||||
assert_eq!(plan.steps.len(), 2);
|
||||
for (step, name) in plan.steps.iter().zip(["java", "kotlin"]) {
|
||||
@@ -562,7 +562,7 @@ mod tests {
|
||||
..Default::default()
|
||||
};
|
||||
assert!(has_kotlin(workspace.path(), &model));
|
||||
assert_eq!(plan(workspace.path(), &model, &CancellationToken::new()).unwrap().steps[0].cwd, external.path());
|
||||
assert_eq!(plan(workspace.path(), &model).unwrap().steps[0].cwd, external.path());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -13,21 +13,17 @@ pub mod kotlin_bridge;
|
||||
pub mod maven;
|
||||
pub mod pom_edit;
|
||||
mod process;
|
||||
#[cfg(test)]
|
||||
mod process_numbers;
|
||||
pub mod sbt;
|
||||
pub mod surefire;
|
||||
mod sync;
|
||||
pub mod web;
|
||||
mod xml;
|
||||
|
||||
pub use gradle::{GradleModel, GradleProject, GradleTask};
|
||||
pub use gradle_deps::{GradleDependency, GradleReport, gradle_dependencies, gradle_reports, save_gradle_report};
|
||||
pub use gradle_deps::{GradleDependency, gradle_dependencies};
|
||||
pub use maven::{MavenDependency, MavenModel, MavenPlugin, MavenProfile, MavenProject, Omission};
|
||||
pub use sbt::{SbtBuild, SbtProject};
|
||||
pub use sync::{
|
||||
SyncOptions, SyncProgress, maven_offline, maven_profiles, save_maven_offline, save_maven_profiles, sync_gradle,
|
||||
sync_gradle_model, sync_maven,
|
||||
SyncOptions, SyncProgress, maven_profiles, save_maven_profiles, sync_gradle, sync_gradle_model, sync_maven,
|
||||
};
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
@@ -83,23 +79,11 @@ pub fn load_linked(
|
||||
maven_repo: Option<PathBuf>,
|
||||
settings: &ide_core::settings::MavenSettings,
|
||||
gradle_settings: &ide_core::settings::GradleSettings,
|
||||
) -> BuildModel {
|
||||
load_linked_with_jdk(root, cache_dir, maven_repo, settings, gradle_settings, None)
|
||||
}
|
||||
|
||||
/// [`load_linked`] with the JDK Maven runs on, for JDK-activated Maven profiles.
|
||||
pub fn load_linked_with_jdk(
|
||||
root: &Path,
|
||||
cache_dir: &Path,
|
||||
maven_repo: Option<PathBuf>,
|
||||
settings: &ide_core::settings::MavenSettings,
|
||||
gradle_settings: &ide_core::settings::GradleSettings,
|
||||
maven_jdk_version: Option<u32>,
|
||||
) -> BuildModel {
|
||||
let maven = maven::has_projects(root, settings).then(|| {
|
||||
let profiles = settings.profiles(&sync::maven_profiles(cache_dir));
|
||||
let repo = maven_repo.or_else(maven::default_local_repo);
|
||||
let mut m = maven::load_with_linked_jdk(root, repo, &profiles, maven_jdk_version, &settings.linked_projects);
|
||||
let mut m = maven::load_with_linked(root, repo, &profiles, &settings.linked_projects);
|
||||
maven::UnlinkedProjects::from_model(&m, settings).filter(&mut m);
|
||||
// The user settings' profiles can be chosen too (`-P` applies to them as well).
|
||||
for p in maven::user_settings_file(root, settings).map(|f| maven::settings_profiles(&f)).unwrap_or_default() {
|
||||
@@ -143,22 +127,10 @@ pub fn gradle_external_roots(
|
||||
gradle::external_roots(root, dirs.iter().map(String::as_str))
|
||||
}
|
||||
|
||||
/// Directories outside `root`, outermost only, of Maven POMs linked from there and, in a
|
||||
/// trusted project, of the modules its reactor lists there (`<module>../service-a</module>`):
|
||||
/// extra content roots, as IDEA imports such modules with content roots of their own.
|
||||
/// Linked POMs are read as explicit paths; the reactor's POMs are parsed, but not their
|
||||
/// parents, and nothing walks directories. `cache_dir` holds the profiles chosen at the last sync.
|
||||
pub fn maven_external_roots(
|
||||
root: &Path,
|
||||
cache_dir: &Path,
|
||||
settings: &ide_core::settings::MavenSettings,
|
||||
trusted: bool,
|
||||
) -> Vec<PathBuf> {
|
||||
let mut dirs = maven::external_pom_dirs(root, &settings.linked_projects);
|
||||
if trusted {
|
||||
let profiles = settings.profiles(&sync::maven_profiles(cache_dir));
|
||||
dirs.extend(maven::reactor_external_dirs(root, &profiles, &settings.unlinked_projects));
|
||||
}
|
||||
/// Directories of Maven POMs linked from outside `root`, outermost only.
|
||||
/// Reads just those explicit paths (no POM parse and no directory walk).
|
||||
pub fn maven_external_roots(root: &Path, linked: &[String]) -> Vec<PathBuf> {
|
||||
let dirs = maven::external_pom_dirs(root, linked);
|
||||
let owned: Vec<String> = dirs.iter().map(|dir| dir.to_string_lossy().into_owned()).collect();
|
||||
gradle::external_roots(root, owned.iter().map(String::as_str))
|
||||
}
|
||||
@@ -279,59 +251,6 @@ mod tests {
|
||||
assert!(gradle_external_roots(&root, &temp.path().join("cache"), &settings).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reactor_modules_outside_the_root_are_content_roots_of_a_trusted_project() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(temp.path()).unwrap();
|
||||
let root = base.join("workspace");
|
||||
let cache = base.join("cache");
|
||||
let write = |rel: &str, text: &str| {
|
||||
let path = base.join(rel).join("pom.xml");
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
std::fs::write(path, format!("<project><artifactId>{rel}</artifactId>{text}</project>")).unwrap();
|
||||
};
|
||||
let reactor = |modules: &str| {
|
||||
format!(
|
||||
"<packaging>pom</packaging><modules>{modules}</modules>\
|
||||
<profiles><profile><id>extra</id><modules><module>../service-c</module></modules></profile></profiles>"
|
||||
)
|
||||
};
|
||||
let all = "<module>core</module><module>../service-a</module><module>..</module>";
|
||||
write("workspace", &reactor(all));
|
||||
write("workspace/core", "<modules><module>../../service-d</module></modules>");
|
||||
write("service-a", "<modules><module>impl</module><module>../service-e</module></modules>");
|
||||
for module in ["service-a/impl", "service-c", "service-d", "service-e", "unrelated"] {
|
||||
write(module, "");
|
||||
}
|
||||
// The folder holding the project is not a module beside it, nor are its other modules.
|
||||
write("", "<modules><module>workspace</module><module>unrelated</module></modules>");
|
||||
|
||||
let mut settings = ide_core::settings::MavenSettings::default();
|
||||
let roots = |settings: &ide_core::settings::MavenSettings, trusted| {
|
||||
maven_external_roots(&root, &cache, settings, trusted)
|
||||
};
|
||||
let (a, c, d, e) =
|
||||
(base.join("service-a"), base.join("service-c"), base.join("service-d"), base.join("service-e"));
|
||||
assert_eq!(roots(&settings, true), [a.clone(), d.clone(), e.clone()]);
|
||||
assert!(roots(&settings, false).is_empty(), "Restricted Mode does not widen the index");
|
||||
|
||||
settings.active_profiles = "extra".into();
|
||||
assert_eq!(roots(&settings, true), [a.clone(), c.clone(), d.clone(), e.clone()]);
|
||||
save_maven_profiles(&cache, &["!extra".into()]).unwrap();
|
||||
assert_eq!(roots(&settings, true), [a.clone(), d.clone(), e.clone()]);
|
||||
|
||||
settings.unlinked_projects = vec![a.join("pom.xml").to_string_lossy().replace('\\', "/")];
|
||||
assert_eq!(roots(&settings, true), std::slice::from_ref(&d));
|
||||
settings.unlinked_projects.clear();
|
||||
|
||||
write("workspace", &reactor("<module>core</module>"));
|
||||
assert_eq!(roots(&settings, true), std::slice::from_ref(&d));
|
||||
write("workspace/core", "");
|
||||
assert!(roots(&settings, true).is_empty());
|
||||
write("workspace", &reactor(all));
|
||||
assert_eq!(roots(&settings, true), [a, e]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn settings_profiles_and_checkbox_choices_control_modules_before_sync() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
+113
-1155
File diff suppressed because it is too large.
Load diff
@@ -3,13 +3,7 @@
|
||||
use super::MavenProject;
|
||||
use crate::process;
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult};
|
||||
use std::collections::HashSet;
|
||||
use std::fs::{self, File};
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
use std::time::SystemTime;
|
||||
|
||||
const DEPENDENCY_PLUGIN: &str = "org.apache.maven.plugins:maven-dependency-plugin:3.8.1";
|
||||
const SOURCE_REFRESH_WORKERS: usize = 4;
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub struct Artifact {
|
||||
@@ -17,29 +11,6 @@ pub struct Artifact {
|
||||
pub name: String,
|
||||
pub version: String,
|
||||
pub sources: PathBuf,
|
||||
binary: PathBuf,
|
||||
}
|
||||
|
||||
fn valid_part(part: &str) -> bool {
|
||||
!part.is_empty()
|
||||
&& part != "."
|
||||
&& part != ".."
|
||||
&& part.chars().all(|c| c.is_ascii_alphanumeric() || "_.-".contains(c))
|
||||
}
|
||||
|
||||
fn modified_file(path: &Path) -> Option<SystemTime> {
|
||||
let metadata = fs::metadata(path).ok()?;
|
||||
if metadata.is_file() { metadata.modified().ok() } else { None }
|
||||
}
|
||||
|
||||
impl Artifact {
|
||||
fn stale_binary(&self) -> Option<SystemTime> {
|
||||
if !self.version.ends_with("-SNAPSHOT") {
|
||||
return None;
|
||||
}
|
||||
let binary = modified_file(&self.binary)?;
|
||||
(modified_file(&self.sources)? < binary).then_some(binary)
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolve only jars inside the selected local repository, including custom repositories.
|
||||
@@ -57,14 +28,16 @@ pub fn artifact(jar: &Path, repository: &Path) -> Option<Artifact> {
|
||||
}
|
||||
let n = parts.len();
|
||||
let (name, version, file) = (parts[n - 3], parts[n - 2], parts[n - 1]);
|
||||
if !parts[..n - 1].iter().all(|s| valid_part(s)) || file != format!("{name}-{version}.jar") {
|
||||
let valid = |s: &str| {
|
||||
!s.is_empty() && s != "." && s != ".." && s.chars().all(|c| c.is_ascii_alphanumeric() || "_.-".contains(c))
|
||||
};
|
||||
if !parts[..n - 1].iter().all(|s| valid(s)) || file != format!("{name}-{version}.jar") {
|
||||
return None;
|
||||
}
|
||||
Some(Artifact {
|
||||
group: parts[..n - 3].join("."),
|
||||
name: name.into(),
|
||||
version: version.into(),
|
||||
binary: jar.to_owned(),
|
||||
sources: jar.with_file_name(format!("{name}-{version}-sources.jar")),
|
||||
})
|
||||
}
|
||||
@@ -75,58 +48,26 @@ pub fn download(
|
||||
artifact: &Artifact,
|
||||
repository: &Path,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<Option<PathBuf>> {
|
||||
resolve(root, project, artifact, repository, &[], artifact.stale_binary(), cancel)
|
||||
}
|
||||
|
||||
fn resolve(
|
||||
root: &Path,
|
||||
project: &MavenProject,
|
||||
artifact: &Artifact,
|
||||
repository: &Path,
|
||||
profile_args: &[String],
|
||||
stale: Option<SystemTime>,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<Option<PathBuf>> {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
if stale.is_none() && artifact.sources.is_file() {
|
||||
if artifact.sources.is_file() {
|
||||
return Ok(Some(artifact.sources.clone()));
|
||||
}
|
||||
let mut args = vec!["-B".into(), "-N".into(), "-Dstyle.color=never".into()];
|
||||
args.extend(project.options.iter().cloned());
|
||||
args.extend(profile_args.iter().cloned());
|
||||
args.push(format!("-Dmaven.repo.local={}", repository.display()));
|
||||
let coordinate = format!("-Dartifact={}:{}:{}:jar:sources", artifact.group, artifact.name, artifact.version);
|
||||
let stage = if let Some(binary) = stale {
|
||||
// Keep the existing attachment readable while Maven resolves the timestamped snapshot.
|
||||
// Disable Resolver's in-place copy to the base -SNAPSHOT filename.
|
||||
let stage =
|
||||
tempfile::Builder::new().prefix(".openidea-sources-").tempdir_in(artifact.sources.parent().unwrap())?;
|
||||
args.extend([
|
||||
"-U".into(),
|
||||
"-Daether.artifactResolver.snapshotNormalization=false".into(),
|
||||
format!("{DEPENDENCY_PLUGIN}:copy"),
|
||||
coordinate,
|
||||
"-Dmdep.useBaseVersion=true".into(),
|
||||
format!("-DoutputDirectory={}", stage.path().display()),
|
||||
]);
|
||||
Some((stage, binary))
|
||||
} else {
|
||||
args.extend([format!("{DEPENDENCY_PLUGIN}:get"), coordinate, "-Dtransitive=false".into()]);
|
||||
None
|
||||
};
|
||||
args.extend(project.options.clone());
|
||||
args.extend([
|
||||
format!("-Dmaven.repo.local={}", repository.display()),
|
||||
"org.apache.maven.plugins:maven-dependency-plugin:3.8.1:get".into(),
|
||||
format!("-Dartifact={}:{}:{}:jar:sources", artifact.group, artifact.name, artifact.version),
|
||||
"-Dtransitive=false".into(),
|
||||
]);
|
||||
let output = process::run(&project.command, &args, &root.join(&project.dir), &project.env, cancel, |_, _| {})?;
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
if let Some((stage, binary)) = stage {
|
||||
let resolved = stage.path().join(artifact.sources.file_name().unwrap());
|
||||
if output.success && resolved.is_file() {
|
||||
return replace_stale_sources(artifact, &resolved, binary, cancel);
|
||||
}
|
||||
} else if artifact.sources.is_file() {
|
||||
if artifact.sources.is_file() {
|
||||
return Ok(Some(artifact.sources.clone()));
|
||||
}
|
||||
let coordinate = format!("{}:{}:jar:sources:{}", artifact.group, artifact.name, artifact.version);
|
||||
@@ -142,115 +83,6 @@ fn resolve(
|
||||
))
|
||||
}
|
||||
|
||||
fn replace_stale_sources(
|
||||
artifact: &Artifact,
|
||||
resolved: &Path,
|
||||
binary: SystemTime,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<Option<PathBuf>> {
|
||||
// Maven can fall back to a locally installed snapshot. Keep its timestamp if it returned
|
||||
// the same bytes so a later reload can retry when newer sources are available.
|
||||
let hash = |path| -> std::io::Result<_> { Ok(blake3::Hasher::new().update_reader(File::open(path)?)?.finalize()) };
|
||||
if hash(resolved)? == hash(&artifact.sources)? {
|
||||
return Ok(None);
|
||||
}
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
match artifact.stale_binary() {
|
||||
Some(current) if current == binary => {
|
||||
File::options().write(true).open(resolved)?.set_modified(SystemTime::now().max(binary))?;
|
||||
fs::rename(resolved, &artifact.sources)?;
|
||||
Ok(Some(artifact.sources.clone()))
|
||||
}
|
||||
None if artifact.sources.is_file() => Ok(Some(artifact.sources.clone())),
|
||||
_ => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolved Maven dependencies with an existing attachment. Binaries may still be
|
||||
/// updating during import, so freshness is checked when the refresh runs.
|
||||
pub fn cached_snapshots<'a>(
|
||||
repository: &Path,
|
||||
projects: impl Iterator<Item = (usize, &'a MavenProject)>,
|
||||
) -> Vec<(usize, Artifact)> {
|
||||
let mut seen = HashSet::new();
|
||||
let mut candidates = Vec::new();
|
||||
for (owner, project) in projects {
|
||||
let mut dependencies: Vec<_> = project.dependencies.iter().collect();
|
||||
while let Some(dep) = dependencies.pop() {
|
||||
if !dep.resolved() {
|
||||
continue;
|
||||
}
|
||||
dependencies.extend(&dep.children);
|
||||
let Some(version) = dep.version.as_deref().filter(|v| v.ends_with("-SNAPSHOT") && valid_part(v)) else {
|
||||
continue;
|
||||
};
|
||||
if dep.scope == "system"
|
||||
|| dep.classifier.is_some()
|
||||
|| !matches!(dep.kind.as_str(), "jar" | "bundle" | "maven-plugin" | "ejb")
|
||||
|| !valid_part(&dep.artifact_id)
|
||||
|| !dep.group_id.split('.').all(valid_part)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let name = &dep.artifact_id;
|
||||
let jar = repository
|
||||
.join(dep.group_id.replace('.', "/"))
|
||||
.join(name)
|
||||
.join(version)
|
||||
.join(format!("{name}-{version}.jar"));
|
||||
if let Some(artifact) = artifact(&jar, repository)
|
||||
&& artifact.sources.is_file()
|
||||
&& seen.insert(jar)
|
||||
{
|
||||
candidates.push((owner, artifact));
|
||||
}
|
||||
}
|
||||
}
|
||||
candidates
|
||||
}
|
||||
|
||||
/// Refresh only previously attached snapshots. Maven subprocesses are bounded
|
||||
/// and share the build reload's cancellation token.
|
||||
pub fn refresh_snapshots(
|
||||
root: &Path,
|
||||
projects: &[MavenProject],
|
||||
repository: &Path,
|
||||
candidates: &[(usize, Artifact)],
|
||||
profiles: &[String],
|
||||
cancel: &CancellationToken,
|
||||
) -> Vec<PathBuf> {
|
||||
let profile_args = if profiles.is_empty() { vec![] } else { vec![format!("-P{}", profiles.join(","))] };
|
||||
let profile_args = &profile_args;
|
||||
let stale: Vec<_> = candidates.iter().filter(|(_, artifact)| artifact.stale_binary().is_some()).collect();
|
||||
let batch_size = stale.len().div_ceil(SOURCE_REFRESH_WORKERS).max(1);
|
||||
std::thread::scope(|scope| {
|
||||
let workers: Vec<_> = stale
|
||||
.chunks(batch_size)
|
||||
.map(|batch| {
|
||||
scope.spawn(move || {
|
||||
let mut refreshed = Vec::new();
|
||||
for (owner, artifact) in batch.iter().copied() {
|
||||
if cancel.is_cancelled() {
|
||||
break;
|
||||
}
|
||||
let Some(binary) = artifact.stale_binary() else { continue };
|
||||
match resolve(root, &projects[*owner], artifact, repository, profile_args, Some(binary), cancel)
|
||||
{
|
||||
Ok(Some(_)) => refreshed.push(artifact.binary.clone()),
|
||||
Ok(None) => {}
|
||||
Err(e) => tracing::debug!(path = %artifact.sources.display(), "Maven sources refresh: {e}"),
|
||||
}
|
||||
}
|
||||
refreshed
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
workers.into_iter().flat_map(|worker| worker.join().expect("Maven sources worker")).collect()
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -289,86 +121,4 @@ mod tests {
|
||||
assert_eq!(artifact(Path::new(path), repository), None, "{path}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selects_existing_snapshot_attachments_from_the_resolved_tree() {
|
||||
use crate::maven::{MavenDependency, Omission};
|
||||
|
||||
let repo = tempfile::tempdir().unwrap();
|
||||
let dependency = |name: &str, version: &str, cached: bool| {
|
||||
if cached {
|
||||
let dir = repo.path().join("example").join(name).join(version);
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
fs::write(dir.join(format!("{name}-{version}-sources.jar")), b"cached").unwrap();
|
||||
}
|
||||
MavenDependency {
|
||||
group_id: "example".into(),
|
||||
artifact_id: name.into(),
|
||||
version: Some(version.into()),
|
||||
kind: "jar".into(),
|
||||
..Default::default()
|
||||
}
|
||||
};
|
||||
let transitive = dependency("transitive", "1-SNAPSHOT", true);
|
||||
let direct = MavenDependency { children: vec![transitive.clone()], ..dependency("direct", "1-SNAPSHOT", true) };
|
||||
let omitted =
|
||||
MavenDependency { omitted: Some(Omission::Conflict), ..dependency("omitted", "1-SNAPSHOT", true) };
|
||||
let projects = [
|
||||
MavenProject {
|
||||
dependencies: vec![
|
||||
direct,
|
||||
omitted,
|
||||
dependency("missing", "1-SNAPSHOT", false),
|
||||
dependency("release", "1", true),
|
||||
],
|
||||
..Default::default()
|
||||
},
|
||||
MavenProject { dependencies: vec![transitive], ..Default::default() },
|
||||
];
|
||||
let mut found: Vec<_> = cached_snapshots(repo.path(), projects.iter().enumerate())
|
||||
.into_iter()
|
||||
.map(|(owner, artifact)| (owner, artifact.name))
|
||||
.collect();
|
||||
found.sort();
|
||||
assert_eq!(found, [(0, "direct".into()), (0, "transitive".into())]);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn downloads_sources_again_when_the_snapshot_binary_is_newer() {
|
||||
use std::fs::FileTimes;
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
use std::time::Duration;
|
||||
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let repository = dir.path().join("repository");
|
||||
let jar = repository.join("example/lib/1-SNAPSHOT/lib-1-SNAPSHOT.jar");
|
||||
fs::create_dir_all(jar.parent().unwrap()).unwrap();
|
||||
fs::write(&jar, b"new binary").unwrap();
|
||||
let artifact = artifact(&jar, &repository).unwrap();
|
||||
fs::write(&artifact.sources, b"old sources").unwrap();
|
||||
File::open(&artifact.sources)
|
||||
.unwrap()
|
||||
.set_times(FileTimes::new().set_modified(SystemTime::now() - Duration::from_secs(60)))
|
||||
.unwrap();
|
||||
let launcher = dir.path().join("mvn");
|
||||
fs::write(
|
||||
&launcher,
|
||||
"#!/bin/sh\nfor arg do\n case \"$arg\" in\n -DoutputDirectory=*) out=\"${arg#*=}\" ;;\n esac\ndone\nprintf 'new sources' > \"$out/lib-1-SNAPSHOT-sources.jar\"\n",
|
||||
)
|
||||
.unwrap();
|
||||
fs::set_permissions(&launcher, fs::Permissions::from_mode(0o755)).unwrap();
|
||||
let cancel = CancellationToken::new();
|
||||
cancel.cancel();
|
||||
assert!(download(dir.path(), &MavenProject::default(), &artifact, &repository, &cancel).is_err());
|
||||
assert_eq!(fs::read(&artifact.sources).unwrap(), b"old sources");
|
||||
let project = MavenProject { command: launcher.to_string_lossy().into_owned(), ..Default::default() };
|
||||
let cancel = CancellationToken::new();
|
||||
let path = download(dir.path(), &project, &artifact, &repository, &cancel).unwrap().unwrap();
|
||||
assert_eq!(fs::read(&path).unwrap(), b"new sources");
|
||||
assert_eq!(
|
||||
download(dir.path(), &MavenProject::default(), &artifact, &repository, &CancellationToken::new()).unwrap(),
|
||||
Some(path)
|
||||
);
|
||||
}
|
||||
}
|
||||
+26
-490
@@ -17,94 +17,16 @@ pub(crate) enum Stream {
|
||||
Stderr,
|
||||
}
|
||||
|
||||
/// A single line longer than this without a newline is delivered as several lines: the pump
|
||||
/// buffer stays bounded whatever the child prints (progress bars, minified bundles, binary
|
||||
/// output), and every byte still arrives.
|
||||
pub(crate) const MAX_LINE_BYTES: usize = 1024 * 1024;
|
||||
/// `Output::text` stops growing past this while the pipes keep draining: a chatty build can
|
||||
/// print far more than is ever parsed back out of the retained copy.
|
||||
pub(crate) const MAX_TEXT_BYTES: usize = 32 * 1024 * 1024;
|
||||
/// Lines the pipe readers may queue ahead of the consumer. A build printing faster than
|
||||
/// `on_line` takes its lines waits on its full pipe, as it would on a terminal, instead of
|
||||
/// the lines piling up in memory (a line is at most [`MAX_LINE_BYTES`] in [`run_bounded`]).
|
||||
const LINE_QUEUE: usize = 64;
|
||||
/// What [`pump_bounded`] reads from a pipe at a time.
|
||||
const PUMP_CHUNK: usize = 64 * 1024;
|
||||
|
||||
/// One line of a child's output, with the stream it came from.
|
||||
type Line = (Stream, String);
|
||||
|
||||
/// The queue from the pipe readers to the consumer: bounded, so the readers wait while the
|
||||
/// consumer is behind.
|
||||
fn line_queue() -> (mpsc::SyncSender<Line>, mpsc::Receiver<Line>) {
|
||||
mpsc::sync_channel(LINE_QUEUE)
|
||||
}
|
||||
|
||||
pub(crate) struct Output {
|
||||
pub success: bool,
|
||||
/// Every line, stdout and stderr interleaved as received, up to [`MAX_TEXT_BYTES`].
|
||||
/// Every line, stdout and stderr interleaved as received.
|
||||
pub text: String,
|
||||
/// More output followed the retained `text`; the lines were still fed to `on_line`.
|
||||
pub truncated: bool,
|
||||
}
|
||||
|
||||
/// Bounded pump for callers that stream every line and only summarize errors: reads
|
||||
/// [`PUMP_CHUNK`] chunks, splits newline-free runs at a UTF-8 char boundary at the line cap,
|
||||
/// and never grows one line buffer without bound.
|
||||
fn pump_bounded(stream: Box<dyn Read + Send>, kind: Stream, tx: &mpsc::SyncSender<Line>) {
|
||||
let mut reader = BufReader::new(stream);
|
||||
// `terminated`: the buffer ends in the stream's newline. A segment cut from a
|
||||
// newline-free run at the line cap must keep a trailing `\r` — it is data.
|
||||
let send = |buf: &mut Vec<u8>, terminated: bool, tx: &mpsc::SyncSender<Line>| {
|
||||
let line = ide_core::output_encoding::decode_tool_output(buf);
|
||||
let line = if terminated { line.trim_end_matches(['\n', '\r']).to_owned() } else { line };
|
||||
buf.clear();
|
||||
tx.send((kind, line)).is_ok()
|
||||
};
|
||||
let mut chunk = vec![0u8; PUMP_CHUNK];
|
||||
let mut line: Vec<u8> = Vec::with_capacity(256);
|
||||
'read: loop {
|
||||
let n = match reader.read(&mut chunk) {
|
||||
Ok(0) | Err(_) => break,
|
||||
Ok(n) => n,
|
||||
};
|
||||
let mut start = 0;
|
||||
for (i, &b) in chunk[..n].iter().enumerate() {
|
||||
if b == b'\n' {
|
||||
line.extend_from_slice(&chunk[start..=i]);
|
||||
if !send(&mut line, true, tx) {
|
||||
break 'read;
|
||||
}
|
||||
start = i + 1;
|
||||
}
|
||||
}
|
||||
line.extend_from_slice(&chunk[start..n]);
|
||||
while line.len() > MAX_LINE_BYTES {
|
||||
let mut at = MAX_LINE_BYTES;
|
||||
while at > 0 && line[at] & 0xC0 == 0x80 {
|
||||
at -= 1;
|
||||
}
|
||||
// Malformed input with no boundary at all: split raw and let decoding say so.
|
||||
if at == 0 {
|
||||
at = MAX_LINE_BYTES;
|
||||
}
|
||||
let rest = line.split_off(at);
|
||||
if !send(&mut line, false, tx) {
|
||||
break 'read;
|
||||
}
|
||||
line = rest;
|
||||
}
|
||||
}
|
||||
if !line.is_empty() {
|
||||
send(&mut line, true, tx);
|
||||
}
|
||||
}
|
||||
|
||||
/// `program` as spawnable: a bare name (`mvn`, `mvn.cmd`) resolves on the IDE's
|
||||
/// search path — the login shell's `PATH` plus version-manager shims — since the
|
||||
/// app's own `PATH` can be minimal and `Command` would not see `mvn` there. The `PATH`
|
||||
/// of the project holding `cwd` (its direnv `.envrc`) comes first.
|
||||
pub(crate) fn program_path(program: &str, env: &BTreeMap<String, String>, cwd: &Path) -> std::path::PathBuf {
|
||||
/// app's own `PATH` can be minimal and `Command` would not see `mvn` there.
|
||||
pub(crate) fn program_path(program: &str, env: &BTreeMap<String, String>) -> std::path::PathBuf {
|
||||
let path = std::path::Path::new(program);
|
||||
if !path.is_relative() || path.components().count() > 1 {
|
||||
return path.to_path_buf();
|
||||
@@ -113,13 +35,12 @@ pub(crate) fn program_path(program: &str, env: &BTreeMap<String, String>, cwd: &
|
||||
.iter()
|
||||
.find(|(k, _)| k.eq_ignore_ascii_case("PATH"))
|
||||
.map(|(_, v)| std::ffi::OsString::from(v))
|
||||
.unwrap_or_else(|| ide_core::tool_path::search_path_in(cwd));
|
||||
.unwrap_or_else(ide_core::tool_path::search_path);
|
||||
ide_core::process::find_executable(program, &search).unwrap_or_else(|| path.to_path_buf())
|
||||
}
|
||||
|
||||
/// Runs `program args` in `cwd`, feeding each output line to `on_line`; kills
|
||||
/// the process group and returns `cancelled` when `cancel` fires. `Output.text`
|
||||
/// keeps every line: callers that parse a complete model from it use this.
|
||||
/// the process group and returns `cancelled` when `cancel` fires.
|
||||
pub(crate) fn run(
|
||||
program: &str,
|
||||
args: &[String],
|
||||
@@ -131,20 +52,6 @@ pub(crate) fn run(
|
||||
run_with_env(program, args, cwd, env, false, cancel, on_line)
|
||||
}
|
||||
|
||||
/// Like [`run`], but bounds both the per-line buffer and the retained copy. For callers
|
||||
/// that stream every line to `on_line` and use `Output.text` only for error summaries:
|
||||
/// sync/model listings must be kept whole and use [`run`] instead.
|
||||
pub(crate) fn run_bounded(
|
||||
program: &str,
|
||||
args: &[String],
|
||||
cwd: &Path,
|
||||
env: &BTreeMap<String, String>,
|
||||
cancel: &CancellationToken,
|
||||
on_line: impl FnMut(Stream, &str),
|
||||
) -> IdeResult<Output> {
|
||||
run_with_env_capture(program, args, cwd, env, RunOptions { bounded: true, ..Default::default() }, cancel, on_line)
|
||||
}
|
||||
|
||||
pub(crate) fn run_with_env(
|
||||
program: &str,
|
||||
args: &[String],
|
||||
@@ -152,39 +59,14 @@ pub(crate) fn run_with_env(
|
||||
env: &BTreeMap<String, String>,
|
||||
clear_env: bool,
|
||||
cancel: &CancellationToken,
|
||||
on_line: impl FnMut(Stream, &str),
|
||||
) -> IdeResult<Output> {
|
||||
run_with_env_capture(program, args, cwd, env, RunOptions { clear_env, ..Default::default() }, cancel, on_line)
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Default)]
|
||||
struct RunOptions {
|
||||
clear_env: bool,
|
||||
bounded: bool,
|
||||
}
|
||||
|
||||
fn run_with_env_capture(
|
||||
program: &str,
|
||||
args: &[String],
|
||||
cwd: &Path,
|
||||
env: &BTreeMap<String, String>,
|
||||
options: RunOptions,
|
||||
cancel: &CancellationToken,
|
||||
mut on_line: impl FnMut(Stream, &str),
|
||||
) -> IdeResult<Output> {
|
||||
let RunOptions { clear_env, bounded } = options;
|
||||
tracing::info!("build: {program} {} (in {})", args.join(" "), cwd.display());
|
||||
// Output is read as UTF-8: JVMs on Windows are told to write it (see `ide_core::output_encoding`).
|
||||
let encoding =
|
||||
ide_core::output_encoding::fix(program, args, env, |k| std::env::var(k).ok(), "UTF-8", cfg!(windows));
|
||||
let program = program_path(program, env, cwd);
|
||||
let mut command = if ide_core::process::needs_sh(&program) {
|
||||
let mut sh = Command::new("/bin/sh");
|
||||
sh.arg(&program);
|
||||
sh
|
||||
} else {
|
||||
Command::new(&program)
|
||||
};
|
||||
let program = program_path(program, env);
|
||||
let mut command = Command::new(&program);
|
||||
command.args(args).current_dir(cwd).envs(env).envs(encoding.env.iter().map(|(k, v)| (k, v))).stdin(Stdio::null());
|
||||
command.stdout(Stdio::piped()).stderr(Stdio::piped());
|
||||
// Its own group: `mvnw` / `gradlew` start the JVM as a child, and cancelling kills both.
|
||||
@@ -194,25 +76,20 @@ fn run_with_env_capture(
|
||||
}
|
||||
let mut child =
|
||||
command.spawn().map_err(|e| IdeError::unavailable(format!("cannot start {}: {e}", program.display())))?;
|
||||
let (tx, rx) = line_queue();
|
||||
let pump = |stream: Box<dyn Read + Send>, kind: Stream, tx: mpsc::SyncSender<Line>| {
|
||||
let (tx, rx) = mpsc::channel::<(Stream, String)>();
|
||||
let pump = |stream: Box<dyn Read + Send>, kind: Stream, tx: mpsc::Sender<(Stream, String)>| {
|
||||
std::thread::spawn(move || {
|
||||
if bounded {
|
||||
pump_bounded(stream, kind, &tx);
|
||||
} else {
|
||||
// Model listings are parsed from Output.text: keep every line whole, however long.
|
||||
let mut reader = BufReader::new(stream);
|
||||
let mut buf = Vec::new();
|
||||
loop {
|
||||
buf.clear();
|
||||
match reader.read_until(b'\n', &mut buf) {
|
||||
Ok(0) | Err(_) => break,
|
||||
Ok(_) => {
|
||||
let line = ide_core::output_encoding::decode_tool_output(&buf);
|
||||
let line = line.trim_end_matches(['\n', '\r']).to_owned();
|
||||
if tx.send((kind, line)).is_err() {
|
||||
break;
|
||||
}
|
||||
let mut reader = BufReader::new(stream);
|
||||
let mut buf = Vec::new();
|
||||
loop {
|
||||
buf.clear();
|
||||
match reader.read_until(b'\n', &mut buf) {
|
||||
Ok(0) | Err(_) => break,
|
||||
Ok(_) => {
|
||||
let line = ide_core::output_encoding::decode_tool_output(&buf);
|
||||
let line = line.trim_end_matches(['\n', '\r']).to_owned();
|
||||
if tx.send((kind, line)).is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -224,18 +101,7 @@ fn run_with_env_capture(
|
||||
child.stderr.take().map(|s| pump(Box::new(s), Stream::Stderr, tx.clone())),
|
||||
];
|
||||
drop(tx);
|
||||
// Retained copy of the output: the first half of the cap, then — once output overflows —
|
||||
// a rolling tail instead of the middle. Error summaries read the end of the output, while
|
||||
// listings parsed out of a successful run read from the start. The pipes keep draining
|
||||
// either way: `on_line` still sees every line, and the child waits on its pipe only
|
||||
// while `on_line` is behind, never because the retained copy is full.
|
||||
let cap = MAX_TEXT_BYTES / 2;
|
||||
let mut head = String::new();
|
||||
let mut tail: std::collections::VecDeque<Vec<u8>> = Default::default();
|
||||
let mut chunk: Vec<u8> = Vec::new();
|
||||
let mut tail_bytes = 0usize;
|
||||
let mut total = 0usize;
|
||||
let mut truncated = false;
|
||||
let mut text = String::new();
|
||||
loop {
|
||||
if cancel.is_cancelled() {
|
||||
kill_tree(&mut child);
|
||||
@@ -245,34 +111,8 @@ fn run_with_env_capture(
|
||||
Ok((_, line)) if encoding.notice.as_ref() == Some(&line) => {}
|
||||
Ok((stream, line)) => {
|
||||
on_line(stream, &line);
|
||||
if !bounded {
|
||||
// The caller parses a complete model from `text`, so keep every line.
|
||||
head.push_str(&line);
|
||||
head.push('\n');
|
||||
continue;
|
||||
}
|
||||
total += line.len() + 1;
|
||||
if !truncated {
|
||||
if head.len() + line.len() < cap {
|
||||
head.push_str(&line);
|
||||
head.push('\n');
|
||||
continue;
|
||||
}
|
||||
truncated = true;
|
||||
}
|
||||
// Fixed-size chunks, not per-line buffers: a chatty build pushes millions of
|
||||
// lines past the cap, and the tail must add no allocation per line.
|
||||
chunk.extend_from_slice(line.as_bytes());
|
||||
chunk.push(b'\n');
|
||||
if chunk.len() >= 64 * 1024 {
|
||||
tail_bytes += chunk.len();
|
||||
tail.push_back(std::mem::take(&mut chunk));
|
||||
chunk.reserve_exact(64 * 1024);
|
||||
while tail_bytes > cap {
|
||||
let Some(front) = tail.pop_front() else { break };
|
||||
tail_bytes -= front.len();
|
||||
}
|
||||
}
|
||||
text.push_str(&line);
|
||||
text.push('\n');
|
||||
}
|
||||
Err(mpsc::RecvTimeoutError::Timeout) => {}
|
||||
Err(mpsc::RecvTimeoutError::Disconnected) => break,
|
||||
@@ -282,87 +122,12 @@ fn run_with_env_capture(
|
||||
let _ = r.join();
|
||||
}
|
||||
let status = child.wait()?;
|
||||
let mut text = head;
|
||||
if truncated {
|
||||
if !chunk.is_empty() {
|
||||
tail_bytes += chunk.len();
|
||||
tail.push_back(std::mem::take(&mut chunk));
|
||||
}
|
||||
// The last partial chunk may sit past the cap; drop whole front chunks back under it.
|
||||
while tail_bytes > cap {
|
||||
let Some(front) = tail.pop_front() else { break };
|
||||
tail_bytes -= front.len();
|
||||
}
|
||||
// Tail chunks are flushed only right after a completed line, so the tail always begins
|
||||
// at a line boundary — no leading fragment to drop.
|
||||
let tail = ide_core::output_encoding::decode_tool_output(&tail.into_iter().flatten().collect::<Vec<u8>>());
|
||||
let omitted = total.saturating_sub(text.len() + tail.len());
|
||||
if omitted == 0 {
|
||||
// Everything that overflowed the head still fits in the tail: nothing was lost.
|
||||
truncated = false;
|
||||
} else {
|
||||
text.push_str(&format!("[{omitted} bytes of build output between these lines were not retained]\n"));
|
||||
}
|
||||
text.push_str(&tail);
|
||||
}
|
||||
Ok(Output { success: status.success(), text, truncated })
|
||||
Ok(Output { success: status.success(), text })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::time::Instant;
|
||||
|
||||
#[test]
|
||||
fn a_model_line_over_one_mebibyte_is_kept_whole_for_the_parsers() {
|
||||
if cfg!(windows) {
|
||||
return;
|
||||
}
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
// A Gradle MODEL_LINE JSON line longer than the bounded pump's 1 MiB line cap,
|
||||
// surrounded by ordinary output.
|
||||
let script = "echo start; head -c 1048576 /dev/zero | tr '\\0' a; printf '\\n{\"id\":\"big\"}\\n'; echo end";
|
||||
let mut lines = Vec::new();
|
||||
let out = run(
|
||||
"sh",
|
||||
&["-c".into(), script.into()],
|
||||
tmp.path(),
|
||||
&BTreeMap::new(),
|
||||
&CancellationToken::new(),
|
||||
|_, line| lines.push(line.to_owned()),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(out.success);
|
||||
assert!(!out.truncated);
|
||||
// The long line is one line, not segments that a JSON-line parser would skip.
|
||||
assert_eq!(lines.len(), 4);
|
||||
assert_eq!(lines[1].len(), 1_048_576);
|
||||
assert!(out.text.contains("{\"id\":\"big\"}"));
|
||||
let models: Vec<serde_json::Value> = out.text.lines().filter_map(|l| serde_json::from_str(l).ok()).collect();
|
||||
assert_eq!(models.len(), 1, "the model line must survive full retention");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_successful_report_over_the_text_cap_is_retained_in_full() {
|
||||
if cfg!(windows) {
|
||||
return;
|
||||
}
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let args = ["-c".into(), r"awk 'BEGIN{for(i=1;i<=6000000;i++)print i}'".into()];
|
||||
let mut fed = 0usize;
|
||||
let out = run("sh", &args, tmp.path(), &BTreeMap::new(), &CancellationToken::new(), |_, line| {
|
||||
fed += line.len() + 1;
|
||||
})
|
||||
.unwrap();
|
||||
assert!(out.success);
|
||||
assert!(!out.truncated);
|
||||
// Every line of a large successful dependency/model report is still there.
|
||||
assert_eq!(out.text.len(), fed);
|
||||
assert!(out.text.starts_with("1\n"));
|
||||
assert!(out.text.ends_with("6000000\n"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn runs_and_cancels_processes() {
|
||||
@@ -382,11 +147,10 @@ mod tests {
|
||||
)
|
||||
.unwrap();
|
||||
assert!(!out.success);
|
||||
assert!(!out.truncated);
|
||||
lines.sort_by(|a, b| a.1.cmp(&b.1));
|
||||
assert_eq!(lines, [(Stream::Stdout, "one".to_owned()), (Stream::Stderr, "two".to_owned())]);
|
||||
cancel.cancel();
|
||||
let err = run_bounded("sh", &["-c".into(), "sleep 5".into()], tmp.path(), &BTreeMap::new(), &cancel, |_, _| {})
|
||||
let err = run("sh", &["-c".into(), "sleep 5".into()], tmp.path(), &BTreeMap::new(), &cancel, |_, _| {})
|
||||
.err()
|
||||
.unwrap();
|
||||
assert_eq!(err.kind, ide_core::error::ErrorKind::Cancelled);
|
||||
@@ -406,237 +170,9 @@ mod tests {
|
||||
std::thread::sleep(Duration::from_millis(200));
|
||||
c.cancel();
|
||||
});
|
||||
let err =
|
||||
run_bounded("sh", &["-c".into(), script], tmp.path(), &BTreeMap::new(), &cancel, |_, _| {}).err().unwrap();
|
||||
let err = run("sh", &["-c".into(), script], tmp.path(), &BTreeMap::new(), &cancel, |_, _| {}).err().unwrap();
|
||||
assert_eq!(err.kind, ide_core::error::ErrorKind::Cancelled);
|
||||
std::thread::sleep(Duration::from_millis(1300));
|
||||
assert!(!marker.exists(), "the background child must be killed with the group");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn output_past_the_text_cap_keeps_head_and_tail_and_drains() {
|
||||
if cfg!(windows) {
|
||||
return;
|
||||
}
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
// Numbered lines 1..=6,000,000 ≈ 45 MB: past the 32 MiB retained cap.
|
||||
let args = ["-c".into(), r"awk 'BEGIN{for(i=1;i<=6000000;i++)print i}'".into()];
|
||||
let mut fed = 0usize;
|
||||
let mut last_seen = String::new();
|
||||
let out = run_bounded("sh", &args, tmp.path(), &BTreeMap::new(), &CancellationToken::new(), |_, line| {
|
||||
fed += line.len() + 1;
|
||||
last_seen = line.to_owned();
|
||||
})
|
||||
.unwrap();
|
||||
assert!(out.success);
|
||||
assert!(out.truncated);
|
||||
// The pipes drained to the end: the callback saw the last line.
|
||||
assert_eq!(last_seen, "6000000");
|
||||
assert_eq!(fed, out_success_bytes());
|
||||
// The retained copy is bounded, keeps the head and the tail, and says what was dropped.
|
||||
assert!(out.text.len() <= MAX_TEXT_BYTES + 128, "{}", out.text.len());
|
||||
assert!(out.text.starts_with("1\n"));
|
||||
assert!(out.text.ends_with("6000000\n"));
|
||||
assert!(out.text.contains("were not retained]"));
|
||||
assert!(!out.text.contains("\n3000000\n"), "a middle line must be the dropped part");
|
||||
}
|
||||
|
||||
/// Lines `1..=6_000_000` emit exactly this many bytes (digit count + newline each).
|
||||
fn out_success_bytes() -> usize {
|
||||
(1..=6_000_000u64).map(|n| n.checked_ilog10().unwrap() as usize + 2).sum()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_newline_free_run_longer_than_the_line_cap_arrives_as_split_lines() {
|
||||
if cfg!(windows) {
|
||||
return;
|
||||
}
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
// 2.5 MiB of `x` without a single newline.
|
||||
let args = ["-c".into(), "head -c 2621440 /dev/zero | tr '\\0' x".into()];
|
||||
let mut lines = Vec::new();
|
||||
let out = run_bounded("sh", &args, tmp.path(), &BTreeMap::new(), &CancellationToken::new(), |_, line| {
|
||||
lines.push(line.to_owned())
|
||||
})
|
||||
.unwrap();
|
||||
assert!(out.success);
|
||||
assert!(!out.truncated);
|
||||
// Split at the cap, not dropped: the segments carry every byte and none is unbounded.
|
||||
assert!(lines.len() >= 3, "{}", lines.len());
|
||||
assert_eq!(lines.iter().map(String::len).sum::<usize>(), 2_621_440);
|
||||
assert!(lines.iter().all(|l| l.len() <= MAX_LINE_BYTES));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_line_split_never_cuts_a_multibyte_character() {
|
||||
if cfg!(windows) {
|
||||
return;
|
||||
}
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
// `x` up to one byte before the 1 MiB cap, then `é` (two bytes) straddling it, then more `x`.
|
||||
let script =
|
||||
"head -c 1048575 /dev/zero | tr '\\0' x; printf '\\303\\251'; head -c 1048575 /dev/zero | tr '\\0' x";
|
||||
let mut lines = Vec::new();
|
||||
let out = run_bounded(
|
||||
"sh",
|
||||
&["-c".into(), script.into()],
|
||||
tmp.path(),
|
||||
&BTreeMap::new(),
|
||||
&CancellationToken::new(),
|
||||
|_, line| lines.push(line.to_owned()),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(out.success);
|
||||
// The é straddles the 1 MiB split point: segments shift to keep it whole.
|
||||
assert!(lines.len() >= 2, "{}", lines.len());
|
||||
// The character survived the split: present whole, never as U+FFFD halves.
|
||||
assert!(lines.iter().any(|l| l.contains('é')));
|
||||
assert!(lines.iter().all(|l| !l.contains('\u{FFFD}')));
|
||||
assert_eq!(lines.iter().map(String::len).sum::<usize>(), 1_048_575 + 2 + 1_048_575);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn output_just_past_the_head_cap_loses_nothing() {
|
||||
if cfg!(windows) {
|
||||
return;
|
||||
}
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
// 4-byte `pad` lines up to just past the 16 MiB head cap, then the real last line:
|
||||
// the overflow fits the tail whole, so nothing is dropped and nothing is marked.
|
||||
let script = "yes pad | head -c 16777213; echo 'FATAL: the real error'";
|
||||
let out = run_bounded(
|
||||
"sh",
|
||||
&["-c".into(), script.into()],
|
||||
tmp.path(),
|
||||
&BTreeMap::new(),
|
||||
&CancellationToken::new(),
|
||||
|_, _| {},
|
||||
)
|
||||
.unwrap();
|
||||
assert!(out.success);
|
||||
assert!(!out.truncated);
|
||||
assert!(!out.text.contains("were not retained]"));
|
||||
assert!(out.text.starts_with("pad\n"));
|
||||
assert!(out.text.ends_with("FATAL: the real error\n"));
|
||||
}
|
||||
|
||||
/// Numbered lines of `LINE_LEN` bytes each, counting the bytes taken: a pipe stand-in that
|
||||
/// reports when it is dropped, which is when the pump owning it ends.
|
||||
const LINE_LEN: usize = 100;
|
||||
|
||||
struct NumberedLines {
|
||||
next: usize,
|
||||
lines: usize,
|
||||
taken: Arc<AtomicUsize>,
|
||||
gone: mpsc::Sender<()>,
|
||||
}
|
||||
|
||||
fn numbered(n: usize) -> String {
|
||||
format!("{n:0width$}", width = LINE_LEN - 1)
|
||||
}
|
||||
|
||||
impl Read for NumberedLines {
|
||||
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
|
||||
let mut n = 0;
|
||||
while self.next < self.lines && n + LINE_LEN <= buf.len() {
|
||||
buf[n..n + LINE_LEN - 1].copy_from_slice(numbered(self.next).as_bytes());
|
||||
buf[n + LINE_LEN - 1] = b'\n';
|
||||
self.next += 1;
|
||||
n += LINE_LEN;
|
||||
}
|
||||
self.taken.fetch_add(n, Ordering::SeqCst);
|
||||
Ok(n)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for NumberedLines {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.gone.send(());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_slow_consumer_holds_the_pump_back_instead_of_queueing_every_line() {
|
||||
const LINES: usize = 50_000;
|
||||
let taken = Arc::new(AtomicUsize::new(0));
|
||||
let (gone, _) = mpsc::channel();
|
||||
let pipe = NumberedLines { next: 0, lines: LINES, taken: taken.clone(), gone };
|
||||
let (tx, rx) = line_queue();
|
||||
let pump = std::thread::spawn(move || pump_bounded(Box::new(pipe), Stream::Stdout, &tx));
|
||||
let (mut count, mut peak) = (0usize, 0usize);
|
||||
loop {
|
||||
match rx.recv_timeout(Duration::from_secs(60)) {
|
||||
Ok((stream, line)) => {
|
||||
assert_eq!(stream, Stream::Stdout);
|
||||
assert_eq!(line, numbered(count), "a line arrived out of order or damaged");
|
||||
// Read from the pipe but not yet handed over: the rest of the chunk the pump
|
||||
// is cutting into lines, and the queue.
|
||||
peak = peak.max(taken.load(Ordering::SeqCst) - count * LINE_LEN);
|
||||
count += 1;
|
||||
// A consumer that cannot keep up with the process.
|
||||
if count.is_multiple_of(LINE_QUEUE) {
|
||||
std::thread::sleep(Duration::from_millis(1));
|
||||
}
|
||||
}
|
||||
Err(mpsc::RecvTimeoutError::Disconnected) => break,
|
||||
Err(mpsc::RecvTimeoutError::Timeout) => panic!("the pump stalled"),
|
||||
}
|
||||
}
|
||||
pump.join().unwrap();
|
||||
assert_eq!(count, LINES);
|
||||
let bound = PUMP_CHUNK + (LINE_QUEUE + 2) * LINE_LEN;
|
||||
assert!(peak <= bound, "{peak} bytes read ahead of the consumer, more than {bound}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pump_blocked_on_a_full_queue_ends_when_the_consumer_is_gone() {
|
||||
let taken = Arc::new(AtomicUsize::new(0));
|
||||
let (gone_tx, gone) = mpsc::channel();
|
||||
// Far more than the queue and a few chunks hold.
|
||||
let pipe = NumberedLines { next: 0, lines: 100_000, taken: taken.clone(), gone: gone_tx };
|
||||
let (tx, rx) = line_queue();
|
||||
let pump = std::thread::spawn(move || pump_bounded(Box::new(pipe), Stream::Stdout, &tx));
|
||||
// A consumer that takes nothing: the queue fills, with the pump inside its first chunk.
|
||||
let deadline = Instant::now() + Duration::from_secs(30);
|
||||
while taken.load(Ordering::SeqCst) == 0 {
|
||||
assert!(Instant::now() < deadline, "the pump never read");
|
||||
std::thread::sleep(Duration::from_millis(1));
|
||||
}
|
||||
// Time for a pump that does not wait to run ahead.
|
||||
std::thread::sleep(Duration::from_millis(100));
|
||||
assert!(taken.load(Ordering::SeqCst) <= PUMP_CHUNK, "the pump read past a full queue");
|
||||
assert!(gone.try_recv().is_err(), "the pump ended while its consumer was still there");
|
||||
drop(rx);
|
||||
gone.recv_timeout(Duration::from_secs(30)).expect("the pump stayed blocked after the consumer was gone");
|
||||
pump.join().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_slow_on_line_still_sees_every_line_in_order_and_the_exit_status() {
|
||||
if cfg!(windows) {
|
||||
return;
|
||||
}
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let args = ["-c".into(), "awk 'BEGIN{for(i=1;i<=300000;i++)print i}'; exit 4".into()];
|
||||
for bounded in [false, true] {
|
||||
let mut next = 1usize;
|
||||
let on_line = |stream: Stream, line: &str| {
|
||||
assert_eq!(stream, Stream::Stdout);
|
||||
assert_eq!(line, next.to_string());
|
||||
next += 1;
|
||||
if next.is_multiple_of(1000) {
|
||||
std::thread::sleep(Duration::from_millis(1));
|
||||
}
|
||||
};
|
||||
let cancel = CancellationToken::new();
|
||||
let out = if bounded {
|
||||
run_bounded("sh", &args, tmp.path(), &BTreeMap::new(), &cancel, on_line)
|
||||
} else {
|
||||
run("sh", &args, tmp.path(), &BTreeMap::new(), &cancel, on_line)
|
||||
}
|
||||
.unwrap();
|
||||
assert!(!out.success);
|
||||
assert_eq!(next, 300_001, "lines were lost");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
//! Timed evidence for the bounded build-output capture (issue #3936). Not an assertion:
|
||||
//! run it on both revisions of `process.rs` and compare the printed numbers.
|
||||
//!
|
||||
//! ```text
|
||||
//! cargo test -p ide-build --release --lib -- --ignored --nocapture numbers
|
||||
//! ```
|
||||
|
||||
use crate::process;
|
||||
use ide_core::CancellationToken;
|
||||
use std::collections::BTreeMap;
|
||||
use std::time::Instant;
|
||||
|
||||
/// 256 MiB of 17-byte lines from `yes`, drained by `process::run` with a counting callback.
|
||||
#[test]
|
||||
#[ignore = "prints elapsed time and retained bytes; see the module docs"]
|
||||
fn high_output_process_numbers() {
|
||||
if cfg!(windows) {
|
||||
return;
|
||||
}
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let args = ["-c".into(), "yes 0123456789abcdef | head -c 268435456".into()];
|
||||
let start = Instant::now();
|
||||
let mut lines = 0u64;
|
||||
let mut fed = 0usize;
|
||||
let out = process::run_bounded("sh", &args, tmp.path(), &BTreeMap::new(), &CancellationToken::new(), |_, line| {
|
||||
lines += 1;
|
||||
fed += line.len() + 1;
|
||||
})
|
||||
.unwrap();
|
||||
println!(
|
||||
"elapsed {:?} | success {} | retained {} bytes | fed {lines} lines / {fed} bytes",
|
||||
start.elapsed(),
|
||||
out.success,
|
||||
out.text.len()
|
||||
);
|
||||
}
|
||||
@@ -1,216 +0,0 @@
|
||||
//! A Maven module's Surefire configuration, for test runs OpenIDEA starts itself instead of
|
||||
//! Surefire (IDEA's `MavenJUnitPatcher`): what the forked test JVM would get from the POM.
|
||||
//!
|
||||
//! Read from the effective POM the last sync cached (Maven merged parents, profiles and
|
||||
//! `pluginManagement` there), else from the module's own `pom.xml` and its `<properties>`.
|
||||
|
||||
use crate::maven::{MavenModel, interpolate};
|
||||
use crate::xml::{self, Element};
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::path::Path;
|
||||
|
||||
const SUREFIRE: &str = "maven-surefire-plugin";
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct SurefireConfig {
|
||||
/// `<argLine>`, split into JVM options.
|
||||
pub arg_line: Vec<String>,
|
||||
/// `<systemPropertyVariables>` and the older `<systemProperties>`.
|
||||
pub system_properties: BTreeMap<String, String>,
|
||||
/// `<environmentVariables>`.
|
||||
pub environment: BTreeMap<String, String>,
|
||||
pub working_directory: Option<String>,
|
||||
/// `<additionalClasspathElements>`.
|
||||
pub additional_classpath: Vec<String>,
|
||||
/// `<classpathDependencyExcludes>`: `groupId:artifactId`.
|
||||
pub classpath_excludes: Vec<String>,
|
||||
}
|
||||
|
||||
/// The Surefire configuration of the Maven module at `module` (absolute), if it is one.
|
||||
pub fn surefire_config(root: &Path, cache_dir: &Path, model: &MavenModel, module: &Path) -> Option<SurefireConfig> {
|
||||
let same = |a: &Path, b: &Path| dunce::canonicalize(a).ok() == dunce::canonicalize(b).ok();
|
||||
let project = model.projects.iter().find(|p| same(&root.join(&p.dir), module))?;
|
||||
let pom = root.join(&project.pom);
|
||||
let modified = |p: &Path| std::fs::metadata(p).and_then(|m| m.modified()).ok();
|
||||
// A cache written before the POM last changed would apply an old configuration.
|
||||
let effective = std::fs::read_dir(cache_dir).ok()?.flatten().map(|e| e.path()).find_map(|path| {
|
||||
let name = path.file_name()?.to_str()?;
|
||||
if !(name.starts_with("effective-pom-") && name.ends_with(".xml")) || modified(&path) < modified(&pom) {
|
||||
return None;
|
||||
}
|
||||
let root = xml::parse(&xml::read_text(&path)?)?;
|
||||
let projects: Vec<Element> = if root.name == "projects" {
|
||||
root.children.into_iter().filter(|p| p.name == "project").collect()
|
||||
} else {
|
||||
vec![root]
|
||||
};
|
||||
projects.into_iter().find(|p| {
|
||||
let group = p.text_of("groupId").or_else(|| p.at("parent/groupId").map(|g| g.text.trim().to_owned()));
|
||||
group.as_deref() == Some(project.group_id.as_str())
|
||||
&& p.text_of("artifactId").as_deref() == Some(&project.artifact_id)
|
||||
})
|
||||
});
|
||||
let (element, own) = match effective {
|
||||
Some(e) => (e, false),
|
||||
// ponytail: without a sync, inherited configuration and parent properties are missing; Reload adds them.
|
||||
None => (xml::parse(&xml::read_text(&pom)?)?, true),
|
||||
};
|
||||
let mut props: HashMap<String, String> = element
|
||||
.child("properties")
|
||||
.map(|p| p.children.iter().map(|c| (c.name.clone(), c.text.trim().to_owned())).collect())
|
||||
.unwrap_or_default();
|
||||
let dir = module.to_string_lossy().into_owned();
|
||||
for (key, value) in [
|
||||
("basedir", dir.clone()),
|
||||
("project.basedir", dir.clone()),
|
||||
("project.build.directory", format!("{dir}/target")),
|
||||
("project.groupId", project.group_id.clone()),
|
||||
("project.artifactId", project.artifact_id.clone()),
|
||||
("project.version", project.version.clone()),
|
||||
] {
|
||||
props.entry(key.into()).or_insert(value);
|
||||
}
|
||||
Some(read(&element, &props, own))
|
||||
}
|
||||
|
||||
/// `<build><plugins>` Surefire's configuration, then its `default-test` execution's.
|
||||
fn read(project: &Element, props: &HashMap<String, String>, own: bool) -> SurefireConfig {
|
||||
let is_surefire = |p: &&Element| p.text_of("artifactId").as_deref() == Some(SUREFIRE);
|
||||
let mut plugins: Vec<&Element> = project.list("build/plugins", "plugin").into_iter().filter(is_surefire).collect();
|
||||
if own && plugins.is_empty() {
|
||||
plugins = project.list("build/pluginManagement/plugins", "plugin").into_iter().filter(is_surefire).collect();
|
||||
}
|
||||
let mut configurations: Vec<&Element> = Vec::new();
|
||||
for plugin in plugins {
|
||||
configurations.extend(plugin.child("configuration"));
|
||||
let default_test = plugin
|
||||
.list("executions", "execution")
|
||||
.into_iter()
|
||||
.find(|e| e.text_of("id").as_deref() == Some("default-test"));
|
||||
configurations.extend(default_test.and_then(|e| e.child("configuration")));
|
||||
}
|
||||
let value = |text: &str| resolve(text.trim(), props);
|
||||
let mut config = SurefireConfig::default();
|
||||
for c in configurations {
|
||||
if let Some(arg_line) = c.child("argLine") {
|
||||
config.arg_line = split_arg_line(&value(&arg_line.text));
|
||||
}
|
||||
for p in c.child("systemPropertyVariables").map_or(&[][..], |p| &p.children) {
|
||||
config.system_properties.insert(p.name.clone(), value(&p.text));
|
||||
}
|
||||
// `<systemProperties>`: `<property><name/><value/></property>` (deprecated, still honoured).
|
||||
for p in c.list("systemProperties", "property") {
|
||||
if let Some(name) = p.text_of("name") {
|
||||
config.system_properties.insert(name, value(&p.text_of("value").unwrap_or_default()));
|
||||
}
|
||||
}
|
||||
for e in c.child("environmentVariables").map_or(&[][..], |e| &e.children) {
|
||||
config.environment.insert(e.name.clone(), value(&e.text));
|
||||
}
|
||||
if let Some(dir) = c.text_of("workingDirectory").map(|d| value(&d)).filter(|d| !d.is_empty()) {
|
||||
config.working_directory = Some(dir);
|
||||
}
|
||||
let texts = |list: &str, item: &str| -> Vec<String> {
|
||||
c.list(list, item).into_iter().map(|e| value(&e.text)).filter(|t| !t.is_empty()).collect()
|
||||
};
|
||||
config.additional_classpath.extend(texts("additionalClasspathElements", "additionalClasspathElement"));
|
||||
config.classpath_excludes.extend(texts("classpathDependencyExcludes", "classpathDependencyExclude"));
|
||||
}
|
||||
config
|
||||
}
|
||||
|
||||
/// `${…}` from the POM's properties, then Surefire's late replacement `@{…}` (a property a plugin
|
||||
/// sets during the build, such as JaCoCo's `argLine`, is unknown here and left out, as in IDEA).
|
||||
fn resolve(text: &str, props: &HashMap<String, String>) -> String {
|
||||
let mut out = interpolate(text, props);
|
||||
for open in ["@{", "${"] {
|
||||
while let Some(start) = out.find(open) {
|
||||
let Some(len) = out[start..].find('}') else { break };
|
||||
let key = &out[start + 2..start + len];
|
||||
let replacement = if open == "@{" { props.get(key).cloned().unwrap_or_default() } else { String::new() };
|
||||
out.replace_range(start..=start + len, &replacement);
|
||||
}
|
||||
}
|
||||
out.trim().to_owned()
|
||||
}
|
||||
|
||||
/// Splits `argLine` as Surefire does (plexus `CommandLineUtils`): whitespace, `"…"` and `'…'`, no escapes.
|
||||
fn split_arg_line(line: &str) -> Vec<String> {
|
||||
let mut out = Vec::new();
|
||||
let mut current: Option<String> = None;
|
||||
let mut quote: Option<char> = None;
|
||||
for c in line.chars() {
|
||||
match quote {
|
||||
Some(q) if c == q => quote = None,
|
||||
Some(_) => current.get_or_insert_default().push(c),
|
||||
None if c == '"' || c == '\'' => {
|
||||
quote = Some(c);
|
||||
current.get_or_insert_default();
|
||||
}
|
||||
None if c.is_whitespace() => out.extend(current.take()),
|
||||
None => current.get_or_insert_default().push(c),
|
||||
}
|
||||
}
|
||||
out.extend(current);
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const POM: &str = r#"<project>
|
||||
<groupId>com.example</groupId><artifactId>orders</artifactId><version>1</version>
|
||||
<properties><openideaFail>true</openideaFail><mockito>/m2/mockito.jar</mockito></properties>
|
||||
<build><plugins><plugin>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<configuration>
|
||||
<argLine>@{argLine} @{jacoco} -javaagent:${mockito} --add-opens "java.base/java.lang=ALL-UNNAMED" -Dx=${undefined}</argLine>
|
||||
<systemPropertyVariables><openidea.fail>${openideaFail}</openidea.fail><dir>${project.build.directory}</dir></systemPropertyVariables>
|
||||
<systemProperties><property><name>old</name><value>style</value></property></systemProperties>
|
||||
<environmentVariables><TZ>UTC</TZ></environmentVariables>
|
||||
<additionalClasspathElements><additionalClasspathElement>${basedir}/extra</additionalClasspathElement></additionalClasspathElements>
|
||||
<classpathDependencyExcludes><classpathDependencyExclude>org.slf4j:slf4j-simple</classpathDependencyExclude></classpathDependencyExcludes>
|
||||
</configuration>
|
||||
<executions><execution><id>default-test</id><configuration><workingDirectory>${basedir}/work</workingDirectory></configuration></execution></executions>
|
||||
</plugin></plugins></build>
|
||||
</project>"#;
|
||||
|
||||
fn model(dir: &Path) -> MavenModel {
|
||||
crate::maven::load(dir)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_the_module_pom_and_the_effective_pom_the_sync_cached() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
std::fs::write(root.join("pom.xml"), POM).unwrap();
|
||||
let cache = root.join("cache");
|
||||
std::fs::create_dir_all(&cache).unwrap();
|
||||
let config = surefire_config(root, &cache, &model(root), root).unwrap();
|
||||
let d = root.to_string_lossy();
|
||||
assert_eq!(
|
||||
config.arg_line,
|
||||
["-javaagent:/m2/mockito.jar", "--add-opens", "java.base/java.lang=ALL-UNNAMED", "-Dx="]
|
||||
);
|
||||
assert_eq!(config.system_properties["openidea.fail"], "true");
|
||||
assert_eq!(config.system_properties["dir"], format!("{d}/target"));
|
||||
assert_eq!(config.system_properties["old"], "style");
|
||||
assert_eq!(config.environment["TZ"], "UTC");
|
||||
assert_eq!(config.working_directory, Some(format!("{d}/work")));
|
||||
assert_eq!(config.additional_classpath, [format!("{d}/extra")]);
|
||||
assert_eq!(config.classpath_excludes, ["org.slf4j:slf4j-simple"]);
|
||||
|
||||
// A sync's effective POM wins: it has what the module inherits.
|
||||
let effective = POM.replace("<argLine>", "<argLine>-Xmx1g ").replace("<TZ>UTC</TZ>", "<TZ>Asia/Tokyo</TZ>");
|
||||
std::fs::write(cache.join("effective-pom-0.xml"), format!("<projects>{effective}</projects>")).unwrap();
|
||||
let config = surefire_config(root, &cache, &model(root), root).unwrap();
|
||||
assert_eq!(config.arg_line[0], "-Xmx1g");
|
||||
assert_eq!(config.environment["TZ"], "Asia/Tokyo");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn splits_arg_line_like_surefire() {
|
||||
assert_eq!(split_arg_line(r#" -a "b c" 'd "e"' C:\x\y "" "#), ["-a", "b c", r#"d "e""#, r"C:\x\y", ""]);
|
||||
}
|
||||
}
|
||||
+53
-163
@@ -86,29 +86,15 @@ const MAVEN_CACHE_VERSION: u32 = 1;
|
||||
|
||||
/// `dependency:tree` of a plugin version whose `-Dverbose` lists the occurrences Maven
|
||||
/// omitted (conflicts, duplicates): verbose output was dropped in 3.0 and is back since 3.2.
|
||||
/// Offline, it is used only when an earlier sync downloaded it; otherwise the newest version
|
||||
/// in the local repository is.
|
||||
/// Offline, the project's own plugin version is used instead, since this one may not be cached.
|
||||
const DEPENDENCY_TREE: &str = "org.apache.maven.plugins:maven-dependency-plugin:3.8.1:tree";
|
||||
const DEPENDENCY_TREE_JAR: &str =
|
||||
"org/apache/maven/plugins/maven-dependency-plugin/3.8.1/maven-dependency-plugin-3.8.1.jar";
|
||||
|
||||
/// The goals that read the effective POM into `effective` and the verbose dependency trees;
|
||||
/// `repo` is the local repository the build resolves from. Both goals name their plugin by
|
||||
/// coordinates: offline, a prefix resolves only from group metadata the repository may lack.
|
||||
fn maven_sync_goals(effective: &Path, offline: bool, repo: Option<&Path>) -> Vec<String> {
|
||||
let pinned = !offline || repo.is_some_and(|repo| repo.join(DEPENDENCY_TREE_JAR).is_file());
|
||||
let tree = if pinned {
|
||||
DEPENDENCY_TREE.to_owned()
|
||||
} else {
|
||||
repo.and_then(|repo| maven::newest_local_plugin(repo, "maven-dependency-plugin", 2)).map_or_else(
|
||||
|| "dependency:tree".to_owned(),
|
||||
|v| format!("org.apache.maven.plugins:maven-dependency-plugin:{v}:tree"),
|
||||
)
|
||||
};
|
||||
/// The goals that read the effective POM into `effective` and the verbose dependency trees.
|
||||
fn maven_sync_goals(effective: &Path, offline: bool) -> Vec<String> {
|
||||
vec![
|
||||
maven::plugin_goal("help:effective-pom", repo),
|
||||
"help:effective-pom".into(),
|
||||
format!("-Doutput={}", effective.to_string_lossy()),
|
||||
tree,
|
||||
if offline { "dependency:tree".into() } else { DEPENDENCY_TREE.into() },
|
||||
"-Dverbose".into(),
|
||||
]
|
||||
}
|
||||
@@ -132,7 +118,6 @@ fn sync_maven_options(options: &[String]) -> Vec<String> {
|
||||
}
|
||||
const GRADLE_CACHE: &str = "gradle.json";
|
||||
const MAVEN_PROFILES: &str = "maven-profiles.json";
|
||||
const MAVEN_OFFLINE: &str = "maven-offline.json";
|
||||
|
||||
/// The Maven profiles (`-P` entries, `!id` deactivates) the project was last synced
|
||||
/// with: what the IDE resolves it with besides `mvn` (the Java language server, Build Project).
|
||||
@@ -142,39 +127,20 @@ pub fn maven_profiles(cache_dir: &Path) -> Vec<String> {
|
||||
|
||||
/// Records the profiles of a sync for [`maven_profiles`]; `true` when they changed.
|
||||
pub fn save_maven_profiles(cache_dir: &Path, profiles: &[String]) -> IdeResult<bool> {
|
||||
save_if_changed(cache_dir, MAVEN_PROFILES, &profiles.to_vec())
|
||||
}
|
||||
|
||||
/// Whether the project was last synced offline (`-o`): the Java language server then
|
||||
/// resolves it offline too.
|
||||
pub fn maven_offline(cache_dir: &Path) -> bool {
|
||||
read_cache(cache_dir, MAVEN_OFFLINE).unwrap_or(false)
|
||||
}
|
||||
|
||||
/// Records the offline mode of a sync for [`maven_offline`]; `true` when it changed.
|
||||
pub fn save_maven_offline(cache_dir: &Path, offline: bool) -> IdeResult<bool> {
|
||||
save_if_changed(cache_dir, MAVEN_OFFLINE, &offline)
|
||||
}
|
||||
|
||||
fn save_if_changed<T: Serialize + DeserializeOwned + PartialEq + Default>(
|
||||
dir: &Path,
|
||||
name: &str,
|
||||
value: &T,
|
||||
) -> IdeResult<bool> {
|
||||
if read_cache::<T>(dir, name).unwrap_or_default() == *value {
|
||||
if maven_profiles(cache_dir) == profiles {
|
||||
return Ok(false);
|
||||
}
|
||||
std::fs::create_dir_all(dir)?;
|
||||
let json = serde_json::to_vec(value).map_err(|e| IdeError::internal(e.to_string()))?;
|
||||
std::fs::write(dir.join(name), json)?;
|
||||
std::fs::create_dir_all(cache_dir)?;
|
||||
let json = serde_json::to_vec(profiles).map_err(|e| IdeError::internal(e.to_string()))?;
|
||||
std::fs::write(cache_dir.join(MAVEN_PROFILES), json)?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
pub(crate) fn read_cache<T: DeserializeOwned>(dir: &Path, name: &str) -> Option<T> {
|
||||
fn read_cache<T: DeserializeOwned>(dir: &Path, name: &str) -> Option<T> {
|
||||
serde_json::from_slice(&std::fs::read(dir.join(name)).ok()?).ok()
|
||||
}
|
||||
|
||||
pub(crate) fn write_cache<T: Serialize>(dir: &Path, name: &str, value: &T) -> IdeResult<()> {
|
||||
fn write_cache<T: Serialize>(dir: &Path, name: &str, value: &T) -> IdeResult<()> {
|
||||
std::fs::create_dir_all(dir)?;
|
||||
let json = serde_json::to_vec(value).map_err(|e| IdeError::internal(e.to_string()))?;
|
||||
let tmp = dir.join(format!("{name}.tmp"));
|
||||
@@ -190,7 +156,7 @@ fn hash_files(files: &[PathBuf]) -> String {
|
||||
|
||||
/// Like IDEA's auto-import CRC: editing a comment or reformatting a build script
|
||||
/// does not make the last sync stale.
|
||||
pub(crate) fn hash_gradle_files(files: &[PathBuf]) -> String {
|
||||
fn hash_gradle_files(files: &[PathBuf]) -> String {
|
||||
hash_contents(files, |f| {
|
||||
let text = std::fs::read_to_string(f).unwrap_or_default();
|
||||
let script = f.extension().is_some_and(|e| e == "gradle" || e == "kts");
|
||||
@@ -302,20 +268,8 @@ fn run(
|
||||
process::run(program, args, cwd, env, cancel, |_, line| on_line(line))
|
||||
}
|
||||
|
||||
/// What a sync records when a *successful* child run's output was truncated: parsing a
|
||||
/// truncated listing would silently produce an incomplete model, so it is surfaced, not hidden.
|
||||
pub(crate) fn truncation_note(out: &Output) -> Option<String> {
|
||||
out.truncated.then(|| {
|
||||
format!(
|
||||
"the build printed more than the retained {} MiB of output; the model may be incomplete",
|
||||
crate::process::MAX_TEXT_BYTES / (1024 * 1024)
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
/// The first error lines of a failed build, for the tool window.
|
||||
pub(crate) fn error_summary(output: &Output) -> String {
|
||||
let text = &output.text;
|
||||
pub(crate) fn error_summary(text: &str) -> String {
|
||||
// The JVM's "could not find or load main class" (localized) when `gradlew` has no jar.
|
||||
if text.contains("org.gradle.wrapper.GradleWrapperMain") {
|
||||
return "gradle/wrapper/gradle-wrapper.jar is missing (often excluded by a `*.jar` rule in .gitignore). \
|
||||
@@ -335,15 +289,11 @@ pub(crate) fn error_summary(output: &Output) -> String {
|
||||
.filter(|l| !l.is_empty() && !l.starts_with("Re-run Maven") && !l.starts_with("To see the full stack trace"))
|
||||
.take(4)
|
||||
.collect();
|
||||
let mut summary = if lines.is_empty() {
|
||||
if lines.is_empty() {
|
||||
text.lines().rev().find(|l| !l.trim().is_empty()).unwrap_or("the build failed").trim().to_owned()
|
||||
} else {
|
||||
lines.join("\n")
|
||||
};
|
||||
if output.truncated {
|
||||
summary.push_str("\n[the build printed more than the retained output; this summary may miss lines]");
|
||||
}
|
||||
summary
|
||||
}
|
||||
|
||||
/// `[INFO] Building core 1.0-SNAPSHOT [2/3]` → ("core 1.0-SNAPSHOT", 2, 3).
|
||||
@@ -376,8 +326,25 @@ pub fn sync_maven(
|
||||
verbose: true,
|
||||
..MavenCache::default()
|
||||
};
|
||||
// Where the build resolves its jars, and therefore where the plugin goals are read from.
|
||||
let repo = maven::local_repository_for(&options.maven_options);
|
||||
// Where the build resolves its jars, and therefore where the plugin goals are read
|
||||
// from: `-Dmaven.repo.local=` first, then `<localRepository>` of the `-s` settings,
|
||||
// then the user's default repository (which `plugin()` resolves itself).
|
||||
let local_repo: Option<PathBuf> =
|
||||
options.maven_options.iter().find_map(|a| a.strip_prefix("-Dmaven.repo.local=")).map(PathBuf::from).or_else(
|
||||
|| {
|
||||
let mut args = options.maven_options.iter();
|
||||
while let Some(arg) = args.next() {
|
||||
let path = match arg.as_str() {
|
||||
"-s" | "--settings" => args.next().map(String::as_str),
|
||||
_ => arg.strip_prefix("-s=").or_else(|| arg.strip_prefix("--settings=")),
|
||||
};
|
||||
if let Some(path) = path {
|
||||
return maven::local_repository_of(Path::new(path));
|
||||
}
|
||||
}
|
||||
None
|
||||
},
|
||||
);
|
||||
let mut errors: Vec<String> = Vec::new();
|
||||
for (n, top) in model.projects.iter().filter(|p| !p.aggregated).enumerate() {
|
||||
let effective = cache_dir.join(format!("effective-pom-{n}.xml"));
|
||||
@@ -399,7 +366,7 @@ pub fn sync_maven(
|
||||
if !options.profiles.is_empty() {
|
||||
args.push(format!("-P{}", options.profiles.join(",")));
|
||||
}
|
||||
args.extend(maven_sync_goals(&effective, options.offline, repo.as_deref()));
|
||||
args.extend(maven_sync_goals(&effective, options.offline));
|
||||
progress(SyncProgress { message: format!("Reading {}", top.display_name), fraction: None });
|
||||
let command = options.maven_command.as_deref().unwrap_or(&top.command);
|
||||
let out = run(command, &args, &root.join(&top.dir), &options.env, cancel, |line| {
|
||||
@@ -416,7 +383,7 @@ pub fn sync_maven(
|
||||
}
|
||||
})?;
|
||||
let effective_projects = std::fs::read_to_string(&effective)
|
||||
.map(|t| maven::parse_effective_pom_in(&t, repo.as_deref()))
|
||||
.map(|t| maven::parse_effective_pom_in(&t, local_repo.as_deref()))
|
||||
.unwrap_or_default();
|
||||
let trees = maven::parse_dependency_tree(&out.text);
|
||||
for (key, plugins, deps) in effective_projects {
|
||||
@@ -430,9 +397,7 @@ pub fn sync_maven(
|
||||
}
|
||||
}
|
||||
if !out.success {
|
||||
errors.push(error_summary(&out));
|
||||
} else if let Some(note) = truncation_note(&out) {
|
||||
errors.push(note);
|
||||
errors.push(error_summary(&out.text));
|
||||
}
|
||||
}
|
||||
cache.at_ms = now_ms();
|
||||
@@ -472,8 +437,6 @@ pub fn sync_gradle_model(
|
||||
let mut args: Vec<String> = vec![
|
||||
"--console=plain".into(),
|
||||
"-q".into(),
|
||||
// The init script reports the evaluated projects, even when a build enables the configuration cache.
|
||||
"-Dorg.gradle.configuration-cache=false".into(),
|
||||
"--init-script".into(),
|
||||
init_script.to_string_lossy().into_owned(),
|
||||
"tasks".into(),
|
||||
@@ -494,7 +457,7 @@ pub fn sync_gradle_model(
|
||||
Ok(out) => out,
|
||||
Err(_) if cancel.is_cancelled() => return Err(IdeError::cancelled()),
|
||||
Err(error) if error.kind == ide_core::error::ErrorKind::Unavailable => {
|
||||
Output { success: false, text: error.message, truncated: false }
|
||||
Output { success: false, text: error.message }
|
||||
}
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
@@ -507,7 +470,7 @@ pub fn sync_gradle_model(
|
||||
let cache = GradleCache {
|
||||
hash: hash_gradle_files(&gradle::build_files(root, &model)),
|
||||
at_ms: now_ms(),
|
||||
error: if !out.success { Some(error_summary(&out)) } else { truncation_note(&out) },
|
||||
error: (!out.success).then(|| error_summary(&out.text)),
|
||||
tasks: if out.success { gradle::parse_tasks(&out.text) } else { Vec::new() },
|
||||
projects,
|
||||
resources: true,
|
||||
@@ -549,18 +512,14 @@ mod tests {
|
||||
assert!(loaded.gradle[0].sync_error.as_deref().unwrap().contains("cannot start"));
|
||||
assert!(loaded.gradle[1].sync_error.is_none());
|
||||
assert_eq!(loaded.gradle[1].projects[0].tasks[0].name, "healthy");
|
||||
// A wrapper without the execute bit (committed from Windows, unpacked from a zip)
|
||||
// runs through `sh`, and its mode is left alone.
|
||||
let plain_wrapper = root.join("a/gradlew");
|
||||
std::fs::write(&plain_wrapper, "#!/bin/sh\nprintf '%s\\n' 'Build tasks' '-----------' 'plain - ok'\n").unwrap();
|
||||
std::fs::set_permissions(&plain_wrapper, std::fs::Permissions::from_mode(0o644)).unwrap();
|
||||
models[0].command = plain_wrapper.to_string_lossy().into_owned();
|
||||
let bad_wrapper = root.join("a/gradlew");
|
||||
std::fs::write(&bad_wrapper, "#!/bin/sh\nexit 0\n").unwrap();
|
||||
std::fs::set_permissions(&bad_wrapper, std::fs::Permissions::from_mode(0o644)).unwrap();
|
||||
models[0].command = bad_wrapper.to_string_lossy().into_owned();
|
||||
run(&models[0]).unwrap();
|
||||
let loaded = crate::load_linked(root, &cache, None, &Default::default(), &settings);
|
||||
assert!(loaded.gradle[0].sync_error.is_none());
|
||||
assert_eq!(loaded.gradle[0].projects[0].tasks[0].name, "plain");
|
||||
assert!(loaded.gradle[0].sync_error.as_deref().unwrap().contains("cannot start"));
|
||||
assert!(loaded.gradle[1].sync_error.is_none());
|
||||
assert_eq!(std::fs::metadata(&plain_wrapper).unwrap().permissions().mode() & 0o777, 0o644);
|
||||
let blocked_cache = root.join("blocked-cache");
|
||||
std::fs::write(&blocked_cache, "a file cannot contain sync caches").unwrap();
|
||||
assert!(
|
||||
@@ -929,47 +888,12 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_offline_mode_of_the_last_sync_is_kept_for_the_language_server() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let cache = tmp.path().join("cache");
|
||||
assert!(!maven_offline(&cache), "never synced: online");
|
||||
assert!(save_maven_offline(&cache, true).unwrap());
|
||||
assert!(maven_offline(&cache));
|
||||
assert!(!save_maven_offline(&cache, true).unwrap(), "unchanged");
|
||||
assert!(save_maven_offline(&cache, false).unwrap());
|
||||
assert!(!maven_offline(&cache));
|
||||
assert!(!save_maven_offline(&tmp.path().join("other"), false).unwrap(), "online is the default");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sync_reads_verbose_trees_with_a_pinned_plugin_unless_offline_without_it() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let help = "org.apache.maven.plugins:maven-help-plugin:3.5.1:effective-pom";
|
||||
let online = maven_sync_goals(Path::new("e.xml"), false, Some(tmp.path()));
|
||||
assert_eq!(online, [help, "-Doutput=e.xml", DEPENDENCY_TREE, "-Dverbose"]);
|
||||
// Offline with neither plugin cached: the tree falls back to the project's own version.
|
||||
let offline = maven_sync_goals(Path::new("e.xml"), true, Some(tmp.path()));
|
||||
assert_eq!(offline, [help, "-Doutput=e.xml", "dependency:tree", "-Dverbose"]);
|
||||
// #5757: offline, plugins in the local repository are named by their coordinates, since
|
||||
// the prefix needs group metadata a repository filled from a private mirror may lack.
|
||||
for (artifact, version) in
|
||||
[("maven-help-plugin", "3.4.0"), ("maven-help-plugin", "2.2"), ("maven-dependency-plugin", "3.6.1")]
|
||||
{
|
||||
let jar =
|
||||
tmp.path().join(format!("org/apache/maven/plugins/{artifact}/{version}/{artifact}-{version}.jar"));
|
||||
std::fs::create_dir_all(jar.parent().unwrap()).unwrap();
|
||||
std::fs::write(&jar, "").unwrap();
|
||||
}
|
||||
// A version folder without its jar (only the POM was fetched) doesn't count.
|
||||
std::fs::create_dir_all(tmp.path().join("org/apache/maven/plugins/maven-help-plugin/3.10.0")).unwrap();
|
||||
let offline = maven_sync_goals(Path::new("e.xml"), true, Some(tmp.path()));
|
||||
assert_eq!(offline[0], "org.apache.maven.plugins:maven-help-plugin:3.4.0:effective-pom");
|
||||
assert_eq!(offline[2], "org.apache.maven.plugins:maven-dependency-plugin:3.6.1:tree");
|
||||
// Downloaded by an online sync: offline keeps using it, the project's version may be missing.
|
||||
let jar = tmp.path().join(DEPENDENCY_TREE_JAR);
|
||||
std::fs::create_dir_all(jar.parent().unwrap()).unwrap();
|
||||
std::fs::write(&jar, "").unwrap();
|
||||
assert_eq!(maven_sync_goals(Path::new("e.xml"), true, Some(tmp.path()))[2], DEPENDENCY_TREE);
|
||||
fn sync_reads_verbose_trees_with_a_pinned_plugin_unless_offline() {
|
||||
let online = maven_sync_goals(Path::new("e.xml"), false);
|
||||
assert_eq!(online, ["help:effective-pom", "-Doutput=e.xml", DEPENDENCY_TREE, "-Dverbose"]);
|
||||
let offline = maven_sync_goals(Path::new("e.xml"), true);
|
||||
assert_eq!(offline[2], "dependency:tree");
|
||||
assert!(offline.contains(&"-Dverbose".to_owned()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -990,22 +914,10 @@ mod tests {
|
||||
);
|
||||
assert_eq!(maven_building("[INFO] Building jar: x.jar"), None);
|
||||
let text = "[INFO] x\n[ERROR] Failed to execute goal\n[ERROR] \n[ERROR] Re-run Maven using -X\n";
|
||||
let out = |text: &str, truncated| crate::process::Output { success: false, text: text.to_owned(), truncated };
|
||||
assert_eq!(error_summary(&out(text, false)), "Failed to execute goal");
|
||||
assert_eq!(error_summary(&out("one\nlast line\n\n", false)), "last line");
|
||||
assert_eq!(error_summary(text), "Failed to execute goal");
|
||||
assert_eq!(error_summary("one\nlast line\n\n"), "last line");
|
||||
let missing_jar = "错误: 找不到或无法加载主类 org.gradle.wrapper.GradleWrapperMain\n";
|
||||
assert!(error_summary(&out(missing_jar, false)).starts_with("gradle/wrapper/gradle-wrapper.jar is missing"));
|
||||
// A truncated capture says so instead of hiding that lines are missing.
|
||||
assert!(error_summary(&out(text, true)).ends_with("this summary may miss lines]"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_truncated_successful_run_is_surfaced_not_silent() {
|
||||
let out = |truncated| crate::process::Output { success: true, text: String::new(), truncated };
|
||||
assert!(truncation_note(&out(false)).is_none());
|
||||
let note = truncation_note(&out(true)).unwrap();
|
||||
assert!(note.starts_with("the build printed more than the retained 32 MiB"), "{note}");
|
||||
assert!(note.ends_with("the model may be incomplete"));
|
||||
assert!(error_summary(missing_jar).starts_with("gradle/wrapper/gradle-wrapper.jar is missing"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1021,28 +933,6 @@ mod tests {
|
||||
assert!(sync_maven_options(&[]).is_empty());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn maven_sync_runs_a_wrapper_without_the_execute_bit() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path().join("p");
|
||||
std::fs::create_dir_all(&root).unwrap();
|
||||
std::fs::write(root.join("pom.xml"), "<project><groupId>g</groupId><artifactId>a</artifactId></project>")
|
||||
.unwrap();
|
||||
let mvnw = root.join("mvnw");
|
||||
std::fs::write(&mvnw, "#!/bin/sh\nprintf '%s\\n' \"$@\" > mvnw-args\n").unwrap();
|
||||
std::fs::set_permissions(&mvnw, std::fs::Permissions::from_mode(0o644)).unwrap();
|
||||
let cache = tmp.path().join("cache");
|
||||
sync_maven(&root, &cache, &SyncOptions::default(), &CancellationToken::new(), &|_| {}).unwrap();
|
||||
let args = std::fs::read_to_string(root.join("mvnw-args")).unwrap();
|
||||
assert!(args.contains("maven-help-plugin:"), "args: {args}");
|
||||
let loaded = crate::load_linked(&root, &cache, None, &Default::default(), &Default::default());
|
||||
let maven = loaded.maven.unwrap();
|
||||
assert!(maven.synced_at.is_some() && maven.sync_error.is_none(), "{:?}", maven.sync_error);
|
||||
assert_eq!(std::fs::metadata(&mvnw).unwrap().permissions().mode() & 0o777, 0o644);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn maven_sync_runs_the_daemon_command_serially() {
|
||||
@@ -1061,6 +951,6 @@ mod tests {
|
||||
let args = std::fs::read_to_string(root.join("mvnd-args")).unwrap();
|
||||
// `-T1` pins the daemon serial so the dependency trees stay parseable.
|
||||
assert!(args.contains("-T1"), "args: {args}");
|
||||
assert!(args.contains("maven-help-plugin:"), "args: {args}");
|
||||
assert!(args.contains("help:effective-pom"), "args: {args}");
|
||||
}
|
||||
}
|
||||
+14
-30
@@ -137,16 +137,19 @@ pub fn build(root: &Path, model: &BuildModel, id: &str, cache: &Path) -> IdeResu
|
||||
// POM's effective identity first; profiles and -D options can change its GAV.
|
||||
let output = cache.join("artifact-project.txt");
|
||||
let mut probe = top.options.clone();
|
||||
let evaluate =
|
||||
crate::maven::plugin_goal("help:evaluate", crate::maven::local_repository_for(&top.options).as_deref());
|
||||
probe.extend([
|
||||
"-f".into(),
|
||||
root.join(&p.pom).to_string_lossy().into_owned(),
|
||||
evaluate.clone(),
|
||||
"help:evaluate".into(),
|
||||
"-Dexpression=project.id".into(),
|
||||
format!("-Doutput={}", output.display()),
|
||||
]);
|
||||
args.extend(["-DskipTests".into(), "package".into(), evaluate, format!("-Doutput={}", manifest.display())]);
|
||||
args.extend([
|
||||
"-DskipTests".into(),
|
||||
"package".into(),
|
||||
"help:evaluate".into(),
|
||||
format!("-Doutput={}", manifest.display()),
|
||||
]);
|
||||
return Ok(WebBuild {
|
||||
command: top.command.clone(),
|
||||
args,
|
||||
@@ -169,25 +172,13 @@ pub fn build(root: &Path, model: &BuildModel, id: &str, cache: &Path) -> IdeResu
|
||||
fs::write(
|
||||
&script,
|
||||
format!(
|
||||
r#"import org.gradle.util.GradleVersion
|
||||
|
||||
gradle.projectsEvaluated {{
|
||||
r#"gradle.projectsEvaluated {{
|
||||
def p = gradle.rootProject.project({})
|
||||
def artifact = {{ t ->
|
||||
t.dependsOn 'war'
|
||||
// Resolved here so the action holds no task or project (configuration cache).
|
||||
def war = p.tasks.getByName('war')
|
||||
// `archiveFile` is Gradle 5.1+, `archivePath` is gone in 8.0.
|
||||
def archive = war.hasProperty('archiveFile') ? war.archiveFile : war.archivePath
|
||||
def manifest = new File({})
|
||||
t.doLast {{
|
||||
def file = archive instanceof File ? archive : archive.get().asFile
|
||||
manifest.setText(file.absolutePath, 'UTF-8')
|
||||
}}
|
||||
def warTask = p.tasks.named('war')
|
||||
p.tasks.register('openideaTomcatArtifact') {{
|
||||
dependsOn warTask
|
||||
doLast {{ new File({}).setText(warTask.get().archiveFile.get().asFile.absolutePath, 'UTF-8') }}
|
||||
}}
|
||||
// `register` is Gradle 4.9+.
|
||||
if (GradleVersion.current() >= GradleVersion.version('4.9')) p.tasks.register('openideaTomcatArtifact', artifact)
|
||||
else p.tasks.create('openideaTomcatArtifact', artifact)
|
||||
}}
|
||||
"#,
|
||||
groovy_literal(path),
|
||||
@@ -279,7 +270,7 @@ mod tests {
|
||||
assert_eq!(a.len(), 1);
|
||||
let plan = build(tmp.path(), &model, &a[0].id, &tmp.path().join("base")).unwrap();
|
||||
assert!(plan.args.contains(&":openideaTomcatArtifact".into()));
|
||||
assert!(fs::read_to_string(tmp.path().join("base/war.init.gradle")).unwrap().contains("? war.archiveFile :"));
|
||||
assert!(fs::read_to_string(tmp.path().join("base/war.init.gradle")).unwrap().contains("archiveFile.get()"));
|
||||
assert!(!crate::gradle::has_war_plugin("// plugins { war }"));
|
||||
}
|
||||
|
||||
@@ -306,14 +297,7 @@ mod tests {
|
||||
assert!(plan.args.contains(&format!("{}:openideaTomcatArtifact", module.trim_end_matches(':'))));
|
||||
let script = fs::read_to_string(cache.join("war.init.gradle")).unwrap();
|
||||
assert!(script.contains(&format!("rootProject.project('{}')", module)));
|
||||
assert!(script.contains("manifest.setText(file.absolutePath, 'UTF-8')"));
|
||||
// `archiveFile` is Gradle 5.1+, `register` 4.9+ (#3864).
|
||||
assert!(
|
||||
script.contains(": war.archivePath") && script.contains("else p.tasks.create('openideaTomcatArtifact'")
|
||||
);
|
||||
// The configuration cache can't serialize a task or project the action refers to.
|
||||
let action = &script[script.find("doLast").unwrap()..script.find("// `register`").unwrap()];
|
||||
assert!(!action.contains("p.") && !action.contains("war."), "{action}");
|
||||
assert!(script.contains("archiveFile.get().asFile.absolutePath, 'UTF-8'"));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,85 +0,0 @@
|
||||
use std::io::{Cursor, Error, ErrorKind, Result};
|
||||
|
||||
/// A top-down BITMAPV5HEADER and BGRA pixels. The alpha mask lets native paste targets
|
||||
/// retain transparency; the PNG flavor is also written for browsers and image editors.
|
||||
pub(crate) fn png_to_dib(png: &[u8]) -> Result<Vec<u8>> {
|
||||
let invalid = |error| Error::new(ErrorKind::InvalidData, error);
|
||||
let mut decoder = png::Decoder::new(Cursor::new(png));
|
||||
decoder.set_transformations(png::Transformations::normalize_to_color8());
|
||||
let mut reader = decoder.read_info().map_err(invalid)?;
|
||||
let rgba_size = (reader.info().width as usize)
|
||||
.checked_mul(reader.info().height as usize)
|
||||
.and_then(|pixels| pixels.checked_mul(4))
|
||||
.filter(|size| *size <= 64 * 1024 * 1024)
|
||||
.ok_or_else(|| Error::new(ErrorKind::InvalidData, "Clipboard image is too large"))?;
|
||||
let size = reader
|
||||
.output_buffer_size()
|
||||
.filter(|size| *size <= 64 * 1024 * 1024)
|
||||
.ok_or_else(|| Error::new(ErrorKind::InvalidData, "Clipboard image is too large"))?;
|
||||
let mut pixels = vec![0; size];
|
||||
let info = reader.next_frame(&mut pixels).map_err(invalid)?;
|
||||
let mut dib = vec![0; 124];
|
||||
dib[0..4].copy_from_slice(&124u32.to_le_bytes());
|
||||
dib[4..8].copy_from_slice(&info.width.to_le_bytes());
|
||||
dib[8..12].copy_from_slice(&(-(info.height as i32)).to_le_bytes());
|
||||
dib[12..14].copy_from_slice(&1u16.to_le_bytes());
|
||||
dib[14..16].copy_from_slice(&32u16.to_le_bytes());
|
||||
dib[16..20].copy_from_slice(&3u32.to_le_bytes()); // BI_BITFIELDS
|
||||
dib[20..24].copy_from_slice(&(rgba_size as u32).to_le_bytes());
|
||||
for (at, value) in [(40, 0x00ff0000u32), (44, 0x0000ff00), (48, 0x000000ff), (52, 0xff000000), (56, 0x73524742)] {
|
||||
dib[at..at + 4].copy_from_slice(&value.to_le_bytes());
|
||||
}
|
||||
dib[108..112].copy_from_slice(&4u32.to_le_bytes()); // LCS_GM_IMAGES
|
||||
for pixel in pixels[..info.buffer_size()].chunks_exact(info.color_type.samples()) {
|
||||
let rgba = match info.color_type {
|
||||
png::ColorType::Rgba => [pixel[0], pixel[1], pixel[2], pixel[3]],
|
||||
png::ColorType::Rgb => [pixel[0], pixel[1], pixel[2], 255],
|
||||
png::ColorType::Grayscale => [pixel[0], pixel[0], pixel[0], 255],
|
||||
png::ColorType::GrayscaleAlpha => [pixel[0], pixel[0], pixel[0], pixel[1]],
|
||||
png::ColorType::Indexed => unreachable!("palette expansion requested"),
|
||||
};
|
||||
dib.extend_from_slice(&[rgba[2], rgba[1], rgba[0], rgba[3]]);
|
||||
}
|
||||
Ok(dib)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn encode(color: png::ColorType, pixels: &[u8]) -> Vec<u8> {
|
||||
let mut png = Vec::new();
|
||||
{
|
||||
let mut encoder = png::Encoder::new(&mut png, 1, 2);
|
||||
encoder.set_color(color);
|
||||
encoder.set_depth(png::BitDepth::Eight);
|
||||
encoder.write_header().unwrap().write_image_data(pixels).unwrap();
|
||||
}
|
||||
png
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_rgba_colors_alpha_and_top_down_row_order() {
|
||||
let png = encode(png::ColorType::Rgba, &[255, 0, 0, 128, 0, 255, 0, 255]);
|
||||
let dib = png_to_dib(&png).unwrap();
|
||||
assert_eq!(i32::from_le_bytes(dib[8..12].try_into().unwrap()), -2);
|
||||
assert_eq!(&dib[124..], &[0, 0, 255, 128, 0, 255, 0, 255]);
|
||||
let round_trip = crate::dib_to_png(&dib).unwrap();
|
||||
let mut reader = png::Decoder::new(Cursor::new(round_trip)).read_info().unwrap();
|
||||
let mut pixels = vec![0; reader.output_buffer_size().unwrap()];
|
||||
reader.next_frame(&mut pixels).unwrap();
|
||||
assert_eq!(pixels, [255, 0, 0, 128, 0, 255, 0, 255]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn supports_rgb_and_grayscale_without_assuming_an_alpha_channel() {
|
||||
for (color, pixels, expected) in [
|
||||
(png::ColorType::Rgb, vec![255, 0, 0, 0, 255, 0], vec![0, 0, 255, 255, 0, 255, 0, 255]),
|
||||
(png::ColorType::Grayscale, vec![20, 200], vec![20, 20, 20, 255, 200, 200, 200, 255]),
|
||||
(png::ColorType::GrayscaleAlpha, vec![20, 10, 200, 250], vec![20, 20, 20, 10, 200, 200, 200, 250]),
|
||||
] {
|
||||
assert_eq!(&png_to_dib(&encode(color, &pixels)).unwrap()[124..], expected);
|
||||
}
|
||||
assert!(png_to_dib(b"not a PNG").is_err());
|
||||
}
|
||||
}
|
||||
@@ -25,29 +25,6 @@
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[cfg(any(windows, test))]
|
||||
mod image;
|
||||
|
||||
/// Writes a PNG as a native image, independently of WebView clipboard permissions.
|
||||
/// Call on the main thread on macOS and Linux; `owner` is a window handle on Windows.
|
||||
pub fn set_png(png: &[u8], owner: usize) -> std::io::Result<()> {
|
||||
if png.get(..8) != Some(b"\x89PNG\r\n\x1a\n") || png.get(12..16) != Some(b"IHDR") || png.len() < 24 {
|
||||
return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "Invalid clipboard image"));
|
||||
}
|
||||
let width = u32::from_be_bytes(png[16..20].try_into().unwrap()) as usize;
|
||||
let height = u32::from_be_bytes(png[20..24].try_into().unwrap()) as usize;
|
||||
if width == 0
|
||||
|| height == 0
|
||||
|| !width
|
||||
.checked_mul(height)
|
||||
.and_then(|pixels| pixels.checked_mul(4))
|
||||
.is_some_and(|size| size <= 64 * 1024 * 1024)
|
||||
{
|
||||
return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "Clipboard image is too large"));
|
||||
}
|
||||
imp::set_png(png, owner)
|
||||
}
|
||||
|
||||
/// Replaces every clipboard flavor with plain text. `owner` is the calling window
|
||||
/// handle on Windows, ignored elsewhere. Call on the main thread on macOS and Linux.
|
||||
pub fn set_text(text: &str, owner: usize) -> std::io::Result<()> {
|
||||
@@ -263,7 +240,6 @@ mod imp {
|
||||
/// `CF_DIB`: Windows synthesizes it from `CF_BITMAP` and `CF_DIBV5`, so every
|
||||
/// bitmap on the clipboard reads as one.
|
||||
const CF_DIB: u32 = 8;
|
||||
const CF_DIBV5: u32 = 17;
|
||||
|
||||
/// The `PNG` format browsers and the Snipping Tool add beside the bitmap; it
|
||||
/// keeps transparency, so it is read first.
|
||||
@@ -372,35 +348,6 @@ mod imp {
|
||||
paths
|
||||
}
|
||||
|
||||
/// `Preferred DropEffect`: a `DWORD` saying whether the files were copied or cut.
|
||||
/// Explorer writes it with every file list, and paste targets that move files
|
||||
/// between machines (Remote Desktop's clipboard redirection, #3863) read it.
|
||||
fn drop_effect_format() -> u32 {
|
||||
let name: Vec<u16> = "Preferred DropEffect\0".encode_utf16().collect();
|
||||
unsafe { RegisterClipboardFormatW(name.as_ptr()) }
|
||||
}
|
||||
|
||||
/// `DROPEFFECT_COPY`.
|
||||
const DROPEFFECT_COPY: u32 = 1;
|
||||
|
||||
/// An `HGLOBAL` holding a copy of `bytes`. Null when the allocation failed.
|
||||
fn global_bytes(bytes: &[u8]) -> Handle {
|
||||
unsafe {
|
||||
let memory = GlobalAlloc(GMEM_MOVEABLE, bytes.len());
|
||||
if memory.is_null() {
|
||||
return ptr::null_mut();
|
||||
}
|
||||
let data = GlobalLock(memory);
|
||||
if data.is_null() {
|
||||
GlobalFree(memory);
|
||||
return ptr::null_mut();
|
||||
}
|
||||
ptr::copy_nonoverlapping(bytes.as_ptr(), data as *mut u8, bytes.len());
|
||||
GlobalUnlock(memory);
|
||||
memory
|
||||
}
|
||||
}
|
||||
|
||||
/// An `HGLOBAL` holding `text` as UTF-16 with a terminating NUL, and its
|
||||
/// byte size. Null when the allocation failed.
|
||||
fn global_text(text: &str) -> (Handle, usize) {
|
||||
@@ -446,48 +393,6 @@ mod imp {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_png(png: &[u8], owner: usize) -> std::io::Result<()> {
|
||||
let dib = super::image::png_to_dib(png)?;
|
||||
let format = png_format();
|
||||
if format == 0 {
|
||||
return Err(std::io::Error::last_os_error());
|
||||
}
|
||||
let formats = [(format, png), (CF_DIBV5, dib.as_slice())];
|
||||
// SAFETY: allocations remain ours until SetClipboardData accepts them. Prepare both
|
||||
// before replacing the clipboard; free only allocations the OS did not take.
|
||||
unsafe {
|
||||
let mut blocks: Vec<_> = formats.iter().map(|(_, bytes)| global_bytes(bytes)).collect();
|
||||
if blocks.iter().any(|memory| memory.is_null()) || !open_for(owner as Handle) {
|
||||
let error = std::io::Error::last_os_error();
|
||||
for memory in blocks {
|
||||
if !memory.is_null() {
|
||||
GlobalFree(memory);
|
||||
}
|
||||
}
|
||||
return Err(error);
|
||||
}
|
||||
let mut result = Ok(());
|
||||
if EmptyClipboard() == 0 {
|
||||
result = Err(std::io::Error::last_os_error());
|
||||
} else {
|
||||
for ((format, _), memory) in formats.iter().zip(&mut blocks) {
|
||||
if SetClipboardData(*format, *memory).is_null() {
|
||||
result = Err(std::io::Error::last_os_error());
|
||||
break;
|
||||
}
|
||||
*memory = ptr::null_mut();
|
||||
}
|
||||
}
|
||||
CloseClipboard();
|
||||
for memory in blocks {
|
||||
if !memory.is_null() {
|
||||
GlobalFree(memory);
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_files(paths: &[PathBuf]) -> bool {
|
||||
let bytes = encode(paths);
|
||||
if bytes.len() <= HEADER {
|
||||
@@ -525,13 +430,6 @@ mod imp {
|
||||
if !taken {
|
||||
GlobalFree(memory);
|
||||
}
|
||||
let effect = drop_effect_format();
|
||||
if effect != 0 {
|
||||
let effect_memory = global_bytes(&DROPEFFECT_COPY.to_le_bytes());
|
||||
if !effect_memory.is_null() && SetClipboardData(effect, effect_memory).is_null() {
|
||||
GlobalFree(effect_memory);
|
||||
}
|
||||
}
|
||||
let (text_memory, _) = global_text(&text);
|
||||
if !text_memory.is_null() {
|
||||
// The text alone still pastes somewhere useful.
|
||||
@@ -555,7 +453,7 @@ mod imp {
|
||||
NSBitmapImageFileType, NSBitmapImageRep, NSPasteboard, NSPasteboardReadingOptionKey, NSPasteboardTypePNG,
|
||||
NSPasteboardTypeString, NSPasteboardTypeTIFF, NSPasteboardURLReadingFileURLsOnlyKey, NSPasteboardWriting,
|
||||
};
|
||||
use objc2_foundation::{NSArray, NSData, NSDictionary, NSNumber, NSString, NSURL};
|
||||
use objc2_foundation::{NSArray, NSDictionary, NSNumber, NSString, NSURL};
|
||||
use std::path::PathBuf;
|
||||
|
||||
use super::names_text;
|
||||
@@ -653,23 +551,6 @@ mod imp {
|
||||
})
|
||||
}
|
||||
|
||||
pub fn set_png(png: &[u8], _owner: usize) -> std::io::Result<()> {
|
||||
debug_assert!(MainThreadMarker::new().is_some(), "NSPasteboard access requires the main thread");
|
||||
autoreleasepool(|_| {
|
||||
let data = NSData::with_bytes(png);
|
||||
if NSBitmapImageRep::imageRepWithData(&data).is_none() {
|
||||
return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "Invalid clipboard image"));
|
||||
}
|
||||
let board = NSPasteboard::generalPasteboard();
|
||||
board.clearContents();
|
||||
if board.setData_forType(Some(&data), unsafe { NSPasteboardTypePNG }) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(std::io::Error::other("Cannot write clipboard image"))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
pub fn set_files(paths: &[PathBuf]) -> bool {
|
||||
debug_assert!(MainThreadMarker::new().is_some(), "NSPasteboard access requires the main thread");
|
||||
autoreleasepool(|_| {
|
||||
@@ -700,21 +581,6 @@ mod imp {
|
||||
mod imp {
|
||||
use std::path::PathBuf;
|
||||
|
||||
pub fn set_png(png: &[u8], _owner: usize) -> std::io::Result<()> {
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
let image = gtk::gdk_pixbuf::Pixbuf::from_read(std::io::Cursor::new(png.to_vec()))
|
||||
.map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error.to_string()))?;
|
||||
gtk::Clipboard::get(>k::gdk::SELECTION_CLIPBOARD).set_image(&image);
|
||||
Ok(())
|
||||
}
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
{
|
||||
let _ = png;
|
||||
Err(std::io::Error::other("Clipboard images are unavailable on this platform"))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_text(text: &str, _owner: usize) -> std::io::Result<()> {
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
@@ -756,15 +622,6 @@ mod imp {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn invalid_or_oversized_images_are_rejected_before_accessing_the_clipboard() {
|
||||
assert!(set_png(b"not a PNG", 0).is_err());
|
||||
let mut header = b"\x89PNG\r\n\x1a\n\0\0\0\rIHDR".to_vec();
|
||||
header.extend_from_slice(&100_000u32.to_be_bytes());
|
||||
header.extend_from_slice(&100_000u32.to_be_bytes());
|
||||
assert!(set_png(&header, 0).is_err());
|
||||
}
|
||||
|
||||
fn paths(list: &[&str]) -> Vec<PathBuf> {
|
||||
list.iter().map(PathBuf::from).collect()
|
||||
}
|
||||
|
||||
@@ -1,18 +0,0 @@
|
||||
[package]
|
||||
name = "ide-command"
|
||||
description = "Declares OpenIDEA's backend commands once and derives their adapters, trust class and placement"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[lib]
|
||||
proc-macro = true
|
||||
|
||||
[dependencies]
|
||||
heck.workspace = true
|
||||
proc-macro2.workspace = true
|
||||
quote.workspace = true
|
||||
syn.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
serde.workspace = true
|
||||
@@ -1,92 +0,0 @@
|
||||
// Stand-in for the parts of `ide-host` that the code generated by `#[command]`, `domain!` and
|
||||
// `domains!` names; doctests `include!` it at their crate root.
|
||||
|
||||
pub type IdeResult<T> = Result<T, IdeError>;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct IdeError(pub String);
|
||||
|
||||
impl IdeError {
|
||||
pub fn unavailable(m: impl Into<String>) -> Self {
|
||||
Self(m.into())
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Host;
|
||||
|
||||
impl Host {
|
||||
pub fn plugin_host(&self) -> Option<std::sync::Arc<plugins::PluginHost>> {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
pub mod plugins {
|
||||
pub struct PluginHost;
|
||||
}
|
||||
|
||||
pub mod catalogue {
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum TrustClass {
|
||||
Always,
|
||||
OutsideRestricted,
|
||||
Trusted,
|
||||
}
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Placement {
|
||||
Desktop,
|
||||
ProjectHost,
|
||||
}
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Mode {
|
||||
Sync,
|
||||
Async,
|
||||
Spawn,
|
||||
}
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct Command {
|
||||
pub name: &'static str,
|
||||
pub trust: TrustClass,
|
||||
pub placement: Placement,
|
||||
pub bindings: bool,
|
||||
pub mode: Mode,
|
||||
}
|
||||
}
|
||||
|
||||
pub mod ops {
|
||||
pub struct Channel<T>(pub std::marker::PhantomData<T>);
|
||||
pub type Emit<T> = std::sync::Arc<dyn Fn(T) + Send + Sync>;
|
||||
}
|
||||
|
||||
pub mod rpc {
|
||||
use crate::catalogue::TrustClass;
|
||||
use crate::{IdeResult, ops::Channel};
|
||||
|
||||
pub struct Call {
|
||||
pub host: std::sync::Arc<crate::Host>,
|
||||
pub window: String,
|
||||
}
|
||||
|
||||
impl Call {
|
||||
pub fn arg<T: Default>(&self, _name: &str) -> IdeResult<T> {
|
||||
Ok(T::default())
|
||||
}
|
||||
pub fn sender<T>(&self, _name: &str) -> IdeResult<Channel<T>> {
|
||||
Ok(Channel(std::marker::PhantomData))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct Dispatcher(pub Vec<(&'static str, TrustClass)>);
|
||||
|
||||
impl Dispatcher {
|
||||
pub fn add<F, Fut, T>(&mut self, name: &'static str, trust: TrustClass, _f: F) -> &mut Self
|
||||
where
|
||||
F: Fn(Call) -> Fut + Send + Sync + 'static,
|
||||
Fut: Future<Output = IdeResult<T>> + Send + 'static,
|
||||
T: serde::Serialize,
|
||||
{
|
||||
self.0.push((name, trust));
|
||||
self
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,884 +0,0 @@
|
||||
//! Declares OpenIDEA's backend commands once, on the fn that implements them.
|
||||
//!
|
||||
//! A command that runs on the project host is an `ide-host` fn with `#[command]`; its module
|
||||
//! lists it in `domain!`, and `ide-host` lists its domains in `domains!`. From that `src-tauri`
|
||||
//! derives the Tauri adapter and its bindings entry, and `ide-host` derives the JSON-RPC handler
|
||||
//! `openidea-server` answers. A command only the desktop runs keeps its hand-written Tauri fn,
|
||||
//! with `#[desktop_command]`, and its module lists it in `desktop_domain!`. Every command
|
||||
//! declares its trust class, and each declaration yields a `COMMAND`
|
||||
//! (`ide_host::catalogue::Command`): its name, trust class, placement, bindings entry and
|
||||
//! execution mode.
|
||||
//!
|
||||
//! The examples below build against a stand-in for `ide-host` (`src/doctest_host.rs`). Every
|
||||
//! `compile_fail` example differs from the example before it only by the mistake it names.
|
||||
|
||||
use heck::ToLowerCamelCase;
|
||||
use proc_macro::TokenStream;
|
||||
use proc_macro2::TokenStream as T2;
|
||||
use quote::{ToTokens, format_ident, quote};
|
||||
use syn::ext::IdentExt;
|
||||
use syn::parse::{Parse, ParseStream};
|
||||
use syn::punctuated::Punctuated;
|
||||
use syn::{FnArg, GenericArgument, Ident, ItemFn, Pat, PathArguments, ReturnType, Token, Type};
|
||||
|
||||
/// `#[command(trust = …)]` on a project-host command's implementation in `ide-host`.
|
||||
///
|
||||
/// The fn's name is the command's name and its `///` lines are the bindings' docs. Parameters
|
||||
/// of type `&Host` or `&Arc<Host>`, `window: &str` and `plugins: &Arc<PluginHost>` are injected;
|
||||
/// every other parameter is an argument, owned, whose key is its camelCase name, and
|
||||
/// `Channel<T>` streams values back. `async fn` gives an async Tauri adapter, `fn` a sync one.
|
||||
/// A result of type `IdeResult<T>` is returned as is; any other result is a success. A JSON-RPC
|
||||
/// request that leaves out an argument marked `#[default]` gets the type's default, so servers
|
||||
/// keep answering clients older than the argument.
|
||||
///
|
||||
/// Options:
|
||||
/// - `trust = always | outside_restricted | trusted` (required): where the command may run;
|
||||
/// `always` includes Restricted Mode, `outside_restricted` needs no project or a trusted
|
||||
/// one, `trusted` needs a trusted project.
|
||||
/// - `desktop_body = async | sync | spawn`: the Tauri adapter calls the hand-written fn of the
|
||||
/// same name in `src-tauri` instead of this one, which stays the server's implementation.
|
||||
/// `spawn` runs that sync body off the invoking thread.
|
||||
///
|
||||
/// ```
|
||||
/// # include!("doctest_host.rs");
|
||||
/// pub mod vcs {
|
||||
/// use crate::{Host, IdeResult, ops::Channel};
|
||||
/// use ide_command::command;
|
||||
///
|
||||
/// /// Renames a branch.
|
||||
/// #[command(trust = trusted)]
|
||||
/// pub async fn vcs_rename_branch(
|
||||
/// host: &Host,
|
||||
/// window: &str,
|
||||
/// from: String,
|
||||
/// to: String,
|
||||
/// unset_upstream: bool,
|
||||
/// ) -> IdeResult<()> {
|
||||
/// Ok(())
|
||||
/// }
|
||||
///
|
||||
/// #[command(trust = always)]
|
||||
/// pub fn vcs_watch(window: &str, #[default] depth: u32, on_event: Channel<u32>) -> bool {
|
||||
/// true
|
||||
/// }
|
||||
///
|
||||
/// ide_command::domain!(vcs: vcs_rename_branch, vcs_watch);
|
||||
/// }
|
||||
///
|
||||
/// ide_command::domains!(vcs: crate::vcs);
|
||||
///
|
||||
/// fn main() {
|
||||
/// use catalogue::{Mode, Placement, TrustClass};
|
||||
/// let mut d = rpc::Dispatcher::default();
|
||||
/// register_domains(&mut d);
|
||||
/// assert_eq!(d.0, [("vcs_rename_branch", TrustClass::Trusted), ("vcs_watch", TrustClass::Always)]);
|
||||
/// let watch = vcs::__cmd_vcs_watch::COMMAND;
|
||||
/// assert_eq!((watch.placement, watch.bindings, watch.mode), (Placement::ProjectHost, true, Mode::Sync));
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// A command without a trust class:
|
||||
///
|
||||
/// ```compile_fail
|
||||
/// # include!("doctest_host.rs");
|
||||
/// pub mod vcs {
|
||||
/// #[ide_command::command]
|
||||
/// pub fn vcs_watch(window: &str) -> bool {
|
||||
/// true
|
||||
/// }
|
||||
///
|
||||
/// ide_command::domain!(vcs: vcs_watch);
|
||||
/// }
|
||||
/// # fn main() {}
|
||||
/// ```
|
||||
///
|
||||
/// A command its module doesn't list:
|
||||
///
|
||||
/// ```compile_fail,E0425
|
||||
/// # include!("doctest_host.rs");
|
||||
/// pub mod vcs {
|
||||
/// #[ide_command::command(trust = always)]
|
||||
/// pub fn vcs_watch(window: &str) -> bool {
|
||||
/// true
|
||||
/// }
|
||||
///
|
||||
/// #[ide_command::command(trust = always)]
|
||||
/// pub fn vcs_unwatch(window: &str) -> bool {
|
||||
/// true
|
||||
/// }
|
||||
///
|
||||
/// ide_command::domain!(vcs: vcs_watch);
|
||||
/// }
|
||||
/// # fn main() {}
|
||||
/// ```
|
||||
///
|
||||
/// Two commands with one name, in different modules:
|
||||
///
|
||||
/// ```compile_fail,E0428
|
||||
/// # include!("doctest_host.rs");
|
||||
/// pub mod vcs {
|
||||
/// #[ide_command::command(trust = always)]
|
||||
/// pub fn vcs_watch(window: &str) -> bool {
|
||||
/// true
|
||||
/// }
|
||||
///
|
||||
/// ide_command::domain!(vcs: vcs_watch);
|
||||
/// }
|
||||
///
|
||||
/// pub mod search {
|
||||
/// #[ide_command::command(trust = always)]
|
||||
/// pub fn vcs_watch(window: &str) -> bool {
|
||||
/// true
|
||||
/// }
|
||||
///
|
||||
/// ide_command::domain!(search: vcs_watch);
|
||||
/// }
|
||||
/// # fn main() {}
|
||||
/// ```
|
||||
///
|
||||
/// A borrowed argument:
|
||||
///
|
||||
/// ```compile_fail
|
||||
/// # include!("doctest_host.rs");
|
||||
/// pub mod vcs {
|
||||
/// #[ide_command::command(trust = always)]
|
||||
/// pub fn vcs_watch(window: &str, path: &str) -> bool {
|
||||
/// true
|
||||
/// }
|
||||
///
|
||||
/// ide_command::domain!(vcs: vcs_watch);
|
||||
/// }
|
||||
/// # fn main() {}
|
||||
/// ```
|
||||
///
|
||||
/// A stream that isn't a `Channel<T>`:
|
||||
///
|
||||
/// ```compile_fail
|
||||
/// # include!("doctest_host.rs");
|
||||
/// pub mod vcs {
|
||||
/// use crate::ops::Emit;
|
||||
///
|
||||
/// #[ide_command::command(trust = always)]
|
||||
/// pub fn vcs_watch(window: &str, on_event: Emit<u32>) -> bool {
|
||||
/// true
|
||||
/// }
|
||||
///
|
||||
/// ide_command::domain!(vcs: vcs_watch);
|
||||
/// }
|
||||
/// # fn main() {}
|
||||
/// ```
|
||||
#[proc_macro_attribute]
|
||||
pub fn command(attr: TokenStream, item: TokenStream) -> TokenStream {
|
||||
let opts = syn::parse_macro_input!(attr as Opts);
|
||||
let f = syn::parse_macro_input!(item as ItemFn);
|
||||
expand_command(opts, f).unwrap_or_else(|e| e.to_compile_error()).into()
|
||||
}
|
||||
|
||||
fn expand_command(opts: Opts, mut f: ItemFn) -> syn::Result<T2> {
|
||||
opts.only(&["trust", "desktop_body"])?;
|
||||
let trust = opts.trust()?;
|
||||
// `#[default]` is read here and not emitted.
|
||||
let defaulted: Vec<bool> = f
|
||||
.sig
|
||||
.inputs
|
||||
.iter_mut()
|
||||
.map(|input| match input {
|
||||
FnArg::Typed(pt) => {
|
||||
let before = pt.attrs.len();
|
||||
pt.attrs.retain(|a| !a.path().is_ident("default"));
|
||||
pt.attrs.len() != before
|
||||
}
|
||||
FnArg::Receiver(_) => false,
|
||||
})
|
||||
.collect();
|
||||
let name = &f.sig.ident;
|
||||
if !f.sig.generics.params.is_empty() {
|
||||
return Err(syn::Error::new_spanned(&f.sig.generics, "a command is not generic"));
|
||||
}
|
||||
let is_async = f.sig.asyncness.is_some();
|
||||
let (run, body) = match opts.value("desktop_body") {
|
||||
None if is_async => (format_ident!("async"), quote!(derived)),
|
||||
None => (format_ident!("sync"), quote!(derived)),
|
||||
Some(Some(m)) if ["async", "sync", "spawn"].contains(&m.to_string().as_str()) => (m, quote!(desktop)),
|
||||
Some(v) => return Err(error(v.as_ref().unwrap_or(name), "`desktop_body = async | sync | spawn`")),
|
||||
};
|
||||
let mode = match run.to_string().as_str() {
|
||||
"async" => quote!(Async),
|
||||
"spawn" => quote!(Spawn),
|
||||
_ => quote!(Sync),
|
||||
};
|
||||
|
||||
let mut aliases = Vec::new(); // one type alias per argument, resolved in the fn's own scope
|
||||
let mut args = Vec::new(); // the arguments, for the Tauri adapter's signature
|
||||
let mut call = Vec::new(); // every parameter in declared order, for the Tauri adapter's call
|
||||
let mut rpc_call = Vec::new(); // the same, for the JSON-RPC handler
|
||||
let mut needs_plugins = false;
|
||||
for (input, defaulted) in f.sig.inputs.iter().zip(defaulted) {
|
||||
let FnArg::Typed(pt) = input else {
|
||||
return Err(error(input, "a command is a free fn"));
|
||||
};
|
||||
let Pat::Ident(pi) = &*pt.pat else {
|
||||
return Err(error(&pt.pat, "command parameters are plain identifiers"));
|
||||
};
|
||||
let ident = &pi.ident;
|
||||
let plain_only = || error(ident, "`#[default]` marks a plain argument");
|
||||
if defaulted && injected(ident, &pt.ty).is_some() {
|
||||
return Err(plain_only());
|
||||
}
|
||||
match injected(ident, &pt.ty) {
|
||||
Some(Injected::Host) => {
|
||||
call.push(quote!((inj host)));
|
||||
rpc_call.push(quote!(&c.host));
|
||||
continue;
|
||||
}
|
||||
Some(Injected::Window) => {
|
||||
call.push(quote!((inj window)));
|
||||
rpc_call.push(quote!(&c.window));
|
||||
continue;
|
||||
}
|
||||
Some(Injected::Plugins) => {
|
||||
needs_plugins = true;
|
||||
call.push(quote!((inj plugins)));
|
||||
rpc_call.push(quote!(&plugins));
|
||||
continue;
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
if matches!(&*pt.ty, Type::Reference(_)) {
|
||||
return Err(error(
|
||||
&pt.ty,
|
||||
"command arguments are owned; the injected references are `&Host`, `window: &str` and `plugins: &Arc<PluginHost>`",
|
||||
));
|
||||
}
|
||||
let seg = last_segment(&pt.ty);
|
||||
if seg.is_some_and(|s| s.ident == "Emit") {
|
||||
return Err(error(&pt.ty, "a command streams through `Channel<T>`, not `Emit<T>`"));
|
||||
}
|
||||
let key = ident.unraw().to_string().to_lower_camel_case();
|
||||
let alias = format_ident!("A{}", args.len());
|
||||
if let Some(inner) = seg.filter(|s| s.ident == "Channel").and_then(type_argument) {
|
||||
if defaulted {
|
||||
return Err(plain_only());
|
||||
}
|
||||
aliases.push(quote!(pub type #alias = #inner;));
|
||||
args.push(quote!((#ident channel #alias)));
|
||||
call.push(quote!((arg channel #ident)));
|
||||
rpc_call.push(quote!(c.sender(#key)?));
|
||||
} else {
|
||||
let ty = &pt.ty;
|
||||
aliases.push(quote!(pub type #alias = #ty;));
|
||||
args.push(quote!((#ident plain #alias)));
|
||||
call.push(quote!((arg plain #ident)));
|
||||
rpc_call.push(if defaulted {
|
||||
quote!(c.arg::<::core::option::Option<#ty>>(#key)?.unwrap_or_default())
|
||||
} else {
|
||||
quote!(c.arg(#key)?)
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
let ret: Type = match &f.sig.output {
|
||||
ReturnType::Default => syn::parse_quote!(()),
|
||||
ReturnType::Type(_, t) => (**t).clone(),
|
||||
};
|
||||
let fallible = last_segment(&ret).is_some_and(|s| s.ident == "IdeResult");
|
||||
// specta exports `fn f()` as `void` and `fn f() -> ()` as `null`: keep which one was written.
|
||||
let ret_alias = match &f.sig.output {
|
||||
ReturnType::Default => quote!(),
|
||||
ReturnType::Type(..) => quote!(Ret),
|
||||
};
|
||||
let shape = if fallible { quote!(fallible [#ret_alias]) } else { quote!(infallible [#ret_alias]) };
|
||||
let await_ = is_async.then(|| quote!(.await));
|
||||
let invoke = quote!(super::#name(#(#rpc_call),*) #await_);
|
||||
let invoke = if fallible { invoke } else { quote!(Ok(#invoke)) };
|
||||
let plugins = needs_plugins.then(|| {
|
||||
quote! {
|
||||
let plugins = c.host.plugin_host()
|
||||
.ok_or_else(|| crate::IdeError::unavailable("the plugin host has shut down"))?;
|
||||
}
|
||||
});
|
||||
let docs: Vec<_> = f.attrs.iter().filter(|a| a.path().is_ident("doc")).collect();
|
||||
let module = format_ident!("__cmd_{}", name);
|
||||
let tokens = format_ident!("__catalogue_{}", name);
|
||||
let name_str = name.unraw().to_string();
|
||||
|
||||
Ok(quote! {
|
||||
#f
|
||||
|
||||
// Resolves only if this module's `domain!` lists the command.
|
||||
const _: () = self::__listed::#name;
|
||||
|
||||
#[doc(hidden)]
|
||||
#[allow(non_snake_case)]
|
||||
pub mod #module {
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
#(#aliases)*
|
||||
pub type Ret = #ret;
|
||||
pub const COMMAND: crate::catalogue::Command = crate::catalogue::Command {
|
||||
name: #name_str,
|
||||
trust: crate::catalogue::TrustClass::#trust,
|
||||
placement: crate::catalogue::Placement::ProjectHost,
|
||||
bindings: true,
|
||||
mode: crate::catalogue::Mode::#mode,
|
||||
};
|
||||
/// The JSON-RPC handler.
|
||||
pub async fn rpc(c: crate::rpc::Call) -> crate::IdeResult<impl ::serde::Serialize + use<>> {
|
||||
#plugins
|
||||
#invoke
|
||||
}
|
||||
}
|
||||
|
||||
/// The command's signature, handed to `$cb!` for `src-tauri` to derive its Tauri adapter.
|
||||
#[doc(hidden)]
|
||||
#[macro_export]
|
||||
macro_rules! #tokens {
|
||||
([$($cb:tt)*] { $($ctx:tt)* }) => {
|
||||
$($cb)*! { { $($ctx)* } {
|
||||
name: #name,
|
||||
module: #module,
|
||||
docs: [ #(#docs)* ],
|
||||
run: #run,
|
||||
result: #shape,
|
||||
body: #body,
|
||||
args: [ #(#args)* ],
|
||||
call: [ #(#call)* ],
|
||||
} }
|
||||
};
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// `domain!(vcs: vcs_status, vcs_rename_branch, …)`: the commands one `ide-host` module
|
||||
/// declares with `#[command]`, in any order. It goes once at the end of that module and gives it
|
||||
/// the server's `register`; `domains!` names the domain.
|
||||
///
|
||||
/// ```
|
||||
/// # include!("doctest_host.rs");
|
||||
/// pub mod vcs {
|
||||
/// #[ide_command::command(trust = always)]
|
||||
/// pub fn vcs_watch(window: &str) -> bool {
|
||||
/// true
|
||||
/// }
|
||||
///
|
||||
/// ide_command::domain!(vcs: vcs_watch);
|
||||
/// }
|
||||
/// # fn main() {}
|
||||
/// ```
|
||||
///
|
||||
/// A listed name that isn't a command:
|
||||
///
|
||||
/// ```compile_fail,E0433
|
||||
/// # include!("doctest_host.rs");
|
||||
/// pub mod vcs {
|
||||
/// #[ide_command::command(trust = always)]
|
||||
/// pub fn vcs_watch(window: &str) -> bool {
|
||||
/// true
|
||||
/// }
|
||||
///
|
||||
/// ide_command::domain!(vcs: vcs_watch, vcs_unwatch);
|
||||
/// }
|
||||
/// # fn main() {}
|
||||
/// ```
|
||||
#[proc_macro]
|
||||
pub fn domain(input: TokenStream) -> TokenStream {
|
||||
let Domain { name, commands } = syn::parse_macro_input!(input as Domain);
|
||||
let modules: Vec<_> = commands.iter().map(|c| format_ident!("__cmd_{}", c)).collect();
|
||||
let tokens: Vec<_> = commands.iter().map(|c| format_ident!("__catalogue_{}", c)).collect();
|
||||
let list = format_ident!("__domain_{}", name);
|
||||
let names = commands.iter();
|
||||
let listed = commands.iter();
|
||||
let d = quote!($);
|
||||
quote! {
|
||||
#[doc(hidden)]
|
||||
#[allow(non_upper_case_globals)]
|
||||
mod __listed {
|
||||
#( pub(super) const #listed: () = (); )*
|
||||
}
|
||||
|
||||
// Resolves only from the `domains!` entry that names this domain.
|
||||
#[doc(hidden)]
|
||||
#[allow(non_upper_case_globals)]
|
||||
pub(crate) const #list: () = ();
|
||||
|
||||
/// Adds this module's commands to the server.
|
||||
pub(crate) fn register(d: &mut crate::rpc::Dispatcher) {
|
||||
#( d.add(#modules::COMMAND.name, #modules::COMMAND.trust, #modules::rpc); )*
|
||||
}
|
||||
|
||||
/// `@each`: each command's signature, in list order. `@names`: the list.
|
||||
#[doc(hidden)]
|
||||
#[macro_export]
|
||||
macro_rules! #list {
|
||||
(@each [#d (#d cb:tt)*] { #d (#d ctx:tt)* }) => {
|
||||
#( #d crate::#tokens!{ [#d (#d cb)*] { #d (#d ctx)* } } )*
|
||||
};
|
||||
(@names [#d (#d cb:tt)*] { #d (#d ctx:tt)* }) => {
|
||||
#d (#d cb)*! { { #d (#d ctx)* } [ #(#names)* ] }
|
||||
};
|
||||
}
|
||||
}
|
||||
.into()
|
||||
}
|
||||
|
||||
/// `domains!(vcs: crate::ops::vcs::commands, …)`, once in `ide-host`: every domain, by the name
|
||||
/// its `domain!` gives it and the crate path of its module. It gives the server
|
||||
/// `register_domains`, and hands `src-tauri` the list of domains through `__domains!`.
|
||||
///
|
||||
/// ```
|
||||
/// # include!("doctest_host.rs");
|
||||
/// pub mod vcs {
|
||||
/// #[ide_command::command(trust = always)]
|
||||
/// pub fn vcs_watch(window: &str) -> bool {
|
||||
/// true
|
||||
/// }
|
||||
///
|
||||
/// ide_command::domain!(vcs: vcs_watch);
|
||||
/// }
|
||||
///
|
||||
/// ide_command::domains!(vcs: crate::vcs);
|
||||
/// # fn main() {}
|
||||
/// ```
|
||||
///
|
||||
/// A domain under another name than its `domain!` gives it:
|
||||
///
|
||||
/// ```compile_fail,E0425
|
||||
/// # include!("doctest_host.rs");
|
||||
/// pub mod vcs {
|
||||
/// #[ide_command::command(trust = always)]
|
||||
/// pub fn vcs_watch(window: &str) -> bool {
|
||||
/// true
|
||||
/// }
|
||||
///
|
||||
/// ide_command::domain!(vcs: vcs_watch);
|
||||
/// }
|
||||
///
|
||||
/// ide_command::domains!(git: crate::vcs);
|
||||
/// # fn main() {}
|
||||
/// ```
|
||||
#[proc_macro]
|
||||
pub fn domains(input: TokenStream) -> TokenStream {
|
||||
let entries = syn::parse_macro_input!(input with Punctuated::<DomainPath, Token![,]>::parse_terminated);
|
||||
let mut names = Vec::new();
|
||||
let mut paths = Vec::new();
|
||||
let mut from_crate = Vec::new();
|
||||
for DomainPath { name, path } in entries {
|
||||
let mut segments = path.segments.iter();
|
||||
if path.leading_colon.is_some() || segments.next().is_none_or(|s| s.ident != "crate") {
|
||||
return error(&path, "a domain's path starts with `crate::`").to_compile_error().into();
|
||||
}
|
||||
let rest: Vec<_> = segments.map(|s| &s.ident).collect();
|
||||
from_crate.push(quote!(#(#rest)::*));
|
||||
names.push(name);
|
||||
paths.push(path);
|
||||
}
|
||||
let lists: Vec<_> = names.iter().map(|n| format_ident!("__domain_{}", n)).collect();
|
||||
let d = quote!($);
|
||||
quote! {
|
||||
#( const _: () = #paths::#lists; )*
|
||||
|
||||
/// Adds every domain's commands to the server.
|
||||
pub(crate) fn register_domains(d: &mut crate::rpc::Dispatcher) {
|
||||
#( #paths::register(d); )*
|
||||
}
|
||||
|
||||
/// `@names`: each domain as `(name __domain_name { path })`.
|
||||
#[doc(hidden)]
|
||||
#[macro_export]
|
||||
macro_rules! __domains {
|
||||
(@names [#d (#d cb:tt)*] { #d (#d ctx:tt)* }) => {
|
||||
#d (#d cb)*! { { #d (#d ctx)* } [ #( (#names #lists { #d crate::#from_crate }) )* ] }
|
||||
};
|
||||
}
|
||||
}
|
||||
.into()
|
||||
}
|
||||
|
||||
/// `#[desktop_command(trust = …)]` on a command only the desktop runs, above its
|
||||
/// `#[tauri::command]` in `src-tauri`, whose `(async)` it reads. The fn is left as written.
|
||||
///
|
||||
/// Options: `trust` as for `#[command]` (required), and `bindings = none` for a command that is
|
||||
/// registered outside tauri-specta; such a command isn't listed in `desktop_domain!`.
|
||||
///
|
||||
/// ```
|
||||
/// # include!("doctest_host.rs");
|
||||
/// # extern crate self as ide_host;
|
||||
/// pub mod clipboard {
|
||||
/// #[ide_command::desktop_command(trust = always)]
|
||||
/// pub async fn clipboard_text() -> Option<String> {
|
||||
/// None
|
||||
/// }
|
||||
///
|
||||
/// ide_command::desktop_domain!(clipboard_text);
|
||||
/// }
|
||||
///
|
||||
/// fn main() {
|
||||
/// let text = clipboard::clipboard_text::COMMAND;
|
||||
/// assert_eq!((text.name, text.placement), ("clipboard_text", catalogue::Placement::Desktop));
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// A command without a trust class:
|
||||
///
|
||||
/// ```compile_fail
|
||||
/// # include!("doctest_host.rs");
|
||||
/// # extern crate self as ide_host;
|
||||
/// pub mod clipboard {
|
||||
/// #[ide_command::desktop_command]
|
||||
/// pub async fn clipboard_text() -> Option<String> {
|
||||
/// None
|
||||
/// }
|
||||
///
|
||||
/// ide_command::desktop_domain!(clipboard_text);
|
||||
/// }
|
||||
/// # fn main() {}
|
||||
/// ```
|
||||
///
|
||||
/// A command its module doesn't list:
|
||||
///
|
||||
/// ```compile_fail,E0425
|
||||
/// # include!("doctest_host.rs");
|
||||
/// # extern crate self as ide_host;
|
||||
/// pub mod clipboard {
|
||||
/// #[ide_command::desktop_command(trust = always)]
|
||||
/// pub async fn clipboard_text() -> Option<String> {
|
||||
/// None
|
||||
/// }
|
||||
///
|
||||
/// #[ide_command::desktop_command(trust = always)]
|
||||
/// pub async fn clipboard_html() -> Option<String> {
|
||||
/// None
|
||||
/// }
|
||||
///
|
||||
/// ide_command::desktop_domain!(clipboard_text);
|
||||
/// }
|
||||
/// # fn main() {}
|
||||
/// ```
|
||||
#[proc_macro_attribute]
|
||||
pub fn desktop_command(attr: TokenStream, item: TokenStream) -> TokenStream {
|
||||
let opts = syn::parse_macro_input!(attr as Opts);
|
||||
let f = syn::parse_macro_input!(item as ItemFn);
|
||||
expand_desktop_command(opts, f).unwrap_or_else(|e| e.to_compile_error()).into()
|
||||
}
|
||||
|
||||
fn expand_desktop_command(opts: Opts, f: ItemFn) -> syn::Result<T2> {
|
||||
opts.only(&["trust", "bindings"])?;
|
||||
let trust = opts.trust()?;
|
||||
let bindings = match opts.value("bindings") {
|
||||
None => true,
|
||||
Some(Some(v)) if v == "none" => false,
|
||||
Some(v) => return Err(error(v.as_ref().unwrap_or(&f.sig.ident), "`bindings = none`")),
|
||||
};
|
||||
// `#[tauri::command(async)]` runs a sync fn off the invoking thread.
|
||||
let spawned = f.attrs.iter().any(|a| {
|
||||
let path = a.path();
|
||||
path.segments.len() == 2
|
||||
&& path.segments[0].ident == "tauri"
|
||||
&& path.segments[1].ident == "command"
|
||||
&& a.parse_args::<Ident>().is_ok_and(|i| i == "async")
|
||||
});
|
||||
let mode = if f.sig.asyncness.is_some() {
|
||||
quote!(Async)
|
||||
} else if spawned {
|
||||
quote!(Spawn)
|
||||
} else {
|
||||
quote!(Sync)
|
||||
};
|
||||
let name = &f.sig.ident;
|
||||
let name_str = name.unraw().to_string();
|
||||
let listed = bindings.then(|| quote!(const _: () = self::__listed::#name;));
|
||||
Ok(quote! {
|
||||
#f
|
||||
|
||||
#listed
|
||||
|
||||
#[doc(hidden)]
|
||||
pub mod #name {
|
||||
pub const COMMAND: ::ide_host::catalogue::Command = ::ide_host::catalogue::Command {
|
||||
name: #name_str,
|
||||
trust: ::ide_host::catalogue::TrustClass::#trust,
|
||||
placement: ::ide_host::catalogue::Placement::Desktop,
|
||||
bindings: #bindings,
|
||||
mode: ::ide_host::catalogue::Mode::#mode,
|
||||
};
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// `desktop_domain!(clipboard_text, clipboard_write_text, …)`: the `#[desktop_command]`s of one
|
||||
/// `src-tauri` module that are in the bindings, in any order. It goes once at the end of that
|
||||
/// module and gives it `__desktop_domain!(@names …)`.
|
||||
#[proc_macro]
|
||||
pub fn desktop_domain(input: TokenStream) -> TokenStream {
|
||||
let commands = syn::parse_macro_input!(input with Punctuated::<Ident, Token![,]>::parse_terminated);
|
||||
let names = commands.iter();
|
||||
let listed = commands.iter();
|
||||
let d = quote!($);
|
||||
quote! {
|
||||
#[doc(hidden)]
|
||||
#[allow(non_upper_case_globals)]
|
||||
mod __listed {
|
||||
#( pub(super) const #listed: () = (); )*
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
macro_rules! __desktop_domain {
|
||||
(@names [#d (#d cb:tt)*] { #d (#d ctx:tt)* }) => {
|
||||
#d (#d cb)*! { { #d (#d ctx)* } [ #(#names)* ] }
|
||||
};
|
||||
}
|
||||
#[allow(unused_imports)]
|
||||
pub(crate) use __desktop_domain;
|
||||
}
|
||||
.into()
|
||||
}
|
||||
|
||||
/// `sorted_catalogue!(bindings: a::x, b::y, …; raw: c::z, …)`, in `src-tauri`: every command,
|
||||
/// sorted by name, as `(collect_commands![…bindings…], [COMMAND, …every command…])`. Each path
|
||||
/// names a command fn and the module of the same name that holds its `COMMAND`.
|
||||
///
|
||||
/// ```
|
||||
/// # include!("doctest_host.rs");
|
||||
/// # extern crate self as ide_host;
|
||||
/// # extern crate self as tauri_specta;
|
||||
/// # #[macro_export]
|
||||
/// # macro_rules! collect_commands { ($($p:path),*) => { [$(stringify!($p)),*] } }
|
||||
/// pub mod clipboard {
|
||||
/// #[ide_command::desktop_command(trust = always)]
|
||||
/// pub async fn clipboard_text() -> Option<String> {
|
||||
/// None
|
||||
/// }
|
||||
///
|
||||
/// #[ide_command::desktop_command(trust = always)]
|
||||
/// pub fn clipboard_clear() {}
|
||||
///
|
||||
/// ide_command::desktop_domain!(clipboard_text, clipboard_clear);
|
||||
/// }
|
||||
///
|
||||
/// fn main() {
|
||||
/// let (commands, rows) = ide_command::sorted_catalogue!(
|
||||
/// bindings: clipboard::clipboard_text, clipboard::clipboard_clear;
|
||||
/// raw:
|
||||
/// );
|
||||
/// assert_eq!(commands, ["clipboard :: clipboard_clear", "clipboard :: clipboard_text"]);
|
||||
/// assert_eq!(rows.map(|c| c.name), ["clipboard_clear", "clipboard_text"]);
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Two commands with one name:
|
||||
///
|
||||
/// ```compile_fail
|
||||
/// # include!("doctest_host.rs");
|
||||
/// # extern crate self as ide_host;
|
||||
/// # extern crate self as tauri_specta;
|
||||
/// # #[macro_export]
|
||||
/// # macro_rules! collect_commands { ($($p:path),*) => { [$(stringify!($p)),*] } }
|
||||
/// pub mod clipboard {
|
||||
/// #[ide_command::desktop_command(trust = always)]
|
||||
/// pub async fn clipboard_text() -> Option<String> {
|
||||
/// None
|
||||
/// }
|
||||
///
|
||||
/// #[ide_command::desktop_command(trust = always)]
|
||||
/// pub fn clipboard_clear() {}
|
||||
///
|
||||
/// ide_command::desktop_domain!(clipboard_text, clipboard_clear);
|
||||
/// }
|
||||
///
|
||||
/// pub mod editor {
|
||||
/// #[ide_command::desktop_command(trust = always)]
|
||||
/// pub fn clipboard_clear() {}
|
||||
///
|
||||
/// ide_command::desktop_domain!(clipboard_clear);
|
||||
/// }
|
||||
///
|
||||
/// fn main() {
|
||||
/// let (commands, rows) = ide_command::sorted_catalogue!(
|
||||
/// bindings: clipboard::clipboard_text, clipboard::clipboard_clear, editor::clipboard_clear;
|
||||
/// raw:
|
||||
/// );
|
||||
/// }
|
||||
/// ```
|
||||
#[proc_macro]
|
||||
pub fn sorted_catalogue(input: TokenStream) -> TokenStream {
|
||||
let Catalogue { bindings, raw } = syn::parse_macro_input!(input as Catalogue);
|
||||
let key = |p: &syn::Path| p.segments.last().map(|s| s.ident.unraw().to_string()).unwrap_or_default();
|
||||
let mut bindings: Vec<_> = bindings.into_iter().collect();
|
||||
bindings.sort_by_cached_key(key);
|
||||
let mut all: Vec<_> = bindings.iter().chain(&raw).collect();
|
||||
all.sort_by_cached_key(|p| key(p));
|
||||
for pair in all.windows(2) {
|
||||
if key(pair[0]) == key(pair[1]) {
|
||||
let (a, b) = (pair[0], pair[1]);
|
||||
let message = format!(
|
||||
"command `{}` is declared twice: `{}` and `{}`",
|
||||
key(b),
|
||||
a.to_token_stream(),
|
||||
b.to_token_stream()
|
||||
);
|
||||
return syn::Error::new_spanned(b, message).to_compile_error().into();
|
||||
}
|
||||
}
|
||||
quote! {
|
||||
(
|
||||
::tauri_specta::collect_commands![ #(#bindings),* ],
|
||||
[ #( #all::COMMAND ),* ],
|
||||
)
|
||||
}
|
||||
.into()
|
||||
}
|
||||
|
||||
struct Catalogue {
|
||||
bindings: Punctuated<syn::Path, Token![,]>,
|
||||
raw: Punctuated<syn::Path, Token![,]>,
|
||||
}
|
||||
|
||||
impl Parse for Catalogue {
|
||||
fn parse(input: ParseStream) -> syn::Result<Self> {
|
||||
let paths = |input: ParseStream, label: &str| -> syn::Result<Punctuated<syn::Path, Token![,]>> {
|
||||
let ident: Ident = input.parse()?;
|
||||
if ident != label {
|
||||
return Err(error(&ident, &format!("expected `{label}:`")));
|
||||
}
|
||||
input.parse::<Token![:]>()?;
|
||||
let mut out = Punctuated::new();
|
||||
while !input.is_empty() && !input.peek(Token![;]) {
|
||||
out.push_value(input.parse()?);
|
||||
if !input.peek(Token![,]) {
|
||||
break;
|
||||
}
|
||||
out.push_punct(input.parse()?);
|
||||
}
|
||||
Ok(out)
|
||||
};
|
||||
let bindings = paths(input, "bindings")?;
|
||||
input.parse::<Token![;]>()?;
|
||||
let raw = paths(input, "raw")?;
|
||||
let _ = input.parse::<Option<Token![;]>>()?;
|
||||
Ok(Self { bindings, raw })
|
||||
}
|
||||
}
|
||||
|
||||
enum Injected {
|
||||
Host,
|
||||
Window,
|
||||
Plugins,
|
||||
}
|
||||
|
||||
/// `&Host` or `&Arc<Host>` under any name, `window: &str`, `plugins: &Arc<PluginHost>`.
|
||||
fn injected(ident: &Ident, ty: &Type) -> Option<Injected> {
|
||||
let Type::Reference(r) = ty else { return None };
|
||||
if r.mutability.is_some() {
|
||||
return None;
|
||||
}
|
||||
let seg = last_segment(&r.elem)?;
|
||||
let arc_of =
|
||||
|name: &str| seg.ident == "Arc" && type_argument(seg).and_then(last_segment).is_some_and(|s| s.ident == name);
|
||||
if seg.ident == "Host" || arc_of("Host") {
|
||||
Some(Injected::Host)
|
||||
} else if ident == "window" && seg.ident == "str" {
|
||||
Some(Injected::Window)
|
||||
} else if ident == "plugins" && arc_of("PluginHost") {
|
||||
Some(Injected::Plugins)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn last_segment(ty: &Type) -> Option<&syn::PathSegment> {
|
||||
match ty {
|
||||
Type::Path(p) if p.qself.is_none() => p.path.segments.last(),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn type_argument(seg: &syn::PathSegment) -> Option<&Type> {
|
||||
match &seg.arguments {
|
||||
PathArguments::AngleBracketed(a) => a.args.iter().find_map(|g| match g {
|
||||
GenericArgument::Type(t) => Some(t),
|
||||
_ => None,
|
||||
}),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn error(span: impl ToTokens, message: &str) -> syn::Error {
|
||||
syn::Error::new_spanned(span, message)
|
||||
}
|
||||
|
||||
/// `name: a, b, …`
|
||||
struct Domain {
|
||||
name: Ident,
|
||||
commands: Punctuated<Ident, Token![,]>,
|
||||
}
|
||||
|
||||
impl Parse for Domain {
|
||||
fn parse(input: ParseStream) -> syn::Result<Self> {
|
||||
let name = input.parse()?;
|
||||
input.parse::<Token![:]>()?;
|
||||
Ok(Self { name, commands: Punctuated::parse_terminated(input)? })
|
||||
}
|
||||
}
|
||||
|
||||
/// `name: crate::path`
|
||||
struct DomainPath {
|
||||
name: Ident,
|
||||
path: syn::Path,
|
||||
}
|
||||
|
||||
impl Parse for DomainPath {
|
||||
fn parse(input: ParseStream) -> syn::Result<Self> {
|
||||
let name = input.parse()?;
|
||||
input.parse::<Token![:]>()?;
|
||||
Ok(Self { name, path: input.parse()? })
|
||||
}
|
||||
}
|
||||
|
||||
/// An attribute's options: `key = value` and bare `key`.
|
||||
struct Opts(Vec<(Ident, Option<Ident>)>);
|
||||
|
||||
impl Parse for Opts {
|
||||
fn parse(input: ParseStream) -> syn::Result<Self> {
|
||||
let mut out = Vec::new();
|
||||
while !input.is_empty() {
|
||||
let key: Ident = input.parse()?;
|
||||
let value = if input.peek(Token![=]) {
|
||||
input.parse::<Token![=]>()?;
|
||||
// `async` is a keyword.
|
||||
Some(Ident::parse_any(input)?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
out.push((key, value));
|
||||
if !input.is_empty() {
|
||||
input.parse::<Token![,]>()?;
|
||||
}
|
||||
}
|
||||
Ok(Self(out))
|
||||
}
|
||||
}
|
||||
|
||||
impl Opts {
|
||||
fn value(&self, key: &str) -> Option<Option<Ident>> {
|
||||
self.0.iter().find(|(k, _)| k == key).map(|(_, v)| v.clone())
|
||||
}
|
||||
|
||||
fn only(&self, known: &[&str]) -> syn::Result<()> {
|
||||
match self.0.iter().map(|(k, _)| k).find(|k| !known.iter().any(|n| *k == n)) {
|
||||
Some(k) => Err(error(k, &format!("unknown option; the options are {}", known.join(", ")))),
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
fn trust(&self) -> syn::Result<T2> {
|
||||
match self.value("trust").flatten().map(|t| t.to_string()).as_deref() {
|
||||
Some("always") => Ok(quote!(Always)),
|
||||
Some("outside_restricted") => Ok(quote!(OutsideRestricted)),
|
||||
Some("trusted") => Ok(quote!(Trusted)),
|
||||
_ => Err(syn::Error::new(
|
||||
proc_macro2::Span::call_site(),
|
||||
"every command declares its trust class: `trust = always | outside_restricted | trusted`",
|
||||
)),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,6 @@ edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
base64.workspace = true
|
||||
dunce.workspace = true
|
||||
encoding_rs.workspace = true
|
||||
serde.workspace = true
|
||||
|
||||
@@ -1,319 +0,0 @@
|
||||
//! Runs a tool's CLI (`docker`, `gh`, `adb`) as a child process: bounded runs that collect
|
||||
//! its output, and cancellable streams that hand over its output line by line.
|
||||
//!
|
||||
//! Every child leads its own process group ([`own_group`]), so cancelling or timing out
|
||||
//! reaches what it started in turn (`gh` → `git`, `docker` → CLI plugins such as compose).
|
||||
//! They get [`KILL_GRACE`] to exit on `SIGTERM` and clean up (git removes its lock files)
|
||||
//! before `SIGKILL`.
|
||||
|
||||
use crate::process::{own_group, prepare, terminate_tree};
|
||||
use crate::{CancellationToken, IdeError, IdeResult};
|
||||
use std::borrow::Cow;
|
||||
use std::io::{Read, Write};
|
||||
use std::process::{Child, Command, Stdio};
|
||||
use std::sync::mpsc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// How long a cancelled or timed-out child's process group gets to exit on `SIGTERM`
|
||||
/// before `SIGKILL`.
|
||||
const KILL_GRACE: Duration = Duration::from_millis(20);
|
||||
|
||||
/// How many of a streamed child's last non-blank stderr lines are kept for its error message.
|
||||
const STDERR_TAIL: usize = 20;
|
||||
|
||||
/// How a tool's output bytes become text.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Decoding {
|
||||
/// [`decode_tool_output`](crate::output_encoding::decode_tool_output): UTF-8, and on
|
||||
/// Windows the system code page for what is not.
|
||||
ToolOutput,
|
||||
/// UTF-8, invalid bytes replaced by U+FFFD.
|
||||
Utf8Lossy,
|
||||
}
|
||||
|
||||
impl Decoding {
|
||||
fn decode(self, bytes: &[u8]) -> Cow<'_, str> {
|
||||
match self {
|
||||
Decoding::ToolOutput => Cow::Owned(crate::output_encoding::decode_tool_output(bytes)),
|
||||
Decoding::Utf8Lossy => String::from_utf8_lossy(bytes),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What a child's stdin is fed with, and how.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Input<'a> {
|
||||
/// Written before the output is read, then closed: only for input small enough
|
||||
/// (a password) to fit the pipe, as a full pipe blocks the caller.
|
||||
Inline(&'a str),
|
||||
/// Written by a thread of its own, then closed: a large body must not block on a full
|
||||
/// pipe while the child is not reading yet.
|
||||
Threaded(&'a str),
|
||||
}
|
||||
|
||||
/// How a streamed child's `\r` is read.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum CarriageReturn {
|
||||
/// Ends a line like `\n`: progress output rewrites its line in place.
|
||||
EndsLine,
|
||||
/// Is dropped; only `\n` ends a line.
|
||||
Dropped,
|
||||
}
|
||||
|
||||
/// What a bounded run collected.
|
||||
pub struct Output {
|
||||
pub stdout: String,
|
||||
pub stderr: String,
|
||||
pub success: bool,
|
||||
}
|
||||
|
||||
/// Which pipe a streamed line came from.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Stream {
|
||||
Stdout,
|
||||
Stderr,
|
||||
}
|
||||
|
||||
/// One tool's CLI: its name for error messages and how its output is decoded.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct CliTool {
|
||||
name: &'static str,
|
||||
decoding: Decoding,
|
||||
}
|
||||
|
||||
impl CliTool {
|
||||
pub const fn new(name: &'static str, decoding: Decoding) -> Self {
|
||||
Self { name, decoding }
|
||||
}
|
||||
|
||||
fn spawn(self, cmd: &mut Command) -> IdeResult<Child> {
|
||||
cmd.spawn().map_err(|e| IdeError::unavailable(format!("could not run {}: {e}", self.name)))
|
||||
}
|
||||
|
||||
/// Pipes stdout and stderr, closes stdin and starts the child in its own process group.
|
||||
fn configure(cmd: &mut Command) {
|
||||
cmd.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped());
|
||||
prepare(own_group(cmd));
|
||||
}
|
||||
|
||||
/// Runs `cmd` to completion. Fails when it outlives `timeout` or `cancel` fires;
|
||||
/// a non-zero exit is reported in [`Output::success`], not as an error.
|
||||
pub fn run(self, cmd: Command, timeout: Duration, cancel: Option<&CancellationToken>) -> IdeResult<Output> {
|
||||
self.run_with_input(cmd, None, timeout, cancel)
|
||||
}
|
||||
|
||||
/// [`run`](Self::run) with `input` written to the child's stdin and then closed.
|
||||
pub fn run_with_input(
|
||||
self,
|
||||
mut cmd: Command,
|
||||
input: Option<Input>,
|
||||
timeout: Duration,
|
||||
cancel: Option<&CancellationToken>,
|
||||
) -> IdeResult<Output> {
|
||||
Self::configure(&mut cmd);
|
||||
if input.is_some() {
|
||||
cmd.stdin(Stdio::piped());
|
||||
}
|
||||
let mut child = self.spawn(&mut cmd)?;
|
||||
match (input, child.stdin.take()) {
|
||||
(Some(Input::Inline(text)), Some(mut stdin)) => {
|
||||
// Dropping `stdin` afterwards closes it, so the CLI sees EOF.
|
||||
let _ = stdin.write_all(text.as_bytes());
|
||||
}
|
||||
(Some(Input::Threaded(text)), Some(mut stdin)) => {
|
||||
let text = text.to_owned();
|
||||
std::thread::spawn(move || {
|
||||
let _ = stdin.write_all(text.as_bytes());
|
||||
});
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
let decoding = self.decoding;
|
||||
let out = child.stdout.take().map(|pipe| read_all(pipe, decoding));
|
||||
let err = child.stderr.take().map(|pipe| read_all(pipe, decoding));
|
||||
let deadline = Instant::now() + timeout;
|
||||
let status = loop {
|
||||
if let Some(status) = child.try_wait()? {
|
||||
break status;
|
||||
}
|
||||
if cancel.is_some_and(CancellationToken::is_cancelled) {
|
||||
terminate_tree(&mut child, KILL_GRACE);
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
if Instant::now() >= deadline {
|
||||
terminate_tree(&mut child, KILL_GRACE);
|
||||
return Err(IdeError::unavailable(format!("{} did not respond in time", self.name)));
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
};
|
||||
Ok(Output {
|
||||
stdout: out.map(|t| t.join().unwrap_or_default()).unwrap_or_default(),
|
||||
stderr: err.map(|t| t.join().unwrap_or_default()).unwrap_or_default(),
|
||||
success: status.success(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Runs `cmd`, handing every output line to `on_line` until it exits or `cancel`
|
||||
/// fires. Returns whether it exited successfully plus the last stderr lines.
|
||||
pub fn stream(
|
||||
self,
|
||||
cmd: Command,
|
||||
cancel: &CancellationToken,
|
||||
on_line: &mut dyn FnMut(Stream, String),
|
||||
) -> IdeResult<(bool, Vec<String>)> {
|
||||
let mut lines = self.lines(cmd, cancel, CarriageReturn::EndsLine)?;
|
||||
let mut stderr_tail: Vec<String> = Vec::new();
|
||||
loop {
|
||||
match lines.poll(cancel, Duration::from_millis(50))? {
|
||||
Poll::Line(stream, line) => {
|
||||
if stream == Stream::Stderr && !line.trim().is_empty() {
|
||||
keep_stderr_line(&mut stderr_tail, line.clone());
|
||||
}
|
||||
on_line(stream, line);
|
||||
}
|
||||
Poll::Closed | Poll::Timeout => {}
|
||||
Poll::Finished => break,
|
||||
}
|
||||
}
|
||||
Ok((lines.finish(cancel)?, stderr_tail))
|
||||
}
|
||||
|
||||
/// Starts `cmd` with a reader thread per pipe, for a caller that drives the loop itself
|
||||
/// (see [`Lines::poll`]). Fails when `cancel` has already fired, without starting it.
|
||||
pub fn lines(self, mut cmd: Command, cancel: &CancellationToken, cr: CarriageReturn) -> IdeResult<Lines> {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
Self::configure(&mut cmd);
|
||||
let mut child = self.spawn(&mut cmd)?;
|
||||
let (tx, rx) = mpsc::channel::<Event>();
|
||||
let mut open = 0;
|
||||
if let Some(out) = child.stdout.take() {
|
||||
spawn_reader(out, tx.clone(), Stream::Stdout, self.decoding, cr);
|
||||
open += 1;
|
||||
}
|
||||
if let Some(err) = child.stderr.take() {
|
||||
spawn_reader(err, tx.clone(), Stream::Stderr, self.decoding, cr);
|
||||
open += 1;
|
||||
}
|
||||
drop(tx);
|
||||
Ok(Lines { child, rx, open })
|
||||
}
|
||||
}
|
||||
|
||||
/// Appends a stderr line to `tail`, which keeps only the last [`STDERR_TAIL`].
|
||||
pub fn keep_stderr_line(tail: &mut Vec<String>, line: String) {
|
||||
tail.push(line);
|
||||
if tail.len() > STDERR_TAIL {
|
||||
tail.remove(0);
|
||||
}
|
||||
}
|
||||
|
||||
fn read_all(mut pipe: impl Read + Send + 'static, decoding: Decoding) -> std::thread::JoinHandle<String> {
|
||||
std::thread::spawn(move || {
|
||||
let mut buf = Vec::new();
|
||||
let _ = pipe.read_to_end(&mut buf);
|
||||
decoding.decode(&buf).into_owned()
|
||||
})
|
||||
}
|
||||
|
||||
enum Event {
|
||||
Line(Stream, String),
|
||||
Closed,
|
||||
}
|
||||
|
||||
fn spawn_reader(
|
||||
mut pipe: impl Read + Send + 'static,
|
||||
tx: mpsc::Sender<Event>,
|
||||
stream: Stream,
|
||||
decoding: Decoding,
|
||||
cr: CarriageReturn,
|
||||
) {
|
||||
std::thread::spawn(move || {
|
||||
let mut buf = [0u8; 8192];
|
||||
let mut pending: Vec<u8> = Vec::new();
|
||||
let flush = |pending: &mut Vec<u8>| {
|
||||
if !pending.is_empty() {
|
||||
let line = decoding.decode(pending).trim_end().to_string();
|
||||
pending.clear();
|
||||
let _ = tx.send(Event::Line(stream, line));
|
||||
}
|
||||
};
|
||||
loop {
|
||||
match pipe.read(&mut buf) {
|
||||
Ok(0) | Err(_) => break,
|
||||
Ok(n) => {
|
||||
for &b in &buf[..n] {
|
||||
if b == b'\n' || (b == b'\r' && cr == CarriageReturn::EndsLine) {
|
||||
flush(&mut pending);
|
||||
} else if b != b'\r' {
|
||||
pending.push(b);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
flush(&mut pending);
|
||||
let _ = tx.send(Event::Closed);
|
||||
});
|
||||
}
|
||||
|
||||
/// A running child whose output lines are read by threads: see [`CliTool::lines`].
|
||||
pub struct Lines {
|
||||
child: Child,
|
||||
rx: mpsc::Receiver<Event>,
|
||||
/// Pipes whose reader has not reported its end yet.
|
||||
open: usize,
|
||||
}
|
||||
|
||||
/// What [`Lines::poll`] saw.
|
||||
pub enum Poll {
|
||||
Line(Stream, String),
|
||||
/// A pipe reached its end.
|
||||
Closed,
|
||||
/// Nothing arrived within the wait.
|
||||
Timeout,
|
||||
/// Every pipe is at its end.
|
||||
Finished,
|
||||
}
|
||||
|
||||
impl Lines {
|
||||
/// Waits up to `wait` for the next line. Fails, after killing the child, when `cancel` has fired.
|
||||
pub fn poll(&mut self, cancel: &CancellationToken, wait: Duration) -> IdeResult<Poll> {
|
||||
if self.open == 0 {
|
||||
return Ok(Poll::Finished);
|
||||
}
|
||||
if cancel.is_cancelled() {
|
||||
terminate_tree(&mut self.child, KILL_GRACE);
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
match self.rx.recv_timeout(wait) {
|
||||
Ok(Event::Line(stream, line)) => Ok(Poll::Line(stream, line)),
|
||||
Ok(Event::Closed) => {
|
||||
self.open -= 1;
|
||||
Ok(Poll::Closed)
|
||||
}
|
||||
Err(mpsc::RecvTimeoutError::Timeout) => Ok(Poll::Timeout),
|
||||
Err(mpsc::RecvTimeoutError::Disconnected) => {
|
||||
self.open = 0;
|
||||
Ok(Poll::Finished)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Waits for the child to exit and returns whether it did so successfully. Fails, after
|
||||
/// killing it, when `cancel` fires first.
|
||||
pub fn finish(mut self, cancel: &CancellationToken) -> IdeResult<bool> {
|
||||
let status = loop {
|
||||
if let Some(status) = self.child.try_wait()? {
|
||||
break status;
|
||||
}
|
||||
if cancel.is_cancelled() {
|
||||
terminate_tree(&mut self.child, KILL_GRACE);
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
};
|
||||
Ok(status.success())
|
||||
}
|
||||
}
|
||||
@@ -197,34 +197,17 @@ pub enum ImportsOnPaste {
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct FoldingSettings {
|
||||
pub show_outline: bool,
|
||||
pub outline_visibility: FoldingOutlineVisibility,
|
||||
pub file_header: bool,
|
||||
pub imports: bool,
|
||||
pub doc_comments: bool,
|
||||
pub go_short_blocks: bool,
|
||||
}
|
||||
|
||||
impl Default for FoldingSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
show_outline: true,
|
||||
outline_visibility: FoldingOutlineVisibility::Hover,
|
||||
file_header: true,
|
||||
imports: true,
|
||||
doc_comments: false,
|
||||
go_short_blocks: true,
|
||||
}
|
||||
Self { show_outline: true, file_header: true, imports: true, doc_comments: false }
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum FoldingOutlineVisibility {
|
||||
#[default]
|
||||
Hover,
|
||||
Always,
|
||||
}
|
||||
|
||||
/// Editor › General › Editor Tabs.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
@@ -290,8 +273,6 @@ pub struct SmartKeysSettings {
|
||||
pub pair_quotes: bool,
|
||||
pub surround_selection: bool,
|
||||
pub tab_out_of_pair: bool,
|
||||
/// A `;` typed before the closing `)` of a statement goes to the end of the statement.
|
||||
pub semicolon_at_statement_end: bool,
|
||||
/// Simultaneous `<tag></tag>` editing: renaming a tag renames its matching tag.
|
||||
pub simultaneous_tag_editing: bool,
|
||||
/// Reformat on paste: `none` | `indentBlock` | `indentEachLine`.
|
||||
@@ -313,7 +294,6 @@ impl Default for SmartKeysSettings {
|
||||
pair_quotes: true,
|
||||
surround_selection: true,
|
||||
tab_out_of_pair: true,
|
||||
semicolon_at_statement_end: true,
|
||||
simultaneous_tag_editing: true,
|
||||
reformat_on_paste: "indentEachLine".into(),
|
||||
escape_on_paste: true,
|
||||
@@ -338,7 +318,6 @@ pub struct CodeEditingSettings {
|
||||
/// Next / previous error goes to errors only (skips warnings).
|
||||
pub next_error_errors_only: bool,
|
||||
pub sticky_lines_max: u32,
|
||||
pub sticky_lines_disabled_languages: Vec<String>,
|
||||
}
|
||||
|
||||
impl Default for CodeEditingSettings {
|
||||
@@ -351,7 +330,6 @@ impl Default for CodeEditingSettings {
|
||||
quick_doc_delay: 500,
|
||||
next_error_errors_only: true,
|
||||
sticky_lines_max: 5,
|
||||
sticky_lines_disabled_languages: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -364,11 +342,7 @@ pub struct InlayHintsSettings {
|
||||
pub parameters: bool,
|
||||
/// Hints of other kinds (chaining, closing labels…).
|
||||
pub other: bool,
|
||||
/// The Dart server's closing labels (`// Column` after a widget's closing bracket).
|
||||
pub closing_labels: bool,
|
||||
pub disabled_languages: Vec<String>,
|
||||
/// Code vision as a whole (usages, author and language-server lenses); the switches below apply while it is on.
|
||||
pub code_vision: bool,
|
||||
/// Code vision: usages above declarations.
|
||||
pub code_vision_usages: bool,
|
||||
/// Code vision: last author of a declaration (VCS blame) beside its usages.
|
||||
@@ -398,9 +372,7 @@ impl Default for InlayHintsSettings {
|
||||
types: true,
|
||||
parameters: true,
|
||||
other: true,
|
||||
closing_labels: true,
|
||||
disabled_languages: Vec::new(),
|
||||
code_vision: true,
|
||||
code_vision_usages: true,
|
||||
code_vision_author: true,
|
||||
code_vision_no_usages: true,
|
||||
@@ -445,9 +417,6 @@ pub struct TextAttributesOverride {
|
||||
pub effect: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub effect_color: Option<String>,
|
||||
/// IDEA's `ERROR_STRIPE_COLOR`: the diff overview-lane marker of a change type.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub error_stripe_color: Option<String>,
|
||||
}
|
||||
|
||||
/// Editor › Code Style › <Language> › Tabs and Indents (unset fields inherit).
|
||||
@@ -474,18 +443,6 @@ pub struct LanguageCodeStyle {
|
||||
/// Comment Code › Add a space at line comment start.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub line_comment_add_space: Option<bool>,
|
||||
/// PHP: align `=>` in multi-line arrays after formatting (other languages ignore it).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub align_key_value_pairs: Option<bool>,
|
||||
/// PHP: align `=` of consecutive assignment statements after formatting.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub align_consecutive_assignments: Option<bool>,
|
||||
/// SQL › Case › Keywords: `upper` | `lower` | `keep` (other languages ignore it).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub keyword_case: Option<String>,
|
||||
/// SQL › Case › Identifiers (unquoted names): `upper` | `lower` | `keep`.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub identifier_case: Option<String>,
|
||||
}
|
||||
|
||||
/// Editor › Code Style (General tab + per-language overrides).
|
||||
@@ -577,41 +534,3 @@ mod auto_import_tests {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod folding_tests {
|
||||
use super::{FoldingOutlineVisibility, FoldingSettings};
|
||||
|
||||
#[test]
|
||||
fn folding_outline_defaults_to_hover_for_existing_settings() {
|
||||
let settings: FoldingSettings = serde_json::from_str(r#"{"showOutline":false}"#).unwrap();
|
||||
assert!(!settings.show_outline);
|
||||
assert_eq!(settings.outline_visibility, FoldingOutlineVisibility::Hover);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn folding_outline_visibility_round_trips() {
|
||||
for mode in ["hover", "always"] {
|
||||
let json = serde_json::json!({ "outlineVisibility": mode });
|
||||
let settings: FoldingSettings = serde_json::from_value(json).unwrap();
|
||||
assert_eq!(serde_json::to_value(settings).unwrap()["outlineVisibility"], mode);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod sticky_lines_tests {
|
||||
use super::CodeEditingSettings;
|
||||
|
||||
#[test]
|
||||
fn sticky_lines_language_exclusions_round_trip_and_default_to_empty() {
|
||||
let old: CodeEditingSettings = serde_json::from_value(serde_json::json!({"stickyLinesMax": 3})).unwrap();
|
||||
assert_eq!(old.sticky_lines_max, 3);
|
||||
assert!(old.sticky_lines_disabled_languages.is_empty());
|
||||
let json = serde_json::json!(["markdown", "rust"]);
|
||||
let saved: CodeEditingSettings =
|
||||
serde_json::from_value(serde_json::json!({"stickyLinesDisabledLanguages": json})).unwrap();
|
||||
assert_eq!(saved.sticky_lines_disabled_languages, ["markdown", "rust"]);
|
||||
assert_eq!(serde_json::to_value(saved).unwrap()["stickyLinesDisabledLanguages"], json);
|
||||
}
|
||||
}
|
||||
Loaded 100 of 3725 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user