Compare commits

..
Author SHA1 Message Date
l0ng-ai 953b51b8c6 fix(debugger): show JVM values as {Type@id} summary and map entries as key -> value
The Variables view showed the Java debugger's text under its type: args = {String[]} String[0]@9, map = {HashMap} HashMap@10 size=1, and a map entry as 0 = {HashMap$Node} HashMap$Node@31 "a":"b". A JVM object now reads {String[0]@9} [] and {HashMap@10} size = 1, a map entry as "a" -> "b" without its index, and a String without its type. Inline values and the value tooltip use the same text (args: [], map: size = 1). Values from other debuggers keep their text and type.
2026-11-13 19:23:54 +08:00
3874 changed files with 58334 additions and 434899 deletions

No files matched your search

-7
View File
@@ -1,7 +0,0 @@
# Link debug builds for the oldest system we support, so Launch Services
# accepts the bundle on macOS 11. Without this a newer SDK leaves
# LC_BUILD_VERSION.minos at 12.0 and the app is refused (-10825) before main
# can load a newer WebKit. An explicitly exported MACOSX_DEPLOYMENT_TARGET
# still wins: this is only the default for local builds and CI.
[env]
MACOSX_DEPLOYMENT_TARGET = "11.0"
Binary file not shown.

Before

Width:  |  Height:  |  Size: 169 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 86 KiB

+1 -1
View File
@@ -7,7 +7,7 @@ BASEDPYRIGHT=1.40.2
RUFF=0.17.3 RUFF=0.17.3
GOPLS=v0.24.0 GOPLS=v0.24.0
JDTLS=1.63.0-202610191322 JDTLS=1.63.0-202610191322
KOTLIN_LSP=271.2085.0 KOTLIN_LSP=263.7084.0
GRADLE=8.14.3 GRADLE=8.14.3
INTELEPHENSE=1.18.5 INTELEPHENSE=1.18.5
# The JDK projects compile against (JAVA_HOME): library navigation opens its sources. # The JDK projects compile against (JAVA_HOME): library navigation opens its sources.
-41
View File
@@ -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}`);
+27 -129
View File
@@ -5,7 +5,6 @@ on:
pull_request: pull_request:
branches: [main] branches: [main]
types: [opened, synchronize, reopened] types: [opened, synchronize, reopened]
merge_group:
workflow_dispatch: workflow_dispatch:
permissions: permissions:
@@ -13,9 +12,8 @@ permissions:
concurrency: concurrency:
group: ci-${{ github.ref }} group: ci-${{ github.ref }}
# A newer push supersedes a pull request's run in progress. Runs on main and in the merge # A newer push supersedes the run in progress, on main too.
# queue finish, so a broken main shows up and the queue's required checks report. cancel-in-progress: true
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
env: env:
CARGO_TERM_COLOR: always CARGO_TERM_COLOR: always
@@ -25,7 +23,7 @@ env:
jobs: jobs:
# Which parts a pull request touches, so jobs it can't affect skip and leave the # 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: changes:
name: Changes name: Changes
runs-on: ubuntu-latest runs-on: ubuntu-latest
@@ -34,12 +32,7 @@ jobs:
pull-requests: read pull-requests: read
outputs: outputs:
rust: ${{ steps.classify.outputs.rust }} 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 }} frontend: ${{ steps.classify.outputs.frontend }}
e2e: ${{ steps.classify.outputs.e2e }}
catalog: ${{ steps.classify.outputs.catalog }}
steps: steps:
- id: classify - id: classify
env: env:
@@ -47,99 +40,49 @@ jobs:
PR: ${{ github.event.pull_request.number }} PR: ${{ github.event.pull_request.number }}
run: | run: |
set -euo pipefail set -euo pipefail
jobs="rust server plugins deny frontend e2e catalog"
if [ "$GITHUB_EVENT_NAME" != pull_request ]; then 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 exit 0
fi fi
gh api --paginate "repos/$GITHUB_REPOSITORY/pulls/$PR/files" \ gh api --paginate "repos/$GITHUB_REPOSITORY/pulls/$PR/files" \
--jq '.[] | .filename, (.previous_filename // empty)' > files.txt --jq '.[] | .filename, (.previous_filename // empty)' > files.txt
cat 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$)' 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. # 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/)' 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. # A job runs when any changed file falls outside the paths that can't affect it.
plugin_web='^plugins/official/[^/]+/web-src/' rust=false
# Paths the frontend checks never read... if grep -Ev "$docs|$web" files.txt | grep -q . || grep -Eq "$embedded" files.txt; then rust=true; fi
backend='^(crates/|src-tauri/|sdk/|wit/|java/|fixtures/|Cargo\.(toml|lock)$|deny\.toml$|rustfmt\.toml$|rust-toolchain(\.toml)?$|\.cargo/)' frontend=false
# ...except these, which frontend tests and e2e fixtures load (the crate manifests: if grep -Ev "$docs" files.txt | grep -q .; then frontend=true; fi
# scripts/smoke-paths.test.ts, through cargo metadata). echo "rust=$rust frontend=$frontend"
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$)' echo "rust=$rust" >> "$GITHUB_OUTPUT"
# What the browser app and its e2e tests are built from. echo "frontend=$frontend" >> "$GITHUB_OUTPUT"
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
rust: rust:
name: Rust (${{ matrix.os }}) name: Rust (${{ matrix.os }})
needs: changes needs: changes
if: needs.changes.outputs.rust == 'true' if: needs.changes.outputs.rust == 'true'
permissions:
contents: read
timeout-minutes: 60 timeout-minutes: 60
strategy: strategy:
fail-fast: false fail-fast: false
matrix: matrix:
os: [macos-latest, ubuntu-22.04, windows-latest] os: [macos-latest, ubuntu-22.04, windows-latest]
# Self-hosted runners (scripts/selfhost-runner) only for trusted events, and only while the runs-on: ${{ matrix.os }}
# SELFHOSTED_RUNNERS repository variable is 'true': runs-on cannot fall back when none is online.
runs-on: ${{ matrix.os == 'ubuntu-22.04' && vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || matrix.os }}
steps: steps:
- uses: actions/checkout@v5 - uses: actions/checkout@v5
- uses: pnpm/action-setup@v5 - uses: pnpm/action-setup@v5
with: { version: 11 } with: { version: 11 }
- uses: actions/setup-node@v5 - uses: actions/setup-node@v5
with: with: { node-version: 22, cache: pnpm }
node-version: 22
cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }}
package-manager-cache: ${{ runner.environment != 'self-hosted' }}
- uses: dtolnay/rust-toolchain@stable - uses: dtolnay/rust-toolchain@stable
with: { components: "clippy, rustfmt" } with: { components: "clippy, rustfmt" }
# Self-hosted runners keep persistent local Cargo caches; GitHub-hosted runners use Actions cache # Only main saves the cache (saving takes minutes on Windows); PRs restore main's.
# (only main saves it because saving takes minutes on Windows; PRs restore main's).
- uses: Swatinem/rust-cache@v2 - uses: Swatinem/rust-cache@v2
if: runner.environment != 'self-hosted'
with: with:
save-if: ${{ github.ref == 'refs/heads/main' }} 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 - uses: taiki-e/install-action@nextest
- name: Linux deps - name: Linux deps
if: runner.os == 'Linux' if: runner.os == 'Linux'
@@ -155,42 +98,17 @@ jobs:
# Test fixtures write LF files; keep Git from converting them on checkout. # Test fixtures write LF files; keep Git from converting them on checkout.
- run: git config --global core.autocrlf false - run: git config --global core.autocrlf false
- run: cargo nextest run --workspace --no-fail-fast - run: cargo nextest run --workspace --no-fail-fast
- name: Remote backend with Docker Compose # nextest ran export_bindings, which rewrites src/bindings.ts.
- name: Bindings are up to date
if: runner.os == 'Linux' if: runner.os == 'Linux'
run: | run: git diff --exit-code src/bindings.ts
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: 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): # The remote development server ships as a static Linux binary (release-build.yml):
# keep that build working. # keep that build working.
server: server:
name: Remote server (linux musl) name: Remote server (linux musl)
needs: changes needs: changes
if: needs.changes.outputs.server == 'true' if: needs.changes.outputs.rust == 'true'
timeout-minutes: 40 timeout-minutes: 40
runs-on: ubuntu-22.04 runs-on: ubuntu-22.04
steps: steps:
@@ -208,7 +126,7 @@ jobs:
plugins: plugins:
name: Plugins (SDK, official, fixtures) name: Plugins (SDK, official, fixtures)
needs: changes needs: changes
if: needs.changes.outputs.plugins == 'true' if: needs.changes.outputs.rust == 'true'
timeout-minutes: 30 timeout-minutes: 30
runs-on: ubuntu-22.04 runs-on: ubuntu-22.04
env: env:
@@ -260,7 +178,7 @@ jobs:
deny: deny:
name: Cargo deny name: Cargo deny
needs: changes needs: changes
if: needs.changes.outputs.deny == 'true' if: needs.changes.outputs.rust == 'true'
timeout-minutes: 15 timeout-minutes: 15
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
@@ -289,32 +207,12 @@ jobs:
- run: pnpm test - run: pnpm test
- run: pnpm build - 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: ubuntu-latest
steps:
- uses: actions/checkout@v5
- uses: pnpm/action-setup@v5
with: { version: 11 }
- uses: actions/setup-node@v5
with: { node-version: 22, cache: pnpm }
- run: pnpm install --frozen-lockfile
- run: pnpm vitest run src/platform/locales/textCatalog.test.ts
e2e: e2e:
name: E2E (${{ matrix.shard }}/4) name: E2E
needs: changes needs: changes
if: needs.changes.outputs.e2e == 'true' if: needs.changes.outputs.frontend == 'true'
timeout-minutes: 30 timeout-minutes: 30
runs-on: ubuntu-24.04 runs-on: ubuntu-24.04
strategy:
fail-fast: false
matrix:
shard: [1, 2, 3, 4]
# Browsers and their system libraries are preinstalled; keep the tag in step with @playwright/test. # Browsers and their system libraries are preinstalled; keep the tag in step with @playwright/test.
container: mcr.microsoft.com/playwright:v1.64.1-noble container: mcr.microsoft.com/playwright:v1.64.1-noble
steps: steps:
@@ -324,12 +222,12 @@ jobs:
- uses: actions/setup-node@v5 - uses: actions/setup-node@v5
with: { node-version: 22, cache: pnpm } with: { node-version: 22, cache: pnpm }
- run: pnpm install --frozen-lockfile - run: pnpm install --frozen-lockfile
- run: pnpm e2e --shard=${{ matrix.shard }}/4 - run: pnpm e2e
env: env:
HOME: /root HOME: /root
- uses: actions/upload-artifact@v6 - uses: actions/upload-artifact@v6
if: failure() if: failure()
with: with:
name: playwright-report-${{ matrix.shard }} name: playwright-report
path: playwright-report/ path: playwright-report/
retention-days: 7 retention-days: 7
+12 -140
View File
@@ -8,9 +8,6 @@ name: Language smoke
# (Run, Run tests, the test tree, Rerun Failed Tests): smoke/run.test.ts; and debugging its # (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, # entry point with the debugger the IDE installs (breakpoint, frames, variables, evaluate,
# Step Over, Resume): smoke/debug.test.ts. # 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: on:
push: push:
branches: [main] branches: [main]
@@ -18,37 +15,14 @@ on:
- "crates/**" - "crates/**"
- "languages/**" - "languages/**"
- "fixtures/**" - "fixtures/**"
- "java/**"
- "Cargo.toml" - "Cargo.toml"
- "Cargo.lock" - "Cargo.lock"
- "src/features/run/**" - "src/features/run/**"
- "src/features/debugger/**" - "src/features/debugger/**"
- "src/features/build-tools/**"
- "src/platform/**" - "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/**" - "smoke/**"
- "vite.config.ts"
- "tsconfig.json"
- "package.json" - "package.json"
- "pnpm-lock.yaml" - "pnpm-lock.yaml"
- "pnpm-workspace.yaml"
- "patches/**"
- ".github/workflows/language-smoke.yml" - ".github/workflows/language-smoke.yml"
- ".github/tool-versions.env" - ".github/tool-versions.env"
pull_request: pull_request:
@@ -65,113 +39,14 @@ concurrency:
env: env:
CARGO_TERM_COLOR: always CARGO_TERM_COLOR: always
CARGO_INCREMENTAL: 0 CARGO_INCREMENTAL: 0
# Line tables keep test backtraces readable and the binaries the build job hands on small.
CARGO_PROFILE_DEV_DEBUG: line-tables-only
jobs: 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
runs-on: 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 != '[]'
# The tests find the fixtures through the checkout path compiled into them (CARGO_MANIFEST_DIR),
# which is the same on every GitHub-hosted runner.
runs-on: ubuntu-22.04
timeout-minutes: 30
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
- uses: Swatinem/rust-cache@v2
with:
shared-key: language-smoke
save-if: ${{ github.ref == 'refs/heads/main' }}
- 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 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: smoke:
name: Language smoke (${{ matrix.language }}) name: Language smoke (${{ matrix.language }})
needs: [changes, build]
strategy: strategy:
fail-fast: false fail-fast: false
matrix: matrix:
language: ${{ fromJSON(needs.changes.outputs.languages) }} 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. # 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' }} runs-on: ${{ (matrix.language == 'c' || matrix.language == 'cpp') && 'ubuntu-24.04' || 'ubuntu-22.04' }}
timeout-minutes: 40 timeout-minutes: 40
@@ -181,11 +56,11 @@ jobs:
- run: grep -E '^[A-Z0-9_]+=' .github/tool-versions.env >> "$GITHUB_ENV" - run: grep -E '^[A-Z0-9_]+=' .github/tool-versions.env >> "$GITHUB_ENV"
- uses: dtolnay/rust-toolchain@stable - uses: dtolnay/rust-toolchain@stable
with: { components: "rust-analyzer, rustfmt" } with: { components: "rust-analyzer, rustfmt" }
- uses: actions/download-artifact@v6 # One build cache for every language; main saves it.
with: { name: smoke-bin } - uses: Swatinem/rust-cache@v2
- run: | with:
tar -xf smoke-bin.tar && rm smoke-bin.tar shared-key: language-smoke
mkdir -p target/debug && mv smoke-bin/openidea-server target/debug/ save-if: ${{ github.ref == 'refs/heads/main' && matrix.language == 'rust' }}
- uses: pnpm/action-setup@v4 - uses: pnpm/action-setup@v4
with: { version: 11 } with: { version: 11 }
@@ -241,20 +116,17 @@ jobs:
- if: matrix.language == 'php' - if: matrix.language == 'php'
run: npm install --global "intelephense@$INTELEPHENSE" run: npm install --global "intelephense@$INTELEPHENSE"
# The binaries from the build job, run from the crate directory as `cargo test` does. - run: cargo test --locked -p ide-host --test language_smoke --no-run
- working-directory: crates/ide-host - run: cargo test --locked -p ide-host --test language_smoke -- --ignored --exact ${{ matrix.language }}
run: ../../smoke-bin/language_smoke --ignored --exact ${{ matrix.language }}
- if: matrix.language == 'java' - if: matrix.language == 'java'
working-directory: crates/ide-host run: cargo test --locked -p ide-host --test project_smoke -- --ignored --exact maven_sync jdk
run: ../../smoke-bin/project_smoke --ignored --exact maven_sync jdk maven_launch_classpath_uses_the_runner_jdk_classifier
- if: matrix.language == 'kotlin' - if: matrix.language == 'kotlin'
working-directory: crates/ide-host run: cargo test --locked -p ide-host --test project_smoke -- --ignored --exact gradle_sync
run: ../../smoke-bin/project_smoke --ignored --exact gradle_sync
- if: matrix.language == 'python' - if: matrix.language == 'python'
working-directory: crates/ide-host run: cargo test --locked -p ide-host --test project_smoke -- --ignored --exact python_venv
run: ../../smoke-bin/project_smoke --ignored --exact python_venv
- run: pnpm install --frozen-lockfile - 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/run.test.ts -t "^${{ matrix.language }}$"
- run: pnpm smoke smoke/debug.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. # The IDE installs the debugger from GitHub releases: authenticated, against rate limits.
+119
View File
@@ -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
+20 -39
View File
@@ -1,7 +1,7 @@
name: Release build name: Release build
# Builds a tag's desktop apps, remote servers and updater manifest into its draft release # Builds a tag's desktop apps, remote servers and updater manifest into its draft release.
# (run by release.yml). # Stable releases (release.yml) and nightly builds (nightly.yml) both run it.
on: on:
workflow_call: workflow_call:
inputs: inputs:
@@ -78,7 +78,7 @@ jobs:
- uses: dtolnay/rust-toolchain@stable - uses: dtolnay/rust-toolchain@stable
with: { targets: "${{ matrix.target }}" } with: { targets: "${{ matrix.target }}" }
- uses: Swatinem/rust-cache@v2 - uses: Swatinem/rust-cache@v2
with: { key: "${{ matrix.target }}", cache-on-failure: true } with: { key: "${{ matrix.target }}" }
- name: Linux deps - name: Linux deps
if: runner.os == 'Linux' if: runner.os == 'Linux'
run: | run: |
@@ -181,7 +181,7 @@ jobs:
- uses: dtolnay/rust-toolchain@stable - uses: dtolnay/rust-toolchain@stable
with: { targets: "${{ matrix.target }}" } with: { targets: "${{ matrix.target }}" }
- uses: Swatinem/rust-cache@v2 - uses: Swatinem/rust-cache@v2
with: { key: "server-${{ matrix.target }}", cache-on-failure: true } with: { key: "server-${{ matrix.target }}" }
- name: musl toolchain - name: musl toolchain
if: runner.os == 'Linux' if: runner.os == 'Linux'
run: sudo apt-get update && sudo apt-get install -y musl-tools run: sudo apt-get update && sudo apt-get install -y musl-tools
@@ -224,17 +224,18 @@ jobs:
return; return;
} }
// Bundle suffix → updater platform keys, as tauri-action names them. // Bundle suffix → updater platform keys, as tauri-action names them.
const windows = (arch, msi, nsis) => [ // Nightly versions don't fit MSI or RPM, so those builds offer NSIS on Windows.
[msi, [`windows-${arch}`, `windows-${arch}-msi`]], const nightly = tag.includes("-nightly.");
[nsis, [`windows-${arch}-nsis`]], const windows = (arch, msi, nsis) => nightly
]; ? [[nsis, [`windows-${arch}`, `windows-${arch}-nsis`]]]
: [[msi, [`windows-${arch}`, `windows-${arch}-msi`]], [nsis, [`windows-${arch}-nsis`]]];
const kinds = [ const kinds = [
[/_aarch64\.AppImage$/, ["linux-aarch64", "linux-aarch64-appimage"]], [/_aarch64\.AppImage$/, ["linux-aarch64", "linux-aarch64-appimage"]],
[/_arm64\.deb$/, ["linux-aarch64-deb"]], [/_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\.AppImage$/, ["linux-x86_64", "linux-x86_64-appimage"]],
[/_amd64\.deb$/, ["linux-x86_64-deb"]], [/_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"]], [/_aarch64\.app\.tar\.gz$/, ["darwin-aarch64", "darwin-aarch64-app"]],
[/_x64\.app\.tar\.gz$/, ["darwin-x86_64", "darwin-x86_64-app"]], [/_x64\.app\.tar\.gz$/, ["darwin-x86_64", "darwin-x86_64-app"]],
...windows("aarch64", /_arm64_en-US\.msi$/, /_arm64-setup\.exe$/), ...windows("aarch64", /_arm64_en-US\.msi$/, /_arm64-setup\.exe$/),
@@ -261,46 +262,26 @@ jobs:
} }
// The update's notes: the release body without its Download section. That // The update's notes: the release body without its Download section. That
// section only matters on the release page, and What's new follows it. // section only matters on the release page, and What's new follows it.
// A translated section, "## 中文" added at the end of the draft before it is
// published (it runs to the next heading of its level, or the end), becomes
// `notes.zh-CN`: What's new shows it in that UI language and falls back to
// `notes`, the English rest of the body. HTML comments are dropped.
const { data: release } = await github.rest.repos.getRelease({ owner, repo, release_id }); const { data: release } = await github.rest.repos.getRelease({ owner, repo, release_id });
const languages = { "中文": "zh-CN" }; const withoutDownloadSection = (body) => {
const notesByLanguage = (body) => { const kept = [];
const parts = { "": [] };
let lang = "";
let langLevel = 0;
let skip = 0; let skip = 0;
for (const line of body.replace(/<!--[\s\S]*?-->/g, "").split(/\r?\n/)) { for (const line of body.split(/\r?\n/)) {
const heading = /^(#{1,6})\s+(.*)$/.exec(line); const heading = /^(#{1,6})\s+(.*)$/.exec(line);
if (heading) { if (heading) {
const level = heading[1].length; const level = heading[1].length;
const title = heading[2].trim(); if (!skip && level <= 3 && /^download$/i.test(heading[2].trim())) {
if (skip && level <= skip) skip = 0;
if (lang && level <= langLevel) lang = "";
if (!skip && level <= 3 && /^download$/i.test(title)) {
skip = level; skip = level;
continue; continue;
} }
if (!skip && !lang && level <= 2 && languages[title]) { if (skip && level <= skip) skip = 0;
lang = languages[title];
langLevel = level;
parts[lang] ??= [];
continue;
}
} }
if (!skip) parts[lang].push(line); if (!skip) kept.push(line);
} }
return Object.fromEntries(Object.entries(parts).map(([key, lines]) => [key, lines.join("\n").trim()])); return kept.join("\n").trim();
};
const { "": notes, ...translated } = notesByLanguage(String(release.body ?? ""));
const translations = Object.fromEntries(
Object.entries(translated).filter(([, text]) => text).map(([lang, text]) => [`notes.${lang}`, text]),
);
const manifest = {
version: tag.replace(/^v/, ""), notes, ...translations, pub_date: new Date().toISOString(), platforms,
}; };
const notes = withoutDownloadSection(String(release.body ?? ""));
const manifest = { version: tag.replace(/^v/, ""), notes, pub_date: new Date().toISOString(), platforms };
const old = assets.find((a) => a.name === "latest.json"); const old = assets.find((a) => a.name === "latest.json");
if (old) await github.rest.repos.deleteReleaseAsset({ owner, repo, asset_id: old.id }); if (old) await github.rest.repos.deleteReleaseAsset({ owner, repo, asset_id: old.id });
await github.rest.repos.uploadReleaseAsset({ await github.rest.repos.uploadReleaseAsset({
+3 -2
View File
@@ -1,7 +1,7 @@
name: Release name: Release
on: on:
push: push:
tags: ["v*"] tags: ["v*", "!v*-nightly.*"]
workflow_dispatch: workflow_dispatch:
inputs: inputs:
tag: tag:
@@ -23,6 +23,7 @@ env:
jobs: jobs:
# Creates (or reuses) one draft release that every platform build uploads into. # Creates (or reuses) one draft release that every platform build uploads into.
create-release: create-release:
if: ${{ !contains(github.event.inputs.tag || github.ref_name, '-nightly.') }}
permissions: permissions:
contents: write contents: write
runs-on: ubuntu-latest runs-on: ubuntu-latest
@@ -61,7 +62,7 @@ jobs:
core.setOutput("id", existing.id); core.setOutput("id", existing.id);
return; 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 previous = releases.find((r) => !r.draft && !r.prerelease);
const { data: notes } = await github.rest.repos.generateReleaseNotes({ const { data: notes } = await github.rest.repos.generateReleaseNotes({
owner, repo, tag_name: tag, previous_tag_name: previous?.tag_name, owner, repo, tag_name: tag, previous_tag_name: previous?.tag_name,
-1
View File
@@ -9,7 +9,6 @@
"dist", "dist",
"target", "target",
"src/bindings.ts", "src/bindings.ts",
"docs/snippets/plugin-catalog.jsx",
"evals/*/golden", "evals/*/golden",
"src/editor/core/cm/angular/parser*.ts", "src/editor/core/cm/angular/parser*.ts",
"src/editor/core/cm/jsp/parser*.ts", "src/editor/core/cm/jsp/parser*.ts",
+2 -12
View File
@@ -9,8 +9,7 @@ Visual style: dark, low-contrast greys, one cool accent
- `crates/ide-*` — backend crates; one domain each. Depend on `ide-core` for shared - `crates/ide-*` — backend crates; one domain each. Depend on `ide-core` for shared
types; never reach into another crate's internals. types; never reach into another crate's internals.
- `src-tauri/` — glue only: `state.rs` (AppState / Project), `commands/<domain>.rs` - `src-tauri/` — glue only: `state.rs` (AppState / Project), `commands/<domain>.rs`
(desktop-only commands; the adapters of `ide-host` commands are derived), `events.rs`. (thin typed IPC adapters), `events.rs`. No domain logic here.
No domain logic here.
- `src/bindings.ts` — generated by tauri-specta (`pnpm gen:bindings`). Never edit. - `src/bindings.ts` — generated by tauri-specta (`pnpm gen:bindings`). Never edit.
- `src/platform/` — ipc (`call`, `onIdeEvent`, `nextRequestId`), actions registry, - `src/platform/` — ipc (`call`, `onIdeEvent`, `nextRequestId`), actions registry,
keymap + dispatcher, context keys / `when` clauses, project store. keymap + dispatcher, context keys / `when` clauses, project store.
@@ -34,9 +33,6 @@ Visual style: dark, low-contrast greys, one cool accent
- IPC coordinates: 0-based lines, **UTF-16** columns/offsets everywhere (`ide-core::text`). - 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. - Every command returns `IdeResult<T>`; convert internal errors at the crate edge.
- Declare a command once, on its implementation: `#[command(trust = …)]` in `ide-host::ops`
plus its module's `domain!` list (Tauri adapter, server handler and bindings are derived);
desktop-only commands use `#[desktop_command(trust = …)]` and `desktop_domain!`.
- Streaming → `tauri::ipc::Channel<T>`; cancellable → UI-allocated `RequestId` + - Streaming → `tauri::ipc::Channel<T>`; cancellable → UI-allocated `RequestId` +
`cancel_request`. Backend → UI notifications → `IdeEvent` via `EventSink`. `cancel_request`. Backend → UI notifications → `IdeEvent` via `EventSink`.
- Long work never blocks the UI thread or a Tauri command thread: use - Long work never blocks the UI thread or a Tauri command thread: use
@@ -46,7 +42,6 @@ Visual style: dark, low-contrast greys, one cool accent
shortcuts live in `src/platform/keymaps/`. shortcuts live in `src/platform/keymaps/`.
- Styling: CSS Modules + tokens only (no hex literals in components). Inline SVG - 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. 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 - 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). `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. Other locales may lack entries; their UI shows the English text until a translator adds it.
@@ -73,15 +68,10 @@ Shared agent skills live in `.agents/skills/` (`.claude/skills/` links to them):
## Commands ## Commands
- Optional: `mise install` provisions the contributor toolchain; `mise tasks` lists the task aliases. - `pnpm tauri dev` — run the app with worktree isolation (Node 22.18+).
See [Development setup](docs/en/contribute/setup.mdx). The direct commands below still work without mise.
- `pnpm tauri dev` — run the app with worktree isolation. Use Node 22.22.2 or later on the 22.x line.
`pnpm dev:app` also enables the global Tauri API. `pnpm dev:status` reports `pnpm dev:app` also enables the global Tauri API. `pnpm dev:status` reports
this worktree's running MCP bridges and actual ports. this worktree's running MCP bridges and actual ports.
- `pnpm build` — typecheck + bundle frontend. - `pnpm build` — typecheck + bundle frontend.
- `pnpm dogfood:local [--build-only]` (or `mise run dogfood:local`) — build and locally install the grey-icon dogfood desktop app sharing release settings and data.
- `pnpm dogfood:remote <remote_name> [--restart | --no-restart] [--clean]` (or `mise run dogfood:remote <remote_name>`) — sync backend sources to a host from **Tools › SSH Configurations**, build `openidea-server`, and stage it for Remote Development.
- `pnpm dogfood:all <remote_name> [--restart | --no-restart]` (or `mise run dogfood:all <remote_name>`) — run `dogfood:local` and `dogfood:remote <remote_name>` in parallel.
- `cargo nextest run --workspace` (or `cargo test`), `cargo clippy --workspace --all-targets -- -D warnings`, `cargo fmt --all`. - `cargo 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 - `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). on `fixtures/` with that language's real server installed (CI: `Language smoke`, pinned versions).
Generated
+155 -333
View File
File diff suppressed because it is too large. Load diff
+3 -12
View File
@@ -5,7 +5,7 @@ members = ["crates/*", "src-tauri"]
exclude = ["sdk", "plugins"] exclude = ["sdk", "plugins"]
[workspace.package] [workspace.package]
version = "0.1.50" version = "0.1.44"
edition = "2024" edition = "2024"
rust-version = "1.96" rust-version = "1.96"
license = "Apache-2.0" license = "Apache-2.0"
@@ -38,12 +38,10 @@ ide-web = { path = "crates/ide-web" }
ide-spell = { path = "crates/ide-spell" } ide-spell = { path = "crates/ide-spell" }
ide-agent = { path = "crates/ide-agent" } ide-agent = { path = "crates/ide-agent" }
ide-clipboard = { path = "crates/ide-clipboard" } ide-clipboard = { path = "crates/ide-clipboard" }
ide-drag-out = { path = "crates/ide-drag-out" }
ide-fonts = { path = "crates/ide-fonts" } ide-fonts = { path = "crates/ide-fonts" }
ide-ssh = { path = "crates/ide-ssh" } ide-ssh = { path = "crates/ide-ssh" }
ide-remote = { path = "crates/ide-remote" } ide-remote = { path = "crates/ide-remote" }
ide-host = { path = "crates/ide-host" } ide-host = { path = "crates/ide-host" }
ide-command = { path = "crates/ide-command" }
ide-mcp = { path = "crates/ide-mcp" } ide-mcp = { path = "crates/ide-mcp" }
ide-scaffold = { path = "crates/ide-scaffold" } ide-scaffold = { path = "crates/ide-scaffold" }
ide-notebook = { path = "crates/ide-notebook" } 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-jvm-inspect = { path = "crates/ide-jvm-inspect" }
ide-jdwp = { path = "crates/ide-jdwp" } ide-jdwp = { path = "crates/ide-jdwp" }
ide-heap = { path = "crates/ide-heap" } ide-heap = { path = "crates/ide-heap" }
ide-streams = { path = "crates/ide-streams" }
# serialization & IPC typing # serialization & IPC typing
serde = { version = "1", features = ["derive"] } 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"] } tokio-util = { version = "0.7", features = ["rt"] }
parking_lot = "0.12" parking_lot = "0.12"
rayon = "1" rayon = "1"
dashmap = "6"
futures = "0.3" futures = "0.3"
tokio-tungstenite = { version = "0.28", default-features = false, features = ["connect", "__rustls-tls"] } tokio-tungstenite = { version = "0.28", default-features = false, features = ["connect", "__rustls-tls"] }
# errors & diagnostics # errors & diagnostics
thiserror = "2" thiserror = "2"
anyhow = "1"
tracing = "0.1" tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter", "fmt"] } tracing-subscriber = { version = "0.3", features = ["env-filter", "fmt"] }
@@ -91,8 +90,6 @@ dunce = "1"
dirs = "6" dirs = "6"
memmap2 = "0.9" memmap2 = "0.9"
zip = { version = "9.2.3", default-features = false, features = ["deflate"] } zip = { version = "9.2.3", default-features = false, features = ["deflate"] }
flate2 = "1"
tar = "0.4"
# search, index, language # search, index, language
grep-searcher = "0.1" grep-searcher = "0.1"
@@ -124,12 +121,6 @@ uuid = { version = "1", features = ["v4"] }
keyring = "4.2" keyring = "4.2"
keyring-core = "1" keyring-core = "1"
# proc macros
heck = "0.5"
proc-macro2 = "1"
quote = "1"
syn = { version = "2", features = ["full"] }
# testing # testing
insta = { version = "1", features = ["yaml"] } insta = { version = "1", features = ["yaml"] }
proptest = "1" proptest = "1"
+14 -5
View File
@@ -9,10 +9,6 @@
The IDE you know, rebuilt in Rust. The IDE you know, rebuilt in Rust.
</p> </p>
<p align="center">
English · <a href="README.zh-CN.md">简体中文</a> · <a href="README.tr.md">Türkçe</a>
</p>
<p align="center"> <p align="center">
<a href="https://github.com/l0ng-ai/openidea/releases/latest"><b>Download</b></a> <a href="https://github.com/l0ng-ai/openidea/releases/latest"><b>Download</b></a>
&nbsp;·&nbsp; &nbsp;·&nbsp;
@@ -23,6 +19,8 @@
<a href="#plugins">Plugins</a> <a href="#plugins">Plugins</a>
&nbsp;·&nbsp; &nbsp;·&nbsp;
<a href="#community">Community</a> <a href="#community">Community</a>
&nbsp;·&nbsp;
<a href="#sponsor">Sponsor</a>
</p> </p>
https://github.com/user-attachments/assets/234dd54c-1255-4b3a-b35c-533d78d737c0 https://github.com/user-attachments/assets/234dd54c-1255-4b3a-b35c-533d78d737c0
@@ -68,10 +66,21 @@ the [official plugins](plugins/official). The plugin API is still a preview.
- [Discord](https://discord.gg/2Zy4yn7gP) — questions, feedback and release news. - [Discord](https://discord.gg/2Zy4yn7gP) — questions, feedback and release news.
- WeChat group — scan to join: - 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.png" alt="WeChat group QR code" width="200">
- Contributing: see [CONTRIBUTING.md](CONTRIBUTING.md) and the [contributor docs](https://openidea.sh/en/contribute/setup). - Contributing: see [CONTRIBUTING.md](CONTRIBUTING.md) and the [contributor docs](https://openidea.sh/en/contribute/setup).
## Sponsor
If OpenIDEA saves you time, you can support its development with Alipay or WeChat Pay.
<table>
<tr>
<td align="center"><img src=".github/assets/sponsor-alipay.png" alt="Alipay QR code" width="200"><br>Alipay</td>
<td align="center"><img src=".github/assets/sponsor-wechat.png" alt="WeChat Pay QR code" width="200"><br>WeChat Pay</td>
</tr>
</table>
## License ## License
[Apache 2.0](LICENSE). Bundled third-party assets are listed in [`THIRD_PARTY_LICENSES.md`](THIRD_PARTY_LICENSES.md). [Apache 2.0](LICENSE). Bundled third-party assets are listed in [`THIRD_PARTY_LICENSES.md`](THIRD_PARTY_LICENSES.md).
-79
View File
@@ -1,79 +0,0 @@
<p align="center">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="src-tauri/icons/source/openidea-wordmark-dark.svg">
<img src="src-tauri/icons/source/openidea-wordmark.svg" alt="OpenIDEA" height="56">
</picture>
</p>
<p align="center">
Bildiğin IDE, Rust ile yeniden yazıldı.
</p>
<p align="center">
<a href="README.md">English</a> · <a href="README.zh-CN.md">简体中文</a> · Türkçe
</p>
<p align="center">
<a href="https://github.com/l0ng-ai/openidea/releases/latest"><b>İndir</b></a>
&nbsp;·&nbsp;
<a href="https://openidea.sh">Belgeler</a>
&nbsp;·&nbsp;
<a href="#performans-karşılaştırması">Performans</a>
&nbsp;·&nbsp;
<a href="#eklentiler">Eklentiler</a>
&nbsp;·&nbsp;
<a href="#topluluk">Topluluk</a>
</p>
https://github.com/user-attachments/assets/234dd54c-1255-4b3a-b35c-533d78d737c0
OpenIDEA, IntelliJ IDEA'nın çalışma biçimini (kısayol tuşlarını, araç pencerelerini,
her şeyi arama alışkanlığını) çekirdeği Rust ile yazılmış yerel bir uygulamaya taşır.
Editör, kod analizi, hata ayıklayıcı (debugger), Git, terminal, veritabanı ve HTTP istemcileri;
60'tan fazla dil için. macOS, Windows ve Linux sürümleri var.
## Performans karşılaştırması
[freqtrade](https://github.com/freqtrade/freqtrade) projesini (Python, ~770 dosya)
önbellekler hazırken açma, 5 çalıştırmanın ortancası:
| | OpenIDEA | IntelliJ IDEA 2026.2.3 |
| ---------------------------- | ----------------------- | ---------------------- |
| Projeyle pencerenin açılması | **0,9 sn** | 3,1 sn |
| Hazır (CPU sakinleşti) | **1,1 sn** | 13,2 sn |
| Bellek (USS, tüm işlemler) | **169 MB** | 2011 MB |
| Hazır olana kadar CPU süresi | **2,4 sn** | 47,9 sn |
| Boştayken CPU | Bir çekirdeğin **%4**'ü | Bir çekirdeğin %7'si |
| Kapanma | **0,3 sn** | 5,9 sn |
`main` dalından derlenmiş bir OpenIDEA sürümü ve varsayılan ayar ve eklentilerle IDEA;
Windows 11, 32 çekirdekli AMD, 62 GB RAM.
IDEA, Python'u daha derinlemesine analiz eder; yani "hazır" iki tarafta aynı işi ifade etmez.
İkisi de dışarıdan, aynı yöntemle ölçüldü: kendi makinende ve projelerinde denemek için
[`perf/compare`](perf/compare) klasörüne bak.
## Eklentiler
Eklentiler; eylemler, kod tamamlama, hızlı düzeltmeler, araç pencereleri, özel editörler,
temalar, dosya simgeleri ve diller ekler. Korumalı (sandbox) WebAssembly bileşenleri olarak çalışırlar;
temalar, simge temaları ve diller için hiç kod yazmak gerekmez.
Eklentileri Ayarlar › Eklentiler (Settings › Plugins) bölümünden kur ya da
`openidea-plugin new` ile kendininkini başlat. Ayrıntılar için [OpenIDEA eklentisi yazmak](https://openidea.sh/en/plugins) sayfasına ve
[resmi eklentilere](plugins/official) bak. Eklenti API'si hâlâ önizleme aşamasında.
## Topluluk
- [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">
- Katkıda bulunmak için: [CONTRIBUTING.md](CONTRIBUTING.md) ve [katkıcı belgeleri](https://openidea.sh/en/contribute/setup).
## Lisans
[Apache 2.0](LICENSE). Pakete dahil üçüncü taraf varlıklar [`THIRD_PARTY_LICENSES.md`](THIRD_PARTY_LICENSES.md) dosyasında listelenir.
<sub>JetBrains ile bağlantılı değildir. IntelliJ IDEA, JetBrains s.r.o.'nun ticari markasıdır.</sub>
-88
View File
@@ -1,88 +0,0 @@
<p align="center">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="src-tauri/icons/source/openidea-wordmark-dark.svg">
<img src="src-tauri/icons/source/openidea-wordmark.svg" alt="OpenIDEA" height="56">
</picture>
</p>
<p align="center">
你熟悉的 IDE,用 Rust 重新打造。
</p>
<p align="center">
<a href="README.md">English</a> · 简体中文
</p>
<p align="center">
<a href="https://github.com/l0ng-ai/openidea/releases/latest"><b>下载</b></a>
&nbsp;·&nbsp;
<a href="https://openidea.sh/zh">文档</a>
&nbsp;·&nbsp;
<a href="#性能对比">性能对比</a>
&nbsp;·&nbsp;
<a href="#插件">插件</a>
&nbsp;·&nbsp;
<a href="#社区">社区</a>
&nbsp;·&nbsp;
<a href="#赞助">赞助</a>
</p>
https://github.com/user-attachments/assets/234dd54c-1255-4b3a-b35c-533d78d737c0
OpenIDEA 把 IntelliJ IDEA 的使用方式(快捷键、工具窗口、随处搜索的习惯)带到一个以 Rust
为核心的原生桌面应用里。
编辑器、代码洞察、调试器、Git、终端、数据库客户端和 HTTP 客户端,支持 60 多种语言。
提供 macOS、Windows 和 Linux 版本。
## 性能对比
在缓存已预热的情况下打开 [freqtrade](https://github.com/freqtrade/freqtrade)(Python,约 770 个文件),
取 5 次运行的中位数:
| | OpenIDEA | IntelliJ IDEA 2026.2.3 |
| --------------------- | -------------- | ---------------------- |
| 显示项目窗口 | **0.9 s** | 3.1 s |
| 就绪(CPU 平稳) | **1.1 s** | 13.2 s |
| 内存(USS,所有进程) | **169 MB** | 2011 MB |
| 就绪前消耗的 CPU 时间 | **2.4 s** | 47.9 s |
| 空闲 CPU | 单核的 **4 %** | 单核的 7 % |
| 退出 | **0.3 s** | 5.9 s |
测试使用 `main` 分支的 OpenIDEA release 构建,以及默认设置和插件的 IDEA,环境为 Windows 11、
32 核 AMD、62 GB 内存。IDEA 对 Python 的分析更深入,所以两边的“就绪”并不代表完成了同样多的工作。
两者都以相同方式从外部测量:可以用 [`perf/compare`](perf/compare) 在自己的机器和项目上复现。
## 插件
插件可以添加操作、补全、快速修复、工具窗口、自定义编辑器、主题、文件图标和语言。插件以沙箱化的
WebAssembly 组件运行;主题、图标主题和语言无需编写代码。
在“设置 › 插件”中安装,或用 `openidea-plugin new` 创建自己的插件:参见
[编写 OpenIDEA 插件](https://openidea.sh/zh/plugins)和[官方插件](plugins/official)。插件 API 目前仍是预览版。
## 社区
- [Discord](https://discord.gg/2Zy4yn7gP):提问、反馈和版本发布消息。
- 微信群,扫码加入:
<img src=".github/assets/wechat-group-4.png" alt="微信群二维码" width="200">
- 参与贡献:参见 [CONTRIBUTING.md](CONTRIBUTING.md) 和[贡献者文档](https://openidea.sh/zh/contribute/setup)。
## 赞助
如果 OpenIDEA 帮你节省了时间,可以通过支付宝或微信支付支持它的开发。
<table>
<tr>
<td align="center"><img src=".github/assets/sponsor-alipay.png" alt="支付宝收款码" width="200"><br>支付宝</td>
<td align="center"><img src=".github/assets/sponsor-wechat.png" alt="微信支付收款码" width="200"><br>微信支付</td>
</tr>
</table>
## 许可证
[Apache 2.0](LICENSE)。随附的第三方资源列在 [`THIRD_PARTY_LICENSES.md`](THIRD_PARTY_LICENSES.md) 中。
<sub>与 JetBrains 无关联。IntelliJ IDEA 是 JetBrains s.r.o. 的商标。</sub>
+2 -71
View File
@@ -4,7 +4,7 @@
`src/ui/brands/*.svg` use the unmodified logo paths from `src/ui/brands/*.svg` use the unmodified logo paths from
[Simple Icons](https://github.com/simple-icons/simple-icons), retrieved through [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 ## 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`, → `maven/`); `plugins/gradle` (`icons/expui/gradle` → `toolwindows/gradle`,
`icons/expui/gradleLoadChanges` → `build/gradleLoadChanges`, `icons/expui/gradleLoadChanges` → `build/gradleLoadChanges`,
`icons/expui/gradle`, `icons/gradleSubproject` → `gradle/`); `icons/expui/gradle`, `icons/gradleSubproject` → `gradle/`);
`platform/external-system-impl` (`icons/newui/task` → `externalSystem/task`); `platform/external-system-impl` (`icons/newui/task` → `externalSystem/task`).
`platform/dvcs-impl` (`icons/new/cherryPick` → `vcs/cherryPick`).
Copyright 2000-2026 JetBrains s.r.o. and contributors. Apache License 2.0 (below). Copyright 2000-2026 JetBrains s.r.o. and contributors. Apache License 2.0 (below).
- [intellij-plugins](https://github.com/JetBrains/intellij-plugins) (each plugin - [intellij-plugins](https://github.com/JetBrains/intellij-plugins) (each plugin
carries its own licence): `protobuf/protoeditor-core` (`newui/protoFile` → 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`. 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 ## JetBrains IntelliJ Platform VCS log graph algorithms
`crates/ide-vcs/src/bek.rs` and `src/features/vcs/graph.ts` adapt the Bek ordering, `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 `(@fade.done)`), runs of text that entities split (`a && b`) parsed as one, and one
token for `{` and `}`. 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 ## nvim-treesitter queries
`crates/ide-syntax/queries/<grammar>/locals.scm` are derived from the `locals.scm` `crates/ide-syntax/queries/<grammar>/locals.scm` are derived from the `locals.scm`
-9
View File
@@ -7,8 +7,6 @@ license.workspace = true
[dependencies] [dependencies]
encoding_rs.workspace = true encoding_rs.workspace = true
base64.workspace = true
blake3.workspace = true
ide-vfs.workspace = true ide-vfs.workspace = true
ide-core.workspace = true ide-core.workspace = true
ide-mcp.workspace = true ide-mcp.workspace = true
@@ -26,10 +24,3 @@ dunce.workspace = true
uuid.workspace = true uuid.workspace = true
tempfile.workspace = true tempfile.workspace = true
which = "8" which = "8"
semver = "1"
[target.'cfg(unix)'.dependencies]
rustix = { version = "1", features = ["fs"] }
[dev-dependencies]
tokio = { workspace = true, features = ["test-util"] }
+49 -156
View File
@@ -3,207 +3,100 @@
//! `initialize` alone). //! `initialize` alone).
use super::{Conn, Dialect}; use super::{Conn, Dialect};
use crate::catalogs::Discovered;
use crate::config; use crate::config;
use crate::model::AgentConfigOption; use crate::model::AgentConfigOption;
use crate::provider::ProviderSpec; use crate::provider::ProviderSpec;
use crate::{Shared, client_info}; use crate::{Shared, client_info};
use parking_lot::Mutex; use parking_lot::Mutex;
use serde_json::{Value, json}; use serde_json::{Value, json};
use std::collections::BTreeMap;
use std::sync::Arc; use std::sync::Arc;
use std::time::Duration; 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) }; 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 /// Opens `session/new`, reads `configOptions`, and records per-model `thought_level` choices.
/// 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) -> Result<(), String> {
pub(crate) async fn run(shared: &Arc<Shared>, spec: &ProviderSpec, model: Option<&str>) -> Result<Discovered, String> {
let prefer_stored = crate::provider::prefer_stored_copilot_auth();
match run_once(shared, spec, prefer_stored, model).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;
if retry.is_ok() {
crate::provider::mark_prefer_stored_copilot_auth();
}
retry
}
other => other,
}
}
async fn run_once(
shared: &Arc<Shared>,
spec: &ProviderSpec,
strip_ambient: bool,
selected_model: Option<&str>,
) -> Result<Discovered, String> {
let root = shared.paths.project_root.clone(); let root = shared.paths.project_root.clone();
let launch = spec.clone(); let launch = spec.clone();
let launch = tokio::task::spawn_blocking({ let launch = tokio::task::spawn_blocking({
let root = root.clone(); let root = root.clone();
move || launch.resolve_for_launch_with_copilot_env(&root, strip_ambient) move || launch.resolve_for_launch(&root)
}) })
.await .await
.map_err(|e| e.to_string())??; .map_err(|e| e.to_string())?;
let cwd = dunce::canonicalize(&root).unwrap_or(root); let cwd = dunce::canonicalize(&root).unwrap_or(root);
let updates = Arc::new(DiscoveryUpdates { provider: spec.id.clone(), ..Default::default() }); let stderr: Arc<Mutex<Vec<String>>> = Arc::default();
let client = Dialect::wrap(updates.clone()); let lines = stderr.clone();
let on_stderr: Box<dyn Fn(String) + Send + Sync> = Box::new(|_| {}); let on_stderr: Box<dyn Fn(String) + Send + Sync> = Box::new(move |l| lines.lock().push(l));
let client = Dialect::wrap(Arc::new(ide_jsonrpc::NoopHandler));
let peer = (shared.connector)(&launch, &cwd, client.clone(), on_stderr) 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 conn = Conn::new(peer.clone(), client);
let work = async { 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(); let cwd_s = cwd.to_string_lossy().into_owned();
// No project MCP during discovery: Cursor can spend a long time spawning servers. // No project MCP during discovery: Cursor can spend a long time spawning servers.
let new: Value = conn let new: Value = conn
.request("session/new", json!({ "cwd": cwd_s, "mcpServers": [] }), None) .request("session/new", json!({ "cwd": cwd_s, "mcpServers": [] }), None)
.await .await
.map_err(discovery_error)?; .map_err(|e| e.to_string())?;
let mut options = config::options_of(&new); let mut options = config::options_of(&new);
config::add_client_options(&launch.id, &mut options); config::add_client_options(&launch.id, &mut options);
let model_option = options.iter().find(|o| o.category.as_deref() == Some("model")); let model_option = options.iter().find(|o| o.category.as_deref() == Some("model"));
let mut levels = BTreeMap::new(); let effort = levels_for_model_from_slice(&options);
let has_config = new.get("configOptions").is_some_and(Value::is_array); let levels: Vec<(String, Vec<AgentConfigOption>)> = match (model_option, effort) {
if has_config && let Some(model) = model_option.and_then(|o| o.current.as_ref()) { (Some(model), Some(effort)) if !model.values.is_empty() => {
levels.insert(model.clone(), levels_for_model_from_slice(&options)); model.values.iter().map(|v| (v.value.clone(), effort.clone())).collect()
} }
if let Some(selected) = selected_model (Some(model), Some(effort)) => model.current.clone().map(|m| vec![(m, effort)]).unwrap_or_default(),
&& let Some(option) = model_option.filter(|o| o.values.iter().any(|v| v.value == selected)) _ => Vec::new(),
&& !levels.contains_key(selected) };
{ let option_ids: Vec<_> = options.iter().map(|o| o.id.as_str()).collect();
let session = tracing::info!(
new.get("sessionId").and_then(Value::as_str).ok_or("The agent did not return a session ID")?; "agent {}: settings discovery got {} config option(s) {:?}, {} model effort list(s)",
let (method, mut params) = config::set_request(option, selected); launch.id,
params["sessionId"] = json!(session); options.len(),
updates.config.lock().session = Some(session.to_owned()); option_ids,
let response: Value = conn.request(method, params, None).await.map_err(discovery_error)?; levels.len()
let settings = if let Some(settings) = selected_settings(&response, selected) { );
Some(settings) shared.remember_discovered(&launch.id, &options, &[], &levels);
} else { Ok::<(), String>(())
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 commands = updates
.commands
.lock()
.clone()
.or_else(|| new.get("availableCommands").map(|_| config::commands_of(&new, &launch.id)));
Ok::<_, String>(Discovered { config: options, commands, levels })
}; };
let result = tokio::time::timeout(DISCOVER_TIMEOUT, work).await; let result = tokio::time::timeout(DISCOVER_TIMEOUT, work).await;
peer.kill(); peer.kill();
match result { match result {
Ok(result) => result, Ok(Ok(())) => Ok(()),
Err(_) => Err("the agent did not answer in time".into()), Ok(Err(e)) => Err(match stderr.lock().last() {
} Some(line) => format!("{e}: {line}"),
} None => e,
}),
#[derive(Default)] Err(_) => {
struct DiscoveryUpdates { let tail = stderr.lock().join("\n");
provider: String, if tail.is_empty() {
commands: Mutex<Option<Vec<crate::AgentCommand>>>, Err("the agent did not answer in time".into())
config: Mutex<DiscoveryConfig>, } else {
changed: tokio::sync::Notify, Err(format!("the agent did not answer in time:\n{tail}"))
}
#[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();
}
}
_ => {}
} }
} }
fn on_request(&self, method: &str, _: Value) -> Result<Value, (i64, String)> {
Err((ide_jsonrpc::codes::METHOD_NOT_FOUND, format!("unsupported discovery request {method}")))
}
} }
fn discovery_error(error: ide_jsonrpc::RpcError) -> String { fn is_thought_level(o: &AgentConfigOption) -> bool {
match error { o.category.as_deref() == Some("thought_level")
ide_jsonrpc::RpcError::Server { code, message, .. } if super::auth_required(code, &message) => { || matches!(o.id.as_str(), "effort" | "reasoning_effort" | "thinking" | "reasoning")
"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>> { fn levels_for_model_from_slice(options: &[AgentConfigOption]) -> Option<Vec<AgentConfigOption>> {
response.get("configOptions")?.as_array()?; let levels: Vec<_> = options
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
.iter() .iter()
.filter(|o| config::is_per_model_option(o)) .filter(|o| is_thought_level(o))
.cloned() .cloned()
.map(|mut o| { .map(|mut o| {
if config::is_context_option(&o.id) { if o.category.as_deref() != Some("thought_level") {
if o.category.is_none() {
o.category = Some("model_config".into());
}
} else if o.category.as_deref() != Some("thought_level") {
o.category = Some("thought_level".into()); o.category = Some("thought_level".into());
} }
o o
}) })
.collect() .collect();
(!levels.is_empty()).then_some(levels)
} }
+1 -7
View File
@@ -108,7 +108,6 @@ fn manager(dir: &Path, agent: Arc<FakeV2Agent>) -> AgentManager {
custom_agents_dir: None, custom_agents_dir: None,
home_dir: None, home_dir: None,
env_secrets: None, env_secrets: None,
catalogs: Arc::default(),
}, },
tokio::runtime::Handle::current(), tokio::runtime::Handle::current(),
connector, connector,
@@ -155,7 +154,6 @@ async fn a_task_runs_on_a_v2_agent_and_resumes_its_session() {
config: vec![AgentConfigChoice { id: "model".into(), value: "haiku".into() }], config: vec![AgentConfigChoice { id: "model".into(), value: "haiku".into() }],
isolation: Isolation::Local, isolation: Isolation::Local,
base: None, base: None,
..Default::default()
}) })
.await .await
.unwrap(); .unwrap();
@@ -203,11 +201,7 @@ async fn a_task_runs_on_a_v2_agent_and_resumes_its_session() {
let agent2 = Arc::new(FakeV2Agent::default()); let agent2 = Arc::new(FakeV2Agent::default());
let mgr2 = manager(tmp.path(), agent2.clone()); let mgr2 = manager(tmp.path(), agent2.clone());
mgr2.prompt(&task.id, text("again"), false).await.unwrap(); 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. tokio::time::sleep(Duration::from_millis(50)).await;
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;
}
wait_for(&mgr2, &task.id, AgentStatus::Ready).await; wait_for(&mgr2, &task.id, AgentStatus::Ready).await;
let entries = mgr2.entries(&task.id, None).unwrap(); let entries = mgr2.entries(&task.id, None).unwrap();
assert_eq!(summary(&entries[6..]), ["user: again", "agent: second turn"]); assert_eq!(summary(&entries[6..]), ["user: again", "agent: second turn"]);
+3 -32
View File
@@ -17,8 +17,6 @@
pub(crate) mod discover; pub(crate) mod discover;
mod normalize; mod normalize;
pub(crate) use normalize::base64 as normalize_base64;
use ide_jsonrpc::{Handler, Peer, RpcError, codes}; use ide_jsonrpc::{Handler, Peer, RpcError, codes};
use normalize::Normalizer; use normalize::Normalizer;
use parking_lot::Mutex; use parking_lot::Mutex;
@@ -27,7 +25,7 @@ use serde::de::DeserializeOwned;
use serde_json::{Value, json}; use serde_json::{Value, json};
use std::collections::HashMap; use std::collections::HashMap;
use std::sync::Arc; use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU8, Ordering}; use std::sync::atomic::{AtomicU8, Ordering};
use tokio::sync::oneshot; use tokio::sync::oneshot;
/// ACP's error code for a request that needs the user to sign in. /// ACP's error code for a request that needs the user to sign in.
@@ -60,8 +58,6 @@ fn client_capabilities() -> Value {
"terminal": false, "terminal": false,
// Subagents as sessions of their own (ACP subagents RFD; v2 baseline). // Subagents as sessions of their own (ACP subagents RFD; v2 baseline).
"subagents": {}, "subagents": {},
// Forms the agent asks the user to fill in (`elicitation/create`); not URL mode.
"elicitation": { "form": {} },
// Cursor exposes model parameters (e.g. Composer `fast`) as separate config options // Cursor exposes model parameters (e.g. Composer `fast`) as separate config options
// only when the client advertises this flag (undocumented Cursor ACP extension). // only when the client advertises this flag (undocumented Cursor ACP extension).
"_meta": { "parameterizedModelPicker": true }, "_meta": { "parameterizedModelPicker": true },
@@ -162,16 +158,9 @@ impl Negotiated {
Self { generation: 2, capabilities, agent_info: response.get("info").cloned(), auth_methods, meta } 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 /// Whether a saved session can be reopened (`session/load` on v1, `session/resume` on v2).
/// `sessionCapabilities.resume` (DeepSeek Harness), which stands in for it.
pub fn load_session(&self) -> bool { pub fn load_session(&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)
}
/// 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")
} }
/// `promptCapabilities.<name>` (`image`, `audio`, `embeddedContext`). /// `promptCapabilities.<name>` (`image`, `audio`, `embeddedContext`).
@@ -212,8 +201,6 @@ pub(crate) struct Dialect {
inner: Arc<dyn Handler>, inner: Arc<dyn Handler>,
/// 0 until `initialize` answers; then 1 or 2. /// 0 until `initialize` answers; then 1 or 2.
generation: AtomicU8, generation: AtomicU8,
/// Set by `initialize`: a v1 agent's `session/load` is sent as `session/resume`.
resume_load: AtomicBool,
normalizer: Mutex<Normalizer>, normalizer: Mutex<Normalizer>,
/// Running v2 prompts, by session id. /// Running v2 prompts, by session id.
turns: Mutex<HashMap<String, Turn>>, turns: Mutex<HashMap<String, Turn>>,
@@ -231,7 +218,6 @@ impl Dialect {
Arc::new(Self { Arc::new(Self {
inner, inner,
generation: AtomicU8::new(0), generation: AtomicU8::new(0),
resume_load: AtomicBool::new(false),
normalizer: Mutex::new(Normalizer::default()), normalizer: Mutex::new(Normalizer::default()),
turns: Mutex::new(HashMap::new()), turns: Mutex::new(HashMap::new()),
}) })
@@ -241,10 +227,6 @@ impl Dialect {
self.generation.load(Ordering::Acquire) self.generation.load(Ordering::Acquire)
} }
fn resume_load(&self) -> bool {
self.resume_load.load(Ordering::Acquire)
}
fn v2(&self) -> bool { fn v2(&self) -> bool {
self.generation() == 2 self.generation() == 2
} }
@@ -338,13 +320,6 @@ impl Handler for Dialect {
} }
self.inner.on_request(method, params) self.inner.on_request(method, params)
} }
fn on_request_raw(&self, method: &str, params: Value, raw: &[u8]) -> Result<Value, (i64, String, Option<Value>)> {
if self.v2() && method == "session/request_permission" {
return self.on_request_with_data(method, params);
}
self.inner.on_request_raw(method, params, raw)
}
} }
/// A v2 permission request with the v1 `toolCall` (its subject's, titled with the request's title). /// A v2 permission request with the v1 `toolCall` (its subject's, titled with the request's title).
@@ -394,7 +369,6 @@ impl Conn {
let response: Value = self.peer.request("initialize", initialize_params(client_info), None).await?; let response: Value = self.peer.request("initialize", initialize_params(client_info), None).await?;
let negotiated = Negotiated::from_initialize(&response); let negotiated = Negotiated::from_initialize(&response);
self.dialect.generation.store(negotiated.generation, Ordering::Release); self.dialect.generation.store(negotiated.generation, Ordering::Release);
self.dialect.resume_load.store(negotiated.resume_instead_of_load(), Ordering::Release);
Ok(negotiated) Ok(negotiated)
} }
@@ -408,9 +382,6 @@ impl Conn {
let params = serde_json::to_value(params).map_err(|e| RpcError::Protocol(e.to_string()))?; let params = serde_json::to_value(params).map_err(|e| RpcError::Protocol(e.to_string()))?;
let value = if self.dialect.v2() { let value = if self.dialect.v2() {
self.request_v2(method, params, cancel).await? 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 { } else {
self.peer.request(method, params, cancel).await? self.peer.request(method, params, cancel).await?
}; };
+1 -91
View File
@@ -97,13 +97,10 @@ fn the_negotiating_request_carries_both_versions() {
p["clientCapabilities"]["_meta"]["parameterizedModelPicker"], true, p["clientCapabilities"]["_meta"]["parameterizedModelPicker"], true,
"Cursor and similar agents need parameterized model options (e.g. fast on/off)" "Cursor and similar agents need parameterized model options (e.g. fast on/off)"
); );
// Forms only: URL mode would open pages the agent names.
assert_eq!(p["clientCapabilities"]["elicitation"], json!({ "form": {} }));
// What we sent in the capture is what claude-agent-acp negotiated v2 and v1 from. // What we sent in the capture is what claude-agent-acp negotiated v2 and v1 from.
let sent = frames(TURN, "out")[0]["params"]["clientCapabilities"].clone(); let sent = frames(TURN, "out")[0]["params"]["clientCapabilities"].clone();
let mut expected = sent; let mut expected = sent;
expected["_meta"] = p["clientCapabilities"]["_meta"].clone(); expected["_meta"] = p["clientCapabilities"]["_meta"].clone();
expected["elicitation"] = p["clientCapabilities"]["elicitation"].clone();
assert_eq!(expected, p["clientCapabilities"]); assert_eq!(expected, p["clientCapabilities"]);
} }
@@ -158,7 +155,6 @@ async fn discovery_reads_effort_and_fast_from_session_new_then_stops_the_agent()
custom_agents_dir: None, custom_agents_dir: None,
home_dir: None, home_dir: None,
env_secrets: None, env_secrets: None,
catalogs: Arc::default(),
}, },
tokio::runtime::Handle::current(), tokio::runtime::Handle::current(),
connector, connector,
@@ -171,8 +167,7 @@ async fn discovery_reads_effort_and_fast_from_session_new_then_stops_the_agent()
let fast = cursor.config.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.category.as_deref(), Some("model_config"));
assert_eq!(fast.current.as_deref(), Some("false")); assert_eq!(fast.current.as_deref(), Some("false"));
// The effort option belongs to the session's model; m2 may offer other levels. assert!(cursor.thought_levels.contains_key("m1") && cursor.thought_levels.contains_key("m2"));
assert_eq!(cursor.thought_levels.keys().collect::<Vec<_>>(), ["m1"]);
assert!(cursor.thought_levels["m1"].iter().any(|o| o.category.as_deref() == Some("thought_level"))); assert!(cursor.thought_levels["m1"].iter().any(|o| o.category.as_deref() == Some("thought_level")));
} }
@@ -180,7 +175,6 @@ async fn discovery_reads_effort_and_fast_from_session_new_then_stops_the_agent()
fn a_v2_initialize_response_reads_as_v1_capabilities() { fn a_v2_initialize_response_reads_as_v1_capabilities() {
let n = Negotiated::from_initialize(&result(TURN, 1)); let n = Negotiated::from_initialize(&result(TURN, 1));
assert_eq!(n.generation, 2); assert_eq!(n.generation, 2);
assert!(!n.resume_instead_of_load(), "v2 maps `session/load` itself");
assert!(n.load_session()); assert!(n.load_session());
assert!(n.prompt("image") && n.prompt("embeddedContext") && !n.prompt("audio")); assert!(n.prompt("image") && n.prompt("embeddedContext") && !n.prompt("audio"));
assert!(n.session("fork") && n.session("resume") && n.session("close") && n.session("delete")); assert!(n.session("fork") && n.session("resume") && n.session("close") && n.session("delete"));
@@ -682,87 +676,3 @@ fn stdio_mcp_is_v1_baseline_and_negotiated_in_v2() {
.mcp_stdio() .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"]);
}
-80
View File
@@ -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}");
}
}
}
-669
View File
@@ -1,669 +0,0 @@
//! Model availability for new tasks. Sessions own selections; discovery owns catalogs.
use crate::{
AgentCommand, AgentConfigOption, AgentEvent, AgentModelCatalog, Known, Shared, acp, config, native, provider,
};
use ide_core::{IdeError, IdeResult};
use parking_lot::Mutex;
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, HashMap};
use std::path::PathBuf;
use std::sync::{Arc, Weak};
use std::time::Duration;
use tokio::sync::watch;
use tokio::time::Instant;
const FRESH_FOR: Duration = Duration::from_secs(15 * 60);
const COOLDOWN: Duration = Duration::from_secs(30);
type Store = Arc<Mutex<HashMap<String, Known>>>;
type Key = (PathBuf, PathBuf, String);
/// Backend-wide single-flight model lookups, scoped to project and effective launch configuration.
#[derive(Default)]
pub struct AgentCatalogs {
state: Mutex<State>,
#[cfg(test)]
clock_ms: std::sync::atomic::AtomicU64,
}
#[derive(Default)]
struct State {
stores: HashMap<PathBuf, Store>,
entries: HashMap<Key, Entry>,
subscribers: Vec<Weak<Shared>>,
generation: u64,
}
struct Entry {
// Launch credentials remain only in memory, never serialized or logged.
context: LaunchContext,
generation: u64,
completed: Option<Instant>,
successful: Option<Instant>,
retry_at_ms: Option<f64>,
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 {
pub config: Vec<AgentConfigOption>,
pub thought_levels: BTreeMap<String, Vec<AgentConfigOption>>,
pub refreshed_at_ms: Option<f64>,
}
impl CatalogData {
fn model_option(&self) -> Option<&AgentConfigOption> {
self.config.iter().find(|o| o.category.as_deref() == Some("model"))
}
fn lists(&self, model: &str) -> bool {
self.model_option().is_some_and(|o| o.values.iter().any(|v| v.value == model))
}
}
#[derive(Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct SavedCatalog {
/// An opaque cryptographic digest, never raw launch arguments or credentials.
fingerprint: String,
#[serde(flatten)]
catalog: CatalogData,
}
#[derive(PartialEq)]
struct LaunchContext {
spec: provider::ProviderSpec,
executable: PathBuf,
modified: Option<std::time::SystemTime>,
len: Option<u64>,
}
impl LaunchContext {
fn new(spec: provider::ProviderSpec, root: &std::path::Path) -> Self {
let resolved = spec.clone().resolve_for_launch(root);
let executable = dunce::canonicalize(&resolved.command).unwrap_or_else(|_| PathBuf::from(&resolved.command));
let metadata = std::fs::metadata(&executable).ok();
Self {
spec,
executable,
modified: metadata.as_ref().and_then(|m| m.modified().ok()),
len: metadata.as_ref().map(std::fs::Metadata::len),
}
}
fn fingerprint(&self) -> String {
let mut hash = blake3::Hasher::new();
fn field(hash: &mut blake3::Hasher, value: &[u8]) {
hash.update(&(value.len() as u64).to_le_bytes());
hash.update(value);
}
field(&mut hash, b"openidea-model-catalog-v1");
field(
&mut hash,
match self.spec.driver {
provider::Driver::Acp => b"acp",
provider::Driver::Codex => b"codex",
provider::Driver::Claude => b"claude",
provider::Driver::Copilot => b"copilot",
},
);
field(&mut hash, self.spec.command.as_bytes());
hash.update(&(self.spec.args.len() as u64).to_le_bytes());
for arg in &self.spec.args {
field(&mut hash, arg.as_bytes());
}
hash.update(&(self.spec.env.len() as u64).to_le_bytes());
for (name, value) in &self.spec.env {
field(&mut hash, name.as_bytes());
field(&mut hash, value.as_bytes());
}
field(&mut hash, self.executable.to_string_lossy().as_bytes());
if let Some(modified) = self.modified.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()) {
hash.update(&modified.as_nanos().to_le_bytes());
}
if let Some(len) = self.len {
hash.update(&len.to_le_bytes());
}
hash.finalize().to_hex().to_string()
}
}
pub(crate) struct Discovered {
pub config: Vec<AgentConfigOption>,
pub commands: Option<Vec<AgentCommand>>,
pub levels: BTreeMap<String, Vec<AgentConfigOption>>,
}
pub(crate) struct KillPeer(pub ide_jsonrpc::Peer);
impl Drop for KillPeer {
fn drop(&mut self) {
self.0.kill();
}
}
impl AgentCatalogs {
fn now(&self) -> Instant {
let now = Instant::now();
#[cfg(test)]
let now = now + Duration::from_millis(self.clock_ms.load(std::sync::atomic::Ordering::Relaxed));
now
}
fn epoch_ms(&self) -> f64 {
let now = crate::now_ms();
#[cfg(test)]
let now = now + self.clock_ms.load(std::sync::atomic::Ordering::Relaxed) as f64;
now
}
pub(crate) fn store(&self, path: &std::path::Path) -> Store {
self.state
.lock()
.stores
.entry(path.to_path_buf())
.or_insert_with(|| {
Arc::new(Mutex::new(
std::fs::read(path).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default(),
))
})
.clone()
}
pub(crate) fn subscribe(&self, shared: &Arc<Shared>) {
let mut state = self.state.lock();
state.subscribers.retain(|s| s.strong_count() > 0);
state.subscribers.push(Arc::downgrade(shared));
}
fn key(shared: &Shared, provider: &str) -> Key {
(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 {
let cache = shared.known.lock();
cache
.get(provider)
.and_then(|known| known.catalogs.get(&shared.root_key()))
.map(|saved| saved.catalog.clone())
.unwrap_or_default()
}
pub(crate) fn cached(&self, shared: &Shared, provider: &str) -> CatalogData {
self.state
.lock()
.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();
cache.get(provider)?.catalogs.get(&shared.root_key())?.catalog.thought_levels.get(model).cloned()
}
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)
})
}
pub(crate) fn evict_if_idle(&self, shared: &Shared, provider: &str) {
let key = Self::key(shared, provider);
let mut state = self.state.lock();
if state.entries.get(&key).is_some_and(|e| e.flight.is_none()) {
state.entries.remove(&key);
}
}
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));
AgentModelCatalog {
provider: provider.to_owned(),
config: shared.config_for_new_task(catalog.config, 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()),
}
}
/// Start or join a lookup. No queued refresh can outlive the request that asked for it.
pub(crate) fn request(
self: &Arc<Self>,
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);
let now = self.now();
let mut state = self.state.lock();
let changed = state.entries.get(&key).is_none_or(|e| e.context != context);
if changed {
if let Some(abort) = state.entries.get_mut(&key).and_then(|entry| entry.abort.take()) {
abort.abort();
}
state.generation += 1;
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.fingerprint == context.fingerprint());
let age = saved
.as_ref()
.filter(|_| matching)
.and_then(|saved| saved.catalog.refreshed_at_ms)
.map(|at| self.epoch_ms() - at)
.filter(|age| *age >= 0.0 && *age < FRESH_FOR.as_millis() as f64)
.map(|age| Duration::from_secs_f64(age / 1000.0));
let successful = age.and_then(|age| now.checked_sub(age));
let completed = age.filter(|age| *age < COOLDOWN).and_then(|age| now.checked_sub(age));
let retry_at_ms = completed
.and_then(|_| saved.as_ref().and_then(|s| s.catalog.refreshed_at_ms))
.map(|at| at + COOLDOWN.as_millis() as f64);
let catalog = saved.map(|saved| {
let mut catalog = saved.catalog;
if !matching {
catalog.refreshed_at_ms = None;
catalog.thought_levels.clear();
}
catalog
});
state.entries.insert(
key.clone(),
Entry {
context,
generation,
completed,
successful,
retry_at_ms,
catalog,
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 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 {
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));
}
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 {
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 _ = done.send(true);
});
// A subscriber can re-enter and change configuration during the start event.
let mut state = self.state.lock();
if let Some(entry) = state.entries.get_mut(&key).filter(|entry| entry.generation == generation) {
if entry.flight.is_some() {
entry.abort = Some(task.abort_handle());
}
} else {
task.abort();
}
}
(snapshot, flight)
}
fn complete(
&self,
shared: &Shared,
key: Key,
generation: u64,
model: Option<String>,
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)
.map(|spec| LaunchContext::new(spec, &shared.paths.project_root));
let mut state = self.state.lock();
let Some(entry) = state.entries.get_mut(&key).filter(|e| e.generation == generation) else { return };
// Configuration may have changed without another refresh request arriving.
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;
let snapshot = self.snapshot(shared, &key.2, entry);
state.entries.remove(&key);
drop(state);
self.broadcast(shared, &snapshot);
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.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 {
config: found.config,
thought_levels: found.levels,
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 {
if catalog.lists(&model) && !catalog.thought_levels.contains_key(&model) {
catalog.thought_levels.insert(model, levels);
}
}
if let Some(commands) = found.commands {
known.commands.insert(shared.root_key(), commands);
}
known.catalogs.insert(
shared.root_key(),
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);
}
false
}
};
let snapshot = self.snapshot(shared, &key.2, entry);
drop(state);
self.broadcast(shared, &snapshot);
if success {
for subscriber in self.subscribers(shared) {
subscriber.emit(AgentEvent::Providers);
}
}
}
/// Records the efforts a session reported for a listed `model` other than the one discovery
/// read: ACP discovery opens one session, so it knows only that model's efforts.
pub(crate) fn learn_levels(&self, shared: &Shared, provider: &str, model: &str, levels: Vec<AgentConfigOption>) {
let lacks = |catalog: &CatalogData| {
catalog.lists(model)
&& catalog.model_option().and_then(|o| o.current.as_deref()) != Some(model)
&& catalog.thought_levels.get(model) != Some(&levels)
};
let key = Self::key(shared, provider);
let mut state = self.state.lock();
let mut learned = false;
if let Some(catalog) = state.entries.get_mut(&key).and_then(|e| e.catalog.as_mut()).filter(|c| lacks(c)) {
catalog.thought_levels.insert(model.to_owned(), levels.clone());
learned = true;
}
let mut cache = shared.known.lock();
if let Some(saved) = cache
.get_mut(provider)
.and_then(|known| known.catalogs.get_mut(&shared.root_key()))
.filter(|saved| lacks(&saved.catalog))
{
saved.catalog.thought_levels.insert(model.to_owned(), levels);
learned = true;
}
if !learned {
return;
}
shared.persist_known(&cache);
drop(cache);
let snapshot = state.entries.get(&key).map(|entry| self.snapshot(shared, provider, entry));
drop(state);
if let Some(snapshot) = snapshot {
self.broadcast(shared, &snapshot);
}
}
fn subscribers(&self, shared: &Shared) -> Vec<Arc<Shared>> {
self.state
.lock()
.subscribers
.iter()
.filter_map(Weak::upgrade)
.filter(|s| {
s.paths.models_file == shared.paths.models_file && s.paths.project_root == shared.paths.project_root
})
.collect()
}
fn broadcast(&self, shared: &Shared, catalog: &AgentModelCatalog) {
for subscriber in self.subscribers(shared) {
subscriber.emit(AgentEvent::ModelCatalog { catalog: catalog.clone() });
}
}
}
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> {
// 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)
}
}
async fn discover(
shared: &Arc<Shared>,
spec: provider::ProviderSpec,
model: Option<&str>,
) -> Result<Discovered, String> {
match spec.driver {
provider::Driver::Acp => acp::discover::run(shared, &spec, model).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?;
Ok(Discovered {
commands: Some(config::commands_of(
&serde_json::json!({ "availableCommands": found.commands }),
&spec.id,
)),
config: config::options_of(&serde_json::json!({ "configOptions": found.options })),
levels: found
.efforts
.into_iter()
.map(|(model, option)| {
let levels = option
.map(|o| config::options_of(&serde_json::json!({ "configOptions": [o] })))
.unwrap_or_default();
(model, levels)
})
.collect(),
})
}
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;
}
match native::copilot::discover(spec.clone(), shared.paths.project_root.clone()).await {
Ok(found) => Ok(Discovered {
commands: Some(config::commands_of(
&serde_json::json!({ "availableCommands": found.commands }),
&spec.id,
)),
config: config::options_of(&serde_json::json!({ "configOptions": found.options })),
levels: found
.per_model
.into_iter()
.map(|(model, opts)| {
let parsed = if opts.is_empty() {
Vec::new()
} else {
config::options_of(&serde_json::json!({ "configOptions": opts }))
};
(model, parsed)
})
.collect(),
}),
Err(err) if err.allow_acp_fallback => {
tracing::warn!(
"Copilot headless catalog discovery failed ({}); falling back to `copilot --acp`",
err.message
);
shared.mark_copilot_acp_fallback(&spec);
let acp_spec = native::copilot::acp_fallback_spec(&spec);
acp::discover::run(shared, &acp_spec, model).await
}
Err(err) => Err(err.message),
}
}
}
}
#[cfg(test)]
mod tests;
File diff suppressed because it is too large. Load diff
-395
View File
@@ -1,395 +0,0 @@
//! Checks and updates only the global npm installation selected by the agent launcher.
use crate::{AgentManager, AgentSource, provider};
use ide_core::{CancellationToken, IdeError, IdeResult, error::ErrorKind};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use specta::Type;
use std::{
fs, io,
path::{Path, PathBuf},
process::Command,
};
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
pub struct AgentCliOffer {
pub current: String,
pub latest: String,
pub prefix: PathBuf,
}
#[derive(Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(tag = "status", rename_all = "camelCase")]
pub enum AgentCliUpdateResult {
Available(AgentCliOffer),
Permission(AgentCliOffer),
Current { current: String },
Channel { current: String },
Updated { current: String },
Unmanaged,
Error { code: String },
}
pub(crate) fn package(id: &str) -> Option<&'static str> {
Some(match id {
"claude" => "@anthropic-ai/claude-code",
"codex" => "@openai/codex",
"gemini" => "@google/gemini-cli",
"opencode" => "opencode-ai",
"copilot" => "@github/copilot",
"qwen" => "@qwen-code/qwen-code",
"auggie" => "@augmentcode/auggie",
"qoder" => "@qoder-ai/qodercli",
"omp" => "@oh-my-pi/pi-coding-agent",
_ => return None,
})
}
impl AgentManager {
pub fn cli_update(
&self,
id: &str,
offer: Option<&AgentCliOffer>,
cancel: &CancellationToken,
) -> IdeResult<AgentCliUpdateResult> {
let spec = self.shared.spec(id).ok_or_else(|| IdeError::invalid(format!("unknown agent {id}")))?;
let (Some(pkg), Some(builtin)) = (package(id), provider::builtin_spec(id)) else {
return Ok(AgentCliUpdateResult::Unmanaged);
};
if spec.source != AgentSource::Builtin {
return Ok(AgentCliUpdateResult::Unmanaged);
}
let Ok(npm) = which::which("npm") else { return Ok(AgentCliUpdateResult::Unmanaged) };
let program = spec.resolve_for_launch(&self.shared.paths.project_root).command;
match maintain(&npm, Path::new(&program), &builtin.command, pkg, offer, cancel) {
Err(e) if e.kind == ErrorKind::Unavailable => Ok(AgentCliUpdateResult::Error { code: e.message }),
result => result,
}
}
}
struct Installation {
modules: PathBuf,
folder: PathBuf,
link: PathBuf,
}
impl Installation {
fn at(prefix: &Path, pkg: &str, bin: &str) -> Self {
let modules = prefix.join(if cfg!(windows) { "node_modules" } else { "lib/node_modules" });
let link = if cfg!(windows) { prefix.join(format!("{bin}.cmd")) } else { prefix.join("bin").join(bin) };
Self { folder: modules.join(pkg), modules, link }
}
fn version(&self, program: &Path, pkg: &str, bin: &str) -> IdeResult<Option<String>> {
if !program.is_absolute() || !self.folder.try_exists()? || !self.link.try_exists()? || !program.try_exists()? {
return Ok(None);
}
let folder = dunce::canonicalize(&self.folder)?;
if fs::symlink_metadata(&self.folder)?.is_symlink()
|| dunce::canonicalize(program)? != dunce::canonicalize(&self.link)?
{
return Ok(None);
}
let manifest = self.folder.join("package.json");
if !manifest.try_exists()? {
return Ok(None);
}
let manifest: Value = serde_json::from_slice(&fs::read(manifest)?)
.map_err(|_| IdeError::invalid("Invalid npm package manifest"))?;
let entry = manifest["bin"].as_str().or_else(|| manifest["bin"][bin].as_str());
let Some(entry) = entry.filter(|_| manifest["name"] == pkg) else { return Ok(None) };
let Some(version) = manifest["version"].as_str() else {
return Err(IdeError::invalid("Missing npm package version"));
};
let entry = folder.join(entry);
if !entry.try_exists()? {
return Ok(None);
}
let entry = dunce::canonicalize(entry)?;
if !entry.starts_with(&folder) {
return Ok(None);
}
#[cfg(unix)]
let owns = fs::symlink_metadata(&self.link)?.is_symlink() && dunce::canonicalize(&self.link)? == entry;
#[cfg(windows)]
let owns = {
let prefix = dunce::canonicalize(self.link.parent().unwrap())?;
let Ok(target) = entry.strip_prefix(prefix) else { return Ok(None) };
let needle = format!("%dp0%\\{}\"", target.display()).to_lowercase();
fs::read_to_string(&self.link)?.replace('/', "\\").to_lowercase().contains(&needle)
};
Ok(owns.then(|| version.to_owned()))
}
fn writable(&self) -> io::Result<bool> {
for dir in [&*self.folder, self.folder.parent().unwrap(), &self.modules, self.link.parent().unwrap()] {
#[cfg(unix)]
let access: io::Result<()> =
rustix::fs::accessat(rustix::fs::CWD, dir, rustix::fs::Access::WRITE_OK, rustix::fs::AtFlags::empty())
.map_err(Into::into);
#[cfg(windows)]
let access = tempfile::tempfile_in(dir).map(drop);
match access {
Err(e) if matches!(e.kind(), io::ErrorKind::PermissionDenied | io::ErrorKind::ReadOnlyFilesystem) => {
return Ok(false);
}
other => other?,
}
}
Ok(true)
}
}
fn stable(version: &str) -> Option<semver::Version> {
semver::Version::parse(version).ok().filter(|v| v.pre.is_empty() && v.build.is_empty())
}
fn maintain(
npm: &Path,
program: &Path,
bin: &str,
pkg: &str,
approved: Option<&AgentCliOffer>,
cancel: &CancellationToken,
) -> IdeResult<AgentCliUpdateResult> {
use AgentCliUpdateResult::*;
let run = |args: &[&str]| {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
let mut cmd = Command::new(npm);
cmd.args(args)
.current_dir(npm.parent().unwrap())
.env("NPM_CONFIG_UPDATE_NOTIFIER", "false")
.env("NPM_CONFIG_LOGLEVEL", "error");
ide_tools::run_streamed(cmd, cancel, &|_| {}).map_err(|e| {
if e.kind == ErrorKind::Cancelled {
return e;
}
// npm diagnostics can contain private registry URLs; expose only known codes.
let code = e
.message
.split(|c: char| !c.is_ascii_alphanumeric() && c != '_')
.find(|w| {
matches!(
*w,
"EACCES"
| "EPERM"
| "EROFS"
| "ENOTFOUND"
| "EAI_AGAIN"
| "ETIMEDOUT"
| "E404"
| "E401"
| "E403"
)
})
.unwrap_or("npm");
IdeError::unavailable(code)
})
};
let output = run(&["prefix", "-g"])?;
let prefix = Path::new(output.trim_end());
if !prefix.is_absolute() {
return Err(IdeError::invalid("Invalid npm global prefix"));
}
let installation = Installation::at(prefix, pkg, bin);
let Some(current) = installation.version(program, pkg, bin)? else { return Ok(Unmanaged) };
let latest: String = serde_json::from_str(&run(&["view", &format!("{pkg}@latest"), "version", "--json"])?)
.map_err(|_| IdeError::invalid("Invalid npm version response"))?;
let (Some(before), Some(after)) = (stable(&current), stable(&latest)) else {
return Ok(Channel { current });
};
if before >= after {
return Ok(Current { current });
}
let offer = AgentCliOffer { current, latest, prefix: prefix.to_owned() };
if !installation.writable()? {
return Ok(Permission(offer));
}
if approved != Some(&offer) {
return Ok(Available(offer));
}
run(&[
"install",
"-g",
"--prefix",
prefix.to_str().unwrap(),
"--no-audit",
"--no-fund",
&format!("{pkg}@{}", offer.latest),
])?;
if installation.version(program, pkg, bin)?.as_ref() != Some(&offer.latest) {
return Err(IdeError::invalid("npm installation verification failed"));
}
Ok(Updated { current: offer.latest })
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
use tempfile::TempDir;
const PKG: &str = "@anthropic-ai/claude-code";
struct Fixture {
root: TempDir,
install: Installation,
}
impl Fixture {
fn new() -> Self {
let root = tempfile::Builder::new().prefix("全局 prefix ").tempdir().unwrap();
let install = Installation::at(root.path(), PKG, "claude");
fs::create_dir_all(&install.folder).unwrap();
fs::create_dir_all(install.link.parent().unwrap()).unwrap();
fs::write(install.folder.join("entry.js"), "").unwrap();
#[cfg(unix)]
std::os::unix::fs::symlink(install.folder.join("entry.js"), &install.link).unwrap();
#[cfg(windows)]
fs::write(&install.link, r#"@"%dp0%\node_modules\@anthropic-ai\claude-code\entry.js""#).unwrap();
let fixture = Self { root, install };
fixture.manifest(PKG, "2.1.9");
fixture
}
fn manifest(&self, name: &str, version: &str) {
fs::write(
self.install.folder.join("package.json"),
json!({"name":name,"version":version,"bin":{"claude":"entry.js"}}).to_string(),
)
.unwrap();
}
fn version(&self) -> Option<String> {
self.install.version(&self.install.link, PKG, "claude").unwrap()
}
#[cfg(unix)]
fn npm(&self, script: &str) -> PathBuf {
use std::os::unix::fs::PermissionsExt;
let path = self.root.path().join("npm");
fs::write(&path, format!("#!/bin/sh\nset -eu\n{script}\n")).unwrap();
fs::set_permissions(&path, fs::Permissions::from_mode(0o755)).unwrap();
path
}
}
#[test]
fn requires_the_selected_install_and_its_exact_package_entry() {
let f = Fixture::new();
assert_eq!(f.version().as_deref(), Some("2.1.9"));
let other = f.root.path().join("other");
fs::write(&other, "").unwrap();
assert_eq!(f.install.version(&other, PKG, "claude").unwrap(), None);
f.manifest("other-package", "2.1.9");
assert_eq!(f.version(), None);
f.manifest(PKG, "2.1.9");
fs::remove_file(&f.install.link).unwrap();
#[cfg(unix)]
std::os::unix::fs::symlink(&other, &f.install.link).unwrap();
#[cfg(windows)]
fs::write(&f.install.link, r#"@"%dp0%\other""#).unwrap();
assert_eq!(f.version(), None);
}
#[cfg(unix)]
const NPM: &str = r#"case "$1" in
prefix) pwd -P ;;
view) cat latest ;;
install)
test "$2" = "-g" && test "$3" = "--prefix" && test "$4" = "$(pwd -P)"
test "$7" = "@anthropic-ai/[email protected]"
cp updated.json "$4/lib/node_modules/@anthropic-ai/claude-code/package.json"
touch installed ;;
*) exit 2 ;;
esac"#;
#[cfg(unix)]
#[test]
fn installs_only_the_confirmed_offer_and_rechecks_ownership() {
use AgentCliUpdateResult::*;
let f = Fixture::new();
let npm = f.npm(NPM);
let cancel = CancellationToken::new();
let run =
|offer: Option<&AgentCliOffer>| maintain(&npm, &f.install.link, "claude", PKG, offer, &cancel).unwrap();
let latest = f.root.path().join("latest");
fs::write(&latest, r#""2.1.12""#).unwrap();
let Available(offer) = run(None) else { panic!("expected an offer") };
for different in [
AgentCliOffer { prefix: PathBuf::from("/other"), ..offer.clone() },
AgentCliOffer { current: "2.0.0".into(), ..offer.clone() },
] {
assert_eq!(run(Some(&different)), Available(offer.clone()));
}
fs::write(&latest, r#""2.2.0""#).unwrap();
assert!(matches!(run(Some(&offer)), Available(new) if new.latest == "2.2.0"));
fs::write(&latest, r#""2.0.0""#).unwrap();
assert!(matches!(run(Some(&offer)), Current { .. }));
fs::write(&latest, r#""2.2.0-beta.1""#).unwrap();
assert!(matches!(run(Some(&offer)), Channel { .. }));
fs::write(&latest, r#""2.1.12""#).unwrap();
f.manifest("other-package", "2.1.9");
assert_eq!(run(Some(&offer)), Unmanaged);
assert!(!f.root.path().join("installed").exists());
f.manifest(PKG, "2.1.12");
fs::copy(f.install.folder.join("package.json"), f.root.path().join("updated.json")).unwrap();
f.manifest(PKG, "2.1.9");
assert_eq!(run(Some(&offer)), Updated { current: "2.1.12".into() });
assert!(f.root.path().join("installed").exists());
assert_eq!(run(None), Current { current: "2.1.12".into() });
}
#[cfg(unix)]
#[test]
fn permission_failure_never_starts_an_install() {
use std::os::unix::fs::PermissionsExt;
let f = Fixture::new();
let npm = f.npm(NPM);
fs::write(f.root.path().join("latest"), r#""2.1.12""#).unwrap();
let run = |offer: Option<&AgentCliOffer>| {
maintain(&npm, &f.install.link, "claude", PKG, offer, &CancellationToken::new()).unwrap()
};
let AgentCliUpdateResult::Available(offer) = run(None) else { panic!("expected an offer") };
fs::set_permissions(&f.install.folder, fs::Permissions::from_mode(0o555)).unwrap();
// root can write even when no mode bit grants write permission.
if tempfile::tempfile_in(&f.install.folder).is_err() {
assert_eq!(run(Some(&offer)), AgentCliUpdateResult::Permission(offer));
}
fs::set_permissions(&f.install.folder, fs::Permissions::from_mode(0o755)).unwrap();
assert!(!f.root.path().join("installed").exists());
}
#[cfg(unix)]
#[test]
fn cancellation_stops_a_running_npm_process() {
use std::time::{Duration, Instant};
let f = Fixture::new();
let npm = f.npm(
r#"case "$1" in
prefix) pwd -P ;;
view) echo '"2.1.12"' ;;
install) touch started; exec sleep 30 ;;
esac"#,
);
let cancel = CancellationToken::new();
let AgentCliUpdateResult::Available(offer) =
maintain(&npm, &f.install.link, "claude", PKG, None, &cancel).unwrap()
else {
panic!("expected an offer")
};
let started = f.root.path().join("started");
std::thread::scope(|s| {
let op = s.spawn(|| maintain(&npm, &f.install.link, "claude", PKG, Some(&offer), &cancel));
let deadline = Instant::now() + Duration::from_secs(5);
while !started.exists() && Instant::now() < deadline {
std::thread::sleep(Duration::from_millis(10));
}
cancel.cancel();
assert!(started.exists());
assert_eq!(op.join().unwrap().unwrap_err().kind, ErrorKind::Cancelled);
});
assert_eq!(f.version().as_deref(), Some("2.1.9"));
}
}
+12 -150
View File
@@ -3,7 +3,7 @@
use crate::model::{ use crate::model::{
AgentCommand, AgentCommandSource, AgentConfigOption, AgentConfigValue, AgentConfigVia, AgentCost, AgentLimit, AgentCommand, AgentCommandSource, AgentConfigOption, AgentConfigValue, AgentConfigVia, AgentCost, AgentLimit,
AgentModelPricing, AgentTokens, AgentUsage, AgentUsage,
}; };
use serde_json::{Value, json}; use serde_json::{Value, json};
@@ -20,24 +20,17 @@ pub(crate) fn add_client_options(provider: &str, config: &mut Vec<AgentConfigOpt
description: Some("Tool approvals for this Cursor conversation".into()), description: Some("Tool approvals for this Cursor conversation".into()),
category: Some("approval".into()), category: Some("approval".into()),
current: Some("ask".into()), current: Some("ask".into()),
default_value: Some("ask".into()),
via: AgentConfigVia::Option, via: AgentConfigVia::Option,
values: vec![ values: vec![
AgentConfigValue { AgentConfigValue {
value: "ask".into(), value: "ask".into(),
name: "Ask for approval".into(), name: "Ask for approval".into(),
description: Some("Show permission requests from Cursor".into()), description: Some("Show permission requests from Cursor".into()),
cost_category: None,
usage_multiplier: None,
pricing: None,
}, },
AgentConfigValue { AgentConfigValue {
value: "bypass".into(), value: "bypass".into(),
name: "Bypass approvals".into(), name: "Bypass approvals".into(),
description: Some("Automatically approve tool requests in this conversation".into()), description: Some("Automatically approve tool requests in this conversation".into()),
cost_category: None,
usage_multiplier: None,
pricing: None,
}, },
], ],
}); });
@@ -125,18 +118,6 @@ pub(crate) fn options_of(result: &Value) -> Vec<AgentConfigOption> {
out out
} }
pub(crate) fn is_context_option(id: &str) -> bool {
matches!(id, "context_tier" | "contextTier")
}
/// Whether an option's available values and default belong to the selected model
/// (`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"))
|| matches!(o.id.as_str(), "effort" | "reasoning_effort" | "thinking" | "reasoning")
|| is_context_option(&o.id)
}
/// A `configOptions` array; only select options are kept (the UI shows them as dropdowns). /// A `configOptions` array; only select options are kept (the UI shows them as dropdowns).
pub(crate) fn parse_options(options: &Value) -> Vec<AgentConfigOption> { pub(crate) fn parse_options(options: &Value) -> Vec<AgentConfigOption> {
let Some(list) = options.as_array() else { return Vec::new() }; let Some(list) = options.as_array() else { return Vec::new() };
@@ -152,8 +133,6 @@ pub(crate) fn parse_options(options: &Value) -> Vec<AgentConfigOption> {
None => values.extend(value_of(v)), None => values.extend(value_of(v)),
} }
} }
let current = str_of(o, "currentValue");
let default_value = str_of(o, "defaultValue").or_else(|| current.clone());
Some(AgentConfigOption { Some(AgentConfigOption {
name: str_of(o, "name").unwrap_or_else(|| id.clone()), name: str_of(o, "name").unwrap_or_else(|| id.clone()),
description: str_of(o, "description"), description: str_of(o, "description"),
@@ -164,10 +143,9 @@ pub(crate) fn parse_options(options: &Value) -> Vec<AgentConfigOption> {
matches!(id.as_str(), "effort" | "reasoning_effort" | "thinking" | "reasoning") matches!(id.as_str(), "effort" | "reasoning_effort" | "thinking" | "reasoning")
.then(|| "thought_level".into()) .then(|| "thought_level".into())
}) })
.or_else(|| (id == "fast" || is_context_option(&id)).then(|| "model_config".into())) .or_else(|| matches!(id.as_str(), "fast").then(|| "model_config".into()))
}), }),
current, current: str_of(o, "currentValue"),
default_value,
values, values,
via: AgentConfigVia::Option, via: AgentConfigVia::Option,
id, id,
@@ -177,24 +155,9 @@ pub(crate) fn parse_options(options: &Value) -> Vec<AgentConfigOption> {
} }
/// A `config_option_update`: its options replace the config-option ones; `modes` / `models` /// A `config_option_update`: its options replace the config-option ones; `modes` / `models`
/// stand-ins stay, and initial `default_value`s survive same-model option edits for Reset. /// stand-ins stay.
pub(crate) fn merge_update(config: &mut Vec<AgentConfigOption>, options: &Value) { pub(crate) fn merge_update(config: &mut Vec<AgentConfigOption>, options: &Value) {
let mut fresh = parse_options(options); let fresh = parse_options(options);
let old_model = config.iter().find(|o| o.category.as_deref() == Some("model")).and_then(|o| o.current.as_deref());
let new_model = fresh.iter().find(|o| o.category.as_deref() == Some("model")).and_then(|o| o.current.as_deref());
let same_model = old_model == new_model;
for f in &mut fresh {
if f.default_value == f.current
&& (same_model || !is_per_model_option(f))
&& let Some(prev_default) = config
.iter()
.find(|p| p.id == f.id)
.and_then(|p| p.default_value.as_ref())
.filter(|def| f.values.iter().any(|v| v.value == **def))
{
f.default_value = Some(prev_default.clone());
}
}
let covered = |o: &AgentConfigOption| fresh.iter().any(|f| f.category.is_some() && f.category == o.category); let covered = |o: &AgentConfigOption| fresh.iter().any(|f| f.category.is_some() && f.category == o.category);
config.retain(|o| o.id == CURSOR_APPROVAL || (o.via != AgentConfigVia::Option && !covered(o))); config.retain(|o| o.id == CURSOR_APPROVAL || (o.via != AgentConfigVia::Option && !covered(o)));
let legacy = std::mem::take(config); let legacy = std::mem::take(config);
@@ -219,23 +182,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`. /// `available_commands_update`.
pub(crate) fn commands_of(update: &Value, provider: &str) -> Vec<AgentCommand> { pub(crate) fn commands_of(update: &Value, provider: &str) -> Vec<AgentCommand> {
update update
@@ -272,18 +218,6 @@ pub(crate) fn usage_of(update: &Value) -> Option<AgentUsage> {
Some(AgentUsage { used: tokens("used")?, size: tokens("size").filter(|s| *s > 0)?, cost }) 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. /// The usage-limit windows a [`crate::LIMITS_UPDATE`] carries; malformed entries are skipped.
pub(crate) fn limits_of(update: &Value) -> Vec<AgentLimit> { pub(crate) fn limits_of(update: &Value) -> Vec<AgentLimit> {
let limits = update.get("limits").and_then(Value::as_array).into_iter().flatten(); let limits = update.get("limits").and_then(Value::as_array).into_iter().flatten();
@@ -317,21 +251,16 @@ fn legacy(
Some(AgentConfigValue { Some(AgentConfigValue {
name: str_of(m, "name").unwrap_or_else(|| value.clone()), name: str_of(m, "name").unwrap_or_else(|| value.clone()),
description: str_of(m, "description"), description: str_of(m, "description"),
cost_category: None,
usage_multiplier: None,
pricing: pricing_of(m),
value, value,
}) })
}) })
.collect(); .collect();
let current = str_of(v, current);
AgentConfigOption { AgentConfigOption {
id: id.to_owned(), id: id.to_owned(),
name: name.to_owned(), name: name.to_owned(),
description: None, description: None,
category: Some(id.to_owned()), category: Some(id.to_owned()),
default_value: current.clone(), current: str_of(v, current),
current,
values, values,
via, via,
} }
@@ -339,35 +268,13 @@ fn legacy(
fn value_of(v: &Value) -> Option<AgentConfigValue> { fn value_of(v: &Value) -> Option<AgentConfigValue> {
let value = v.get("value")?.as_str()?.to_owned(); let value = v.get("value")?.as_str()?.to_owned();
let meta = v.get("_meta");
let cost_category = meta
.and_then(|m| m.get("copilotPriceCategory").or_else(|| m.get("priceCategory")))
.and_then(Value::as_str)
.map(|s| s.trim().to_ascii_lowercase())
.filter(|s| !s.is_empty());
let usage_multiplier = meta
.and_then(|m| m.get("copilotUsage").or_else(|| m.get("usageMultiplier")))
.and_then(Value::as_str)
.map(str::trim)
.filter(|s| !s.is_empty())
.map(str::to_owned);
Some(AgentConfigValue { Some(AgentConfigValue {
name: str_of(v, "name").unwrap_or_else(|| value.clone()), name: str_of(v, "name").unwrap_or_else(|| value.clone()),
description: str_of(v, "description"), description: str_of(v, "description"),
cost_category,
usage_multiplier,
pricing: pricing_of(v),
value, value,
}) })
} }
fn pricing_of(v: &Value) -> Option<Box<AgentModelPricing>> {
v.pointer("/_meta/pricing")
.or_else(|| v.get("pricing"))
.and_then(|p| serde_json::from_value(p.clone()).ok())
.map(Box::new)
}
fn str_of(v: &Value, key: &str) -> Option<String> { fn str_of(v: &Value, key: &str) -> Option<String> {
v.get(key).and_then(Value::as_str).map(str::to_owned) v.get(key).and_then(Value::as_str).map(str::to_owned)
} }
@@ -380,15 +287,6 @@ mod tests {
c.iter().map(|o| (o.id.as_str(), o.current.as_deref())).collect() 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] #[test]
fn config_options_win_over_the_older_fields() { fn config_options_win_over_the_older_fields() {
let r = json!({ let r = json!({
@@ -504,53 +402,17 @@ mod tests {
#[test] #[test]
fn effort_and_fast_categories_are_inferred_from_ids() { fn effort_and_fast_categories_are_inferred_from_ids() {
let mut c = options_of(&json!({ let c = options_of(&json!({
"configOptions": [ "configOptions": [
{"id": "model", "type": "select", "currentValue": "gemini-4-carbon", {"id": "effort", "type": "select", "currentValue": "high",
"options": [{"value": "gemini-4-carbon", "name": "Gemini 4 Carbon", "options": [{"value": "low"}, {"value": "high"}]},
"description": "Powerful · Medium cost",
"_meta": {"copilotPriceCategory": "Medium", "copilotUsage": "1x"}}]},
{"id": "effort", "type": "select", "currentValue": "medium",
"options": [{"value": "low"}, {"value": "medium"}, {"value": "high"}]},
{"id": "contextTier", "type": "select", "currentValue": "default",
"options": [{"value": "default", "name": "200K"}, {"value": "long_context", "name": "1M"}]},
{"id": "fast", "type": "select", "currentValue": "false", {"id": "fast", "type": "select", "currentValue": "false",
"options": [{"value": "false", "name": "Off"}, {"value": "true", "name": "On"}]} "options": [{"value": "false", "name": "Off"}, {"value": "true", "name": "On"}]}
] ]
})); }));
assert_eq!(c.len(), 4); assert_eq!(c.len(), 2);
assert_eq!(c[0].values[0].cost_category.as_deref(), Some("medium")); assert_eq!(c[0].category.as_deref(), Some("thought_level"));
assert_eq!(c[0].values[0].usage_multiplier.as_deref(), Some("1x")); assert_eq!(c[1].category.as_deref(), Some("model_config"));
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!(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(
&mut c,
&json!([
{"id": "model", "type": "select", "currentValue": "gemini-4-carbon",
"options": [{"value": "gemini-4-carbon"}]},
{"id": "effort", "type": "select", "currentValue": "high",
"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("high"), Some("medium")));
// Switching models refreshes per-model `default_value` to the new model's default.
merge_update(
&mut c,
&json!([
{"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"}]}
]),
);
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")));
} }
#[test] #[test]
-305
View File
@@ -1,305 +0,0 @@
//! ACP elicitation in form mode: the agent's restricted JSON Schema as form fields, and the
//! user's answer as the `elicitation/create` response.
use crate::model::{AgentForm, AgentFormField, AgentFormFieldKind, AgentFormOption, AgentPermissionOption};
use serde::Deserialize;
use serde::de::{Deserializer, IgnoredAny, MapAccess, Visitor};
use serde_json::{Map, Value, json};
/// The reply that declines the form; a JSON object of field name to values accepts it, and
/// anything else cancels it.
const DECLINE: &str = "decline";
/// The form `elicitation/create` asks for; `Err` when it asks for something else.
pub(crate) fn form_of(params: &Value) -> Result<AgentForm, String> {
if params.get("mode").and_then(Value::as_str) != Some("form") {
return Err("only form elicitation is supported".to_owned());
}
let schema = params.get("requestedSchema").ok_or("requestedSchema is missing")?;
let required: Vec<&str> = schema
.get("required")
.and_then(Value::as_array)
.map(|names| names.iter().filter_map(Value::as_str).collect())
.unwrap_or_default();
let properties = schema.get("properties").and_then(Value::as_object).ok_or("requestedSchema has no properties")?;
let fields = properties
.iter()
.map(|(name, property)| field(name, property, required.contains(&name.as_str())))
.collect::<Result<_, _>>()?;
Ok(AgentForm { fields })
}
/// Orders the fields as the request's schema lists them: `Value` keeps object keys sorted, and
/// the agent's order is the one its form reads in.
pub(crate) fn in_schema_order(form: &mut AgentForm, raw: &[u8]) {
#[derive(Deserialize)]
struct Request {
params: Params,
}
#[derive(Deserialize)]
struct Params {
#[serde(rename = "requestedSchema")]
schema: Schema,
}
#[derive(Deserialize)]
struct Schema {
properties: Keys,
}
struct Keys(Vec<String>);
impl<'de> Deserialize<'de> for Keys {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
struct Visit;
impl<'de> Visitor<'de> for Visit {
type Value = Keys;
fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
f.write_str("an object")
}
fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Keys, A::Error> {
let mut keys = Vec::new();
while let Some((key, IgnoredAny)) = map.next_entry::<String, IgnoredAny>()? {
keys.push(key);
}
Ok(Keys(keys))
}
}
deserializer.deserialize_map(Visit)
}
}
let Ok(request) = serde_json::from_slice::<Request>(raw) else { return };
let order = request.params.schema.properties.0;
form.fields.sort_by_key(|field| order.iter().position(|name| *name == field.name).unwrap_or(usize::MAX));
}
fn field(name: &str, property: &Value, required: bool) -> Result<AgentFormField, String> {
let text = |key: &str| property.get(key).and_then(Value::as_str).unwrap_or_default().trim().to_owned();
let number = |key: &str| property.get(key).and_then(Value::as_f64);
let unsupported = || format!("field {name} has an unsupported schema");
let (kind, options, min, max) = match property.get("type").and_then(Value::as_str) {
Some("string") => match choices(property) {
Some(options) => (AgentFormFieldKind::Choice, options, None, None),
None => (AgentFormFieldKind::Text, Vec::new(), number("minLength"), number("maxLength")),
},
Some("number") => (AgentFormFieldKind::Number, Vec::new(), number("minimum"), number("maximum")),
Some("integer") => (AgentFormFieldKind::Integer, Vec::new(), number("minimum"), number("maximum")),
Some("boolean") => (AgentFormFieldKind::Boolean, Vec::new(), None, None),
Some("array") => {
let options = property.get("items").and_then(choices).ok_or_else(unsupported)?;
(AgentFormFieldKind::Choices, options, number("minItems"), number("maxItems"))
}
_ => return Err(unsupported()),
};
let default = match property.get("default") {
Some(Value::Array(values)) => values.iter().filter_map(scalar).collect(),
Some(value) => scalar(value).into_iter().collect(),
None => Vec::new(),
};
let title = text("title");
Ok(AgentFormField {
name: name.to_owned(),
title: if title.is_empty() { name.to_owned() } else { title },
description: text("description"),
required,
kind,
options,
default,
min,
max,
})
}
/// The values of a choice: `enum` (titled by the legacy `enumNames`), or `oneOf` / `anyOf`
/// of `{ const, title }`.
fn choices(schema: &Value) -> Option<Vec<AgentFormOption>> {
let option = |value: &str, label: Option<&str>, description: Option<&str>| AgentFormOption {
value: value.to_owned(),
label: label.filter(|l| !l.trim().is_empty()).unwrap_or(value).to_owned(),
description: description.unwrap_or_default().trim().to_owned(),
};
if let Some(values) = schema.get("enum").and_then(Value::as_array) {
let names = schema.get("enumNames").and_then(Value::as_array);
return Some(
values
.iter()
.enumerate()
.filter_map(|(i, value)| {
Some(option(value.as_str()?, names.and_then(|n| n.get(i)).and_then(Value::as_str), None))
})
.collect(),
);
}
let listed = schema.get("oneOf").or_else(|| schema.get("anyOf"))?.as_array()?;
Some(
listed
.iter()
.filter_map(|o| {
let text = |key: &str| o.get(key).and_then(Value::as_str);
Some(option(text("const")?, text("title"), text("description")))
})
.collect(),
)
}
fn scalar(value: &Value) -> Option<String> {
match value {
Value::String(text) => Some(text.clone()),
Value::Number(number) => Some(number.to_string()),
Value::Bool(flag) => Some(flag.to_string()),
_ => None,
}
}
/// A form is submitted from its own card; this option only names a declined form.
pub(crate) fn options() -> Vec<AgentPermissionOption> {
vec![AgentPermissionOption { id: DECLINE.to_owned(), name: "Decline".to_owned(), kind: "reject_once".to_owned() }]
}
/// The `elicitation/create` response to the user's `reply`, and what the conversation
/// records as chosen.
pub(crate) fn answer(form: &AgentForm, reply: Option<&str>) -> (Value, String) {
let values = match reply {
Some(DECLINE) => return (json!({ "action": "decline" }), "Decline".to_owned()),
Some(reply) => serde_json::from_str::<Map<String, Value>>(reply).ok(),
None => None,
};
let Some(values) = values else { return (json!({ "action": "cancel" }), "Cancelled".to_owned()) };
let mut content = Map::new();
let mut shown = Vec::new();
for field in &form.fields {
let given: Vec<&str> = match values.get(&field.name) {
Some(Value::Array(items)) => items.iter().filter_map(Value::as_str).collect(),
Some(Value::String(item)) => vec![item.as_str()],
_ => Vec::new(),
};
let given: Vec<&str> = given.into_iter().map(str::trim).filter(|v| !v.is_empty()).collect();
let Some(&first) = given.first() else { continue };
let value = match field.kind {
AgentFormFieldKind::Text | AgentFormFieldKind::Choice => json!(first),
AgentFormFieldKind::Number => match first.parse::<f64>() {
Ok(number) => json!(number),
Err(_) => continue,
},
AgentFormFieldKind::Integer => match first.parse::<i64>() {
Ok(number) => json!(number),
Err(_) => continue,
},
AgentFormFieldKind::Boolean => json!(first == "true"),
AgentFormFieldKind::Choices => json!(given),
};
let label = |value: &str| {
field.options.iter().find(|o| o.value == value).map_or_else(|| value.to_owned(), |o| o.label.clone())
};
let text = match field.kind {
AgentFormFieldKind::Boolean => (if first == "true" { "yes" } else { "no" }).to_owned(),
AgentFormFieldKind::Choices => given.iter().map(|v| label(v)).collect::<Vec<_>>().join(", "),
_ => label(first),
};
shown.push(format!("{}: {text}", field.title));
content.insert(field.name.clone(), value);
}
let chosen = if shown.is_empty() { "Submitted".to_owned() } else { shown.join("; ") };
(json!({ "action": "accept", "content": content }), chosen)
}
#[cfg(test)]
mod tests {
use super::*;
/// The form OMP's `ask` tool sends: a choice with a recommended default, then an
/// optional typed answer beside it.
fn ask() -> Value {
json!({
"sessionId": "s", "mode": "form", "message": "Which database?",
"requestedSchema": { "type": "object", "properties": {
"q0": { "type": "string", "title": "Which database?", "description": "Storage",
"oneOf": [{ "const": "pg", "title": "Postgres", "description": "Relational" },
{ "const": "sqlite", "title": "SQLite" }],
"default": "pg" },
"q0__other": { "type": "string", "title": "Other (type your own)" }
} }
})
}
#[test]
fn fields_follow_the_schema_order() {
let raw = br#"{ "jsonrpc": "2.0", "id": 3, "method": "elicitation/create", "params": { "mode": "form",
"requestedSchema": { "type": "object", "properties": {
"strategy": { "type": "string" }, "tests": { "type": "boolean" }, "note": { "type": "string" }
} } } }"#;
let params = serde_json::from_slice::<Value>(raw).unwrap()["params"].take();
let mut form = form_of(&params).unwrap();
in_schema_order(&mut form, raw);
assert_eq!(form.fields.iter().map(|f| f.name.as_str()).collect::<Vec<_>>(), ["strategy", "tests", "note"]);
}
#[test]
fn reads_choices_and_text_fields() {
let form = form_of(&ask()).unwrap();
let [choice, other] = form.fields.as_slice() else { panic!("{form:?}") };
assert_eq!((choice.name.as_str(), choice.kind, choice.required), ("q0", AgentFormFieldKind::Choice, false));
assert_eq!(choice.options[0].label, "Postgres");
assert_eq!(choice.options[0].description, "Relational");
assert_eq!(choice.default, ["pg"]);
assert_eq!((other.kind, other.title.as_str()), (AgentFormFieldKind::Text, "Other (type your own)"));
}
#[test]
fn reads_every_restricted_schema_kind() {
let form = form_of(&json!({ "mode": "form", "requestedSchema": {
"type": "object", "required": ["count"],
"properties": {
"count": { "type": "integer", "minimum": 1, "maximum": 5 },
"ratio": { "type": "number" },
"ok": { "type": "boolean", "default": true },
"size": { "type": "string", "enum": ["s", "l"], "enumNames": ["Small", "Large"] },
"tags": { "type": "array", "items": { "anyOf": [{ "const": "a" }, { "const": "b" }] },
"default": ["b"], "maxItems": 2 }
}
} }))
.unwrap();
let field = |name: &str| form.fields.iter().find(|f| f.name == name).unwrap();
use AgentFormFieldKind::*;
let kinds: Vec<_> = ["count", "ratio", "ok", "size", "tags"].map(|name| field(name).kind).into();
assert_eq!(kinds, [Integer, Number, Boolean, Choice, Choices]);
assert!(field("count").required && !field("ratio").required);
assert_eq!((field("count").min, field("count").max), (Some(1.0), Some(5.0)));
assert_eq!(field("ok").default, ["true"]);
assert_eq!(field("size").options[1].label, "Large");
assert_eq!((field("tags").default.as_slice(), field("tags").max), (["b".to_owned()].as_slice(), Some(2.0)));
}
#[test]
fn url_mode_and_unsupported_fields_are_refused() {
assert!(form_of(&json!({ "mode": "url", "url": "https://example.com" })).is_err());
let nested = json!({ "mode": "form", "requestedSchema": { "type": "object", "properties": {
"address": { "type": "object" }
} } });
assert!(form_of(&nested).is_err());
}
#[test]
fn an_answer_is_typed_by_its_field() {
let form = form_of(&json!({ "mode": "form", "requestedSchema": { "type": "object", "properties": {
"count": { "type": "integer" },
"ok": { "type": "boolean" },
"size": { "type": "string", "oneOf": [{ "const": "s", "title": "Small" }] },
"tags": { "type": "array", "items": { "enum": ["a", "b"] } },
"note": { "type": "string" }
} } }))
.unwrap();
let reply = json!({ "count": ["3"], "ok": ["false"], "size": ["s"], "tags": ["a", "b"], "note": [" "] });
let (response, chosen) = answer(&form, Some(&reply.to_string()));
assert_eq!(
response,
json!({ "action": "accept", "content": { "count": 3, "ok": false, "size": "s", "tags": ["a", "b"] } })
);
assert_eq!(chosen, "count: 3; ok: no; size: Small; tags: a, b");
}
#[test]
fn declining_and_dismissing_send_no_content() {
let form = form_of(&ask()).unwrap();
assert_eq!(answer(&form, Some(DECLINE)), (json!({ "action": "decline" }), "Decline".to_owned()));
assert_eq!(answer(&form, None).0, json!({ "action": "cancel" }));
assert_eq!(answer(&form, Some("cancel")).0, json!({ "action": "cancel" }));
}
}
+8 -63
View File
@@ -3,13 +3,11 @@
//! //!
//! Only the native providers keep transcripts on disk in a readable form: Claude Code //! Only the native providers keep transcripts on disk in a readable form: Claude Code
//! (`<config>/projects/*/<id>.jsonl`, see `native::claude::history`) and Codex //! (`<config>/projects/*/<id>.jsonl`, see `native::claude::history`) and Codex
//! (`<home>/.codex/sessions/**`, rollout files with a `session_meta` line, named in //! (`<home>/.codex/sessions/**`, rollout files with a `session_meta` line).
//! `<home>/.codex/session_index.jsonl`).
use super::native::claude::history; use super::native::claude::history;
use serde::Serialize; use serde::Serialize;
use specta::Type; use specta::Type;
use std::collections::HashMap;
use std::io::BufRead; use std::io::BufRead;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
@@ -134,10 +132,7 @@ fn codex_meta(line: &serde_json::Value) -> Option<(String, Option<String>)> {
let payload = let payload =
line.get("payload").filter(|p| p.get("type").and_then(serde_json::Value::as_str) == Some("session_meta")); line.get("payload").filter(|p| p.get("type").and_then(serde_json::Value::as_str) == Some("session_meta"));
let inner = payload.and_then(|p| p.get("payload")).or_else(|| { let inner = payload.and_then(|p| p.get("payload")).or_else(|| {
line.get("type") line.get("type").and_then(serde_json::Value::as_str).filter(|t| *t == "session_meta").and(Some(line))
.and_then(serde_json::Value::as_str)
.filter(|t| *t == "session_meta")
.map(|_| line.get("payload").unwrap_or(line))
})?; })?;
let id = inner.get("id").and_then(serde_json::Value::as_str)?.to_owned(); let id = inner.get("id").and_then(serde_json::Value::as_str)?.to_owned();
let cwd = inner.get("cwd").and_then(serde_json::Value::as_str).map(str::to_owned); let cwd = inner.get("cwd").and_then(serde_json::Value::as_str).map(str::to_owned);
@@ -211,39 +206,11 @@ fn rollout_files(dir: &Path, depth: usize, out: &mut Vec<PathBuf>) {
} }
} }
/// Thread names Codex keeps in `session_index.jsonl`, by thread id. A rename adds a line, /// Codex sessions of the project at `root`: `<home>/.codex/sessions/**`.
/// so the last one wins.
fn codex_names(codex_home: &Path) -> HashMap<String, String> {
let Ok(file) = std::fs::File::open(codex_home.join("session_index.jsonl")) else { return HashMap::new() };
let mut names = HashMap::new();
for line in std::io::BufReader::new(file).lines() {
let Ok(line) = line else { break };
let Ok(v) = serde_json::from_str::<serde_json::Value>(&line) else { continue };
let id = v.get("id").and_then(serde_json::Value::as_str);
let name = v.get("thread_name").and_then(serde_json::Value::as_str).map(str::trim).filter(|n| !n.is_empty());
if let (Some(id), Some(name)) = (id, name) {
names.insert(id.to_owned(), name.to_owned());
}
}
names
}
/// Codex sessions of the project at `root`: `<home>/.codex/sessions/**`, titled by their
/// thread names, else by their first prompts.
pub fn codex_sessions(codex_home: &Path, root: &Path) -> Vec<ExternalSession> { pub fn codex_sessions(codex_home: &Path, root: &Path) -> Vec<ExternalSession> {
let mut files = Vec::new(); let mut files = Vec::new();
rollout_files(&codex_home.join("sessions"), 4, &mut files); rollout_files(&codex_home.join("sessions"), 4, &mut files);
let mut sessions: Vec<ExternalSession> = files.iter().filter_map(|p| codex_file(p)).filter(|s| in_project(s.cwd.as_deref(), root)).collect()
files.iter().filter_map(|p| codex_file(p)).filter(|s| in_project(s.cwd.as_deref(), root)).collect();
if !sessions.is_empty() {
let names = codex_names(codex_home);
for s in &mut sessions {
if let Some(name) = names.get(&s.session_id) {
s.title = short(name);
}
}
}
sessions
} }
#[cfg(test)] #[cfg(test)]
@@ -296,28 +263,16 @@ mod tests {
assert_eq!(sessions[0].title, "hello there"); assert_eq!(sessions[0].title, "hello there");
} }
#[test]
fn codex_meta_accepts_current_and_legacy_shapes() {
let meta = json!({"id": "thread-1", "cwd": "/work/app"});
for line in [
json!({"type": "session_meta", "payload": meta}),
json!({"payload": {"type": "session_meta", "payload": meta}}),
json!({"type": "session_meta", "id": "thread-1", "cwd": "/work/app"}),
] {
assert_eq!(codex_meta(&line), Some(("thread-1".to_owned(), Some("/work/app".to_owned()))));
}
}
#[test] #[test]
fn lists_codex_rollouts_with_meta() { fn lists_codex_rollouts_with_meta() {
let tmp = tempfile::tempdir().unwrap(); let tmp = tempfile::tempdir().unwrap();
write( write(
&tmp.path().join("sessions/2026/01/02/rollout-01.jsonl"), &tmp.path().join("sessions/2026/01/02/rollout-01.jsonl"),
&[ &[
json!({"timestamp": "t", "type": "session_meta", json!({"timestamp": "t", "payload": {"type": "session_meta",
"payload": {"id": "thread-1", "cwd": "/work/app"}}), "payload": {"id": "thread-1", "cwd": "/work/app"}}}),
json!({"timestamp": "t", "type": "event_msg", json!({"timestamp": "t", "payload": {"type": "user_message",
"payload": {"type": "user_message", "message": "add tests"}}), "payload": {"message": "add tests"}}}),
], ],
); );
write(&tmp.path().join("sessions/notes.jsonl"), &[json!({"nope": true})]); write(&tmp.path().join("sessions/notes.jsonl"), &[json!({"nope": true})]);
@@ -327,16 +282,6 @@ mod tests {
assert_eq!((s.provider.as_str(), s.session_id.as_str()), ("codex", "thread-1")); assert_eq!((s.provider.as_str(), s.session_id.as_str()), ("codex", "thread-1"));
assert_eq!(s.title, "add tests"); assert_eq!(s.title, "add tests");
assert_eq!(s.cwd.as_deref(), Some("/work/app")); assert_eq!(s.cwd.as_deref(), Some("/work/app"));
write(
&tmp.path().join("session_index.jsonl"),
&[
json!({"id": "thread-1", "thread_name": "Add tests", "updated_at": "t1"}),
json!({"id": "thread-2", "thread_name": "Other", "updated_at": "t1"}),
json!({"id": "thread-1", "thread_name": "Add parser tests", "updated_at": "t2"}),
],
);
assert_eq!(codex_sessions(tmp.path(), Path::new("/work"))[0].title, "Add parser tests");
} }
#[test] #[test]
-111
View File
@@ -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"));
}
}
+407 -1957
View File
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+4 -409
View File
@@ -5,15 +5,6 @@ use serde::{Deserialize, Serialize};
use specta::Type; use specta::Type;
use std::collections::BTreeMap; use std::collections::BTreeMap;
/// Why a task needs the user's attention (native / in-app notify).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum AgentAttentionReason {
Finished,
Input,
Failed,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
pub enum AgentStatus { pub enum AgentStatus {
@@ -45,17 +36,14 @@ pub struct AgentCapabilities {
pub steer: bool, pub steer: bool,
/// It reports its background tasks and stops them one by one. /// It reports its background tasks and stops them one by one.
pub background_tasks: bool, pub background_tasks: bool,
/// The connected agent can report a breakdown of its context window.
pub context_usage: bool,
} }
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)] #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
pub enum Isolation { pub enum Isolation {
/// A new git worktree on its own branch. /// A new git worktree on its own branch.
Worktree, Worktree,
/// The project's own checkout. /// The project's own checkout.
#[default]
Local, Local,
} }
@@ -107,35 +95,6 @@ pub struct AgentTask {
// Boxed so that `AgentEvent::Task` stays within clippy's `large_enum_variant` bound on Windows. // Boxed so that `AgentEvent::Task` stays within clippy's `large_enum_variant` bound on Windows.
#[serde(default)] #[serde(default)]
pub background: Box<Vec<AgentBackgroundTask>>, pub background: Box<Vec<AgentBackgroundTask>>,
/// 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. /// A task the agent runs in the background while the conversation goes on.
@@ -161,40 +120,6 @@ pub struct AgentRetry {
pub error: Option<String>, pub error: Option<String>,
} }
/// Token pricing (Credits per 1M tokens) and context window capacity for one tier.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentTokenPricing {
pub input: f64,
pub output: f64,
#[serde(default)]
#[specta(optional)]
pub cache_read: Option<f64>,
#[serde(default)]
#[specta(optional)]
pub cache_write: Option<f64>,
#[serde(default)]
#[specta(optional)]
pub context_tokens: Option<u32>,
}
/// Pricing and context-tier metadata attached to a model [`AgentConfigValue`].
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentModelPricing {
/// `"low"`, `"medium"`, `"high"`, or `"very_high"`.
#[serde(default)]
#[specta(optional)]
pub cost_tier: Option<String>,
/// Request-based billing multiplier (e.g. `1.0`, `0.33`, `3.0`), when applicable.
#[serde(default)]
#[specta(optional)]
pub multiplier: Option<f64>,
/// Token pricing keyed by context tier (`"default"`, `"long_context"`).
#[serde(default)]
pub tiers: BTreeMap<String, AgentTokenPricing>,
}
/// One value of a select-type session setting. /// One value of a select-type session setting.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
@@ -202,18 +127,6 @@ pub struct AgentConfigValue {
pub value: String, pub value: String,
pub name: String, pub name: String,
pub description: Option<String>, pub description: Option<String>,
/// Relative cost category from ACP `_meta` (`copilotPriceCategory`, e.g. `low`, `medium`, `high`, `very_high`).
#[serde(default)]
#[specta(optional)]
pub cost_category: Option<String>,
/// Usage multiplier from ACP `_meta` (`copilotUsage`, e.g. `1x`, `0x`, `3x`).
#[serde(default)]
#[specta(optional)]
pub usage_multiplier: Option<String>,
/// Detailed per-tier token pricing from `_meta.pricing` when available.
#[serde(default)]
#[specta(optional)]
pub pricing: Option<Box<AgentModelPricing>>,
} }
/// How a setting is changed. /// How a setting is changed.
@@ -239,10 +152,6 @@ pub struct AgentConfigOption {
/// ACP category: `model`, `mode`, `thought_level`, or agent-specific. /// ACP category: `model`, `mode`, `thought_level`, or agent-specific.
pub category: Option<String>, pub category: Option<String>,
pub current: Option<String>, pub current: Option<String>,
/// Initial default value reported by the agent, preserved across session updates for Reset.
#[serde(default)]
#[specta(optional)]
pub default_value: Option<String>,
pub values: Vec<AgentConfigValue>, pub values: Vec<AgentConfigValue>,
pub via: AgentConfigVia, pub via: AgentConfigVia,
} }
@@ -280,24 +189,6 @@ pub struct AgentUsage {
pub cost: Option<Box<AgentCost>>, 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)] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
pub struct AgentCost { pub struct AgentCost {
@@ -327,22 +218,6 @@ pub struct AgentImage {
pub name: Option<String>, 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. /// A message to the agent: text, plus files to look at and images.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)] #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
@@ -438,59 +313,6 @@ pub struct AgentQuestionOption {
pub preview: Option<String>, pub preview: Option<String>,
} }
/// A form the agent asks the user to fill in (ACP `elicitation/create`, form mode).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentForm {
pub fields: Vec<AgentFormField>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentFormField {
/// The property name the answer is keyed by.
pub name: String,
pub title: String,
#[serde(default)]
pub description: String,
#[serde(default)]
pub required: bool,
pub kind: AgentFormFieldKind,
/// The choices of a `choice` or `choices` field.
#[serde(default)]
pub options: Vec<AgentFormOption>,
/// The initial answer: option values, a text, a number, or `true` / `false`.
#[serde(default)]
pub default: Vec<String>,
/// Bounds: the number of a `number` / `integer`, the length of a `text`, the count of `choices`.
#[serde(default)]
pub min: Option<f64>,
#[serde(default)]
pub max: Option<f64>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum AgentFormFieldKind {
Text,
Number,
Integer,
Boolean,
/// One of `options`.
Choice,
/// Any of `options`.
Choices,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentFormOption {
pub value: String,
pub label: String,
#[serde(default)]
pub description: String,
}
/// One item of a task's conversation. /// One item of a task's conversation.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(tag = "type", rename_all = "camelCase", rename_all_fields = "camelCase")] #[serde(tag = "type", rename_all = "camelCase", rename_all_fields = "camelCase")]
@@ -515,19 +337,8 @@ pub enum AgentEntry {
Agent { Agent {
text: String, 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 { Thought {
text: String, text: String,
/// When the reasoning started (ms since the epoch); `None` in tasks saved before.
#[serde(default)]
started_ms: Option<f64>,
}, },
Tool { Tool {
id: String, id: String,
@@ -536,17 +347,9 @@ pub enum AgentEntry {
kind: String, kind: String,
status: AgentToolStatus, status: AgentToolStatus,
locations: Vec<IpcPath>, 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. /// Text the tool reported (command output…), truncated.
output: Option<String>, output: Option<String>,
diffs: Vec<AgentToolDiff>, 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 { Plan {
items: Vec<AgentPlanItem>, items: Vec<AgentPlanItem>,
@@ -590,10 +393,6 @@ pub enum AgentEntry {
/// of question to answer instead of an option. /// of question to answer instead of an option.
#[serde(default)] #[serde(default)]
questions: Vec<AgentQuestion>, questions: Vec<AgentQuestion>,
/// Set when the agent asks for a form (ACP elicitation); answered with a JSON object of
/// field name to its values, `decline`, or nothing to cancel.
#[serde(default)]
form: Option<AgentForm>,
/// Name of the chosen option, or `None` while pending. Cancelled requests read "Cancelled". /// Name of the chosen option, or `None` while pending. Cancelled requests read "Cancelled".
chosen: Option<String>, chosen: Option<String>,
}, },
@@ -620,9 +419,6 @@ pub struct AgentProvider {
pub command_read_only_reason: Option<AgentCommandReadOnlyReason>, pub command_read_only_reason: Option<AgentCommandReadOnlyReason>,
/// Whether the command was found (on `PATH`). /// Whether the command was found (on `PATH`).
pub installed: bool, 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). /// Environment variables it starts with (from its agent file).
pub env: BTreeMap<String, String>, pub env: BTreeMap<String, String>,
/// Settings (models, modes…) the agent offered last time it ran; empty before its first session. /// Settings (models, modes…) the agent offered last time it ran; empty before its first session.
@@ -677,7 +473,7 @@ pub struct AgentProbe {
pub error: Option<String>, pub error: Option<String>,
} }
#[derive(Clone, Debug, Default, Serialize, Deserialize, Type)] #[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
pub struct NewAgentTask { pub struct NewAgentTask {
/// Validated by the host; defaults to the window project root. /// Validated by the host; defaults to the window project root.
@@ -690,16 +486,6 @@ pub struct NewAgentTask {
pub isolation: Isolation, pub isolation: Isolation,
/// Branch to start the worktree from; the current branch when `None`. /// Branch to start the worktree from; the current branch when `None`.
pub base: Option<String>, pub base: Option<String>,
/// 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 /// A file the task changed: against [`AgentTask::base_commit`], or against `HEAD` in the
@@ -714,8 +500,6 @@ pub struct AgentChange {
pub removed: u32, pub removed: u32,
/// Path before a rename; the left side of its diff reads this path. /// Path before a rename; the left side of its diff reads this path.
pub old_path: Option<String>, 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. /// A commit made while the task ran, with the files it changed against its first parent.
@@ -741,8 +525,6 @@ pub enum AgentChangesView {
SinceStart, SinceStart,
/// The uncommitted files against `HEAD`; commits made since the start stay. /// The uncommitted files against `HEAD`; commits made since the start stay.
Group, 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. /// A task's uncommitted files and the commits made since it started.
@@ -756,26 +538,13 @@ pub struct AgentChanges {
pub commits: Vec<AgentCommit>, pub commits: Vec<AgentCommit>,
} }
/// Authoritative choices for new tasks, independent of any running session's settings. /// Streamed to the window that subscribed (`AgentManager::subscribe`).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentModelCatalog {
pub provider: String,
pub config: Vec<AgentConfigOption>,
pub thought_levels: BTreeMap<String, Vec<AgentConfigOption>>,
pub refreshing: bool,
pub refreshed_at_ms: Option<f64>,
pub retry_at_ms: Option<f64>,
pub error: Option<String>,
}
/// Streamed to the window that subscribed (`AgentManager::subscribe_as`).
#[derive(Clone, Debug, Serialize, Type)] #[derive(Clone, Debug, Serialize, Type)]
#[serde(tag = "type", rename_all = "camelCase", rename_all_fields = "camelCase")] #[serde(tag = "type", rename_all = "camelCase", rename_all_fields = "camelCase")]
pub enum AgentEvent { pub enum AgentEvent {
/// A task was created or its metadata changed. /// A task was created or its metadata changed.
Task { Task {
task: Box<AgentTask>, task: AgentTask,
}, },
Removed { Removed {
id: String, id: String,
@@ -806,18 +575,8 @@ pub enum AgentEvent {
provider: String, provider: String,
limits: Vec<AgentLimit>, limits: Vec<AgentLimit>,
}, },
/// A model lookup started or completed, including unsuccessful lookups.
ModelCatalog {
catalog: AgentModelCatalog,
},
/// The installed or configured agent providers changed. /// The installed or configured agent providers changed.
Providers, Providers,
/// The task needs attention once (finished turn, explicit input, or failure).
Attention {
task: String,
event_id: String,
reason: AgentAttentionReason,
},
} }
pub use ide_core::settings::{AgentMcpServer, McpTransport}; pub use ide_core::settings::{AgentMcpServer, McpTransport};
@@ -855,9 +614,6 @@ pub struct McpServer {
/// Agent provider ids this server is enabled for; empty means enabled for all agents. /// Agent provider ids this server is enabled for; empty means enabled for all agents.
#[serde(default)] #[serde(default)]
pub agents: Vec<String>, pub agents: Vec<String>,
/// True when this Workspace server was added outside OpenIDEA and has not been approved yet.
#[serde(default)]
pub unapproved: bool,
} }
/// Payload for creating or updating a user or workspace MCP server. /// Payload for creating or updating a user or workspace MCP server.
@@ -890,167 +646,6 @@ fn default_true() -> bool {
true 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")]
pub struct McpExternalSource {
/// Stable source identifier (e.g. `"copilot-cli"`, `"jetbrains-air"`, `"claude-code"`, `"cursor"`, `"workspace-mcp"`, `"vscode-mcp"`).
pub id: String,
/// Human-readable source label (e.g. `"GitHub Copilot CLI"`).
pub label: String,
/// Absolute path of the discovered configuration file.
pub path: IpcPath,
/// Suggested target scope when importing this source into OpenIDEA settings.
pub suggested_scope: McpScope,
/// Agent provider ID this external CLI reads natively (`Some("copilot")`, `Some("claude")`, `Some("cursor")`, or `None`).
pub native_provider: Option<String>,
/// Servers found inside this external configuration file (values omitted for safety; imported directly on the host).
pub servers: Vec<McpDiscoveredServer>,
}
/// Summary of one server discovered inside an external MCP configuration file.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct McpDiscoveredServer {
pub name: String,
pub transport: McpTransport,
pub enabled: bool,
pub command: Option<String>,
pub args: Vec<String>,
pub url: Option<String>,
/// Environment variable names declared on this server (values stay on the host).
pub env_keys: Vec<String>,
/// HTTP header names declared on this server (values stay on the host).
pub header_keys: Vec<String>,
}
/// Selection of one server from an external MCP configuration source to import.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct McpImportSelection {
pub source_id: String,
pub name: String,
}
/// One tool advertised by an MCP server during `tools/list`.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct McpToolSummary {
pub name: String,
pub description: Option<String>,
}
/// Result of testing/probing an MCP server (`initialize` + `tools/list`).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct McpProbeResult {
pub ok: bool,
pub server_name: Option<String>,
pub server_version: Option<String>,
pub protocol_version: Option<String>,
pub tools: Vec<McpToolSummary>,
pub duration_ms: u32,
pub error: Option<String>,
}
/// Payload for creating a custom ACP agent (always the ACP driver); the id /// Payload for creating a custom ACP agent (always the ACP driver); the id
/// becomes the `<config>/agents/<id>.toml` file name. /// becomes the `<config>/agents/<id>.toml` file name.
#[derive(Clone, Debug, Deserialize, Type)] #[derive(Clone, Debug, Deserialize, Type)]
@@ -158,42 +158,6 @@ pub(crate) fn title(entries: &[Value]) -> Option<String> {
.map(str::to_owned) .map(str::to_owned)
} }
/// Claude Code titles a session from the last 1000 characters of its text.
const TITLE_SOURCE_CHARS: usize = 1000;
/// Below this Claude Code gives no title without asking the model.
const TITLE_SOURCE_MIN_CHARS: usize = 10;
/// The conversation's own text to title the session after: the prompts and the replies,
/// without the files attached to the prompts. `None` while there is too little.
pub(super) fn title_source(entries: &[Value]) -> Option<String> {
let mut text = String::new();
for e in chain(entries, None) {
if !(is_turn_start(e) || kind(e) == "assistant") {
continue;
}
let blocks = match e.pointer("/message/content") {
Some(Value::String(s)) => vec![s.as_str()],
Some(Value::Array(blocks)) => blocks
.iter()
.filter(|b| b.get("type").and_then(Value::as_str) == Some("text"))
.filter_map(|b| b.get("text").and_then(Value::as_str))
.filter(|t| !t.starts_with("\n<context ref="))
.collect(),
_ => Vec::new(),
};
for block in blocks {
text.push_str(block);
text.push('\n');
}
}
let text = text.trim();
let len = text.chars().count();
if len < TITLE_SOURCE_MIN_CHARS {
return None;
}
Some(text.chars().skip(len.saturating_sub(TITLE_SOURCE_CHARS)).collect())
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
@@ -255,29 +219,6 @@ mod tests {
assert_eq!(cut(&c, 1), Ok(None)); assert_eq!(cut(&c, 1), Ok(None));
} }
#[test]
fn titles_come_from_prompts_and_replies() {
let mut prompt = user("u1", None, "Fix the login form");
prompt["message"]["content"]
.as_array_mut()
.unwrap()
.push(json!({"type": "text", "text": "\n<context ref=\"file:///p/a.rs\">\nfn a() {}\n</context>"}));
let entries = vec![
prompt,
assistant(
"a1",
"u1",
json!([{"type": "thinking", "thinking": "hm"}, {"type": "text", "text": "Done."},
{"type": "tool_use", "id": "t1", "name": "Bash", "input": {}}]),
),
json!({"type": "user", "uuid": "r1", "parentUuid": "a1", "message": {"content": [{"type": "tool_result", "tool_use_id": "t1", "content": "out"}]}}),
];
assert_eq!(title_source(&entries).as_deref(), Some("Fix the login form\nDone."));
assert_eq!(title_source(&[user("u1", None, "hi")]), None);
let long = "x".repeat(TITLE_SOURCE_CHARS + 5);
assert_eq!(title_source(&[user("u1", None, &long)]).map(|t| t.chars().count()), Some(TITLE_SOURCE_CHARS));
}
#[test] #[test]
fn project_directory_names() { fn project_directory_names() {
assert_eq!(escape(Path::new("/private/tmp/a.b/c_d")), "-private-tmp-a-b-c-d"); assert_eq!(escape(Path::new("/private/tmp/a.b/c_d")), "-private-tmp-a-b-c-d");
+23 -154
View File
@@ -85,8 +85,6 @@ pub(crate) async fn discover(spec: ProviderSpec, cwd: PathBuf) -> Result<Discove
let (spec, cwd) = spec.await.map_err(|e| e.to_string())?; let (spec, cwd) = spec.await.map_err(|e| e.to_string())?;
let mut args = spec.args; let mut args = spec.args;
args.extend(Start::New { id: uuid::Uuid::new_v4().to_string() }.args()); args.extend(Start::New { id: uuid::Uuid::new_v4().to_string() }.args());
// Metadata discovery must not launch project-configured MCP servers.
args.extend(["--strict-mcp-config".into(), "--mcp-config".into(), "{\"mcpServers\":{}}".into()]);
let launch = Launch { program: spec.command, args, cwd, env: spec.env }; let launch = Launch { program: spec.command, args, cwd, env: spec.env };
let mut io = cli::Process.launch(&launch, Arc::new(|_| {})).map_err(|e| e.to_string())?; let mut io = cli::Process.launch(&launch, Arc::new(|_| {})).map_err(|e| e.to_string())?;
let _stop = io.kill.clone().drop_guard(); let _stop = io.kill.clone().drop_guard();
@@ -170,14 +168,6 @@ struct Session {
id: String, id: String,
cwd: PathBuf, cwd: PathBuf,
mcp_config: Option<tempfile::TempPath>, 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>, shim: Weak<Shim>,
st: Mutex<State>, st: Mutex<State>,
/// Serializes (re)starting the process. /// Serializes (re)starting the process.
@@ -201,8 +191,6 @@ struct State {
limit_resets_ms: Option<f64>, limit_resets_ms: Option<f64>,
terminal_only: Vec<String>, terminal_only: Vec<String>,
titled: bool, titled: bool,
/// A title is being read or generated.
titling: bool,
} }
struct Turn { struct Turn {
@@ -352,24 +340,18 @@ impl Shim {
cwd: PathBuf, cwd: PathBuf,
start: Start, start: Start,
pending: bool, pending: bool,
params: &Value, mcp_config: Option<String>,
) -> Arc<Session> { ) -> Arc<Session> {
let mcp_off = mcp_off(params); let mcp_config = mcp_config.and_then(|json| match write_mcp_config(&json) {
let mcp_config = mcp_config(params).and_then(|json| match write_mcp_config(&json) {
Ok(path) => Some(path), Ok(path) => Some(path),
Err(e) => { Err(e) => {
tracing::warn!("Claude Code session {id}: cannot write its MCP configuration: {e}"); tracing::warn!("Claude Code session {id}: cannot write its MCP configuration: {e}");
None None
} }
}); });
let skills = params.pointer("/_meta/openidea/skills");
let session = Arc::new(Session { let session = Arc::new(Session {
id: id.to_owned(), id: id.to_owned(),
mcp_config, 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), shim: Arc::downgrade(self),
st: Mutex::new(State { st: Mutex::new(State {
proc: None, proc: None,
@@ -383,7 +365,6 @@ impl Shim {
limit_resets_ms: None, limit_resets_ms: None,
terminal_only: Vec::new(), terminal_only: Vec::new(),
titled: false, titled: false,
titling: false,
}), }),
cwd, cwd,
starting: tokio::sync::Mutex::new(()), starting: tokio::sync::Mutex::new(()),
@@ -415,9 +396,9 @@ impl Shim {
"agentCapabilities": { "agentCapabilities": {
"loadSession": true, "loadSession": true,
"promptCapabilities": { "image": true, "embeddedContext": true }, "promptCapabilities": { "image": true, "embeddedContext": true },
"sessionCapabilities": { "fork": {}, "additionalDirectories": {} }, "sessionCapabilities": { "fork": {} },
"mcpCapabilities": { "stdio": true, "http": true, "sse": true }, "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() }, "agentInfo": { "name": "claude", "title": "Claude Code", "version": self.version() },
"authMethods": [], "authMethods": [],
@@ -425,8 +406,13 @@ impl Shim {
} }
"session/new" => { "session/new" => {
let id = new_uuid(false); let id = new_uuid(false);
let session = let session = self.add_session(
self.add_session(&id, self.cwd_of(&params), Start::New { id: id.clone() }, false, &params); &id,
self.cwd_of(&params),
Start::New { id: id.clone() },
false,
mcp_config(&params),
);
rt.block_on(session.ensure()).map_err(|e| self.start_error(&session, e))?; rt.block_on(session.ensure()).map_err(|e| self.start_error(&session, e))?;
session.announce_commands(); session.announce_commands();
Ok(json!({ "sessionId": id, "configOptions": session.st.lock().settings.options() })) Ok(json!({ "sessionId": id, "configOptions": session.st.lock().settings.options() }))
@@ -442,7 +428,7 @@ impl Shim {
None => return Err(invalid(format!("no Claude Code session {id} in {}", cwd.display()))), None => return Err(invalid(format!("no Claude Code session {id} in {}", cwd.display()))),
}; };
let chain = self.base_chain(&cwd, &start).map_err(internal)?; let chain = self.base_chain(&cwd, &start).map_err(internal)?;
let session = self.add_session(id, cwd, start, pending, &params); let session = self.add_session(id, cwd, start, pending, mcp_config(&params));
rt.block_on(session.ensure()).map_err(|e| self.start_error(&session, e))?; rt.block_on(session.ensure()).map_err(|e| self.start_error(&session, e))?;
if method == "session/load" { if method == "session/load" {
session.replay(&chain); session.replay(&chain);
@@ -468,7 +454,7 @@ impl Shim {
(start, st.settings.clone()) (start, st.settings.clone())
}; };
self.save_pending(&id, Some(&start)); self.save_pending(&id, Some(&start));
let session = self.add_session(&id, source.cwd.clone(), start, true, &params); let session = self.add_session(&id, source.cwd.clone(), start, true, mcp_config(&params));
session.st.lock().settings = settings; session.st.lock().settings = settings;
let options = session.st.lock().settings.options(); let options = session.st.lock().settings.options();
Ok(json!({ "sessionId": id, "configOptions": options })) Ok(json!({ "sessionId": id, "configOptions": options }))
@@ -502,11 +488,6 @@ impl Shim {
session.steer(params.get("prompt").cloned().unwrap_or_default()).map_err(invalid)?; session.steer(params.get("prompt").cloned().unwrap_or_default()).map_err(invalid)?;
Ok(json!({})) Ok(json!({}))
} }
"_openidea/context_usage" => {
let session = self.session(&params)?;
let proc = session.st.lock().proc.clone().ok_or_else(|| internal("Claude Code is not running"))?;
rt.block_on(proc.control(json!({ "subtype": "get_context_usage" }))).map_err(internal)
}
"_openidea/stop_task" => { "_openidea/stop_task" => {
let session = self.session(&params)?; let session = self.session(&params)?;
let task = params.get("taskId").and_then(Value::as_str).ok_or_else(|| invalid("no taskId"))?; let task = params.get("taskId").and_then(Value::as_str).ok_or_else(|| invalid("no taskId"))?;
@@ -602,12 +583,11 @@ impl Shim {
impl super::Shim for Shim { impl super::Shim for Shim {
fn attach(&self, client: Peer) { fn attach(&self, client: Peer) {
let _ = self.client.set(client.clone()); let _ = self.client.set(client.clone());
// The client went away: so do the processes. Held until then: the connection drops // The client went away: so do the processes.
// its handler (this shim) as it closes, and the sessions would go without stopping. let weak = self.me.clone();
let me = self.me.upgrade();
tokio::spawn(async move { tokio::spawn(async move {
client.closed().await; client.closed().await;
if let Some(me) = me { if let Some(me) = weak.upgrade() {
me.closed.store(true, Ordering::Release); me.closed.store(true, Ordering::Release);
let sessions: Vec<Arc<Session>> = me.sessions.lock().drain().map(|(_, s)| s).collect(); let sessions: Vec<Arc<Session>> = me.sessions.lock().drain().map(|(_, s)| s).collect();
for s in sessions { for s in sessions {
@@ -618,15 +598,6 @@ impl super::Shim for Shim {
} }
} }
impl Drop for Session {
/// A session dropped without being stopped (the shim went away) takes its process along.
fn drop(&mut self) {
if let Some(p) = self.st.get_mut().proc.take() {
p.kill.cancel();
}
}
}
impl Session { impl Session {
fn shim(&self) -> Option<Arc<Shim>> { fn shim(&self) -> Option<Arc<Shim>> {
self.shim.upgrade() self.shim.upgrade()
@@ -680,20 +651,6 @@ impl Session {
if let Some(config) = &self.mcp_config { if let Some(config) = &self.mcp_config {
args.extend(["--mcp-config".to_owned(), config.to_string_lossy().into_owned()]); 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()); args.extend(start.args());
let launch = let launch =
Launch { program: shim.config.program.clone(), args, cwd: self.cwd.clone(), env: shim.config.env.clone() }; Launch { program: shim.config.program.clone(), args, cwd: self.cwd.clone(), env: shim.config.env.clone() };
@@ -1007,16 +964,11 @@ impl Session {
let mut updates = Vec::new(); let mut updates = Vec::new();
let mut finished = None; let mut finished = None;
let mut read_title = false; let mut read_title = false;
let mut refresh_usage = false;
{ {
let mut st = self.st.lock(); let mut st = self.st.lock();
let st = &mut *st; let st = &mut *st;
match kind { match kind {
"system" => match msg.get("subtype").and_then(Value::as_str) { "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") => { Some("init") => {
st.terminal_only = strings(msg.get("terminal_slash_commands")); st.terminal_only = strings(msg.get("terminal_slash_commands"));
} }
@@ -1096,8 +1048,7 @@ impl Session {
} else if matches!(st.start, Start::New { .. }) { } else if matches!(st.start, Start::New { .. }) {
st.start = Start::Resume { id: self.id.clone(), at: None }; st.start = Start::Resume { id: self.id.clone(), at: None };
} }
read_title = !st.titled && !st.titling; read_title = !st.titled;
st.titling |= read_title;
if let Some(turn) = st.turn.as_ref() if let Some(turn) = st.turn.as_ref()
&& belongs(turn, &msg) && belongs(turn, &msg)
{ {
@@ -1120,56 +1071,15 @@ impl Session {
if read_title { if read_title {
self.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 /// Sends the title Claude Code gave the session, once it has one.
/// 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
/// Claude Code is asked for, as it titles no session run the way the Agent SDK runs it.
/// Without a title the next turn tries again.
fn read_title(self: &Arc<Self>) { fn read_title(self: &Arc<Self>) {
let me = self.clone(); let me = self.clone();
tokio::spawn(async move { tokio::task::spawn_blocking(move || {
let reader = me.clone(); let Some(title) = chain_title(&me) else { return };
let entries = tokio::task::spawn_blocking(move || transcript_entries(&reader)).await.ok().flatten(); me.st.lock().titled = true;
let mut title = entries.as_deref().and_then(history::title); if let Some(shim) = me.shim() {
if title.is_none()
&& let Some(source) = entries.as_deref().and_then(history::title_source)
{
title = me.generate_title(source).await;
}
{
let mut st = me.st.lock();
st.titling = false;
if title.is_none() {
return;
}
st.titled = true;
}
if let (Some(title), Some(shim)) = (title, me.shim()) {
shim.notify(vec![Update { shim.notify(vec![Update {
session: me.id.clone(), session: me.id.clone(),
update: json!({ "sessionUpdate": "session_info_update", "title": title }), update: json!({ "sessionUpdate": "session_info_update", "title": title }),
@@ -1178,19 +1088,6 @@ impl Session {
}); });
} }
/// A title Claude Code generates from `source`, also written to the transcript.
async fn generate_title(&self, source: String) -> Option<String> {
let proc = self.st.lock().proc.clone()?;
let request = json!({ "subtype": "generate_session_title", "description": source, "persist": true });
match proc.control(request).await {
Ok(r) => r.get("title").and_then(Value::as_str).map(str::trim).filter(|t| !t.is_empty()).map(str::to_owned),
Err(e) => {
tracing::debug!("generating a claude session title: {e}");
None
}
}
}
async fn on_cli_request(self: &Arc<Self>, proc: &Arc<Proc>, msg: Value) { async fn on_cli_request(self: &Arc<Self>, proc: &Arc<Proc>, msg: Value) {
let id = msg.get("request_id").and_then(Value::as_str).unwrap_or_default().to_owned(); let id = msg.get("request_id").and_then(Value::as_str).unwrap_or_default().to_owned();
let request = msg.get("request").cloned().unwrap_or_default(); let request = msg.get("request").cloned().unwrap_or_default();
@@ -1520,13 +1417,9 @@ fn strings(v: Option<&Value>) -> Vec<String> {
/// The title in a session's transcript (or that of the session it continues). /// The title in a session's transcript (or that of the session it continues).
fn chain_title(session: &Session) -> Option<String> { fn chain_title(session: &Session) -> Option<String> {
history::title(&transcript_entries(session)?)
}
fn transcript_entries(session: &Session) -> Option<Vec<Value>> {
let shim = session.shim()?; let shim = session.shim()?;
let path = shim.transcript(&session.cwd, &session.id).filter(|p| p.exists())?; let path = shim.transcript(&session.cwd, &session.id).filter(|p| p.exists())?;
history::read(&path).ok() history::title(&history::read(&path).ok()?)
} }
fn start_json(start: &Start) -> Value { fn start_json(start: &Start) -> Value {
@@ -1555,30 +1448,6 @@ fn write_mcp_config(json: &str) -> std::io::Result<tempfile::TempPath> {
Ok(file.into_temp_path()) 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). /// ACP `mcpServers` as Claude Code's `--mcp-config` JSON (`None` when there are none).
fn mcp_config(params: &Value) -> Option<String> { fn mcp_config(params: &Value) -> Option<String> {
let servers = params.get("mcpServers")?.as_array()?; let servers = params.get("mcpServers")?.as_array()?;
+2 -22
View File
@@ -48,17 +48,10 @@ impl Settings {
.filter_map(|m| { .filter_map(|m| {
let s = |k: &str| m.get(k).and_then(Value::as_str).map(str::to_owned); let s = |k: &str| m.get(k).and_then(Value::as_str).map(str::to_owned);
let value = s("value")?; 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 { Some(Model {
name, name: s("displayName").unwrap_or_else(|| value.clone()),
description: s("description"), description: s("description"),
resolved, resolved: s("resolvedModel"),
efforts: if m.get("supportsEffort").and_then(Value::as_bool) == Some(true) { efforts: if m.get("supportsEffort").and_then(Value::as_bool) == Some(true) {
m.get("supportedEffortLevels") m.get("supportedEffortLevels")
.and_then(Value::as_array) .and_then(Value::as_array)
@@ -237,19 +230,6 @@ mod tests {
assert_eq!(s.model, "claude-x-1"); 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] #[test]
fn options_follow_the_model() { fn options_follow_the_model() {
let mut s = Settings::from_cli(&init(), &json!({"applied": {"model": "claude-sonnet-5-5", "effort": "high"}})); let mut s = Settings::from_cli(&init(), &json!({"applied": {"model": "claude-sonnet-5-5", "effort": "high"}}));
+4 -140
View File
@@ -311,8 +311,6 @@ struct Replay {
sent: Arc<Mutex<Vec<Vec<Value>>>>, sent: Arc<Mutex<Vec<Vec<Value>>>>,
launched: Mutex<Vec<Vec<String>>>, launched: Mutex<Vec<Vec<String>>>,
errors: Arc<Mutex<Vec<String>>>, errors: Arc<Mutex<Vec<String>>>,
/// Each process's kill token.
kills: Mutex<Vec<CancellationToken>>,
} }
impl Cli for Replay { impl Cli for Replay {
@@ -333,7 +331,6 @@ impl Cli for Replay {
let (shim_in, cli_in) = tokio::io::duplex(1 << 20); let (shim_in, cli_in) = tokio::io::duplex(1 << 20);
let (mut cli_out, shim_out) = tokio::io::duplex(1 << 20); let (mut cli_out, shim_out) = tokio::io::duplex(1 << 20);
let kill = CancellationToken::new(); let kill = CancellationToken::new();
self.kills.lock().push(kill.clone());
let (sent, errors, token) = (self.sent.clone(), self.errors.clone(), kill.clone()); let (sent, errors, token) = (self.sent.clone(), self.errors.clone(), kill.clone());
sent.lock().push(Vec::new()); sent.lock().push(Vec::new());
tokio::spawn(async move { tokio::spawn(async move {
@@ -424,18 +421,14 @@ impl Replayed {
} }
} }
fn replay_cli(processes: Vec<Vec<Frame>>) -> Arc<Replay> { async fn replay(name: &str) -> Replayed {
Arc::new(Replay { let processes = load_fixture(name);
let cli = Arc::new(Replay {
processes: Mutex::new(processes.into()), processes: Mutex::new(processes.into()),
sent: Arc::default(), sent: Arc::default(),
launched: Mutex::default(), launched: Mutex::default(),
errors: Arc::default(), errors: Arc::default(),
kills: Mutex::default(), });
})
}
async fn replay(name: &str) -> Replayed {
let cli = replay_cli(load_fixture(name));
let (config, cwd) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap()); let (config, cwd) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
let cwd_path = std::fs::canonicalize(cwd.path()).unwrap(); let cwd_path = std::fs::canonicalize(cwd.path()).unwrap();
let h = let h =
@@ -468,101 +461,6 @@ async fn replay_simple() {
assert_eq!(user["message"]["content"][0]["text"], "Reply with exactly: hello there"); assert_eq!(user["message"]["content"][0]["text"], "Reply with exactly: hello there");
} }
/// The app closing the connection (an idle task released, archived or deleted) stops the
/// CLI processes of its sessions, idle ones included.
#[tokio::test(flavor = "multi_thread")]
async fn closing_the_connection_stops_the_processes() {
let r = replay("simple").await;
assert!(r.cli.kills.lock().iter().all(|k| !k.is_cancelled()));
r.h.client.kill();
let kills = r.cli.kills.lock().clone();
tokio::time::timeout(Duration::from_secs(5), async {
for k in kills {
k.cancelled().await;
}
})
.await
.expect("every process was stopped");
}
#[tokio::test(flavor = "multi_thread")]
async fn sessions_without_a_title_get_one_generated() {
let mut processes = load_fixture("simple");
processes[0].extend([
Frame::Shim(json!({"type": "control_request", "request_id": "req_3",
"request": {"subtype": "generate_session_title"}})),
Frame::Cli(json!({"type": "control_response",
"response": {"subtype": "success", "request_id": "req_3", "response": {"title": "Say hello"}}})),
]);
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.clone(),
Vec::new(),
)
.await;
let session = h.new_session().await;
// The transcript Claude Code writes, without the title it gives sessions in a terminal.
let dir = config.path().join("projects").join(history::escape(&cwd_path));
std::fs::create_dir_all(&dir).unwrap();
let prompt = json!({"type": "user", "uuid": "u1", "parentUuid": null,
"message": {"role": "user", "content": "Reply with exactly: hello there"}});
std::fs::write(dir.join(format!("{session}.jsonl")), format!("{prompt}\n")).unwrap();
h.prompt(&session, "Reply with exactly: hello there").await.unwrap();
let mut titles = Vec::new();
for _ in 0..100 {
titles = h.updates(&session, "session_info_update");
if !titles.is_empty() {
break;
}
tokio::time::sleep(Duration::from_millis(20)).await;
}
assert!(cli.errors.lock().is_empty(), "{:?}", cli.errors.lock());
assert_eq!(titles.iter().map(|t| t["title"].clone()).collect::<Vec<_>>(), [json!("Say hello")]);
let sent = cli.sent.lock()[0].clone();
let request =
sent.iter().find(|m| m.pointer("/request/subtype") == Some(&json!("generate_session_title"))).unwrap();
assert_eq!(request["request"]["description"], "Reply with exactly: hello there");
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")] #[tokio::test(flavor = "multi_thread")]
async fn replay_multi_turn() { async fn replay_multi_turn() {
let r = replay("multi_turn").await; let r = replay("multi_turn").await;
@@ -829,7 +727,6 @@ async fn a_stop_ahead_of_its_prompt_cancels_it() {
sent: Arc::default(), sent: Arc::default(),
launched: Mutex::default(), launched: Mutex::default(),
errors: Arc::default(), errors: Arc::default(),
kills: Mutex::default(),
}); });
let (dir, cwd) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap()); let (dir, cwd) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
let h = Harness::connect(cli.clone(), dir.path().into(), dir.path().join("p"), cwd.path().into(), Vec::new()).await; let h = Harness::connect(cli.clone(), dir.path().into(), dir.path().join("p"), cwd.path().into(), Vec::new()).await;
@@ -873,7 +770,6 @@ async fn a_failed_turn_reports_its_failure() {
sent: Arc::default(), sent: Arc::default(),
launched: Mutex::default(), launched: Mutex::default(),
errors: Arc::default(), errors: Arc::default(),
kills: Mutex::default(),
}); });
let (dir, cwd) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap()); let (dir, cwd) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
let h = let h =
@@ -1130,24 +1026,6 @@ fn streamed_text_is_not_sent_twice() {
assert_eq!(usage[0].update, json!({"sessionUpdate": "usage_update", "used": 15, "size": 1000})); 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] #[test]
fn rate_limits_and_cost() { fn rate_limits_and_cost() {
let mut t = Translator::new("s", PathBuf::from("/w"), false); let mut t = Translator::new("s", PathBuf::from("/w"), false);
@@ -1293,13 +1171,6 @@ async fn skipped_questions_have_no_answers() {
assert_eq!(cancelled, None); 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] #[test]
fn mcp_servers_become_an_mcp_config() { fn mcp_servers_become_an_mcp_config() {
assert_eq!(mcp_config(&json!({ "mcpServers": [] })), None); assert_eq!(mcp_config(&json!({ "mcpServers": [] })), None);
@@ -1325,10 +1196,3 @@ fn mcp_servers_become_an_mcp_config() {
drop(path); drop(path);
assert!(!kept.exists()); assert!(!kept.exists());
} }
#[test]
fn additional_directories_are_read_from_the_session_params() {
let params = json!({ "cwd": "/w/api", "additionalDirectories": ["/w/web", 3, "/w/docs"] });
assert_eq!(additional_dirs(&params), ["/w/web", "/w/docs"]);
assert!(additional_dirs(&json!({ "cwd": "/w/api" })).is_empty());
}
@@ -144,22 +144,6 @@ pub(super) fn result_fields(name: &str, input: &Value, block: &Value, structured
content.push(text(&t)); 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" } }); let mut out = json!({ "status": if failed { "failed" } else { "completed" } });
if !content.is_empty() { if !content.is_empty() {
out["content"] = Value::Array(content); out["content"] = Value::Array(content);
@@ -246,43 +230,6 @@ mod tests {
assert_eq!(call_fields("WebSearch", &json!({"query": "q"}), cwd)["kind"], "fetch"); 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] #[test]
fn results() { fn results() {
let input = json!({"file_path": "/w/n.txt", "content": "two"}); 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()); 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)) 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 // 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`). // the list and stays up while it isn't empty (see `Task::release_when_idle`).
Some("background_tasks_changed") => { Some("background_tasks_changed") => {
@@ -568,16 +561,6 @@ impl Translator {
self.usage_update().into_iter().collect() 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> { fn usage_update(&self) -> Option<Update> {
let used = self.used?; let used = self.used?;
let size = self 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);
}
}
+71 -584
View File
@@ -2,11 +2,7 @@
//! translated to and from ACP. A codex thread is an ACP session; a subagent's thread is //! 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. //! a subagent session of the thread that spawned it.
mod commands;
mod translate; mod translate;
mod trust;
pub(crate) use commands::BUILTIN_COMMANDS;
#[cfg(test)] #[cfg(test)]
mod tests; mod tests;
@@ -14,8 +10,6 @@ mod tests;
use super::Shim; use super::Shim;
use crate::acp::AUTH_REQUIRED; use crate::acp::AUTH_REQUIRED;
use crate::provider::ProviderSpec; use crate::provider::ProviderSpec;
use crate::{AgentCommand, AgentCommandSource};
use commands::{BuiltinCommand, ParsedCommand};
use ide_jsonrpc::{Framing, Handler, Peer, RpcError, codes}; use ide_jsonrpc::{Framing, Handler, Peer, RpcError, codes};
use parking_lot::Mutex; use parking_lot::Mutex;
use serde_json::{Value, json}; use serde_json::{Value, json};
@@ -34,22 +28,6 @@ const OUTPUT_EVERY: Duration = Duration::from_millis(200);
const EARLY_CANCEL: Duration = Duration::from_secs(1); const EARLY_CANCEL: Duration = Duration::from_secs(1);
/// How long the client's connection outlives codex. /// How long the client's connection outlives codex.
const EXIT_GRACE: Duration = Duration::from_millis(100); const EXIT_GRACE: Duration = Duration::from_millis(100);
/// What a thread's name is asked for with, after its first turn.
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( pub(crate) fn connect(
spec: &ProviderSpec, spec: &ProviderSpec,
@@ -63,92 +41,6 @@ pub(crate) fn connect(
}) })
} }
/// A model lookup uses app-server directly: no thread, task, prompt or project MCP.
pub(crate) async fn discover(
spec: ProviderSpec,
cwd: std::path::PathBuf,
) -> Result<crate::catalogs::Discovered, String> {
let spec = tokio::task::spawn_blocking({
let cwd = cwd.clone();
move || spec.resolve_for_launch(&cwd)
})
.await
.map_err(|e| e.to_string())?;
let peer = Peer::spawn_framed(
&spec.command,
&spec.args,
&cwd,
&spec.env,
Arc::new(ide_jsonrpc::NoopHandler),
Box::new(|_| {}),
Framing::Lines,
)
.map_err(|e| e.to_string())?;
let _stop = crate::catalogs::KillPeer(peer.clone());
tokio::time::timeout(Duration::from_secs(30), async {
let _: Value = peer.request("initialize", initialize_params(), None).await.map_err(|e| e.to_string())?;
peer.notify("initialized", Value::Null).map_err(|e| e.to_string())?;
let mut models = list_models(&peer).await.map_err(|e| e.message)?;
models.retain(|model| !model.hidden);
let mut settings = Settings::of(&json!({}), &models);
if settings.model.is_empty()
&& let Some(model) = models.first()
{
settings.model = model.id.clone();
settings.fit_effort(&models);
}
let options = translate::config_options(&models, &settings);
let config = crate::config::options_of(&json!({ "configOptions": options }));
let levels = models
.iter()
.map(|model| {
let mut settings = settings.clone();
settings.model = model.id.clone();
settings.fit_effort(&models);
let options = translate::config_options(&models, &settings);
let levels = crate::config::options_of(&json!({ "configOptions": options }))
.into_iter()
.filter(|o| o.category.as_deref() == Some("thought_level"))
.collect();
(model.id.clone(), levels)
})
.collect();
Ok(crate::catalogs::Discovered { config, commands: None, levels })
})
.await
.map_err(|_| "Codex model discovery timed out".to_owned())?
}
fn initialize_params() -> Value {
json!({
"clientInfo": { "name": "openidea", "title": "OpenIDEA", "version": env!("CARGO_PKG_VERSION") },
"capabilities": { "experimentalApi": true, "optOutNotificationMethods": OPT_OUT },
})
}
async fn list_models(peer: &Peer) -> Result<Vec<ModelInfo>, ResponseError> {
let mut all = Vec::new();
let mut cursor = Value::Null;
let mut seen = HashSet::new();
loop {
let page: Value = peer.request("model/list", json!({ "cursor": cursor }), None).await.map_err(from_codex)?;
let Some(data) = page.get("data").and_then(Value::as_array) else {
return Err(error(codes::INTERNAL_ERROR, "Codex returned an invalid model list"));
};
let models = translate::models_of(&page);
if models.len() != data.len() {
return Err(error(codes::INTERNAL_ERROR, "Codex returned an invalid model list"));
}
all.extend(models);
match page.get("nextCursor") {
None | Some(Value::Null) => return Ok(all),
Some(Value::String(next)) if next.is_empty() => return Ok(all),
Some(Value::String(next)) if seen.insert(next.clone()) => cursor = json!(next),
_ => return Err(error(codes::INTERNAL_ERROR, "Codex returned an invalid model-list cursor")),
}
}
}
/// Connects `client` to a shim driving the codex connection `connect_codex` opens (it /// Connects `client` to a shim driving the codex connection `connect_codex` opens (it
/// gets the handler for what codex sends). Each side's end closes the other. /// gets the handler for what codex sends). Each side's end closes the other.
fn attach( fn attach(
@@ -202,8 +94,6 @@ struct State {
threads: HashMap<String, Thread>, threads: HashMap<String, Thread>,
/// The last `account/rateLimits/updated` snapshot. /// The last `account/rateLimits/updated` snapshot.
rate_limits: Option<Value>, rate_limits: Option<Value>,
/// Project trust has been checked (and, when needed, asked about) on this connection.
trust_checked: HashSet<String>,
/// Codex exited. /// Codex exited.
gone: bool, gone: bool,
} }
@@ -236,12 +126,6 @@ struct Thread {
early_cancel: Option<Instant>, early_cancel: Option<Instant>,
/// The latest agent message (a subagent's answer). /// The latest agent message (a subagent's answer).
answer: String, 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.
naming: bool,
} }
struct PendingPrompt { struct PendingPrompt {
@@ -334,38 +218,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}"))) 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 { impl CodexShim {
fn codex(&self) -> &Peer { fn codex(&self) -> &Peer {
self.codex.get().expect("attached before any message") self.codex.get().expect("attached before any message")
@@ -375,12 +227,6 @@ impl CodexShim {
self.codex().request(method, params, None).await.map_err(from_codex) 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> { async fn handle(&self, method: &str, params: Value) -> Result<Value, ResponseError> {
match method { match method {
"initialize" => self.initialize().await, "initialize" => self.initialize().await,
@@ -397,7 +243,15 @@ impl CodexShim {
} }
async fn initialize(&self) -> Result<Value, ResponseError> { async fn initialize(&self) -> Result<Value, ResponseError> {
let info = self.call("initialize", initialize_params()).await?; let info = self
.call(
"initialize",
json!({
"clientInfo": { "name": "openidea", "title": "OpenIDEA", "version": env!("CARGO_PKG_VERSION") },
"capabilities": { "experimentalApi": true, "optOutNotificationMethods": OPT_OUT },
}),
)
.await?;
self.codex().notify("initialized", Value::Null).map_err(from_codex)?; self.codex().notify("initialized", Value::Null).map_err(from_codex)?;
self.state.lock().initialized = true; self.state.lock().initialized = true;
// `<client>/<codex version> (<platform>) …` // `<client>/<codex version> (<platform>) …`
@@ -413,7 +267,7 @@ impl CodexShim {
"loadSession": true, "loadSession": true,
"promptCapabilities": { "image": true, "audio": false, "embeddedContext": true }, "promptCapabilities": { "image": true, "audio": false, "embeddedContext": true },
"mcpCapabilities": { "http": false, "sse": false, "stdio": true }, "mcpCapabilities": { "http": false, "sse": false, "stdio": true },
"sessionCapabilities": { "fork": {}, "close": {}, "additionalDirectories": {} }, "sessionCapabilities": { "fork": {}, "close": {} },
"_meta": { "openidea": { "rollback": true, "steer": true } }, "_meta": { "openidea": { "rollback": true, "steer": true } },
}, },
"agentInfo": { "name": "codex", "title": "Codex", "version": version }, "agentInfo": { "name": "codex", "title": "Codex", "version": version },
@@ -421,15 +275,32 @@ impl CodexShim {
})) }))
} }
/// Cache only complete, successful listings; a failed page must never become availability. /// The models codex offers; empty when it can't list them.
async fn models(&self) -> Result<Arc<Vec<ModelInfo>>, ResponseError> { async fn models(&self) -> Arc<Vec<ModelInfo>> {
let mut cached = self.models.lock().await; let mut cached = self.models.lock().await;
if let Some(models) = cached.as_ref() { if let Some(m) = cached.as_ref() {
return Ok(models.clone()); return m.clone();
} }
let models = Arc::new(list_models(self.codex()).await?); let mut all = Vec::new();
let mut cursor = Value::Null;
loop {
match self.call("model/list", json!({ "cursor": cursor })).await {
Ok(page) => {
all.extend(translate::models_of(&page));
match page.get("nextCursor").filter(|c| c.is_string()) {
Some(next) if *next != cursor => cursor = next.clone(),
_ => break,
}
}
Err(e) => {
tracing::warn!("codex: listing models failed: {}", e.message);
return Arc::new(all);
}
}
}
let models = Arc::new(all);
*cached = Some(models.clone()); *cached = Some(models.clone());
Ok(models) models
} }
async fn publish_skills(&self, session: &str) { async fn publish_skills(&self, session: &str) {
@@ -446,31 +317,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`. /// 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) { fn open_thread(&self, result: &Value, models: &[ModelInfo], settings: Option<Settings>) -> (String, Value) {
let thread = result.get("thread").unwrap_or(&Value::Null); let thread = result.get("thread").unwrap_or(&Value::Null);
@@ -483,21 +329,20 @@ impl CodexShim {
t.parent = None; t.parent = None;
t.settings = Some(settings); t.settings = Some(settings);
t.cwd = cwd; t.cwd = cwd;
t.named = thread.get("name").and_then(Value::as_str).is_some_and(|n| !n.trim().is_empty());
(id, options) (id, options)
} }
async fn new_session(&self, params: &Value) -> Result<Value, ResponseError> { async fn new_session(&self, params: &Value) -> Result<Value, ResponseError> {
let models = self.models().await?; let models = self.models().await;
self.prepare_project_trust(params).await;
let mut request = json!({ "cwd": params.get("cwd") }); 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 result = self.call("thread/start", request).await?;
let (id, options) = self.open_thread(&result, &models, None); let (id, options) = self.open_thread(&result, &models, None);
if id.is_empty() { if id.is_empty() {
return Err(error(codes::INTERNAL_ERROR, "codex started no thread")); return Err(error(codes::INTERNAL_ERROR, "codex started no thread"));
} }
self.apply_skill_roots(&id, params).await;
self.publish_skills(&id).await; self.publish_skills(&id).await;
Ok(json!({ "sessionId": id, "configOptions": options })) Ok(json!({ "sessionId": id, "configOptions": options }))
} }
@@ -505,10 +350,11 @@ impl CodexShim {
/// Resumes the thread and replays its history before answering. /// Resumes the thread and replays its history before answering.
async fn load_session(&self, params: &Value) -> Result<Value, ResponseError> { async fn load_session(&self, params: &Value) -> Result<Value, ResponseError> {
let id = str_param(params, "sessionId")?; let id = str_param(params, "sessionId")?;
let models = self.models().await?; let models = self.models().await;
self.prepare_project_trust(params).await;
let mut request = json!({ "threadId": id, "cwd": params.get("cwd") }); 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 result = self.call("thread/resume", request).await?;
let (_, options) = self.open_thread(&result, &models, None); let (_, options) = self.open_thread(&result, &models, None);
let cwd = self.state.lock().threads.get(id).and_then(|t| t.cwd.clone()); let cwd = self.state.lock().threads.get(id).and_then(|t| t.cwd.clone());
@@ -516,18 +362,18 @@ impl CodexShim {
for update in translate::history(thread, cwd.as_deref()) { for update in translate::history(thread, cwd.as_deref()) {
self.emit(id, update); self.emit(id, update);
} }
self.apply_skill_roots(id, params).await;
self.publish_skills(id).await; self.publish_skills(id).await;
Ok(json!({ "configOptions": options })) Ok(json!({ "configOptions": options }))
} }
async fn fork_session(&self, params: &Value) -> Result<Value, ResponseError> { async fn fork_session(&self, params: &Value) -> Result<Value, ResponseError> {
let source = str_param(params, "sessionId")?; let source = str_param(params, "sessionId")?;
let models = self.models().await?; 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 settings = self.state.lock().threads.get(source).and_then(|t| t.settings.clone());
let mut request = json!({ "threadId": source, "cwd": params.get("cwd") }); 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 { if let Some(s) = &settings {
request["model"] = json!(s.model_slug(&models)); request["model"] = json!(s.model_slug(&models));
request["approvalPolicy"] = json!(s.mode.approval_policy()); request["approvalPolicy"] = json!(s.mode.approval_policy());
@@ -535,7 +381,6 @@ impl CodexShim {
} }
let result = self.call("thread/fork", request).await?; let result = self.call("thread/fork", request).await?;
let (id, options) = self.open_thread(&result, &models, settings); let (id, options) = self.open_thread(&result, &models, settings);
self.apply_skill_roots(&id, params).await;
self.publish_skills(&id).await; self.publish_skills(&id).await;
Ok(json!({ "sessionId": id, "configOptions": options })) Ok(json!({ "sessionId": id, "configOptions": options }))
} }
@@ -544,7 +389,7 @@ impl CodexShim {
let session = str_param(params, "sessionId")?; let session = str_param(params, "sessionId")?;
let option = str_param(params, "configId")?; let option = str_param(params, "configId")?;
let value = str_param(params, "value")?; let value = str_param(params, "value")?;
let models = self.models().await?; let models = self.models().await;
let mut state = self.state.lock(); let mut state = self.state.lock();
let settings = state let settings = state
.threads .threads
@@ -557,18 +402,11 @@ impl CodexShim {
async fn prompt(&self, params: &Value) -> Result<Value, ResponseError> { async fn prompt(&self, params: &Value) -> Result<Value, ResponseError> {
let session = str_param(params, "sessionId")?.to_owned(); let session = str_param(params, "sessionId")?.to_owned();
let prompt = params.get("prompt").unwrap_or(&Value::Null); let input = translate::user_input(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);
if input.is_empty() { if input.is_empty() {
return Err(invalid("empty prompt")); 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 (done, ended) = oneshot::channel();
let settings = { let settings = {
let mut state = self.state.lock(); let mut state = self.state.lock();
@@ -584,213 +422,33 @@ impl CodexShim {
t.error = None; t.error = None;
t.settings.clone() t.settings.clone()
}; };
let started = match command.as_ref() { let mut request = json!({ "threadId": session, "input": input, "summary": "auto" });
Some(command) => match command.command { if let Some(s) = settings {
BuiltinCommand::Compact => { request["model"] = json!(s.model_slug(&models));
// Codex reports compaction as its own turn, using the same started/completed request["approvalPolicy"] = json!(s.mode.approval_policy());
// notifications that finish the pending session/prompt above. request["sandboxPolicy"] = s.mode.sandbox_policy();
self.call("thread/compact/start", json!({ "threadId": session })).await if let Some(effort) = &s.effort {
} request["effort"] = json!(effort);
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
} }
};
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() match self.call("turn/start", request).await {
&& command.is_none() Ok(started) => {
&& let Some(thread) = self.state.lock().threads.get_mut(&session) if let Some(turn) = started.pointer("/turn/id").and_then(Value::as_str) {
&& let Some(settings) = thread.settings.as_mut() self.turn_known(&session, turn, false);
{ }
// A Default override is needed only for the first turn that resets a resumed }
// Plan thread; omitting it afterwards preserves compatibility with older Codex. Err(e) => {
settings.collaboration_mode_override = None; if let Some(t) = self.state.lock().threads.get_mut(&session) {
} t.prompt = None;
if let Err(e) = started { }
if let Some(t) = self.state.lock().threads.get_mut(&session) { return Err(e);
t.prompt = None;
} }
return Err(e);
} }
let (turn, last_error) = ended.await.map_err(|_| error(codes::INTERNAL_ERROR, "Codex exited"))?; let (turn, last_error) = ended.await.map_err(|_| error(codes::INTERNAL_ERROR, "Codex exited"))?;
let rate_limits = self.state.lock().rate_limits.clone(); let rate_limits = self.state.lock().rate_limits.clone();
stop_reason(&turn, last_error, rate_limits.as_ref()) 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> { async fn steer(&self, params: &Value) -> Result<Value, ResponseError> {
let session = str_param(params, "sessionId")?; let session = str_param(params, "sessionId")?;
let turn = self.state.lock().threads.get(session).and_then(|t| t.turn.clone()); let turn = self.state.lock().threads.get(session).and_then(|t| t.turn.clone());
@@ -916,25 +574,6 @@ impl CodexShim {
fn on_codex_notification(self: &Arc<Self>, method: &str, params: &Value) { fn on_codex_notification(self: &Arc<Self>, method: &str, params: &Value) {
let thread = params.get("threadId").and_then(Value::as_str).unwrap_or_default(); let thread = params.get("threadId").and_then(Value::as_str).unwrap_or_default();
match method { 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" => { "skills/changed" => {
let shim = self.clone(); let shim = self.clone();
let sessions: Vec<String> = self let sessions: Vec<String> = self
@@ -985,15 +624,9 @@ impl CodexShim {
t.last_chunk = None; t.last_chunk = None;
Some(translate::plan(params)) Some(translate::plan(params))
}), }),
"thread/tokenUsage/updated" => self.with_thread(thread, |t, _| { "thread/tokenUsage/updated" => self.with_thread(thread, |_, _| translate::usage(params)),
if let Some(usage) = params.get("tokenUsage") { "thread/name/updated" => self.with_thread(thread, |_, _| {
t.token_usage = Some(usage.clone());
}
translate::usage(params)
}),
"thread/name/updated" => self.with_thread(thread, |t, _| {
let title = params.get("threadName").and_then(Value::as_str)?; let title = params.get("threadName").and_then(Value::as_str)?;
t.named = true;
Some(json!({ "sessionUpdate": "session_info_update", "title": title })) Some(json!({ "sessionUpdate": "session_info_update", "title": title }))
}), }),
"thread/started" => self.thread_started(params.get("thread").unwrap_or(&Value::Null)), "thread/started" => self.thread_started(params.get("thread").unwrap_or(&Value::Null)),
@@ -1082,11 +715,6 @@ impl CodexShim {
} }
Some(t.chunk(kind, &id, &text)) Some(t.chunk(kind, &id, &text))
}); });
if ty == "agentMessage"
&& let Some(update) = translate::question_update(item)
{
self.emit(thread, update);
}
} }
"subAgentActivity" => { "subAgentActivity" => {
let child = item.get("agentThreadId").and_then(Value::as_str).unwrap_or_default(); let child = item.get("agentThreadId").and_then(Value::as_str).unwrap_or_default();
@@ -1184,10 +812,9 @@ impl CodexShim {
} }
} }
fn turn_completed(self: &Arc<Self>, thread: &str, turn: &Value) { fn turn_completed(&self, thread: &str, turn: &Value) {
let id = turn.get("id").and_then(Value::as_str).unwrap_or_default(); let id = turn.get("id").and_then(Value::as_str).unwrap_or_default();
let completed = turn.get("status").and_then(Value::as_str) == Some("completed"); let (parent, answer) = {
let (parent, answer, name) = {
let mut state = self.state.lock(); let mut state = self.state.lock();
let Some(t) = state.threads.get_mut(thread) else { return }; let Some(t) = state.threads.get_mut(thread) else { return };
if t.turn.as_deref().is_none_or(|r| r == id) { if t.turn.as_deref().is_none_or(|r| r == id) {
@@ -1203,15 +830,8 @@ impl CodexShim {
let _ = p.done.send((turn.clone(), error.clone())); let _ = p.done.send((turn.clone(), error.clone()));
} }
let answer = std::mem::take(&mut t.answer); let answer = std::mem::take(&mut t.answer);
let name = (t.parent.clone(), (answer, error))
completed && !id.is_empty() && t.parent.is_none() && t.settings.is_some() && !t.named && !t.naming;
t.naming |= name;
(t.parent.clone(), (answer, error), name)
}; };
if name {
let (shim, thread, turn) = (self.clone(), thread.to_owned(), id.to_owned());
self.runtime.spawn(async move { shim.name_thread(&thread, &turn).await });
}
let Some(parent) = parent else { return }; let Some(parent) = parent else { return };
let (answer, error) = answer; let (answer, error) = answer;
let mut state_of = match turn.get("status").and_then(Value::as_str) { let mut state_of = match turn.get("status").and_then(Value::as_str) {
@@ -1233,28 +853,6 @@ impl CodexShim {
} }
} }
/// Names a thread from what it holds after `turn`, as codex leaves naming to its
/// clients; `thread/name/updated` brings the name back. Unnamed, the next turn tries again.
async fn name_thread(&self, thread: &str, turn: &str) {
let sample = json!({ "threadId": thread, "expectedTurnId": turn, "prompt": NAME_PROMPT, "effort": "low" });
let named = match self.call("thread/sample", sample).await {
Ok(r) => match r.get("text").and_then(Value::as_str).and_then(translate::thread_name) {
Some(name) => {
self.call("thread/name/set", json!({ "threadId": thread, "name": name })).await.map(|_| ())
}
None => Err(error(codes::INTERNAL_ERROR, "codex gave no name")),
},
Err(e) => Err(e),
};
if let Err(e) = &named {
tracing::debug!("naming codex thread {thread}: {}", e.message);
}
if let Some(t) = self.state.lock().threads.get_mut(thread) {
t.naming = false;
t.named |= named.is_ok();
}
}
/// Requests from codex: approvals and questions, asked as ACP permission requests. /// Requests from codex: approvals and questions, asked as ACP permission requests.
fn on_codex_request(&self, method: &str, params: &Value) -> Result<Value, (i64, String)> { fn on_codex_request(&self, method: &str, params: &Value) -> Result<Value, (i64, String)> {
let thread = params.get("threadId").and_then(Value::as_str).unwrap_or_default().to_owned(); let thread = params.get("threadId").and_then(Value::as_str).unwrap_or_default().to_owned();
@@ -1484,114 +1082,3 @@ fn stop_reason(turn: &Value, last_error: Option<Value>, rate_limits: Option<&Val
}; };
Ok(json!({ "stopReason": stop })) 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"))
}
+9 -688
View File
@@ -11,155 +11,6 @@ use std::collections::VecDeque;
use std::path::PathBuf; use std::path::PathBuf;
use tokio::io::{AsyncBufReadExt, AsyncRead, AsyncWrite, AsyncWriteExt, BufReader}; use tokio::io::{AsyncBufReadExt, AsyncRead, AsyncWrite, AsyncWriteExt, BufReader};
struct ModelPages {
pages: Mutex<VecDeque<Result<Value, (i64, String)>>>,
cursors: Mutex<Vec<Value>>,
}
impl Handler for ModelPages {
fn on_notification(&self, _: &str, _: Value) {}
fn on_request(&self, method: &str, params: Value) -> Result<Value, (i64, String)> {
assert_eq!(method, "model/list", "listing models must never start a thread or turn");
self.cursors.lock().push(params["cursor"].clone());
self.pages.lock().pop_front().expect("another expected page")
}
}
fn model_peer(pages: Arc<ModelPages>) -> (Peer, Peer) {
let (ours, theirs) = tokio::io::duplex(1 << 16);
let (read, write) = tokio::io::split(theirs);
let server = Peer::connect_framed(read, write, pages, Framing::Lines);
let (read, write) = tokio::io::split(ours);
(Peer::connect_framed(read, write, Arc::new(ide_jsonrpc::NoopHandler), Framing::Lines), server)
}
#[tokio::test]
async fn model_pagination_failure_does_not_cache_an_incomplete_catalog() {
let first = json!({ "data": [{ "id": "first" }], "nextCursor": "next" });
let pages = Arc::new(ModelPages {
pages: Mutex::new(VecDeque::from([
Ok(first.clone()),
Err((-32000, "authentication expired".into())),
Ok(first),
Ok(json!({ "data": [{ "id": "second" }], "nextCursor": null })),
])),
cursors: Mutex::default(),
});
let (peer, server) = model_peer(pages.clone());
let shim = CodexShim {
runtime: tokio::runtime::Handle::current(),
codex: OnceLock::from(peer.clone()),
client: OnceLock::new(),
state: Mutex::default(),
models: tokio::sync::Mutex::new(None),
skills: tokio::sync::Mutex::new(()),
};
assert_eq!(shim.models().await.unwrap_err().message, "authentication expired");
let models = shim.models().await.unwrap();
assert_eq!(models.iter().map(|m| m.id.as_str()).collect::<Vec<_>>(), ["first", "second"]);
assert_eq!(shim.models().await.unwrap().len(), 2);
assert_eq!(*pages.cursors.lock(), [Value::Null, json!("next"), Value::Null, json!("next")]);
peer.kill();
server.kill();
}
#[tokio::test]
async fn repeated_or_invalid_model_cursors_and_malformed_pages_are_failures() {
for pages in [
vec![json!({ "data": [], "nextCursor": "a" }), json!({ "data": [], "nextCursor": "a" })],
vec![
json!({ "data": [], "nextCursor": "a" }),
json!({ "data": [], "nextCursor": "b" }),
json!({ "data": [], "nextCursor": "a" }),
],
vec![json!({ "data": [], "nextCursor": 7 })],
vec![json!({ "nextCursor": null })],
vec![json!({ "data": [{}], "nextCursor": null })],
] {
let pages =
Arc::new(ModelPages { pages: Mutex::new(pages.into_iter().map(Ok).collect()), cursors: Mutex::default() });
let (peer, server) = model_peer(pages);
assert!(list_models(&peer).await.is_err());
peer.kill();
server.kill();
}
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn native_discovery_only_initializes_and_pages_models_then_stops_the_process() {
use std::os::unix::fs::PermissionsExt;
let tmp = tempfile::tempdir().unwrap();
let script = tmp.path().join("fake-codex");
std::fs::write(
&script,
r#"#!/usr/bin/env python3
import json, os, pathlib, sys
pathlib.Path('pid').write_text(str(os.getpid()))
for line in sys.stdin:
request = json.loads(line)
with pathlib.Path('requests').open('a') as f:
f.write(json.dumps(request) + '\n')
method = request['method']
if method == 'initialized':
continue
if method == 'initialize':
result = {}
elif method == 'model/list':
cursor = request['params']['cursor']
model = 'one' if cursor is None else 'two'
result = {'data': [{'id': model, 'isDefault': cursor is None,
'defaultReasoningEffort': 'low', 'supportedReasoningEfforts': [{'reasoningEffort': 'low'}]}],
'nextCursor': 'second-page' if cursor is None else None}
else:
raise RuntimeError('must not create a thread or prompt: ' + method)
print(json.dumps({'jsonrpc': '2.0', 'id': request['id'], 'result': result}), flush=True)
"#,
)
.unwrap();
std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();
let spec = ProviderSpec {
id: "codex".into(),
name: "Codex".into(),
driver: crate::provider::Driver::Codex,
command: script.to_string_lossy().into_owned(),
args: Vec::new(),
env: Vec::new(),
login_hint: String::new(),
source: crate::AgentSource::Builtin,
};
let found = discover(spec, tmp.path().to_path_buf()).await.unwrap();
let models: Vec<_> = found
.config
.iter()
.filter(|o| o.category.as_deref() == Some("model"))
.flat_map(|o| o.values.iter().map(|v| v.value.as_str()))
.collect();
assert_eq!(models, ["one", "two"]);
assert_eq!(found.levels.keys().map(String::as_str).collect::<Vec<_>>(), ["one", "two"]);
let requests = std::fs::read_to_string(tmp.path().join("requests")).unwrap();
let requests: Vec<Value> = requests.lines().map(|line| serde_json::from_str(line).unwrap()).collect();
assert_eq!(
requests.iter().map(|r| r["method"].as_str().unwrap()).collect::<Vec<_>>(),
["initialize", "initialized", "model/list", "model/list"]
);
assert_eq!(requests[2]["params"]["cursor"], Value::Null);
assert_eq!(requests[3]["params"]["cursor"], "second-page");
let pid = std::fs::read_to_string(tmp.path().join("pid")).unwrap();
tokio::time::timeout(Duration::from_secs(5), async {
loop {
let alive = std::process::Command::new("kill").args(["-0", pid.trim()]).output().unwrap().status.success();
if !alive {
break;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await
.expect("discovery must kill and reap its child");
}
// ---- Pure translations ------------------------------------------------------------- // ---- Pure translations -------------------------------------------------------------
fn models() -> Vec<ModelInfo> { fn models() -> Vec<ModelInfo> {
@@ -180,38 +31,24 @@ fn settings_follow_the_thread_and_the_models() {
let result = json!({"model": "big", "reasoningEffort": null, "approvalPolicy": "untrusted", let result = json!({"model": "big", "reasoningEffort": null, "approvalPolicy": "untrusted",
"sandbox": {"type": "workspaceWrite"}}); "sandbox": {"type": "workspaceWrite"}});
let mut s = Settings::of(&result, &models); let mut s = Settings::of(&result, &models);
assert_eq!( assert_eq!(s, Settings { model: "big".into(), effort: Some("low".into()), mode: Mode::Ask });
s,
Settings {
model: "big".into(),
effort: Some("low".into()),
mode: Mode::Ask,
collaboration_mode: DEFAULT_COLLABORATION_MODE.into(),
collaboration_mode_override: None,
}
);
let options = config_options(&models, &s); let options = config_options(&models, &s);
let ids: Vec<&str> = options.as_array().unwrap().iter().map(|o| o["id"].as_str().unwrap()).collect(); 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[0]["options"].as_array().unwrap().len(), 2, "hidden models are left out");
assert_eq!(options[1]["category"], "thought_level"); assert_eq!(options[1]["category"], "thought_level");
assert_eq!(options[1]["options"][1]["name"], "Extra high"); assert_eq!(options[1]["options"][1]["name"], "Extra high");
assert_eq!(options[2]["currentValue"], "ask"); 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. // A model without efforts drops the option; its slug is what codex gets.
s.set(&models, MODEL, "plain").unwrap(); s.set(&models, MODEL, "plain").unwrap();
assert_eq!((s.effort.as_deref(), s.model_slug(&models).as_str()), (None, "plain-slug")); 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, EFFORT, "low").is_err());
assert!(s.set(&models, MODEL, "nope").is_err()); assert!(s.set(&models, MODEL, "nope").is_err());
s.set(&models, MODE, "full-access").unwrap(); s.set(&models, MODE, "full-access").unwrap();
assert_eq!((s.mode.approval_policy(), s.mode.sandbox_policy()), ("never", json!({"type": "dangerFullAccess"}))); 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. // A model codex runs that it doesn't list is still offered.
let s = Settings::of(&json!({"model": "custom", "sandbox": {"type": "readOnly"}}), &models); let s = Settings::of(&json!({"model": "custom", "sandbox": {"type": "readOnly"}}), &models);
@@ -240,18 +77,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] #[test]
fn commands_are_titled_by_what_they_do() { fn commands_are_titled_by_what_they_do() {
let cmd = |actions: Value| { let cmd = |actions: Value| {
@@ -473,63 +298,12 @@ fn history_replays_turns() {
assert_eq!(updates[4]["status"], "completed"); assert_eq!(updates[4]["status"], "completed");
} }
#[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 --------------------------------------------------------------------- // ---- Transcripts ---------------------------------------------------------------------
/// The ACP client: records updates and answers permission requests in order. /// The ACP client: records updates and answers permission requests in order.
#[derive(Default)] #[derive(Default)]
struct Client { struct Client {
updates: Mutex<Vec<Value>>, updates: Mutex<Vec<Value>>,
warnings: Mutex<Vec<Value>>,
asked: Mutex<Vec<Value>>, asked: Mutex<Vec<Value>>,
/// Option ids to choose; `None` (or none left) cancels. /// Option ids to choose; `None` (or none left) cancels.
answers: Mutex<VecDeque<Option<&'static str>>>, answers: Mutex<VecDeque<Option<&'static str>>>,
@@ -539,8 +313,6 @@ impl Handler for Client {
fn on_notification(&self, method: &str, params: Value) { fn on_notification(&self, method: &str, params: Value) {
if method == "session/update" { if method == "session/update" {
self.updates.lock().push(params); self.updates.lock().push(params);
} else if method == "_openidea/warning" {
self.warnings.lock().push(params);
} }
} }
@@ -606,10 +378,6 @@ async fn questions_share_one_card_and_keep_their_ids() {
#[derive(Clone, Copy, Debug, PartialEq)] #[derive(Clone, Copy, Debug, PartialEq)]
enum Scenario { enum Scenario {
AuthFailure, AuthFailure,
Command(&'static str),
Compact,
PlanThenPrompt,
PlanToggleThenPrompt,
Interrupt, Interrupt,
Resume, Resume,
Steer, Steer,
@@ -624,10 +392,6 @@ impl Scenario {
fn file(self) -> &'static str { fn file(self) -> &'static str {
match self { match self {
Scenario::AuthFailure => "auth_failure", Scenario::AuthFailure => "auth_failure",
Scenario::Command(_) => "simple",
Scenario::Compact => "simple",
Scenario::PlanThenPrompt => "simple",
Scenario::PlanToggleThenPrompt => "simple",
Scenario::Interrupt => "interrupt", Scenario::Interrupt => "interrupt",
Scenario::Resume => "resume", Scenario::Resume => "resume",
Scenario::Steer => "steer", Scenario::Steer => "steer",
@@ -685,21 +449,6 @@ async fn drive(scenario: Scenario, acp: &Peer, client: &Client, cwd: &str, threa
Scenario::AuthFailure | Scenario::Simple | Scenario::UsageLimit | Scenario::Subagent => { Scenario::AuthFailure | Scenario::Simple | Scenario::UsageLimit | Scenario::Subagent => {
out.push(("prompt", request(acp, "session/prompt", prompt("Reply with the single word: hi")).await)); 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 => { Scenario::Interrupt => {
out.push(("mode", request(acp, "session/set_config_option", set(MODE, "read-only")).await)); out.push(("mode", request(acp, "session/set_config_option", set(MODE, "read-only")).await));
let running = { let running = {
@@ -767,37 +516,6 @@ fn load(name: &str) -> Transcript {
Transcript { meta, frames } 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. /// Plays codex: waits for each frame the shim should send, sends what codex sent.
/// Returns the frames the shim sent. /// Returns the frames the shim sent.
async fn play<R: AsyncRead + Unpin, W: AsyncWrite + Unpin>( async fn play<R: AsyncRead + Unpin, W: AsyncWrite + Unpin>(
@@ -817,10 +535,8 @@ async fn play<R: AsyncRead + Unpin, W: AsyncWrite + Unpin>(
.unwrap() .unwrap()
.unwrap_or_else(|| panic!("the shim closed before {frame}")); .unwrap_or_else(|| panic!("the shim closed before {frame}"));
let actual: Value = serde_json::from_str(&line).unwrap(); 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; play an unsupported server.
// unsupported server. if actual["method"] == "skills/list" && frame["method"] != "skills/list" {
let method = actual["method"].as_str().unwrap_or_default();
if matches!(method, "config/read" | "skills/list" | "thread/sample") && frame["method"] != method {
let reply = json!({ "id": actual["id"], "error": { "code": -32601, "message": "unsupported" } }); let reply = json!({ "id": actual["id"], "error": { "code": -32601, "message": "unsupported" } });
write.write_all(format!("{reply}\n").as_bytes()).await.unwrap(); write.write_all(format!("{reply}\n").as_bytes()).await.unwrap();
continue; continue;
@@ -858,14 +574,7 @@ async fn play<R: AsyncRead + Unpin, W: AsyncWrite + Unpin>(
/// Runs `scenario` against its transcript; returns the ACP results, the client and /// Runs `scenario` against its transcript; returns the ACP results, the client and
/// the frames the shim sent. /// the frames the shim sent.
async fn replay(scenario: Scenario) -> (Results, Arc<Client>, Vec<Value>, Value) { async fn replay(scenario: Scenario) -> (Results, Arc<Client>, Vec<Value>, Value) {
let (results, client, sent, meta, _codex) = replay_transcript(scenario, load(scenario.file())).await; let t = load(scenario.file());
(results, client, sent, meta)
}
/// Both connections of a replay, which stay open while it is held.
type CodexEnd = Box<dyn std::any::Any>;
async fn replay_transcript(scenario: Scenario, t: Transcript) -> (Results, Arc<Client>, Vec<Value>, Value, CodexEnd) {
let (ours, theirs) = tokio::io::duplex(1 << 20); let (ours, theirs) = tokio::io::duplex(1 << 20);
let (tr, tw) = tokio::io::split(theirs); let (tr, tw) = tokio::io::split(theirs);
let client = Arc::new(Client::default()); let client = Arc::new(Client::default());
@@ -881,8 +590,8 @@ async fn replay_transcript(scenario: Scenario, t: Transcript) -> (Results, Arc<C
.await .await
.expect("the scenario finished"); .expect("the scenario finished");
// Codex stays up until the scenario is over. // Codex stays up until the scenario is over.
let (sent, read, write) = player.await.unwrap(); let (sent, _read, _write) = player.await.unwrap();
(results, client, sent, meta, Box::new((acp, read, write))) (results, client, sent, meta)
} }
fn sent<'a>(frames: &'a [Value], method: &str) -> Vec<&'a Value> { fn sent<'a>(frames: &'a [Value], method: &str) -> Vec<&'a Value> {
@@ -893,149 +602,6 @@ fn session_of(results: &Results, label: &str) -> String {
result(results, label).as_ref().unwrap()["sessionId"].as_str().unwrap().to_owned() 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")] #[tokio::test(flavor = "multi_thread")]
async fn auth_failure_names_auth() { async fn auth_failure_names_auth() {
let (results, _client, frames, _) = replay(Scenario::AuthFailure).await; let (results, _client, frames, _) = replay(Scenario::AuthFailure).await;
@@ -1047,7 +613,7 @@ async fn auth_failure_names_auth() {
let categories: Vec<&str> = let categories: Vec<&str> =
new["configOptions"].as_array().unwrap().iter().map(|o| o["category"].as_str().unwrap()).collect(); 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. // 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(); let model = new["configOptions"][0]["currentValue"].as_str().unwrap();
assert_eq!(model, "gpt-6-luna"); assert_eq!(model, "gpt-6-luna");
assert!(new["configOptions"][0]["options"].as_array().unwrap().iter().any(|o| o["value"] == model)); assert!(new["configOptions"][0]["options"].as_array().unwrap().iter().any(|o| o["value"] == model));
@@ -1235,42 +801,6 @@ async fn a_simple_turn_streams_reasoning_text_and_usage() {
assert_eq!(info["title"], "Say hi"); assert_eq!(info["title"], "Say hi");
} }
#[tokio::test(flavor = "multi_thread")]
async fn an_unnamed_thread_is_named_after_its_first_turn() {
let mut t = load(Scenario::Simple.file());
t.frames.retain(|(_, f)| f["method"] != "thread/name/updated");
let thread = "01a18300-0000-7000-8000-000000000001";
t.frames.extend([
(true, json!({"id": 90, "method": "thread/sample"})),
(false, json!({"id": 90, "result": {"responseId": "r", "sourceTurnId": thread, "text": "\"Say hi.\"\n"}})),
(true, json!({"id": 91, "method": "thread/name/set"})),
(false, json!({"id": 91, "result": {}})),
(false, json!({"method": "thread/name/updated", "params": {"threadId": thread, "threadName": "Say hi"}})),
]);
let (results, client, frames, _, _codex) = replay_transcript(Scenario::Simple, t).await;
let session = session_of(&results, "new");
let sample = &sent(&frames, "thread/sample")[0]["params"];
assert_eq!((sample["threadId"].as_str(), sample["expectedTurnId"].as_str()), (Some(thread), Some(thread)));
assert_eq!(sent(&frames, "thread/name/set")[0]["params"], json!({"threadId": thread, "name": "Say hi"}));
let mut info = Vec::new();
for _ in 0..100 {
info = client.of(&session).into_iter().filter(|u| u["sessionUpdate"] == "session_info_update").collect();
if !info.is_empty() {
break;
}
tokio::time::sleep(Duration::from_millis(20)).await;
}
assert_eq!(info.iter().map(|u| u["title"].clone()).collect::<Vec<_>>(), [json!("Say hi")]);
}
#[test]
fn thread_names_are_the_first_line_of_the_reply() {
assert_eq!(thread_name(" \n“修复登录表单。”\nmore").as_deref(), Some("修复登录表单"));
assert_eq!(thread_name("**Fix the login form.**").as_deref(), Some("Fix the login form"));
assert_eq!(thread_name(" \n\"\" "), None);
assert_eq!(thread_name(&"x".repeat(100)).map(|n| n.chars().count()), Some(80));
}
#[tokio::test(flavor = "multi_thread")] #[tokio::test(flavor = "multi_thread")]
async fn settings_apply_to_the_next_turn() { async fn settings_apply_to_the_next_turn() {
let (results, client, frames, _) = replay(Scenario::MultiTurn).await; let (results, client, frames, _) = replay(Scenario::MultiTurn).await;
@@ -1287,7 +817,6 @@ async fn settings_apply_to_the_next_turn() {
(starts[0]["params"]["model"].as_str(), starts[0]["params"]["effort"].as_str()), (starts[0]["params"]["model"].as_str(), starts[0]["params"]["effort"].as_str()),
(Some("gpt-5.6-luna"), Some("medium")) (Some("gpt-5.6-luna"), Some("medium"))
); );
assert!(starts[0]["params"].get("collaborationMode").is_none());
assert_eq!( assert_eq!(
(starts[1]["params"]["model"].as_str(), starts[1]["params"]["effort"].as_str()), (starts[1]["params"]["model"].as_str(), starts[1]["params"]["effort"].as_str()),
(Some("gpt-5.5"), Some("high")) (Some("gpt-5.5"), Some("high"))
@@ -1296,192 +825,6 @@ async fn settings_apply_to_the_next_turn() {
assert_eq!(client.text(&session, "agent_message_chunk"), "oneOn it.\n\ntwo"); 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")] #[tokio::test(flavor = "multi_thread")]
async fn approvals_are_asked_and_answered() { async fn approvals_are_asked_and_answered() {
let (results, client, frames, _) = replay(Scenario::Approvals).await; let (results, client, frames, _) = replay(Scenario::Approvals).await;
@@ -1721,17 +1064,6 @@ fn session_mcp_servers_become_thread_configuration() {
json!({"mcp_servers":{"OpenIDEA":{"command":"/app/openidea","args":["--mcp-stdio","--project","/project"],"env":{"K":"V"}}}}) 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")] #[tokio::test(flavor = "multi_thread")]
@@ -1847,14 +1179,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!({"data": []})).unwrap()["availableCommands"].as_array().unwrap().is_empty());
assert!(skill_commands(&json!({})).is_none()); assert!(skill_commands(&json!({})).is_none());
} }
#[test]
fn workspace_roots_join_the_thread_roots() {
let params = json!({ "cwd": "/w/api", "mcpServers": [], "additionalDirectories": ["/w/web"] });
let mut request = json!({});
apply_thread_config(&params, &mut request);
assert_eq!(request["runtimeWorkspaceRoots"], json!(["/w/api", "/w/web"]));
let mut request = json!({});
apply_thread_config(&json!({ "cwd": "/w/api", "mcpServers": [] }), &mut request);
assert!(request.get("runtimeWorkspaceRoots").is_none());
}
+1 -108
View File
@@ -138,12 +138,6 @@ pub(super) struct Settings {
pub model: String, pub model: String,
pub effort: Option<String>, pub effort: Option<String>,
pub mode: Mode, 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 { impl Settings {
@@ -162,12 +156,6 @@ impl Settings {
result.get("approvalPolicy").unwrap_or(&Value::Null), result.get("approvalPolicy").unwrap_or(&Value::Null),
result.get("sandbox").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.fit_effort(models);
s s
@@ -206,13 +194,6 @@ impl Settings {
self.effort = Some(value.to_owned()); self.effort = Some(value.to_owned());
} }
MODE => self.mode = Mode::parse(value).ok_or_else(|| format!("unknown mode {value}"))?, 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}")), _ => return Err(format!("unknown setting {option}")),
} }
Ok(()) Ok(())
@@ -222,9 +203,6 @@ impl Settings {
pub(super) const MODEL: &str = "model"; pub(super) const MODEL: &str = "model";
pub(super) const EFFORT: &str = "reasoning_effort"; pub(super) const EFFORT: &str = "reasoning_effort";
pub(super) const MODE: &str = "mode"; 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. /// ACP `configOptions`: model, reasoning effort (for models that have it) and mode.
pub(super) fn config_options(models: &[ModelInfo], s: &Settings) -> Value { 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(), "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<_>>(), "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) 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 { fn select_value(value: &str, name: &str, description: Option<&str>) -> Value {
let mut v = json!({ "value": value, "name": name }); let mut v = json!({ "value": value, "name": name });
if let Some(d) = description { if let Some(d) = description {
@@ -657,16 +612,6 @@ pub(super) fn usage(params: &Value) -> Option<Value> {
Some(json!({ "sessionUpdate": "usage_update", "used": used, "size": size })) Some(json!({ "sessionUpdate": "usage_update", "used": used, "size": size }))
} }
/// A thread name from the model's reply to the naming prompt: its first line, without
/// quotes or a closing period. `None` when nothing is left.
pub(super) fn thread_name(reply: &str) -> Option<String> {
const MAX_NAME: usize = 80;
let line = reply.lines().map(str::trim).find(|l| !l.is_empty())?;
let line = line.trim_matches(|c: char| matches!(c, '"' | '\'' | '`' | '“' | '”' | '「' | '」' | '*'));
let line = line.trim_end_matches(['.', '。']).trim();
(!line.is_empty()).then(|| line.chars().take(MAX_NAME).collect())
}
/// How a failed turn is reported. /// How a failed turn is reported.
#[derive(Debug, PartialEq)] #[derive(Debug, PartialEq)]
pub(super) enum Failure { pub(super) enum Failure {
@@ -871,7 +816,6 @@ pub(super) fn history(thread: &Value, cwd: Option<&str>) -> Vec<Value> {
if !text.is_empty() { if !text.is_empty() {
out.push(chunk("agent_message_chunk", text)); out.push(chunk("agent_message_chunk", text));
} }
out.extend(question_update(item));
} }
Some("reasoning") => { Some("reasoning") => {
let text = reasoning_text(item); let text = reasoning_text(item);
@@ -891,36 +835,6 @@ pub(super) fn history(thread: &Value, cwd: Option<&str>) -> Vec<Value> {
out 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). /// A reasoning item's summary (or, without one, its raw text).
pub(super) fn reasoning_text(item: &Value) -> String { pub(super) fn reasoning_text(item: &Value) -> String {
let parts = |k: &str| -> Vec<String> { let parts = |k: &str| -> Vec<String> {
@@ -954,18 +868,8 @@ fn str_of(v: &Value, key: &str) -> Option<String> {
/// Session-scoped MCP configuration, carried in thread/start, resume and fork. /// Session-scoped MCP configuration, carried in thread/start, resume and fork.
pub(super) fn mcp_config(params: &Value) -> Option<Value> { 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(); 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") { if server.get("type").and_then(Value::as_str).is_some_and(|t| t != "stdio") {
continue; continue;
} }
@@ -987,16 +891,5 @@ pub(super) fn mcp_config_with_external(
"args":server.get("args").cloned().unwrap_or_else(||json!([])),"env":env}), "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})) (!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.
}
}
File diff suppressed because it is too large. Load diff
@@ -1,853 +0,0 @@
//! Model catalog, effort levels, context-window tiers, and token pricing from
//! `copilot --headless --stdio` (`models.list` + `models.listTokenPriceUnits`).
use crate::model::{AgentModelPricing, AgentTokenPricing};
use serde_json::{Value, json};
use std::collections::{BTreeMap, HashMap};
pub(super) const MODEL: &str = "model";
pub(super) const EFFORT: &str = "reasoning_effort";
pub(super) const CONTEXT_TIER: &str = "context_tier";
pub(super) const MODE: &str = "mode";
pub(super) const ALLOW_ALL: &str = "allow_all";
const BATCH_TOKENS: f64 = 1_000_000.0;
const NANO_AIU_PER_CREDIT: f64 = 1_000_000_000.0;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum Mode {
Agent,
Plan,
Autopilot,
}
impl Mode {
pub const ALL: [Mode; 3] = [Mode::Agent, Mode::Plan, Mode::Autopilot];
pub fn id(self) -> &'static str {
match self {
Mode::Agent => "agent",
Mode::Plan => "plan",
Mode::Autopilot => "autopilot",
}
}
pub fn wire(self) -> &'static str {
match self {
Mode::Agent => "interactive",
Mode::Plan => "plan",
Mode::Autopilot => "autopilot",
}
}
pub fn name(self) -> &'static str {
match self {
Mode::Agent => "Agent",
Mode::Plan => "Plan",
Mode::Autopilot => "Autopilot",
}
}
pub fn description(self) -> &'static str {
match self {
Mode::Agent => "Default agent mode for conversational interactions",
Mode::Plan => "Plan mode for creating and executing multi-step plans",
Mode::Autopilot => "Autonomous mode that enables allow-all and runs until task completion",
}
}
pub fn parse(value: &str) -> Option<Mode> {
let short = value.rsplit(['#', '/']).next().unwrap_or(value);
match short {
"agent" | "interactive" => Some(Mode::Agent),
"plan" => Some(Mode::Plan),
"autopilot" => Some(Mode::Autopilot),
_ => None,
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub(super) struct ContextTierChoice {
pub id: &'static str,
pub label: String,
pub tokens: u32,
pub description: &'static str,
}
#[derive(Clone, Debug, PartialEq)]
pub(super) struct ModelEntry {
pub id: String,
pub name: String,
pub description: Option<String>,
pub is_default: bool,
pub default_effort: Option<String>,
pub efforts: Vec<String>,
pub context_tiers: Vec<ContextTierChoice>,
pub default_context_tokens: Option<u32>,
pub max_context_tokens: Option<u32>,
pub pricing: Option<AgentModelPricing>,
}
impl ModelEntry {
/// Copilot's default reasoning effort for this model: user setting (`effortLevel`) when
/// supported, otherwise the model's `defaultReasoningEffort`, `"medium"`, or first listed.
pub fn default_effort<'a>(&'a self, user_default: Option<&str>) -> Option<&'a str> {
if let Some(wanted) = user_default
&& let Some(found) = self.efforts.iter().find(|e| e.as_str() == wanted)
{
return Some(found.as_str());
}
if let Some(model_def) = self.default_effort.as_deref()
&& let Some(found) = self.efforts.iter().find(|e| e.as_str() == model_def)
{
return Some(found.as_str());
}
self.efforts.iter().find(|e| e.as_str() == "medium").or_else(|| self.efforts.first()).map(String::as_str)
}
/// Copilot's default context-window tier for this model: user setting (`contextTier`) when
/// supported, otherwise `"default"` (`200K`), or first listed.
pub fn default_context_tier(&self, user_default: Option<&str>) -> Option<&'static str> {
if let Some(wanted) = user_default
&& let Some(found) = self.context_tiers.iter().find(|t| t.id == wanted)
{
return Some(found.id);
}
self.context_tiers.iter().find(|t| t.id == "default").or_else(|| self.context_tiers.first()).map(|t| t.id)
}
/// Active context window capacity in tokens for `tier`.
pub fn context_tokens(&self, tier: Option<&str>) -> Option<u32> {
if let Some(tier) = tier
&& let Some(found) = self.context_tiers.iter().find(|t| t.id == tier)
{
return Some(found.tokens);
}
self.context_tiers
.iter()
.find(|t| t.id == "default")
.or_else(|| self.context_tiers.first())
.map(|t| t.tokens)
.or(self.default_context_tokens)
.or(self.max_context_tokens)
}
}
/// Copilot's own configured defaults from `user.settings.get` (`~/.copilot/config.json`)
/// and optional CLI launch flags (`--model`, `--effort`, `--context`, `--allow-all`).
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(super) struct UserDefaults {
pub model: Option<String>,
pub effort: Option<String>,
pub context_tier: Option<String>,
pub mode: Option<Mode>,
pub allow_all: Option<bool>,
}
impl UserDefaults {
pub fn from_rpc_and_args(settings_rpc: Option<&Value>, args: &[String]) -> Self {
let mut out = Self::default();
if let Some(res) = settings_rpc {
out.model = setting_str(res, "model");
out.effort = setting_str(res, "effortLevel").or_else(|| setting_str(res, "reasoningEffort"));
out.context_tier = setting_str(res, "contextTier");
out.mode = setting_str(res, "defaultMode").and_then(|m| Mode::parse(&m));
out.allow_all = setting_str(res, "defaultPermissionMode").and_then(|p| match p.as_str() {
"allow-all" | "allow_all" | "bypass" | "autopilot" => Some(true),
"manual" => Some(false),
_ => None,
});
}
let mut iter = args.iter().peekable();
while let Some(arg) = iter.next() {
let s = arg.as_str();
if s == "--allow-all" || s == "--yolo" {
out.allow_all = Some(true);
} else if let Some(v) = flag_val(s, "--model", &mut iter) {
out.model = Some(v);
} else if let Some(v) =
flag_val(s, "--effort", &mut iter).or_else(|| flag_val(s, "--reasoning-effort", &mut iter))
{
out.effort = Some(v);
} else if let Some(v) = flag_val(s, "--context", &mut iter) {
out.context_tier = Some(v);
}
}
out
}
}
fn setting_str(res: &Value, key: &str) -> Option<String> {
let settings = res.get("settings");
let raw = settings
.and_then(|s| s.get(key))
.and_then(|entry| entry.get("value").or(Some(entry)))
.or_else(|| res.get(key))?;
raw.as_str().map(str::trim).filter(|s| !s.is_empty()).map(str::to_owned)
}
fn flag_val<'a>(
arg: &'a str,
flag: &str,
iter: &mut std::iter::Peekable<std::slice::Iter<'a, String>>,
) -> Option<String> {
if arg == flag {
return iter.next().map(|v| v.trim()).filter(|v| !v.is_empty()).map(str::to_owned);
}
let prefix = format!("{flag}=");
arg.strip_prefix(&prefix).map(str::trim).filter(|v| !v.is_empty()).map(str::to_owned)
}
#[derive(Clone, Debug, PartialEq)]
pub(super) struct Settings {
pub model: String,
pub effort: Option<String>,
pub context_tier: Option<String>,
pub mode: Mode,
pub allow_all: bool,
defaults: UserDefaults,
/// Explicit per-session user overrides; `None` means track Copilot's default for each model.
explicit_effort: Option<String>,
explicit_context_tier: Option<String>,
}
impl Settings {
pub fn new(models: &[ModelEntry], defaults: &UserDefaults) -> Self {
let model = defaults
.model
.as_deref()
.filter(|id| models.iter().any(|m| m.id == *id))
.or_else(|| models.iter().find(|m| m.is_default && m.id != "auto").map(|m| m.id.as_str()))
.or_else(|| models.iter().find(|m| m.id != "auto").map(|m| m.id.as_str()))
.or_else(|| models.first().map(|m| m.id.as_str()))
.unwrap_or("auto")
.to_owned();
let mode = defaults.mode.unwrap_or(Mode::Agent);
let allow_all = defaults.allow_all.unwrap_or(false) || mode == Mode::Autopilot;
let mut s = Self {
model,
effort: None,
context_tier: None,
mode,
allow_all,
defaults: defaults.clone(),
explicit_effort: None,
explicit_context_tier: None,
};
s.fit_to_model(models);
s
}
pub fn fit_to_model(&mut self, models: &[ModelEntry]) {
let Some(m) = models.iter().find(|m| m.id == self.model) else {
self.effort = None;
self.context_tier = None;
return;
};
self.effort = if m.efforts.is_empty() {
None
} else if let Some(wanted) = self.explicit_effort.as_deref().filter(|w| m.efforts.iter().any(|e| e == *w)) {
Some(wanted.to_owned())
} else {
m.default_effort(self.defaults.effort.as_deref()).map(str::to_owned)
};
self.context_tier = if m.context_tiers.is_empty() {
None
} else if let Some(wanted) =
self.explicit_context_tier.as_deref().filter(|w| m.context_tiers.iter().any(|t| t.id == *w))
{
Some(wanted.to_owned())
} else {
m.default_context_tier(self.defaults.context_tier.as_deref()).map(str::to_owned)
};
}
pub fn set(&mut self, models: &[ModelEntry], option: &str, value: &str) -> Result<(), String> {
match option {
MODEL => {
if !models.is_empty() && !models.iter().any(|m| m.id == value) && value != self.model {
return Err(format!("unknown model {value}"));
}
self.model = value.to_owned();
self.fit_to_model(models);
}
EFFORT => {
let m = models.iter().find(|m| m.id == self.model);
if !m.is_some_and(|m| m.efforts.iter().any(|e| e == value)) {
return Err(format!("{} has no reasoning effort {value}", self.model));
}
self.effort = Some(value.to_owned());
self.explicit_effort = Some(value.to_owned());
}
CONTEXT_TIER => {
let m = models.iter().find(|m| m.id == self.model);
if !m.is_some_and(|m| m.context_tiers.iter().any(|t| t.id == value)) {
return Err(format!("{} has no context tier {value}", self.model));
}
self.context_tier = Some(value.to_owned());
self.explicit_context_tier = Some(value.to_owned());
}
MODE => {
let mode = Mode::parse(value).ok_or_else(|| format!("unknown mode {value}"))?;
self.mode = mode;
if mode == Mode::Autopilot {
self.allow_all = true;
}
}
ALLOW_ALL => match value {
"on" | "true" => self.allow_all = true,
"off" | "false" => self.allow_all = false,
_ => return Err(format!("unknown allow_all value {value}")),
},
_ => return Err(format!("unknown setting {option}")),
}
Ok(())
}
pub fn active_context_tokens(&self, models: &[ModelEntry]) -> Option<u32> {
models.iter().find(|m| m.id == self.model).and_then(|m| m.context_tokens(self.context_tier.as_deref()))
}
}
/// Parses `models.list` + optional `models.listTokenPriceUnits` into catalog entries,
/// prepending `"auto"` when direct models are present or Copilot advertises an enabled Auto tier.
pub(super) fn parse_catalog(list: &Value, price_units: Option<&Value>) -> Vec<ModelEntry> {
let units = parse_price_units(price_units);
let raw = list
.get("models")
.or_else(|| list.get("data"))
.and_then(Value::as_array)
.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)) {
out.push(ModelEntry {
id: "auto".into(),
name: "Auto".into(),
description: Some("Let Copilot pick the best model".into()),
is_default: false,
default_effort: None,
efforts: Vec::new(),
context_tiers: Vec::new(),
default_context_tokens: None,
max_context_tokens: None,
pricing: None,
});
}
for m in raw {
if let Some(entry) = parse_model(m, &units) {
out.push(entry);
}
}
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)
|| m.get("modelPickerEnabled").and_then(Value::as_bool) == Some(false)
{
return None;
}
let name = str_of(m, "name")
.or_else(|| str_of(m, "label"))
.or_else(|| str_of(m, "displayName"))
.filter(|s| !s.is_empty())
.unwrap_or(&id)
.to_owned();
let mut efforts = parse_efforts(m);
efforts.sort_by_key(|e| effort_rank(e));
efforts.dedup();
let limits = m.pointer("/capabilities/limits");
let max_prompt =
limits.and_then(|l| u32_of(l, "max_prompt_tokens").or_else(|| u32_of(l, "maxPromptTokens"))).filter(|&n| n > 0);
let max_window = limits
.and_then(|l| u32_of(l, "max_context_window_tokens").or_else(|| u32_of(l, "maxContextWindowTokens")))
.filter(|&n| n > 0);
let billing = m.get("billing");
let multiplier = billing.and_then(|b| f64_of(b, "multiplier"));
let raw_category = str_of(m, "modelPickerPriceCategory")
.or_else(|| str_of(m, "model_picker_price_category"))
.or_else(|| str_of(m, "priceCategory"))
.or_else(|| str_of(m, "price_category"))
.or_else(|| billing.and_then(|b| str_of(b, "priceCategory").or_else(|| str_of(b, "price_category"))));
let mut cost_tier = raw_category.and_then(normalize_cost_tier).map(str::to_owned);
let token_prices = billing.and_then(|b| b.get("token_prices").or_else(|| b.get("tokenPrices")));
let unit = units.get(&id).copied().unwrap_or(PriceUnit::Credits);
let (mut tiers, default_max, long_max) = parse_token_prices(token_prices, max_prompt, max_window, unit);
let mut context_tiers = Vec::new();
if let (Some(def_tokens), Some(long_tokens)) = (default_max, long_max)
&& def_tokens < long_tokens
{
context_tiers.push(ContextTierChoice {
id: "default",
label: format_tokens(def_tokens),
tokens: def_tokens,
description: "Default recommended context size",
});
context_tiers.push(ContextTierChoice {
id: "long_context",
label: format_tokens(long_tokens),
tokens: long_tokens,
description: "Maximum context window for longer sessions",
});
}
if cost_tier.is_none()
&& let Some(def) = tiers.get("default")
{
cost_tier = Some(infer_cost_tier(def.output).to_owned());
}
if let Some(def_tokens) = default_max.or(max_window).or(max_prompt)
&& let Some(def) = tiers.get_mut("default")
&& def.context_tokens.is_none()
{
def.context_tokens = Some(def_tokens);
}
if let Some(long_tokens) = long_max
&& let Some(long) = tiers.get_mut("long_context")
{
long.context_tokens = Some(long_tokens);
}
let pricing = (!tiers.is_empty() || cost_tier.is_some() || multiplier.is_some()).then_some(AgentModelPricing {
cost_tier,
multiplier,
tiers,
});
let description = multiplier
.map(|mul| {
let clean = round6(mul);
if (clean - clean.round()).abs() < 1e-6 {
format!("{}x", clean.round() as i64)
} else {
format!("{clean}x")
}
})
.or_else(|| str_of(m, "description").filter(|d| !d.is_empty() && *d != name).map(str::to_owned))
.or_else(|| (id == "auto").then(|| "Let Copilot pick the best model".to_owned()));
let is_default = m
.get("is_chat_default")
.or_else(|| m.get("isChatDefault"))
.or_else(|| m.get("isDefault"))
.and_then(Value::as_bool)
.unwrap_or(false);
let default_effort = str_of(m, "defaultReasoningEffort")
.or_else(|| str_of(m, "default_reasoning_effort"))
.map(str::trim)
.filter(|s| !s.is_empty())
.map(str::to_owned);
Some(ModelEntry {
id,
name,
description,
is_default,
default_effort,
efforts,
context_tiers,
default_context_tokens: default_max.or(max_window).or(max_prompt),
max_context_tokens: long_max.or(default_max).or(max_window).or(max_prompt),
pricing,
})
}
fn parse_efforts(m: &Value) -> Vec<String> {
let arr = m
.get("supportedReasoningEfforts")
.or_else(|| m.get("supported_reasoning_efforts"))
.or_else(|| m.pointer("/capabilities/supports/reasoning_effort"))
.or_else(|| m.pointer("/capabilities/supports/reasoningEffort"));
arr.and_then(Value::as_array)
.into_iter()
.flatten()
.filter_map(|v| v.as_str().filter(|s| !s.is_empty()).map(str::to_owned))
.collect()
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum PriceUnit {
Credits,
NanoAiu,
}
fn parse_price_units(raw: Option<&Value>) -> HashMap<String, PriceUnit> {
let mut out = HashMap::new();
let Some(raw) = raw else { return out };
let unit_of = |s: &str| {
if s.eq_ignore_ascii_case("nano_aiu") || s.eq_ignore_ascii_case("nanoaiu") || s.contains("nano") {
Some(PriceUnit::NanoAiu)
} else if s.to_ascii_lowercase().contains("credit") || s.eq_ignore_ascii_case("aic") {
Some(PriceUnit::Credits)
} else {
None
}
};
if let Some(map) =
raw.get("units").or_else(|| raw.get("priceUnits")).or_else(|| raw.get("models")).and_then(Value::as_object)
{
for (k, v) in map {
let u = v
.as_str()
.and_then(unit_of)
.or_else(|| v.get("unit").or_else(|| v.get("priceUnit")).and_then(Value::as_str).and_then(unit_of));
if let Some(u) = u {
out.insert(k.clone(), u);
}
}
}
for key in ["units", "priceUnits", "models"] {
if let Some(arr) = raw.get(key).and_then(Value::as_array) {
for item in arr {
let id = str_of(item, "modelId").or_else(|| str_of(item, "id"));
let u = str_of(item, "unit").or_else(|| str_of(item, "priceUnit")).and_then(unit_of);
if let (Some(id), Some(u)) = (id, u) {
out.insert(id.to_owned(), u);
}
}
}
}
out
}
fn parse_token_prices(
tp: Option<&Value>,
max_prompt: Option<u32>,
max_window: Option<u32>,
unit: PriceUnit,
) -> (BTreeMap<String, AgentTokenPricing>, Option<u32>, Option<u32>) {
let mut tiers = BTreeMap::new();
let Some(tp) = tp else {
return (tiers, None, max_window.or(max_prompt));
};
let batch =
f64_of(tp, "batch_size").or_else(|| f64_of(tp, "batchSize")).filter(|&b| b > 0.0).unwrap_or(BATCH_TOKENS);
let batch_scale = BATCH_TOKENS / batch;
let unit_scale = match unit {
PriceUnit::Credits => 1.0,
PriceUnit::NanoAiu => 1.0 / NANO_AIU_PER_CREDIT,
};
let scale = batch_scale * unit_scale;
let parse_tier = |node: &Value| -> Option<(AgentTokenPricing, Option<u32>)> {
let input = f64_of(node, "input_price").or_else(|| f64_of(node, "inputPrice"))?;
let output = f64_of(node, "output_price").or_else(|| f64_of(node, "outputPrice"))?;
// Guard against raw nano-AIU numbers even if `listTokenPriceUnits` was unavailable.
let effective = if unit == PriceUnit::Credits && (input >= 10_000_000.0 || output >= 10_000_000.0) {
scale / NANO_AIU_PER_CREDIT
} else {
scale
};
let cache_read = f64_of(node, "cache_read_price")
.or_else(|| f64_of(node, "cacheReadPrice"))
.or_else(|| f64_of(node, "cache_price"))
.or_else(|| f64_of(node, "cachePrice"))
.map(|v| round6(v * effective));
let cache_write = f64_of(node, "cache_write_price")
.or_else(|| f64_of(node, "cacheWritePrice"))
.map(|v| round6(v * effective));
let ctx = u32_of(node, "max_prompt_tokens")
.or_else(|| u32_of(node, "maxPromptTokens"))
.or_else(|| u32_of(node, "context_max"))
.or_else(|| u32_of(node, "contextMax"))
.filter(|&n| n > 0);
Some((
AgentTokenPricing {
input: round6(input * effective),
output: round6(output * effective),
cache_read,
cache_write,
context_tokens: ctx,
},
ctx,
))
};
// Both CAPI `/models` (`token_prices.default` + `token_prices.long_context`) and
// `copilot --headless` `models.list` (top-level `tokenPrices` + `tokenPrices.longContext`)
// share the same per-tier fields.
let def_node = tp.get("default").unwrap_or(tp);
let mut def_max = None;
if let Some((def_pricing, ctx)) = parse_tier(def_node) {
def_max = ctx;
tiers.insert("default".into(), def_pricing);
}
let long_node = tp.get("longContext").or_else(|| tp.get("long_context"));
let mut long_max = None;
if let Some(long_node) = long_node
&& let Some((mut long_pricing, ctx)) = parse_tier(long_node)
{
// Use the full context window capacity (`1_000_000`) when available so models whose
// `max_prompt_tokens` deduct `max_output_tokens` (e.g. `872_000` = `1M - 128K` on
// GPT-6 Sol, `936_000` = `1M - 64K` on Gemini 4 Carbon) display cleanly as `1M`.
let cap = match (ctx, max_window) {
(Some(c), Some(w)) if w >= c => Some(w),
(Some(c), _) => Some(c),
(None, w) => w.or(max_prompt),
};
long_max = cap;
long_pricing.context_tokens = cap;
tiers.insert("long_context".into(), long_pricing);
} else if let (Some(d), Some(p)) = (def_max, max_prompt)
&& d < p
&& let Some(def) = tiers.get("default").cloned()
{
let cap = max_window.filter(|&w| w >= p).unwrap_or(p);
long_max = Some(cap);
tiers.insert("long_context".into(), AgentTokenPricing { context_tokens: Some(cap), ..def });
}
(tiers, def_max, long_max)
}
fn normalize_cost_tier(raw: &str) -> Option<&'static str> {
match raw.trim().to_ascii_lowercase().as_str() {
"lightweight" | "low" => Some("low"),
"versatile" | "medium" | "standard" => Some("medium"),
"powerful" | "high" | "premium" => Some("high"),
"very_high" | "veryhigh" => Some("very_high"),
_ => None,
}
}
fn infer_cost_tier(output_credits_per_1m: f64) -> &'static str {
if output_credits_per_1m < 300.0 {
"low"
} else if output_credits_per_1m <= 1500.0 {
"medium"
} else {
"high"
}
}
/// Formats token capacity matching VS Code (`200000` → `"200K"`, `1000000` → `"1M"`).
pub(super) fn format_tokens(tokens: u32) -> String {
if tokens >= 1_000_000 {
let m = (f64::from(tokens) / 1_000_000.0 * 10.0).floor() / 10.0;
if (m - m.round()).abs() < 1e-6 { format!("{}M", m.round() as u32) } else { format!("{m:.1}M") }
} else if tokens > 900_000 {
"1M".into()
} else if tokens >= 1_000 {
format!("{}K", (f64::from(tokens) / 1_000.0).round() as u32)
} else {
tokens.to_string()
}
}
pub(super) fn effort_rank(effort: &str) -> u8 {
match effort {
"none" => 0,
"minimal" => 1,
"low" => 2,
"medium" => 3,
"high" => 4,
"xhigh" | "extra_high" => 5,
"max" => 6,
_ => 3,
}
}
pub(super) fn effort_label(effort: &str) -> (&'static str, &'static str) {
match effort {
"none" => ("None", "No additional reasoning; fastest responses."),
"minimal" => ("Minimal", "Least reasoning; fastest responses."),
"low" => ("Low", "Minimal reasoning before responding."),
"medium" => ("Medium", "Balanced reasoning and speed."),
"high" => ("High", "More thorough reasoning; slower responses."),
"xhigh" => ("Extra High", "Extensive reasoning for the hardest problems."),
"max" => ("Max", "Maximum reasoning; slowest but most thorough."),
_ => ("Default", ""),
}
}
/// ACP `configOptions` for the active session settings.
pub(super) fn config_options(models: &[ModelEntry], s: &Settings) -> Value {
let mut model_values: Vec<Value> = models.iter().map(model_option_value).collect();
if !s.model.is_empty() && !models.iter().any(|m| m.id == s.model) {
model_values.push(json!({ "value": s.model, "name": s.model }));
}
let mut out = Vec::new();
if !model_values.is_empty() {
out.push(json!({
"id": MODEL,
"name": "Model",
"category": "model",
"type": "select",
"currentValue": s.model,
"options": model_values,
}));
}
if let Some(m) = models.iter().find(|m| m.id == s.model) {
if let (Some(opt), Some(current)) = (effort_option_for(m, s.effort.as_deref()), s.effort.as_deref()) {
let mut o = opt;
o["currentValue"] = json!(current);
out.push(o);
}
if let (Some(opt), Some(current)) =
(context_tier_option_for(m, s.context_tier.as_deref()), s.context_tier.as_deref())
{
let mut o = opt;
o["currentValue"] = json!(current);
out.push(o);
}
}
out.push(json!({
"id": MODE,
"name": "Mode",
"category": "mode",
"type": "select",
"currentValue": s.mode.id(),
"options": Mode::ALL.iter().map(|m| json!({
"value": m.id(),
"name": m.name(),
"description": m.description(),
})).collect::<Vec<_>>(),
}));
out.push(json!({
"id": ALLOW_ALL,
"name": "Allow All",
"category": "permissions",
"type": "select",
"currentValue": if s.allow_all { "on" } else { "off" },
"options": [
{ "value": "on", "name": "On", "description": "Automatically approve all tool, path, and URL requests" },
{ "value": "off", "name": "Off", "description": "Require approval for tool, path, and URL requests" },
],
}));
Value::Array(out)
}
/// Per-model options (`[reasoning_effort?, context_tier?]`) for every model in `models`,
/// each defaulted to Copilot's own defaults (respecting `user.settings.get` / CLI flags).
pub(super) fn per_model_options(models: &[ModelEntry], defaults: &UserDefaults) -> Vec<(String, Vec<Value>)> {
models
.iter()
.map(|m| {
let mut opts = Vec::new();
if let Some(effort) = effort_option_for(m, m.default_effort(defaults.effort.as_deref())) {
opts.push(effort);
}
if let Some(ctx) = context_tier_option_for(m, m.default_context_tier(defaults.context_tier.as_deref())) {
opts.push(ctx);
}
(m.id.clone(), opts)
})
.collect()
}
fn model_option_value(m: &ModelEntry) -> Value {
let mut v = json!({ "value": m.id, "name": m.name });
if let Some(d) = &m.description {
v["description"] = json!(d);
}
if let Some(pricing) = &m.pricing {
let mut meta = serde_json::Map::new();
meta.insert("pricing".into(), json!(pricing));
if let Some(cat) = &pricing.cost_tier {
meta.insert("copilotPriceCategory".into(), json!(cat));
}
v["_meta"] = Value::Object(meta);
}
v
}
fn effort_option_for(m: &ModelEntry, current: Option<&str>) -> Option<Value> {
if m.efforts.len() <= 1 && m.efforts.is_empty() {
return None;
}
let default = current.filter(|c| m.efforts.iter().any(|e| e == *c)).or_else(|| m.default_effort(None))?;
let options: Vec<Value> = m
.efforts
.iter()
.map(|e| {
let (label, desc) = effort_label(e);
let name = if label == "Default" { capitalize(e) } else { label.to_owned() };
let mut item = json!({ "value": e, "name": name });
if !desc.is_empty() {
item["description"] = json!(desc);
}
item
})
.collect();
Some(json!({
"id": EFFORT,
"name": "Effort Level",
"description": "How much reasoning the model performs before responding. Higher effort can improve quality at the cost of speed.",
"category": "thought_level",
"type": "select",
"currentValue": default,
"options": options,
}))
}
fn context_tier_option_for(m: &ModelEntry, current: Option<&str>) -> Option<Value> {
if m.context_tiers.len() < 2 {
return None;
}
let default =
current.filter(|c| m.context_tiers.iter().any(|t| t.id == *c)).or_else(|| m.default_context_tier(None))?;
let options: Vec<Value> = m
.context_tiers
.iter()
.map(|t| {
json!({
"value": t.id,
"name": t.label,
"description": t.description,
})
})
.collect();
Some(json!({
"id": CONTEXT_TIER,
"name": "Context Size",
"description": "Context window size for this model.",
"category": "model_config",
"type": "select",
"currentValue": default,
"options": options,
}))
}
fn capitalize(s: &str) -> String {
let mut chars = s.chars();
chars.next().map(|c| c.to_uppercase().chain(chars).collect()).unwrap_or_default()
}
fn round6(n: f64) -> f64 {
let r = (n * 1_000_000.0).round() / 1_000_000.0;
if r == 0.0 { 0.0 } else { r }
}
fn str_of<'a>(v: &'a Value, key: &str) -> Option<&'a str> {
v.get(key).and_then(Value::as_str)
}
fn f64_of(v: &Value, key: &str) -> Option<f64> {
v.get(key).and_then(Value::as_f64).filter(|n| n.is_finite())
}
fn u32_of(v: &Value, key: &str) -> Option<u32> {
v.get(key).and_then(Value::as_u64).and_then(|n| u32::try_from(n).ok())
}
@@ -1,753 +0,0 @@
use super::models::{self, CONTEXT_TIER, EFFORT, MODEL, Mode, Settings, UserDefaults};
use super::{acp_args, acp_fallback_spec, attach, headless_args};
use crate::config;
use crate::provider::Driver;
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!({
"models": [
{
"id": "gemini-4-carbon",
"name": "Gemini 4 Carbon",
"priceCategory": "versatile",
"supportedReasoningEfforts": ["low", "medium", "high"],
"defaultReasoningEffort": "medium",
"capabilities": {
"supports": { "vision": true, "reasoningEffort": true },
"limits": {
"max_context_window_tokens": 1_000_000,
"max_prompt_tokens": 1_000_000,
"max_output_tokens": 64_000
}
},
"billing": {
"is_premium": true,
"multiplier": 1.0,
"token_prices": {
"batch_size": 1_000_000,
"preferred_tier": "default",
"default": {
"input_price": 100.0,
"output_price": 500.0,
"cache_read_price": 10.0,
"cache_write_price": 0.0,
"max_prompt_tokens": 200_000
},
"long_context": {
"input_price": 200.0,
"output_price": 1000.0,
"cache_read_price": 10.0,
"cache_write_price": 0.0,
"max_prompt_tokens": 1_000_000
}
}
}
},
{
"id": "gpt-5.6-sol",
"name": "GPT-5.6 Sol",
"priceCategory": "powerful",
"supportedReasoningEfforts": ["none", "low", "medium", "high", "xhigh", "max"],
"defaultReasoningEffort": "medium",
"capabilities": {
"supports": { "vision": true },
"limits": {
"max_context_window_tokens": 1_000_000,
"max_prompt_tokens": 1_000_000
}
},
"billing": {
"multiplier": 2.0,
"token_prices": {
"batch_size": 1_000_000,
"default": {
"input_price": 250_000_000_000.0,
"output_price": 1_500_000_000_000.0,
"cache_read_price": 25_000_000_000.0,
"cache_write_price": 0.0,
"max_prompt_tokens": 200_000
},
"long_context": {
"input_price": 500_000_000_000.0,
"output_price": 3_000_000_000_000.0,
"cache_read_price": 50_000_000_000.0,
"cache_write_price": 0.0,
"max_prompt_tokens": 1_000_000
}
}
}
},
{
"id": "mai-experimental-internal",
"name": "MAI Experimental",
"priceCategory": "lightweight",
"supportedReasoningEfforts": ["low", "medium"],
"capabilities": {
"limits": {
"max_context_window_tokens": 131_072,
"max_prompt_tokens": 131_072
}
},
"billing": {
"multiplier": 0.33
}
}
]
})
}
fn sample_price_units() -> Value {
json!({
"units": {
"gemini-4-carbon": "ai_credits",
"gpt-5.6-sol": "nano_aiu"
}
})
}
#[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()));
assert_eq!(
catalog.iter().map(|m| m.id.as_str()).collect::<Vec<_>>(),
["auto", "gemini-4-carbon", "gpt-5.6-sol", "mai-experimental-internal"]
);
let gemini = catalog.iter().find(|m| m.id == "gemini-4-carbon").unwrap();
assert_eq!(gemini.default_effort(None), Some("medium"));
assert_eq!(gemini.default_context_tier(None), Some("default"));
assert_eq!(
gemini.context_tiers.iter().map(|t| (t.id, t.label.as_str(), t.tokens)).collect::<Vec<_>>(),
[("default", "200K", 200_000), ("long_context", "1M", 1_000_000)]
);
let pricing = gemini.pricing.as_ref().unwrap();
assert_eq!(pricing.cost_tier.as_deref(), Some("medium"));
let long_p = &pricing.tiers["long_context"];
assert_eq!(
(long_p.input, long_p.output, long_p.cache_read, long_p.cache_write),
(200.0, 1000.0, Some(10.0), Some(0.0))
);
let def_p = &pricing.tiers["default"];
assert_eq!((def_p.input, def_p.output), (100.0, 500.0));
// Nano-AIU conversion (10^9 nano-AIU = 1 AI Credit).
let sol = catalog.iter().find(|m| m.id == "gpt-5.6-sol").unwrap();
assert_eq!(sol.default_effort(None), Some("medium"));
assert_eq!(sol.default_context_tier(None), Some("default"));
let sol_long = &sol.pricing.as_ref().unwrap().tiers["long_context"];
assert_eq!((sol_long.input, sol_long.output, sol_long.cache_read), (500.0, 3000.0, Some(50.0)));
// Single-window model has no multi-tier `context_tier` toggle.
let mai = catalog.iter().find(|m| m.id == "mai-experimental-internal").unwrap();
assert!(mai.context_tiers.is_empty());
assert_eq!(mai.default_effort(None), Some("medium"));
// Initial settings pick Copilot's own defaults (`medium` effort + `default` 200K context).
let mut s = Settings::new(&catalog, &UserDefaults::default());
assert_eq!(s.model, "gemini-4-carbon");
assert_eq!(s.effort.as_deref(), Some("medium"));
assert_eq!(s.context_tier.as_deref(), Some("default"));
assert_eq!(s.active_context_tokens(&catalog), Some(200_000));
// Switching to GPT-5.6 Sol without an explicit override stays on Copilot's defaults (`medium` + `default`).
s.set(&catalog, MODEL, "gpt-5.6-sol").unwrap();
assert_eq!(s.effort.as_deref(), Some("medium"));
assert_eq!(s.context_tier.as_deref(), Some("default"));
// Explicit session overrides (`xhigh` + `long_context`) stick across models that support them,
// and fall back to Copilot's default when switching to a model that does not.
s.set(&catalog, EFFORT, "xhigh").unwrap();
s.set(&catalog, CONTEXT_TIER, "long_context").unwrap();
assert_eq!(s.active_context_tokens(&catalog), Some(1_000_000));
s.set(&catalog, MODEL, "mai-experimental-internal").unwrap();
assert_eq!(s.effort.as_deref(), Some("medium"));
assert_eq!(s.context_tier, None);
// User settings from `user.settings.get` (1.0.112+ `{ value, default, isDefault }` shape) and CLI flags are honored.
let rpc_settings = json!({
"settings": {
"model": { "value": "gpt-5.6-sol", "default": null, "isDefault": false },
"effortLevel": { "value": "high", "default": null, "isDefault": false },
"contextTier": { "value": "long_context", "default": null, "isDefault": false },
"defaultMode": { "value": "plan", "default": "interactive", "isDefault": false },
}
});
let user_defs = UserDefaults::from_rpc_and_args(Some(&rpc_settings), &[]);
let configured = Settings::new(&catalog, &user_defs);
assert_eq!(configured.model, "gpt-5.6-sol");
assert_eq!(configured.effort.as_deref(), Some("high"));
assert_eq!(configured.context_tier.as_deref(), Some("long_context"));
assert_eq!(configured.mode, Mode::Plan);
// Per-model discovery options preserve pricing on `model` values and emit Copilot's defaults.
let raw = models::config_options(&catalog, &Settings::new(&catalog, &UserDefaults::default()));
let parsed = config::parse_options(&raw);
let model_opt = parsed.iter().find(|o| o.id == MODEL).unwrap();
let gem_val = model_opt.values.iter().find(|v| v.value == "gemini-4-carbon").unwrap();
assert_eq!(gem_val.pricing.as_ref().unwrap().cost_tier.as_deref(), Some("medium"));
assert_eq!(parsed.iter().find(|o| o.id == EFFORT).unwrap().current.as_deref(), Some("medium"));
assert_eq!(parsed.iter().find(|o| o.id == CONTEXT_TIER).unwrap().current.as_deref(), Some("default"));
}
#[test]
fn parses_headless_sdk_models_list_flat_token_prices_and_single_tier_models() {
let sdk_list = json!({
"models": [
{ "id": "auto", "name": "Auto" },
{
"id": "gemini-4-carbon",
"name": "Gemini 4 Carbon",
"modelPickerCategory": "powerful",
"modelPickerPriceCategory": "medium",
"supportedReasoningEfforts": ["low", "medium", "high"],
"capabilities": {
"limits": {
"max_context_window_tokens": 1_000_000,
"max_output_tokens": 64_000,
"max_prompt_tokens": 936_000
}
},
"billing": {
"tokenPrices": {
"inputPrice": 200,
"outputPrice": 1000,
"cachePrice": 10,
"cacheReadPrice": 10,
"cacheWritePrice": 0,
"contextMax": 200_000,
"maxPromptTokens": 200_000,
"batchSize": 1_000_000,
"longContext": {
"inputPrice": 200,
"outputPrice": 1000,
"cachePrice": 10,
"cacheReadPrice": 10,
"cacheWritePrice": 0,
"contextMax": 936_000,
"maxPromptTokens": 936_000
}
}
}
},
{
"id": "gpt-6-sol",
"name": "GPT-6 Sol",
"modelPickerPriceCategory": "medium",
"supportedReasoningEfforts": ["none", "low", "medium", "high", "xhigh", "max"],
"capabilities": {
"limits": {
"max_context_window_tokens": 1_000_000,
"max_output_tokens": 128_000,
"max_prompt_tokens": 872_000
}
},
"billing": {
"tokenPrices": {
"inputPrice": 250,
"outputPrice": 1250,
"contextMax": 272_000,
"maxPromptTokens": 272_000,
"batchSize": 1_000_000,
"longContext": {
"inputPrice": 500,
"outputPrice": 2500,
"contextMax": 872_000,
"maxPromptTokens": 872_000
}
}
}
},
{
"id": "gpt-5.3-codex",
"name": "GPT-5.3-Codex",
"modelPickerPriceCategory": "medium",
"supportedReasoningEfforts": ["low", "medium", "high", "xhigh"],
"capabilities": {
"limits": {
"max_context_window_tokens": 400_000,
"max_output_tokens": 128_000,
"max_prompt_tokens": 272_000
}
},
"billing": {
"tokenPrices": {
"inputPrice": 150,
"outputPrice": 600,
"contextMax": 272_000,
"maxPromptTokens": 272_000,
"batchSize": 1_000_000
}
}
}
]
});
let units = json!({
"units": [
{ "modelId": "gemini-4-carbon", "unit": "ai_credits" },
{ "modelId": "gpt-6-sol", "unit": "ai_credits" },
{ "modelId": "gpt-5.3-codex", "unit": "ai_credits" }
]
});
let catalog = models::parse_catalog(&sdk_list, Some(&units));
let carbon = catalog.iter().find(|m| m.id == "gemini-4-carbon").unwrap();
assert_eq!(
carbon.context_tiers.iter().map(|t| (t.id, t.label.as_str())).collect::<Vec<_>>(),
[("default", "200K"), ("long_context", "1M")]
);
let cp = carbon.pricing.as_ref().unwrap();
assert_eq!(cp.cost_tier.as_deref(), Some("medium"));
assert_eq!((cp.tiers["long_context"].input, cp.tiers["long_context"].output), (200.0, 1000.0));
let sol = catalog.iter().find(|m| m.id == "gpt-6-sol").unwrap();
assert_eq!(
sol.context_tiers.iter().map(|t| (t.id, t.label.as_str())).collect::<Vec<_>>(),
[("default", "272K"), ("long_context", "1M")]
);
let codex = catalog.iter().find(|m| m.id == "gpt-5.3-codex").unwrap();
assert!(codex.context_tiers.is_empty(), "single-tier model must not get a synthetic long_context tier");
}
#[test]
fn headless_and_acp_args_roundtrip_while_preserving_user_flags() {
assert_eq!(headless_args(&["--acp".into()]), vec!["--headless", "--no-auto-update", "--stdio"]);
assert_eq!(
headless_args(&["--log-level".into(), "debug".into(), "--headless".into(), "--stdio".into()]),
vec!["--log-level", "debug", "--headless", "--stdio", "--no-auto-update"]
);
assert_eq!(
acp_args(&[
"--headless".into(),
"--no-auto-update".into(),
"--stdio".into(),
"--context".into(),
"long_context".into()
]),
vec!["--acp", "--context", "long_context"]
);
let spec = crate::provider::builtin_spec("copilot").unwrap();
assert_eq!(spec.driver, Driver::Copilot);
let fallback = acp_fallback_spec(&spec);
assert_eq!(fallback.driver, Driver::Acp);
assert_eq!(fallback.args, vec!["--acp"]);
}
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 {
fn on_notification(&self, _method: &str, _params: Value) {}
fn on_request(&self, method: &str, params: Value) -> Result<Value, (i64, String)> {
self.calls.lock().push((method.to_owned(), params.clone()));
match method {
"connect" => Ok(json!({ "ok": true, "protocolVersion": 3, "version": "1.0.112" })),
"models.list" => Ok(sample_models_list()),
"models.listTokenPriceUnits" => Ok(sample_price_units()),
"user.settings.get" => Ok(json!({ "settings": { "model": "gemini-4-carbon" } })),
"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();
std::thread::spawn(move || {
let _ = peer.notify(
"session.event",
json!({
"sessionId": sid,
"event": {
"id": "e1",
"type": "session.usage_info",
"data": { "currentTokens": 42_000, "tokenLimit": 1_000_000 }
}
}),
);
let _ = peer.notify(
"session.event",
json!({
"sessionId": sid,
"event": {
"id": "e2",
"type": "assistant.message_delta",
"data": { "messageId": "m1", "deltaContent": "Hello from 1M context!" }
}
}),
);
let _ = peer.notify(
"session.event",
json!({
"sessionId": sid,
"event": {
"id": "e3",
"type": "session.idle",
"data": { "aborted": false, "mode": "interactive" }
}
}),
);
});
}
Ok(json!({ "messageId": "msg-1" }))
}
_ => Err((codes::METHOD_NOT_FOUND, format!("unexpected {method}"))),
}
}
}
struct CollectUpdates(Mutex<Vec<Value>>);
impl Handler for CollectUpdates {
fn on_notification(&self, method: &str, params: Value) {
if method == "session/update" {
self.0.lock().push(params["update"].clone());
}
}
fn on_request(&self, method: &str, _params: Value) -> Result<Value, (i64, String)> {
Err((codes::METHOD_NOT_FOUND, format!("unexpected {method}")))
}
}
#[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 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["agentInfo"]["version"], "1.0.112");
assert_eq!(init["agentCapabilities"]["_meta"]["openidea"]["steer"], true);
let created: Value = client.request("session/new", json!({ "cwd": "/tmp", "mcpServers": [] }), None).await.unwrap();
assert_eq!(created["sessionId"], "cop-sess-1");
// Verify `session.create` sent `"trustWorkingDirectory": "session"`, `gemini-4-carbon`,
// and Copilot's own defaults (`reasoningEffort: "medium"` and `contextTier: "default"`).
{
let calls = server.calls.lock();
let (_, create_params) = calls.iter().find(|(m, _)| m == "session.create").unwrap();
assert_eq!(create_params["trustWorkingDirectory"], "session");
assert_eq!(create_params["model"], "gemini-4-carbon");
assert_eq!(create_params["reasoningEffort"], "medium");
assert_eq!(create_params["contextTier"], "default");
}
// Switch Context Size up to 1M (`long_context`) and Effort to `high` live via `session/set_config_option`.
let _: Value = client
.request(
"session/set_config_option",
json!({
"sessionId": "cop-sess-1",
"configId": "reasoning_effort",
"value": "high"
}),
None,
)
.await
.unwrap();
let switched_1m: Value = client
.request(
"session/set_config_option",
json!({
"sessionId": "cop-sess-1",
"configId": "context_tier",
"value": "long_context"
}),
None,
)
.await
.unwrap();
let opts_1m = config::options_of(&switched_1m);
assert_eq!(opts_1m.iter().find(|o| o.id == "context_tier").unwrap().current.as_deref(), Some("long_context"));
// Run a turn and verify 1M usage_update + streamed message chunk.
let prompt_res: Value = client
.request(
"session/prompt",
json!({
"sessionId": "cop-sess-1",
"prompt": [{ "type": "text", "text": "Explain architecture" }]
}),
None,
)
.await
.unwrap();
assert_eq!(prompt_res["stopReason"], "end_turn");
{
let seen = updates.0.lock();
assert!(
seen.iter().any(|u| u["sessionUpdate"] == "usage_update" && u["size"] == 1_000_000 && u["used"] == 42_000)
);
assert!(
seen.iter().any(
|u| u["sessionUpdate"] == "agent_message_chunk" && u["content"]["text"] == "Hello from 1M context!"
)
);
}
// Switch Context Size back down to 200K (`default`) live via `session/set_config_option`.
let switched: Value = client
.request(
"session/set_config_option",
json!({
"sessionId": "cop-sess-1",
"configId": "context_tier",
"value": "default"
}),
None,
)
.await
.unwrap();
let opts = config::options_of(&switched);
assert_eq!(opts.iter().find(|o| o.id == "context_tier").unwrap().current.as_deref(), Some("default"));
{
let calls = server.calls.lock();
let (_, sw_params) = calls.iter().rfind(|(m, _)| m == "session.model.switchTo").unwrap();
assert_eq!(sw_params["modelId"], "gemini-4-carbon");
assert_eq!(sw_params["reasoningEffort"], "high");
assert_eq!(sw_params["contextTier"], "default");
}
// Switching context_tier immediately emits an updated `usage_update` with `size: 200_000`.
assert!(
updates
.0
.lock()
.iter()
.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"));
}
@@ -1,613 +0,0 @@
//! Pure translations between Copilot headless JSON-RPC payloads (`session.event`,
//! permissions, slash commands, MCP servers) and ACP v1.
use crate::LIMITS_UPDATE;
use serde_json::{Map, Value, json};
use std::collections::{HashMap, HashSet};
use std::path::Path;
const MAX_OUTPUT: usize = 64 * 1024;
#[derive(Default)]
pub(super) struct EventTranslator {
/// Assistant message IDs that already streamed deltas, so final `assistant.message` won't duplicate them.
streamed_messages: HashSet<String>,
/// Tool call metadata captured on `tool.execution_start`, keyed by `toolCallId`.
tools: HashMap<String, ToolInfo>,
/// Subagents started in this session (`toolCallId` → subagent session id).
subagents: HashMap<String, String>,
/// Last reported prompt token count, used when updating context size.
pub last_used_tokens: Option<u32>,
}
#[derive(Clone, Debug)]
struct ToolInfo {
kind: &'static str,
title: String,
locations: Vec<Value>,
output: String,
diffs: Vec<Value>,
}
/// An ACP notification `(session_id, update)` produced from a Copilot `session.event`.
pub(super) struct Translated {
pub updates: Vec<(String, Value)>,
pub terminal: Option<TurnTerminal>,
}
#[derive(Debug, Clone, PartialEq)]
pub(super) enum TurnTerminal {
Idle { aborted: bool },
Error { message: String, data: Option<Value> },
}
impl EventTranslator {
pub fn reset_turn(&mut self) {
self.streamed_messages.clear();
}
pub fn translate(&mut self, main_session: &str, event: &Value, fallback_limit: Option<u32>) -> Translated {
let mut out = Translated { updates: Vec::new(), terminal: None };
let event_type = str_of(event, "type").unwrap_or_default();
let data = event.get("data").unwrap_or(&Value::Null);
let agent_id = str_of(event, "agentId").filter(|s| !s.is_empty());
let target_session =
agent_id.map(|id| format!("{main_session}:sub:{id}")).unwrap_or_else(|| main_session.to_owned());
match event_type {
"assistant.reasoning_delta" => {
let delta = str_of(data, "deltaContent").or_else(|| str_of(data, "content")).unwrap_or_default();
if !delta.is_empty() {
out.updates.push((
target_session,
json!({ "sessionUpdate": "agent_thought_chunk", "content": { "type": "text", "text": delta } }),
));
}
}
"assistant.message_delta" => {
if data.get("parentToolCallId").and_then(Value::as_str).is_some() && agent_id.is_none() {
return out;
}
if let Some(mid) = str_of(data, "messageId") {
self.streamed_messages.insert(mid.to_owned());
}
let delta = str_of(data, "deltaContent").unwrap_or_default();
if !delta.is_empty() {
out.updates.push((
target_session,
json!({ "sessionUpdate": "agent_message_chunk", "content": { "type": "text", "text": delta } }),
));
}
}
"assistant.message" => {
if data.get("parentToolCallId").and_then(Value::as_str).is_some() && agent_id.is_none() {
return out;
}
let already = str_of(data, "messageId").is_some_and(|mid| self.streamed_messages.contains(mid));
if !already && let Some(content) = str_of(data, "content").filter(|c| !c.is_empty()) {
out.updates.push((
target_session,
json!({ "sessionUpdate": "agent_message_chunk", "content": { "type": "text", "text": content } }),
));
}
}
"tool.execution_start" => {
let tool_name = str_of(data, "toolName").unwrap_or_default();
if matches!(tool_name, "report_intent" | "tool_search_tool" | "tool_search_tool_regex") {
return out;
}
let Some(call_id) = str_of(data, "toolCallId").filter(|s| !s.is_empty()) else { return out };
let args = data.get("arguments").unwrap_or(&Value::Null);
if tool_name == "task" && agent_id.is_none() {
let sub_id = format!("{main_session}:task:{call_id}");
self.subagents.insert(call_id.to_owned(), sub_id.clone());
let title = str_of(args, "name").or_else(|| str_of(args, "agent_type")).unwrap_or("Subagent");
let desc = str_of(args, "description");
let prompt = str_of(args, "prompt");
out.updates.push((
main_session.to_owned(),
json!({
"sessionUpdate": "subagent_update",
"subagentId": sub_id,
"title": title,
"description": desc,
"prompt": prompt,
"status": "running",
"cancellable": false,
}),
));
return out;
}
let info = describe_tool(tool_name, args);
let mut update = json!({
"sessionUpdate": "tool_call",
"toolCallId": call_id,
"title": info.title,
"kind": info.kind,
"status": "in_progress",
});
if !info.locations.is_empty() {
update["locations"] = Value::Array(info.locations.clone());
}
if !info.diffs.is_empty() {
update["content"] = Value::Array(info.diffs.clone());
}
self.tools.insert(call_id.to_owned(), info);
out.updates.push((target_session, update));
}
"tool.execution_partial_result" | "tool.shell_output" => {
let Some(call_id) = str_of(data, "toolCallId") else { return out };
let chunk = str_of(data, "partialOutput")
.or_else(|| str_of(data, "output"))
.or_else(|| str_of(data, "chunk"))
.unwrap_or_default();
if chunk.is_empty() {
return out;
}
if let Some(info) = self.tools.get_mut(call_id) {
info.output.push_str(chunk);
trim_tail(&mut info.output);
let content = tool_content(&info.output, &info.diffs);
out.updates.push((
target_session,
json!({
"sessionUpdate": "tool_call_update",
"toolCallId": call_id,
"content": content,
}),
));
}
}
"tool.execution_complete" => {
let Some(call_id) = str_of(data, "toolCallId") else { return out };
let success = data.get("success").and_then(Value::as_bool).unwrap_or(true);
let result_text = extract_tool_result_text(data);
if let Some(sub_id) = self.subagents.remove(call_id) {
out.updates.push((
main_session.to_owned(),
json!({
"sessionUpdate": "subagent_update",
"subagentId": sub_id,
"status": if success { "done" } else { "failed" },
"reply": result_text,
"error": (!success).then(|| result_text.clone()).flatten(),
}),
));
return out;
}
let Some(mut info) = self.tools.remove(call_id) else { return out };
if info.output.is_empty()
&& let Some(t) = result_text
&& info.kind != "edit"
{
info.output = t;
trim_tail(&mut info.output);
}
let mut update = json!({
"sessionUpdate": "tool_call_update",
"toolCallId": call_id,
"status": if success { "completed" } else { "failed" },
});
let content = tool_content(&info.output, &info.diffs);
if !content.is_empty() {
update["content"] = Value::Array(content);
}
out.updates.push((target_session, update));
}
"subagent.started" => {
if let Some(call_id) = str_of(data, "toolCallId") {
let sub_id = self
.subagents
.entry(call_id.to_owned())
.or_insert_with(|| format!("{main_session}:task:{call_id}"))
.clone();
let title = str_of(data, "agentDisplayName").or_else(|| str_of(data, "agentName"));
let desc = str_of(data, "agentDescription");
out.updates.push((
main_session.to_owned(),
json!({
"sessionUpdate": "subagent_update",
"subagentId": sub_id,
"title": title,
"description": desc,
"status": "running",
}),
));
}
}
"subagent.failed" => {
if let Some(call_id) = str_of(data, "toolCallId")
&& let Some(sub_id) = self.subagents.get(call_id).cloned()
{
out.updates.push((
main_session.to_owned(),
json!({
"sessionUpdate": "subagent_update",
"subagentId": sub_id,
"status": "failed",
"error": str_of(data, "error").or_else(|| str_of(data, "message")),
}),
));
}
}
"session.title_changed" => {
if let Some(title) = str_of(data, "title").map(str::trim).filter(|t| !t.is_empty()) {
out.updates.push((
main_session.to_owned(),
json!({ "sessionUpdate": "session_info_update", "title": title }),
));
}
}
"session.usage_info" => {
let used = data.get("currentTokens").and_then(Value::as_u64).and_then(|n| u32::try_from(n).ok());
let limit = data
.get("tokenLimit")
.and_then(Value::as_u64)
.and_then(|n| u32::try_from(n).ok())
.filter(|&n| n > 0)
.or(fallback_limit);
if let (Some(used), Some(size)) = (used, limit) {
self.last_used_tokens = Some(used);
out.updates.push((
main_session.to_owned(),
json!({ "sessionUpdate": "usage_update", "used": used, "size": size }),
));
}
}
"assistant.usage" => {
if agent_id.is_none() {
let used = data.get("inputTokens").and_then(Value::as_u64).and_then(|n| u32::try_from(n).ok());
if let (Some(used), Some(size)) = (used, fallback_limit.filter(|&s| s > 0)) {
self.last_used_tokens = Some(used);
out.updates.push((
main_session.to_owned(),
json!({ "sessionUpdate": "usage_update", "used": used, "size": size }),
));
}
}
if let Some(limits) = quota_limits(data.get("quotaSnapshots")) {
out.updates.push((main_session.to_owned(), limits));
}
}
"session.idle" if agent_id.is_none() => {
let mode = str_of(data, "mode").unwrap_or_default();
if mode != "autopilot" {
let aborted = data.get("aborted").and_then(Value::as_bool).unwrap_or(false);
out.terminal = Some(TurnTerminal::Idle { aborted });
}
}
"session.autopilot_stopped" if agent_id.is_none() => {
let reason = str_of(data, "reason").unwrap_or_default();
if reason == "error" {
out.terminal = Some(TurnTerminal::Error { message: "Autopilot request failed".into(), data: None });
} else {
out.terminal = Some(TurnTerminal::Idle { aborted: reason == "aborted" });
}
}
"session.error" if agent_id.is_none() => {
let message = str_of(data, "message").unwrap_or("Copilot reported an error.").to_owned();
out.terminal = Some(TurnTerminal::Error { message, data: Some(data.clone()) });
}
_ => {}
}
out
}
}
fn describe_tool(name: &str, args: &Value) -> ToolInfo {
let mut locations = Vec::new();
let mut diffs = Vec::new();
if let Some(p) = str_of(args, "path").or_else(|| str_of(args, "filePath")).filter(|p| !p.is_empty()) {
locations.push(json!({ "path": p }));
}
let (kind, title) = match name {
"bash" | "powershell" | "shell" => {
let cmd = str_of(args, "command").or_else(|| str_of(args, "description")).unwrap_or("Run command");
("execute", cmd.to_owned())
}
"view" | "read_file" => {
let label = str_of(args, "path")
.and_then(|p| Path::new(p).file_name().and_then(|n| n.to_str()))
.unwrap_or("Read file");
("read", format!("Read {label}"))
}
"grep" | "glob" | "semantic_search" => {
let pat = str_of(args, "pattern").or_else(|| str_of(args, "query")).unwrap_or(name);
("search", format!("Search {pat}"))
}
"edit" => {
let path = str_of(args, "path").unwrap_or_default();
let old = str_of(args, "old_str").unwrap_or_default();
let new = str_of(args, "new_str").unwrap_or_default();
if !path.is_empty() {
diffs.push(json!({ "type": "diff", "path": path, "oldText": old, "newText": new }));
}
let label = Path::new(path).file_name().and_then(|n| n.to_str()).unwrap_or("file");
("edit", format!("Edit {label}"))
}
"create" => {
let path = str_of(args, "path").unwrap_or_default();
let new = str_of(args, "file_text").unwrap_or_default();
if !path.is_empty() {
diffs.push(json!({ "type": "diff", "path": path, "oldText": "", "newText": new }));
}
let label = Path::new(path).file_name().and_then(|n| n.to_str()).unwrap_or("file");
("edit", format!("Create {label}"))
}
"web_fetch" => {
let url = str_of(args, "url").unwrap_or("URL");
("fetch", format!("Fetch {url}"))
}
_ => ("other", str_of(args, "description").unwrap_or(name).to_owned()),
};
ToolInfo { kind, title, locations, output: String::new(), diffs }
}
fn extract_tool_result_text(data: &Value) -> Option<String> {
if let Some(err) = data.pointer("/error/message").and_then(Value::as_str).filter(|s| !s.is_empty()) {
return Some(err.to_owned());
}
let result = data.get("result")?;
if let Some(s) = result.as_str() {
return (!s.is_empty()).then(|| s.to_owned());
}
str_of(result, "content")
.or_else(|| str_of(result, "detailedContent"))
.or_else(|| str_of(result, "textResultForLlm"))
.filter(|s| !s.is_empty())
.map(str::to_owned)
}
fn tool_content(output: &str, diffs: &[Value]) -> Vec<Value> {
let mut out = diffs.to_vec();
if !output.is_empty() {
out.push(json!({ "type": "content", "content": { "type": "text", "text": output } }));
}
out
}
fn quota_limits(snapshots: Option<&Value>) -> Option<Value> {
let map = snapshots?.as_object()?;
let mut limits = Vec::new();
for (window, snap) in map {
let used_pct = snap
.get("percentageUsed")
.and_then(Value::as_f64)
.or_else(|| snap.get("remainingPercentage").and_then(Value::as_f64).map(|rem| 100.0 - rem));
let Some(used_pct) = used_pct.filter(|p| p.is_finite()) else { continue };
let resets_ms = snap.get("resetsAt").and_then(Value::as_f64);
let mut entry = json!({
"window": window,
"usedPercent": used_pct.clamp(0.0, 100.0),
});
if let Some(ms) = resets_ms {
entry["resetsMs"] = json!(ms);
}
limits.push(entry);
}
(!limits.is_empty()).then(|| json!({ "sessionUpdate": LIMITS_UPDATE, "limits": limits }))
}
/// Builds an ACP `session/request_permission` payload from Copilot's `permission.requested` data.
pub(super) fn permission_request(session_id: &str, perm: &Value) -> Value {
let kind = str_of(perm, "kind").unwrap_or("other");
let tool_call_id = str_of(perm, "toolCallId").unwrap_or("permission");
let (acp_kind, title, raw_input) = match kind {
"shell" => {
let cmd = str_of(perm, "fullCommandText").or_else(|| str_of(perm, "command")).unwrap_or_default();
let title = str_of(perm, "intention")
.filter(|s| !s.is_empty())
.map(str::to_owned)
.unwrap_or_else(|| if cmd.is_empty() { "Run shell command".into() } else { format!("Run {cmd}") });
("execute", title, json!({ "command": cmd }))
}
"write" => {
let path = str_of(perm, "fileName").or_else(|| str_of(perm, "path")).unwrap_or("file");
("edit", format!("Edit {path}"), json!({ "path": path }))
}
"read" => {
let path = str_of(perm, "path").unwrap_or("file");
("read", format!("Read {path}"), json!({ "path": path }))
}
"url" => {
let url = str_of(perm, "url").unwrap_or("URL");
("fetch", format!("Allow network access to {url}"), json!({ "url": url }))
}
"mcp" => {
let server = str_of(perm, "serverName").unwrap_or("MCP");
let tool = str_of(perm, "toolName").unwrap_or("tool");
("other", format!("Run {server}: {tool}"), perm.clone())
}
_ => {
let t = str_of(perm, "intention").or_else(|| str_of(perm, "message")).unwrap_or("Allow action");
("other", t.to_owned(), perm.clone())
}
};
json!({
"sessionId": session_id,
"toolCall": {
"toolCallId": tool_call_id,
"kind": acp_kind,
"title": title,
"rawInput": raw_input,
},
"options": [
{ "optionId": "approve-once", "name": "Allow once", "kind": "allow_once" },
{ "optionId": "approved", "name": "Always allow", "kind": "allow_always" },
{ "optionId": "denied", "name": "Reject", "kind": "reject_once" },
],
})
}
/// Builds an ACP `session/request_permission` question card for Copilot's `userInput.request`.
pub(super) fn user_input_permission_request(session_id: &str, req: &Value) -> Value {
let question = str_of(req, "question").unwrap_or("Provide input");
let choices: Vec<Value> = req
.get("choices")
.and_then(Value::as_array)
.into_iter()
.flatten()
.filter_map(|c| c.as_str().map(|label| json!({ "label": label, "description": "" })))
.collect();
json!({
"sessionId": session_id,
"toolCall": {
"toolCallId": str_of(req, "toolCallId").unwrap_or("ask_user"),
"kind": "other",
"title": question,
"_meta": {
"questions": [{
"header": "Question",
"question": question,
"multiSelect": false,
"options": choices,
}]
}
},
"options": [
{ "optionId": "submit", "name": "Submit", "kind": "allow_once" },
{ "optionId": "cancel", "name": "Cancel", "kind": "reject_once" },
],
})
}
/// Converts ACP `mcpServers` array into Copilot's `mcpServers` object map.
pub(super) fn wire_mcp_servers(acp_servers: Option<&Value>) -> Option<Value> {
let list = acp_servers?.as_array()?;
let mut out = Map::new();
for item in list {
let Some(name) = str_of(item, "name").filter(|n| !n.is_empty()) else { continue };
let transport = str_of(item, "type").unwrap_or("stdio");
match transport {
"http" | "sse" => {
let Some(url) = str_of(item, "url").filter(|u| !u.is_empty()) else { continue };
let mut headers = Map::new();
for kv in item.get("headers").and_then(Value::as_array).into_iter().flatten() {
if let (Some(k), Some(v)) = (str_of(kv, "name"), str_of(kv, "value")) {
headers.insert(k.to_owned(), json!(v));
}
}
out.insert(
name.to_owned(),
json!({
"type": transport,
"url": url,
"headers": headers,
"tools": ["*"],
}),
);
}
_ => {
let Some(cmd) = str_of(item, "command").filter(|c| !c.is_empty()) else { continue };
let args: Vec<Value> = item.get("args").and_then(Value::as_array).cloned().unwrap_or_default();
let mut env = Map::new();
for kv in item.get("env").and_then(Value::as_array).into_iter().flatten() {
if let (Some(k), Some(v)) = (str_of(kv, "name"), str_of(kv, "value")) {
env.insert(k.to_owned(), json!(v));
}
}
out.insert(
name.to_owned(),
json!({
"type": "local",
"command": cmd,
"args": args,
"env": env,
"tools": ["*"],
}),
);
}
}
}
(!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();
let mut out = Vec::new();
for cmd in commands_res.and_then(|v| v.get("commands")).and_then(Value::as_array).into_iter().flatten() {
let Some(name) = str_of(cmd, "name").map(|n| n.trim_start_matches('/')).filter(|n| !n.is_empty()) else {
continue;
};
if !seen.insert(name.to_owned()) {
continue;
}
let hint = cmd.pointer("/input/hint").and_then(Value::as_str).filter(|h| !h.is_empty());
out.push(json!({
"name": name,
"description": str_of(cmd, "description").unwrap_or_default(),
"source": "command",
"input": hint.map(|h| json!({ "hint": h })),
}));
}
for skill in skills_res.and_then(|v| v.get("skills")).and_then(Value::as_array).into_iter().flatten() {
if skill.get("enabled").and_then(Value::as_bool) == Some(false)
|| skill.get("userInvocable").and_then(Value::as_bool) == Some(false)
{
continue;
}
let Some(name) = str_of(skill, "commandName")
.or_else(|| str_of(skill, "name"))
.map(|n| n.trim_start_matches('/'))
.filter(|n| !n.is_empty())
else {
continue;
};
if !seen.insert(name.to_owned()) {
continue;
}
let hint = str_of(skill, "argumentHint").filter(|h| !h.is_empty());
out.push(json!({
"name": name,
"description": str_of(skill, "description").unwrap_or_default(),
"source": "skill",
"input": hint.map(|h| json!({ "hint": h })),
}));
}
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;
while !text.is_char_boundary(cut) {
cut += 1;
}
text.replace_range(..cut, "");
}
}
fn str_of<'a>(v: &'a Value, key: &str) -> Option<&'a str> {
v.get(key).and_then(Value::as_str)
}
-1
View File
@@ -13,7 +13,6 @@
pub(crate) mod claude; pub(crate) mod claude;
pub(crate) mod codex; pub(crate) mod codex;
pub(crate) mod copilot;
use ide_jsonrpc::{Framing, Handler, Peer}; use ide_jsonrpc::{Framing, Handler, Peer};
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
+6 -264
View File
@@ -9,8 +9,6 @@ use serde_json::Value;
use std::collections::BTreeMap; use std::collections::BTreeMap;
use std::path::{Path, PathBuf}; 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 /// 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. /// (`native`), so tasks see every agent as ACP and read features from its capabilities.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
@@ -22,8 +20,6 @@ pub(crate) enum Driver {
Codex, Codex,
/// `claude` in stream-json mode. /// `claude` in stream-json mode.
Claude, Claude,
/// `copilot --headless --no-auto-update --stdio`.
Copilot,
} }
#[derive(Clone, Debug, PartialEq)] #[derive(Clone, Debug, PartialEq)]
@@ -58,21 +54,8 @@ const BUILTIN: &[(&str, &str, Driver, &[&str], &str)] = &[
&["npx", "-y", "@agentclientprotocol/[email protected]"], &["npx", "-y", "@agentclientprotocol/[email protected]"],
"Run `codex login` in a terminal.", "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."), ("gemini", "Gemini CLI", Driver::Acp, &["gemini", "--experimental-acp"], "Run `gemini` in a terminal and sign in."),
( ("copilot", "GitHub Copilot", Driver::Acp, &["copilot", "--acp"], "Run `copilot` in a terminal and sign in."),
"copilot",
"GitHub Copilot",
Driver::Copilot,
&["copilot", "--headless", "--no-auto-update", "--stdio"],
"Run `copilot` in a terminal and sign in.",
),
("cursor", "Cursor", Driver::Acp, &["cursor-agent", "acp"], "Run `cursor-agent login` in a terminal."), ("cursor", "Cursor", Driver::Acp, &["cursor-agent", "acp"], "Run `cursor-agent login` in a terminal."),
("opencode", "OpenCode", Driver::Acp, &["opencode", "acp"], "Run `opencode auth login` in a terminal."), ("opencode", "OpenCode", Driver::Acp, &["opencode", "acp"], "Run `opencode auth login` in a terminal."),
("qwen", "Qwen Code", Driver::Acp, &["qwen", "--experimental-acp"], "Run `qwen` in a terminal and sign in."), ("qwen", "Qwen Code", Driver::Acp, &["qwen", "--experimental-acp"], "Run `qwen` in a terminal and sign in."),
@@ -84,7 +67,6 @@ const BUILTIN: &[(&str, &str, Driver, &[&str], &str)] = &[
("kiro", "Kiro", Driver::Acp, &["kiro-cli", "acp"], "Run `kiro-cli login` in a terminal."), ("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."), ("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."), ("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> { fn builtins() -> Vec<ProviderSpec> {
@@ -138,34 +120,10 @@ impl ProviderSpec {
} }
/// Resolve once before connecting, so authentication guidance names that same install. /// Resolve once before connecting, so authentication guidance names that same install.
pub(crate) fn resolve_for_launch(self, cwd: &Path) -> Self { pub(crate) fn resolve_for_launch(mut self, cwd: &Path) -> Self {
let strip = prefer_stored_copilot_auth();
self.resolve_for_launch_base(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 {
if self.driver != Driver::Acp { if self.driver != Driver::Acp {
self.command = crate::native::newest_install(&self.command); 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); let program = ide_jsonrpc::resolve_spawn_program(&self.command, &self.env);
self.command = self.command =
if program.components().count() > 1 && !program.is_absolute() { cwd.join(program) } else { program } if program.components().count() > 1 && !program.is_absolute() { cwd.join(program) } else { program }
@@ -175,113 +133,6 @@ impl ProviderSpec {
} }
} }
const AMBIENT_COPILOT_AUTH_VARS: [&str; 3] = ["COPILOT_GITHUB_TOKEN", "GH_TOKEN", "GITHUB_TOKEN"];
static PREFER_STORED_COPILOT_AUTH: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
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)
}
pub(crate) fn mark_prefer_stored_copilot_auth() {
PREFER_STORED_COPILOT_AUTH.store(true, std::sync::atomic::Ordering::Release);
}
pub(crate) fn has_unconfigured_copilot_ambient_token(spec_env: &[(String, String)]) -> bool {
AMBIENT_COPILOT_AUTH_VARS.iter().any(|&key| {
!spec_env.iter().any(|(k, v)| k == key && !v.is_empty())
&& ambient_copilot_env_value(key).is_some_and(|v| !v.is_empty())
})
}
fn ambient_copilot_env_value(key: &str) -> Option<String> {
ide_core::process::shell_env()
.find(|(k, _)| *k == key)
.map(|(_, v)| v.to_string_lossy().into_owned())
.or_else(|| ide_core::process::host_var_os(key).map(|v| v.to_string_lossy().into_owned()))
}
/// Builds child environment overrides for `copilot`:
/// - Always clears ambient classic PATs (`ghp_…`), which Copilot CLI unconditionally rejects
/// (`"Classic PATs are not supported"`) instead of falling back to Keychain / `gh` login.
/// - When `strip_ambient_tokens` is true, clears unconfigured ambient `GITHUB_TOKEN` / `GH_TOKEN` /
/// `COPILOT_GITHUB_TOKEN` so Copilot uses its stored login (`~/.copilot` or `gh auth` keyring),
/// while preserving any token explicitly configured in OpenIDEA's agent `spec_env`.
pub(crate) fn sanitized_copilot_env(
spec_env: &[(String, String)],
strip_ambient_tokens: bool,
) -> Vec<(String, String)> {
sanitize_copilot_env_with(spec_env, strip_ambient_tokens, ambient_copilot_env_value)
}
pub(crate) fn sanitize_copilot_env_with(
spec_env: &[(String, String)],
strip_ambient_tokens: bool,
lookup: impl Fn(&str) -> Option<String>,
) -> Vec<(String, String)> {
let mut out = Vec::with_capacity(spec_env.len() + AMBIENT_COPILOT_AUTH_VARS.len());
for key in AMBIENT_COPILOT_AUTH_VARS {
let explicit = spec_env.iter().any(|(k, v)| k == key && !v.is_empty());
if explicit {
continue;
}
if let Some(val) = lookup(key).filter(|v| !v.is_empty())
&& (strip_ambient_tokens || val.trim().starts_with("ghp_"))
{
out.push((key.to_owned(), String::new()));
}
}
out.extend(spec_env.iter().cloned());
out
}
fn render_login_hint(spec: &ProviderSpec, program: &Path, on_path: Option<&Path>, windows: bool) -> String { fn render_login_hint(spec: &ProviderSpec, program: &Path, on_path: Option<&Path>, windows: bool) -> String {
let Some(builtin) = builtin_spec(&spec.id) else { return spec.login_hint.clone() }; let Some(builtin) = builtin_spec(&spec.id) else { return spec.login_hint.clone() };
let prefix = format!("Run `{}", builtin.command); let prefix = format!("Run `{}", builtin.command);
@@ -320,13 +171,10 @@ fn render_login_command<'a>(program: &Path, args: impl IntoIterator<Item = &'a s
} }
/// Whether `id` names a built-in agent that needs no registry install (native drivers /// Whether `id` names a built-in agent that needs no registry install (native drivers
/// other than `copilot`, and `npx -y` adapters). CLI built-ins (`copilot`, `gemini`, …) /// and `npx -y` adapters). CLI built-ins (`copilot`, `gemini`, …) can be installed and
/// can be installed and updated from the ACP Registry into `<config>/agents/<id>.toml`. /// updated from the ACP Registry into `<config>/agents/<id>.toml`.
pub(crate) fn is_builtin(id: &str) -> bool { pub(crate) fn is_builtin(id: &str) -> bool {
id != "copilot" BUILTIN.iter().any(|&(bid, _, driver, cmd, _)| bid == id && (driver != Driver::Acp || cmd.first() == Some(&"npx")))
&& BUILTIN
.iter()
.any(|&(bid, _, driver, cmd, _)| bid == id && (driver != Driver::Acp || cmd.first() == Some(&"npx")))
} }
/// Display name of a built-in agent, when `id` is one. /// Display name of a built-in agent, when `id` is one.
@@ -373,7 +221,6 @@ pub(crate) fn describe(spec: &ProviderSpec) -> AgentProvider {
command_editable: reason.is_none(), command_editable: reason.is_none(),
command_read_only_reason: reason, command_read_only_reason: reason,
installed: installed(&spec.command), 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(), env: spec.env.iter().cloned().collect(),
config: vec![], config: vec![],
thought_levels: BTreeMap::new(), thought_levels: BTreeMap::new(),
@@ -402,31 +249,6 @@ pub(crate) fn set_builtin_env(
id: &str, id: &str,
env: BTreeMap<String, String>, env: BTreeMap<String, String>,
) -> IdeResult<()> { ) -> 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) update_builtin(custom_dir, secrets, id, |agent, _| agent.env = env)
} }
@@ -592,7 +414,7 @@ fn validated_custom_id(id: &str) -> IdeResult<String> {
} }
/// Turns an `acp.json` server name into a file-stem id (`"My Agent!"` → `"my-agent"`). /// 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()); let mut id = String::with_capacity(name.len());
for c in name.chars() { for c in name.chars() {
if c.is_ascii_alphanumeric() { if c.is_ascii_alphanumeric() {
@@ -725,10 +547,6 @@ pub(crate) fn load(custom_dir: Option<&Path>, secrets: Option<&dyn EnvSecrets>)
files.sort(); files.sort();
for path in files { for path in files {
let Some(id) = path.file_stem().and_then(|s| s.to_str()).map(str::to_owned) else { continue }; let Some(id) = path.file_stem().and_then(|s| s.to_str()).map(str::to_owned) else { continue };
let explicit_driver = std::fs::read_to_string(&path)
.ok()
.and_then(|t| toml::from_str::<toml::Table>(&t).ok())
.is_some_and(|t| t.contains_key("driver"));
let agent = match CustomAgent::read_with(&path, &id, secrets) { let agent = match CustomAgent::read_with(&path, &id, secrets) {
Ok(a) => a, Ok(a) => a,
Err(e) => { Err(e) => {
@@ -754,14 +572,6 @@ pub(crate) fn load(custom_dir: Option<&Path>, secrets: Option<&dyn EnvSecrets>)
match specs.iter_mut().find(|s| s.id == spec.id) { match specs.iter_mut().find(|s| s.id == spec.id) {
Some(existing) => { Some(existing) => {
spec.login_hint = existing.login_hint.clone(); spec.login_hint = existing.login_hint.clone();
if !explicit_driver && existing.driver == Driver::Copilot && spec.driver == Driver::Acp {
// Registry installs (`github-copilot-cli`) record `args = ["--acp"]` with no
// `driver`; upgrade them in place to the native headless driver (which
// automatically falls back to `--acp`) while keeping the installed executable
// path and registry version tracking. Explicit `driver = "acp"` stays ACP.
spec.driver = Driver::Copilot;
spec.args = crate::native::copilot::headless_args(&spec.args);
}
if spec.source == AgentSource::Custom { if spec.source == AgentSource::Custom {
spec.source = AgentSource::Builtin; spec.source = AgentSource::Builtin;
} }
@@ -805,15 +615,6 @@ mod tests {
use super::*; use super::*;
use serde_json::json; 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] #[test]
fn qoder_global_and_cn_editions_are_both_built_in() { 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()); let info = |id: &str| describe(&load(None, None).into_iter().find(|s| s.id == id).unwrap());
@@ -1043,46 +844,6 @@ mod tests {
set_builtin_env(dir.path(), None, "not-a-builtin", env).unwrap_err(); 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] #[test]
fn acp_adapters_of_native_agents_are_unlisted_until_customized() { fn acp_adapters_of_native_agents_are_unlisted_until_customized() {
let dir = tempfile::tempdir().unwrap(); let dir = tempfile::tempdir().unwrap();
@@ -1340,23 +1101,4 @@ mod tests {
import_acp(dir.path(), None, "not json").unwrap_err(); import_acp(dir.path(), None, "not json").unwrap_err();
assert!(import_acp(dir.path(), None, "{}").unwrap().is_empty()); assert!(import_acp(dir.path(), None, "{}").unwrap().is_empty());
} }
#[test]
fn sanitizes_classic_pats_and_ambient_tokens_while_preserving_explicit_agent_env() {
let lookup = |k: &str| match k {
"GITHUB_TOKEN" => Some("ghp_classic_pat_123".into()),
"GH_TOKEN" => Some("gho_oauth_token_456".into()),
_ => None,
};
assert_eq!(sanitize_copilot_env_with(&[], false, lookup), vec![("GITHUB_TOKEN".into(), String::new())]);
assert_eq!(
sanitize_copilot_env_with(&[], true, lookup),
vec![("GH_TOKEN".into(), String::new()), ("GITHUB_TOKEN".into(), String::new())]
);
let explicit = vec![("GH_TOKEN".into(), "github_pat_custom".into())];
assert_eq!(
sanitize_copilot_env_with(&explicit, true, lookup),
vec![("GITHUB_TOKEN".into(), String::new()), ("GH_TOKEN".into(), "github_pat_custom".into())]
);
}
} }
+15 -280
View File
@@ -24,9 +24,7 @@ use std::process::Command;
use std::time::Duration; use std::time::Duration;
pub const REGISTRY_URL: &str = "https://cdn.agentclientprotocol.com/registry/v1/latest/registry.json"; 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_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 /// [`maintain`] refreshes a saved index older than this, so updates show without opening
/// the registry. /// the registry.
const REFRESH_AFTER: Duration = Duration::from_secs(24 * 60 * 60); const REFRESH_AFTER: Duration = Duration::from_secs(24 * 60 * 60);
@@ -144,9 +142,6 @@ struct Binary {
env: BTreeMap<String, String>, env: BTreeMap<String, String>,
#[serde(default)] #[serde(default)]
sha256: Option<String>, 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)] #[derive(Clone, Debug, Deserialize)]
@@ -177,48 +172,11 @@ fn parse(text: &str) -> IdeResult<Vec<Entry>> {
if let Some(name) = provider::builtin_name(&e.id) { if let Some(name) = provider::builtin_name(&e.id) {
e.name = name.to_owned(); e.name = name.to_owned();
} }
if e.id == "copilot" {
add_copilot_release_binaries(&mut e, COPILOT_RELEASE_BASE);
}
e e
}) })
.collect()) .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 { fn safe_segment(s: &str) -> bool {
!s.is_empty() !s.is_empty()
&& !s.starts_with('.') && !s.starts_with('.')
@@ -358,7 +316,7 @@ fn visible(
None None
}; };
let choice = choose(e, platform, on_path); 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()); let distribution = choice.map(|c| c.kind());
if distribution.is_none() && installed.is_none() { if distribution.is_none() && installed.is_none() {
return None; return None;
@@ -465,20 +423,6 @@ fn install_entry(
on_path: &dyn Fn(&str) -> bool, on_path: &dyn Fn(&str) -> bool,
cancel: &CancellationToken, cancel: &CancellationToken,
emit: Emit, 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<()> { ) -> IdeResult<()> {
if is_builtin(&entry.id) { if is_builtin(&entry.id) {
return Err(IdeError::invalid(format!("{} is built in", entry.name))); return Err(IdeError::invalid(format!("{} is built in", entry.name)));
@@ -499,32 +443,9 @@ fn install_entry_with(
} }
fs::create_dir_all(&dir)?; fs::create_dir_all(&dir)?;
let installed = match &choice { let installed = match &choice {
Choice::Binary(b) => match install_binary(b, &dir, cancel, emit) { Choice::Binary(b) => install_binary(b, &dir, cancel, emit).map(|exe| (exe, b.args.clone(), b.env.clone())),
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::Npx(p) => { 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) => { Choice::Uvx(p) => {
install_uv(p, entry, &dir, platform, cancel, emit).map(|exe| (exe, p.args.clone(), p.env.clone())) 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); 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 { let agent = CustomAgent {
name: Some(entry.name.clone()), name: Some(entry.name.clone()),
driver: Driver::Acp, driver: Driver::Acp,
@@ -595,23 +508,13 @@ fn install_binary(b: &Binary, dir: &Path, cancel: &CancellationToken, emit: Emit
fs::create_dir_all(&downloads)?; fs::create_dir_all(&downloads)?;
let file = downloads.join(name); let file = downloads.join(name);
emit(InstallEvent::Line { text: format!("Downloading {}", b.archive) }); emit(InstallEvent::Line { text: format!("Downloading {}", b.archive) });
let http = http()?; http()?.download(&b.archive, &file, None, cancel, emit)?;
http.download(&b.archive, &file, None, cancel, emit)?; match &b.sha256 {
match (&b.sha256, &b.sha256_url) { Some(expected) => {
(Some(expected), _) => {
verify_sha256(&file, expected)?; verify_sha256(&file, expected)?;
emit(InstallEvent::Line { text: "SHA-256 checksum verified".into() }); emit(InstallEvent::Line { text: "SHA-256 checksum verified".into() });
} }
(None, Some(checksum_url)) => { None => emit(InstallEvent::Line { text: "The registry gives no checksum for this download".into() }),
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() }),
} }
if cancel.is_cancelled() { if cancel.is_cancelled() {
return Err(IdeError::cancelled()); return Err(IdeError::cancelled());
@@ -664,20 +567,6 @@ fn install_npm(
platform: Platform, platform: Platform,
cancel: &CancellationToken, cancel: &CancellationToken,
emit: Emit, 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> { ) -> IdeResult<PathBuf> {
let (name, version) = split_npm_spec(&p.package); let (name, version) = split_npm_spec(&p.package);
let spec = match version { let spec = match version {
@@ -685,27 +574,10 @@ fn install_npm_with(
_ => format!("{name}@{}", entry.version), _ => format!("{name}@{}", entry.version),
}; };
check_spec(&spec)?; check_spec(&spec)?;
let specs = [spec.clone()]; let npm = which::which("npm").map_err(|_| IdeError::unavailable(format!("npm is required to install {name}")))?;
ide_tools::run_npm_with_public_fallback( let mut cmd = Command::new(npm);
|extra| { cmd.arg("install").arg("--prefix").arg(dir).args(["--no-audit", "--no-fund"]).arg(&spec).current_dir(dir);
if !extra.is_empty() { ide_tools::run_streamed(cmd, cancel, emit)?;
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 modules = dir.join("node_modules"); let modules = dir.join("node_modules");
let manifest: serde_json::Value = fs::read_to_string(modules.join(name).join("package.json")) let manifest: serde_json::Value = fs::read_to_string(modules.join(name).join("package.json"))
.ok() .ok()
@@ -1000,58 +872,6 @@ mod tests {
assert!(check_url("ftp://x/a").is_err()); 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] #[test]
fn checksums_are_verified() { fn checksums_are_verified() {
let dir = tempfile::tempdir().unwrap(); let dir = tempfile::tempdir().unwrap();
@@ -1149,18 +969,11 @@ esac
assert_eq!(entries.len(), 1); assert_eq!(entries.len(), 1);
assert_eq!((entries[0].id.as_str(), entries[0].name.as_str()), ("copilot", "GitHub Copilot")); 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, &|c| c == "npm" || c == "node");
let shown = visible(&p, &entries, MAC_ARM, &|_| false);
assert_eq!(shown.len(), 1); assert_eq!(shown.len(), 1);
assert_eq!( assert_eq!(
( (shown[0].id.as_str(), shown[0].name.as_str(), shown[0].installed.as_deref()),
shown[0].id.as_str(), ("copilot", "GitHub Copilot", None)
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)
); );
CustomAgent { CustomAgent {
@@ -1174,7 +987,7 @@ esac
.write(&p.agent_file("copilot")) .write(&p.agent_file("copilot"))
.unwrap(); .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)); assert_eq!((shown[0].installed.as_deref(), shown[0].update), (Some("1.0.104"), true));
write_atomic(&p.cache_file, index.as_bytes()).unwrap(); 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(); let fallback = provider::load(Some(&p.agents_dir), None).into_iter().find(|s| s.id == "copilot").unwrap();
assert_eq!(fallback.source, AgentSource::Builtin); 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());
}
} }
-2
View File
@@ -25,7 +25,6 @@ fn paths(dir: &Path) -> AgentPaths {
custom_agents_dir: None, custom_agents_dir: None,
home_dir: None, home_dir: None,
env_secrets: None, env_secrets: None,
catalogs: Arc::default(),
} }
} }
@@ -64,7 +63,6 @@ async fn create(mgr: &AgentManager, provider: &str, prompt: &str) -> String {
config: config(provider), config: config(provider),
isolation: Isolation::Local, isolation: Isolation::Local,
base: None, base: None,
..Default::default()
}; };
mgr.create(req).await.unwrap().id mgr.create(req).await.unwrap().id
} }
-160
View File
@@ -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
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+6 -119
View File
@@ -1,6 +1,6 @@
//! Folds ACP `session/update` notifications into a task's entries. //! 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 ide_core::IpcPath;
use serde_json::Value; use serde_json::Value;
use std::collections::HashMap; use std::collections::HashMap;
@@ -54,23 +54,6 @@ impl Timeline {
let mut out = Applied::default(); let mut out = Applied::default();
let kind = update.get("sessionUpdate").and_then(Value::as_str).unwrap_or_default(); let kind = update.get("sessionUpdate").and_then(Value::as_str).unwrap_or_default();
match kind { 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" => { "agent_message_chunk" | "agent_thought_chunk" => {
let Some(text) = content_text(update.get("content")) else { return out }; let Some(text) = content_text(update.get("content")) else { return out };
out.changed.push(self.append_text(kind == "agent_thought_chunk", &text)); out.changed.push(self.append_text(kind == "agent_thought_chunk", &text));
@@ -84,10 +67,7 @@ impl Timeline {
status: tool_status(update.get("status")).unwrap_or(AgentToolStatus::Pending), status: tool_status(update.get("status")).unwrap_or(AgentToolStatus::Pending),
locations: locations(update.get("locations")), locations: locations(update.get("locations")),
output: None, output: None,
images: Vec::new(),
diffs: Vec::new(), diffs: Vec::new(),
started_ms: Some(crate::now_ms()),
ended_ms: None,
}; };
let index = match self.tools.get(&id) { let index = match self.tools.get(&id) {
Some(&i) => { Some(&i) => {
@@ -137,22 +117,17 @@ impl Timeline {
fn append_text(&mut self, thought: bool, text: &str) -> usize { fn append_text(&mut self, thought: bool, text: &str) -> usize {
match self.entries.last_mut() { match self.entries.last_mut() {
Some(AgentEntry::Agent { text: t }) if !thought => t.push_str(text), 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(); let text = text.to_owned();
return self.push(if thought { return self.push(if thought { AgentEntry::Thought { text } } else { AgentEntry::Agent { text } });
AgentEntry::Thought { text, started_ms: Some(crate::now_ms()) }
} else {
AgentEntry::Agent { text }
});
} }
} }
self.entries.len() - 1 self.entries.len() - 1
} }
fn merge_tool(&mut self, index: usize, update: &Value) { fn merge_tool(&mut self, index: usize, update: &Value) {
let AgentEntry::Tool { title, kind, status, locations: locs, output, images, diffs, ended_ms, .. } = let AgentEntry::Tool { title, kind, status, locations: locs, output, diffs, .. } = &mut self.entries[index]
&mut self.entries[index]
else { else {
return; return;
}; };
@@ -164,9 +139,6 @@ impl Timeline {
} }
if let Some(s) = tool_status(update.get("status")) { if let Some(s) = tool_status(update.get("status")) {
*status = s; *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) { if update.get("locations").is_some_and(Value::is_array) {
*locs = locations(update.get("locations")); *locs = locations(update.get("locations"));
@@ -174,20 +146,10 @@ impl Timeline {
let Some(content) = update.get("content").and_then(Value::as_array) else { return }; let Some(content) = update.get("content").and_then(Value::as_array) else { return };
let mut text = String::new(); let mut text = String::new();
let mut new_diffs = Vec::new(); let mut new_diffs = Vec::new();
let mut new_images = Vec::new();
for item in content { for item in content {
match item.get("type").and_then(Value::as_str) { match item.get("type").and_then(Value::as_str) {
Some("content") => { Some("content") => {
let content = item.get("content"); if let Some(t) = content_text(item.get("content")) {
if let Some(image) = content.filter(|c| c.get("type").and_then(Value::as_str) == Some("image"))
&& let (Some(data), Some(mime)) =
(image.get("data").and_then(Value::as_str), image.get("mimeType").and_then(Value::as_str))
&& !data.is_empty()
&& mime.starts_with("image/")
{
new_images.push(AgentImage { mime_type: mime.into(), data: data.into(), name: None });
}
if let Some(t) = content_text(content) {
if !text.is_empty() { if !text.is_empty() {
text.push('\n'); text.push('\n');
} }
@@ -204,19 +166,11 @@ impl Timeline {
} }
} }
if !text.is_empty() { 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)); *output = Some(tail(text));
} }
if !new_diffs.is_empty() { if !new_diffs.is_empty() {
*diffs = new_diffs; *diffs = new_diffs;
} }
if !new_images.is_empty() {
*images = new_images;
}
} }
/// Adds or updates the card of subagent `id` from its `subagent_update`; returns the /// Adds or updates the card of subagent `id` from its `subagent_update`; returns the
@@ -434,50 +388,6 @@ mod tests {
use super::*; use super::*;
use serde_json::json; 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] #[test]
fn chunks_merge_into_one_message_until_another_entry_comes() { fn chunks_merge_into_one_message_until_another_entry_comes() {
let mut t = Timeline::default(); let mut t = Timeline::default();
@@ -486,14 +396,11 @@ mod tests {
assert_eq!(t.apply(&chunk("lo")).changed, vec![0]); assert_eq!(t.apply(&chunk("lo")).changed, vec![0]);
t.apply(&json!({"sessionUpdate": "agent_thought_chunk", "content": {"type": "text", "text": "hmm"}})); t.apply(&json!({"sessionUpdate": "agent_thought_chunk", "content": {"type": "text", "text": "hmm"}}));
t.apply(&chunk("again")); 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!( assert_eq!(
t.entries, t.entries,
vec![ vec![
AgentEntry::Agent { text: "Hello".into() }, AgentEntry::Agent { text: "Hello".into() },
AgentEntry::Thought { text: "hmm".into(), started_ms: None }, AgentEntry::Thought { text: "hmm".into() },
AgentEntry::Agent { text: "again".into() }, AgentEntry::Agent { text: "again".into() },
] ]
); );
@@ -534,7 +441,6 @@ mod tests {
command: None, command: None,
options: vec![], options: vec![],
questions: vec![], questions: vec![],
form: None,
chosen: None, chosen: None,
}); });
assert_eq!(t.end_turn(None), vec![2, 3]); assert_eq!(t.end_turn(None), vec![2, 3]);
@@ -585,25 +491,6 @@ mod tests {
assert!(matches!(t.entries[2], AgentEntry::User { done_ms: None, .. })); 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] #[test]
fn long_output_keeps_its_tail() { fn long_output_keeps_its_tail() {
let s = tail("é".repeat(MAX_OUTPUT)); let s = tail("é".repeat(MAX_OUTPUT));
+10 -592
View File
@@ -3,8 +3,7 @@
use crate::model::{AgentChange, AgentChanges, AgentCommit}; use crate::model::{AgentChange, AgentChanges, AgentCommit};
use ide_core::{IdeError, IdeResult, IpcPath}; use ide_core::{IdeError, IdeResult, IpcPath};
use ide_vcs::{ChangeKind, LogQuery, Repo}; use ide_vcs::{ChangeKind, LogQuery, Repo};
use serde::{Deserialize, Serialize}; use std::collections::BTreeMap;
use std::collections::{BTreeMap, BTreeSet};
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::time::{Duration, UNIX_EPOCH}; use std::time::{Duration, UNIX_EPOCH};
@@ -25,116 +24,6 @@ fn discover(path: &Path) -> IdeResult<Option<Repo>> {
Ok(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> { fn repo_at(path: &Path) -> IdeResult<Repo> {
discover(path)?.ok_or_else(|| IdeError::unavailable(format!("{} is not in a git repository", path.display()))) 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. /// `HEAD`'s commit in `cwd`, `None` outside a repository or before its first commit.
pub(crate) fn head_commit(cwd: &Path) -> IdeResult<Option<String>> { pub(crate) fn head_commit(cwd: &Path) -> IdeResult<Option<String>> {
if spans_repos(cwd) {
return Ok(Some("HEAD".to_owned()));
}
match discover(cwd)? { match discover(cwd)? {
Some(repo) => Ok(repo.head()?.1), Some(repo) => Ok(repo.head()?.1),
None => Ok(None), None => Ok(None),
@@ -240,7 +126,6 @@ pub(crate) fn changes(cwd: &Path, base: &str) -> IdeResult<Vec<AgentChange>> {
added, added,
removed, removed,
old_path: f.old_path, old_path: f.old_path,
repo: None,
} }
}) })
.collect(); .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 /// Files renamed since `rev`, by their new repository-relative path: the old path, as a deletion
/// to roll back along with the rename. /// to roll back along with the rename.
pub(crate) fn rename_sources(cwd: &Path, rev: &str) -> IdeResult<BTreeMap<String, AgentChange>> { 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 Some(repo) = discover(cwd)? else { return Ok(BTreeMap::new()) };
let root = repo.root().to_path_buf(); let root = repo.root().to_path_buf();
Ok(repo Ok(repo
@@ -274,7 +156,6 @@ pub(crate) fn rename_sources(cwd: &Path, rev: &str) -> IdeResult<BTreeMap<String
added: 0, added: 0,
removed: 0, removed: 0,
old_path: None, old_path: None,
repo: None,
}; };
Some((f.path, source)) 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 { 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); 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 /// 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, added,
removed, removed,
old_path: f.old_path, old_path: f.old_path,
repo: None,
} }
}) })
.collect(); .collect();
@@ -382,30 +262,10 @@ impl TaskBase {
} }
/// The files the task changed, less those changed before it started and untouched since. /// The files the task changed, less those changed before it started and untouched since.
pub(crate) fn changes( pub(crate) fn changes(&self, before: &BTreeMap<String, Stamp>) -> IdeResult<Vec<AgentChange>> {
&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>> {
let (cwd, start) = match self { let (cwd, start) = match self {
Self::Worktree { cwd, base } => return Ok(without_untouched(changes(cwd, base)?, before)), Self::Worktree { cwd, base } => return Ok(without_untouched(changes(cwd, base)?, before)),
Self::Local { cwd, start } => { Self::Local { cwd, start } => (cwd, start.as_deref()),
if let Some((base, repos)) = nested_repos(cwd)? {
return Ok(without_untouched(nested_changes(&base, &repos, touched)?, before));
}
(cwd, start.as_deref())
}
}; };
let Some(repo) = discover(cwd)? else { return Ok(Vec::new()) }; 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 // 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. /// reads cannot put a file in both lists.
pub(crate) fn grouped_changes(&self, before: &BTreeMap<String, Stamp>) -> IdeResult<AgentChanges> { pub(crate) fn grouped_changes(&self, before: &BTreeMap<String, Stamp>) -> IdeResult<AgentChanges> {
let cwd = self.cwd(); 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 Some(repo) = discover(cwd)? else { return Ok(AgentChanges::default()) };
let head = repo.head()?.1; let head = repo.head()?.1;
let uncommitted = match &head { let uncommitted = match &head {
@@ -495,8 +352,6 @@ impl TaskBase {
pub(crate) fn rev(&self) -> IdeResult<Option<String>> { pub(crate) fn rev(&self) -> IdeResult<Option<String>> {
let (cwd, start) = match self { let (cwd, start) = match self {
Self::Worktree { base, .. } => return Ok(Some(base.clone())), 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()), Self::Local { cwd, start } => (cwd, start.as_deref()),
}; };
let Some(repo) = discover(cwd)? else { return Ok(None) }; let Some(repo) = discover(cwd)? else { return Ok(None) };
@@ -689,41 +544,10 @@ pub(crate) fn stamp(path: &Path) -> Stamp {
pub(crate) fn snapshot(cwd: &Path) -> IdeResult<BTreeMap<String, 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 // 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. // and held up starting a task in a checkout with many of them.
if let Some((base, repos)) = nested_repos(cwd)? {
let roots: Vec<PathBuf> = repos.iter().map(|r| r.root().to_path_buf()).collect();
let mut out = BTreeMap::new();
for repo in &repos {
for s in repo.status()? {
if let Some(rel) = nested_rel(&base, repo, &roots, &s.path) {
out.insert(rel, stamp(&s.path));
}
}
}
return Ok(out);
}
let Some(repo) = Repo::discover(cwd)? else { return Ok(BTreeMap::new()) }; let Some(repo) = Repo::discover(cwd)? else { return Ok(BTreeMap::new()) };
Ok(repo.status()?.into_iter().map(|s| (s.rel_path, stamp(&s.path))).collect()) 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,
/// or back to as committed.
pub(crate) fn changed_between(start: &BTreeMap<String, Stamp>, end: &BTreeMap<String, Stamp>) -> Vec<String> {
let mut changed: Vec<String> =
end.iter().filter(|(path, stamp)| start.get(*path) != Some(*stamp)).map(|(path, _)| path.clone()).collect();
changed.extend(start.keys().filter(|path| !end.contains_key(*path)).cloned());
changed
}
/// The changes among `changes` that the task made, when it records the files its turns
/// changed (`None`: every change counts).
pub(crate) fn made_by_task(changes: Vec<AgentChange>, touched: Option<&BTreeSet<String>>) -> Vec<AgentChange> {
let Some(touched) = touched else { return changes };
changes
.into_iter()
.filter(|c| touched.contains(&c.rel_path) || c.old_path.as_ref().is_some_and(|old| touched.contains(old)))
.collect()
}
/// Drops the changes that were there before the task and haven't been touched since. /// Drops the changes that were there before the task and haven't been touched since.
pub(crate) fn without_untouched(changes: Vec<AgentChange>, before: &BTreeMap<String, Stamp>) -> Vec<AgentChange> { pub(crate) fn without_untouched(changes: Vec<AgentChange>, before: &BTreeMap<String, Stamp>) -> Vec<AgentChange> {
changes.into_iter().filter(|c| before.get(&c.rel_path).is_none_or(|s| *s != stamp(&c.path))).collect() changes.into_iter().filter(|c| before.get(&c.rel_path).is_none_or(|s| *s != stamp(&c.path))).collect()
@@ -743,16 +567,10 @@ fn saved_name(rel: &str) -> String {
/// into `dir`, so rolling back the task's changes to them restores the user's own edits. /// into `dir`, so rolling back the task's changes to them restores the user's own edits.
/// Whether anything was saved. /// Whether anything was saved.
pub(crate) fn save_before(cwd: &Path, before: &BTreeMap<String, Stamp>, dir: &Path) -> IdeResult<bool> { pub(crate) fn save_before(cwd: &Path, before: &BTreeMap<String, Stamp>, dir: &Path) -> IdeResult<bool> {
let root = match nested_repos(cwd)? { let Some(repo) = Repo::discover(cwd)? else { return Ok(false) };
Some((base, _)) => base,
None => match Repo::discover(cwd)? {
Some(repo) => repo.root().to_path_buf(),
None => return Ok(false),
},
};
let mut saved = false; let mut saved = false;
for (rel, stamp) in before { 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) { if stamp.is_none() || !std::fs::metadata(&path).is_ok_and(|m| m.is_file() && m.len() <= SAVED_MAX) {
continue; continue;
} }
@@ -773,6 +591,7 @@ pub(crate) fn restore(
before: &BTreeMap<String, Stamp>, before: &BTreeMap<String, Stamp>,
saved: Option<&Path>, saved: Option<&Path>,
) -> IdeResult<()> { ) -> IdeResult<()> {
let path = &change.path.0;
let content = match before.get(&change.rel_path) { let content = match before.get(&change.rel_path) {
Some(None) => None, Some(None) => None,
Some(Some(_)) => { Some(Some(_)) => {
@@ -787,18 +606,12 @@ pub(crate) fn restore(
} }
None => match rev { None => match rev {
Some(rev) => { Some(rev) => {
let at = change.repo.as_ref().map_or(cwd, |r| r.0.as_path()); let repo = Repo::discover(cwd)?.ok_or_else(|| IdeError::invalid("not in a git repository"))?;
let repo = Repo::discover(at)?.ok_or_else(|| IdeError::invalid("not in a git repository"))?; repo.file_bytes_at(path, Some(rev))?
repo.file_bytes_at(&change.path.0, Some(rev))?
} }
None => None, None => None,
}, },
}; };
put(&change.path.0, content)
}
/// Writes `content` to `path`, or removes the file when there is none.
fn put(path: &Path, content: Option<Vec<u8>>) -> IdeResult<()> {
match content { match content {
Some(bytes) => { Some(bytes) => {
if let Some(parent) = path.parent() { if let Some(parent) = path.parent() {
@@ -814,221 +627,8 @@ fn put(path: &Path, content: Option<Vec<u8>>) -> IdeResult<()> {
Ok(()) 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 the task's last turn started: what that turn's changes are compared with
/// and rolled back to. Recorded like the task's own start: `HEAD`, the files already changed,
/// and copies of those.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
#[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>>,
}
/// Records the checkout at `cwd` as a turn starts, with copies of its changed files in `dir`.
/// The copies `previous` saved of files unchanged since are kept rather than made again, so
/// starting a turn copies little more than what the turn before it changed.
pub(crate) fn start_turn(cwd: &Path, dir: &Path, previous: Option<&TurnStart>) -> IdeResult<TurnStart> {
let Some(at) = TurnRepos::of(cwd)? else { return Ok(TurnStart::default()) };
let mut heads = BTreeMap::new();
let head = if at.nested {
for repo in &at.repos {
heads.extend(repo.head()?.1.map(|h| (root_key(repo.root()), h)));
}
None
} else {
at.repos[0].head()?.1
};
// As the turn's end is read, so the two compare.
let before = snapshot(cwd)?;
let mut saved = BTreeSet::new();
match previous {
Some(previous) => {
for rel in &previous.saved {
let unchanged =
before.get(rel).is_some_and(|now| now.is_some() && previous.before.get(rel) == Some(now));
if unchanged {
saved.insert(rel.clone());
} else {
let _ = std::fs::remove_file(dir.join(saved_name(rel)));
}
}
}
None => {
let _ = std::fs::remove_dir_all(dir);
}
}
for (rel, stamp) in &before {
let path = at.base.join(rel);
if stamp.is_none()
|| saved.contains(rel)
|| !std::fs::metadata(&path).is_ok_and(|m| m.is_file() && m.len() <= SAVED_MAX)
{
continue;
}
std::fs::create_dir_all(dir)?;
// One that can't be copied is listed but can't be rolled back, as a large one.
if std::fs::copy(&path, dir.join(saved_name(rel))).is_ok() {
saved.insert(rel.clone());
}
}
Ok(TurnStart { head, heads, before, saved, changed: None })
}
/// 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(|| saved_copy(dir, rel)).flatten() {
Some(bytes) => Ok(Some(bytes)),
None => Err(IdeError::invalid(format!(
"{rel} had changes when the turn started that weren't saved; roll it back in Git instead"
))),
},
None => {
let path = at.base.join(rel);
match at.owner(&path).and_then(|repo| Some((repo, at.head_then(start, repo)?))) {
Some((repo, head)) => repo.file_bytes_at(&path, Some(head)),
None => Ok(None),
}
}
}
}
/// 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>> { pub(crate) fn file_at(cwd: &Path, path: &Path, rev: &str) -> IdeResult<Option<String>> {
// With nested repositories, the file's own one. let Some(repo) = discover(cwd)? else { return Ok(None) };
let at = if spans_repos(cwd) { path.parent().unwrap_or(cwd) } else { cwd };
let Some(repo) = discover(at)? else { return Ok(None) };
let encoding = match ide_vfs::load_text(path) { 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), 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), Err(_) => ide_vfs::detect_encoding(&repo.file_bytes_at(path, Some(rev))?.unwrap_or_default(), None),
@@ -1157,111 +757,6 @@ mod tests {
assert!(ok, "git {args:?}"); 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] #[test]
fn worktree_changes_are_listed_against_the_base() { fn worktree_changes_are_listed_against_the_base() {
let tmp = tempfile::tempdir().unwrap(); let tmp = tempfile::tempdir().unwrap();
@@ -1301,67 +796,6 @@ mod tests {
assert!(!created.path.exists()); 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<_>>();
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, None).unwrap();
assert_eq!(first.saved, set(&["a.txt", "b.txt"]));
// A copy made again would replace this mark.
std::fs::write(dir.join(saved_name("b.txt")), "kept\n").unwrap();
std::thread::sleep(std::time::Duration::from_millis(10));
std::fs::write(repo.join("a.txt"), "turn two\n").unwrap();
let second = start_turn(&repo, &dir, Some(&first)).unwrap();
assert_eq!(second.saved, set(&["a.txt", "b.txt"]));
assert_eq!(saved_copy(&dir, "a.txt").as_deref(), Some(&b"turn two\n"[..]));
assert_eq!(saved_copy(&dir, "b.txt").as_deref(), Some(&b"kept\n"[..]));
// Back as committed: nothing to keep a copy of.
git(&repo, &["checkout", "--", "a.txt"]);
let third = start_turn(&repo, &dir, Some(&second)).unwrap();
assert_eq!(third.saved, set(&["b.txt"]));
assert_eq!(saved_copy(&dir, "a.txt"), None);
// Without a record of the last turn (a task from before), every copy is made afresh.
let fresh = start_turn(&repo, &dir, None).unwrap();
assert_eq!(fresh.saved, set(&["b.txt"]));
assert_eq!(saved_copy(&dir, "b.txt").as_deref(), Some(&b"b\n"[..]));
}
#[cfg(unix)]
#[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, None).unwrap();
std::fs::write(repo.join("a.txt"), "turn 2\n").unwrap();
std::fs::write(repo.join("new.txt"), "new\n").unwrap();
let link = tmp.path().join("link");
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] #[test]
fn commits_since_the_base_are_listed_with_their_files() { fn commits_since_the_base_are_listed_with_their_files() {
let tmp = tempfile::tempdir().unwrap(); let tmp = tempfile::tempdir().unwrap();
@@ -1750,20 +1184,4 @@ mod tests {
assert_eq!(std::fs::read_to_string(repo.join("a.txt")).unwrap(), "one\nMINE\n"); assert_eq!(std::fs::read_to_string(repo.join("a.txt")).unwrap(), "one\nMINE\n");
assert_eq!(std::fs::read_to_string(repo.join("gone.txt")).unwrap(), "bye\nbye\n"); assert_eq!(std::fs::read_to_string(repo.join("gone.txt")).unwrap(), "bye\nbye\n");
} }
#[test]
fn a_turn_changed_the_files_whose_state_moved() {
let start: BTreeMap<String, Stamp> =
[("edited", Some((1, 1))), ("same", Some((2, 2))), ("reverted", Some((3, 3)))]
.into_iter()
.map(|(p, s)| (p.to_owned(), s))
.collect();
let end: BTreeMap<String, Stamp> = [("edited", Some((1, 9))), ("same", Some((2, 2))), ("new", Some((4, 4)))]
.into_iter()
.map(|(p, s)| (p.to_owned(), s))
.collect();
let mut changed = changed_between(&start, &end);
changed.sort();
assert_eq!(changed, ["edited", "new", "reverted"]);
}
} }
+2
View File
@@ -10,6 +10,8 @@ ide-core.workspace = true
ide-language.workspace = true ide-language.workspace = true
serde.workspace = true serde.workspace = true
specta.workspace = true specta.workspace = true
tree-sitter.workspace = true
rayon.workspace = true rayon.workspace = true
tracing.workspace = true
# Pinned: 0.40.2+ moves to tree-sitter 0.26, the workspace is on 0.25. # Pinned: 0.40.2+ moves to tree-sitter 0.26, the workspace is on 0.25.
ast-grep-core = "=0.40.1" ast-grep-core = "=0.40.1"
+3
View File
@@ -10,3 +10,6 @@ ide-core.workspace = true
serde.workspace = true serde.workspace = true
specta.workspace = true specta.workspace = true
which = "8" which = "8"
[dev-dependencies]
tempfile.workspace = true
+6
View File
@@ -91,6 +91,12 @@ fn executable() -> IdeResult<PathBuf> {
}) })
} }
/// The directory holding adb, for command lines that expect `adb` on `PATH`.
pub fn platform_tools_dir() -> Option<&'static Path> {
static DIR: OnceLock<Option<PathBuf>> = OnceLock::new();
DIR.get_or_init(|| adb_executable().as_deref().and_then(Path::parent).map(Path::to_path_buf)).as_deref()
}
/// Connected devices, online ones first; starting the adb daemon when needed. /// Connected devices, online ones first; starting the adb daemon when needed.
pub fn devices() -> IdeResult<Vec<AndroidDevice>> { pub fn devices() -> IdeResult<Vec<AndroidDevice>> {
let adb = executable()?; let adb = executable()?;
+134 -216
View File
@@ -1,18 +1,101 @@
//! The `adb` CLI as a child process: bounded runs, and cancellable line streams //! Child processes of the `adb` CLI: bounded runs, and cancellable line streams
//! that are handed over in batches (logcat is far too chatty for one message a line). //! 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::process::terminate_tree;
use ide_core::cli_process::{CarriageReturn, CliTool, Decoding, Poll, Stream, keep_stderr_line}; use ide_core::{CancellationToken, IdeError, IdeResult};
use ide_core::{CancellationToken, IdeResult}; use std::io::Read;
use std::process::Command; use std::process::{Child, Command, Stdio};
use std::sync::mpsc;
use std::time::{Duration, Instant}; 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; /// 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. /// 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> { pub(crate) fn run(mut cmd: Command, timeout: Duration, cancel: Option<&CancellationToken>) -> IdeResult<Output> {
ADB.run(cmd, timeout, cancel) 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>)) { 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 /// 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. /// tail for the error message. Returns whether the child exited successfully.
pub(crate) fn stream_batched<T>( pub(crate) fn stream_batched<T>(
cmd: Command, mut cmd: Command,
cancel: &CancellationToken, cancel: &CancellationToken,
idle: Duration, idle: Duration,
max: usize, max: usize,
mut parse: impl FnMut(&str) -> Option<T>, mut parse: impl FnMut(&str) -> Option<T>,
on_batch: &mut dyn FnMut(Vec<T>), on_batch: &mut dyn FnMut(Vec<T>),
) -> IdeResult<(bool, Vec<String>)> { ) -> 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 stderr_tail: Vec<String> = Vec::new();
let mut batch: Vec<T> = Vec::with_capacity(max); let mut batch: Vec<T> = Vec::with_capacity(max);
// When the first line of the waiting batch arrived. // When the first line of the waiting batch arrived.
let mut since = Instant::now(); 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()) }; let wait = if batch.is_empty() { idle } else { idle.saturating_sub(since.elapsed()) };
match lines.poll(cancel, wait)? { match rx.recv_timeout(wait) {
Poll::Line(Stream::Stdout, line) => { Ok(Event::Line(true, line)) => {
if let Some(item) = parse(&line) { if let Some(item) = parse(&line) {
if batch.is_empty() { if batch.is_empty() {
since = Instant::now(); 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() { 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 => {} Ok(Event::Closed) => open -= 1,
Poll::Timeout => flush(&mut batch, on_batch), Err(mpsc::RecvTimeoutError::Timeout) => flush(&mut batch, on_batch),
Poll::Finished => break, Err(mpsc::RecvTimeoutError::Disconnected) => break,
} }
} }
flush(&mut batch, on_batch); 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))] #[cfg(all(test, unix))]
mod tests { mod tests {
use super::*; use super::*;
use ide_core::error::ErrorKind;
use ide_core::process::process_alive;
#[test] #[test]
fn a_steady_stream_is_handed_over_while_it_runs() { fn a_steady_stream_is_handed_over_while_it_runs() {
@@ -90,199 +203,4 @@ mod tests {
assert_eq!(sizes.iter().sum::<usize>(), 20); assert_eq!(sizes.iter().sum::<usize>(), 20);
assert!(sizes.len() >= 3, "lines arriving every 20 ms waited for the end: {sizes:?}"); assert!(sizes.len() >= 3, "lines arriving every 20 ms waited for the end: {sizes:?}");
} }
const LONG: Duration = Duration::from_secs(30);
fn sh(script: &str) -> Command {
let mut cmd = Command::new("sh");
cmd.args(["-c", script]);
cmd
}
/// A script that records its pid in `name`'s file, then runs `rest`.
fn recording_pid(name: &str, rest: &str) -> (Command, std::path::PathBuf) {
let file = std::env::temp_dir().join(format!("openidea-process-{}-{name}", std::process::id()));
let _ = std::fs::remove_file(&file);
(sh(&format!("echo $$ > '{0}.tmp' && mv '{0}.tmp' '{0}'; {rest}", file.display())), file)
}
fn recorded_pid(file: &std::path::Path) -> u32 {
let pid = std::fs::read_to_string(file).unwrap().trim().parse().unwrap();
let _ = std::fs::remove_file(file);
pid
}
/// Cancels `cancel` once the script has recorded its pid.
fn cancel_when_recorded(file: &std::path::Path, cancel: &CancellationToken) {
let (file, cancel) = (file.to_owned(), cancel.clone());
std::thread::spawn(move || {
while !file.exists() {
std::thread::sleep(Duration::from_millis(5));
}
cancel.cancel();
});
}
fn assert_gone(pid: u32) {
let deadline = Instant::now() + Duration::from_secs(5);
while process_alive(pid) {
assert!(Instant::now() < deadline, "process {pid} survived");
std::thread::sleep(Duration::from_millis(20));
}
}
#[test]
fn the_exit_status_is_reported_not_raised() {
assert!(run(sh("exit 0"), LONG, None).unwrap().success);
assert!(!run(sh("exit 3"), LONG, None).unwrap().success);
}
#[test]
fn both_streams_are_captured_separately_and_in_order() {
let out = run(sh("printf 'a\\nb\\nc\\n'; printf 'x\\ny\\n' >&2"), LONG, None).unwrap();
assert_eq!(out.stdout, "a\nb\nc\n");
assert_eq!(out.stderr, "x\ny\n");
assert!(out.success);
}
#[test]
fn invalid_utf8_is_replaced_in_collected_output() {
let out = run(sh("printf 'ok\\n\\377\\n'; printf 'a\\377b' >&2"), LONG, None).unwrap();
assert_eq!(out.stdout, "ok\n\u{FFFD}\n");
assert_eq!(out.stderr, "a\u{FFFD}b");
}
#[test]
fn stdin_is_closed() {
assert_eq!(run(sh("cat; echo done"), LONG, None).unwrap().stdout, "done\n");
}
#[test]
fn a_missing_program_is_unavailable() {
let err = run(Command::new("/nonexistent/openidea-adb"), LONG, None).err().unwrap();
assert_eq!(err.kind, ErrorKind::Unavailable);
assert_eq!(err.message, "could not run adb: No such file or directory (os error 2)");
}
#[test]
fn a_run_past_its_timeout_fails_and_the_child_is_killed() {
let (cmd, file) = recording_pid("adb-timeout", "exec sleep 30");
let err = run(cmd, Duration::from_secs(1), None).err().unwrap();
assert_eq!(err.kind, ErrorKind::Unavailable);
assert_eq!(err.message, "adb did not respond in time");
assert_gone(recorded_pid(&file));
}
#[test]
fn a_cancelled_run_fails_and_the_child_is_killed() {
let (cmd, file) = recording_pid("adb-cancel", "exec sleep 30");
let cancel = CancellationToken::new();
cancel_when_recorded(&file, &cancel);
let err = run(cmd, LONG, Some(&cancel)).err().unwrap();
assert_eq!(err.kind, ErrorKind::Cancelled);
assert_eq!(err.message, "cancelled");
assert_gone(recorded_pid(&file));
}
/// Runs `script` batched by `max` lines (a long `idle`, so only `max` and the end flush),
/// parsing stdout lines unless they are `skip`.
fn batches(script: &str, max: usize) -> (bool, Vec<Vec<String>>, Vec<String>) {
let mut batches = Vec::new();
let (ok, tail) = stream_batched(
sh(script),
&CancellationToken::new(),
LONG,
max,
|line| (line != "skip").then(|| line.to_owned()),
&mut |batch| batches.push(batch),
)
.unwrap();
(ok, batches, tail)
}
#[test]
fn a_batch_is_handed_over_as_soon_as_max_lines_are_ready() {
let (ok, batches, _) = batches("printf '1\\n2\\n3\\n4\\n5\\n'", 2);
assert!(ok);
assert_eq!(batches, [vec!["1", "2"], vec!["3", "4"], vec!["5"]]);
}
#[test]
fn lines_the_parser_rejects_are_dropped() {
let (_, batches, _) = batches("printf '1\\nskip\\n2\\n'", 10);
assert_eq!(batches, [vec!["1", "2"]]);
}
#[test]
fn carriage_returns_are_dropped_not_split_on_and_line_ends_are_trimmed() {
let (_, batches, _) = batches("printf 'a\\r\\nb\\rc \\n\\n\\nd'", 10);
assert_eq!(batches, [vec!["a", "bc", "d"]]);
}
#[test]
fn a_stream_replaces_invalid_utf8() {
let (_, batches, _) = batches("printf 'a\\377b\\n'", 10);
assert_eq!(batches, [vec!["a\u{FFFD}b"]]);
}
#[test]
fn a_stream_reports_the_exit_status() {
assert!(batches("exit 0", 10).0);
assert!(!batches("exit 2", 10).0);
}
#[test]
fn stderr_is_not_parsed_and_its_last_twenty_non_blank_lines_are_kept() {
let (_, batches, tail) =
batches("echo ' ' >&2; i=1; while [ $i -le 25 ]; do echo e$i >&2; i=$((i+1)); done; echo out", 10);
assert_eq!(batches, [vec!["out"]]);
let expected: Vec<String> = (6..=25).map(|i| format!("e{i}")).collect();
assert_eq!(tail, expected);
}
#[test]
fn a_stream_cancelled_before_it_starts_does_not_spawn() {
let cancel = CancellationToken::new();
cancel.cancel();
let err = stream_batched(
Command::new("/nonexistent/openidea-adb"),
&cancel,
LONG,
10,
|line| Some(line.to_owned()),
&mut |_| {},
)
.err()
.unwrap();
assert_eq!(err.kind, ErrorKind::Cancelled);
assert_eq!(err.message, "cancelled");
}
#[test]
fn a_stream_cancelled_while_running_fails_and_the_child_is_killed() {
let (cmd, file) = recording_pid("adb-stream-cancel", "echo started; exec sleep 30");
let cancel = CancellationToken::new();
let err = stream_batched(cmd, &cancel, LONG, 1, |line| Some(line.to_owned()), &mut |_| cancel.cancel())
.err()
.unwrap();
assert_eq!(err.kind, ErrorKind::Cancelled);
assert_eq!(err.message, "cancelled");
assert_gone(recorded_pid(&file));
}
#[test]
fn a_missing_program_cannot_be_streamed() {
let err = stream_batched(
Command::new("/nonexistent/openidea-adb"),
&CancellationToken::new(),
LONG,
10,
|line| Some(line.to_owned()),
&mut |_| {},
)
.err()
.unwrap();
assert_eq!(err.kind, ErrorKind::Unavailable);
assert_eq!(err.message, "could not run adb: No such file or directory (os error 2)");
}
} }
+2
View File
@@ -17,4 +17,6 @@ serde_json.workspace = true
specta.workspace = true specta.workspace = true
tracing.workspace = true tracing.workspace = true
dirs.workspace = true dirs.workspace = true
[dev-dependencies]
tempfile.workspace = true tempfile.workspace = true
+6 -22
View File
@@ -47,20 +47,13 @@ pub fn plan(root: &Path, model: &BuildModel, module: &Path, cache: &Path) -> Ide
fs::write( fs::write(
&script, &script,
format!( format!(
r#"import org.gradle.util.GradleVersion r#"gradle.projectsEvaluated {{
gradle.projectsEvaluated {{
def p = gradle.rootProject.project({}) def p = gradle.rootProject.project({})
def update = {{ t -> def resources = p.tasks.named('processResources')
t.dependsOn 'processResources' p.tasks.register('openideaUpdateResources') {{
// Resolved here so the action holds no task or project (configuration cache). dependsOn resources
def dir = p.tasks.getByName('processResources').destinationDir doLast {{ new File({}).setText(resources.get().destinationDir.absolutePath, 'UTF-8') }}
def manifest = new File({})
t.doLast {{ manifest.setText(dir.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), literal(&p.path),
@@ -179,16 +172,7 @@ mod tests {
assert_eq!(gradle.command, "/tools/gradlew"); assert_eq!(gradle.command, "/tools/gradlew");
assert_eq!(gradle.args.last().unwrap(), ":app:openideaUpdateResources"); assert_eq!(gradle.args.last().unwrap(), ":app:openideaUpdateResources");
let script = fs::read_to_string(cache.join("resources.init.gradle")).unwrap(); let script = fs::read_to_string(cache.join("resources.init.gradle")).unwrap();
assert!( assert!(script.contains("processResources") && script.contains("destinationDir.absolutePath"));
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("build/resources/main")); // The task owns custom output locations. assert!(!script.contains("build/resources/main")); // The task owns custom output locations.
} }
+6 -23
View File
@@ -120,7 +120,7 @@ fn collect(
break; 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()); inputs.push(program.clone());
// Maven installed via a symlink still reads conf from its distribution. // Maven installed via a symlink still reads conf from its distribution.
if let Ok(program) = dunce::canonicalize(program) if let Ok(program) = dunce::canonicalize(program)
@@ -131,7 +131,7 @@ fn collect(
} }
} }
if !environment.contains_key("JAVA_HOME") { 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()); inputs.push(java.clone());
if let Ok(java) = dunce::canonicalize(java) if let Ok(java) = dunce::canonicalize(java)
&& let Some(home) = java.parent().and_then(Path::parent) && let Some(home) = java.parent().and_then(Path::parent)
@@ -171,7 +171,7 @@ fn collect(
let steps = plan let steps = plan
.steps .steps
.iter() .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(); .collect();
// Profiles and plugins can read arbitrary environment variables. Keep a signature // Profiles and plugins can read arbitrary environment variables. Keep a signature
// of the inherited environment without persisting unrelated credentials. // of the inherited environment without persisting unrelated credentials.
@@ -182,7 +182,7 @@ fn collect(
} }
/// Scans every input, storing project inputs relative to the project. /// Scans every input, storing project inputs relative to the project.
pub(super) fn scan_all( fn scan_all(
root: &Path, root: &Path,
inputs: Vec<PathBuf>, inputs: Vec<PathBuf>,
cancel: &CancellationToken, cancel: &CancellationToken,
@@ -210,7 +210,7 @@ pub fn launch_fingerprint(
if projects.is_empty() { if projects.is_empty() {
return Ok(None); 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 Some(collected) = collect(root, &projects, &plan, local_repo)? else { return Ok(None) };
let Collected { inputs, environment, steps, inherited_hash } = collected; let Collected { inputs, environment, steps, inherited_hash } = collected;
let parameters = serde_json::to_string(&(root, module, test, steps, environment, inherited_hash, projects)) 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>, file: Option<&Path>,
cancel: &CancellationToken, cancel: &CancellationToken,
) -> IdeResult<Option<LaunchFingerprint>> { ) -> 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 { if plan.system != BuildSystem::Maven {
return Ok(None); return Ok(None);
} }
@@ -264,23 +264,6 @@ pub fn menu_fingerprint(
Ok(Some(LaunchFingerprint { version: 2, parameters, files: scan_all(root, inputs, cancel)? })) 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 { impl LaunchFingerprint {
/// Folders (relative to the project) of the Maven projects whose POM is an input. /// Folders (relative to the project) of the Maven projects whose POM is an input.
pub(super) fn project_dirs(&self) -> impl Iterator<Item = &Path> { pub(super) fn project_dirs(&self) -> impl Iterator<Item = &Path> {
+62 -458
View File
@@ -5,22 +5,15 @@
mod fingerprint; mod fingerprint;
mod launch_resources; mod launch_resources;
mod modules;
mod parse; mod parse;
mod single; mod single;
mod structure;
mod up_to_date; mod up_to_date;
pub use fingerprint::{LaunchFingerprint, launch_fingerprint, menu_fingerprint}; pub use fingerprint::{LaunchFingerprint, launch_fingerprint, menu_fingerprint};
pub use launch_resources::process_launch_resources; pub use launch_resources::process_launch_resources;
pub use modules::record_module_build;
pub use single::{ pub use single::{
SingleFileTarget, compile_file_plan, find_javac, javac_step, module_classpath, module_classpaths, SingleFileTarget, compile_file_plan, find_javac, javac_step, module_classpath, single_file_classpath,
single_file_classpath, single_file_target, single_file_target,
};
pub use structure::{
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}; pub use up_to_date::{menu_up_to_date, record_menu_build};
@@ -60,10 +53,6 @@ pub enum BuildSystem {
TypeScript, TypeScript,
#[serde(rename = "cmake")] #[serde(rename = "cmake")]
CMake, CMake,
#[serde(rename = "dotnet")]
Dotnet,
/// A Java project without a build tool, compiled from its Project Structure.
Javac,
} }
/// One command of a build. /// One command of a build.
@@ -74,10 +63,6 @@ pub struct BuildStep {
pub cwd: PathBuf, pub cwd: PathBuf,
pub env: BTreeMap<String, String>, pub env: BTreeMap<String, String>,
format: Format, format: Format,
/// Folders created before the command runs (a compiler's output).
mkdirs: Vec<PathBuf>,
/// Work done in the IDE instead of a command, with its console title.
action: Option<(structure::Action, String)>,
} }
impl BuildStep { impl BuildStep {
@@ -88,26 +73,16 @@ impl BuildStep {
cwd: cwd.to_path_buf(), cwd: cwd.to_path_buf(),
env: BTreeMap::new(), env: BTreeMap::new(),
format, format,
mkdirs: Vec::new(),
action: None,
} }
} }
fn action(action: structure::Action, root: &Path) -> Self {
let title = action.display(root);
BuildStep { action: Some((action, title)), ..Self::new("", &[], root, Format::Gradle) }
}
/// A CMake configure/build invocation, parsed as compiler output in the Build view. /// A CMake configure/build invocation, parsed as compiler output in the Build view.
pub fn cmake(program: &str, args: Vec<String>, cwd: PathBuf, env: BTreeMap<String, String>) -> Self { pub fn cmake(program: &str, args: Vec<String>, cwd: PathBuf, env: BTreeMap<String, String>) -> Self {
Self { program: program.into(), args, cwd, env, format: Format::Gcc, mkdirs: Vec::new(), action: None } Self { program: program.into(), args, cwd, env, format: Format::Gcc }
} }
/// The command line as echoed in the console. /// The command line as echoed in the console.
pub fn display(&self) -> String { pub fn display(&self) -> String {
if let Some((_, title)) = &self.action {
return title.clone();
}
let program = Path::new(&self.program).file_name().map_or(self.program.clone(), |n| n.to_string_lossy().into()); let program = Path::new(&self.program).file_name().map_or(self.program.clone(), |n| n.to_string_lossy().into());
std::iter::once(program) std::iter::once(program)
.chain(self.args.iter().map(|a| if a.contains(' ') { format!("\"{a}\"") } else { a.clone() })) .chain(self.args.iter().map(|a| if a.contains(' ') { format!("\"{a}\"") } else { a.clone() }))
@@ -190,8 +165,6 @@ fn detect_dir(dir: &Path, model: &BuildModel, root: &Path) -> Option<BuildSystem
|| has(dir, &["build.gradle", "build.gradle.kts", "settings.gradle", "settings.gradle.kts"]) || has(dir, &["build.gradle", "build.gradle.kts", "settings.gradle", "settings.gradle.kts"])
{ {
Some(BuildSystem::Gradle) Some(BuildSystem::Gradle)
} else if dotnet_target(dir).is_some() {
Some(BuildSystem::Dotnet)
} else if has(dir, &["Cargo.toml"]) { } else if has(dir, &["Cargo.toml"]) {
Some(BuildSystem::Cargo) Some(BuildSystem::Cargo)
} else if has(dir, &["go.mod", "go.work"]) { } else if has(dir, &["go.mod", "go.work"]) {
@@ -222,16 +195,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). /// 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. /// `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( pub fn plan(
root: &Path, root: &Path,
model: &BuildModel, model: &BuildModel,
kind: BuildKind, kind: BuildKind,
file: Option<&Path>, file: Option<&Path>,
cmake: Option<&[CMakeProfile]>, cmake: Option<&[CMakeProfile]>,
cache: Option<&Path>,
cancel: &CancellationToken,
) -> IdeResult<BuildPlan> { ) -> IdeResult<BuildPlan> {
let project_name = root.file_name().map_or_else(|| "project".to_owned(), |n| n.to_string_lossy().into_owned()); let project_name = root.file_name().map_or_else(|| "project".to_owned(), |n| n.to_string_lossy().into_owned());
let module_dir = match file { let module_dir = match file {
@@ -256,7 +225,7 @@ pub fn plan(
.or((!model.gradle.is_empty()).then_some(BuildSystem::Gradle)) .or((!model.gradle.is_empty()).then_some(BuildSystem::Gradle))
.or_else(|| model.maven.as_ref().filter(|m| !m.projects.is_empty()).map(|_| BuildSystem::Maven)) .or_else(|| model.maven.as_ref().filter(|m| !m.projects.is_empty()).map(|_| BuildSystem::Maven))
.ok_or_else(|| { .ok_or_else(|| {
IdeError::not_found("no supported build system (Maven, Gradle, .NET, Cargo, Go, TypeScript, CMake) found") IdeError::not_found("no supported build system (Maven, Gradle, Cargo, Go, TypeScript, CMake) found")
})?; })?;
let module = module_dir.as_deref().filter(|d| *d != root); let module = module_dir.as_deref().filter(|d| *d != root);
let title = match module { let title = match module {
@@ -268,16 +237,13 @@ pub fn plan(
None => project_name, None => project_name,
}; };
let steps = match system { 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::Gradle => gradle_steps(root, model, kind, module_dir.as_deref())?,
BuildSystem::Cargo => cargo_steps(&dir, kind), BuildSystem::Cargo => cargo_steps(&dir, kind),
// Go builds the file's package (a module holds many). // Go builds the file's package (a module holds many).
BuildSystem::Go => go_steps(file.and_then(Path::parent).unwrap_or(&dir), kind)?, BuildSystem::Go => go_steps(file.and_then(Path::parent).unwrap_or(&dir), kind)?,
BuildSystem::TypeScript => ts_steps(&dir, kind), BuildSystem::TypeScript => ts_steps(&dir, kind),
BuildSystem::CMake => cmake_steps(&dir, kind, cmake.and_then(<[_]>::first)), BuildSystem::CMake => cmake_steps(&dir, kind, cmake.and_then(<[_]>::first)),
BuildSystem::Dotnet => dotnet_steps(&dir, kind)?,
// Never detected from a folder: it comes from the Project Structure (`structure_plan`).
BuildSystem::Javac => return Err(IdeError::invalid("no build tool to run")),
}; };
Ok(BuildPlan { system, title, steps }) Ok(BuildPlan { system, title, steps })
} }
@@ -287,8 +253,6 @@ pub(super) fn maven_steps(
model: &BuildModel, model: &BuildModel,
kind: BuildKind, kind: BuildKind,
module: Option<&Path>, module: Option<&Path>,
cache: Option<&Path>,
cancel: &CancellationToken,
) -> IdeResult<Vec<BuildStep>> { ) -> IdeResult<Vec<BuildStep>> {
let fallback; let fallback;
let m = match &model.maven { let m = match &model.maven {
@@ -328,15 +292,7 @@ pub(super) fn maven_steps(
s.env = p.env.clone(); s.env = p.env.clone();
s s
}; };
let Some(module) = module else { let Some(module) = module else { return Ok(tops.iter().map(|p| step(p, &[])).collect()) };
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());
};
// The reactor root containing the module builds it with what it depends on (`-pl … -am`). // The reactor root containing the module builds it with what it depends on (`-pl … -am`).
let rel = rel_str(root, module); let rel = rel_str(root, module);
if !m.projects.iter().any(|p| p.dir == rel) { if !m.projects.iter().any(|p| p.dir == rel) {
@@ -483,6 +439,11 @@ fn go_module_steps(dir: &Path, kind: BuildKind) -> Vec<BuildStep> {
vec![s] 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 { fn has_build_script(dir: &Path) -> bool {
std::fs::read(dir.join("package.json")) std::fs::read(dir.join("package.json"))
.ok() .ok()
@@ -490,42 +451,10 @@ fn has_build_script(dir: &Path) -> bool {
.is_some_and(|v| v.pointer("/scripts/build").is_some_and(serde_json::Value::is_string)) .is_some_and(|v| v.pointer("/scripts/build").is_some_and(serde_json::Value::is_string))
} }
/// The solution (`.sln` / `.slnx`) or project (`.csproj` / `.fsproj` / `.vbproj`) file `dir`
/// builds: a solution first, then a project; the first by name when there are several.
fn dotnet_target(dir: &Path) -> Option<PathBuf> {
let mut files: Vec<PathBuf> =
std::fs::read_dir(dir).ok()?.flatten().map(|e| e.path()).filter(|p| p.is_file()).collect();
files.sort();
let ext = |p: &Path| p.extension().map(|e| e.to_string_lossy().to_ascii_lowercase()).unwrap_or_default();
let solution = files.iter().find(|p| matches!(ext(p).as_str(), "sln" | "slnx"));
solution.or_else(|| files.iter().find(|p| matches!(ext(p).as_str(), "csproj" | "fsproj" | "vbproj"))).cloned()
}
/// `dotnet build` of the directory's solution or project; Rebuild skips incremental builds,
/// Build Artifacts publishes. The summary that repeats every message is left out.
fn dotnet_steps(dir: &Path, kind: BuildKind) -> IdeResult<Vec<BuildStep>> {
let target = dotnet_target(dir).ok_or_else(|| IdeError::not_found("no .NET solution or project found"))?;
let target = target.file_name().map_or_else(String::new, |n| n.to_string_lossy().into_owned());
let verb = if kind == BuildKind::Artifacts { "publish" } else { "build" };
let mut step = BuildStep::new("dotnet", &[verb, &target, "-nologo", "-clp:NoSummary"], dir, Format::Msbuild);
if kind == BuildKind::Rebuild {
step.args.push("--no-incremental".into());
}
// The classic console logger prints the canonical `file(line,col): error` lines; the
// terminal logger (.NET 8+) only appears on a terminal, but rules it out for older SDKs too.
step.env.insert("MSBUILDTERMINALLOGGER".into(), "off".into());
Ok(vec![step])
}
fn ts_steps(dir: &Path, kind: BuildKind) -> Vec<BuildStep> { fn ts_steps(dir: &Path, kind: BuildKind) -> Vec<BuildStep> {
let script = has_build_script(dir); let script = has_build_script(dir);
if script && (kind == BuildKind::Artifacts || !dir.join("tsconfig.json").is_file()) { if script && (kind == BuildKind::Artifacts || !dir.join("tsconfig.json").is_file()) {
return vec![BuildStep::new( return vec![BuildStep::new(package_manager(dir), &["run", "build"], dir, Format::Tsc)];
ide_core::project_roots::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 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()); let program = local.map_or_else(|| "tsc".to_owned(), |p| p.to_string_lossy().into_owned());
@@ -552,9 +481,7 @@ impl PathMap {
let abs = if p.is_absolute() { let abs = if p.is_absolute() {
p.to_path_buf() p.to_path_buf()
} else { } else {
// rustc prints workspace members' files relative to the workspace root, above let in_base = base.map(|b| Path::new(b).join(p)).filter(|c| c.exists());
// 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()));
in_base.unwrap_or_else(|| cwd.join(p)) in_base.unwrap_or_else(|| cwd.join(p))
}; };
let abs = normalize(&abs); let abs = normalize(&abs);
@@ -566,7 +493,7 @@ impl PathMap {
} }
/// Removes `.` and resolvable `..` components without touching the file system. /// 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; use std::path::Component;
let mut out = PathBuf::new(); let mut out = PathBuf::new();
for c in p.components() { for c in p.components() {
@@ -691,36 +618,6 @@ pub fn run(
let command = step.display(); let command = step.display();
on_event(BuildEvent::Step { command: command.clone(), cwd: step.cwd.clone().into() }); on_event(BuildEvent::Step { command: command.clone(), cwd: step.cwd.clone().into() });
on_event(BuildEvent::Progress { message: command.clone(), fraction: None }); on_event(BuildEvent::Progress { message: command.clone(), fraction: None });
if let Some((action, _)) = &step.action {
match action.run(cancel) {
Ok(text) => {
if !text.is_empty() {
on_event(BuildEvent::Output { text: format!("{text}\n"), stderr: false });
}
continue;
}
Err(e) if e.kind == ide_core::error::ErrorKind::Cancelled => return Err(e),
Err(e) => {
let m = BuildMessage {
severity: Severity::Error,
text: e.message.clone(),
path: None,
range: None,
code: None,
};
on_event(BuildEvent::Output { text: format!("{}\n", e.message), stderr: true });
on_event(BuildEvent::Message { message: m.clone() });
messages.push(m);
success = false;
break;
}
}
}
for dir in &step.mkdirs {
if let Err(e) = std::fs::create_dir_all(dir) {
tracing::debug!(dir = %dir.display(), %e, "cannot create the build output folder");
}
}
let mut parser = OutputParser::new(step.format); let mut parser = OutputParser::new(step.format);
let mut emit = |raws: Vec<RawMessage>, messages: &mut Vec<BuildMessage>| { let mut emit = |raws: Vec<RawMessage>, messages: &mut Vec<BuildMessage>| {
for raw in raws { for raw in raws {
@@ -731,7 +628,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); let parsed = parser.feed(line);
match parsed.console { match parsed.console {
Some(text) if text.is_empty() => {} Some(text) if text.is_empty() => {}
@@ -773,7 +670,7 @@ pub fn run(
if !out.success { if !out.success {
success = false; success = false;
if !messages.iter().any(|m| m.severity == Severity::Error) { 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 text = if summary.is_empty() { last_error_line.clone() } else { summary };
let m = BuildMessage { severity: Severity::Error, text, path: None, range: None, code: None }; let m = BuildMessage { severity: Severity::Error, text, path: None, range: None, code: None };
on_event(BuildEvent::Message { message: m.clone() }); on_event(BuildEvent::Message { message: m.clone() });
@@ -897,15 +794,8 @@ pub fn launch_has_non_java_sources(root: &Path, model: &BuildModel, module: &Pat
has_non_java_sources(module) has_non_java_sources(module)
} }
fn launch_plan( fn launch_plan(root: &Path, model: &BuildModel, module: &Path, test: bool, kind: BuildKind) -> IdeResult<BuildPlan> {
root: &Path, let mut plan = plan(root, model, kind, Some(module), None)?;
model: &BuildModel,
module: &Path,
test: bool,
kind: BuildKind,
cancel: &CancellationToken,
) -> IdeResult<BuildPlan> {
let mut plan = plan(root, model, kind, Some(module), None, None, cancel)?;
if plan.system == BuildSystem::Maven && !test { if plan.system == BuildSystem::Maven && !test {
for step in &mut plan.steps { for step in &mut plan.steps {
if let Some(goal) = step.args.last_mut() { if let Some(goal) = step.args.last_mut() {
@@ -916,47 +806,6 @@ fn launch_plan(
Ok(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)] #[derive(Debug)]
pub struct LaunchBuild { pub struct LaunchBuild {
pub class_dirs: Vec<PathBuf>, pub class_dirs: Vec<PathBuf>,
@@ -973,21 +822,7 @@ pub fn build_for_launch(
kind: BuildKind, kind: BuildKind,
cancel: &CancellationToken, cancel: &CancellationToken,
) -> IdeResult<LaunchBuild> { ) -> IdeResult<LaunchBuild> {
let mut built = build_for_launches(root, model, &[module.to_path_buf()], test, kind, cancel)?; let plan = launch_plan(root, model, module, test, kind)?;
Ok(built.pop().unwrap())
}
/// [`build_for_launch`] of several modules of one Maven reactor in a single Maven run:
/// one result per module, in order, sharing the build's failure.
pub fn build_for_launches(
root: &Path,
model: &BuildModel,
modules: &[PathBuf],
test: bool,
kind: BuildKind,
cancel: &CancellationToken,
) -> IdeResult<Vec<LaunchBuild>> {
let plan = merged_launch_plan(root, model, modules, test, kind, cancel)?;
let result = run(root, &plan, cancel, &|_| {})?; let result = run(root, &plan, cancel, &|_| {})?;
let failure = if !result.success { let failure = if !result.success {
let errors: Vec<String> = result let errors: Vec<String> = result
@@ -1004,70 +839,17 @@ pub fn build_for_launches(
} else { } else {
None None
}; };
let class_dirs = |module: &Path| { let class_dirs = if plan.system == BuildSystem::Maven
if plan.system == BuildSystem::Maven && let Some(m) = &model.maven
&& let Some(m) = &model.maven {
{ maven_launch_projects(root, m, module, test)
maven_launch_output_dirs(root, m, module, test).into_iter().filter(|dir| dir.is_dir()).collect() .iter()
} else { .flat_map(|p| launch_class_dirs(plan.system, &subdir(root, &p.dir), test && subdir(root, &p.dir) == module))
launch_class_dirs(plan.system, module, test) .collect()
} } else {
launch_class_dirs(plan.system, module, test)
}; };
Ok(modules.iter().map(|m| LaunchBuild { class_dirs: class_dirs(m), failure: failure.clone() }).collect()) Ok(LaunchBuild { class_dirs, failure })
}
/// 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
} }
fn launch_class_dirs(system: BuildSystem, module: &Path, test: bool) -> Vec<PathBuf> { fn launch_class_dirs(system: BuildSystem, module: &Path, test: bool) -> Vec<PathBuf> {
@@ -1080,7 +862,8 @@ fn launch_class_dirs(system: BuildSystem, module: &Path, test: bool) -> Vec<Path
.map(|d| subdir(module, &format!("build/{d}/{s}"))) .map(|d| subdir(module, &format!("build/{d}/{s}")))
}) })
.collect(), .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(), _ => Vec::new(),
}; };
dirs.into_iter().filter(|d| d.is_dir()).collect() dirs.into_iter().filter(|d| d.is_dir()).collect()
@@ -1104,9 +887,7 @@ mod tests {
write(root, "../external/main.go", "package main\nimport \"example.com/lib\"\nfunc main(){_ = lib.Value()}\n"); write(root, "../external/main.go", "package main\nimport \"example.com/lib\"\nfunc main(){_ = lib.Value()}\n");
// std canonicalization also exercises verbatim paths on Windows. // std canonicalization also exercises verbatim paths on Windows.
for root in [root.to_path_buf(), std::fs::canonicalize(root).unwrap()] { for root in [root.to_path_buf(), std::fs::canonicalize(root).unwrap()] {
let plan = let plan = plan(&root, &BuildModel::default(), BuildKind::Build, None, None).unwrap();
plan(&root, &BuildModel::default(), BuildKind::Build, None, None, None, &CancellationToken::new())
.unwrap();
for step in plan.steps { for step in plan.steps {
let result = std::process::Command::new(&go) let result = std::process::Command::new(&go)
.args(&step.args) .args(&step.args)
@@ -1132,7 +913,7 @@ mod tests {
let canonical = std::fs::canonicalize(&root).unwrap(); let canonical = std::fs::canonicalize(&root).unwrap();
for root in [&root, &canonical, &canonical.join("..").join("workspace")] { for root in [&root, &canonical, &canonical.join("..").join("workspace")] {
for kind in [BuildKind::Build, BuildKind::Rebuild, BuildKind::Artifacts] { 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.system, BuildSystem::Go);
assert_eq!(p.steps.len(), 3); assert_eq!(p.steps.len(), 3);
for (step, module) in p.steps.iter().zip(["api", "lib with spaces", "../shared"]) { for (step, module) in p.steps.iter().zip(["api", "lib with spaces", "../shared"]) {
@@ -1147,30 +928,20 @@ mod tests {
} }
} }
} }
let member = plan( let member =
&root, plan(&root, &BuildModel::default(), BuildKind::Build, Some(&root.join("api/pkg/a.go")), None).unwrap();
&BuildModel::default(),
BuildKind::Build,
Some(&root.join("api/pkg/a.go")),
None,
None,
&CancellationToken::new(),
)
.unwrap();
assert_eq!(member.steps.len(), 1); assert_eq!(member.steps.len(), 1);
assert_eq!(member.steps[0].cwd, root.join("api")); assert_eq!(member.steps[0].cwd, root.join("api"));
assert_eq!(member.steps[0].args, ["build", "./pkg/..."]); assert_eq!(member.steps[0].args, ["build", "./pkg/..."]);
write(&root, "go.work", "use ./missing\n"); write(&root, "go.work", "use ./missing\n");
assert!( assert!(
plan(&root, &BuildModel::default(), BuildKind::Build, None, None, None, &CancellationToken::new()) plan(&root, &BuildModel::default(), BuildKind::Build, None, None)
.unwrap_err() .unwrap_err()
.to_string() .to_string()
.contains("go.mod") .contains("go.mod")
); );
write(&root, "go.work", "go 1.22\n"); write(&root, "go.work", "go 1.22\n");
assert!( assert!(plan(&root, &BuildModel::default(), BuildKind::Build, None, None).is_err());
plan(&root, &BuildModel::default(), BuildKind::Build, None, None, None, &CancellationToken::new()).is_err()
);
} }
#[test] #[test]
@@ -1191,21 +962,11 @@ mod tests {
let mut model = crate::load_linked(root, &root.join("cache"), None, &Default::default(), &settings); 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[0].env.insert("JAVA_HOME".into(), "/jdk-a".into());
model.gradle[1].env.insert("JAVA_HOME".into(), "/jdk-b".into()); model.gradle[1].env.insert("JAVA_HOME".into(), "/jdk-b".into());
let all = let all = super::plan(root, &model, super::BuildKind::Build, None, None).unwrap();
super::plan(root, &model, super::BuildKind::Build, None, None, None, &CancellationToken::new()).unwrap();
assert_eq!(all.steps.len(), 2); assert_eq!(all.steps.len(), 2);
assert_eq!(all.steps[0].cwd, root.join("a")); assert_eq!(all.steps[0].cwd, root.join("a"));
assert_eq!(all.steps[1].cwd, root.join("b")); assert_eq!(all.steps[1].cwd, root.join("b"));
let module = super::plan( let module = super::plan(root, &model, super::BuildKind::Rebuild, Some(&root.join("b/app")), None).unwrap();
root,
&model,
super::BuildKind::Rebuild,
Some(&root.join("b/app")),
None,
None,
&CancellationToken::new(),
)
.unwrap();
assert_eq!(module.steps.len(), 1); 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].program, root.join("b").join(wrapper).to_string_lossy());
assert_eq!(module.steps[0].cwd, root.join("b")); assert_eq!(module.steps[0].cwd, root.join("b"));
@@ -1218,31 +979,11 @@ mod tests {
let mut nested = model.gradle[1].projects[1].clone(); let mut nested = model.gradle[1].projects[1].clone();
nested.path = ":b:app".into(); nested.path = ":b:app".into();
model.gradle[0].projects.push(nested); model.gradle[0].projects.push(nested);
let nested = super::plan( let nested = super::plan(root, &model, super::BuildKind::Build, Some(&root.join("b/app")), None).unwrap();
root,
&model,
super::BuildKind::Build,
Some(&root.join("b/app")),
None,
None,
&CancellationToken::new(),
)
.unwrap();
assert_eq!(nested.steps[0].program, root.join("b").join(wrapper).to_string_lossy()); 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"]); assert_eq!(nested.steps[0].args, ["--console=plain", ":app:classes", ":app:testClasses"]);
model.gradle.clear(); model.gradle.clear();
assert!( assert!(super::plan(root, &model, super::BuildKind::Build, Some(&root.join("b/app")), None).is_err());
super::plan(
root,
&model,
super::BuildKind::Build,
Some(&root.join("b/app")),
None,
None,
&CancellationToken::new()
)
.is_err()
);
} }
#[test] #[test]
@@ -1264,24 +1005,18 @@ mod tests {
}; };
let mut model = crate::load_linked(&root, &base.join("cache"), None, &Default::default(), &settings); 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()); model.gradle[0].env.insert("JAVA_HOME".into(), "/external-jdk".into());
let all = let all = super::plan(&root, &model, super::BuildKind::Build, None, None).unwrap();
super::plan(&root, &model, super::BuildKind::Build, None, None, None, &CancellationToken::new()).unwrap();
assert_eq!(all.steps[0].cwd, external); assert_eq!(all.steps[0].cwd, external);
// Linked roots are saved with forward slashes, so on Windows the program mixes separators. // 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)); assert_eq!(std::path::Path::new(&all.steps[0].program), external.join(wrapper));
let module = let module = super::plan(&root, &model, super::BuildKind::Rebuild, Some(&source), None).unwrap();
super::plan(&root, &model, super::BuildKind::Rebuild, Some(&source), None, None, &CancellationToken::new())
.unwrap();
assert_eq!(module.steps[0].cwd, external); assert_eq!(module.steps[0].cwd, external);
assert_eq!(module.steps[0].env["JAVA_HOME"], "/external-jdk"); assert_eq!(module.steps[0].env["JAVA_HOME"], "/external-jdk");
assert_eq!(module.steps[0].args, ["--console=plain", ":app:clean", ":app:classes", ":app:testClasses"]); assert_eq!(module.steps[0].args, ["--console=plain", ":app:clean", ":app:classes", ":app:testClasses"]);
let other = base.join("unlinked"); let other = base.join("unlinked");
std::fs::create_dir(&other).unwrap(); std::fs::create_dir(&other).unwrap();
std::fs::write(other.join("build.gradle"), "").unwrap(); std::fs::write(other.join("build.gradle"), "").unwrap();
assert!( assert!(super::plan(&root, &model, super::BuildKind::Build, Some(&other), None).is_err());
super::plan(&root, &model, super::BuildKind::Build, Some(&other), None, None, &CancellationToken::new())
.is_err()
);
} }
use super::*; use super::*;
@@ -1322,7 +1057,7 @@ mod tests {
write(&root, "pom.xml", "<project><artifactId>demo</artifactId></project>"); write(&root, "pom.xml", "<project><artifactId>demo</artifactId></project>");
let model = crate::load(&root, &tmp.path().join("cache"), None); let model = crate::load(&root, &tmp.path().join("cache"), None);
for (kind, expected) in [(BuildKind::Build, true), (BuildKind::Rebuild, true), (BuildKind::Artifacts, false)] { 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!( assert_eq!(
plan.steps[0].args.iter().any(|arg| arg == "-Djacoco.skip=true"), plan.steps[0].args.iter().any(|arg| arg == "-Djacoco.skip=true"),
expected, expected,
@@ -1343,7 +1078,7 @@ mod tests {
write(&root, "core/pom.xml", "<project><artifactId>core</artifactId></project>"); write(&root, "core/pom.xml", "<project><artifactId>core</artifactId></project>");
write(&root, "core/src/main/java/A.java", "class A {}"); write(&root, "core/src/main/java/A.java", "class A {}");
let model = crate::load(&root, &tmp.path().join("cache"), None); 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.system, BuildSystem::Maven);
assert_eq!(p.title, "demo"); assert_eq!(p.title, "demo");
assert_eq!(p.steps.len(), 1); assert_eq!(p.steps.len(), 1);
@@ -1351,16 +1086,7 @@ mod tests {
p.steps[0].args, p.steps[0].args,
["-B", "-Dstyle.color=never", maven::LOCAL_REPO_TRACKING_ARG, "-Djacoco.skip=true", "test-compile"] ["-B", "-Dstyle.color=never", maven::LOCAL_REPO_TRACKING_ARG, "-Djacoco.skip=true", "test-compile"]
); );
let p = plan( let p = plan(&root, &model, BuildKind::Rebuild, Some(&root.join("core/src/main/java/A.java")), None).unwrap();
&root,
&model,
BuildKind::Rebuild,
Some(&root.join("core/src/main/java/A.java")),
None,
None,
&CancellationToken::new(),
)
.unwrap();
assert_eq!( assert_eq!(
p.steps[0].args, p.steps[0].args,
[ [
@@ -1382,36 +1108,24 @@ mod tests {
write(&g, "settings.gradle", "include 'app'"); write(&g, "settings.gradle", "include 'app'");
write(&g, "app/build.gradle", "apply plugin: 'java'"); write(&g, "app/build.gradle", "apply plugin: 'java'");
let model = crate::load(&g, &tmp.path().join("cache2"), None); let model = crate::load(&g, &tmp.path().join("cache2"), None);
let p = let p = plan(&g, &model, BuildKind::Build, Some(&g.join("app/src/A.java")), None).unwrap();
plan(&g, &model, BuildKind::Build, Some(&g.join("app/src/A.java")), None, None, &CancellationToken::new())
.unwrap();
assert_eq!(p.system, BuildSystem::Gradle); assert_eq!(p.system, BuildSystem::Gradle);
assert_eq!(p.steps[0].args, ["--console=plain", ":app:classes", ":app:testClasses"]); assert_eq!(p.steps[0].args, ["--console=plain", ":app:classes", ":app:testClasses"]);
assert_eq!( 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"] ["--console=plain", "assemble"]
); );
let c = tmp.path().join("c"); let c = tmp.path().join("c");
write(&c, "Cargo.toml", "[package]\nname='c'"); write(&c, "Cargo.toml", "[package]\nname='c'");
let p = let p = plan(&c, &BuildModel::default(), BuildKind::Rebuild, None, None).unwrap();
plan(&c, &BuildModel::default(), BuildKind::Rebuild, None, None, None, &CancellationToken::new()).unwrap();
assert_eq!(p.system, BuildSystem::Cargo); assert_eq!(p.system, BuildSystem::Cargo);
assert_eq!(p.steps.len(), 2); assert_eq!(p.steps.len(), 2);
assert_eq!(p.steps[0].args[0], "clean"); assert_eq!(p.steps[0].args[0], "clean");
let go = tmp.path().join("go"); let go = tmp.path().join("go");
write(&go, "go.mod", "module x"); write(&go, "go.mod", "module x");
let p = plan( let p = plan(&go, &BuildModel::default(), BuildKind::Build, Some(&go.join("pkg/a/a.go")), None).unwrap();
&go,
&BuildModel::default(),
BuildKind::Build,
Some(&go.join("pkg/a/a.go")),
None,
None,
&CancellationToken::new(),
)
.unwrap();
assert_eq!(p.steps[0].args, ["build", "./pkg/a/..."]); assert_eq!(p.steps[0].args, ["build", "./pkg/a/..."]);
assert_eq!(p.steps[0].cwd, go); assert_eq!(p.steps[0].cwd, go);
@@ -1419,49 +1133,18 @@ mod tests {
write(&ts, "package.json", r#"{"scripts":{"build":"vite build"}}"#); write(&ts, "package.json", r#"{"scripts":{"build":"vite build"}}"#);
write(&ts, "tsconfig.json", "{}"); write(&ts, "tsconfig.json", "{}");
write(&ts, "pnpm-lock.yaml", ""); write(&ts, "pnpm-lock.yaml", "");
let p = let p = plan(&ts, &BuildModel::default(), BuildKind::Build, None, None).unwrap();
plan(&ts, &BuildModel::default(), BuildKind::Build, None, None, None, &CancellationToken::new()).unwrap();
assert_eq!(p.steps[0].args, ["--noEmit", "--pretty", "false", "-p", "."]); assert_eq!(p.steps[0].args, ["--noEmit", "--pretty", "false", "-p", "."]);
let p = plan(&ts, &BuildModel::default(), BuildKind::Artifacts, None, None, None, &CancellationToken::new()) let p = plan(&ts, &BuildModel::default(), BuildKind::Artifacts, None, None).unwrap();
.unwrap();
assert_eq!( assert_eq!(
(p.steps[0].program.as_str(), p.steps[0].args.as_slice()), (p.steps[0].program.as_str(), p.steps[0].args.as_slice()),
("pnpm", &["run".to_owned(), "build".to_owned()][..]) ("pnpm", &["run".to_owned(), "build".to_owned()][..])
); );
// .NET: the solution, else the project; a module build is the file's project. An ASP.NET
// project's package.json (its front end) doesn't make it a TypeScript build.
let net = tmp.path().join("net");
write(&net, "App.sln", "");
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();
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();
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();
assert_eq!(p.steps[0].args[0], "publish");
let cm = tmp.path().join("cm"); let cm = tmp.path().join("cm");
write(&cm, "CMakeLists.txt", "project(app)"); write(&cm, "CMakeLists.txt", "project(app)");
let args = |p: &BuildPlan| p.steps.iter().map(|s| s.args.join(" ")).collect::<Vec<_>>(); let args = |p: &BuildPlan| p.steps.iter().map(|s| s.args.join(" ")).collect::<Vec<_>>();
let p = let p = plan(&cm, &BuildModel::default(), BuildKind::Build, None, None).unwrap();
plan(&cm, &BuildModel::default(), BuildKind::Build, None, None, None, &CancellationToken::new()).unwrap();
assert_eq!(p.system, BuildSystem::CMake); assert_eq!(p.system, BuildSystem::CMake);
assert_eq!( assert_eq!(
args(&p), args(&p),
@@ -1472,8 +1155,7 @@ mod tests {
"an unconfigured project is configured first" "an unconfigured project is configured first"
); );
write(&cm, "cmake-build-release/CMakeCache.txt", ""); write(&cm, "cmake-build-release/CMakeCache.txt", "");
let p = let p = plan(&cm, &BuildModel::default(), BuildKind::Rebuild, None, None).unwrap();
plan(&cm, &BuildModel::default(), BuildKind::Rebuild, None, None, None, &CancellationToken::new()).unwrap();
assert_eq!( assert_eq!(
args(&p), args(&p),
["--build cmake-build-release --config Debug --clean-first"], ["--build cmake-build-release --config Debug --clean-first"],
@@ -1485,34 +1167,17 @@ mod tests {
build_args: vec!["-j".into(), "8".into()], build_args: vec!["-j".into(), "8".into()],
..CMakeProfile::default() ..CMakeProfile::default()
}; };
let p = plan( let p =
&cm, plan(&cm, &BuildModel::default(), BuildKind::Build, None, Some(std::slice::from_ref(&profile))).unwrap();
&BuildModel::default(),
BuildKind::Build,
None,
Some(std::slice::from_ref(&profile)),
None,
&CancellationToken::new(),
)
.unwrap();
assert_eq!(args(&p), ["--build cmake-build-release --config Release -j 8"]); assert_eq!(args(&p), ["--build cmake-build-release --config Release -j 8"]);
let p = plan( let p = plan(&cm, &BuildModel::default(), BuildKind::Build, None, Some(&[CMakeProfile::default()])).unwrap();
&cm,
&BuildModel::default(),
BuildKind::Build,
None,
Some(&[CMakeProfile::default()]),
None,
&CancellationToken::new(),
)
.unwrap();
assert_eq!(p.steps[0].args[..4], ["-S", ".", "-B", "cmake-build-debug"]); assert_eq!(p.steps[0].args[..4], ["-S", ".", "-B", "cmake-build-debug"]);
let siblings = tmp.path().join("siblings"); let siblings = tmp.path().join("siblings");
write(&siblings, "core/pom.xml", "<project><artifactId>core</artifactId></project>"); write(&siblings, "core/pom.xml", "<project><artifactId>core</artifactId></project>");
write(&siblings, "system/pom.xml", "<project><artifactId>system</artifactId></project>"); write(&siblings, "system/pom.xml", "<project><artifactId>system</artifactId></project>");
let model = crate::load(&siblings, &tmp.path().join("cache3"), None); 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.system, BuildSystem::Maven);
assert_eq!( assert_eq!(
p.steps.iter().map(|s| s.cwd.clone()).collect::<Vec<_>>(), p.steps.iter().map(|s| s.cwd.clone()).collect::<Vec<_>>(),
@@ -1521,9 +1186,7 @@ mod tests {
let none = tmp.path().join("none"); let none = tmp.path().join("none");
std::fs::create_dir_all(&none).unwrap(); std::fs::create_dir_all(&none).unwrap();
assert!( assert!(plan(&none, &BuildModel::default(), BuildKind::Build, None, None).is_err());
plan(&none, &BuildModel::default(), BuildKind::Build, None, None, None, &CancellationToken::new()).is_err()
);
} }
#[test] #[test]
@@ -1537,22 +1200,6 @@ mod tests {
assert_eq!(identifier_len("x é_1 c", 2), 3); 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. // Uses Unix absolute paths for the canonical root.
#[cfg(unix)] #[cfg(unix)]
#[test] #[test]
@@ -1722,8 +1369,7 @@ mod tests {
let model = reactor_model(); let model = reactor_model();
for (test, goal) in [(false, "compile"), (true, "test-compile")] { for (test, goal) in [(false, "compile"), (true, "test-compile")] {
// A normal launch is incremental: no `clean` (IDEA's Make, not Rebuild). // 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()) let plan = launch_plan(root, &model, &root.join("app"), test, BuildKind::Build).unwrap();
.unwrap();
let step = &plan.steps[0]; let step = &plan.steps[0];
assert_eq!(step.cwd, root); assert_eq!(step.cwd, root);
assert_eq!(step.program, "mvnw"); assert_eq!(step.program, "mvnw");
@@ -1744,9 +1390,7 @@ mod tests {
] ]
); );
// Rebuild cleans first, as IDEA's Rebuild does. // Rebuild cleans first, as IDEA's Rebuild does.
let plan = let plan = launch_plan(root, &model, &root.join("app"), test, BuildKind::Rebuild).unwrap();
launch_plan(root, &model, &root.join("app"), test, BuildKind::Rebuild, &CancellationToken::new())
.unwrap();
assert_eq!( assert_eq!(
plan.steps[0].args, plan.steps[0].args,
[ [
@@ -1766,46 +1410,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)] #[cfg(unix)]
#[test] #[test]
fn external_launch_returns_upstream_outputs_and_blocks_failure_or_cancellation() { fn external_launch_returns_upstream_outputs_and_blocks_failure_or_cancellation() {
-408
View File
@@ -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(&current));
}
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"));
}
}
+4 -84
View File
@@ -25,8 +25,6 @@ pub(crate) enum Format {
Go, Go,
/// GCC / Clang (through `cmake --build`): `src/a.cpp:12:5: error: msg`. /// GCC / Clang (through `cmake --build`): `src/a.cpp:12:5: error: msg`.
Gcc, Gcc,
/// MSBuild (`dotnet build`): `C:\p\A.cs(12,5): error CS1002: msg [C:\p\App.csproj]`.
Msbuild,
} }
/// What a printed column counts. /// What a printed column counts.
@@ -146,13 +144,6 @@ fn bracket_pos(s: &str) -> Option<(u32, Option<u32>, &str)> {
Some((line, col, rest.trim_start())) Some((line, col, rest.trim_start()))
} }
/// `/C:/p/A.java` → `C:/p/A.java`: Maven and file URIs put a `/` before the drive letter on Windows.
/// Joined as is, it would become the drive-relative `C:p/A.java`.
fn drive_path(p: &str) -> &str {
let b = p.as_bytes();
if b.len() > 2 && b[0] == b'/' && b[1].is_ascii_alphabetic() && b[2] == b':' { &p[1..] } else { p }
}
/// `file:///p/A.kt` → `/p/A.kt` (percent-decoded). /// `file:///p/A.kt` → `/p/A.kt` (percent-decoded).
fn from_file_uri(s: &str) -> String { fn from_file_uri(s: &str) -> String {
let Some(rest) = s.strip_prefix("file://") else { return s.to_owned() }; let Some(rest) = s.strip_prefix("file://") else { return s.to_owned() };
@@ -171,7 +162,9 @@ fn from_file_uri(s: &str) -> String {
out.push(bytes[i]); out.push(bytes[i]);
i += 1; i += 1;
} }
drive_path(&String::from_utf8_lossy(&out)).to_owned() let path = String::from_utf8_lossy(&out).into_owned();
// `file:///C:/x` on Windows.
if path.len() > 2 && path.as_bytes()[0] == b'/' && path.as_bytes()[2] == b':' { path[1..].to_owned() } else { path }
} }
/// Kotlin: `file:///p/A.kt:12:5 msg` or `/p/A.kt: (12, 5): msg`, after the `e: ` / `w: ` prefix. /// Kotlin: `file:///p/A.kt:12:5 msg` or `/p/A.kt: (12, 5): msg`, after the `e: ` / `w: ` prefix.
@@ -229,7 +222,7 @@ fn maven_line(line: &str) -> Option<RawMessage> {
&& looks_like_source_path(path) && looks_like_source_path(path)
&& let Some((ln, col, msg)) = bracket_pos(&format!("[{pos}")) && let Some((ln, col, msg)) = bracket_pos(&format!("[{pos}"))
{ {
return Some(RawMessage::new(severity, msg, ColUnit::Char).at(drive_path(path), ln, col)); return Some(RawMessage::new(severity, msg, ColUnit::Char).at(path, ln, col));
} }
if let Some(m) = kotlin_line(rest) { if let Some(m) = kotlin_line(rest) {
return Some(m); return Some(m);
@@ -270,43 +263,6 @@ fn tsc_line(line: &str) -> Option<RawMessage> {
Some(m) Some(m)
} }
/// MSBuild's canonical form: `path(12,5): error CS1002: msg [project]`, `path(12,5,12,9): …`,
/// or `path : error NU1101: msg [project]` for a project-level message (no position).
/// The path may contain spaces (`C:\Users\Jane Doe\…`); "error" / "warning" are never localized.
fn msbuild_line(line: &str) -> Option<RawMessage> {
let line = line.trim();
// The project the message came from, appended by the console logger.
let line = match line.rfind(" [") {
Some(i) if line.ends_with(']') => &line[..i],
_ => line,
};
let (head, severity, rest) =
[(" error ", Severity::Error), (" warning ", Severity::Warning)].into_iter().find_map(|(word, severity)| {
let i = line.find(&format!(":{word}"))?;
Some((&line[..i], severity, &line[i + word.len() + 1..]))
})?;
let (code, msg) = rest.split_once(':')?;
let code = code.trim();
if code.is_empty() || code.contains(' ') {
return None;
}
let head = head.trim_end();
let (path, pos) = match head.strip_suffix(')').and_then(|h| h.rsplit_once('(')) {
Some((path, pos)) => (path, pos.split(',').map(num).collect::<Vec<_>>()),
None => (head, Vec::new()),
};
let at = |i: usize| pos.get(i).copied().flatten();
// `MSBUILD : error MSB1009` and the like name no file.
let file = path.rsplit(['/', '\\']).next().is_some_and(|n| n.contains('.'));
let mut m = RawMessage::new(severity, msg.trim(), ColUnit::Utf16);
if file {
m.path = Some(path.trim().to_owned());
(m.line, m.col, m.end_line, m.end_col) = (at(0), at(1), at(2), at(3));
}
m.code = Some(code.to_owned());
Some(m)
}
/// go: `./a.go:12:5: msg` (errors only; `go vet` style `a.go:12: msg` too). /// go: `./a.go:12:5: msg` (errors only; `go vet` style `a.go:12: msg` too).
fn go_line(line: &str) -> Option<RawMessage> { fn go_line(line: &str) -> Option<RawMessage> {
let (path, ln, col, rest) = path_line_col(line)?; let (path, ln, col, rest) = path_line_col(line)?;
@@ -443,7 +399,6 @@ impl OutputParser {
Format::Tsc => tsc_line(&line), Format::Tsc => tsc_line(&line),
Format::Go => go_line(&line), Format::Go => go_line(&line),
Format::Gcc => gcc_line(&line), Format::Gcc => gcc_line(&line),
Format::Msbuild => msbuild_line(&line),
Format::Cargo => None, Format::Cargo => None,
}; };
if let Some(msg) = parsed { if let Some(msg) = parsed {
@@ -501,20 +456,6 @@ mod tests {
assert_eq!(out[1].unit, ColUnit::Char); assert_eq!(out[1].unit, ColUnit::Char);
} }
#[test]
fn maven_windows_paths_drop_the_slash_before_the_drive() {
let out = parse(
Format::Maven,
"[ERROR] /C:/dev/p/src/main/java/a/A.java:[18,41] package a.b does not exist\n\
[ERROR] C:\\dev\\p\\B.java:[3,8] cannot find symbol\n\
[ERROR] file:///C:/dev/p/K.kt:4:9 Unresolved reference 'x'.\n",
);
assert_eq!(out.len(), 3, "{out:?}");
assert_eq!(pos(&out[0]), (Severity::Error, "C:/dev/p/src/main/java/a/A.java", 18, Some(41)));
assert_eq!(pos(&out[1]), (Severity::Error, "C:\\dev\\p\\B.java", 3, Some(8)));
assert_eq!(pos(&out[2]), (Severity::Error, "C:/dev/p/K.kt", 4, Some(9)));
}
#[test] #[test]
fn maven_detail_lines_with_level_prefix_and_kotlin() { fn maven_detail_lines_with_level_prefix_and_kotlin() {
let out = parse( let out = parse(
@@ -591,27 +532,6 @@ mod tests {
assert!(plain.messages.is_empty() && plain.console.is_none()); assert!(plain.messages.is_empty() && plain.console.is_none());
} }
#[test]
fn msbuild_canonical_messages() {
let out = parse(
Format::Msbuild,
" Determining projects to restore...\n\
C:\\Users\\Jane Doe\\App\\Program.cs(12,5): error CS1002: ; expected [C:\\Users\\Jane Doe\\App\\App.csproj]\n\
/p/App/Models/User.cs(3,8,3,12): warning CS0168: The variable 'e' is declared but never used [/p/App/App.csproj]\n\
/p/App/App.csproj : error NU1101: Unable to find package Foo. [/p/App/App.csproj]\n\
MSBUILD : error MSB1009: Project file does not exist.\n\
Build FAILED.\n",
);
assert_eq!(out.len(), 4, "{out:?}");
assert_eq!(pos(&out[0]), (Severity::Error, "C:\\Users\\Jane Doe\\App\\Program.cs", 12, Some(5)));
assert_eq!((out[0].code.as_deref(), out[0].text.as_str()), (Some("CS1002"), "; expected"));
assert_eq!(pos(&out[1]), (Severity::Warning, "/p/App/Models/User.cs", 3, Some(8)));
assert_eq!((out[1].end_line, out[1].end_col), (Some(3), Some(12)));
assert_eq!((out[2].path.as_deref(), out[2].line), (Some("/p/App/App.csproj"), None));
assert_eq!(out[2].text, "Unable to find package Foo.");
assert_eq!((out[3].path.as_deref(), out[3].code.as_deref()), (None, Some("MSB1009")));
}
#[test] #[test]
fn tsc_plain_and_pretty() { fn tsc_plain_and_pretty() {
let out = parse( let out = parse(
+59 -236
View File
@@ -10,14 +10,11 @@ use std::process::Command as ProcCommand;
/// Output file of the `dependency:build-classpath` probe, relative to each module. /// Output file of the `dependency:build-classpath` probe, relative to each module.
const CP_FILE: &str = "target/ide-compile-cp.txt"; 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;
/// The resolved dependency classpath for one module and scope, tied to the same /// 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. /// inputs as its launch build so POM, JDK, settings and profile changes invalidate it.
#[derive(Debug, Deserialize, Serialize)] #[derive(Debug, Deserialize, Serialize)]
struct CachedClasspath { struct CachedClasspath {
version: u32,
fingerprint: LaunchFingerprint, fingerprint: LaunchFingerprint,
classpath: String, classpath: String,
} }
@@ -129,73 +126,30 @@ pub fn module_classpath(
cache: &Path, cache: &Path,
cancel: &ide_core::CancellationToken, cancel: &ide_core::CancellationToken,
) -> IdeResult<String> { ) -> IdeResult<String> {
module_classpaths(root, model, &[module.to_path_buf()], test, local_repo, cache, cancel) 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);
/// [`module_classpath`] of `modules[0]`. The other modules, launched together with it if let (Some(fingerprint), Some(path)) = (&fingerprint, &cache_path)
/// (#3971), share its Maven probe when they have no cached classpath, which leaves && let Ok(bytes) = fs::read(path)
/// theirs cached for their own launches. && let Ok(cached) = serde_json::from_slice::<CachedClasspath>(&bytes)
pub fn module_classpaths( && cached.fingerprint == *fingerprint
root: &Path, && classpath_entries_exist(root, &cached.classpath)
model: &BuildModel, {
modules: &[PathBuf], return Ok(cached.classpath);
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 scope = if test { "test" } else { "runtime" }; let classpath = classpath(root, model, &target, if test { "test" } else { "runtime" }, true)?;
let targets: Vec<&SingleFileTarget> = probes.iter().map(|p| &p.0).collect();
let classpaths = match classpaths(root, model, &targets, scope, true) {
Ok(classpaths) => classpaths,
// Another module's failure must not cost this launch its own probe.
Err(_) if targets.len() > 1 && !cancel.is_cancelled() => classpaths(root, model, &targets[..1], scope, true)?,
Err(e) => return Err(e),
};
if cancel.is_cancelled() { if cancel.is_cancelled() {
return Err(IdeError::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) {
if let (Some(fingerprint), Some(path)) = (fingerprint, cache_path) { let cached = CachedClasspath { fingerprint, classpath: classpath.clone() };
let cached = if let Err(error) = cache_classpath(&path, &cached) {
CachedClasspath { version: CLASSPATH_CACHE_VERSION, fingerprint, classpath: classpath.clone() }; tracing::debug!(path = %path.display(), %error, "Cannot cache the Java launch classpath");
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 /// One cache file per module and scope. Mirroring the module path keeps nested
/// modules and their different dependency scopes from overwriting each other. /// modules and their different dependency scopes from overwriting each other.
fn classpath_cache_path(root: &Path, cache: &Path, module: &Path, test: bool) -> Option<PathBuf> { fn classpath_cache_path(root: &Path, cache: &Path, module: &Path, test: bool) -> Option<PathBuf> {
@@ -237,62 +191,6 @@ fn classpath(
scope: &str, scope: &str,
compile_first: bool, compile_first: bool,
) -> IdeResult<String> { ) -> IdeResult<String> {
Ok(classpaths(root, model, &[target], scope, compile_first)?.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,
) -> IdeResult<Vec<String>> {
let top = &targets[0].top;
let probe = CP_FILE;
let mut args = vec!["-B", "-Dstyle.color=never", maven::LOCAL_REPO_TRACKING_ARG];
args.extend(top.options.iter().map(String::as_str));
// The reactor root among them builds every module.
let selection = if targets.iter().any(|t| t.pl.is_empty()) {
String::new()
} else {
let mut pl: Vec<&str> = targets.iter().map(|t| t.pl.as_str()).collect();
pl.sort();
pl.dedup();
pl.join(",")
};
if !selection.is_empty() {
args.extend(["-pl", selection.as_str(), "-am"]);
}
let output_arg = format!("-Dmdep.outputFile={probe}");
let scope_arg = format!("-Dmdep.includeScope={scope}");
// A launch build may only have reached `compile`. Running `compile` in this
// same Maven session lets the dependency plugin resolve Reactor siblings from
// their target/classes without paying for package-phase plugins.
if compile_first {
args.push("compile");
}
args.extend(["dependency:build-classpath", output_arg.as_str(), scope_arg.as_str(), "-q"]);
let top_dir = subdir(root, &top.dir);
let mut command = ProcCommand::new(&top.command);
command.args(&args).envs(&top.env).current_dir(&top_dir);
let status = ide_core::process::prepare(&mut command)
.output()
.map_err(|e| IdeError::internal(format!("cannot resolve the compile classpath: {e}")))?;
if !status.status.success() {
let stdout = String::from_utf8_lossy(&status.stdout);
let stderr = String::from_utf8_lossy(&status.stderr);
// 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}")));
}
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(); let mut entries: Vec<String> = Vec::new();
// The module's own classes first: the file almost always uses classes next to it. // 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"] }; let own: &[&str] = if target.test { &["target/test-classes", "target/classes"] } else { &["target/classes"] };
@@ -310,16 +208,46 @@ fn target_classpath(root: &Path, model: &BuildModel, target: &SingleFileTarget)
if dir == target.module { if dir == target.module {
continue; continue;
} }
// A dependency's tests are not exported with its main artifact. Any explicitly for classes in ["target/classes", "target/test-classes"] {
// declared test artifact is supplied by Maven's resolved classpath below. let path = dir.join(classes);
let path = dir.join("target/classes"); if path.is_dir() {
if path.is_dir() { entries.push(path.to_string_lossy().into_owned());
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. // 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| { let content = fs::read_to_string(&cp_file).map_err(|e| {
IdeError::internal(format!("cannot resolve the compile classpath: {} ({e})", cp_file.display())) IdeError::internal(format!("cannot resolve the compile classpath: {} ({e})", cp_file.display()))
})?; })?;
@@ -409,19 +337,13 @@ mod tests {
root, root,
"pom.xml", "pom.xml",
r#"<project><groupId>demo</groupId><artifactId>parent</artifactId><version>1</version> 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( write(
root, root,
"lib/pom.xml", "lib/pom.xml",
r#"<project><parent><groupId>demo</groupId><artifactId>parent</artifactId><version>1</version></parent> 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>"#, <artifactId>lib</artifactId></project>"#,
);
write(
root,
"shared/pom.xml",
r#"<project><parent><groupId>demo</groupId><artifactId>parent</artifactId><version>1</version></parent>
<artifactId>shared</artifactId></project>"#,
); );
write( write(
root, root,
@@ -432,7 +354,6 @@ mod tests {
write(root, "app/src/main/java/demo/Main.java", "class Main {}"); write(root, "app/src/main/java/demo/Main.java", "class Main {}");
write(root, "app/src/test/java/demo/MainTest.java", "class MainTest {}"); write(root, "app/src/test/java/demo/MainTest.java", "class MainTest {}");
write(root, "lib/target/classes/Lib.class", "built"); write(root, "lib/target/classes/Lib.class", "built");
write(root, "shared/target/classes/Shared.class", "built");
crate::load(root, &root.join("cache"), None) crate::load(root, &root.join("cache"), None)
} }
@@ -515,9 +436,7 @@ mod tests {
let target = single_file_target(root, &model, &file).unwrap(); let target = single_file_target(root, &model, &file).unwrap();
assert!(target.top.command.ends_with("mvnw")); assert!(target.top.command.ends_with("mvnw"));
assert_eq!(target.pl, "app"); 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(); 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 = ':'; let separator = ':';
// Reactor class directories first, so fresh outputs shadow installed snapshots. // Reactor class directories first, so fresh outputs shadow installed snapshots.
let lib = root.join("lib/target/classes").to_string_lossy().into_owned(); let lib = root.join("lib/target/classes").to_string_lossy().into_owned();
@@ -532,16 +451,9 @@ mod tests {
assert!(cp.split(separator).count() >= 3, "{cp}"); assert!(cp.split(separator).count() >= 3, "{cp}");
let args = fs::read_to_string(root.join("args.txt")).unwrap(); 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 == "compile" || a == "package"), "{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}");
} }
/// 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)] #[cfg(unix)]
#[test] #[test]
fn launch_module_classpath_uses_the_matching_dependency_scope() { fn launch_module_classpath_uses_the_matching_dependency_scope() {
@@ -553,29 +465,15 @@ mod tests {
let script = root.join("mvnw"); let script = root.join("mvnw");
fs::write( fs::write(
&script, &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(); .unwrap();
fs::set_permissions(&script, fs::Permissions::from_mode(0o755)).unwrap(); fs::set_permissions(&script, fs::Permissions::from_mode(0o755)).unwrap();
let model = crate::load(root, &root.join("cache"), None); 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 cache = root.join("cache");
let runtime = let runtime =
module_classpath(root, &model, &root.join("app"), false, None, &cache, &CancellationToken::new()).unwrap(); 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}"); assert!(runtime.contains("/repo/runtime.jar"), "{runtime}");
let args = fs::read_to_string(root.join("args.txt")).unwrap(); let args = fs::read_to_string(root.join("args.txt")).unwrap();
assert!(args.lines().any(|a| a == "compile"), "{args}"); assert!(args.lines().any(|a| a == "compile"), "{args}");
@@ -584,65 +482,16 @@ mod tests {
let test = let test =
module_classpath(root, &model, &root.join("app"), true, None, &cache, &CancellationToken::new()).unwrap(); module_classpath(root, &model, &root.join("app"), true, None, &cache, &CancellationToken::new()).unwrap();
assert!(test.contains("/repo/fixture-tests.jar"), "{test}"); assert!(test.contains("/repo/test.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}");
let args = fs::read_to_string(root.join("args.txt")).unwrap(); let args = fs::read_to_string(root.join("args.txt")).unwrap();
assert!(args.lines().any(|a| a == "-Dmdep.includeScope=test"), "{args}"); 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 = dir.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 /// The launch classpath follows the Maven runner JDK and is reused until that
/// build input changes; the probe does not run packaging plugins. /// build input changes; the probe does not run packaging plugins.
#[cfg(unix)] #[cfg(unix)]
#[test] #[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; use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().unwrap(); let dir = tempfile::tempdir().unwrap();
@@ -664,7 +513,6 @@ mod tests {
fs::write(home.join("release"), format!("JAVA_VERSION=\"{version}\"\n")).unwrap(); fs::write(home.join("release"), format!("JAVA_VERSION=\"{version}\"\n")).unwrap();
fs::write(home.join("bin/java"), "").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 cache = root.join("classpath-cache");
let cancel = CancellationToken::new(); let cancel = CancellationToken::new();
let jdk21 = root.join("jdk21"); let jdk21 = root.join("jdk21");
@@ -678,30 +526,6 @@ mod tests {
assert_eq!(second, first); assert_eq!(second, first);
assert_eq!(fs::read_to_string(root.join("calls.txt")).unwrap(), "x"); 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"); let jdk8 = root.join("jdk8");
for project in &mut model.maven.as_mut().unwrap().projects { for project in &mut model.maven.as_mut().unwrap().projects {
project.env.insert("JAVA_HOME".into(), jdk8.to_string_lossy().into_owned()); project.env.insert("JAVA_HOME".into(), jdk8.to_string_lossy().into_owned());
@@ -709,7 +533,6 @@ mod tests {
let switched = module_classpath(root, &model, &root.join("app"), false, None, &cache, &cancel).unwrap(); 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("jdk8/classpath/jdk.jar"), "{switched}");
assert!(!switched.contains("jdk21/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(), "xx");
assert_eq!(fs::read_to_string(root.join("calls.txt")).unwrap(), calls);
} }
} }
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -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 /// Re-stamps files whose content changed without advancing mtime (git
/// checkout, external sync): timestamp-incremental Maven would otherwise skip /// checkout, external sync): timestamp-incremental Maven would otherwise skip
/// them as "unchanged" and the rebuild would compile nothing. /// 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(); let now = std::time::SystemTime::now();
for rel in edits { for rel in edits {
let path = root.join(rel); let path = root.join(rel);
+3 -8
View File
@@ -30,9 +30,7 @@ def processedResources = { Project p, s ->
def describe = { Project p -> def describe = { Project p ->
def m = [path: identity(p), dir: canon(p.projectDir), buildDir: canon(p.layout.buildDirectory.get().asFile)] 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) if (p.gradle.parent != null) m.build = identity(p.rootProject)
m.resolvableConfigurations = p.configurations.findAll { it.canBeResolved }.collect { it.name }.sort() def sets = p.extensions.findByName('sourceSets')
// Gradle 4.x has it as a convention property, not an extension.
def sets = p.extensions.findByName('sourceSets') ?: p.findProperty('sourceSets')
if (sets != null) { if (sets != null) {
// Test source sets as IDEA classifies them: `test`, test fixtures, JVM test suites, // Test source sets as IDEA classifies them: `test`, test fixtures, JVM test suites,
// and sets whose folders the `idea` plugin lists as test sources. // and sets whose folders the `idea` plugin lists as test sources.
@@ -53,12 +51,9 @@ def describe = { Project p ->
} }
} }
try { try {
// `java` is Gradle 4.10+ (a convention before), its toolchain 6.7+.
def java = p.extensions.findByName('java') def java = p.extensions.findByName('java')
def lv = null def lv = java?.toolchain?.languageVersion?.getOrNull()
try { lv = java?.toolchain?.languageVersion?.getOrNull() } catch (ignored) {} m.java = lv != null ? lv.asInt() : (java?.targetCompatibility?.majorVersion as Integer)
def target = java != null ? java.targetCompatibility : p.findProperty('targetCompatibility')
m.java = lv != null ? lv.asInt() : (target?.majorVersion as Integer)
} catch (ignored) {} } catch (ignored) {}
println '@openidea-model\t' + JsonOutput.toJson(m) println '@openidea-model\t' + JsonOutput.toJson(m)
} }
+1 -20
View File
@@ -41,10 +41,6 @@ pub struct GradleProject {
/// Project-relative build script, if any. /// Project-relative build script, if any.
pub build_file: Option<String>, pub build_file: Option<String>,
pub tasks: Vec<GradleTask>, 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`, /// Identity path of the nested build holding the project (`:lib` for `includeBuild`,
/// `:buildSrc`); null for the opened build. /// `:buildSrc`); null for the opened build.
#[serde(default)] #[serde(default)]
@@ -305,7 +301,6 @@ fn project_at(root: &Path, path: String, name: String, pdir: &Path) -> GradlePro
path, path,
name, name,
tasks, tasks,
resolvable_configurations: None,
build: None, build: None,
} }
} }
@@ -322,8 +317,6 @@ pub struct ReportedProject {
pub build_dir: Option<String>, pub build_dir: Option<String>,
#[serde(default)] #[serde(default)]
pub source_sets: Vec<ReportedSourceSet>, pub source_sets: Vec<ReportedSourceSet>,
#[serde(default)]
pub resolvable_configurations: Option<Vec<String>>,
/// Toolchain language version, else target compatibility. /// Toolchain language version, else target compatibility.
#[serde(default)] #[serde(default)]
pub java: Option<u32>, 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")) { if p.build.as_deref().is_some_and(|b| b.ends_with(":buildSrc")) {
project.tasks.clear(); project.tasks.clear();
} }
project.resolvable_configurations = p.resolvable_configurations.clone();
project.build = p.build.clone(); project.build = p.build.clone();
project project
}) })
@@ -1471,7 +1463,7 @@ dependencies {
model.projects.push(project); model.projects.push(project);
} }
assert!(build_files(root, &model).contains(&root.join("included/deps.gradle"))); assert!(build_files(root, &model).contains(&root.join("included/deps.gradle")));
let model = crate::BuildModel { maven: None, gradle: vec![model], sbt: Vec::new() }; let model = crate::BuildModel { maven: None, gradle: vec![model] };
assert_eq!(crate::dependency_coordinates(root, &model)[0].artifact_id, "included"); assert_eq!(crate::dependency_coordinates(root, &model)[0].artifact_id, "included");
} }
@@ -1638,11 +1630,6 @@ Pattern: clean<TaskName>: Cleans the output files of a task.
path: path.into(), path: path.into(),
dir: ws.join(d).to_string_lossy().into_owned(), dir: ws.join(d).to_string_lossy().into_owned(),
build: build.map(Into::into), build: build.map(Into::into),
resolvable_configurations: match path {
":" => Some(vec!["reviewTools".into(), "runtimeClasspath".into()]),
":lib:core" => Some(Vec::new()),
_ => None,
},
..ReportedProject::default() ..ReportedProject::default()
}; };
format!("{MODEL_LINE}{}\n", serde_json::to_string(&project).unwrap()) 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]; let build_src = &model.projects[2];
assert!(build_src.tasks.is_empty(), "buildSrc tasks cannot run from the root build"); 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!(!model.projects[4].tasks.is_empty());
assert!(build_files(&root, &model).contains(&ws.join("lib/settings.gradle"))); assert!(build_files(&root, &model).contains(&ws.join("lib/settings.gradle")));
} }
+6 -91
View File
@@ -1,16 +1,13 @@
//! A Gradle project's resolved dependencies for the Dependency Analyzer: //! A Gradle project's resolved dependencies for the Dependency Analyzer:
//! `gradle <project>:dependencies --configuration <name>`, parsed from its tree report. //! `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::gradle;
use crate::process; use crate::process;
use crate::sync::{self, SyncOptions, error_summary}; use crate::sync::{SyncOptions, error_summary};
use ide_core::{CancellationToken, IdeError, IdeResult}; use ide_core::{CancellationToken, IdeError, IdeResult};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use specta::Type; use specta::Type;
use std::path::Path; use std::path::Path;
use std::sync::Mutex;
/// One line of the report: an occurrence of a dependency where it is requested. /// One line of the report: an occurrence of a dependency where it is requested.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)] #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
@@ -135,7 +132,7 @@ pub fn gradle_dependencies(
configuration: &str, configuration: &str,
cancel: &CancellationToken, cancel: &CancellationToken,
) -> IdeResult<Vec<GradleDependency>> { ) -> 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}"))); return Err(IdeError::invalid(format!("not a configuration name: {configuration}")));
} }
if !project.starts_with(':') || project.chars().any(char::is_whitespace) { 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 task = if project == ":" { ":dependencies".to_owned() } else { format!("{project}:dependencies") };
let mut args: Vec<String> = 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 { if options.offline {
args.push("--offline".into()); args.push("--offline".into());
} }
@@ -156,62 +153,11 @@ pub fn gradle_dependencies(
|_, _| {}, |_, _| {},
)?; )?;
if !out.success { if !out.success {
return Err(IdeError::unavailable(error_summary(&out))); return Err(IdeError::unavailable(error_summary(&out.text)));
}
if let Some(note) = sync::truncation_note(&out) {
return Err(IdeError::unavailable(note));
} }
Ok(parse_report(&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)] #[cfg(test)]
mod tests { mod tests {
use super::*; 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)] #[cfg(unix)]
#[test] #[test]
fn runs_the_report_of_the_project_and_configuration() { fn runs_the_report_of_the_project_and_configuration() {
@@ -340,14 +255,14 @@ runtimeClasspath - Runtime classpath of source set 'main'.
&gradle::load(root).unwrap(), &gradle::load(root).unwrap(),
&options, &options,
":app", ":app",
"review.tools", "testRuntimeClasspath",
&CancellationToken::new(), &CancellationToken::new(),
) )
.unwrap(); .unwrap();
assert_eq!(tree, vec![dep("org.a", "b", Some("1.0"))]); assert_eq!(tree, vec![dep("org.a", "b", Some("1.0"))]);
assert_eq!( assert_eq!(
std::fs::read_to_string(root.join("args")).unwrap().trim(), 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"
); );
} }
} }
+5 -5
View File
@@ -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()) { if model.maven.as_ref().is_none_or(|m| m.projects.is_empty()) {
return Err(IdeError::invalid("Kotlin bridge requires a Maven build root")); return Err(IdeError::invalid("Kotlin bridge requires a Maven build root"));
} }
Ok(compile::BuildPlan { Ok(compile::BuildPlan {
system: compile::BuildSystem::Maven, system: compile::BuildSystem::Maven,
title: root.file_name().unwrap_or_default().to_string_lossy().into_owned(), 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, cancel: &CancellationToken,
) -> IdeResult<Outcome> { ) -> IdeResult<Outcome> {
std::fs::create_dir_all(generation)?; std::fs::create_dir_all(generation)?;
let mut plan = plan(root, model, cancel)?; let mut plan = plan(root, model)?;
let mut manifests = Vec::new(); let mut manifests = Vec::new();
for (index, step) in plan.steps.iter_mut().enumerate() { for (index, step) in plan.steps.iter_mut().enumerate() {
step.args.push("--fail-at-end".into()); step.args.push("--fail-at-end".into());
@@ -522,7 +522,7 @@ mod tests {
} }
std::fs::write(root.join("kotlin/App.kt"), "class App").unwrap(); std::fs::write(root.join("kotlin/App.kt"), "class App").unwrap();
assert!(has_kotlin(root, &model), "{marker}"); 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.system, compile::BuildSystem::Maven);
assert_eq!(plan.steps.len(), 2); assert_eq!(plan.steps.len(), 2);
for (step, name) in plan.steps.iter().zip(["java", "kotlin"]) { for (step, name) in plan.steps.iter().zip(["java", "kotlin"]) {
@@ -562,7 +562,7 @@ mod tests {
..Default::default() ..Default::default()
}; };
assert!(has_kotlin(workspace.path(), &model)); 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] #[test]
+12 -97
View File
@@ -1,4 +1,4 @@
//! Build tool models for the Maven, Gradle and sbt tool windows, and Build › Build //! Build tool models for the Maven and Gradle tool windows, and Build › Build
//! Project ([`compile`]) for Maven, Gradle, Cargo, Go and TypeScript projects. //! Project ([`compile`]) for Maven, Gradle, Cargo, Go and TypeScript projects.
//! //!
//! [`load`] reads the project's build files (instant, no build tool involved) //! [`load`] reads the project's build files (instant, no build tool involved)
@@ -13,20 +13,15 @@ pub mod kotlin_bridge;
pub mod maven; pub mod maven;
pub mod pom_edit; pub mod pom_edit;
mod process; mod process;
#[cfg(test)]
mod process_numbers;
pub mod sbt;
mod sync; mod sync;
pub mod web; pub mod web;
mod xml; mod xml;
pub use gradle::{GradleModel, GradleProject, GradleTask}; 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 maven::{MavenDependency, MavenModel, MavenPlugin, MavenProfile, MavenProject, Omission};
pub use sbt::{SbtBuild, SbtProject};
pub use sync::{ pub use sync::{
SyncOptions, SyncProgress, maven_offline, maven_profiles, save_maven_offline, save_maven_profiles, sync_gradle, SyncOptions, SyncProgress, maven_profiles, save_maven_profiles, sync_gradle, sync_gradle_model, sync_maven,
sync_gradle_model, sync_maven,
}; };
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
@@ -47,9 +42,6 @@ pub struct BuildModel {
pub maven: Option<MavenModel>, pub maven: Option<MavenModel>,
#[serde(default)] #[serde(default)]
pub gradle: Vec<GradleModel>, pub gradle: Vec<GradleModel>,
/// sbt builds, read from their `build.sbt` (sbt is not started).
#[serde(default)]
pub sbt: Vec<SbtBuild>,
} }
impl BuildModel { impl BuildModel {
@@ -82,23 +74,11 @@ pub fn load_linked(
maven_repo: Option<PathBuf>, maven_repo: Option<PathBuf>,
settings: &ide_core::settings::MavenSettings, settings: &ide_core::settings::MavenSettings,
gradle_settings: &ide_core::settings::GradleSettings, 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 { ) -> BuildModel {
let maven = maven::has_projects(root, settings).then(|| { let maven = maven::has_projects(root, settings).then(|| {
let profiles = settings.profiles(&sync::maven_profiles(cache_dir)); let profiles = settings.profiles(&sync::maven_profiles(cache_dir));
let repo = maven_repo.or_else(maven::default_local_repo); 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); maven::UnlinkedProjects::from_model(&m, settings).filter(&mut m);
// The user settings' profiles can be chosen too (`-P` applies to them as well). // 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() { for p in maven::user_settings_file(root, settings).map(|f| maven::settings_profiles(&f)).unwrap_or_default() {
@@ -116,7 +96,7 @@ pub fn load_linked_with_jdk(
g g
}) })
.collect(); .collect();
BuildModel { maven, gradle, sbt: sbt::load(root) } BuildModel { maven, gradle }
} }
/// Gradle project folders outside `root` as of the last sync (`includeFlat` siblings): /// Gradle project folders outside `root` as of the last sync (`includeFlat` siblings):
@@ -142,22 +122,10 @@ pub fn gradle_external_roots(
gradle::external_roots(root, dirs.iter().map(String::as_str)) gradle::external_roots(root, dirs.iter().map(String::as_str))
} }
/// Directories outside `root`, outermost only, of Maven POMs linked from there and, in a /// Directories of Maven POMs linked from outside `root`, outermost only.
/// trusted project, of the modules its reactor lists there (`<module>../service-a</module>`): /// Reads just those explicit paths (no POM parse and no directory walk).
/// extra content roots, as IDEA imports such modules with content roots of their own. pub fn maven_external_roots(root: &Path, linked: &[String]) -> Vec<PathBuf> {
/// Linked POMs are read as explicit paths; the reactor's POMs are parsed, but not their let dirs = maven::external_pom_dirs(root, linked);
/// 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));
}
let owned: Vec<String> = dirs.iter().map(|dir| dir.to_string_lossy().into_owned()).collect(); 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)) gradle::external_roots(root, owned.iter().map(String::as_str))
} }
@@ -278,59 +246,6 @@ mod tests {
assert!(gradle_external_roots(&root, &temp.path().join("cache"), &settings).is_empty()); 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] #[test]
fn settings_profiles_and_checkbox_choices_control_modules_before_sync() { fn settings_profiles_and_checkbox_choices_control_modules_before_sync() {
let tmp = tempfile::tempdir().unwrap(); let tmp = tempfile::tempdir().unwrap();
@@ -414,7 +329,7 @@ mod tests {
..Default::default() ..Default::default()
}; };
let gradle = gradle::load(root).into_iter().collect(); let gradle = gradle::load(root).into_iter().collect();
let model = BuildModel { maven: Some(maven), gradle, sbt: Vec::new() }; let model = BuildModel { maven: Some(maven), gradle };
let names: Vec<String> = dependency_coordinates(root, &model) let names: Vec<String> = dependency_coordinates(root, &model)
.into_iter() .into_iter()
.map(|c| format!("{}{}:{}:{}", if c.gradle { "G " } else { "M " }, c.group_id, c.artifact_id, c.version)) .map(|c| format!("{}{}:{}:{}", if c.gradle { "G " } else { "M " }, c.group_id, c.artifact_id, c.version))
@@ -433,7 +348,7 @@ mod tests {
"ext { gson = '2.8.9' }\ndependencies { implementation \"com.google.code.gson:gson:${gson}\" }\n", "ext { gson = '2.8.9' }\ndependencies { implementation \"com.google.code.gson:gson:${gson}\" }\n",
) )
.unwrap(); .unwrap();
let model = BuildModel { maven: None, gradle: gradle::load(root).into_iter().collect(), sbt: Vec::new() }; let model = BuildModel { maven: None, gradle: gradle::load(root).into_iter().collect() };
let names: Vec<String> = dependency_coordinates(root, &model) let names: Vec<String> = dependency_coordinates(root, &model)
.into_iter() .into_iter()
.map(|c| format!("{}:{}:{}", c.group_id, c.artifact_id, c.version)) .map(|c| format!("{}:{}:{}", c.group_id, c.artifact_id, c.version))
@@ -452,7 +367,7 @@ mod tests {
) )
.unwrap(); .unwrap();
std::fs::write(root.join("gradle.properties"), "# versions\nv = 1.2\nonlyInProperties: 2.3\n").unwrap(); std::fs::write(root.join("gradle.properties"), "# versions\nv = 1.2\nonlyInProperties: 2.3\n").unwrap();
let model = BuildModel { maven: None, gradle: gradle::load(root).into_iter().collect(), sbt: Vec::new() }; let model = BuildModel { maven: None, gradle: gradle::load(root).into_iter().collect() };
let versions: Vec<_> = dependency_coordinates(root, &model).into_iter().map(|c| c.version).collect(); let versions: Vec<_> = dependency_coordinates(root, &model).into_iter().map(|c| c.version).collect();
assert_eq!(versions, ["1.2", "2.3"]); assert_eq!(versions, ["1.2", "2.3"]);
} }
File diff suppressed because it is too large. Load diff
+13 -263
View File
@@ -3,13 +3,7 @@
use super::MavenProject; use super::MavenProject;
use crate::process; use crate::process;
use ide_core::{CancellationToken, IdeError, IdeResult}; use ide_core::{CancellationToken, IdeError, IdeResult};
use std::collections::HashSet;
use std::fs::{self, File};
use std::path::{Component, Path, PathBuf}; 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)] #[derive(Debug, PartialEq, Eq)]
pub struct Artifact { pub struct Artifact {
@@ -17,29 +11,6 @@ pub struct Artifact {
pub name: String, pub name: String,
pub version: String, pub version: String,
pub sources: PathBuf, 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. /// 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 n = parts.len();
let (name, version, file) = (parts[n - 3], parts[n - 2], parts[n - 1]); 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; return None;
} }
Some(Artifact { Some(Artifact {
group: parts[..n - 3].join("."), group: parts[..n - 3].join("."),
name: name.into(), name: name.into(),
version: version.into(), version: version.into(),
binary: jar.to_owned(),
sources: jar.with_file_name(format!("{name}-{version}-sources.jar")), sources: jar.with_file_name(format!("{name}-{version}-sources.jar")),
}) })
} }
@@ -75,58 +48,26 @@ pub fn download(
artifact: &Artifact, artifact: &Artifact,
repository: &Path, repository: &Path,
cancel: &CancellationToken, 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>> { ) -> IdeResult<Option<PathBuf>> {
if cancel.is_cancelled() { if cancel.is_cancelled() {
return Err(IdeError::cancelled()); return Err(IdeError::cancelled());
} }
if stale.is_none() && artifact.sources.is_file() { if artifact.sources.is_file() {
return Ok(Some(artifact.sources.clone())); return Ok(Some(artifact.sources.clone()));
} }
let mut args = vec!["-B".into(), "-N".into(), "-Dstyle.color=never".into()]; let mut args = vec!["-B".into(), "-N".into(), "-Dstyle.color=never".into()];
args.extend(project.options.iter().cloned()); args.extend(project.options.clone());
args.extend(profile_args.iter().cloned()); args.extend([
args.push(format!("-Dmaven.repo.local={}", repository.display())); format!("-Dmaven.repo.local={}", repository.display()),
let coordinate = format!("-Dartifact={}:{}:{}:jar:sources", artifact.group, artifact.name, artifact.version); "org.apache.maven.plugins:maven-dependency-plugin:3.8.1:get".into(),
let stage = if let Some(binary) = stale { format!("-Dartifact={}:{}:{}:jar:sources", artifact.group, artifact.name, artifact.version),
// Keep the existing attachment readable while Maven resolves the timestamped snapshot. "-Dtransitive=false".into(),
// 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
};
let output = process::run(&project.command, &args, &root.join(&project.dir), &project.env, cancel, |_, _| {})?; let output = process::run(&project.command, &args, &root.join(&project.dir), &project.env, cancel, |_, _| {})?;
if cancel.is_cancelled() { if cancel.is_cancelled() {
return Err(IdeError::cancelled()); return Err(IdeError::cancelled());
} }
if let Some((stage, binary)) = stage { if artifact.sources.is_file() {
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() {
return Ok(Some(artifact.sources.clone())); return Ok(Some(artifact.sources.clone()));
} }
let coordinate = format!("{}:{}:jar:sources:{}", artifact.group, artifact.name, artifact.version); 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)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
@@ -289,86 +121,4 @@ mod tests {
assert_eq!(artifact(Path::new(path), repository), None, "{path}"); 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
View File
@@ -17,94 +17,16 @@ pub(crate) enum Stream {
Stderr, 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(crate) struct Output {
pub success: bool, 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, 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 /// `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 /// 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` /// app's own `PATH` can be minimal and `Command` would not see `mvn` there.
/// of the project holding `cwd` (its direnv `.envrc`) comes first. pub(crate) fn program_path(program: &str, env: &BTreeMap<String, String>) -> std::path::PathBuf {
pub(crate) fn program_path(program: &str, env: &BTreeMap<String, String>, cwd: &Path) -> std::path::PathBuf {
let path = std::path::Path::new(program); let path = std::path::Path::new(program);
if !path.is_relative() || path.components().count() > 1 { if !path.is_relative() || path.components().count() > 1 {
return path.to_path_buf(); return path.to_path_buf();
@@ -113,13 +35,12 @@ pub(crate) fn program_path(program: &str, env: &BTreeMap<String, String>, cwd: &
.iter() .iter()
.find(|(k, _)| k.eq_ignore_ascii_case("PATH")) .find(|(k, _)| k.eq_ignore_ascii_case("PATH"))
.map(|(_, v)| std::ffi::OsString::from(v)) .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()) 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 /// Runs `program args` in `cwd`, feeding each output line to `on_line`; kills
/// the process group and returns `cancelled` when `cancel` fires. `Output.text` /// the process group and returns `cancelled` when `cancel` fires.
/// keeps every line: callers that parse a complete model from it use this.
pub(crate) fn run( pub(crate) fn run(
program: &str, program: &str,
args: &[String], args: &[String],
@@ -131,20 +52,6 @@ pub(crate) fn run(
run_with_env(program, args, cwd, env, false, cancel, on_line) 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( pub(crate) fn run_with_env(
program: &str, program: &str,
args: &[String], args: &[String],
@@ -152,39 +59,14 @@ pub(crate) fn run_with_env(
env: &BTreeMap<String, String>, env: &BTreeMap<String, String>,
clear_env: bool, clear_env: bool,
cancel: &CancellationToken, 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), mut on_line: impl FnMut(Stream, &str),
) -> IdeResult<Output> { ) -> IdeResult<Output> {
let RunOptions { clear_env, bounded } = options;
tracing::info!("build: {program} {} (in {})", args.join(" "), cwd.display()); 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`). // Output is read as UTF-8: JVMs on Windows are told to write it (see `ide_core::output_encoding`).
let encoding = let encoding =
ide_core::output_encoding::fix(program, args, env, |k| std::env::var(k).ok(), "UTF-8", cfg!(windows)); 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 program = program_path(program, env);
let mut command = if ide_core::process::needs_sh(&program) { let mut command = Command::new(&program);
let mut sh = Command::new("/bin/sh");
sh.arg(&program);
sh
} else {
Command::new(&program)
};
command.args(args).current_dir(cwd).envs(env).envs(encoding.env.iter().map(|(k, v)| (k, v))).stdin(Stdio::null()); 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()); command.stdout(Stdio::piped()).stderr(Stdio::piped());
// Its own group: `mvnw` / `gradlew` start the JVM as a child, and cancelling kills both. // 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 = let mut child =
command.spawn().map_err(|e| IdeError::unavailable(format!("cannot start {}: {e}", program.display())))?; command.spawn().map_err(|e| IdeError::unavailable(format!("cannot start {}: {e}", program.display())))?;
let (tx, rx) = line_queue(); let (tx, rx) = mpsc::channel::<(Stream, String)>();
let pump = |stream: Box<dyn Read + Send>, kind: Stream, tx: mpsc::SyncSender<Line>| { let pump = |stream: Box<dyn Read + Send>, kind: Stream, tx: mpsc::Sender<(Stream, String)>| {
std::thread::spawn(move || { std::thread::spawn(move || {
if bounded { let mut reader = BufReader::new(stream);
pump_bounded(stream, kind, &tx); let mut buf = Vec::new();
} else { loop {
// Model listings are parsed from Output.text: keep every line whole, however long. buf.clear();
let mut reader = BufReader::new(stream); match reader.read_until(b'\n', &mut buf) {
let mut buf = Vec::new(); Ok(0) | Err(_) => break,
loop { Ok(_) => {
buf.clear(); let line = ide_core::output_encoding::decode_tool_output(&buf);
match reader.read_until(b'\n', &mut buf) { let line = line.trim_end_matches(['\n', '\r']).to_owned();
Ok(0) | Err(_) => break, if tx.send((kind, line)).is_err() {
Ok(_) => { break;
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())), child.stderr.take().map(|s| pump(Box::new(s), Stream::Stderr, tx.clone())),
]; ];
drop(tx); drop(tx);
// Retained copy of the output: the first half of the cap, then — once output overflows — let mut text = String::new();
// 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;
loop { loop {
if cancel.is_cancelled() { if cancel.is_cancelled() {
kill_tree(&mut child); kill_tree(&mut child);
@@ -245,34 +111,8 @@ fn run_with_env_capture(
Ok((_, line)) if encoding.notice.as_ref() == Some(&line) => {} Ok((_, line)) if encoding.notice.as_ref() == Some(&line) => {}
Ok((stream, line)) => { Ok((stream, line)) => {
on_line(stream, &line); on_line(stream, &line);
if !bounded { text.push_str(&line);
// The caller parses a complete model from `text`, so keep every line. text.push('\n');
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();
}
}
} }
Err(mpsc::RecvTimeoutError::Timeout) => {} Err(mpsc::RecvTimeoutError::Timeout) => {}
Err(mpsc::RecvTimeoutError::Disconnected) => break, Err(mpsc::RecvTimeoutError::Disconnected) => break,
@@ -282,87 +122,12 @@ fn run_with_env_capture(
let _ = r.join(); let _ = r.join();
} }
let status = child.wait()?; let status = child.wait()?;
let mut text = head; Ok(Output { success: status.success(), text })
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 })
} }
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; 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] #[test]
fn runs_and_cancels_processes() { fn runs_and_cancels_processes() {
@@ -382,11 +147,10 @@ mod tests {
) )
.unwrap(); .unwrap();
assert!(!out.success); assert!(!out.success);
assert!(!out.truncated);
lines.sort_by(|a, b| a.1.cmp(&b.1)); lines.sort_by(|a, b| a.1.cmp(&b.1));
assert_eq!(lines, [(Stream::Stdout, "one".to_owned()), (Stream::Stderr, "two".to_owned())]); assert_eq!(lines, [(Stream::Stdout, "one".to_owned()), (Stream::Stderr, "two".to_owned())]);
cancel.cancel(); 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() .err()
.unwrap(); .unwrap();
assert_eq!(err.kind, ide_core::error::ErrorKind::Cancelled); assert_eq!(err.kind, ide_core::error::ErrorKind::Cancelled);
@@ -406,237 +170,9 @@ mod tests {
std::thread::sleep(Duration::from_millis(200)); std::thread::sleep(Duration::from_millis(200));
c.cancel(); c.cancel();
}); });
let err = let err = run("sh", &["-c".into(), script], tmp.path(), &BTreeMap::new(), &cancel, |_, _| {}).err().unwrap();
run_bounded("sh", &["-c".into(), script], tmp.path(), &BTreeMap::new(), &cancel, |_, _| {}).err().unwrap();
assert_eq!(err.kind, ide_core::error::ErrorKind::Cancelled); assert_eq!(err.kind, ide_core::error::ErrorKind::Cancelled);
std::thread::sleep(Duration::from_millis(1300)); std::thread::sleep(Duration::from_millis(1300));
assert!(!marker.exists(), "the background child must be killed with the group"); 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");
}
}
} }
-36
View File
@@ -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()
);
}
-301
View File
@@ -1,301 +0,0 @@
//! sbt builds for the sbt tool window: each `build.sbt` build under the project root
//! with the projects its definition declares (`lazy val core = project`,
//! `(project in file("core"))`, `Project("core", file("core"))`), read statically —
//! sbt itself is not started.
use serde::{Deserialize, Serialize};
use specta::Type;
use std::path::Path;
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct SbtBuild {
/// Folder of `build.sbt`, relative to the project root (`""` for the root itself).
pub dir: String,
/// The launcher: a `sbt` / `sbtx` script in the build folder, else `sbt` on `PATH`.
pub command: String,
/// `sbt.version` of `project/build.properties`.
pub version: Option<String>,
/// The root project first, then the declared projects in source order.
pub projects: Vec<SbtProject>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct SbtProject {
/// The project id tasks are scoped with (`core/compile`).
pub id: String,
/// Base folder relative to the build folder (`""` for the build's own).
pub dir: String,
/// The build's root project: its tasks run unscoped (and aggregate when sbt does).
pub root: bool,
}
/// The sbt builds under `root` (outermost `build.sbt` folders).
pub fn load(root: &Path) -> Vec<SbtBuild> {
ide_core::project_roots::discover(root, &["build.sbt"])
.into_iter()
.filter_map(|dir| {
let text = std::fs::read_to_string(dir.join("build.sbt")).ok()?;
let rel = dir.strip_prefix(root).unwrap_or(&dir).to_string_lossy().replace('\\', "/");
let name = dir.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| "root".to_owned());
Some(SbtBuild {
dir: rel,
command: launcher(&dir),
version: build_version(&dir),
projects: projects(&text, &name),
})
})
.collect()
}
fn launcher(dir: &Path) -> String {
for script in ["sbt", "sbtx"] {
if !cfg!(windows) && dir.join(script).is_file() {
return format!("./{script}");
}
}
if cfg!(windows) && dir.join("sbt.bat").is_file() {
return "sbt.bat".to_owned();
}
"sbt".to_owned()
}
fn build_version(dir: &Path) -> Option<String> {
let text = std::fs::read_to_string(dir.join("project/build.properties")).ok()?;
text.lines().find_map(|line| {
let (key, value) = line.split_once('=')?;
(key.trim() == "sbt.version").then(|| value.trim().to_owned())
})
}
/// `text` with comments and the contents of string literals blanked (quotes kept),
/// byte for byte, so offsets into it are offsets into `text`.
fn mask(text: &str) -> String {
let mut out = String::with_capacity(text.len());
let blank = |out: &mut String, c: char| {
if c == '\n' {
out.push('\n');
} else {
out.extend(std::iter::repeat_n(' ', c.len_utf8()));
}
};
let mut chars = text.chars().peekable();
while let Some(c) = chars.next() {
match c {
'"' => {
out.push('"');
let mut ahead = chars.clone();
if ahead.next() == Some('"') && ahead.next() == Some('"') {
// `"""…"""`: no escapes inside.
chars.next();
chars.next();
out.push_str("\"\"");
let mut quotes = 0;
for c in chars.by_ref() {
quotes = if c == '"' { quotes + 1 } else { 0 };
if quotes > 0 {
out.push('"')
} else {
blank(&mut out, c)
}
if quotes == 3 {
break;
}
}
continue;
}
while let Some(c) = chars.next() {
if c == '"' || c == '\n' {
out.push(c);
break;
}
blank(&mut out, c);
if c == '\\'
&& let Some(n) = chars.next()
{
blank(&mut out, n);
}
}
}
'/' if chars.peek() == Some(&'/') => {
blank(&mut out, c);
for c in chars.by_ref() {
blank(&mut out, c);
if c == '\n' {
break;
}
}
}
'/' if chars.peek() == Some(&'*') => {
blank(&mut out, c);
let mut prev = ' ';
for c in chars.by_ref() {
blank(&mut out, c);
if prev == '*' && c == '/' {
break;
}
prev = c;
}
}
_ => out.push(c),
}
}
out
}
fn identifier(s: &str) -> Option<(&str, &str)> {
let s = s.trim_start();
if let Some(rest) = s.strip_prefix('`') {
let end = rest.find('`')?;
return Some((&rest[..end], &rest[end + 1..]));
}
let end = s.find(|c: char| !(c.is_alphanumeric() || c == '_')).unwrap_or(s.len());
(end > 0).then(|| (&s[..end], &s[end..]))
}
/// The string literal at the start of `s` (after spaces), and the rest.
fn string_literal(s: &str) -> Option<(&str, &str)> {
let rest = s.trim_start().strip_prefix('"')?;
let end = rest.find('"')?;
Some((&rest[..end], &rest[end + 1..]))
}
/// The folder of a `file("x")` / `new File("x")` at the start of `s`.
fn file_arg(s: &str) -> Option<&str> {
let s = s.trim_start();
let s = s.strip_prefix("file").or_else(|| s.strip_prefix("new File"))?;
let s = s.trim_start().strip_prefix('(')?;
string_literal(s).map(|(dir, _)| dir)
}
fn normalize_dir(dir: &str) -> String {
let dir = dir.trim_start_matches("./").trim_end_matches('/');
if dir == "." { String::new() } else { dir.to_owned() }
}
/// What a `lazy val <id> = <rhs>` declares: a project and its base folder. `rhs` is
/// masked (see [`mask`]); `original` is the same text unmasked, for the folder names.
fn project_of(id: &str, rhs: &str, original: &str) -> Option<String> {
let at = |s: &str| original.get(rhs.len() - s.len()..).unwrap_or_default();
let rhs = rhs.trim_start().trim_start_matches('(').trim_start();
if let Some(rest) = rhs.strip_prefix("Project") {
// `Project("id", file("dir"))` / `Project(id = "x", base = file("dir"))`.
let args = rest.trim_start().strip_prefix('(')?;
let base = args.find("file(").or_else(|| args.find("new File("))?;
return file_arg(at(&args[base..])).map(normalize_dir);
}
let rest = rhs.strip_prefix("project")?;
if rest.starts_with(|c: char| c.is_alphanumeric() || c == '_') {
return None;
}
let rest = rest.trim_start();
let located = rest
.strip_prefix(".in")
.and_then(|r| r.trim_start().strip_prefix('('))
.or_else(|| rest.strip_prefix("in ").or_else(|| rest.strip_prefix("in\t")));
Some(match located.and_then(|l| file_arg(at(l))) {
Some(dir) => normalize_dir(dir),
None => id.to_owned(),
})
}
/// The projects a build definition declares; `name` is the build folder's name, the id
/// sbt gives an implicit root project.
pub fn projects(text: &str, name: &str) -> Vec<SbtProject> {
let masked = mask(text);
let mut out: Vec<SbtProject> = Vec::new();
let mut from = 0;
while let Some(found) = masked[from..].find("val ") {
let at = from + found;
from = at + 4;
if masked[..at].chars().last().is_some_and(|c| c.is_alphanumeric() || c == '_') {
continue;
}
let Some((id, tail)) = identifier(&masked[from..]) else { continue };
let Some(rhs) = tail.trim_start().strip_prefix('=') else { continue };
if rhs.starts_with('=') || rhs.starts_with('>') {
continue;
}
let Some(dir) = project_of(id, rhs, &text[masked.len() - rhs.len()..]) else { continue };
if !out.iter().any(|p| p.id == id) {
out.push(SbtProject { id: id.to_owned(), root: dir.is_empty(), dir });
}
}
match out.iter().position(|p| p.root) {
Some(i) => {
let root = out.remove(i);
out.insert(0, root);
}
None => out.insert(0, SbtProject { id: name.to_owned(), dir: String::new(), root: true }),
}
out
}
#[cfg(test)]
mod tests {
use super::*;
fn ids(text: &str) -> Vec<(String, String, bool)> {
projects(text, "shop").into_iter().map(|p| (p.id, p.dir, p.root)).collect()
}
#[test]
fn single_project_builds_have_an_implicit_root() {
assert_eq!(
ids("ThisBuild / scalaVersion := \"3.3.4\"\nname := \"shop\"\n"),
[("shop".into(), "".into(), true)]
);
}
#[test]
fn declared_projects_and_their_folders() {
let text = r#"
// lazy val commented = project
lazy val root = (project in file("."))
.aggregate(core, `web-app`, util)
.settings(name := "shop")
lazy val core = project
lazy val `web-app` = (project in file("modules/web")).dependsOn(core)
lazy val util = project.in(file("libs/util/"))
lazy val legacy = Project("legacy", file("old"))
/* lazy val hidden = project */
val description = "lazy val fake = project"
lazy val projectSettings = Seq(scalacOptions += "-deprecation")
"#;
assert_eq!(
ids(text),
[
("root".into(), "".into(), true),
("core".into(), "core".into(), false),
("web-app".into(), "modules/web".into(), false),
("util".into(), "libs/util".into(), false),
("legacy".into(), "old".into(), false),
]
);
}
#[test]
fn a_root_declared_last_is_listed_first() {
let text = "lazy val api = project\nlazy val all = (project in file(\".\")).aggregate(api)\n";
assert_eq!(ids(text), [("all".into(), "".into(), true), ("api".into(), "api".into(), false)]);
}
#[test]
fn builds_are_found_with_their_launcher_and_version() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
std::fs::create_dir_all(root.join("svc/project")).unwrap();
std::fs::create_dir_all(root.join("svc/core")).unwrap();
std::fs::write(root.join("svc/build.sbt"), "lazy val core = project\n").unwrap();
// A project's own build.sbt is part of the outer build.
std::fs::write(root.join("svc/core/build.sbt"), "libraryDependencies += \"a\" % \"b\" % \"1\"\n").unwrap();
std::fs::write(root.join("svc/project/build.properties"), "sbt.version = 1.10.7\n").unwrap();
let builds = load(root);
assert_eq!(builds.len(), 1);
let b = &builds[0];
assert_eq!((b.dir.as_str(), b.command.as_str(), b.version.as_deref()), ("svc", "sbt", Some("1.10.7")));
assert_eq!(b.projects.iter().map(|p| p.id.as_str()).collect::<Vec<_>>(), ["svc", "core"]);
}
}
+28 -131
View File
@@ -86,20 +86,15 @@ const MAVEN_CACHE_VERSION: u32 = 1;
/// `dependency:tree` of a plugin version whose `-Dverbose` lists the occurrences Maven /// `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. /// 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 project's own /// Offline, the project's own plugin version is used instead, since this one may not be cached.
/// plugin version is, which may be cached instead.
const DEPENDENCY_TREE: &str = "org.apache.maven.plugins:maven-dependency-plugin:3.8.1:tree"; const DEPENDENCY_TREE: &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; /// The goals that read the effective POM into `effective` and the verbose dependency trees.
/// `repo` is the local repository the build resolves from. fn maven_sync_goals(effective: &Path, offline: bool) -> Vec<String> {
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());
vec![ vec![
"help:effective-pom".into(), "help:effective-pom".into(),
format!("-Doutput={}", effective.to_string_lossy()), format!("-Doutput={}", effective.to_string_lossy()),
if pinned { DEPENDENCY_TREE.into() } else { "dependency:tree".into() }, if offline { "dependency:tree".into() } else { DEPENDENCY_TREE.into() },
"-Dverbose".into(), "-Dverbose".into(),
] ]
} }
@@ -123,7 +118,6 @@ fn sync_maven_options(options: &[String]) -> Vec<String> {
} }
const GRADLE_CACHE: &str = "gradle.json"; const GRADLE_CACHE: &str = "gradle.json";
const MAVEN_PROFILES: &str = "maven-profiles.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 /// 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). /// with: what the IDE resolves it with besides `mvn` (the Java language server, Build Project).
@@ -133,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. /// 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> { pub fn save_maven_profiles(cache_dir: &Path, profiles: &[String]) -> IdeResult<bool> {
save_if_changed(cache_dir, MAVEN_PROFILES, &profiles.to_vec()) if maven_profiles(cache_dir) == profiles {
}
/// 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 {
return Ok(false); return Ok(false);
} }
std::fs::create_dir_all(dir)?; std::fs::create_dir_all(cache_dir)?;
let json = serde_json::to_vec(value).map_err(|e| IdeError::internal(e.to_string()))?; let json = serde_json::to_vec(profiles).map_err(|e| IdeError::internal(e.to_string()))?;
std::fs::write(dir.join(name), json)?; std::fs::write(cache_dir.join(MAVEN_PROFILES), json)?;
Ok(true) 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() 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)?; std::fs::create_dir_all(dir)?;
let json = serde_json::to_vec(value).map_err(|e| IdeError::internal(e.to_string()))?; let json = serde_json::to_vec(value).map_err(|e| IdeError::internal(e.to_string()))?;
let tmp = dir.join(format!("{name}.tmp")); let tmp = dir.join(format!("{name}.tmp"));
@@ -181,7 +156,7 @@ fn hash_files(files: &[PathBuf]) -> String {
/// Like IDEA's auto-import CRC: editing a comment or reformatting a build script /// Like IDEA's auto-import CRC: editing a comment or reformatting a build script
/// does not make the last sync stale. /// 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| { hash_contents(files, |f| {
let text = std::fs::read_to_string(f).unwrap_or_default(); let text = std::fs::read_to_string(f).unwrap_or_default();
let script = f.extension().is_some_and(|e| e == "gradle" || e == "kts"); let script = f.extension().is_some_and(|e| e == "gradle" || e == "kts");
@@ -293,20 +268,8 @@ fn run(
process::run(program, args, cwd, env, cancel, |_, line| on_line(line)) 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. /// The first error lines of a failed build, for the tool window.
pub(crate) fn error_summary(output: &Output) -> String { pub(crate) fn error_summary(text: &str) -> String {
let text = &output.text;
// The JVM's "could not find or load main class" (localized) when `gradlew` has no jar. // The JVM's "could not find or load main class" (localized) when `gradlew` has no jar.
if text.contains("org.gradle.wrapper.GradleWrapperMain") { if text.contains("org.gradle.wrapper.GradleWrapperMain") {
return "gradle/wrapper/gradle-wrapper.jar is missing (often excluded by a `*.jar` rule in .gitignore). \ return "gradle/wrapper/gradle-wrapper.jar is missing (often excluded by a `*.jar` rule in .gitignore). \
@@ -326,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")) .filter(|l| !l.is_empty() && !l.starts_with("Re-run Maven") && !l.starts_with("To see the full stack trace"))
.take(4) .take(4)
.collect(); .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() text.lines().rev().find(|l| !l.trim().is_empty()).unwrap_or("the build failed").trim().to_owned()
} else { } else {
lines.join("\n") 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). /// `[INFO] Building core 1.0-SNAPSHOT [2/3]` → ("core 1.0-SNAPSHOT", 2, 3).
@@ -407,8 +366,7 @@ pub fn sync_maven(
if !options.profiles.is_empty() { if !options.profiles.is_empty() {
args.push(format!("-P{}", options.profiles.join(","))); args.push(format!("-P{}", options.profiles.join(",")));
} }
let repo = local_repo.clone().or_else(maven::default_local_repo); args.extend(maven_sync_goals(&effective, options.offline));
args.extend(maven_sync_goals(&effective, options.offline, repo.as_deref()));
progress(SyncProgress { message: format!("Reading {}", top.display_name), fraction: None }); progress(SyncProgress { message: format!("Reading {}", top.display_name), fraction: None });
let command = options.maven_command.as_deref().unwrap_or(&top.command); let command = options.maven_command.as_deref().unwrap_or(&top.command);
let out = run(command, &args, &root.join(&top.dir), &options.env, cancel, |line| { let out = run(command, &args, &root.join(&top.dir), &options.env, cancel, |line| {
@@ -439,9 +397,7 @@ pub fn sync_maven(
} }
} }
if !out.success { if !out.success {
errors.push(error_summary(&out)); errors.push(error_summary(&out.text));
} else if let Some(note) = truncation_note(&out) {
errors.push(note);
} }
} }
cache.at_ms = now_ms(); cache.at_ms = now_ms();
@@ -481,8 +437,6 @@ pub fn sync_gradle_model(
let mut args: Vec<String> = vec![ let mut args: Vec<String> = vec![
"--console=plain".into(), "--console=plain".into(),
"-q".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".into(),
init_script.to_string_lossy().into_owned(), init_script.to_string_lossy().into_owned(),
"tasks".into(), "tasks".into(),
@@ -503,7 +457,7 @@ pub fn sync_gradle_model(
Ok(out) => out, Ok(out) => out,
Err(_) if cancel.is_cancelled() => return Err(IdeError::cancelled()), Err(_) if cancel.is_cancelled() => return Err(IdeError::cancelled()),
Err(error) if error.kind == ide_core::error::ErrorKind::Unavailable => { 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), Err(error) => return Err(error),
}; };
@@ -516,7 +470,7 @@ pub fn sync_gradle_model(
let cache = GradleCache { let cache = GradleCache {
hash: hash_gradle_files(&gradle::build_files(root, &model)), hash: hash_gradle_files(&gradle::build_files(root, &model)),
at_ms: now_ms(), 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() }, tasks: if out.success { gradle::parse_tasks(&out.text) } else { Vec::new() },
projects, projects,
resources: true, resources: true,
@@ -558,18 +512,14 @@ mod tests {
assert!(loaded.gradle[0].sync_error.as_deref().unwrap().contains("cannot start")); assert!(loaded.gradle[0].sync_error.as_deref().unwrap().contains("cannot start"));
assert!(loaded.gradle[1].sync_error.is_none()); assert!(loaded.gradle[1].sync_error.is_none());
assert_eq!(loaded.gradle[1].projects[0].tasks[0].name, "healthy"); assert_eq!(loaded.gradle[1].projects[0].tasks[0].name, "healthy");
// A wrapper without the execute bit (committed from Windows, unpacked from a zip) let bad_wrapper = root.join("a/gradlew");
// runs through `sh`, and its mode is left alone. std::fs::write(&bad_wrapper, "#!/bin/sh\nexit 0\n").unwrap();
let plain_wrapper = root.join("a/gradlew"); std::fs::set_permissions(&bad_wrapper, std::fs::Permissions::from_mode(0o644)).unwrap();
std::fs::write(&plain_wrapper, "#!/bin/sh\nprintf '%s\\n' 'Build tasks' '-----------' 'plain - ok'\n").unwrap(); models[0].command = bad_wrapper.to_string_lossy().into_owned();
std::fs::set_permissions(&plain_wrapper, std::fs::Permissions::from_mode(0o644)).unwrap();
models[0].command = plain_wrapper.to_string_lossy().into_owned();
run(&models[0]).unwrap(); run(&models[0]).unwrap();
let loaded = crate::load_linked(root, &cache, None, &Default::default(), &settings); let loaded = crate::load_linked(root, &cache, None, &Default::default(), &settings);
assert!(loaded.gradle[0].sync_error.is_none()); assert!(loaded.gradle[0].sync_error.as_deref().unwrap().contains("cannot start"));
assert_eq!(loaded.gradle[0].projects[0].tasks[0].name, "plain");
assert!(loaded.gradle[1].sync_error.is_none()); 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"); let blocked_cache = root.join("blocked-cache");
std::fs::write(&blocked_cache, "a file cannot contain sync caches").unwrap(); std::fs::write(&blocked_cache, "a file cannot contain sync caches").unwrap();
assert!( assert!(
@@ -938,31 +888,12 @@ mod tests {
} }
#[test] #[test]
fn the_offline_mode_of_the_last_sync_is_kept_for_the_language_server() { fn sync_reads_verbose_trees_with_a_pinned_plugin_unless_offline() {
let tmp = tempfile::tempdir().unwrap(); let online = maven_sync_goals(Path::new("e.xml"), false);
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 online = maven_sync_goals(Path::new("e.xml"), false, None);
assert_eq!(online, ["help:effective-pom", "-Doutput=e.xml", DEPENDENCY_TREE, "-Dverbose"]); assert_eq!(online, ["help:effective-pom", "-Doutput=e.xml", DEPENDENCY_TREE, "-Dverbose"]);
let offline = maven_sync_goals(Path::new("e.xml"), true, Some(tmp.path())); let offline = maven_sync_goals(Path::new("e.xml"), true);
assert_eq!(offline[2], "dependency:tree"); assert_eq!(offline[2], "dependency:tree");
assert!(offline.contains(&"-Dverbose".to_owned())); assert!(offline.contains(&"-Dverbose".to_owned()));
// Downloaded by an online sync: offline keeps using it, the project's version may be missing.
let jar = tmp.path().join(DEPENDENCY_TREE_JAR);
std::fs::create_dir_all(jar.parent().unwrap()).unwrap();
std::fs::write(&jar, "").unwrap();
assert_eq!(maven_sync_goals(Path::new("e.xml"), true, Some(tmp.path()))[2], DEPENDENCY_TREE);
} }
#[test] #[test]
@@ -983,22 +914,10 @@ mod tests {
); );
assert_eq!(maven_building("[INFO] Building jar: x.jar"), None); 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 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(text), "Failed to execute goal");
assert_eq!(error_summary(&out(text, false)), "Failed to execute goal"); assert_eq!(error_summary("one\nlast line\n\n"), "last line");
assert_eq!(error_summary(&out("one\nlast line\n\n", false)), "last line");
let missing_jar = "错误: 找不到或无法加载主类 org.gradle.wrapper.GradleWrapperMain\n"; let missing_jar = "错误: 找不到或无法加载主类 org.gradle.wrapper.GradleWrapperMain\n";
assert!(error_summary(&out(missing_jar, false)).starts_with("gradle/wrapper/gradle-wrapper.jar is missing")); assert!(error_summary(missing_jar).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"));
} }
#[test] #[test]
@@ -1014,28 +933,6 @@ mod tests {
assert!(sync_maven_options(&[]).is_empty()); 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("help:effective-pom"), "args: {args}");
let loaded = crate::load_linked(&root, &cache, None, &Default::default(), &Default::default());
let maven = loaded.maven.unwrap();
assert!(maven.synced_at.is_some() && maven.sync_error.is_none(), "{:?}", maven.sync_error);
assert_eq!(std::fs::metadata(&mvnw).unwrap().permissions().mode() & 0o777, 0o644);
}
#[cfg(unix)] #[cfg(unix)]
#[test] #[test]
fn maven_sync_runs_the_daemon_command_serially() { fn maven_sync_runs_the_daemon_command_serially() {
+7 -26
View File
@@ -172,25 +172,13 @@ pub fn build(root: &Path, model: &BuildModel, id: &str, cache: &Path) -> IdeResu
fs::write( fs::write(
&script, &script,
format!( format!(
r#"import org.gradle.util.GradleVersion r#"gradle.projectsEvaluated {{
gradle.projectsEvaluated {{
def p = gradle.rootProject.project({}) def p = gradle.rootProject.project({})
def artifact = {{ t -> def warTask = p.tasks.named('war')
t.dependsOn 'war' p.tasks.register('openideaTomcatArtifact') {{
// Resolved here so the action holds no task or project (configuration cache). dependsOn warTask
def war = p.tasks.getByName('war') doLast {{ new File({}).setText(warTask.get().archiveFile.get().asFile.absolutePath, 'UTF-8') }}
// `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')
}}
}} }}
// `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), groovy_literal(path),
@@ -282,7 +270,7 @@ mod tests {
assert_eq!(a.len(), 1); assert_eq!(a.len(), 1);
let plan = build(tmp.path(), &model, &a[0].id, &tmp.path().join("base")).unwrap(); let plan = build(tmp.path(), &model, &a[0].id, &tmp.path().join("base")).unwrap();
assert!(plan.args.contains(&":openideaTomcatArtifact".into())); 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 }")); assert!(!crate::gradle::has_war_plugin("// plugins { war }"));
} }
@@ -309,14 +297,7 @@ mod tests {
assert!(plan.args.contains(&format!("{}:openideaTomcatArtifact", module.trim_end_matches(':')))); assert!(plan.args.contains(&format!("{}:openideaTomcatArtifact", module.trim_end_matches(':'))));
let script = fs::read_to_string(cache.join("war.init.gradle")).unwrap(); let script = fs::read_to_string(cache.join("war.init.gradle")).unwrap();
assert!(script.contains(&format!("rootProject.project('{}')", module))); assert!(script.contains(&format!("rootProject.project('{}')", module)));
assert!(script.contains("manifest.setText(file.absolutePath, 'UTF-8')")); assert!(script.contains("archiveFile.get().asFile.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}");
} }
} }
} }
+3 -9
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "ide-clipboard" name = "ide-clipboard"
description = "The OS clipboard's file list (Explorer <-> project view) and pasted images: Windows CF_HDROP / PNG / CF_DIB or macOS NSPasteboard, no window or message loop" description = "The OS clipboard's file list (Explorer <-> project view): Windows CF_HDROP or macOS NSPasteboard file URLs, no window or message loop"
version.workspace = true version.workspace = true
edition.workspace = true edition.workspace = true
license.workspace = true license.workspace = true
@@ -9,14 +9,8 @@ license.workspace = true
[target.'cfg(target_os = "macos")'.dependencies] [target.'cfg(target_os = "macos")'.dependencies]
objc2 = { version = "0.6", default-features = false, features = ["std"] } objc2 = { version = "0.6", default-features = false, features = ["std"] }
objc2-foundation = { version = "0.3", default-features = false, features = ["std", "NSArray", "NSData", "NSDictionary", "NSEnumerator", "NSObject", "NSString", "NSURL", "NSValue"] } objc2-foundation = { version = "0.3", default-features = false, features = ["std", "NSArray", "NSDictionary", "NSEnumerator", "NSObject", "NSString", "NSURL", "NSValue"] }
objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "NSBitmapImageRep", "NSImageRep", "NSPasteboard"] } objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "NSPasteboard"] }
[target.'cfg(windows)'.dependencies]
png = "0.18"
[target.'cfg(target_os = "linux")'.dependencies] [target.'cfg(target_os = "linux")'.dependencies]
gtk = "0.18" gtk = "0.18"
[dev-dependencies]
png = "0.18"
+3 -258
View File
@@ -18,10 +18,6 @@
//! //!
//! Other platforms (`text/uri-list` on X11) are not wired up: [`files`] is //! Other platforms (`text/uri-list` on X11) are not wired up: [`files`] is
//! empty and [`set_files`] fails there. //! empty and [`set_files`] fails there.
//!
//! [`png`] reads an image (a screenshot) for the project view's Paste, which
//! saves it as a file: `public.png` or `public.tiff` on macOS, the registered
//! `PNG` format or `CF_DIB` on Windows. Linux reads it through GTK in the app.
use std::path::PathBuf; use std::path::PathBuf;
@@ -38,19 +34,6 @@ pub fn text() -> Option<String> {
imp::text() imp::text()
} }
/// The clipboard's image as PNG bytes, None when it holds none. Call on the main
/// thread on macOS.
#[cfg(any(windows, target_os = "macos"))]
pub fn png() -> Option<Vec<u8>> {
imp::png()
}
/// Whether the clipboard holds an image, without reading it. Call on the main
/// thread on macOS and Linux.
pub fn has_image() -> bool {
imp::has_image()
}
/// Size of `DROPFILES`: `pFiles`, `pt` (two `LONG`s), `fNC`, `fWide`. /// Size of `DROPFILES`: `pFiles`, `pt` (two `LONG`s), `fNC`, `fWide`.
const HEADER: usize = 20; const HEADER: usize = 20;
@@ -151,62 +134,9 @@ pub fn decode(bytes: &[u8]) -> Vec<PathBuf> {
out out
} }
/// `BI_RGB` and `BI_BITFIELDS`: uncompressed pixels, the forms screenshots take.
#[cfg(any(windows, test))]
const BI_RGB: u32 = 0;
#[cfg(any(windows, test))]
const BI_BITFIELDS: u32 = 3;
/// A packed DIB (`BITMAPINFOHEADER` or a later header, then the pixels) as PNG.
/// Only 24- and 32-bit uncompressed bitmaps, which is what screenshots and
/// copied images are; None for anything else. A 32-bit bitmap whose alpha is
/// all zero (most writers leave it unset) is opaque.
#[cfg(any(windows, test))]
fn dib_to_png(dib: &[u8]) -> Option<Vec<u8>> {
let u32_at = |at: usize| dib.get(at..at + 4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]]));
let header = u32_at(0)? as usize;
let width = u32_at(4)? as i32;
let height = u32_at(8)? as i32;
let bits = u16::from_le_bytes([*dib.get(14)?, *dib.get(15)?]);
let compression = u32_at(16)?;
if header < 40 || width <= 0 || height == 0 || !matches!(bits, 24 | 32) {
return None;
}
if compression != BI_RGB && !(compression == BI_BITFIELDS && bits == 32) {
return None;
}
// A `BITMAPINFOHEADER` keeps the three bitfield masks after it; later
// headers hold them inside. Masks other than BGRA's are not supported.
let masks = if compression == BI_BITFIELDS && header == 40 { 12 } else { 0 };
let colors = u32_at(32)? as usize;
let (width, rows) = (width as usize, height.unsigned_abs() as usize);
let stride = (width * bits as usize).div_ceil(32) * 4;
let start = header + masks + colors * 4;
let pixels = dib.get(start..start.checked_add(stride.checked_mul(rows)?)?)?;
let step = bits as usize / 8;
let mut rgba = Vec::with_capacity(width * rows * 4);
for row in 0..rows {
// A positive height stores the bottom row first.
let source = if height > 0 { rows - 1 - row } else { row };
let line = &pixels[source * stride..source * stride + width * step];
for px in line.chunks_exact(step) {
rgba.extend_from_slice(&[px[2], px[1], px[0], if step == 4 { px[3] } else { 255 }]);
}
}
if step == 4 && rgba.as_chunks::<4>().0.iter().all(|px| px[3] == 0) {
rgba.as_chunks_mut::<4>().0.iter_mut().for_each(|px| px[3] = 255);
}
let mut out = Vec::new();
let mut encoder = png::Encoder::new(&mut out, width as u32, rows as u32);
encoder.set_color(png::ColorType::Rgba);
encoder.set_depth(png::BitDepth::Eight);
encoder.write_header().ok()?.write_image_data(&rgba).ok()?;
Some(out)
}
#[cfg(windows)] #[cfg(windows)]
mod imp { mod imp {
use super::{HEADER, decode, dib_to_png, encode, names_text}; use super::{HEADER, decode, encode, names_text};
use std::ffi::c_void; use std::ffi::c_void;
use std::path::PathBuf; use std::path::PathBuf;
use std::ptr; use std::ptr;
@@ -234,59 +164,6 @@ mod imp {
fn GetClipboardData(format: u32) -> Handle; fn GetClipboardData(format: u32) -> Handle;
fn SetClipboardData(format: u32, memory: Handle) -> Handle; fn SetClipboardData(format: u32, memory: Handle) -> Handle;
fn IsClipboardFormatAvailable(format: u32) -> i32; fn IsClipboardFormatAvailable(format: u32) -> i32;
fn RegisterClipboardFormatW(name: *const u16) -> u32;
}
/// `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;
/// The `PNG` format browsers and the Snipping Tool add beside the bitmap; it
/// keeps transparency, so it is read first.
fn png_format() -> u32 {
let name: Vec<u16> = "PNG\0".encode_utf16().collect();
unsafe { RegisterClipboardFormatW(name.as_ptr()) }
}
pub fn has_image() -> bool {
let png = png_format();
(png != 0 && unsafe { IsClipboardFormatAvailable(png) } != 0)
|| unsafe { IsClipboardFormatAvailable(CF_DIB) } != 0
}
/// A copy of the clipboard's `format` block. Call with the clipboard open.
fn read_block(format: u32) -> Option<Vec<u8>> {
// SAFETY: the clipboard keeps the block alive while it is open, and
// `GlobalSize` bounds the bytes read from it.
unsafe {
let memory = GetClipboardData(format);
if memory.is_null() {
return None;
}
let data = GlobalLock(memory);
if data.is_null() {
return None;
}
let bytes = std::slice::from_raw_parts(data as *const u8, GlobalSize(memory)).to_vec();
GlobalUnlock(memory);
Some(bytes)
}
}
pub fn png() -> Option<Vec<u8>> {
if !open() {
return None;
}
let png = png_format();
let image = if png != 0 && unsafe { IsClipboardFormatAvailable(png) } != 0 {
read_block(png)
} else if unsafe { IsClipboardFormatAvailable(CF_DIB) } != 0 {
read_block(CF_DIB).and_then(|dib| dib_to_png(&dib))
} else {
None
};
unsafe { CloseClipboard() };
image
} }
#[link(name = "kernel32")] #[link(name = "kernel32")]
@@ -348,35 +225,6 @@ mod imp {
paths 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 /// An `HGLOBAL` holding `text` as UTF-16 with a terminating NUL, and its
/// byte size. Null when the allocation failed. /// byte size. Null when the allocation failed.
fn global_text(text: &str) -> (Handle, usize) { fn global_text(text: &str) -> (Handle, usize) {
@@ -459,13 +307,6 @@ mod imp {
if !taken { if !taken {
GlobalFree(memory); 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); let (text_memory, _) = global_text(&text);
if !text_memory.is_null() { if !text_memory.is_null() {
// The text alone still pastes somewhere useful. // The text alone still pastes somewhere useful.
@@ -486,8 +327,8 @@ mod imp {
use objc2::runtime::{AnyClass, AnyObject, ProtocolObject}; use objc2::runtime::{AnyClass, AnyObject, ProtocolObject};
use objc2::{ClassType, MainThreadMarker}; use objc2::{ClassType, MainThreadMarker};
use objc2_app_kit::{ use objc2_app_kit::{
NSBitmapImageFileType, NSBitmapImageRep, NSPasteboard, NSPasteboardReadingOptionKey, NSPasteboardTypePNG, NSPasteboard, NSPasteboardReadingOptionKey, NSPasteboardTypeString, NSPasteboardURLReadingFileURLsOnlyKey,
NSPasteboardTypeString, NSPasteboardTypeTIFF, NSPasteboardURLReadingFileURLsOnlyKey, NSPasteboardWriting, NSPasteboardWriting,
}; };
use objc2_foundation::{NSArray, NSDictionary, NSNumber, NSString, NSURL}; use objc2_foundation::{NSArray, NSDictionary, NSNumber, NSString, NSURL};
use std::path::PathBuf; use std::path::PathBuf;
@@ -539,33 +380,6 @@ mod imp {
}) })
} }
pub fn has_image() -> bool {
debug_assert!(MainThreadMarker::new().is_some(), "NSPasteboard access requires the main thread");
autoreleasepool(|_| {
// SAFETY: the types are AppKit constants, valid for the process' lifetime.
let types = NSArray::from_slice(&[unsafe { NSPasteboardTypePNG }, unsafe { NSPasteboardTypeTIFF }]);
NSPasteboard::generalPasteboard().availableTypeFromArray(&types).is_some()
})
}
/// PNG as copied, else TIFF (what macOS screenshots and most apps write) converted.
pub fn png() -> Option<Vec<u8>> {
debug_assert!(MainThreadMarker::new().is_some(), "NSPasteboard access requires the main thread");
autoreleasepool(|_| {
let board = NSPasteboard::generalPasteboard();
// SAFETY: the types are AppKit constants, valid for the process' lifetime.
if let Some(png) = board.dataForType(unsafe { NSPasteboardTypePNG }) {
return Some(png.to_vec());
}
let tiff = board.dataForType(unsafe { NSPasteboardTypeTIFF })?;
let image = NSBitmapImageRep::imageRepWithData(&tiff)?;
// SAFETY: an empty property dictionary is valid for every file type.
let png =
unsafe { image.representationUsingType_properties(NSBitmapImageFileType::PNG, &NSDictionary::new()) }?;
Some(png.to_vec())
})
}
pub fn text() -> Option<String> { pub fn text() -> Option<String> {
debug_assert!(MainThreadMarker::new().is_some(), "NSPasteboard access requires the main thread"); debug_assert!(MainThreadMarker::new().is_some(), "NSPasteboard access requires the main thread");
autoreleasepool(|_| { autoreleasepool(|_| {
@@ -634,17 +448,6 @@ mod imp {
false false
} }
pub fn has_image() -> bool {
#[cfg(target_os = "linux")]
{
gtk::Clipboard::get(&gtk::gdk::SELECTION_CLIPBOARD).wait_is_image_available()
}
#[cfg(not(target_os = "linux"))]
{
false
}
}
pub fn files() -> std::io::Result<Vec<PathBuf>> { pub fn files() -> std::io::Result<Vec<PathBuf>> {
Ok(Vec::new()) Ok(Vec::new())
} }
@@ -718,62 +521,4 @@ mod tests {
bytes.extend_from_slice(b"C:\\a\\b.txt\0C:\\c\0\0"); bytes.extend_from_slice(b"C:\\a\\b.txt\0C:\\c\0\0");
assert_eq!(decode(&bytes), paths(&["C:\\a\\b.txt", "C:\\c"])); assert_eq!(decode(&bytes), paths(&["C:\\a\\b.txt", "C:\\c"]));
} }
/// A `BITMAPINFOHEADER` DIB of `width` × `height` (positive: bottom-up).
fn dib(width: i32, height: i32, bits: u16, compression: u32, rows: &[&[u8]]) -> Vec<u8> {
let mut out = Vec::new();
out.extend_from_slice(&40u32.to_le_bytes());
out.extend_from_slice(&width.to_le_bytes());
out.extend_from_slice(&height.to_le_bytes());
out.extend_from_slice(&1u16.to_le_bytes());
out.extend_from_slice(&bits.to_le_bytes());
out.extend_from_slice(&compression.to_le_bytes());
out.extend_from_slice(&[0u8; 20]);
if compression == super::BI_BITFIELDS {
for mask in [0x00ff_0000u32, 0x0000_ff00, 0x0000_00ff] {
out.extend_from_slice(&mask.to_le_bytes());
}
}
for row in rows {
out.extend_from_slice(row);
}
out
}
fn decode_png(png: &[u8]) -> (u32, u32, Vec<u8>) {
let mut reader = png::Decoder::new(std::io::Cursor::new(png)).read_info().unwrap();
let mut buf = vec![0; reader.output_buffer_size().unwrap()];
let info = reader.next_frame(&mut buf).unwrap();
buf.truncate(info.buffer_size());
(info.width, info.height, buf)
}
#[test]
fn a_bottom_up_24_bit_bitmap_becomes_an_upright_opaque_png() {
// Rows are padded to 4 bytes; the first stored row is the bottom one.
let bottom: &[u8] = &[255, 0, 0, 0, 255, 0, 0, 0];
let top: &[u8] = &[0, 0, 255, 255, 255, 255, 0, 0];
let png = super::dib_to_png(&dib(2, 2, 24, super::BI_RGB, &[bottom, top])).unwrap();
let (w, h, rgba) = decode_png(&png);
assert_eq!((w, h), (2, 2));
assert_eq!(rgba, [255, 0, 0, 255, 255, 255, 255, 255, 0, 0, 255, 255, 0, 255, 0, 255]);
}
#[test]
fn a_32_bit_bitmap_keeps_its_alpha_unless_none_was_written() {
let row: &[u8] = &[10, 20, 30, 0, 40, 50, 60, 0];
let (_, _, rgba) = decode_png(&super::dib_to_png(&dib(2, -1, 32, super::BI_BITFIELDS, &[row])).unwrap());
assert_eq!(rgba, [30, 20, 10, 255, 60, 50, 40, 255]);
let row: &[u8] = &[10, 20, 30, 128, 40, 50, 60, 0];
let (_, _, rgba) = decode_png(&super::dib_to_png(&dib(2, -1, 32, super::BI_RGB, &[row])).unwrap());
assert_eq!(rgba, [30, 20, 10, 128, 60, 50, 40, 0]);
}
#[test]
fn unsupported_or_truncated_bitmaps_are_not_images() {
let row: &[u8] = &[1, 2, 3, 4];
assert!(super::dib_to_png(&dib(4, 1, 8, super::BI_RGB, &[row])).is_none());
assert!(super::dib_to_png(&dib(2, 2, 24, super::BI_RGB, &[row])).is_none());
assert!(super::dib_to_png(&[0; 10]).is_none());
}
} }
-18
View File
@@ -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
-92
View File
@@ -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
}
}
}
-884
View File
@@ -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`",
)),
}
}
}
-1
View File
@@ -6,7 +6,6 @@ edition.workspace = true
license.workspace = true license.workspace = true
[dependencies] [dependencies]
base64.workspace = true
dunce.workspace = true dunce.workspace = true
encoding_rs.workspace = true encoding_rs.workspace = true
serde.workspace = true serde.workspace = true
-319
View File
@@ -1,319 +0,0 @@
//! Runs a tool's CLI (`docker`, `gh`, `adb`) as a child process: bounded runs that collect
//! its output, and cancellable streams that hand over its output line by line.
//!
//! Every child leads its own process group ([`own_group`]), so cancelling or timing out
//! reaches what it started in turn (`gh` → `git`, `docker` → CLI plugins such as compose).
//! They get [`KILL_GRACE`] to exit on `SIGTERM` and clean up (git removes its lock files)
//! before `SIGKILL`.
use crate::process::{own_group, prepare, terminate_tree};
use crate::{CancellationToken, IdeError, IdeResult};
use std::borrow::Cow;
use std::io::{Read, Write};
use std::process::{Child, Command, Stdio};
use std::sync::mpsc;
use std::time::{Duration, Instant};
/// How long a cancelled or timed-out child's process group gets to exit on `SIGTERM`
/// before `SIGKILL`.
const KILL_GRACE: Duration = Duration::from_millis(20);
/// How many of a streamed child's last non-blank stderr lines are kept for its error message.
const STDERR_TAIL: usize = 20;
/// How a tool's output bytes become text.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Decoding {
/// [`decode_tool_output`](crate::output_encoding::decode_tool_output): UTF-8, and on
/// Windows the system code page for what is not.
ToolOutput,
/// UTF-8, invalid bytes replaced by U+FFFD.
Utf8Lossy,
}
impl Decoding {
fn decode(self, bytes: &[u8]) -> Cow<'_, str> {
match self {
Decoding::ToolOutput => Cow::Owned(crate::output_encoding::decode_tool_output(bytes)),
Decoding::Utf8Lossy => String::from_utf8_lossy(bytes),
}
}
}
/// What a child's stdin is fed with, and how.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Input<'a> {
/// Written before the output is read, then closed: only for input small enough
/// (a password) to fit the pipe, as a full pipe blocks the caller.
Inline(&'a str),
/// Written by a thread of its own, then closed: a large body must not block on a full
/// pipe while the child is not reading yet.
Threaded(&'a str),
}
/// How a streamed child's `\r` is read.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CarriageReturn {
/// Ends a line like `\n`: progress output rewrites its line in place.
EndsLine,
/// Is dropped; only `\n` ends a line.
Dropped,
}
/// What a bounded run collected.
pub struct Output {
pub stdout: String,
pub stderr: String,
pub success: bool,
}
/// Which pipe a streamed line came from.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Stream {
Stdout,
Stderr,
}
/// One tool's CLI: its name for error messages and how its output is decoded.
#[derive(Clone, Copy, Debug)]
pub struct CliTool {
name: &'static str,
decoding: Decoding,
}
impl CliTool {
pub const fn new(name: &'static str, decoding: Decoding) -> Self {
Self { name, decoding }
}
fn spawn(self, cmd: &mut Command) -> IdeResult<Child> {
cmd.spawn().map_err(|e| IdeError::unavailable(format!("could not run {}: {e}", self.name)))
}
/// Pipes stdout and stderr, closes stdin and starts the child in its own process group.
fn configure(cmd: &mut Command) {
cmd.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped());
prepare(own_group(cmd));
}
/// Runs `cmd` to completion. Fails when it outlives `timeout` or `cancel` fires;
/// a non-zero exit is reported in [`Output::success`], not as an error.
pub fn run(self, cmd: Command, timeout: Duration, cancel: Option<&CancellationToken>) -> IdeResult<Output> {
self.run_with_input(cmd, None, timeout, cancel)
}
/// [`run`](Self::run) with `input` written to the child's stdin and then closed.
pub fn run_with_input(
self,
mut cmd: Command,
input: Option<Input>,
timeout: Duration,
cancel: Option<&CancellationToken>,
) -> IdeResult<Output> {
Self::configure(&mut cmd);
if input.is_some() {
cmd.stdin(Stdio::piped());
}
let mut child = self.spawn(&mut cmd)?;
match (input, child.stdin.take()) {
(Some(Input::Inline(text)), Some(mut stdin)) => {
// Dropping `stdin` afterwards closes it, so the CLI sees EOF.
let _ = stdin.write_all(text.as_bytes());
}
(Some(Input::Threaded(text)), Some(mut stdin)) => {
let text = text.to_owned();
std::thread::spawn(move || {
let _ = stdin.write_all(text.as_bytes());
});
}
_ => {}
}
let decoding = self.decoding;
let out = child.stdout.take().map(|pipe| read_all(pipe, decoding));
let err = child.stderr.take().map(|pipe| read_all(pipe, decoding));
let deadline = Instant::now() + timeout;
let status = loop {
if let Some(status) = child.try_wait()? {
break status;
}
if cancel.is_some_and(CancellationToken::is_cancelled) {
terminate_tree(&mut child, KILL_GRACE);
return Err(IdeError::cancelled());
}
if Instant::now() >= deadline {
terminate_tree(&mut child, KILL_GRACE);
return Err(IdeError::unavailable(format!("{} did not respond in time", self.name)));
}
std::thread::sleep(Duration::from_millis(10));
};
Ok(Output {
stdout: out.map(|t| t.join().unwrap_or_default()).unwrap_or_default(),
stderr: err.map(|t| t.join().unwrap_or_default()).unwrap_or_default(),
success: status.success(),
})
}
/// Runs `cmd`, handing every output line to `on_line` until it exits or `cancel`
/// fires. Returns whether it exited successfully plus the last stderr lines.
pub fn stream(
self,
cmd: Command,
cancel: &CancellationToken,
on_line: &mut dyn FnMut(Stream, String),
) -> IdeResult<(bool, Vec<String>)> {
let mut lines = self.lines(cmd, cancel, CarriageReturn::EndsLine)?;
let mut stderr_tail: Vec<String> = Vec::new();
loop {
match lines.poll(cancel, Duration::from_millis(50))? {
Poll::Line(stream, line) => {
if stream == Stream::Stderr && !line.trim().is_empty() {
keep_stderr_line(&mut stderr_tail, line.clone());
}
on_line(stream, line);
}
Poll::Closed | Poll::Timeout => {}
Poll::Finished => break,
}
}
Ok((lines.finish(cancel)?, stderr_tail))
}
/// Starts `cmd` with a reader thread per pipe, for a caller that drives the loop itself
/// (see [`Lines::poll`]). Fails when `cancel` has already fired, without starting it.
pub fn lines(self, mut cmd: Command, cancel: &CancellationToken, cr: CarriageReturn) -> IdeResult<Lines> {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
Self::configure(&mut cmd);
let mut child = self.spawn(&mut cmd)?;
let (tx, rx) = mpsc::channel::<Event>();
let mut open = 0;
if let Some(out) = child.stdout.take() {
spawn_reader(out, tx.clone(), Stream::Stdout, self.decoding, cr);
open += 1;
}
if let Some(err) = child.stderr.take() {
spawn_reader(err, tx.clone(), Stream::Stderr, self.decoding, cr);
open += 1;
}
drop(tx);
Ok(Lines { child, rx, open })
}
}
/// Appends a stderr line to `tail`, which keeps only the last [`STDERR_TAIL`].
pub fn keep_stderr_line(tail: &mut Vec<String>, line: String) {
tail.push(line);
if tail.len() > STDERR_TAIL {
tail.remove(0);
}
}
fn read_all(mut pipe: impl Read + Send + 'static, decoding: Decoding) -> std::thread::JoinHandle<String> {
std::thread::spawn(move || {
let mut buf = Vec::new();
let _ = pipe.read_to_end(&mut buf);
decoding.decode(&buf).into_owned()
})
}
enum Event {
Line(Stream, String),
Closed,
}
fn spawn_reader(
mut pipe: impl Read + Send + 'static,
tx: mpsc::Sender<Event>,
stream: Stream,
decoding: Decoding,
cr: CarriageReturn,
) {
std::thread::spawn(move || {
let mut buf = [0u8; 8192];
let mut pending: Vec<u8> = Vec::new();
let flush = |pending: &mut Vec<u8>| {
if !pending.is_empty() {
let line = decoding.decode(pending).trim_end().to_string();
pending.clear();
let _ = tx.send(Event::Line(stream, line));
}
};
loop {
match pipe.read(&mut buf) {
Ok(0) | Err(_) => break,
Ok(n) => {
for &b in &buf[..n] {
if b == b'\n' || (b == b'\r' && cr == CarriageReturn::EndsLine) {
flush(&mut pending);
} else if b != b'\r' {
pending.push(b);
}
}
}
}
}
flush(&mut pending);
let _ = tx.send(Event::Closed);
});
}
/// A running child whose output lines are read by threads: see [`CliTool::lines`].
pub struct Lines {
child: Child,
rx: mpsc::Receiver<Event>,
/// Pipes whose reader has not reported its end yet.
open: usize,
}
/// What [`Lines::poll`] saw.
pub enum Poll {
Line(Stream, String),
/// A pipe reached its end.
Closed,
/// Nothing arrived within the wait.
Timeout,
/// Every pipe is at its end.
Finished,
}
impl Lines {
/// Waits up to `wait` for the next line. Fails, after killing the child, when `cancel` has fired.
pub fn poll(&mut self, cancel: &CancellationToken, wait: Duration) -> IdeResult<Poll> {
if self.open == 0 {
return Ok(Poll::Finished);
}
if cancel.is_cancelled() {
terminate_tree(&mut self.child, KILL_GRACE);
return Err(IdeError::cancelled());
}
match self.rx.recv_timeout(wait) {
Ok(Event::Line(stream, line)) => Ok(Poll::Line(stream, line)),
Ok(Event::Closed) => {
self.open -= 1;
Ok(Poll::Closed)
}
Err(mpsc::RecvTimeoutError::Timeout) => Ok(Poll::Timeout),
Err(mpsc::RecvTimeoutError::Disconnected) => {
self.open = 0;
Ok(Poll::Finished)
}
}
}
/// Waits for the child to exit and returns whether it did so successfully. Fails, after
/// killing it, when `cancel` fires first.
pub fn finish(mut self, cancel: &CancellationToken) -> IdeResult<bool> {
let status = loop {
if let Some(status) = self.child.try_wait()? {
break status;
}
if cancel.is_cancelled() {
terminate_tree(&mut self.child, KILL_GRACE);
return Err(IdeError::cancelled());
}
std::thread::sleep(Duration::from_millis(10));
};
Ok(status.success())
}
}
+1 -58
View File
@@ -12,8 +12,6 @@ use std::collections::BTreeMap;
pub struct EditorGeneralSettings { pub struct EditorGeneralSettings {
/// Change font size with ⌘ + mouse wheel. /// Change font size with ⌘ + mouse wheel.
pub wheel_zoom: bool, pub wheel_zoom: bool,
/// Scope of ⌘ + mouse wheel font zoom: `active` editor | `all` editors.
pub wheel_zoom_scope: String,
pub markdown_image_folder: String, pub markdown_image_folder: String,
pub markdown_image_name_pattern: String, pub markdown_image_name_pattern: String,
/// Drag-and-drop of selected text inside the editor. /// Drag-and-drop of selected text inside the editor.
@@ -39,7 +37,6 @@ impl Default for EditorGeneralSettings {
fn default() -> Self { fn default() -> Self {
Self { Self {
wheel_zoom: false, wheel_zoom: false,
wheel_zoom_scope: "active".into(),
markdown_image_folder: "assets".into(), markdown_image_folder: "assets".into(),
markdown_image_name_pattern: "image-{timestamp}".into(), markdown_image_name_pattern: "image-{timestamp}".into(),
drag_and_drop: true, drag_and_drop: true,
@@ -197,7 +194,6 @@ pub enum ImportsOnPaste {
#[serde(default, rename_all = "camelCase")] #[serde(default, rename_all = "camelCase")]
pub struct FoldingSettings { pub struct FoldingSettings {
pub show_outline: bool, pub show_outline: bool,
pub outline_visibility: FoldingOutlineVisibility,
pub file_header: bool, pub file_header: bool,
pub imports: bool, pub imports: bool,
pub doc_comments: bool, pub doc_comments: bool,
@@ -205,24 +201,10 @@ pub struct FoldingSettings {
impl Default for FoldingSettings { impl Default for FoldingSettings {
fn default() -> Self { fn default() -> Self {
Self { Self { show_outline: true, file_header: true, imports: true, doc_comments: false }
show_outline: true,
outline_visibility: FoldingOutlineVisibility::Hover,
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. /// Editor › General › Editor Tabs.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")] #[serde(default, rename_all = "camelCase")]
@@ -288,10 +270,6 @@ pub struct SmartKeysSettings {
pub pair_quotes: bool, pub pair_quotes: bool,
pub surround_selection: bool, pub surround_selection: bool,
pub tab_out_of_pair: 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`. /// Reformat on paste: `none` | `indentBlock` | `indentEachLine`.
pub reformat_on_paste: String, pub reformat_on_paste: String,
pub escape_on_paste: bool, pub escape_on_paste: bool,
@@ -311,8 +289,6 @@ impl Default for SmartKeysSettings {
pair_quotes: true, pair_quotes: true,
surround_selection: true, surround_selection: true,
tab_out_of_pair: true, tab_out_of_pair: true,
semicolon_at_statement_end: true,
simultaneous_tag_editing: true,
reformat_on_paste: "indentEachLine".into(), reformat_on_paste: "indentEachLine".into(),
escape_on_paste: true, escape_on_paste: true,
smart_indent: true, smart_indent: true,
@@ -361,8 +337,6 @@ pub struct InlayHintsSettings {
/// Hints of other kinds (chaining, closing labels…). /// Hints of other kinds (chaining, closing labels…).
pub other: bool, pub other: bool,
pub disabled_languages: Vec<String>, 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. /// Code vision: usages above declarations.
pub code_vision_usages: bool, pub code_vision_usages: bool,
/// Code vision: last author of a declaration (VCS blame) beside its usages. /// Code vision: last author of a declaration (VCS blame) beside its usages.
@@ -393,7 +367,6 @@ impl Default for InlayHintsSettings {
parameters: true, parameters: true,
other: true, other: true,
disabled_languages: Vec::new(), disabled_languages: Vec::new(),
code_vision: true,
code_vision_usages: true, code_vision_usages: true,
code_vision_author: true, code_vision_author: true,
code_vision_no_usages: true, code_vision_no_usages: true,
@@ -438,9 +411,6 @@ pub struct TextAttributesOverride {
pub effect: Option<String>, pub effect: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub effect_color: Option<String>, 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). /// Editor › Code Style › <Language> › Tabs and Indents (unset fields inherit).
@@ -467,12 +437,6 @@ pub struct LanguageCodeStyle {
/// Comment Code › Add a space at line comment start. /// Comment Code › Add a space at line comment start.
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub line_comment_add_space: Option<bool>, 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>,
} }
/// Editor › Code Style (General tab + per-language overrides). /// Editor › Code Style (General tab + per-language overrides).
@@ -564,24 +528,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);
}
}
}
+2 -76
View File
@@ -20,72 +20,7 @@ pub struct IdeError {
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(tag = "type", rename_all = "camelCase")] #[serde(tag = "type", rename_all = "camelCase")]
pub enum ErrorData { pub enum ErrorData {
Tool { Tool { tool: String, missing: bool },
tool: String,
missing: bool,
},
/// A non-fast-forward push from the current branch to its configured upstream.
PushRejected {
source: String,
upstream: String,
divergence: Option<Box<PushDivergence>>,
/// Other refs may already have been published in the same push.
#[specta(optional)]
report: Option<Box<PushReport>>,
},
/// Git updated some refs before a later ref or push URL failed.
PushPartiallyApplied {
report: Box<PushReport>,
},
/// A conflicted history replay left an amend commit ready to keep separately.
AmendConflict {
commit: String,
},
}
/// Git's reported result for each destination ref. A remote with several push URLs can
/// report more than one result for the same ref.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
pub struct PushReport {
pub remote: Option<String>,
pub refs: Vec<PushRefResult>,
}
impl PushReport {
pub fn new(remote: Option<String>) -> Self {
Self { remote, refs: Vec::new() }
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
pub struct PushRefResult {
pub reference: String,
pub status: PushRefStatus,
/// The number of commits between the tips Git reports for a fast-forward.
pub commits: Option<u32>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum PushRefStatus {
FastForward,
Forced,
Created,
UpToDate,
Deleted,
}
/// The two tips shown in the rejected-push dialog. A retry must use this lease
/// even if a fetch advances the remote-tracking branch while the dialog is open.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct PushDivergence {
pub source: String,
pub remote: String,
pub target: String,
pub local_tip: String,
pub remote_tip: String,
pub remote_commits: u32,
} }
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
@@ -95,7 +30,7 @@ pub enum ErrorKind {
AlreadyExists, AlreadyExists,
PermissionDenied, PermissionDenied,
InvalidInput, InvalidInput,
/// The requested state is stale; the UI must use the current snapshot. /// Document version mismatch; the UI must resync the full text.
OutOfSync, OutOfSync,
Cancelled, Cancelled,
TimedOut, TimedOut,
@@ -180,13 +115,4 @@ mod tests {
serde_json::json!({"kind":"unavailable","message":"no server","data":null}) serde_json::json!({"kind":"unavailable","message":"no server","data":null})
); );
} }
#[test]
fn older_tracked_push_rejections_need_no_report() {
let data: ErrorData = serde_json::from_str(
r#"{"type":"pushRejected","source":"main","upstream":"origin/main","divergence":null}"#,
)
.unwrap();
assert!(matches!(data, ErrorData::PushRejected { report: None, .. }));
}
} }
-168
View File
@@ -36,30 +36,12 @@ pub enum IdeEvent {
}, },
/// Project window membership or selection changed. /// Project window membership or selection changed.
WindowGroupsChanged, WindowGroupsChanged,
/// A project was loaded or unloaded for the MCP server without a window of its own.
McpBackgroundProjectsChanged,
/// A window entered or left full screen, itself or as a member of a full-screen window group. /// A window entered or left full screen, itself or as a member of a full-screen window group.
WindowFullscreenChanged, WindowFullscreenChanged,
/// This remote window's connection ended or another window took over the session.
RemoteConnectionLost {
host: String,
#[serde(default)]
taken_over: bool,
},
ProjectTrustChanged { ProjectTrustChanged {
root: crate::IpcPath, root: crate::IpcPath,
trusted: bool, trusted: bool,
}, },
/// The project's direnv environment (`.envrc`) could not be loaded, or a file it is read
/// from changed and it can be reloaded.
Direnv {
root: crate::IpcPath,
status: DirenvStatus,
},
/// The project's `flutter daemon` changed state, or a device came or went.
FlutterDevices {
list: FlutterDeviceList,
},
/// Files or directories changed on disk (after debouncing, ignore rules applied). /// Files or directories changed on disk (after debouncing, ignore rules applied).
FsChanged { FsChanged {
created: Vec<crate::IpcPath>, created: Vec<crate::IpcPath>,
@@ -90,21 +72,11 @@ pub enum IdeEvent {
DocDirty { DocDirty {
doc: DocId, doc: DocId,
dirty: bool, dirty: bool,
/// Text version when this transition occurred, including when it was saved.
version: u32,
},
/// An open document's file changed on disk while the buffer had unsaved changes. The buffer
/// keeps them (autosave leaves the file alone); the UI offers to load the disk version.
DocDiskConflict {
doc: DocId,
path: String,
}, },
/// A complete workspace edit can be undone as one operation. /// A complete workspace edit can be undone as one operation.
WorkspaceEditApplied { WorkspaceEditApplied {
id: u32, id: u32,
paths: Vec<crate::IpcPath>, paths: Vec<crate::IpcPath>,
/// Files the edit renamed, as the edit named them: editors open on them follow.
moves: Vec<crate::FileMove>,
/// Made by an agent through the MCP server's tools: undoable like a refactoring, but /// Made by an agent through the MCP server's tools: undoable like a refactoring, but
/// not announced as one. /// not announced as one.
by_agent: bool, by_agent: bool,
@@ -146,10 +118,6 @@ pub enum IdeEvent {
LanguageServer { LanguageServer {
server: ServerId, server: ServerId,
name: String, name: String,
/// What the user sees as the server when another program serves in its place.
#[serde(default)]
#[specta(optional)]
label: Option<String>,
status: ServerStatus, status: ServerStatus,
message: Option<String>, message: Option<String>,
}, },
@@ -170,19 +138,6 @@ pub enum IdeEvent {
server: ServerId, server: ServerId,
kind: LspRefreshKind, kind: LspRefreshKind,
}, },
/// A language server asked the user to choose an action, e.g. Dart's
/// "Renamed field will be invisible in …" warning during a rename. Answered
/// with `lsp_message_request_answer`; the server cancels if we reply null.
LspMessageRequest {
id: u32,
server: String,
message: String,
actions: Vec<String>,
},
/// The request was answered or timed out; every window drops its dialog.
LspMessageRequestDone {
id: u32,
},
TerminalExited { TerminalExited {
terminal: TerminalId, terminal: TerminalId,
code: Option<i32>, code: Option<i32>,
@@ -251,60 +206,6 @@ pub enum AskpassKind {
Confirm, Confirm,
} }
/// A target `flutter run -d <id>` can name, or an Android device adb sees but Flutter can't use yet.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct FlutterDevice {
pub id: String,
pub name: String,
/// `android`, `ios`, `macos`, `web`, …
pub platform_type: Option<String>,
/// `mobile`, `desktop` or `web`.
pub category: Option<String>,
pub emulator: bool,
/// The adb state keeping it from being used (`unauthorized`, `offline`, …).
pub unavailable: Option<String>,
}
/// See [`FlutterDeviceList`].
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(tag = "kind", rename_all = "camelCase", rename_all_fields = "camelCase")]
pub enum FlutterDaemonStatus {
#[default]
Stopped,
/// Started; the first device discovery has not finished.
Starting,
Ready,
/// No `flutter` executable on the search path.
NotInstalled,
/// The daemon could not start or exited: what it printed last. It is not restarted on its own.
Failed {
message: String,
},
}
/// The project's Flutter devices, best default first.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct FlutterDeviceList {
pub status: FlutterDaemonStatus,
pub devices: Vec<FlutterDevice>,
}
/// See [`IdeEvent::Direnv`].
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(tag = "kind", rename_all = "camelCase", rename_all_fields = "camelCase")]
pub enum DirenvStatus {
/// `direnv` is not installed (on the search path).
NotInstalled,
/// direnv refuses the `.envrc` until the user approves it with `direnv allow`.
Blocked,
/// `direnv export` failed or took too long: what it printed last.
Failed { message: String },
/// `.envrc`, `flake.nix` or `flake.lock` (a file name in the project root) changed.
Changed { file: String },
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
pub enum ServerStatus { pub enum ServerStatus {
@@ -325,10 +226,6 @@ pub enum LspRefreshKind {
InlayHints, InlayHints,
SemanticTokens, SemanticTokens,
CodeLens, CodeLens,
/// An import or classpath update may have changed inheritance search results.
Inheritance,
/// The Dart server published a document's Flutter outline.
FlutterOutline,
} }
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
@@ -384,21 +281,6 @@ pub enum DebugEvent {
change_type: String, change_type: String,
message: String, message: String,
}, },
/// `flutter debug_adapter`'s `flutter.appStarted` event (launch and attach): the session is
/// a Flutter app that can take a hot reload now. The plain Dart adapter never sends it.
FlutterAppStarted,
/// The VM Service of a Flutter session's app, which DevTools connects to.
FlutterVmService {
uri: String,
/// The Flutter device the app runs on.
device: Option<String>,
},
/// Flutter's inspector selected a widget: its source, 0-based.
FlutterNavigate {
path: crate::IpcPath,
line: u32,
column: u32,
},
/// The session's capabilities changed after it started: fetch them again. /// The session's capabilities changed after it started: fetch them again.
Capabilities, Capabilities,
/// The adapter's `invalidated` event: what it shows for `areas` (`all`, `stacks`, `threads`, /// The adapter's `invalidated` event: what it shows for `areas` (`all`, `stacks`, `threads`,
@@ -409,56 +291,6 @@ pub enum DebugEvent {
JvmBackend { JvmBackend {
state: JvmBackendState, state: JvmBackendState,
}, },
/// A step in the life of one request of a debugged page.
JsNetwork {
event: JsNetworkEvent,
},
/// The adapter does not report the requests of this page: there will be no `JsNetwork`.
JsNetworkUnavailable,
}
/// Which step of a request a [`JsNetworkEvent`] reports.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum JsNetworkKind {
Request,
Response,
Finished,
Failed,
}
/// The script frame that made a request, where the browser ran it (0-based line and column).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct JsInitiator {
pub function: String,
pub url: String,
pub line: u32,
pub column: u32,
}
/// What a debugged page's browser reports about a request, reduced to what the Network view
/// shows. Events of one request share `request_id`; each kind fills its own fields.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct JsNetworkEvent {
pub kind: JsNetworkKind,
pub request_id: String,
/// The browser's monotonic clock, comparable between the events of a page.
pub timestamp_ms: u64,
/// Request and response.
pub url: Option<String>,
pub method: Option<String>,
/// `Fetch`, `XHR`, `Script`, `Document`, …
pub resource_type: Option<String>,
pub status: Option<u16>,
pub mime_type: Option<String>,
/// The request's headers, or the response's.
pub headers: BTreeMap<String, String>,
/// Bytes received over the network, once finished.
pub encoded_length: Option<u64>,
pub error_text: Option<String>,
pub initiator: Option<JsInitiator>,
} }
/// The backend that reads a debugged JVM's objects (instances, fields, referrers). /// The backend that reads a debugged JVM's objects (instances, fields, referrers).
+1 -3
View File
@@ -14,8 +14,7 @@ pub fn inside_git_repo(dir: &Path) -> bool {
dir.ancestors().any(|d| d.join(".git").exists() || d.join(".jj").exists()) dir.ancestors().any(|d| d.join(".git").exists() || d.join(".jj").exists())
} }
/// IDEA's default list, plus `.jj`, rope's `.ropeproject` (pylsp-rope creates it in the /// IDEA's default list, plus `.jj` and the Windows shell files.
/// project root) and the Windows shell files.
pub const DEFAULT_IGNORED_NAMES: &[&str] = &[ pub const DEFAULT_IGNORED_NAMES: &[&str] = &[
"*.pyc", "*.pyc",
"*.pyo", "*.pyo",
@@ -26,7 +25,6 @@ pub const DEFAULT_IGNORED_NAMES: &[&str] = &[
".git", ".git",
".hg", ".hg",
".jj", ".jj",
".ropeproject",
".svn", ".svn",
"CVS", "CVS",
"__pycache__", "__pycache__",
@@ -71,11 +71,6 @@ pub struct SpellingSettings {
pub project_words: Vec<String>, pub project_words: Vec<String>,
/// Custom dictionaries: plain word lists or Hunspell `.dic` files. /// Custom dictionaries: plain word lists or Hunspell `.dic` files.
pub custom_dictionaries: Vec<String>, pub custom_dictionaries: Vec<String>,
/// Where "Save '…' to dictionary" writes: `project`, `application`, or a
/// `spelling.customDictionaries` entry verbatim; empty (the default) is
/// project when one is open, application otherwise.
#[specta(optional)]
pub default_dictionary: Option<String>,
} }
/// Changes to one inspection; absent fields keep the inspection's defaults. /// Changes to one inspection; absent fields keep the inspection's defaults.
-122
View File
@@ -1,122 +0,0 @@
//! Binary arguments of IPC commands travel as base64 text: [`IpcBytes`] is a `Vec<u8>` that
//! serializes as a standard padded base64 string and is a plain `string` in the generated
//! bindings.
//!
//! A plain `Vec<u8>` is a JSON array of numbers, 3.6 times the size of the bytes, and parsing it
//! into a `serde_json::Value` (the remote protocol and Tauri both do) takes about 50 times the
//! bytes in memory: 20 MB become about 1 GB. Base64 is 1.33 times the size and one string.
use base64::Engine;
use base64::engine::general_purpose::STANDARD;
use serde::de::{self, Visitor};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::fmt;
use std::ops::Deref;
/// A binary argument or result of an IPC command.
#[derive(Clone, Default, PartialEq, Eq, specta::Type)]
#[specta(transparent)]
pub struct IpcBytes(#[specta(type = String)] pub Vec<u8>);
impl IpcBytes {
pub fn into_vec(self) -> Vec<u8> {
self.0
}
}
impl fmt::Debug for IpcBytes {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "IpcBytes({} bytes)", self.0.len())
}
}
impl Serialize for IpcBytes {
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
s.serialize_str(&STANDARD.encode(&self.0))
}
}
impl<'de> Deserialize<'de> for IpcBytes {
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
struct Base64;
impl Visitor<'_> for Base64 {
type Value = IpcBytes;
fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("a base64 string")
}
fn visit_str<E: de::Error>(self, v: &str) -> Result<IpcBytes, E> {
STANDARD.decode(v).map(IpcBytes).map_err(|e| E::custom(format!("invalid base64: {e}")))
}
}
d.deserialize_str(Base64)
}
}
impl Deref for IpcBytes {
type Target = [u8];
fn deref(&self) -> &[u8] {
&self.0
}
}
impl From<Vec<u8>> for IpcBytes {
fn from(bytes: Vec<u8>) -> Self {
Self(bytes)
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::{Value, json};
fn round_trip(bytes: Vec<u8>) {
let value = serde_json::to_value(IpcBytes(bytes.clone())).unwrap();
let text = value.as_str().expect("serializes as a string");
assert_eq!(text.len(), bytes.len().div_ceil(3) * 4);
assert_eq!(serde_json::from_value::<IpcBytes>(value).unwrap().into_vec(), bytes);
}
#[test]
fn round_trips_empty_every_byte_and_large_input() {
round_trip(Vec::new());
round_trip((0..=255).collect());
round_trip((0..=255).rev().cycle().take(5 * 1024 * 1024 + 1).collect());
}
#[test]
fn round_trips_through_a_json_document() {
let bytes: Vec<u8> = (0..=255).collect();
let text = serde_json::to_string(&json!({ "data": IpcBytes(bytes.clone()) })).unwrap();
#[derive(Deserialize)]
struct Args {
data: IpcBytes,
}
assert_eq!(serde_json::from_str::<Args>(&text).unwrap().data.into_vec(), bytes);
}
/// The old wire form of a `Vec<u8>`: 3.6 times the bytes. The string must stay near 4/3.
#[test]
fn serialized_form_is_a_string_about_a_third_larger_than_the_bytes() {
let bytes: Vec<u8> = (0..=255).cycle().take(1_000_000).collect();
let json = serde_json::to_string(&IpcBytes(bytes.clone())).unwrap();
assert!(json.starts_with('"') && json.ends_with('"'));
assert!(json.len() <= bytes.len().div_ceil(3) * 4 + 2, "{} bytes for {}", json.len(), bytes.len());
let as_array = serde_json::to_string(&bytes).unwrap();
assert!(json.len() * 2 < as_array.len(), "{} vs {}", json.len(), as_array.len());
}
#[test]
fn rejects_what_is_not_base64() {
for bad in [json!([1, 2, 3]), json!(7), Value::Null, json!("not base64!"), json!("QQ"), json!("QQ=a")] {
assert!(serde_json::from_value::<IpcBytes>(bad.clone()).is_err(), "{bad}");
}
}
#[test]
fn debug_does_not_print_the_bytes() {
assert_eq!(format!("{:?}", IpcBytes(vec![0; 3])), "IpcBytes(3 bytes)");
}
}
+2 -63
View File
@@ -1,10 +1,8 @@
//! JSON with comments (`devcontainer.json`, `deno.jsonc`, `tsconfig.json`): turned //! JSON with comments (`devcontainer.json`, `deno.jsonc`, `tsconfig.json`): turned
//! into plain JSON for `serde_json`. //! into plain JSON for `serde_json`.
/// Strips `//` and `/* */` comments, trailing commas and a leading byte order mark (Visual /// Strips `//` and `/* */` comments and trailing commas so JSONC parses as JSON.
/// Studio writes one into `launchSettings.json`) so JSONC parses as JSON.
pub fn strip(src: &str) -> String { pub fn strip(src: &str) -> String {
let src = src.strip_prefix('\u{feff}').unwrap_or(src);
let mut out = String::with_capacity(src.len()); let mut out = String::with_capacity(src.len());
let mut chars = src.chars().peekable(); let mut chars = src.chars().peekable();
let mut in_str = false; let mut in_str = false;
@@ -40,10 +38,6 @@ pub fn strip(src: &str) -> String {
if prev == '*' && n == '/' { if prev == '*' && n == '/' {
break; break;
} }
// Keep the comment's line breaks so parse errors report the original line.
if n == '\n' {
out.push('\n');
}
prev = n; prev = n;
} }
} }
@@ -69,7 +63,7 @@ pub fn strip(src: &str) -> String {
in_str = true; in_str = true;
cleaned.push(c); cleaned.push(c);
} else if c == ',' { } else if c == ',' {
let next = bytes[i + 1..].iter().find(|ch| !ch.is_ascii_whitespace()); let next = bytes[i + 1..].iter().find(|ch| !ch.is_whitespace());
if !matches!(next, Some('}') | Some(']')) { if !matches!(next, Some('}') | Some(']')) {
cleaned.push(c); cleaned.push(c);
} }
@@ -93,59 +87,4 @@ mod tests {
assert_eq!(v["url"], "https://x.dev//y /* no */"); assert_eq!(v["url"], "https://x.dev//y /* no */");
assert_eq!(v["q"], "say \"hi\","); assert_eq!(v["q"], "say \"hi\",");
} }
#[test]
fn drops_a_byte_order_mark() {
let v: serde_json::Value = serde_json::from_str(&strip("\u{feff}{ \"a\": 1 }")).unwrap();
assert_eq!(v["a"], 1);
}
#[test]
fn keeps_line_breaks_of_block_comments_so_errors_report_the_original_line() {
assert_eq!(strip("{\"a\"/*\n\n*/:x}"), "{\"a\"\n\n:x}");
let err = serde_json::from_str::<serde_json::Value>(&strip("{\"a\"/*\n\n*/:x}")).unwrap_err();
assert_eq!(err.line(), 3);
// A comment is whitespace, not a join: `1 2` stays invalid.
assert!(serde_json::from_str::<serde_json::Value>(&strip("1/*\n*/2")).is_err());
}
#[test]
fn line_comments_keep_their_line_break_and_may_end_the_input() {
assert_eq!(strip("{\"a\":1} // tail"), "{\"a\":1} ");
assert_eq!(strip("// a\r\n{\"a\":1}"), "\n{\"a\":1}");
assert_eq!(strip("[1, // c\n2]"), "[1, \n2]");
}
#[test]
fn unterminated_block_comment_drops_the_rest() {
assert_eq!(strip("{\"a\":1}/* open"), "{\"a\":1}");
assert_eq!(strip("/*"), "");
assert_eq!(strip("/*/ x"), "");
assert_eq!(strip("/**/{}"), "{}");
assert_eq!(strip("/***/{}"), "{}");
}
#[test]
fn comment_markers_inside_strings_survive_including_after_escapes() {
let src = "{\"a\":\"\\\\\",\"b\":\"//x\",\"c\":\"/*y*/\",\"d\":\"é,\u{1F600}\"} // é";
let v: serde_json::Value = serde_json::from_str(&strip(src)).unwrap();
assert_eq!(v, serde_json::json!({"a": "\\", "b": "//x", "c": "/*y*/", "d": "é,\u{1F600}"}));
}
#[test]
fn trailing_commas_are_dropped_across_whitespace_and_comments_only_before_a_closer() {
assert_eq!(strip("[1,2, ]"), "[1,2 ]");
assert_eq!(strip("[1,\r\n]"), "[1\r\n]");
assert_eq!(strip("[1,/*c*/]"), "[1]");
assert_eq!(strip("[1,//c\n]"), "[1\n]");
assert_eq!(strip("[1,/*c*/ ,]"), "[1, ]");
assert_eq!(strip("{\"a\":\"x,}\"}"), "{\"a\":\"x,}\"}");
assert_eq!(strip("[1,2]"), "[1,2]");
}
#[test]
fn only_json_whitespace_may_separate_a_trailing_comma_from_its_closer() {
// U+00A0 is not JSON whitespace: the comma stays and serde_json reports it.
assert_eq!(strip("[1,\u{a0}]"), "[1,\u{a0}]");
}
} }
-6
View File
@@ -4,7 +4,6 @@
//! feature crates depend on `ide-core` and never on each other's internals. //! feature crates depend on `ide-core` and never on each other's internals.
//! All IPC-facing types derive `specta::Type`, which generates `src/bindings.ts`. //! All IPC-facing types derive `specta::Type`, which generates `src/bindings.ts`.
pub mod cli_process;
pub mod editor_settings; pub mod editor_settings;
pub mod error; pub mod error;
pub mod event; pub mod event;
@@ -13,16 +12,13 @@ pub mod ids;
pub mod ignored; pub mod ignored;
pub mod input; pub mod input;
pub mod inspection_settings; pub mod inspection_settings;
pub mod ipc_bytes;
pub mod ipc_path; pub mod ipc_path;
pub mod java_runtime; pub mod java_runtime;
pub mod jsonc; pub mod jsonc;
pub mod memory;
pub mod output_encoding; pub mod output_encoding;
pub mod platform; pub mod platform;
pub mod process; pub mod process;
pub mod project_dir; pub mod project_dir;
pub mod project_env;
pub mod project_roots; pub mod project_roots;
pub mod proxy_settings; pub mod proxy_settings;
pub mod real_path; pub mod real_path;
@@ -32,7 +28,6 @@ pub mod task;
pub mod text; pub mod text;
pub mod tool_path; pub mod tool_path;
pub mod updates; pub mod updates;
pub mod utf8;
pub mod version_managers; pub mod version_managers;
pub mod workflow_settings; pub mod workflow_settings;
pub mod wsl; pub mod wsl;
@@ -40,7 +35,6 @@ pub mod wsl;
pub use error::{IdeError, IdeResult}; pub use error::{IdeError, IdeResult};
pub use event::{EventSink, IdeEvent, NullSink, SharedSink}; pub use event::{EventSink, IdeEvent, NullSink, SharedSink};
pub use ids::*; pub use ids::*;
pub use ipc_bytes::IpcBytes;
pub use ipc_path::IpcPath; pub use ipc_path::IpcPath;
pub use text::*; pub use text::*;
pub use tokio_util::sync::CancellationToken; pub use tokio_util::sync::CancellationToken;
-20
View File
@@ -1,20 +0,0 @@
//! Returning freed heap pages to the OS.
/// Hands pages the allocator has freed but kept back to the OS. Call after a burst of
/// short-lived allocations (a full index scan); until then they still count towards the
/// process's memory footprint.
pub fn release_free_pages() {
#[cfg(target_os = "macos")]
{
unsafe extern "C" {
fn malloc_zone_pressure_relief(zone: *mut std::ffi::c_void, goal: usize) -> usize;
}
// SAFETY: a null zone covers every zone; a zero goal releases as much as possible.
unsafe { malloc_zone_pressure_relief(std::ptr::null_mut(), 0) };
}
#[cfg(all(target_os = "linux", target_env = "gnu"))]
// SAFETY: malloc_trim only returns free memory to the OS.
unsafe {
libc::malloc_trim(0);
}
}
Loaded 100 of 3874 files, more files were not shown because too many files have changed in this diff. Show more