дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-05 09:41:34 +02:00
Порівняти коміти
1
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
1634cd8e84 |
No files matched your search
@@ -1,129 +0,0 @@
|
||||
---
|
||||
name: pr
|
||||
description: Prepare and open an OpenIDEA pull request that a maintainer can accept from its description — scope check, the checks CI runs, evidence chosen by the kind of change, UX consistency review, and a filled-in template. Use before opening or updating a PR ("提 pr", "open a PR", "写 PR 描述", "准备验收证据").
|
||||
---
|
||||
|
||||
# Open a pull request with evidence
|
||||
|
||||
A reviewer should be able to accept the PR from its description: what changed, why, and proof
|
||||
that it works and didn't break its neighbours. Evidence is the part people skip; it is required.
|
||||
|
||||
## 1. Scope
|
||||
|
||||
- One problem per PR. If the description needs more than 2–4 sentences, split it.
|
||||
- `Closes #<n>` when it resolves an issue. Read the issue's comments first: a maintainer may
|
||||
already have decided how it should behave.
|
||||
- The diff contains only what the problem needs: no drive-by refactors, formatting of untouched
|
||||
files, generated files you didn't need to regenerate, or local IDE state (`.openidea/`).
|
||||
- A product decision you can't make (layout or navigation restructure, a changed default, an
|
||||
unclear expected behaviour) → ask in the issue, label `needs-decision`, stop.
|
||||
- Title in Conventional Commits, written as the commit you want on `main`:
|
||||
`fix(editor): keep the caret visible after folding`. It describes the change, not the
|
||||
process; no references to screenshots, other products or "parity".
|
||||
|
||||
## 2. Checks
|
||||
|
||||
Run what CI runs for the parts you touched (`AGENTS.md` § Before opening a PR). Run long checks
|
||||
one at a time. Paste the command and its result line (`test result: ok. 412 passed`,
|
||||
`Tests 87 passed`), not "tests pass".
|
||||
|
||||
Easy to miss:
|
||||
|
||||
| You touched | Also run |
|
||||
| --------------------------------------------------------------- | ------------------------------------------------------------------------------------ |
|
||||
| Any `.ts`/`.tsx`, including tests | `pnpm typecheck` |
|
||||
| A feature's UI | every spec under `e2e/` whose name contains the feature |
|
||||
| New regex in frontend code | `pnpm vitest run src/platform/webkitCompatibility.test.ts` |
|
||||
| Text catalog keys | `pnpm vitest run src/platform/locales/textCatalog.test.ts src/platform/i18n.test.ts` |
|
||||
| `tokens.css` | `pnpm gen:theme-docs`, then the full `pnpm test` |
|
||||
| Moved or removed exports | `pnpm knip` |
|
||||
| A `pub fn` signature | `cargo test -p <crate>` (all targets), or workspace clippy |
|
||||
| A new crate dependency, or imports in files the smoke runs load | `pnpm vitest run scripts/smoke-paths.test.ts` |
|
||||
| IPC types | `pnpm gen:bindings`, commit `src/bindings.ts` |
|
||||
| `wit/` or the plugin SDK | `plugins/build.sh`, commit the rebuilt `dist/` |
|
||||
|
||||
## 3. Evidence
|
||||
|
||||
Pick every row that applies. Evidence must come from the final commit of the branch; re-take it
|
||||
after review changes that affect it.
|
||||
|
||||
| Change | Evidence |
|
||||
| ------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| Bug fix | A test that fails on `main` and passes on the branch (name it), or exact steps from a fresh start with the before/after result |
|
||||
| Visible UI | `before.png` / `after.png` at the same state and window size. Every theme the change touches (at least Islands Light and Islands Dark when colours, borders or icons change). The narrow case when width matters |
|
||||
| Interaction: multi-step, drag and drop, keyboard, focus, animation | A short recording (GIF/MP4), or numbered screenshots of each step |
|
||||
| Keyboard shortcut or action | Where it appears (Find Action, menu, keymap settings) and that it doesn't clash in the default keymaps |
|
||||
| Code intelligence / language support | Which `fixtures/` project, `cargo test -p ide-host --test language_smoke -- --ignored --exact <language>` output; for Java, `pnpm eval --only <id>` numbers before/after |
|
||||
| Run / debug | `pnpm smoke smoke/run.test.ts -t <language>` or `smoke/debug.test.ts`, plus a screenshot of the Run/Debug tool window |
|
||||
| Performance | Before/after numbers on the same machine and build type (`pnpm perf`, `pnpm perf:rust`, or the exact measurement), and evidence the results are identical: a fast path must return the same results or fall back |
|
||||
| Windows / Linux only | The platform's CI job, and a screenshot or log from a real machine. Say plainly if you couldn't run it on that platform |
|
||||
| Backend / IPC | Test output; logs for behaviour tests can't reach |
|
||||
| Remote development / containers / WSL | The flow against a real `openidea-server` host or container, with a screenshot or log |
|
||||
| Plugin API / `wit/` | A sample plugin exercising the change, and the rebuilt `dist/` |
|
||||
| Settings / persisted data / migrations | Start from data written by the previous release and show it still loads and behaves the same |
|
||||
| Security fix | A test for the attack case. Describe the class of problem only; follow `SECURITY.md` for anything not yet public |
|
||||
| Copy, docs, pure refactor | The commands run, and "No visible change" / "no behaviour change" stated |
|
||||
|
||||
Also state what else the change could affect (other languages, platforms, entry points such as
|
||||
menu / context menu / shortcut, other themes) and how you checked each.
|
||||
|
||||
How to capture:
|
||||
|
||||
- Use the `verify` skill to drive the app and take screenshots. Before: on `main` (or with the
|
||||
fix reverted). After: on the branch, same state and window size.
|
||||
- Crop to the relevant area when the window is large, but keep enough context to locate it.
|
||||
- Drag screenshots and recordings into the PR description on GitHub. Never commit them.
|
||||
- No real credentials, tokens, private repository names or personal paths in screenshots or logs.
|
||||
|
||||
## 4. UX consistency
|
||||
|
||||
For any change users can see, review it against `DESIGN.md`, `PRODUCT.md` and
|
||||
`docs/en/contribute/guidelines/ui.mdx` before taking the "after" screenshots:
|
||||
|
||||
- Tokens only; spacing on the `--space-*` scale; icons from `src/ui/icons.tsx`; no emoji.
|
||||
- Built from `src/ui/` primitives and workbench contributions; it looks like its neighbours
|
||||
(same row height, font size, padding, hover/selection, empty state) rather than new.
|
||||
- Same action, same name, place and shortcut as elsewhere in the IDE.
|
||||
- Keyboard reachable, visible focus, focus returns sensibly; `aria-label` on icon buttons.
|
||||
- Every new string in `en.json` and `zh.json`; long translations don't break the layout.
|
||||
- Light and dark, default and narrow widths all look right.
|
||||
- The Impeccable design skills can help critique and polish; they read `DESIGN.md`,
|
||||
`PRODUCT.md` and `.impeccable/`.
|
||||
|
||||
A layout or navigation restructure needs a maintainer decision first (§ 1).
|
||||
|
||||
## 5. Description
|
||||
|
||||
Fill in `.github/pull_request_template.md`; keep it short and plain:
|
||||
|
||||
```markdown
|
||||
Closes #123
|
||||
|
||||
## What and why
|
||||
|
||||
<The change a user notices, and the root cause. 2–4 sentences.>
|
||||
|
||||
## How it was verified
|
||||
|
||||
- [x] Bug fix: `pnpm vitest run src/features/editor/folding.test.ts` — the new
|
||||
`keeps caret visible after fold` fails on main, passes here (12 passed)
|
||||
- [x] Visible UI: before / after (Islands Light, Islands Dark)
|
||||
<screenshots>
|
||||
- `pnpm typecheck`, `pnpm lint`, `pnpm e2e e2e/editor-folding.spec.ts` — all pass
|
||||
- Also affected: folding from the gutter and from ⌘- — both checked in the app
|
||||
|
||||
## Review focus
|
||||
|
||||
<Optional.>
|
||||
```
|
||||
|
||||
The `PR check` workflow labels the PR `needs-info` when **How it was verified** is empty, or when
|
||||
the PR changes UI files and the section has no screenshot or recording and doesn't say
|
||||
"No visible change".
|
||||
|
||||
## 6. Before you push
|
||||
|
||||
- Re-read the diff as the reviewer: anything unrelated, debug output, commented-out code,
|
||||
leftover TODOs?
|
||||
- Rebased on current `main`; checks re-run if the rebase changed anything they cover.
|
||||
- Open as draft while evidence is missing; mark ready once it's in.
|
||||
@@ -1,59 +0,0 @@
|
||||
---
|
||||
name: verify
|
||||
description: Build, launch and drive the OpenIDEA desktop app through the Tauri MCP bridge to verify a change at runtime.
|
||||
---
|
||||
|
||||
# Verify OpenIDEA in the running app
|
||||
|
||||
## Launch
|
||||
|
||||
- Run the app from the worktree that holds the change: `pnpm tauri dev` in the background, logging
|
||||
into your task's scratch subdirectory. Use `pnpm dev:app` instead when your checks call
|
||||
`window.__TAURI__` from `execute_js`. The wrapper gives each worktree its own app identity, data,
|
||||
settings and Vite port, so other worktrees and the installed app don't interfere. If it reports a
|
||||
session already running for this worktree, reuse that one.
|
||||
- Once the app is up, `pnpm dev:status` lists this worktree's MCP bridges. Pass the reported
|
||||
`appIdentifier` (the port) on every `mcp__tauri__*` call. The MCP server is shared between
|
||||
sessions: never `driver_session stop` without an `appIdentifier`, and re-check `document.title` /
|
||||
`location.href` before acting if anything looks off.
|
||||
- Make sure the binary contains the change: a session already running for this worktree may be an
|
||||
older build. Restart it after Rust changes; frontend changes reload through Vite.
|
||||
- After the app restarts, `driver_session start` again for your port (a stale session says "Already connected").
|
||||
- If the `pnpm tauri dev` process exits while the app window stays open, Vite is gone and any webview
|
||||
reload shows an empty `#root`. Stop that app and start the session again.
|
||||
- Stop everything you started when done and nothing else; never use process-name kills.
|
||||
|
||||
## Driving
|
||||
|
||||
- `manage_window focus` before screenshots / timing-sensitive steps: a background window throttles timers
|
||||
(debounced LSP / VCS refreshes stall, `setTimeout` promises in `execute_js` time out) and native
|
||||
screenshots come back black.
|
||||
- Settings is a separate native window `settings-main`; pass `windowId`, focus it before screenshotting.
|
||||
- CodeMirror / xterm ignore MCP `type`. Focus the element, then `document.execCommand('insertText', false, text)`.
|
||||
For xterm Enter, dispatch a `keydown` (`key: 'Enter', keyCode: 13`) on `.xterm-helper-textarea`.
|
||||
- MCP clicks arrive with `event.detail === 0`; CodeMirror treats them as line-select clicks. Set the caret
|
||||
through the view instead: `document.querySelector('.cm-content').cmTile.view`.
|
||||
- MCP `text` strategy can resolve to a hidden node; prefer coordinates (CSS px = image px × 0.9) or CSS selectors.
|
||||
- CSS-module edits often trigger a full page reload in dev: dialogs close, Run sessions and terminal
|
||||
scrollback reset, and each reload spawns a fresh shell. Re-open what you were testing.
|
||||
|
||||
## Evidence
|
||||
|
||||
- For UI or interaction changes, capture `before.png` (on `main` or with the fix reverted) and
|
||||
`after.png` at the same state and window size, into your task's scratch subdirectory. Multi-step
|
||||
flows: a numbered series (`after-1.png`, `after-2.png`, ...). When colours, borders or icons
|
||||
change, take each in Islands Light and Islands Dark. The `pr` skill lists what evidence each
|
||||
kind of change needs.
|
||||
- Report the absolute paths; they go into the PR's **How it was verified** section and the triage
|
||||
acceptance entry. Never commit screenshots to the feature branch.
|
||||
|
||||
## Fixture
|
||||
|
||||
`fixtures/` has sample projects (go-app, rust-app, ts-app, kotlin-gradle, polyglot). Copy one into
|
||||
your scratch directory before editing it, and don't commit the IDE state it creates (`.openidea/`).
|
||||
|
||||
## Flows worth driving
|
||||
|
||||
⌘⇧O Goto File · ⌘⇧F Find in Files (preview scroll + highlight) · ⌘⇧A Find Action · editor edit/undo/autosave ·
|
||||
Terminal (Unicode, venv) · Commit view at the default narrow width · Problems · Run → Stop · Project view
|
||||
New / Delete (nested `a/b.txt` names) · ⌘, Settings search (+ Keymap filter) · Git Log on a repo without commits.
|
||||
@@ -1 +0,0 @@
|
||||
../../.agents/skills/pr
|
||||
@@ -1 +0,0 @@
|
||||
../../.agents/skills/verify
|
||||
@@ -11,10 +11,3 @@ package(=ide-clipboard) & (
|
||||
)
|
||||
'''
|
||||
test-group = "windows-clipboard"
|
||||
|
||||
# The Subversion tests run svn against throwaway servers: none should take minutes. A test
|
||||
# that hangs (a server left stopped) is ended after 5 minutes instead of waiting for svn's own
|
||||
# timeout.
|
||||
[[profile.default.overrides]]
|
||||
filter = 'package(=ide-svn) | (package(=ide-host) & (binary(=svn) | binary(=ij_svn_roots)))'
|
||||
slow-timeout = { period = "60s", terminate-after = 5 }
|
||||
Бінарний файл не відображається.
|
Після Ширина: | Висота: | Розмір: 169 KiB |
Бінарний файл не відображається.
|
До Ширина: | Висота: | Розмір: 179 KiB |
@@ -6,6 +6,4 @@ updates:
|
||||
directory: /
|
||||
schedule: { interval: weekly }
|
||||
groups:
|
||||
# tauri-action builds and uploads the release, so its updates come as their own PR and are
|
||||
# merged after a draft release has gone through with them.
|
||||
actions: { patterns: ["*"], exclude-patterns: ["tauri-apps/tauri-action"] }
|
||||
actions: { patterns: ["*"] }
|
||||
@@ -7,20 +7,11 @@
|
||||
|
||||
## How it was verified
|
||||
|
||||
<!-- Required, from the final version of this branch. Commands you actually ran and
|
||||
their results; what else this could affect and how you checked it still works.
|
||||
Then the evidence for each kind of change this PR makes (AGENTS.md § Issues & PRs):
|
||||
|
||||
- Bug fix: a test that fails on main and passes here, or exact repro steps
|
||||
- Visible UI: before/after screenshots, same state and size; each theme touched
|
||||
- Interaction (multi-step, drag, keyboard, focus): a recording
|
||||
- Code intelligence / run / debug: language_smoke or smoke output on a fixture
|
||||
- Performance: before/after numbers on the same machine, and the results unchanged
|
||||
- Windows/Linux only: CI job plus a screenshot or log from a real machine
|
||||
- Settings / persisted data: starting from the previous version's data
|
||||
- Copy, docs, refactor, no UI change: write "No visible change"
|
||||
|
||||
Drag screenshots and recordings in here; don't commit them. -->
|
||||
<!-- Required. Commands you actually ran and their results; what else this could
|
||||
affect and how you checked it still works.
|
||||
Visible UI changes: before/after screenshots (not for removed UI or copy-only
|
||||
changes). Multi-step interactions: a recording.
|
||||
Backend changes: logs or command output. -->
|
||||
|
||||
## Review focus
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ BASEDPYRIGHT=1.40.2
|
||||
RUFF=0.17.3
|
||||
GOPLS=v0.24.0
|
||||
JDTLS=1.63.0-202610191322
|
||||
KOTLIN_LSP=271.3588.0
|
||||
KOTLIN_LSP=271.2085.0
|
||||
GRADLE=8.14.3
|
||||
INTELEPHENSE=1.18.5
|
||||
# The JDK projects compile against (JAVA_HOME): library navigation opens its sources.
|
||||
|
||||
@@ -106,9 +106,8 @@ jobs:
|
||||
if: needs.changes.outputs.rust == 'true'
|
||||
permissions:
|
||||
contents: read
|
||||
# A Windows build that misses the Rust cache spends ~50 minutes compiling before the tests run;
|
||||
# on macOS clippy plus the test build alone take ~45 minutes.
|
||||
timeout-minutes: ${{ matrix.os == 'ubuntu-latest' && 60 || 75 }}
|
||||
# A Windows build that misses the Rust cache spends ~50 minutes compiling before the tests run.
|
||||
timeout-minutes: ${{ matrix.os == 'windows-latest' && 75 || 60 }}
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
@@ -148,26 +147,11 @@ jobs:
|
||||
fi
|
||||
- uses: taiki-e/install-action@073e1fd0bc889c9aee68dbaaa927cde1b5653a83 # v2.90.11
|
||||
with: { tool: nextest }
|
||||
# ide-sdk's .NET status test and crates/ide-coverage/tests/dotnet_cli.rs run the real `dotnet`
|
||||
# CLI; with CI set they fail, not skip, when it is missing.
|
||||
- uses: actions/setup-dotnet@26b0ec14cb23fa6904739307f278c14f94c95bf1 # v5.4.0
|
||||
with:
|
||||
dotnet-version: 10.0.x
|
||||
- name: Linux deps
|
||||
if: runner.os == 'Linux'
|
||||
run: |
|
||||
pkgs=(libwebkit2gtk-4.1-dev libayatana-appindicator3-dev librsvg2-dev libxdo-dev libssl-dev patchelf subversion sqlite3)
|
||||
pkgs=(libwebkit2gtk-4.1-dev libayatana-appindicator3-dev librsvg2-dev libxdo-dev libssl-dev patchelf)
|
||||
dpkg -s "${pkgs[@]}" >/dev/null 2>&1 || { sudo apt-get update && sudo apt-get install -y "${pkgs[@]}"; }
|
||||
# The Subversion tests run the real svn, svnadmin and svnserve (and sqlite3, to write a
|
||||
# working copy's database); with CI set they fail instead of skipping when these are
|
||||
# missing. Linux gets them with the deps above; macOS has sqlite3. Windows runners skip them.
|
||||
- name: Subversion (macOS)
|
||||
if: runner.os == 'macOS'
|
||||
run: command -v svnadmin >/dev/null || brew install subversion
|
||||
- name: Subversion version
|
||||
if: runner.os != 'Windows'
|
||||
shell: bash
|
||||
run: svn --version --quiet && svnadmin --version --quiet && svnserve --version --quiet && sqlite3 --version
|
||||
# tauri-build checks that frontendDist exists.
|
||||
- run: pnpm install --frozen-lockfile && mkdir -p dist
|
||||
shell: bash
|
||||
@@ -217,47 +201,14 @@ jobs:
|
||||
with:
|
||||
path: ${{ runner.temp }}/jbuild-maven-repository
|
||||
key: ${{ steps.jbuild-maven-cache.outputs.cache-primary-key }}
|
||||
# python_yappi.rs profiles real runs. Self-hosted runners have no setup-python; without
|
||||
# YAPPI_PYTHON those tests return early.
|
||||
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0
|
||||
if: runner.environment == 'github-hosted'
|
||||
id: yappi-python
|
||||
with: { python-version: "3.12", update-environment: false }
|
||||
- name: Install yappi for the Python profiler tests
|
||||
if: steps.yappi-python.outputs.python-path != ''
|
||||
shell: bash
|
||||
env:
|
||||
PYTHON: ${{ steps.yappi-python.outputs.python-path }}
|
||||
run: |
|
||||
"$PYTHON" -m venv "$RUNNER_TEMP/yappi-venv"
|
||||
venv_py="$RUNNER_TEMP/yappi-venv/bin/python"
|
||||
[ -x "$venv_py" ] || venv_py="$RUNNER_TEMP/yappi-venv/Scripts/python.exe"
|
||||
"$venv_py" -m pip install yappi==1.7.6
|
||||
echo "YAPPI_PYTHON=$venv_py" >> "$GITHUB_ENV"
|
||||
# python_memray.rs profiles real runs. memray has no Windows build.
|
||||
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0
|
||||
if: runner.os != 'Windows' && runner.environment == 'github-hosted'
|
||||
id: memray-python
|
||||
with: { python-version: "3.12", update-environment: false }
|
||||
- name: Install memray for the Python profiler tests
|
||||
# Self-hosted runners have no setup-python; without MEMRAY_PYTHON those tests return early.
|
||||
if: steps.memray-python.outputs.python-path != ''
|
||||
shell: bash
|
||||
env:
|
||||
PYTHON: ${{ steps.memray-python.outputs.python-path }}
|
||||
run: |
|
||||
"$PYTHON" -m venv "$RUNNER_TEMP/memray-venv"
|
||||
"$RUNNER_TEMP/memray-venv/bin/python" -m pip install memray==1.21.0
|
||||
echo "MEMRAY_PYTHON=$RUNNER_TEMP/memray-venv/bin/python" >> "$GITHUB_ENV"
|
||||
- run: cargo nextest run --workspace --no-fail-fast
|
||||
- name: Remote backend with Docker Compose
|
||||
# Self-hosted runner containers do not mount /var/run/docker.sock (scripts/selfhost-runner/README.md).
|
||||
if: runner.os == 'Linux' && runner.environment != 'self-hosted'
|
||||
run: |
|
||||
docker pull busybox:latest
|
||||
# --workspace, not -p ide-host: -p would rebuild instead of reusing the test build above.
|
||||
cargo nextest run --workspace --run-ignored only \
|
||||
-E 'package(=ide-host) & binary(=remote_daemon) & test(=compose_service_survives_disconnect_and_is_removed_on_stop)'
|
||||
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
|
||||
@@ -409,12 +360,6 @@ jobs:
|
||||
node-version: 22
|
||||
cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }}
|
||||
package-manager-cache: ${{ runner.environment != 'self-hosted' }}
|
||||
# src/features/dotnet/edit.test.ts and *.cli.test.ts run the real `dotnet` CLI; with CI set they fail, not skip, when it is missing.
|
||||
- uses: actions/setup-dotnet@v5
|
||||
with:
|
||||
dotnet-version: |
|
||||
10.0.x
|
||||
11.0.x
|
||||
- run: pnpm install --frozen-lockfile
|
||||
- run: pnpm typecheck
|
||||
- run: pnpm lint
|
||||
|
||||
@@ -34,9 +34,7 @@ on:
|
||||
- "src/editor/relatedProviders.ts"
|
||||
- "src/editor/core/cm/cornerInset.ts"
|
||||
- "src/editor/core/cm/iconArea.ts"
|
||||
- "src/editor/core/cm/inlineBg.ts"
|
||||
- "src/editor/core/cm/localAppearance.ts"
|
||||
- "src/editor/core/cm/lineNumberOptions.ts"
|
||||
- "src/editor/lsp/availability.ts"
|
||||
- "src/editor/lsp/diagnostics.ts"
|
||||
- "src/editor/lsp/files.ts"
|
||||
@@ -47,7 +45,7 @@ on:
|
||||
- "src/bindings.ts"
|
||||
- "src/styles/tokens.css"
|
||||
- "src/test/setup.ts"
|
||||
- "src/assets/openidea-logo.png"
|
||||
- "src-tauri/icons/128x128.png"
|
||||
- "smoke/**"
|
||||
- "vite.config.ts"
|
||||
- "tsconfig.json"
|
||||
@@ -111,7 +109,7 @@ jobs:
|
||||
# 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-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|build-tools)/|src/platform/|src/workbench/|src/ui/|src/editor/(api|navigationProviders|refactorProviders|relatedProviders|core/cm/(cornerInset|iconArea|inlineBg|lineNumberOptions|localAppearance)|lsp/(availability|diagnostics|files|hint|lsp|positions|snippet))\.ts$|src/bindings\.ts$|src/styles/tokens\.css$|src/test/setup\.ts$|src/assets/openidea-logo\.png$|smoke/|vite\.config\.ts$|tsconfig\.json$|package\.json$|pnpm-(lock|workspace)\.yaml$|patches/|\.github/workflows/language-smoke\.yml$|\.github/tool-versions\.env$)'
|
||||
smoke='^(crates/|Cargo\.(toml|lock)$|src/features/(run|debugger|build|build-tools)/|src/platform/|src/workbench/|src/ui/|src/editor/(api|navigationProviders|refactorProviders|relatedProviders|core/cm/(cornerInset|iconArea|localAppearance)|lsp/(availability|diagnostics|files|hint|lsp|positions|snippet))\.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
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
name: PR check
|
||||
on:
|
||||
# pull_request_target so the check can label PRs from forks. It never checks out
|
||||
# or runs PR code: it only reads the PR title, description and changed file names.
|
||||
# or runs PR code: it only reads the PR title and description.
|
||||
pull_request_target:
|
||||
types: [opened, edited, reopened, ready_for_review, synchronize]
|
||||
types: [opened, edited, reopened, ready_for_review]
|
||||
|
||||
permissions:
|
||||
issues: write
|
||||
@@ -34,24 +34,6 @@ jobs:
|
||||
|
||||
const { owner, repo } = context.repo;
|
||||
const issue_number = pr.number;
|
||||
|
||||
if (verified && verified[1].trim()) {
|
||||
const section = verified[1];
|
||||
const hasMedia =
|
||||
/!\[[^\]]*\]\(|<img\b|<video\b|github\.com\/user-attachments\/|https?:\/\/\S+\.(png|jpe?g|gif|webp|mp4|mov|webm)\b/i.test(section);
|
||||
const optedOut = /no visible change/i.test(section);
|
||||
if (!hasMedia && !optedOut) {
|
||||
const files = await github.paginate(github.rest.pulls.listFiles, { owner, repo, pull_number: issue_number, per_page: 100 });
|
||||
const ui = files
|
||||
.filter(f => f.status !== 'removed')
|
||||
.map(f => f.filename)
|
||||
.filter(name => /^src\/.*\.(tsx|css)$/.test(name) && !/\.(test|spec)\.tsx$/.test(name));
|
||||
if (ui.length) {
|
||||
const shown = ui.slice(0, 3).map(n => `\`${n}\``).join(', ') + (ui.length > 3 ? ', …' : '');
|
||||
problems.push(`This PR changes UI files (${shown}). Add before/after screenshots, or a recording for interactions, to **How it was verified**; if nothing users see changed, write "No visible change" and say what you checked.`);
|
||||
}
|
||||
}
|
||||
}
|
||||
const comments = await github.paginate(github.rest.issues.listComments, { owner, repo, issue_number });
|
||||
const existing = comments.find(c => c.user.type === 'Bot' && c.body.includes(MARKER));
|
||||
const labeled = pr.labels.some(l => l.name === LABEL);
|
||||
|
||||
@@ -47,7 +47,6 @@ jobs:
|
||||
environment: release
|
||||
env:
|
||||
OPENIDEA_OFFICIAL_PLUGIN_KEYS: ${{ needs.plugin-keys.outputs.keys }}
|
||||
OPENIDEA_BUILD: ${{ github.sha }}
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
@@ -285,8 +284,6 @@ jobs:
|
||||
return;
|
||||
}
|
||||
// Bundle suffix → updater platform keys, as tauri-action names them.
|
||||
// Nightly builds skip RPM because RPM rejects `-` in SemVer prerelease versions.
|
||||
const nightly = tag.includes("-nightly.");
|
||||
const windows = (arch, msi, nsis) => [
|
||||
[msi, [`windows-${arch}`, `windows-${arch}-msi`]],
|
||||
[nsis, [`windows-${arch}-nsis`]],
|
||||
@@ -294,10 +291,10 @@ jobs:
|
||||
const kinds = [
|
||||
[/_aarch64\.AppImage$/, ["linux-aarch64", "linux-aarch64-appimage"]],
|
||||
[/_arm64\.deb$/, ["linux-aarch64-deb"]],
|
||||
...(nightly ? [] : [[/\.aarch64\.rpm$/, ["linux-aarch64-rpm"]]]),
|
||||
[/\.aarch64\.rpm$/, ["linux-aarch64-rpm"]],
|
||||
[/_amd64\.AppImage$/, ["linux-x86_64", "linux-x86_64-appimage"]],
|
||||
[/_amd64\.deb$/, ["linux-x86_64-deb"]],
|
||||
...(nightly ? [] : [[/\.x86_64\.rpm$/, ["linux-x86_64-rpm"]]]),
|
||||
[/\.x86_64\.rpm$/, ["linux-x86_64-rpm"]],
|
||||
[/_aarch64\.app\.tar\.gz$/, ["darwin-aarch64", "darwin-aarch64-app"]],
|
||||
[/_x64\.app\.tar\.gz$/, ["darwin-x86_64", "darwin-x86_64-app"]],
|
||||
...windows("aarch64", /_arm64_en-US\.msi$/, /_arm64-setup\.exe$/),
|
||||
|
||||
+5
-6
@@ -33,13 +33,12 @@ target/
|
||||
test-results/
|
||||
playwright-report/
|
||||
|
||||
# Local AI agent files. Shared skills live in .agents/skills; .claude/skills links to them.
|
||||
# Local AI agent files
|
||||
AGENTS.md
|
||||
CLAUDE.md
|
||||
CLAUDE.local.md
|
||||
.claude/*
|
||||
!.claude/skills/
|
||||
.claude/skills/*
|
||||
!.claude/skills/pr
|
||||
!.claude/skills/verify
|
||||
.agents/
|
||||
.claude/
|
||||
|
||||
# Local reference screenshots
|
||||
pycharm-screenshots/
|
||||
@@ -15,12 +15,10 @@
|
||||
"src/editor/core/cm/jsp/parser*.ts",
|
||||
"src/editor/core/cm/astro/parser*.ts",
|
||||
"src/editor/core/cm/django/parser*.ts",
|
||||
"src/editor/core/cm/freemarker/parser*.ts",
|
||||
"plugins/themes.md",
|
||||
"pnpm-lock.yaml",
|
||||
"**/*.toml",
|
||||
"fixtures",
|
||||
"vendor",
|
||||
"plugins/*/web",
|
||||
"plugins/official/*/web",
|
||||
"crates/**/tests/fixtures"
|
||||
|
||||
@@ -16,7 +16,6 @@
|
||||
"src/editor/core/cm/angular/parser*.ts",
|
||||
"src/editor/core/cm/astro/parser*.ts",
|
||||
"fixtures",
|
||||
"vendor",
|
||||
"plugins",
|
||||
"test-results",
|
||||
"playwright-report",
|
||||
|
||||
@@ -1,199 +0,0 @@
|
||||
# OpenIDEA — contributor guide
|
||||
|
||||
Rust + Tauri 2 desktop IDE with full-featured, multi-language code intelligence.
|
||||
Visual style: rounded content islands on a grey frame, low-contrast greys, one cool accent;
|
||||
Islands Light is the default theme. `src/styles/tokens.css` is the source of truth for colours
|
||||
and metrics; `DESIGN.md` and `PRODUCT.md` describe the design system and who the product is for.
|
||||
|
||||
## Layout
|
||||
|
||||
- `crates/ide-*` — backend crates; one domain each. Depend on `ide-core` for shared
|
||||
types; never reach into another crate's internals.
|
||||
- `src-tauri/` — glue only: `state.rs` (AppState / Project), `commands/<domain>.rs`
|
||||
(desktop-only commands; the adapters of `ide-host` commands are derived), `events.rs`.
|
||||
No domain logic here.
|
||||
- `src/bindings.ts` — generated by tauri-specta (`pnpm gen:bindings`). Never edit.
|
||||
- `src/platform/` — ipc (`call`, `onIdeEvent`, `nextRequestId`), actions registry,
|
||||
keymap + dispatcher, context keys / `when` clauses, project store.
|
||||
- `src/workbench/contributions.ts` — extension points (tool windows, status items,
|
||||
overlays, editor kinds) and cross-feature services (editor, tool windows, notifications).
|
||||
- `src/ui/` — design-system primitives. `src/features/<name>/` — one feature each,
|
||||
exporting `activate()` registered in `src/features/index.ts`.
|
||||
- `languages/<id>.toml` — language definitions (detection, comments, LSP, DAP).
|
||||
- `crates/ide-host` — the `openidea-server` binary for remote development and the
|
||||
`openidea-plugin` CLI (plugin starter templates live in its `templates.rs`).
|
||||
- `wit/` — plugin interface definitions; `plugins/` — sample and bundled plugins.
|
||||
Plugin docs: `plugins/README.md`, `plugins/themes.md`.
|
||||
- `java/` — JDT LS extension bundles (`java-usages`, `kotlin-bridge`) and the patched
|
||||
Lombok agent, embedded into the app by `ide-sdk` / `ide-tools`.
|
||||
- `e2e/` — Playwright UI tests (`pnpm e2e`). `evals/` — code-intelligence evals (`pnpm eval`).
|
||||
`fixtures/` — sample projects per language for manual and automated testing.
|
||||
- `docs/` — the Mintlify documentation site (`docs.json` navigation, `en/` and `zh/` pages);
|
||||
preview with `npx mint dev` in `docs/`.
|
||||
|
||||
## Rules
|
||||
|
||||
- IPC coordinates: 0-based lines, **UTF-16** columns/offsets everywhere (`ide-core::text`).
|
||||
- Every command returns `IdeResult<T>`; convert internal errors at the crate edge.
|
||||
- Declare a command once, on its implementation: `#[command(trust = …)]` in `ide-host::ops`
|
||||
plus its module's `domain!` list (Tauri adapter, server handler and bindings are derived);
|
||||
desktop-only commands use `#[desktop_command(trust = …)]` and `desktop_domain!`.
|
||||
- Streaming → `tauri::ipc::Channel<T>`; cancellable → UI-allocated `RequestId` +
|
||||
`cancel_request`. Backend → UI notifications → `IdeEvent` via `EventSink`.
|
||||
- Long work never blocks the UI thread or a Tauri command thread: use
|
||||
`spawn_blocking`/rayon, honour `CancellationToken`.
|
||||
- Frontend features never import each other; communicate via actions, contributions
|
||||
and services. All user-invocable behaviour is an action with a stable id; default
|
||||
shortcuts live in `src/platform/keymaps/`.
|
||||
- Styling: CSS Modules + tokens only (no hex literals in components). Inline SVG
|
||||
icons from `src/ui/icons.tsx`, never emoji. Real `<button>`/`<input>`; `aria-label` on icon buttons.
|
||||
`gap` uses the `--space-*` scale (`src/styles/tokens.css`, 4px grid) where a value is on it.
|
||||
- User-visible text goes through the text catalog: add every new string to both
|
||||
`src/platform/locales/text/en.json` and `zh.json` (`textCatalog.test.ts` enforces it).
|
||||
Other locales may lack entries; their UI shows the English text until a translator adds it.
|
||||
- Keep comments sparse and purposeful; match surrounding style.
|
||||
- New regular expressions in frontend code must run on WebKit (no lookbehind):
|
||||
`src/platform/webkitCompatibility.test.ts` checks them.
|
||||
- For GUI verification, prefer Tauri MCP; use Computer Use only when Tauri MCP is
|
||||
unavailable or cannot cover the required checks.
|
||||
|
||||
## UX changes
|
||||
|
||||
A change to what users see or how they interact must look and behave like the rest of the IDE.
|
||||
|
||||
- `DESIGN.md` (colours, type, layout, components, Do's and Don'ts) and `PRODUCT.md`
|
||||
(users, principles, accessibility) are the reference; `docs/en/contribute/guidelines/ui.mdx`
|
||||
has the code-level rules. Build from `src/ui/` primitives and workbench contributions;
|
||||
don't create a one-off control, colour or spacing when an existing one fits.
|
||||
- Check every theme the change touches (at least Islands Light and Islands Dark) and narrow
|
||||
sizes (e.g. the Commit tool window at its default width, a small window). Long translated
|
||||
strings must not break the layout.
|
||||
- Everything works from the keyboard; focus is visible and lands somewhere sensible when a
|
||||
popup or dialog closes. Icon-only buttons have an `aria-label` and a tooltip.
|
||||
- Follow the conventions users of this kind of IDE already know: the same action keeps the
|
||||
same name, place and shortcut across views. Don't invent a new pattern for an existing one.
|
||||
- Agent and MCP features follow good agent-tool practice: restrained, predictable, reversible.
|
||||
- Restructuring a page layout or navigation, or changing a default behaviour, needs a
|
||||
maintainer's decision first: ask in the issue and label it `needs-decision`.
|
||||
- The Impeccable design skills may be used for design critique and polish; they read
|
||||
`DESIGN.md`, `PRODUCT.md` and `.impeccable/`. A detector exception goes in
|
||||
`.impeccable/config.json` with a reason.
|
||||
|
||||
## Issues & PRs
|
||||
|
||||
Follow `CONTRIBUTING.md` and `.github/pull_request_template.md`: one problem per PR
|
||||
(`Closes #<n>` when it resolves an issue), reproduce first, keep the diff focused, short plain
|
||||
description. Unclear product decisions → `needs-decision` and stop.
|
||||
|
||||
Every PR carries evidence a reviewer can accept without re-running everything, in
|
||||
**How it was verified**. It must come from the final version of the branch:
|
||||
|
||||
| Change | Evidence |
|
||||
| ----------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| Bug fix | A test that fails before the fix and passes after, or exact reproduction steps with before/after result |
|
||||
| Visible UI | Before/after screenshots at the same state and window size; each theme the change touches |
|
||||
| Interaction (multi-step, drag, keyboard, focus) | A short recording or numbered screenshots |
|
||||
| Code intelligence / language support | The fixture used and `language_smoke` output; `pnpm eval` numbers for Java |
|
||||
| Run / debug | `pnpm smoke smoke/run.test.ts` / `smoke/debug.test.ts -t <language>` output |
|
||||
| Performance | Before/after numbers on the same machine (`pnpm perf`, `pnpm perf:rust` or a stated measurement), plus proof the results are unchanged |
|
||||
| Windows / Linux only | The platform's CI job, and a screenshot or log from a real machine |
|
||||
| Backend / IPC | Test output; regenerated `src/bindings.ts` when types changed |
|
||||
| Remote development | The flow against a real `openidea-server` host |
|
||||
| Plugin API / `wit/` | `plugins/build.sh` run and `dist/` committed; a sample plugin using the change |
|
||||
| Settings / persisted data | Behaviour when starting from data written by the previous version |
|
||||
| Copy, docs, refactor | The commands run; "No visible change" when nothing users see changed |
|
||||
|
||||
Attach screenshots and recordings to the PR description; never commit them. The `pr` skill
|
||||
has the full checklist.
|
||||
|
||||
## Skills
|
||||
|
||||
Shared agent skills live in `.agents/skills/` (`.claude/skills/` links to them):
|
||||
`pr` prepares a pull request — checks to run, evidence for the kind of change, description;
|
||||
`verify` drives the running app through Tauri MCP and captures screenshot evidence.
|
||||
|
||||
## Commands
|
||||
|
||||
- Optional: `mise install` provisions the contributor toolchain; `mise tasks` lists the task aliases.
|
||||
See [Development setup](docs/en/contribute/setup.mdx). The direct commands below still work without mise.
|
||||
- `pnpm tauri dev` — run the app with worktree isolation. Use Node 22.22.2 or later on the 22.x line.
|
||||
`pnpm dev:app` also enables the global Tauri API. `pnpm dev:status` reports
|
||||
this worktree's running MCP bridges and actual ports.
|
||||
- `pnpm build` — typecheck + bundle frontend.
|
||||
- `pnpm dogfood:local [--build-only]` (or `mise run dogfood:local`) — build and locally install the grey-icon dogfood desktop app sharing release settings and data.
|
||||
- `pnpm dogfood:remote <remote_name> [--restart | --no-restart] [--clean]` (or `mise run dogfood:remote <remote_name>`) — sync backend sources to a host from **Tools › SSH Configurations**, build `openidea-server`, and stage it for Remote Development.
|
||||
- `pnpm dogfood:servers [all | x86_64 | aarch64]` (or `mise run dogfood:servers ...`) — cross-build and locally stage Linux `openidea-server` binaries with Zig.
|
||||
- `pnpm dogfood:all [all | x86_64 | aarch64] [--build-only]` (or `mise run dogfood:all ...`) — run `dogfood:local` and `dogfood:servers` in parallel, without requiring an SSH host;
|
||||
`dogfood:all <remote_name> [--restart | --no-restart]` runs `dogfood:local` and `dogfood:remote <remote_name>` in parallel instead.
|
||||
- `cargo nextest run --workspace` (or `cargo test`), `cargo clippy --workspace --all-targets -- -D warnings`, `cargo fmt --all`.
|
||||
- `cargo test -p ide-host --test language_smoke -- --ignored --exact <language>` — code intelligence
|
||||
on `fixtures/` with that language's real server installed (CI: `Language smoke`, pinned versions).
|
||||
- `pnpm smoke smoke/run.test.ts -t <language>` — run and test that language's fixture through the
|
||||
run store and a real `openidea-server` (build it first: `cargo build -p ide-host --bin openidea-server`).
|
||||
- `pnpm smoke smoke/debug.test.ts -t <language>` — debug that fixture's entry point the same way, with
|
||||
the debugger the IDE installs (on macOS, CodeLLDB and Delve may need Developer Mode:
|
||||
`sudo DevToolsSecurity -enable`).
|
||||
- `pnpm test`, `pnpm e2e`, `pnpm lint`, `pnpm format:check`, `pnpm knip`, `pnpm typecheck`,
|
||||
`pnpm gen:bindings`.
|
||||
- `pnpm perf` (UI interaction latency / frames / leaks), `pnpm perf:rust` (criterion
|
||||
benches vs budgets). Budgets: `perf/budgets.json`.
|
||||
- `pnpm eval [--only <id>] [--runs n] [--save-baseline]` — Java code intelligence (navigation,
|
||||
usages, gutter markers) in the production workbench against a release `openidea-server` and
|
||||
jdtls: time to feedback / first result / complete, results vs `evals/<language>/golden/`.
|
||||
Report: `target/eval/report.json`. Goldens and `evals/budgets.json` are changed by people only.
|
||||
Tool versions: `.github/tool-versions.env` (shared with Language smoke).
|
||||
- `pnpm release:prepare <version>` — the release commit's changes: app version everywhere,
|
||||
`Cargo.lock`, and the plugin API snapshot when `wit/` moved to a new version.
|
||||
|
||||
## Before opening a PR
|
||||
|
||||
Run what CI runs for the parts you touched:
|
||||
|
||||
- Rust: `cargo fmt --all --check`, `cargo clippy --workspace --all-targets -- -D warnings`,
|
||||
`cargo nextest run --workspace`. After changing IPC types, run `pnpm gen:bindings` and
|
||||
commit `src/bindings.ts`; CI fails if it differs.
|
||||
- Frontend: `pnpm typecheck` (vitest does not type-check), `pnpm lint`, `pnpm format:check`,
|
||||
`pnpm knip`, `pnpm test`, `pnpm build`, and every `e2e/` spec of the feature you touched.
|
||||
- New text keys: `src/platform/locales/textCatalog.test.ts` and `src/platform/i18n.test.ts`.
|
||||
New or renamed tokens: `pnpm gen:theme-docs`.
|
||||
- Changed a `pub fn` signature in a crate: run that crate's whole `cargo test`, not one test.
|
||||
- UI or runtime behaviour: verify in the running app (`.agents/skills/verify`) and collect
|
||||
the evidence above (`.agents/skills/pr`).
|
||||
|
||||
## Pitfalls
|
||||
|
||||
- Run a subset of frontend tests with `pnpm vitest run <path>`. `pnpm test -- <path>` ignores
|
||||
the filter and runs the whole suite, which takes several minutes.
|
||||
- Don't run clippy while iterating: `pnpm tauri dev` compiles anyway. Run
|
||||
`cargo fmt --all` + `cargo clippy -p <crate> --all-targets -- -D warnings` once, right
|
||||
before committing. A cold build cache can take around 5 minutes. Run long checks one at
|
||||
a time, not chained in one shell call that may hit the 10-minute tool timeout.
|
||||
- `pnpm tauri dev` does a full debug build. Clippy only checks the code, so a passing clippy
|
||||
doesn't make the first launch fast.
|
||||
|
||||
## Parallel worktrees
|
||||
|
||||
Several worktrees can be developed and run side by side.
|
||||
|
||||
- Create one per task: `git worktree add ../<name> -b <branch> origin/main`, then
|
||||
`pnpm install` in it.
|
||||
- Launch with `pnpm tauri dev` / `pnpm dev:app`, not the raw `pnpm exec tauri dev` CLI. The
|
||||
wrapper starts Vite on a worktree-derived port (advancing if occupied), passes its actual
|
||||
URL to Tauri, and reports an existing launcher instead of starting another for the same
|
||||
worktree. HMR uses the Vite port.
|
||||
- Debug app identity, data, settings, logs and single-instance scope follow the canonical
|
||||
worktree path captured at build time, independent of launch cwd. Launching the same debug
|
||||
binary again focuses its existing instance and forwards its path argument. Different
|
||||
worktrees and the installed release can coexist. `--release` uses normal release identity
|
||||
and bypasses the development wrapper.
|
||||
- MCP bridge ports are dynamic (9223–9322). Use `pnpm dev:status`, connect to the reported
|
||||
port, verify identifier/cwd, and pass `appIdentifier: <port>` explicitly. Do not assume the
|
||||
default MCP session belongs to this worktree.
|
||||
- Keep each worktree's Cargo output directory separate; do not point `CARGO_TARGET_DIR` or
|
||||
`target` symlinks at a shared directory.
|
||||
- Each worktree's first build is cold (several minutes) and `cargo build` output takes
|
||||
around 9 GB; tests, clippy and incremental builds add more. Avoid running several heavy builds on one machine at the same time.
|
||||
- Stop only processes started for the current worktree/session. Never use broad
|
||||
process-name kills such as `pkill openidea`.
|
||||
- When done: stop that worktree's app and dev session, delete its build output, then
|
||||
`git worktree remove ../<name>`.
|
||||
@@ -1 +0,0 @@
|
||||
AGENTS.md
|
||||
@@ -1,7 +1,6 @@
|
||||
# Contributing to OpenIDEA
|
||||
|
||||
These rules apply to everyone, and to any coding agent working on their behalf.
|
||||
Project layout, coding rules, commands, checks and the evidence a PR needs are in [AGENTS.md](AGENTS.md).
|
||||
|
||||
## Issues
|
||||
|
||||
@@ -27,12 +26,7 @@ Project layout, coding rules, commands, checks and the evidence a PR needs are i
|
||||
- **How it was verified** is required: the commands you ran and their results,
|
||||
and what else the change could affect. Changes to what users see need before/after
|
||||
screenshots; multi-step interactions need a recording. UI that goes away with a removed
|
||||
feature, copy-only and non-visual changes don't; write "No visible change" and say what
|
||||
you checked instead. [AGENTS.md](AGENTS.md#issues--prs) lists the evidence for each kind of
|
||||
change (tests, smoke output, perf numbers, real-machine logs…).
|
||||
- Changes to what users see follow [DESIGN.md](DESIGN.md) and the existing UI: tokens,
|
||||
`src/ui/` primitives, both themes, keyboard access. Restructuring a layout or navigation
|
||||
needs a maintainer's decision first.
|
||||
feature, copy-only and non-visual changes don't; say what you checked instead.
|
||||
- If a change needs a product decision you can't make, ask in the issue and stop
|
||||
rather than guessing.
|
||||
|
||||
@@ -41,4 +35,4 @@ and the plugin API. Community plugins live in their authors' repositories and
|
||||
are listed through [l0ng-ai/openidea-plugins](https://github.com/l0ng-ai/openidea-plugins);
|
||||
see [`plugins/README.md`](plugins/README.md) § 8.1.
|
||||
|
||||
A check on each PR adds `needs-info` when the verification section is missing, or when the PR changes UI files and the section has neither a screenshot nor a recording nor "No visible change". It removes the label once that's fixed.
|
||||
A check on each PR adds `needs-info` when the verification section is missing, and removes it once it's filled in.
|
||||
Створено
+410
-322
File diff suppressed because it is too large.
Load diff
+2
-10
@@ -2,10 +2,10 @@
|
||||
resolver = "3"
|
||||
members = ["crates/*", "src-tauri"]
|
||||
# Plugins and the guest SDK build for wasm32-wasip2 in their own workspaces.
|
||||
exclude = ["sdk", "plugins", "vendor"]
|
||||
exclude = ["sdk", "plugins"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.1.57"
|
||||
version = "0.1.56"
|
||||
edition = "2024"
|
||||
rust-version = "1.96"
|
||||
license = "Apache-2.0"
|
||||
@@ -24,7 +24,6 @@ ide-jsonrpc = { path = "crates/ide-jsonrpc" }
|
||||
ide-lsp = { path = "crates/ide-lsp" }
|
||||
ide-dap = { path = "crates/ide-dap" }
|
||||
ide-vcs = { path = "crates/ide-vcs" }
|
||||
ide-svn = { path = "crates/ide-svn" }
|
||||
ide-github = { path = "crates/ide-github" }
|
||||
ide-terminal = { path = "crates/ide-terminal" }
|
||||
ide-run = { path = "crates/ide-run" }
|
||||
@@ -91,7 +90,6 @@ trash = "5"
|
||||
blake3 = "1"
|
||||
dunce = "1"
|
||||
dirs = "6"
|
||||
jiff = "0.2"
|
||||
memmap2 = "0.9"
|
||||
zip = { version = "9.2.3", default-features = false, features = ["deflate"] }
|
||||
flate2 = "1"
|
||||
@@ -101,7 +99,6 @@ tar = "0.4"
|
||||
grep-searcher = "0.1"
|
||||
grep-regex = "0.1"
|
||||
regex-syntax = "0.8"
|
||||
regex = "1"
|
||||
grep-matcher = "0.1"
|
||||
nucleo-matcher = "0.3"
|
||||
redb = "4"
|
||||
@@ -161,8 +158,3 @@ opt-level = 3
|
||||
panic = "unwind"
|
||||
# Keep the symbol table: crash reports and logged backtraces name functions.
|
||||
strip = "debuginfo"
|
||||
|
||||
# tauri-plugin-mcp-bridge 0.13.2 (debug-only E2E bridge) pins `tauri ~2.12`; this copy only widens
|
||||
# that requirement to 2.13. Drop it once a release supporting tauri 2.13 is published.
|
||||
[patch.crates-io]
|
||||
tauri-plugin-mcp-bridge = { path = "vendor/tauri-plugin-mcp-bridge" }
|
||||
@@ -6,11 +6,6 @@ contributors as part of the IntelliJ Platform (https://github.com/JetBrains/inte
|
||||
https://github.com/JetBrains/intellij-plugins), licensed under the Apache License 2.0.
|
||||
Copyright 2000-2026 JetBrains s.r.o. and contributors.
|
||||
|
||||
The Subversion tests (crates/ide-svn/tests/matrix.rs) take the tree-conflict scenarios,
|
||||
their names and file contents from IntelliJ's svn4idea TreeConflictData
|
||||
(plugins/svn4idea/testSource/org/jetbrains/idea/svn/), Apache License 2.0, Copyright
|
||||
2000-2026 JetBrains s.r.o. and contributors.
|
||||
|
||||
Some Simplified Chinese UI terms follow the Visual Studio Code Simplified Chinese
|
||||
language pack (https://github.com/microsoft/vscode-loc), Copyright (c) Microsoft
|
||||
Corporation, licensed under the MIT License.
|
||||
|
||||
+3
-3
@@ -10,7 +10,7 @@
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
English · <a href="README.zh-CN.md">简体中文</a> · <a href="README.tr.md">Türkçe</a> · <a href="README.ru.md">Русский</a>
|
||||
English · <a href="README.zh-CN.md">简体中文</a> · <a href="README.tr.md">Türkçe</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
@@ -71,10 +71,10 @@ the [official plugins](plugins/official). The plugin API is still a preview.
|
||||
|
||||
## Community
|
||||
|
||||
- [Discord](https://discord.gg/AsZqMgxZm) — questions, feedback and release news.
|
||||
- [Discord](https://discord.gg/2Zy4yn7gP) — questions, feedback and release news.
|
||||
- WeChat group — scan to join:
|
||||
|
||||
<img src=".github/assets/wechat-group-5.png" alt="WeChat group QR code" width="200">
|
||||
<img src=".github/assets/wechat-group-4.png" alt="WeChat group QR code" width="200">
|
||||
|
||||
- Contributing: see [CONTRIBUTING.md](CONTRIBUTING.md) and the [contributor docs](https://openidea.sh/en/contribute/setup).
|
||||
|
||||
|
||||
@@ -1,85 +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> · <a href="README.zh-CN.md">简体中文</a> · <a href="README.tr.md">Türkçe</a> · Русский
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/l0ng-ai/openidea/releases/latest"><b>Скачать</b></a>
|
||||
·
|
||||
<a href="https://openidea.sh">Документация</a>
|
||||
·
|
||||
<a href="#сравнение-производительности">Производительность</a>
|
||||
·
|
||||
<a href="#плагины">Плагины</a>
|
||||
·
|
||||
<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.
|
||||
|
||||
На macOS IDE также можно установить через Homebrew:
|
||||
|
||||
```bash
|
||||
brew install --cask l0ng-ai/tap/openidea
|
||||
```
|
||||
|
||||
## Сравнение производительности
|
||||
|
||||
Открытие проекта [freqtrade](https://github.com/freqtrade/freqtrade) (Python, около 770 файлов)
|
||||
с прогретыми кешами, медиана пяти запусков:
|
||||
|
||||
| | OpenIDEA | IntelliJ IDEA 2026.2.3 |
|
||||
| ---------------------------------------------- | ------------------- | ---------------------- |
|
||||
| Появление окна с проектом | **0,9 с** | 3,1 с |
|
||||
| Готовность (нагрузка на CPU стабилизировалась) | **1,1 с** | 13,2 с |
|
||||
| Память (USS, все процессы) | **169 МБ** | 2011 МБ |
|
||||
| Процессорное время до готовности | **2,4 с** | 47,9 с |
|
||||
| Загрузка CPU в простое | **4 %** одного ядра | 7 % одного ядра |
|
||||
| Завершение работы | **0,3 с** | 5,9 с |
|
||||
|
||||
В тесте использовались релизная сборка OpenIDEA из ветки `main` и IDEA с настройками и плагинами по умолчанию.
|
||||
Окружение: Windows 11, 32-ядерный процессор AMD, 62 ГБ оперативной памяти.
|
||||
IDEA глубже анализирует Python-код, поэтому к моменту готовности обе IDE выполняют разный объём работы.
|
||||
Измерения обеих IDE проводились извне по одной методике: с помощью
|
||||
[`perf/compare`](perf/compare) можно повторить тест на своём компьютере со своими проектами.
|
||||
|
||||
## Плагины
|
||||
|
||||
Плагины добавляют действия, автодополнение кода, быстрые исправления, окна инструментов, пользовательские редакторы,
|
||||
темы оформления, значки файлов и поддержку языков. Они работают как компоненты WebAssembly в изолированной среде;
|
||||
для тем оформления, тем значков и языков писать код не нужно.
|
||||
|
||||
Плагины можно установить в разделе «Настройки › Плагины» (Settings › Plugins) или создать собственный командой
|
||||
`openidea-plugin new`. См. [руководство по созданию плагинов OpenIDEA](https://openidea.sh/en/plugins)
|
||||
и [официальные плагины](plugins/official). API плагинов пока доступен в предварительной версии.
|
||||
|
||||
## Сообщество
|
||||
|
||||
- [Discord](https://discord.gg/AsZqMgxZm): вопросы, обратная связь и новости о релизах.
|
||||
- Группа WeChat: отсканируйте QR-код, чтобы присоединиться.
|
||||
|
||||
<img src=".github/assets/wechat-group-5.png" alt="QR-код группы WeChat" width="200">
|
||||
|
||||
- Как внести вклад: см. [CONTRIBUTING.md](CONTRIBUTING.md) и [документацию для участников проекта](https://openidea.sh/en/contribute/setup).
|
||||
|
||||
## Лицензия
|
||||
|
||||
[Apache 2.0](LICENSE). Включённые в поставку сторонние ресурсы перечислены в [`THIRD_PARTY_LICENSES.md`](THIRD_PARTY_LICENSES.md).
|
||||
|
||||
<sub>OpenIDEA не связан с JetBrains. IntelliJ IDEA — товарный знак JetBrains s.r.o.</sub>
|
||||
+3
-3
@@ -10,7 +10,7 @@
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="README.md">English</a> · <a href="README.zh-CN.md">简体中文</a> · Türkçe · <a href="README.ru.md">Русский</a>
|
||||
<a href="README.md">English</a> · <a href="README.zh-CN.md">简体中文</a> · Türkçe
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
@@ -71,10 +71,10 @@ Eklentileri Ayarlar › Eklentiler (Settings › Plugins) bölümünden kur ya d
|
||||
|
||||
## Topluluk
|
||||
|
||||
- [Discord](https://discord.gg/AsZqMgxZm): sorular, geri bildirim ve sürüm haberleri.
|
||||
- [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-5.png" alt="WeChat grubu QR kodu" width="200">
|
||||
<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).
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="README.md">English</a> · 简体中文 · <a href="README.tr.md">Türkçe</a> · <a href="README.ru.md">Русский</a>
|
||||
<a href="README.md">English</a> · 简体中文
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
@@ -69,10 +69,10 @@ WebAssembly 组件运行;主题、图标主题和语言无需编写代码。
|
||||
|
||||
## 社区
|
||||
|
||||
- [Discord](https://discord.gg/AsZqMgxZm):提问、反馈和版本发布消息。
|
||||
- [Discord](https://discord.gg/2Zy4yn7gP):提问、反馈和版本发布消息。
|
||||
- 微信群,扫码加入:
|
||||
|
||||
<img src=".github/assets/wechat-group-5.png" alt="微信群二维码" width="200">
|
||||
<img src=".github/assets/wechat-group-4.png" alt="微信群二维码" width="200">
|
||||
|
||||
- 参与贡献:参见 [CONTRIBUTING.md](CONTRIBUTING.md) 和[贡献者文档](https://openidea.sh/zh/contribute/setup)。
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
`src/ui/brands/*.svg` use the unmodified logo paths from
|
||||
[Simple Icons](https://github.com/simple-icons/simple-icons), retrieved through
|
||||
Iconify (`simple-icons:angular`, `simple-icons:astro`, `simple-icons:cplusplus`, `simple-icons:dart`, `simple-icons:deepseek`, `simple-icons:django`, `simple-icons:dotnet`, `simple-icons:elixir`, `simple-icons:express`, `simple-icons:fastapi`, `simple-icons:flask`, `simple-icons:flutter`, `simple-icons:go`, `simple-icons:haskell`, `simple-icons:html5`, `simple-icons:kotlin`, `simple-icons:ktor`, `simple-icons:laravel`, `simple-icons:nestjs`, `simple-icons:nextdotjs`, `simple-icons:nodedotjs`, `simple-icons:nuxt`, `simple-icons:odin`, `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:xcode`, `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: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).
|
||||
|
||||
## DuckDB symbol
|
||||
|
||||
@@ -288,34 +288,6 @@ 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.
|
||||
|
||||
## tree-sitter-fsharp queries
|
||||
|
||||
`crates/ide-language/queries/fsharp_signature/highlights.scm` is the signature grammar's
|
||||
`highlights.scm` from [tree-sitter-fsharp](https://github.com/ionide/tree-sitter-fsharp)
|
||||
0.3.13 (the grammar itself is a Cargo dependency).
|
||||
|
||||
### MIT License (tree-sitter-fsharp)
|
||||
|
||||
Copyright (c) 2023 Nikolaj Sidorenco
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
|
||||
## nvim-treesitter queries
|
||||
|
||||
`crates/ide-syntax/queries/<grammar>/locals.scm` are derived from the `locals.scm`
|
||||
|
||||
@@ -18,16 +18,14 @@ ide-tools = { path = "../ide-tools" }
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
specta.workspace = true
|
||||
sqlx.workspace = true
|
||||
tokio.workspace = true
|
||||
toml.workspace = true
|
||||
toml_edit.workspace = true
|
||||
tracing.workspace = true
|
||||
parking_lot.workspace = true
|
||||
dunce.workspace = true
|
||||
jiff.workspace = true
|
||||
uuid.workspace = true
|
||||
tempfile.workspace = true
|
||||
which = "8"
|
||||
semver = "1"
|
||||
sha1 = "0.10"
|
||||
|
||||
|
||||
@@ -24,7 +24,7 @@ pub(crate) async fn run(shared: &Arc<Shared>, spec: &ProviderSpec, model: Option
|
||||
match run_once(shared, spec, prefer_stored, model).await {
|
||||
Err(err)
|
||||
if !prefer_stored
|
||||
&& crate::provider::is_copilot_provider(spec.base_id())
|
||||
&& crate::provider::is_copilot_provider(&spec.id)
|
||||
&& crate::provider::has_unconfigured_copilot_ambient_token(&spec.env, &shared.paths.project_root)
|
||||
&& super::auth_required(0, &err) =>
|
||||
{
|
||||
@@ -53,7 +53,7 @@ async fn run_once(
|
||||
.await
|
||||
.map_err(|e| e.to_string())??;
|
||||
let cwd = dunce::canonicalize(&root).unwrap_or(root);
|
||||
let updates = Arc::new(DiscoveryUpdates { provider: spec.base_id().to_owned(), ..Default::default() });
|
||||
let updates = Arc::new(DiscoveryUpdates { provider: spec.id.clone(), ..Default::default() });
|
||||
let client = Dialect::wrap(updates.clone());
|
||||
let on_stderr: Box<dyn Fn(String) + Send + Sync> = Box::new(|_| {});
|
||||
let peer = (shared.connector)(&launch, &cwd, client.clone(), on_stderr)
|
||||
@@ -69,7 +69,7 @@ async fn run_once(
|
||||
.await
|
||||
.map_err(discovery_error)?;
|
||||
let mut options = config::options_of(&new);
|
||||
config::add_client_options(launch.base_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 mut levels = BTreeMap::new();
|
||||
let has_config = new.get("configOptions").is_some_and(Value::is_array);
|
||||
@@ -119,7 +119,7 @@ async fn run_once(
|
||||
.commands
|
||||
.lock()
|
||||
.clone()
|
||||
.or_else(|| new.get("availableCommands").map(|_| config::commands_of(&new, launch.base_id())));
|
||||
.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;
|
||||
|
||||
@@ -105,7 +105,6 @@ fn manager(dir: &Path, agent: Arc<FakeV2Agent>) -> AgentManager {
|
||||
store_dir: dir.join("store"),
|
||||
worktrees_dir: dir.join("worktrees"),
|
||||
models_file: dir.join("models.json"),
|
||||
cli_dir: dir.join("agent-cli"),
|
||||
custom_agents_dir: None,
|
||||
home_dir: None,
|
||||
env_secrets: None,
|
||||
|
||||
@@ -53,24 +53,6 @@ pub(crate) fn auth_required(code: i64, message: &str) -> bool {
|
||||
.any(|w| w == ["logged", "out"] || w == ["sign", "in"] || w == ["log", "in"] || w == ["login", "required"])
|
||||
}
|
||||
|
||||
/// Whether a failed request only means the agent hasn't finished starting up: OpenCode
|
||||
/// rejects session opens until the location's plugins and MCP servers finish activating
|
||||
/// (`ServiceUnavailableError`, "Location plugins did not finish activating") and reports
|
||||
/// an unavailable server as `ServerUnavailable`. Both arrive as internal errors naming
|
||||
/// the cause in `data.errorName`; retrying them once activation completes succeeds.
|
||||
pub(crate) fn service_warming_up(error: &RpcError) -> bool {
|
||||
let RpcError::Server { code: codes::INTERNAL_ERROR, message, data } = error else {
|
||||
return false;
|
||||
};
|
||||
if let Some(name) = data.as_ref().and_then(|d| d.get("errorName")).and_then(Value::as_str)
|
||||
&& matches!(name, "ServiceUnavailableError" | "ServerUnavailable")
|
||||
{
|
||||
return true;
|
||||
}
|
||||
let lower = message.to_lowercase();
|
||||
lower.contains("did not finish activating") || lower.contains("opencode server is unavailable")
|
||||
}
|
||||
|
||||
/// The capabilities this client offers, in v1 form.
|
||||
fn client_capabilities() -> Value {
|
||||
json!({
|
||||
@@ -80,8 +62,6 @@ fn client_capabilities() -> Value {
|
||||
"subagents": {},
|
||||
// Forms the agent asks the user to fill in (`elicitation/create`); not URL mode.
|
||||
"elicitation": { "form": {} },
|
||||
// Ghost-text next-prompt suggestions (`prompt_suggestions_update`).
|
||||
"session": { "promptSuggestions": {} },
|
||||
// Cursor exposes model parameters (e.g. Composer `fast`) as separate config options
|
||||
// only when the client advertises this flag (undocumented Cursor ACP extension).
|
||||
"_meta": { "parameterizedModelPicker": true },
|
||||
@@ -96,7 +76,7 @@ pub(crate) fn initialize_params(client_info: &Value) -> Value {
|
||||
json!({
|
||||
"protocolVersion": 2,
|
||||
"info": client_info,
|
||||
"capabilities": { "session": { "promptSuggestions": {} } },
|
||||
"capabilities": {},
|
||||
"clientCapabilities": client_capabilities(),
|
||||
"clientInfo": client_info,
|
||||
})
|
||||
|
||||
@@ -52,40 +52,6 @@ fn auth_required_matches_authentication_words_and_sign_in_phrases() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn service_warming_up_matches_opencode_startup_races_only() {
|
||||
for (code, message, data, expected) in [
|
||||
(
|
||||
codes::INTERNAL_ERROR,
|
||||
"Internal error: Internal service failure",
|
||||
Some(json!({"errorName": "ServiceUnavailableError"})),
|
||||
true,
|
||||
),
|
||||
(
|
||||
codes::INTERNAL_ERROR,
|
||||
"Internal error: OpenCode server is unavailable",
|
||||
Some(json!({"errorName": "ServerUnavailable"})),
|
||||
true,
|
||||
),
|
||||
(codes::INTERNAL_ERROR, "Location plugins did not finish activating", None, true),
|
||||
(
|
||||
codes::INTERNAL_ERROR,
|
||||
"Internal error: Internal service failure",
|
||||
Some(json!({"errorName": "SQLiteError"})),
|
||||
false,
|
||||
),
|
||||
(codes::INTERNAL_ERROR, "Internal error: Internal service failure", None, false),
|
||||
(codes::INTERNAL_ERROR, "boom", None, false),
|
||||
(AUTH_REQUIRED, "Authentication required", None, false),
|
||||
] {
|
||||
assert_eq!(
|
||||
service_warming_up(&RpcError::Server { code, message: message.into(), data: data.clone() }),
|
||||
expected,
|
||||
"code={code}, message={message:?}, data={data:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The messages of a fixture going `dir` (`in` or `out`).
|
||||
pub(crate) fn frames(fixture: &str, dir: &str) -> Vec<Value> {
|
||||
fixture
|
||||
@@ -133,14 +99,11 @@ fn the_negotiating_request_carries_both_versions() {
|
||||
);
|
||||
// Forms only: URL mode would open pages the agent names.
|
||||
assert_eq!(p["clientCapabilities"]["elicitation"], json!({ "form": {} }));
|
||||
assert_eq!(p["clientCapabilities"]["session"], json!({ "promptSuggestions": {} }));
|
||||
assert_eq!(p["capabilities"]["session"], json!({ "promptSuggestions": {} }));
|
||||
// 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 mut expected = sent;
|
||||
expected["_meta"] = p["clientCapabilities"]["_meta"].clone();
|
||||
expected["elicitation"] = p["clientCapabilities"]["elicitation"].clone();
|
||||
expected["session"] = p["clientCapabilities"]["session"].clone();
|
||||
assert_eq!(expected, p["clientCapabilities"]);
|
||||
}
|
||||
|
||||
@@ -192,7 +155,6 @@ async fn discovery_reads_effort_and_fast_from_session_new_then_stops_the_agent()
|
||||
store_dir: tmp.path().join("store"),
|
||||
worktrees_dir: tmp.path().join("worktrees"),
|
||||
models_file: tmp.path().join("models.json"),
|
||||
cli_dir: tmp.path().join("agent-cli"),
|
||||
custom_agents_dir: None,
|
||||
home_dir: None,
|
||||
env_secrets: None,
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -254,14 +254,7 @@ impl AgentCatalogs {
|
||||
}
|
||||
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 = {
|
||||
let catalogs = self.clone();
|
||||
let shared = shared.clone();
|
||||
let model = model.to_owned();
|
||||
tokio::task::spawn_blocking(move || catalogs.request(&shared, spec, false, Some(&model)).1)
|
||||
.await
|
||||
.map_err(|e| e.to_string())?
|
||||
};
|
||||
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() {
|
||||
@@ -451,22 +444,7 @@ impl AgentCatalogs {
|
||||
let flight_key = key.clone();
|
||||
let task = shared.runtime.clone().spawn(async move {
|
||||
let result = discover(&shared, spec, model.as_deref()).await;
|
||||
let current = {
|
||||
let shared = shared.clone();
|
||||
let provider_id = flight_key.2.clone();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
shared
|
||||
.paths
|
||||
.provider_specs()
|
||||
.into_iter()
|
||||
.find(|spec| spec.id == provider_id)
|
||||
.map(|spec| LaunchContext::new(spec, &shared.paths.project_root))
|
||||
})
|
||||
.await
|
||||
.ok()
|
||||
.flatten()
|
||||
};
|
||||
coordinator.complete(&shared, flight_key, generation, model, current, result);
|
||||
coordinator.complete(&shared, flight_key, generation, model, result);
|
||||
let _ = done.send(true);
|
||||
});
|
||||
// A subscriber can re-enter and change configuration during the start event.
|
||||
@@ -488,9 +466,12 @@ impl AgentCatalogs {
|
||||
key: Key,
|
||||
generation: u64,
|
||||
model: Option<String>,
|
||||
current: Option<LaunchContext>,
|
||||
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.
|
||||
@@ -641,7 +622,8 @@ 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() = self.shared.paths.provider_specs();
|
||||
*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)
|
||||
}
|
||||
@@ -649,10 +631,7 @@ impl crate::AgentManager {
|
||||
/// Probes Copilot's model catalog for a staged `account` selection (`""` = Copilot CLI
|
||||
/// default) without mutating `models.json` or broadcasting to active sessions before Apply.
|
||||
pub async fn preview_copilot_models(&self, account: &str, model: Option<&str>) -> IdeResult<AgentModelCatalog> {
|
||||
let mut spec = self
|
||||
.shared
|
||||
.paths
|
||||
.provider_specs()
|
||||
let mut spec = provider::load(self.shared.paths.custom_agents_dir.as_deref(), self.shared.env_secrets())
|
||||
.into_iter()
|
||||
.find(|p| p.id == "copilot")
|
||||
.ok_or_else(|| IdeError::not_found("unknown agent 'copilot'"))?;
|
||||
@@ -697,7 +676,7 @@ async fn discover(
|
||||
Ok(Discovered {
|
||||
commands: Some(config::commands_of(
|
||||
&serde_json::json!({ "availableCommands": found.commands }),
|
||||
spec.base_id(),
|
||||
&spec.id,
|
||||
)),
|
||||
config: config::options_of(&serde_json::json!({ "configOptions": found.options })),
|
||||
levels: found
|
||||
@@ -721,7 +700,7 @@ async fn discover(
|
||||
Ok(found) => Ok(Discovered {
|
||||
commands: Some(config::commands_of(
|
||||
&serde_json::json!({ "availableCommands": found.commands }),
|
||||
spec.base_id(),
|
||||
&spec.id,
|
||||
)),
|
||||
config: config::options_of(&serde_json::json!({ "configOptions": found.options })),
|
||||
levels: found
|
||||
|
||||
@@ -157,7 +157,6 @@ fn make_manager_at(root: &Path, models_file: &Path, catalogs: Arc<AgentCatalogs>
|
||||
store_dir: root.join("store"),
|
||||
worktrees_dir: root.join("worktrees"),
|
||||
models_file: models_file.to_path_buf(),
|
||||
cli_dir: root.join("agent-cli"),
|
||||
catalogs,
|
||||
custom_agents_dir: Some(root.join("agents")),
|
||||
home_dir: Some(root.to_path_buf()),
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! Installs built-in CLIs into IDE-owned npm prefixes and updates the npm installation selected by the launcher.
|
||||
//! 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};
|
||||
@@ -29,14 +29,6 @@ pub enum AgentCliUpdateResult {
|
||||
Error { code: String },
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(tag = "status", rename_all = "camelCase")]
|
||||
pub enum AgentCliInstallResult {
|
||||
Installed,
|
||||
NodeRequired,
|
||||
Error { code: String },
|
||||
}
|
||||
|
||||
pub(crate) fn package(id: &str) -> Option<&'static str> {
|
||||
Some(match id {
|
||||
"claude" => "@anthropic-ai/claude-code",
|
||||
@@ -53,64 +45,6 @@ pub(crate) fn package(id: &str) -> Option<&'static str> {
|
||||
}
|
||||
|
||||
impl AgentManager {
|
||||
/// Installs the built-in CLI into an npm prefix owned by the IDE on this host.
|
||||
pub fn cli_install(
|
||||
&self,
|
||||
id: &str,
|
||||
approved_command: &str,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<AgentCliInstallResult> {
|
||||
use AgentCliInstallResult::*;
|
||||
let spec = self.shared.paths.provider_specs().into_iter().find(|spec| spec.id == id);
|
||||
let (Some(spec), Some(pkg), Some(builtin)) = (spec, package(id), provider::builtin_spec(id)) else {
|
||||
return Err(IdeError::invalid("This agent has no built-in CLI installer"));
|
||||
};
|
||||
if spec.source != AgentSource::Builtin || spec.command != builtin.command {
|
||||
return Err(IdeError::invalid("This agent has no built-in CLI installer"));
|
||||
}
|
||||
let prefix = self.shared.paths.cli_dir.join(id);
|
||||
if install_command(&prefix, pkg).as_deref() != Some(approved_command) {
|
||||
return Err(IdeError::invalid("The CLI install command changed. Reopen Agent Setup and try again."));
|
||||
}
|
||||
if provider::installed_with_env(spec.executable(), &spec.env) {
|
||||
return Ok(Installed);
|
||||
}
|
||||
let search = ide_core::tool_path::search_path();
|
||||
let Some(npm) = ide_core::process::find_executable("npm", &search)
|
||||
.filter(|_| ide_core::process::find_executable("node", &search).is_some())
|
||||
else {
|
||||
return Ok(NodeRequired);
|
||||
};
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
let _lock = lock_prefix(&prefix)?;
|
||||
if managed_cli(&prefix, pkg, &builtin.command).is_some() {
|
||||
return Ok(Installed);
|
||||
}
|
||||
let installation = Installation::at(&prefix, pkg, &builtin.command);
|
||||
// Only publish a CLI after npm has finished and its launcher has been verified.
|
||||
let marker = prefix.join(INSTALLED_MARKER);
|
||||
if marker.exists() {
|
||||
fs::remove_file(&marker)?;
|
||||
}
|
||||
let spec = format!("{pkg}@latest");
|
||||
match run_npm(&npm, &install_args(prefix.to_str().unwrap(), &spec), cancel) {
|
||||
Err(error) if error.kind == ErrorKind::Unavailable => return Ok(Error { code: error.message }),
|
||||
result => result?,
|
||||
};
|
||||
if installation.version(&installation.link, pkg, &builtin.command)?.is_none()
|
||||
|| !provider::installed_with_env(&installation.link.to_string_lossy(), &[])
|
||||
{
|
||||
return Err(IdeError::invalid("npm installation verification failed"));
|
||||
}
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
fs::write(marker, [])?;
|
||||
Ok(Installed)
|
||||
}
|
||||
|
||||
pub fn cli_update(
|
||||
&self,
|
||||
id: &str,
|
||||
@@ -124,53 +58,15 @@ impl AgentManager {
|
||||
if spec.source != AgentSource::Builtin {
|
||||
return Ok(AgentCliUpdateResult::Unmanaged);
|
||||
}
|
||||
let Some(npm) = ide_core::process::find_executable("npm", &ide_core::tool_path::search_path()) else {
|
||||
return Ok(AgentCliUpdateResult::Unmanaged);
|
||||
};
|
||||
let prefix = self.shared.paths.cli_dir.join(id);
|
||||
let managed = spec.managed_cli.is_some().then_some(prefix.as_path());
|
||||
let _lock = if offer.is_some() { managed.map(lock_prefix).transpose()? } else { None };
|
||||
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, managed, offer, cancel) {
|
||||
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,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const INSTALLED_MARKER: &str = ".openidea-installed";
|
||||
|
||||
fn lock_prefix(prefix: &Path) -> IdeResult<fs::File> {
|
||||
fs::create_dir_all(prefix)?;
|
||||
let lock = fs::OpenOptions::new()
|
||||
.create(true)
|
||||
.truncate(false)
|
||||
.read(true)
|
||||
.write(true)
|
||||
.open(prefix.join(".openidea-install.lock"))?;
|
||||
lock.try_lock().map_err(|error| match error {
|
||||
fs::TryLockError::WouldBlock => IdeError::new(ErrorKind::AlreadyExists, "CLI installation is in progress"),
|
||||
fs::TryLockError::Error(error) => error.into(),
|
||||
})?;
|
||||
Ok(lock)
|
||||
}
|
||||
|
||||
pub(crate) fn managed_cli(prefix: &Path, pkg: &str, bin: &str) -> Option<PathBuf> {
|
||||
let link = Installation::at(prefix, pkg, bin).link;
|
||||
(prefix.join(INSTALLED_MARKER).is_file() && provider::installed_with_env(&link.to_string_lossy(), &[]))
|
||||
.then_some(link)
|
||||
}
|
||||
|
||||
pub(crate) fn install_command(prefix: &Path, pkg: &str) -> Option<String> {
|
||||
let spec = format!("{pkg}@latest");
|
||||
let args = install_args(prefix.to_str()?, &spec);
|
||||
Some(provider::render_shell_command(Path::new("npm"), args, cfg!(windows)))
|
||||
}
|
||||
|
||||
fn install_args<'a>(prefix: &'a str, spec: &'a str) -> [&'a str; 7] {
|
||||
["install", "-g", "--prefix", prefix, "--no-audit", "--no-fund", spec]
|
||||
}
|
||||
|
||||
struct Installation {
|
||||
modules: PathBuf,
|
||||
folder: PathBuf,
|
||||
@@ -253,19 +149,47 @@ fn maintain(
|
||||
program: &Path,
|
||||
bin: &str,
|
||||
pkg: &str,
|
||||
managed: Option<&Path>,
|
||||
approved: Option<&AgentCliOffer>,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<AgentCliUpdateResult> {
|
||||
use AgentCliUpdateResult::*;
|
||||
let run = |args: &[&str]| run_npm(npm, args, cancel);
|
||||
let output;
|
||||
let prefix = if let Some(prefix) = managed {
|
||||
prefix
|
||||
} else {
|
||||
output = run(&["prefix", "-g"])?;
|
||||
Path::new(output.trim_end())
|
||||
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"));
|
||||
}
|
||||
@@ -286,42 +210,21 @@ fn maintain(
|
||||
if approved != Some(&offer) {
|
||||
return Ok(Available(offer));
|
||||
}
|
||||
run(&install_args(prefix.to_str().unwrap(), &format!("{pkg}@{}", offer.latest)))?;
|
||||
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 })
|
||||
}
|
||||
|
||||
fn run_npm(npm: &Path, args: &[&str], cancel: &CancellationToken) -> IdeResult<String> {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
let mut cmd = Command::new(npm);
|
||||
cmd.args(args)
|
||||
.current_dir(npm.parent().unwrap())
|
||||
.env("PATH", ide_core::tool_path::search_path())
|
||||
.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)
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -409,9 +312,8 @@ esac"#;
|
||||
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, None, offer, &cancel).unwrap()
|
||||
};
|
||||
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") };
|
||||
@@ -447,7 +349,7 @@ esac"#;
|
||||
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, None, offer, &CancellationToken::new()).unwrap()
|
||||
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();
|
||||
@@ -473,13 +375,13 @@ esac"#,
|
||||
);
|
||||
let cancel = CancellationToken::new();
|
||||
let AgentCliUpdateResult::Available(offer) =
|
||||
maintain(&npm, &f.install.link, "claude", PKG, None, None, &cancel).unwrap()
|
||||
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, None, Some(&offer), &cancel));
|
||||
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));
|
||||
|
||||
@@ -131,267 +131,7 @@ fn is_bypass_mode(mode: &str) -> bool {
|
||||
let lower = mode.to_lowercase();
|
||||
let m: String =
|
||||
lower.rsplit(['#', '/']).next().unwrap_or_default().chars().filter(char::is_ascii_lowercase).collect();
|
||||
m.contains("bypass") || m == "yolo" || m.contains("fullaccess") || m == "dangerous" || m == "autopilot"
|
||||
}
|
||||
|
||||
fn upsert_choice(wanted: &mut Vec<crate::model::AgentConfigChoice>, id: &str, value: &str) {
|
||||
if let Some(existing) = wanted.iter_mut().find(|c| c.id == id) {
|
||||
existing.value = value.to_owned();
|
||||
} else {
|
||||
wanted.push(crate::model::AgentConfigChoice { id: id.to_owned(), value: value.to_owned() });
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn is_approval_option(opt: &AgentConfigOption) -> bool {
|
||||
opt.id == CURSOR_APPROVAL || matches!(opt.category.as_deref(), Some("mode" | "permissions" | "approval"))
|
||||
}
|
||||
|
||||
pub(crate) fn is_approval_option_id(id: &str) -> bool {
|
||||
id == CURSOR_APPROVAL || matches!(id, "mode" | "allow_all" | "permissions" | "approval" | "approval_policy")
|
||||
}
|
||||
|
||||
fn wanted_val(wanted: &[crate::model::AgentConfigChoice], id: &str) -> Option<String> {
|
||||
wanted.iter().find(|c| c.id == id).map(|c| c.value.clone())
|
||||
}
|
||||
|
||||
/// Applies an automation's permission policy (`mode`) to `config` and `wanted`, enforcing the
|
||||
/// user's interactive approval setting (`interactive`) as a strict ceiling. When `mode` is `None`
|
||||
/// (an in-session `/loop` or `Send Later` turn), clamps any bypass options down when `interactive`
|
||||
/// is [`ide_core::settings::NewTaskApprovals::Ask`].
|
||||
pub(crate) fn clamp_automation_permissions(
|
||||
provider: &str,
|
||||
mode: Option<crate::automation::AutomationPermissionMode>,
|
||||
interactive: ide_core::settings::NewTaskApprovals,
|
||||
config: &mut [AgentConfigOption],
|
||||
wanted: &mut Vec<crate::model::AgentConfigChoice>,
|
||||
) {
|
||||
use crate::automation::AutomationPermissionMode;
|
||||
use ide_core::settings::NewTaskApprovals;
|
||||
|
||||
if mode.is_none() && interactive == NewTaskApprovals::Bypass {
|
||||
return;
|
||||
}
|
||||
|
||||
let allow_bypass = interactive == NewTaskApprovals::Bypass && mode == Some(AutomationPermissionMode::AllowAll);
|
||||
|
||||
if !allow_bypass {
|
||||
// Strip any explicit bypass choices from `wanted` first so they cannot re-elevate later.
|
||||
wanted.retain(|c| match c.id.as_str() {
|
||||
"mode" => !is_bypass_mode(&c.value),
|
||||
"allow_all" | "permissions" => !matches!(c.value.to_ascii_lowercase().as_str(), "on" | "true"),
|
||||
"approval" | CURSOR_APPROVAL => !c.value.eq_ignore_ascii_case("bypass"),
|
||||
"approval_policy" => !c.value.eq_ignore_ascii_case("never"),
|
||||
_ => true,
|
||||
});
|
||||
ask_for_approvals(config);
|
||||
}
|
||||
|
||||
match provider {
|
||||
"claude" | "claude-acp" => {
|
||||
let cur_wanted = wanted_val(wanted, "mode");
|
||||
let target = if allow_bypass {
|
||||
match cur_wanted.as_deref() {
|
||||
Some("default" | "plan" | "acceptEdits") => cur_wanted.as_deref().unwrap().to_owned(),
|
||||
_ => "bypassPermissions".to_owned(),
|
||||
}
|
||||
} else if interactive == NewTaskApprovals::Bypass && mode == Some(AutomationPermissionMode::Assisted) {
|
||||
match cur_wanted.as_deref() {
|
||||
Some("default" | "plan") => cur_wanted.as_deref().unwrap().to_owned(),
|
||||
_ => "acceptEdits".to_owned(),
|
||||
}
|
||||
} else {
|
||||
// Either Default mode or interactive policy is Ask (where interactive Claude starts in `default`).
|
||||
match cur_wanted.as_deref() {
|
||||
Some("plan") => "plan".to_owned(),
|
||||
_ => "default".to_owned(),
|
||||
}
|
||||
};
|
||||
if let Some(opt) = config.iter_mut().find(|o| o.id == "mode" || o.category.as_deref() == Some("mode"))
|
||||
&& opt.values.iter().any(|v| v.value == target)
|
||||
{
|
||||
let id = opt.id.clone();
|
||||
opt.current = Some(target.clone());
|
||||
upsert_choice(wanted, &id, &target);
|
||||
} else if mode.is_some() || cur_wanted.is_some() {
|
||||
upsert_choice(wanted, "mode", &target);
|
||||
}
|
||||
}
|
||||
"codex" | "codex-acp" => {
|
||||
let cur_wanted = wanted_val(wanted, "mode");
|
||||
let target = if allow_bypass {
|
||||
match cur_wanted.as_deref() {
|
||||
Some("read-only" | "ask" | "auto") => cur_wanted.as_deref().unwrap().to_owned(),
|
||||
_ => "full-access".to_owned(),
|
||||
}
|
||||
} else if mode == Some(AutomationPermissionMode::Default) {
|
||||
"read-only".to_owned()
|
||||
} else if mode.is_some() {
|
||||
// Assisted, or AllowAll clamped by interactive Ask (`ask_for_approvals` maps full-access -> ask).
|
||||
match cur_wanted.as_deref() {
|
||||
Some("read-only") => "read-only".to_owned(),
|
||||
_ => "ask".to_owned(),
|
||||
}
|
||||
} else {
|
||||
// Scheduled /loop or Send Later under interactive Ask: never full-access.
|
||||
match cur_wanted.as_deref() {
|
||||
Some("read-only" | "ask" | "auto") => cur_wanted.as_deref().unwrap().to_owned(),
|
||||
_ => "ask".to_owned(),
|
||||
}
|
||||
};
|
||||
if let Some(opt) = config.iter_mut().find(|o| o.id == "mode" || o.category.as_deref() == Some("mode"))
|
||||
&& opt.values.iter().any(|v| v.value == target)
|
||||
{
|
||||
let id = opt.id.clone();
|
||||
opt.current = Some(target.clone());
|
||||
upsert_choice(wanted, &id, &target);
|
||||
} else if mode.is_some() || cur_wanted.is_some() {
|
||||
upsert_choice(wanted, "mode", &target);
|
||||
}
|
||||
}
|
||||
"copilot" => {
|
||||
if allow_bypass {
|
||||
if !matches!(wanted_val(wanted, "allow_all").as_deref(), Some("off" | "false")) {
|
||||
upsert_choice(wanted, "allow_all", "on");
|
||||
if let Some(opt) = config.iter_mut().find(|o| o.id == "allow_all") {
|
||||
opt.current = Some("on".into());
|
||||
}
|
||||
}
|
||||
} else {
|
||||
upsert_choice(wanted, "allow_all", "off");
|
||||
if let Some(opt) = config.iter_mut().find(|o| o.id == "allow_all") {
|
||||
opt.current = Some("off".into());
|
||||
}
|
||||
let non_auto = match wanted_val(wanted, "mode").as_deref() {
|
||||
Some("plan") => "plan",
|
||||
_ => "agent",
|
||||
};
|
||||
if mode.is_some() || config.iter().any(|o| o.id == "mode" && o.current.as_deref() == Some("autopilot"))
|
||||
{
|
||||
upsert_choice(wanted, "mode", non_auto);
|
||||
}
|
||||
if let Some(opt) = config.iter_mut().find(|o| o.id == "mode")
|
||||
&& (mode.is_some() || opt.current.as_deref() == Some("autopilot"))
|
||||
&& opt.values.iter().any(|v| v.value == non_auto)
|
||||
{
|
||||
opt.current = Some(non_auto.into());
|
||||
}
|
||||
}
|
||||
}
|
||||
"cursor" => {
|
||||
let target = if allow_bypass && wanted_val(wanted, CURSOR_APPROVAL).as_deref() != Some("ask") {
|
||||
"bypass"
|
||||
} else {
|
||||
"ask"
|
||||
};
|
||||
upsert_choice(wanted, CURSOR_APPROVAL, target);
|
||||
if let Some(opt) = config.iter_mut().find(|o| o.id == CURSOR_APPROVAL) {
|
||||
opt.current = Some(target.into());
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
if allow_bypass {
|
||||
let user_chose_non_bypass = config.iter().any(|o| {
|
||||
is_approval_option(o)
|
||||
&& wanted.iter().any(|c| {
|
||||
c.id == o.id && o.category.as_deref().and_then(bypass_value).is_some_and(|b| !b(&c.value))
|
||||
})
|
||||
});
|
||||
if !user_chose_non_bypass {
|
||||
apply_bypass_approvals(config);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Ensure every approval-bearing option in `config` has its enforced value mirrored in `wanted`
|
||||
// so `open_session` actively configures the live session even if the CLI's own config differs.
|
||||
for opt in config.iter().filter(|o| is_approval_option(o)) {
|
||||
if let Some(cur) = opt.current.as_deref() {
|
||||
upsert_choice(wanted, &opt.id, cur);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Verifies that the session's reported `config` options do not exceed the required automation
|
||||
/// permission ceiling (`min(mode, interactive)`). Returns `Err(reason)` if the provider remained
|
||||
/// in a more permissive mode than allowed.
|
||||
pub(crate) fn verify_automation_ceiling(
|
||||
provider: &str,
|
||||
mode: Option<crate::automation::AutomationPermissionMode>,
|
||||
interactive: ide_core::settings::NewTaskApprovals,
|
||||
config: &[AgentConfigOption],
|
||||
) -> Result<(), String> {
|
||||
use crate::automation::AutomationPermissionMode;
|
||||
use ide_core::settings::NewTaskApprovals;
|
||||
|
||||
if mode.is_none() && interactive == NewTaskApprovals::Bypass {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let allow_bypass = interactive == NewTaskApprovals::Bypass && mode == Some(AutomationPermissionMode::AllowAll);
|
||||
if !allow_bypass && bypass_approvals(config) {
|
||||
return Err("Agent did not confirm the required approval ceiling (session remained in bypass mode).".into());
|
||||
}
|
||||
|
||||
let cur_of = |id: &str| config.iter().find(|o| o.id == id).and_then(|o| o.current.as_deref());
|
||||
let mode_cur = config
|
||||
.iter()
|
||||
.find(|o| o.id == "mode" || o.category.as_deref() == Some("mode"))
|
||||
.and_then(|o| o.current.as_deref());
|
||||
|
||||
if !allow_bypass {
|
||||
match provider {
|
||||
"claude" | "claude-acp" => {
|
||||
if let Some(cur) = mode_cur {
|
||||
let allowed = if interactive == NewTaskApprovals::Bypass
|
||||
&& mode == Some(AutomationPermissionMode::Assisted)
|
||||
{
|
||||
matches!(cur, "default" | "plan" | "acceptEdits")
|
||||
} else {
|
||||
matches!(cur, "default" | "plan")
|
||||
};
|
||||
if !allowed {
|
||||
return Err(format!(
|
||||
"Claude session remained in mode '{cur}', exceeding the required approval ceiling."
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
"codex" | "codex-acp" => {
|
||||
if let Some(cur) = mode_cur {
|
||||
let allowed = if mode == Some(AutomationPermissionMode::Default) {
|
||||
cur == "read-only"
|
||||
} else if mode.is_some() {
|
||||
matches!(cur, "read-only" | "ask")
|
||||
} else {
|
||||
matches!(cur, "read-only" | "ask" | "auto")
|
||||
};
|
||||
if !allowed {
|
||||
return Err(format!(
|
||||
"Codex session remained in mode '{cur}', exceeding the required approval ceiling."
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
"copilot" => {
|
||||
if let Some(cur) = cur_of("allow_all")
|
||||
&& matches!(cur.to_ascii_lowercase().as_str(), "on" | "true")
|
||||
{
|
||||
return Err("Copilot session kept allow_all enabled above the approval ceiling.".into());
|
||||
}
|
||||
if let Some(cur) = mode_cur
|
||||
&& cur.eq_ignore_ascii_case("autopilot")
|
||||
{
|
||||
return Err("Copilot session remained in autopilot mode above the approval ceiling.".into());
|
||||
}
|
||||
}
|
||||
"cursor" if cur_of(CURSOR_APPROVAL).is_some_and(|cur| cur.eq_ignore_ascii_case("bypass")) => {
|
||||
return Err("Cursor session remained in bypass mode above the approval ceiling.".into());
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
m.contains("bypass") || m == "yolo" || m.contains("fullaccess") || m == "dangerous"
|
||||
}
|
||||
|
||||
/// The settings in a `session/new` or `session/load` result: its select `configOptions`,
|
||||
@@ -429,19 +169,15 @@ pub(crate) fn is_fast_option(id: &str) -> bool {
|
||||
id == "fast"
|
||||
}
|
||||
|
||||
/// Whether a raw config option id belongs to the selected model rather than the provider.
|
||||
pub(crate) fn is_per_model_option_id(id: &str) -> bool {
|
||||
matches!(id, "effort" | "reasoning_effort" | "thinking" | "reasoning" | "service_tier")
|
||||
|| is_fast_option(id)
|
||||
|| is_context_option(id)
|
||||
}
|
||||
|
||||
/// Whether an option's available values and default belong to the selected model
|
||||
/// (`thought_level`, `context_tier`, and `model_config` options like `context`, `fast` and `service_tier`)
|
||||
/// rather than the provider as a whole.
|
||||
pub(crate) fn is_per_model_option(o: &AgentConfigOption) -> bool {
|
||||
matches!(o.category.as_deref(), Some("thought_level" | "context_tier" | "model_config"))
|
||||
|| is_per_model_option_id(&o.id)
|
||||
|| matches!(o.id.as_str(), "effort" | "reasoning_effort" | "thinking" | "reasoning")
|
||||
|| is_fast_option(&o.id)
|
||||
|| is_context_option(&o.id)
|
||||
|| o.id == "service_tier"
|
||||
}
|
||||
|
||||
/// A `configOptions` array; only select options are kept (the UI shows them as dropdowns).
|
||||
@@ -933,87 +669,6 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn automation_permissions_respect_interactive_approval_ceiling() {
|
||||
use crate::automation::AutomationPermissionMode;
|
||||
use crate::model::AgentConfigChoice;
|
||||
use ide_core::settings::NewTaskApprovals;
|
||||
|
||||
let claude_opts = || {
|
||||
options_of(&json!({"configOptions": [{
|
||||
"id": "mode", "category": "mode", "type": "select", "currentValue": "bypassPermissions",
|
||||
"defaultValue": "default",
|
||||
"options": [
|
||||
{"value": "default"}, {"value": "acceptEdits"}, {"value": "plan"}, {"value": "bypassPermissions"}
|
||||
]
|
||||
}]}))
|
||||
};
|
||||
|
||||
// Claude Assisted under interactive Bypass -> acceptEdits; under interactive Ask -> default!
|
||||
let mut c = claude_opts();
|
||||
let mut wanted = Vec::new();
|
||||
clamp_automation_permissions(
|
||||
"claude",
|
||||
Some(AutomationPermissionMode::Assisted),
|
||||
NewTaskApprovals::Bypass,
|
||||
&mut c,
|
||||
&mut wanted,
|
||||
);
|
||||
assert_eq!(c[0].current.as_deref(), Some("acceptEdits"));
|
||||
assert!(wanted.iter().any(|w| w.id == "mode" && w.value == "acceptEdits"));
|
||||
|
||||
let mut c_ask = claude_opts();
|
||||
let mut wanted_ask = vec![AgentConfigChoice { id: "mode".into(), value: "bypassPermissions".into() }];
|
||||
clamp_automation_permissions(
|
||||
"claude",
|
||||
Some(AutomationPermissionMode::AllowAll),
|
||||
NewTaskApprovals::Ask,
|
||||
&mut c_ask,
|
||||
&mut wanted_ask,
|
||||
);
|
||||
assert_eq!(c_ask[0].current.as_deref(), Some("default"));
|
||||
assert_eq!(wanted_ask, vec![AgentConfigChoice { id: "mode".into(), value: "default".into() }]);
|
||||
|
||||
// Copilot AllowAll under interactive Ask clamps allow_all -> off and autopilot -> agent.
|
||||
let mut copilot = options_of(&json!({"configOptions": [
|
||||
{"id": "mode", "category": "mode", "type": "select", "currentValue": "autopilot",
|
||||
"options": [{"value": "agent"}, {"value": "plan"}, {"value": "autopilot"}]},
|
||||
{"id": "allow_all", "category": "permissions", "type": "select", "currentValue": "on",
|
||||
"options": [{"value": "off"}, {"value": "on"}]}
|
||||
]}));
|
||||
let mut copilot_wanted = vec![AgentConfigChoice { id: "allow_all".into(), value: "on".into() }];
|
||||
clamp_automation_permissions(
|
||||
"copilot",
|
||||
Some(AutomationPermissionMode::AllowAll),
|
||||
NewTaskApprovals::Ask,
|
||||
&mut copilot,
|
||||
&mut copilot_wanted,
|
||||
);
|
||||
assert_eq!(ids(&copilot), [("mode", Some("agent")), ("allow_all", Some("off"))]);
|
||||
assert!(!bypass_approvals(&copilot));
|
||||
|
||||
// Codex Default -> read-only, Assisted -> ask, AllowAll + Ask -> ask, AllowAll + Bypass -> full-access.
|
||||
let codex_opts = || {
|
||||
options_of(&json!({"configOptions": [{
|
||||
"id": "mode", "category": "mode", "type": "select", "currentValue": "full-access",
|
||||
"defaultValue": "ask",
|
||||
"options": [{"value": "read-only"}, {"value": "ask"}, {"value": "auto"}, {"value": "full-access"}]
|
||||
}]}))
|
||||
};
|
||||
for (perm, interactive, expected) in [
|
||||
(AutomationPermissionMode::Default, NewTaskApprovals::Bypass, "read-only"),
|
||||
(AutomationPermissionMode::Assisted, NewTaskApprovals::Bypass, "ask"),
|
||||
(AutomationPermissionMode::AllowAll, NewTaskApprovals::Ask, "ask"),
|
||||
(AutomationPermissionMode::AllowAll, NewTaskApprovals::Bypass, "full-access"),
|
||||
] {
|
||||
let mut opts = codex_opts();
|
||||
let mut w = Vec::new();
|
||||
clamp_automation_permissions("codex", Some(perm), interactive, &mut opts, &mut w);
|
||||
assert_eq!(opts[0].current.as_deref(), Some(expected), "{perm:?} + {interactive:?}");
|
||||
assert!(w.iter().any(|c| c.id == "mode" && c.value == expected));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn command_sources_in_updates_and_stored_tasks() {
|
||||
let update = json!({"availableCommands": [
|
||||
|
||||
@@ -1,10 +1,7 @@
|
||||
//! 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, AgentQuestion,
|
||||
AgentQuestionOption,
|
||||
};
|
||||
use crate::model::{AgentForm, AgentFormField, AgentFormFieldKind, AgentFormOption, AgentPermissionOption};
|
||||
use serde::Deserialize;
|
||||
use serde::de::{Deserializer, IgnoredAny, MapAccess, Visitor};
|
||||
use serde_json::{Map, Value, json};
|
||||
@@ -13,9 +10,6 @@ use serde_json::{Map, Value, json};
|
||||
/// anything else cancels it.
|
||||
const DECLINE: &str = "decline";
|
||||
|
||||
/// What the question card sends for Skip.
|
||||
const SKIP: &str = "reject";
|
||||
|
||||
/// 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") {
|
||||
@@ -154,97 +148,6 @@ fn scalar(value: &Value) -> Option<String> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The questions a form asks when it is an agent's question tool in form shape: every field
|
||||
/// a choice, each followed by its own text field for a typed answer, named after it
|
||||
/// (`question_0` + `question_0_custom` from claude-agent-acp's `AskUserQuestion`, `q0` +
|
||||
/// `q0__other` from OMP's `ask`). They are shown and answered as the agent's questions, one
|
||||
/// at a time like a native `AskUserQuestion` (#7359); [`answer_questions`] turns the answers
|
||||
/// back into the form's values. `None` for any other form.
|
||||
pub(crate) fn questions_of(form: &AgentForm, params: &Value, message: &str) -> Option<Vec<AgentQuestion>> {
|
||||
let choices = form.fields.len() / 2;
|
||||
if choices == 0 || form.fields.len() % 2 == 1 {
|
||||
return None;
|
||||
}
|
||||
let properties = params.pointer("/requestedSchema/properties");
|
||||
form.fields
|
||||
.chunks(2)
|
||||
.map(|pair| {
|
||||
let [choice, text] = pair else { return None };
|
||||
let asks = matches!(choice.kind, AgentFormFieldKind::Choice | AgentFormFieldKind::Choices)
|
||||
&& !choice.options.is_empty()
|
||||
&& text.kind == AgentFormFieldKind::Text
|
||||
&& text.name.len() > choice.name.len()
|
||||
&& text.name.starts_with(&choice.name);
|
||||
if !asks {
|
||||
return None;
|
||||
}
|
||||
let (title, description) = (choice.title.trim(), choice.description.trim());
|
||||
let (header, question) = if choices == 1 && !message.is_empty() {
|
||||
(if title == message || title == choice.name { "" } else { title }, message)
|
||||
} else if description.is_empty() {
|
||||
("", title)
|
||||
} else {
|
||||
(if title == choice.name { "" } else { title }, description)
|
||||
};
|
||||
let schema = properties.and_then(|p| p.get(&choice.name));
|
||||
let options = choice
|
||||
.options
|
||||
.iter()
|
||||
.map(|option| AgentQuestionOption {
|
||||
label: option.label.clone(),
|
||||
description: option.description.clone(),
|
||||
preview: schema.and_then(|s| option_preview(s, &option.value)),
|
||||
})
|
||||
.collect();
|
||||
Some(AgentQuestion {
|
||||
answer_key: Some(choice.name.clone()),
|
||||
header: header.to_owned(),
|
||||
question: question.to_owned(),
|
||||
multi_select: choice.kind == AgentFormFieldKind::Choices,
|
||||
options,
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The preview claude-agent-acp forwards beside an option (`_meta["_claude/askUserQuestionOption"]`).
|
||||
fn option_preview(schema: &Value, value: &str) -> Option<String> {
|
||||
let listed = schema.get("oneOf").or_else(|| schema.get("anyOf")).or_else(|| schema.pointer("/items/anyOf"));
|
||||
listed?
|
||||
.as_array()?
|
||||
.iter()
|
||||
.find(|o| o.get("const").and_then(Value::as_str) == Some(value))?
|
||||
.pointer("/_meta/_claude~1askUserQuestionOption/preview")?
|
||||
.as_str()
|
||||
.map(str::to_owned)
|
||||
}
|
||||
|
||||
/// The form reply to the answers of [`questions_of`]'s questions (question key to the picked
|
||||
/// labels and the typed text): picked options as the choice's values, the text in the field
|
||||
/// beside it. The question card's Skip declines the form; nothing passes through.
|
||||
pub(crate) fn answer_questions(form: &AgentForm, reply: Option<&str>) -> Option<String> {
|
||||
let reply = reply?;
|
||||
if reply == SKIP {
|
||||
return Some(DECLINE.to_owned());
|
||||
}
|
||||
let Ok(answers) = serde_json::from_str::<Map<String, Value>>(reply) else { return Some(reply.to_owned()) };
|
||||
let mut values = Map::new();
|
||||
for pair in form.fields.chunks(2) {
|
||||
let [choice, text] = pair else { continue };
|
||||
let items = answers.get(&choice.name).and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str);
|
||||
let (mut picked, mut typed) = (Vec::new(), Vec::new());
|
||||
for item in items {
|
||||
match choice.options.iter().find(|o| o.label == item) {
|
||||
Some(option) => picked.push(json!(option.value)),
|
||||
None => typed.push(item),
|
||||
}
|
||||
}
|
||||
values.insert(choice.name.clone(), Value::Array(picked));
|
||||
values.insert(text.name.clone(), json!([typed.join("\n")]));
|
||||
}
|
||||
Some(Value::Object(values).to_string())
|
||||
}
|
||||
|
||||
/// 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() }]
|
||||
@@ -392,90 +295,6 @@ mod tests {
|
||||
assert_eq!(chosen, "count: 3; ok: no; size: Small; tags: a, b");
|
||||
}
|
||||
|
||||
/// What claude-agent-acp sends for `AskUserQuestion` with two questions.
|
||||
fn claude_questions() -> Value {
|
||||
json!({
|
||||
"sessionId": "s", "mode": "form", "message": "Please answer the following questions.",
|
||||
"requestedSchema": { "type": "object", "properties": {
|
||||
"question_0": { "type": "string", "title": "Delivery", "description": "How should it ship?",
|
||||
"oneOf": [{ "const": "Util + table (Recommended)", "title": "Util + table (Recommended)",
|
||||
"description": "Tracks tasks",
|
||||
"_meta": { "_claude/askUserQuestionOption": { "preview": "```\nUtil\n```" } } },
|
||||
{ "const": "Util only", "title": "Util only" }] },
|
||||
"question_0_custom": { "type": "string", "title": "Other" },
|
||||
"question_1": { "type": "array", "title": "Targets", "description": "Who receives it?",
|
||||
"items": { "anyOf": [{ "const": "Members", "title": "Members" },
|
||||
{ "const": "Tags", "title": "Tags" }] } },
|
||||
"question_1_custom": { "type": "string", "title": "Other" }
|
||||
} }
|
||||
})
|
||||
}
|
||||
|
||||
fn in_order(params: &Value, names: &[&str]) -> AgentForm {
|
||||
let mut form = form_of(params).unwrap();
|
||||
form.fields.sort_by_key(|f| names.iter().position(|n| *n == f.name));
|
||||
form
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_question_tool_form_is_asked_as_questions() {
|
||||
let params = claude_questions();
|
||||
let form = in_order(¶ms, &["question_0", "question_0_custom", "question_1", "question_1_custom"]);
|
||||
let questions = questions_of(&form, ¶ms, "Please answer the following questions.").unwrap();
|
||||
let [delivery, targets] = questions.as_slice() else { panic!("{questions:?}") };
|
||||
assert_eq!(
|
||||
(
|
||||
delivery.answer_key.as_deref(),
|
||||
delivery.header.as_str(),
|
||||
delivery.question.as_str(),
|
||||
delivery.multi_select
|
||||
),
|
||||
(Some("question_0"), "Delivery", "How should it ship?", false)
|
||||
);
|
||||
assert_eq!(delivery.options[0].description, "Tracks tasks");
|
||||
assert_eq!(delivery.options[0].preview.as_deref(), Some("```\nUtil\n```"));
|
||||
assert_eq!(delivery.options[1].preview, None);
|
||||
assert_eq!((targets.question.as_str(), targets.multi_select), ("Who receives it?", true));
|
||||
|
||||
let reply = json!({ "question_0": ["Util only", "keep it small"], "question_1": ["Members", "Tags"] });
|
||||
let reply = answer_questions(&form, Some(&reply.to_string()));
|
||||
let (response, chosen) = answer(&form, reply.as_deref());
|
||||
assert_eq!(
|
||||
response,
|
||||
json!({ "action": "accept", "content": {
|
||||
"question_0": "Util only", "question_0_custom": "keep it small", "question_1": ["Members", "Tags"]
|
||||
} })
|
||||
);
|
||||
assert_eq!(chosen, "Delivery: Util only; Other: keep it small; Targets: Members, Tags");
|
||||
assert_eq!(answer_questions(&form, Some(SKIP)).as_deref(), Some(DECLINE));
|
||||
assert_eq!(answer_questions(&form, None), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_single_question_reads_from_the_message() {
|
||||
let params = ask();
|
||||
let form = in_order(¶ms, &["q0", "q0__other"]);
|
||||
let questions = questions_of(&form, ¶ms, "Which database?").unwrap();
|
||||
assert_eq!((questions[0].header.as_str(), questions[0].question.as_str()), ("", "Which database?"));
|
||||
assert_eq!(questions[0].options[0].label, "Postgres");
|
||||
let reply = answer_questions(&form, Some(&json!({ "q0": ["SQLite"] }).to_string()));
|
||||
assert_eq!(answer(&form, reply.as_deref()).0, json!({ "action": "accept", "content": { "q0": "sqlite" } }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn other_forms_stay_forms() {
|
||||
let only_choices = form_of(&json!({ "mode": "form", "requestedSchema": { "type": "object", "properties": {
|
||||
"size": { "type": "string", "enum": ["s", "l"] }, "env": { "type": "string", "enum": ["dev"] }
|
||||
} } }))
|
||||
.unwrap();
|
||||
assert_eq!(questions_of(&only_choices, &json!({}), "Pick"), None);
|
||||
let unrelated_text = form_of(&json!({ "mode": "form", "requestedSchema": { "type": "object", "properties": {
|
||||
"size": { "type": "string", "enum": ["s", "l"] }, "note": { "type": "string" }
|
||||
} } }))
|
||||
.unwrap();
|
||||
assert_eq!(questions_of(&unrelated_text, &json!({}), "Pick"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn declining_and_dismissing_send_no_content() {
|
||||
let form = form_of(&ask()).unwrap();
|
||||
|
||||
@@ -2,10 +2,9 @@
|
||||
//! scanned so they can be listed and imported as tasks instead of re-explained (#312).
|
||||
//!
|
||||
//! Only the native providers keep transcripts on disk in a readable form: Claude Code
|
||||
//! (`<config>/projects/*/<id>.jsonl`, see `native::claude::history`), 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/session_index.jsonl`), and Copilot
|
||||
//! (`<config>/session-state/<id>/workspace.yaml` plus `events.jsonl`).
|
||||
//! `<home>/.codex/session_index.jsonl`).
|
||||
|
||||
use super::native::claude::history;
|
||||
use serde::Serialize;
|
||||
@@ -18,7 +17,7 @@ use std::path::{Path, PathBuf};
|
||||
#[derive(Clone, Debug, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ExternalSession {
|
||||
/// The [`crate::AgentProvider`] id that owns it (`claude`, `codex`, `copilot`).
|
||||
/// The [`crate::AgentProvider`] id that owns it (`claude`, `codex`).
|
||||
pub provider: String,
|
||||
/// The id resuming it names (`--resume`, `thread/resume`).
|
||||
pub session_id: String,
|
||||
@@ -27,9 +26,6 @@ pub struct ExternalSession {
|
||||
pub cwd: Option<String>,
|
||||
/// File modification time, ms since the epoch.
|
||||
pub updated_ms: f64,
|
||||
/// Another live process (VS Code, a terminal Copilot CLI) has it open: importing would let two
|
||||
/// apps write the same session, so forking a copy is the safe choice.
|
||||
pub in_use: bool,
|
||||
}
|
||||
|
||||
/// Modification time of `path` in ms, else 0.
|
||||
@@ -127,7 +123,6 @@ pub fn claude_sessions(config_dir: &Path, root: &Path) -> Vec<ExternalSession> {
|
||||
title,
|
||||
cwd,
|
||||
updated_ms: mtime(&path),
|
||||
in_use: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -198,7 +193,6 @@ fn codex_file(path: &Path) -> Option<ExternalSession> {
|
||||
session_id,
|
||||
cwd,
|
||||
updated_ms: mtime(path),
|
||||
in_use: false,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -252,289 +246,6 @@ pub fn codex_sessions(codex_home: &Path, root: &Path) -> Vec<ExternalSession> {
|
||||
sessions
|
||||
}
|
||||
|
||||
/// Whether `raw` is a YAML block-scalar header (`|`, `|-`, `|+`, `>`, `>-`, `>+`, with optional indent digit).
|
||||
fn is_yaml_block_header(raw: &str) -> bool {
|
||||
let mut chars = raw.chars();
|
||||
matches!(chars.next(), Some('|' | '>')) && chars.all(|c| matches!(c, '-' | '+') || c.is_ascii_digit())
|
||||
}
|
||||
|
||||
/// Unquotes a single-line YAML scalar value from Copilot's `workspace.yaml`.
|
||||
fn parse_yaml_inline_value(raw: &str) -> String {
|
||||
if raw.starts_with('"') {
|
||||
serde_json::from_str(raw).unwrap_or_else(|_| raw.trim_matches('"').to_owned())
|
||||
} else if raw.starts_with('\'') && raw.ends_with('\'') && raw.len() >= 2 {
|
||||
raw[1..raw.len() - 1].replace("''", "'")
|
||||
} else {
|
||||
raw.to_owned()
|
||||
}
|
||||
}
|
||||
|
||||
/// Metadata for one Copilot session, read without opening its potentially multi-gigabyte event log.
|
||||
/// Supports both inline scalars (`name: "Fix\nbug"`) and block scalars (`name: |-\n Fix\n bug`).
|
||||
fn copilot_metadata(path: &Path) -> Option<HashMap<String, String>> {
|
||||
let file = std::fs::File::open(path).ok()?;
|
||||
let mut lines = std::io::BufReader::new(file).lines().map_while(Result::ok).peekable();
|
||||
let mut metadata = HashMap::new();
|
||||
while let Some(line) = lines.next() {
|
||||
if line.is_empty() || line.starts_with(char::is_whitespace) || line.trim_start().starts_with('#') {
|
||||
continue;
|
||||
}
|
||||
let Some((key, raw)) = line.split_once(':') else { continue };
|
||||
let key = key.trim();
|
||||
let raw = raw.trim();
|
||||
if key.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if is_yaml_block_header(raw) {
|
||||
let folded = raw.starts_with('>');
|
||||
let mut block = Vec::new();
|
||||
while let Some(next) = lines.peek() {
|
||||
if next.is_empty() || next.starts_with(' ') || next.starts_with('\t') {
|
||||
block.push(lines.next().unwrap_or_default());
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
while block.last().is_some_and(|l| l.trim().is_empty()) {
|
||||
block.pop();
|
||||
}
|
||||
let indent = block
|
||||
.iter()
|
||||
.filter(|l| !l.trim().is_empty())
|
||||
.map(|l| l.bytes().take_while(|&b| b == b' ').count())
|
||||
.min()
|
||||
.unwrap_or(0);
|
||||
let sep = if folded { " " } else { "\n" };
|
||||
let joined = block
|
||||
.iter()
|
||||
.map(|l| if l.len() >= indent { &l[indent..] } else { l.trim_start() })
|
||||
.collect::<Vec<_>>()
|
||||
.join(sep);
|
||||
if !joined.trim().is_empty() {
|
||||
metadata.insert(key.to_owned(), joined);
|
||||
}
|
||||
} else if !raw.is_empty() {
|
||||
metadata.insert(key.to_owned(), parse_yaml_inline_value(raw));
|
||||
}
|
||||
}
|
||||
(!metadata.is_empty()).then_some(metadata)
|
||||
}
|
||||
|
||||
/// The first real prompt in a Copilot event log, used when an old or unnamed session has no title.
|
||||
fn copilot_prompt(path: &Path) -> Option<String> {
|
||||
let file = std::fs::File::open(path).ok()?;
|
||||
std::io::BufReader::new(file)
|
||||
.lines()
|
||||
.take(400)
|
||||
.filter_map(|line| line.ok())
|
||||
.filter_map(|line| serde_json::from_str::<serde_json::Value>(&line).ok())
|
||||
.find_map(|event| {
|
||||
(event.get("type").and_then(serde_json::Value::as_str) == Some("user.message"))
|
||||
.then(|| event.pointer("/data/content").and_then(serde_json::Value::as_str).map(str::trim))
|
||||
.flatten()
|
||||
.filter(|text| !text.is_empty())
|
||||
.map(short)
|
||||
})
|
||||
}
|
||||
|
||||
/// Candidate VS Code Agent Host SQLite databases (`<user>/globalStorage/agent-host.db`),
|
||||
/// ordered oldest-first so a newer database wins when two editions share a session.
|
||||
fn vscode_agent_host_dbs(home: &Path) -> Vec<PathBuf> {
|
||||
let mut bases = vec![home.join("Library/Application Support"), home.join(".config"), home.join("AppData/Roaming")];
|
||||
let real_home = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE"));
|
||||
if real_home.as_deref().is_some_and(|h| Path::new(h) == home) {
|
||||
for var in ["XDG_CONFIG_HOME", "APPDATA"] {
|
||||
if let Some(dir) = std::env::var_os(var).filter(|v| !v.is_empty()).map(PathBuf::from)
|
||||
&& !bases.contains(&dir)
|
||||
{
|
||||
bases.push(dir);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut dbs = Vec::new();
|
||||
for base in bases {
|
||||
for app in ["Code", "Code - Insiders"] {
|
||||
dbs.push(base.join(app).join("User/globalStorage/agent-host.db"));
|
||||
}
|
||||
}
|
||||
for server in [".vscode-server", ".vscode-server-insiders"] {
|
||||
dbs.push(home.join(server).join("data/User/globalStorage/agent-host.db"));
|
||||
}
|
||||
dbs.retain(|p| p.is_file());
|
||||
dbs.sort_by(|a, b| mtime(a).total_cmp(&mtime(b)));
|
||||
dbs
|
||||
}
|
||||
|
||||
fn is_generic_vscode_placeholder(title: &str, source: Option<&str>) -> bool {
|
||||
source != Some("user") && (title.eq_ignore_ascii_case("new session") || title.eq_ignore_ascii_case("new chat"))
|
||||
}
|
||||
|
||||
fn pick_vscode_chat_title(
|
||||
scs_title: Option<&str>,
|
||||
scs_source: Option<&str>,
|
||||
metadata_json: Option<&str>,
|
||||
payload_json: Option<&str>,
|
||||
) -> Option<String> {
|
||||
if let Some(t) = scs_title.map(str::trim).filter(|t| !t.is_empty())
|
||||
&& !is_generic_vscode_placeholder(t, scs_source)
|
||||
{
|
||||
return Some(t.to_owned());
|
||||
}
|
||||
for blob in [metadata_json, payload_json].into_iter().flatten() {
|
||||
let Ok(v) = serde_json::from_str::<serde_json::Value>(blob) else { continue };
|
||||
let summary = v.pointer("/data/summary").and_then(serde_json::Value::as_str).map(str::trim);
|
||||
let source = v.pointer("/data/titleSource").and_then(serde_json::Value::as_str);
|
||||
if let Some(t) = summary.filter(|t| !t.is_empty())
|
||||
&& !is_generic_vscode_placeholder(t, source)
|
||||
{
|
||||
return Some(t.to_owned());
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// The rows of one `agent-host.db` that map a backing Copilot session (`sdkSessionId`) to its
|
||||
/// title. Read through a read-only connection that sets no `journal_mode` or other write pragma,
|
||||
/// so VS Code's database is never changed. An unknown schema (a newer VS Code) reads nothing.
|
||||
async fn read_vscode_chat_rows(path: &Path) -> Vec<[Option<String>; 5]> {
|
||||
use sqlx::{Connection, Row};
|
||||
const FULL_QUERY: &str = "\
|
||||
SELECT c.provider_data, scs.title, scs.title_source, c.metadata, s.payload \
|
||||
FROM chats_v2 c \
|
||||
LEFT JOIN session_chat_state scs \
|
||||
ON scs.session_uri = c.owner_session_uri AND scs.chat_uri = c.chat_uri \
|
||||
LEFT JOIN sessions_v2 s \
|
||||
ON s.session_uri = c.owner_session_uri \
|
||||
WHERE c.tombstoned = 0 \
|
||||
ORDER BY COALESCE(s.modified_time, 0) ASC, COALESCE(c.chat_order, 0) ASC";
|
||||
const FALLBACK_QUERY: &str = "SELECT provider_data, NULL, NULL, metadata, NULL FROM chats_v2 WHERE tombstoned = 0";
|
||||
|
||||
let options = sqlx::sqlite::SqliteConnectOptions::new()
|
||||
.filename(path)
|
||||
.read_only(true)
|
||||
.create_if_missing(false)
|
||||
.busy_timeout(std::time::Duration::from_millis(200));
|
||||
let Ok(mut conn) = sqlx::SqliteConnection::connect_with(&options).await else { return Vec::new() };
|
||||
let rows = match sqlx::query(FULL_QUERY).fetch_all(&mut conn).await {
|
||||
Ok(rows) => rows,
|
||||
Err(_) => sqlx::query(FALLBACK_QUERY).fetch_all(&mut conn).await.unwrap_or_default(),
|
||||
};
|
||||
let _ = conn.close().await;
|
||||
rows.iter().map(|row| std::array::from_fn(|i| row.try_get::<Option<String>, _>(i).ok().flatten())).collect()
|
||||
}
|
||||
|
||||
/// Session titles VS Code's Agent Host (`vscode-agent-host`) assigns to backing Copilot CLI
|
||||
/// sessions (`sdkSessionId` → summary or user rename). VS Code keeps these in its own
|
||||
/// `agent-host.db` rather than in Copilot's `workspace.yaml`, so without them a renamed chat
|
||||
/// would be listed under its first prompt. Best-effort: any failure leaves the CLI titles.
|
||||
fn vscode_copilot_titles(home: Option<&Path>) -> HashMap<String, String> {
|
||||
let Some(home) = home else { return HashMap::new() };
|
||||
let dbs = vscode_agent_host_dbs(home);
|
||||
if dbs.is_empty() {
|
||||
return HashMap::new();
|
||||
}
|
||||
// Callers are sync and may run on a runtime thread or none: a private runtime on its own
|
||||
// thread works from either without blocking a runtime worker.
|
||||
let rows: Vec<[Option<String>; 5]> = std::thread::scope(|scope| {
|
||||
scope
|
||||
.spawn(|| {
|
||||
let Ok(rt) = tokio::runtime::Builder::new_current_thread().enable_all().build() else {
|
||||
return Vec::new();
|
||||
};
|
||||
rt.block_on(async {
|
||||
let mut all = Vec::new();
|
||||
for path in &dbs {
|
||||
all.extend(read_vscode_chat_rows(path).await);
|
||||
}
|
||||
all
|
||||
})
|
||||
})
|
||||
.join()
|
||||
.unwrap_or_default()
|
||||
});
|
||||
let mut titles = HashMap::new();
|
||||
for [pdata, scs_title, scs_source, metadata, payload] in rows {
|
||||
let Some(pdata) = pdata else { continue };
|
||||
let Ok(pv) = serde_json::from_str::<serde_json::Value>(&pdata) else { continue };
|
||||
let Some(sdk_id) = pv.get("sdkSessionId").and_then(serde_json::Value::as_str).filter(|s| !s.is_empty()) else {
|
||||
continue;
|
||||
};
|
||||
if let Some(title) =
|
||||
pick_vscode_chat_title(scs_title.as_deref(), scs_source.as_deref(), metadata.as_deref(), payload.as_deref())
|
||||
{
|
||||
titles.insert(sdk_id.to_owned(), title);
|
||||
}
|
||||
}
|
||||
titles
|
||||
}
|
||||
|
||||
/// Whether a live process holds the Copilot session in `dir`. Copilot writes `inuse.<pid>.lock`
|
||||
/// while a CLI or SDK host (such as VS Code) has the session open; a crash leaves a stale one,
|
||||
/// so only a lock whose process still runs counts.
|
||||
fn copilot_session_in_use(dir: &Path) -> bool {
|
||||
std::fs::read_dir(dir).into_iter().flatten().flatten().any(|entry| {
|
||||
let name = entry.file_name();
|
||||
let Some(pid) = name
|
||||
.to_str()
|
||||
.and_then(|n| n.strip_prefix("inuse."))
|
||||
.and_then(|n| n.strip_suffix(".lock"))
|
||||
.and_then(|n| n.parse::<u32>().ok())
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
ide_core::process::process_alive(pid)
|
||||
})
|
||||
}
|
||||
|
||||
/// Copilot sessions of the project at `root`: `<config>/session-state/<id>`, titled by VS Code's
|
||||
/// Agent Host summary/rename (when started from VS Code), their recorded CLI name, or first prompt.
|
||||
/// Directories without an event log are unfinished sessions and are not listed.
|
||||
pub fn copilot_sessions(copilot_home: &Path, home: Option<&Path>, root: &Path) -> Vec<ExternalSession> {
|
||||
let mut pending: Vec<(ExternalSession, bool)> = std::fs::read_dir(copilot_home.join("session-state"))
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.flatten()
|
||||
.filter_map(|entry| {
|
||||
let dir = entry.path();
|
||||
let events = dir.join("events.jsonl");
|
||||
if !events.is_file() {
|
||||
return None;
|
||||
}
|
||||
let metadata = copilot_metadata(&dir.join("workspace.yaml"))?;
|
||||
let session_id = metadata.get("id").cloned().or_else(|| entry.file_name().to_str().map(str::to_owned))?;
|
||||
let cwd = metadata.get("cwd").cloned().or_else(|| metadata.get("git_root").cloned());
|
||||
if !in_project(cwd.as_deref(), root) {
|
||||
return None;
|
||||
}
|
||||
let raw_name = metadata.get("name").map(String::as_str).map(str::trim).filter(|name| !name.is_empty());
|
||||
let cli_user_named = metadata.get("user_named").is_some_and(|v| v == "true")
|
||||
&& raw_name.is_some_and(|n| !n.eq_ignore_ascii_case("new session"));
|
||||
let title = raw_name
|
||||
.map(short)
|
||||
.or_else(|| copilot_prompt(&events))
|
||||
.unwrap_or_else(|| format!("Copilot session {}", &session_id[..session_id.len().min(8)]));
|
||||
let session = ExternalSession {
|
||||
provider: "copilot".to_owned(),
|
||||
session_id,
|
||||
title,
|
||||
cwd,
|
||||
updated_ms: mtime(&events),
|
||||
in_use: copilot_session_in_use(&dir),
|
||||
};
|
||||
Some((session, cli_user_named))
|
||||
})
|
||||
.collect();
|
||||
if !pending.is_empty() {
|
||||
let vscode_titles = vscode_copilot_titles(home);
|
||||
for (session, cli_user_named) in &mut pending {
|
||||
if !*cli_user_named && let Some(title) = vscode_titles.get(&session.session_id) {
|
||||
session.title = short(title);
|
||||
}
|
||||
}
|
||||
}
|
||||
pending.into_iter().map(|(s, _)| s).collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -633,111 +344,6 @@ mod tests {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
assert!(claude_sessions(&tmp.path().join("nope"), Path::new("/work")).is_empty());
|
||||
assert!(codex_sessions(&tmp.path().join("nope"), Path::new("/work")).is_empty());
|
||||
assert!(copilot_sessions(&tmp.path().join("nope"), None, Path::new("/work")).is_empty());
|
||||
}
|
||||
|
||||
fn exec_sqlite(path: &Path, sql: &'static str) {
|
||||
use sqlx::Connection;
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
|
||||
rt.block_on(async {
|
||||
let options = sqlx::sqlite::SqliteConnectOptions::new().filename(path).create_if_missing(true);
|
||||
let mut conn = sqlx::SqliteConnection::connect_with(&options).await.unwrap();
|
||||
sqlx::raw_sql(sql).execute(&mut conn).await.unwrap();
|
||||
conn.close().await.unwrap();
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lists_copilot_sessions_with_names_block_scalars_vscode_titles_and_prompt_fallbacks() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let copilot_home = tmp.path().join(".copilot");
|
||||
let session = copilot_home.join("session-state/copilot-1");
|
||||
write(
|
||||
&session.join("events.jsonl"),
|
||||
&[
|
||||
json!({"type": "session.start", "data": {}}),
|
||||
json!({"type": "user.message", "data": {"content": "fix the parser"}}),
|
||||
],
|
||||
);
|
||||
std::fs::write(
|
||||
session.join("workspace.yaml"),
|
||||
"id: copilot-1\ncwd: /work/app/api\nname: \"Fix parser\\nand tests\"\n",
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let block_scalar = copilot_home.join("session-state/copilot-block");
|
||||
write(&block_scalar.join("events.jsonl"), &[json!({"type": "session.start", "data": {}})]);
|
||||
std::fs::write(
|
||||
block_scalar.join("workspace.yaml"),
|
||||
"id: copilot-block\ncwd: /work/app\nname: |-\n check why excalidraw font\n is not displayed\nuser_named: false\n",
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let vscode_renamed = copilot_home.join("session-state/copilot-vscode");
|
||||
write(
|
||||
&vscode_renamed.join("events.jsonl"),
|
||||
&[json!({"type": "user.message", "data": {"content": "create a branch deng/session add Create Session"}})],
|
||||
);
|
||||
std::fs::write(
|
||||
vscode_renamed.join("workspace.yaml"),
|
||||
"id: copilot-vscode\ncwd: /work/app\nclient_name: vscode-agent-host\nname: create a branch deng/session add Create Session\nuser_named: false\n",
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let vscode_placeholder = copilot_home.join("session-state/copilot-placeholder");
|
||||
write(&vscode_placeholder.join("events.jsonl"), &[json!({"type": "session.start", "data": {}})]);
|
||||
std::fs::write(
|
||||
vscode_placeholder.join("workspace.yaml"),
|
||||
"id: copilot-placeholder\ncwd: /work/app\nname: Greeting exchange\nuser_named: false\n",
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let unnamed = copilot_home.join("session-state/copilot-2");
|
||||
write(
|
||||
&unnamed.join("events.jsonl"),
|
||||
&[json!({"type": "user.message", "data": {"content": "add a regression test"}})],
|
||||
);
|
||||
std::fs::write(unnamed.join("workspace.yaml"), "id: copilot-2\ncwd: /work/app\n").unwrap();
|
||||
// A live holder marks the session in use; a lock left by a process that exited does not.
|
||||
std::fs::write(session.join(format!("inuse.{}.lock", std::process::id())), "").unwrap();
|
||||
std::fs::write(unnamed.join("inuse.2147483646.lock"), "").unwrap();
|
||||
|
||||
let empty = copilot_home.join("session-state/copilot-empty");
|
||||
std::fs::create_dir_all(&empty).unwrap();
|
||||
std::fs::write(empty.join("workspace.yaml"), "id: copilot-empty\ncwd: /work/app\n").unwrap();
|
||||
|
||||
let other = copilot_home.join("session-state/copilot-other");
|
||||
write(
|
||||
&other.join("events.jsonl"),
|
||||
&[json!({"type": "user.message", "data": {"content": "unrelated project"}})],
|
||||
);
|
||||
std::fs::write(other.join("workspace.yaml"), "id: copilot-other\ncwd: /other\n").unwrap();
|
||||
|
||||
exec_sqlite(
|
||||
&tmp.path().join(".config/Code/User/globalStorage/agent-host.db"),
|
||||
"CREATE TABLE sessions_v2 (session_uri TEXT PRIMARY KEY, payload TEXT, modified_time INTEGER);
|
||||
CREATE TABLE session_chat_state (session_uri TEXT, chat_uri TEXT, title TEXT, title_source TEXT);
|
||||
CREATE TABLE chats_v2 (chat_uri TEXT PRIMARY KEY, owner_session_uri TEXT, chat_order INTEGER, provider_data TEXT, metadata TEXT, tombstoned INTEGER);
|
||||
INSERT INTO sessions_v2 VALUES ('copilotcli:/vs1', '{}', 100);
|
||||
INSERT INTO chats_v2 VALUES ('chat:/vs1', 'copilotcli:/vs1', 0, '{\"sdkSessionId\":\"copilot-vscode\"}', '{\"data\":{\"summary\":\"Session\",\"titleSource\":\"user\"}}', 0);
|
||||
INSERT INTO sessions_v2 VALUES ('copilotcli:/vs2', '{}', 100);
|
||||
INSERT INTO chats_v2 VALUES ('chat:/vs2', 'copilotcli:/vs2', 0, '{\"sdkSessionId\":\"copilot-placeholder\"}', '{\"data\":{\"summary\":\"New session\",\"titleSource\":\"auto\"}}', 0);",
|
||||
);
|
||||
|
||||
let sessions = copilot_sessions(&copilot_home, Some(tmp.path()), Path::new("/work"));
|
||||
assert_eq!(sessions.len(), 5);
|
||||
let mut by_id: HashMap<_, _> = sessions.into_iter().map(|s| (s.session_id.clone(), s)).collect();
|
||||
let named = by_id.remove("copilot-1").unwrap();
|
||||
assert_eq!((named.provider.as_str(), named.title.as_str()), ("copilot", "Fix parser and tests"));
|
||||
assert_eq!(named.cwd.as_deref(), Some("/work/app/api"));
|
||||
assert!(named.in_use);
|
||||
assert_eq!(by_id.remove("copilot-block").unwrap().title, "check why excalidraw font is not displayed");
|
||||
assert_eq!(by_id.remove("copilot-vscode").unwrap().title, "Session");
|
||||
assert_eq!(by_id.remove("copilot-placeholder").unwrap().title, "Greeting exchange");
|
||||
let unnamed = by_id.remove("copilot-2").unwrap();
|
||||
assert_eq!(unnamed.title, "add a regression test");
|
||||
assert!(!unnamed.in_use);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -16,19 +16,14 @@ pub(crate) fn from_content(content: &Value) -> Option<AgentImage> {
|
||||
if let (Some(data), Some(mime)) = (str_of(content, "data"), str_of(content, "mimeType"))
|
||||
&& mime.starts_with("image/")
|
||||
{
|
||||
return Some(AgentImage { mime_type: mime.into(), data: data.into(), name: None, inline_number: None });
|
||||
return Some(AgentImage { mime_type: mime.into(), data: data.into(), name: None });
|
||||
}
|
||||
from_uri(str_of(content, "uri")?)
|
||||
}
|
||||
"resource" => {
|
||||
let resource = content.get("resource")?;
|
||||
let (data, mime) = (str_of(resource, "blob")?, str_of(resource, "mimeType")?);
|
||||
mime.starts_with("image/").then(|| AgentImage {
|
||||
mime_type: mime.into(),
|
||||
data: data.into(),
|
||||
name: None,
|
||||
inline_number: None,
|
||||
})
|
||||
mime.starts_with("image/").then(|| AgentImage { mime_type: mime.into(), data: data.into(), name: None })
|
||||
}
|
||||
"resource_link" => {
|
||||
let uri = str_of(content, "uri")?;
|
||||
@@ -56,7 +51,6 @@ pub(crate) fn from_uri(uri: &str) -> Option<AgentImage> {
|
||||
mime_type: mime.into(),
|
||||
data: data.into(),
|
||||
name: None,
|
||||
inline_number: None,
|
||||
});
|
||||
}
|
||||
uri.starts_with("file://").then(|| from_file(Path::new(&uri_path(uri))))?
|
||||
@@ -73,7 +67,6 @@ pub(crate) fn from_file(path: &Path) -> Option<AgentImage> {
|
||||
mime_type: mime.into(),
|
||||
data: base64::engine::general_purpose::STANDARD.encode(bytes),
|
||||
name: path.file_name().and_then(|n| n.to_str()).map(str::to_owned),
|
||||
inline_number: None,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
+277
-1581
File diff suppressed because it is too large.
Load diff
@@ -68,27 +68,9 @@ fn to_mcp_server(scope: McpScope, name: &str, cfg: &AgentMcpServer) -> McpServer
|
||||
headers: cfg.headers.iter().map(|(k, v)| McpKeyValue { name: k.clone(), value: v.clone() }).collect(),
|
||||
agents: cfg.agents.clone(),
|
||||
unapproved: false,
|
||||
plugin_id: None,
|
||||
plugin_name: None,
|
||||
registry_name: cfg.registry_name.clone(),
|
||||
registry_url: cfg.registry_url.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Merges `projected` MCP servers from enabled agent plugins behind `configured` User and
|
||||
/// Workspace servers so standalone settings entries always take precedence on name clashes.
|
||||
pub fn merge_projected_servers(mut configured: Vec<McpServer>, projected: Vec<McpServer>) -> Vec<McpServer> {
|
||||
let existing: HashSet<String> = configured.iter().map(|s| s.name.clone()).collect();
|
||||
// Same-named servers from different bundles are distinct rows (ids are `plugin:<bundle>:<server>`).
|
||||
let mut seen_projected: HashSet<String> = HashSet::new();
|
||||
for srv in projected {
|
||||
if !existing.contains(&srv.name) && seen_projected.insert(srv.id.clone()) {
|
||||
configured.push(srv);
|
||||
}
|
||||
}
|
||||
configured
|
||||
}
|
||||
|
||||
fn normalize_provider(id: &str) -> &str {
|
||||
id.strip_suffix("-acp").unwrap_or(id)
|
||||
}
|
||||
@@ -256,28 +238,6 @@ pub fn apply_save(
|
||||
if input.scope == McpScope::Workspace && !has_workspace {
|
||||
return Err("Open a project to configure workspace MCP servers".into());
|
||||
}
|
||||
let existing_meta = input.id.as_deref().and_then(parse_server_id).and_then(|(prev_scope, prev_name)| {
|
||||
let map = match prev_scope {
|
||||
McpScope::User => &*user,
|
||||
McpScope::Workspace => &*workspace,
|
||||
};
|
||||
map.get(prev_name).map(|prev| (prev.registry_name.clone(), prev.registry_url.clone()))
|
||||
});
|
||||
let registry_name = input
|
||||
.registry_name
|
||||
.as_deref()
|
||||
.map(str::trim)
|
||||
.filter(|s| !s.is_empty())
|
||||
.map(str::to_owned)
|
||||
.or_else(|| existing_meta.as_ref().and_then(|(rn, _)| rn.clone()));
|
||||
let registry_url = input
|
||||
.registry_url
|
||||
.as_deref()
|
||||
.map(str::trim)
|
||||
.filter(|s| !s.is_empty())
|
||||
.map(str::to_owned)
|
||||
.or_else(|| existing_meta.and_then(|(_, ru)| ru));
|
||||
|
||||
let cfg = match input.transport {
|
||||
McpTransport::Stdio => {
|
||||
let cmd = input.command.as_deref().map(str::trim).unwrap_or_default();
|
||||
@@ -301,8 +261,6 @@ pub fn apply_save(
|
||||
url: None,
|
||||
headers: BTreeMap::new(),
|
||||
agents: normalize_agents_list(input.agents),
|
||||
registry_name,
|
||||
registry_url,
|
||||
}
|
||||
}
|
||||
McpTransport::Http | McpTransport::Sse => {
|
||||
@@ -327,8 +285,6 @@ pub fn apply_save(
|
||||
url: Some(url.to_owned()),
|
||||
headers,
|
||||
agents: normalize_agents_list(input.agents),
|
||||
registry_name,
|
||||
registry_url,
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -443,8 +399,13 @@ pub fn apply_save_json(
|
||||
Ok(saved_names)
|
||||
}
|
||||
|
||||
const COPILOT_PLUGIN_MANIFESTS: &[&str] =
|
||||
&[".github/plugin/plugin.json", ".plugin/plugin.json", ".claude-plugin/plugin.json", "plugin.json"];
|
||||
const COPILOT_PLUGIN_MANIFESTS: &[&str] = &[
|
||||
".github/plugin/plugin.json",
|
||||
".plugin/plugin.json",
|
||||
".claude-plugin/plugin.json",
|
||||
".cursor-plugin/plugin.json",
|
||||
"plugin.json",
|
||||
];
|
||||
|
||||
#[derive(Clone, PartialEq, Eq)]
|
||||
enum SourceFormat {
|
||||
@@ -1046,8 +1007,6 @@ fn parse_one_server_def(obj: &serde_json::Map<String, Value>) -> Option<AgentMcp
|
||||
url,
|
||||
headers: parse_key_values_map(obj.get("headers")),
|
||||
agents,
|
||||
registry_name: None,
|
||||
registry_url: None,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1092,14 +1051,6 @@ fn extract_servers_from_root(root: &Value, fallback_name: Option<&str>) -> BTree
|
||||
out
|
||||
}
|
||||
|
||||
pub(crate) fn read_external_mcp_file(path: &Path) -> BTreeMap<String, AgentMcpServer> {
|
||||
read_external_file(path)
|
||||
}
|
||||
|
||||
pub(crate) fn parse_mcp_value(root: &Value) -> Result<BTreeMap<String, AgentMcpServer>, String> {
|
||||
Ok(extract_servers_from_root(root, None))
|
||||
}
|
||||
|
||||
fn read_external_file(path: &Path) -> BTreeMap<String, AgentMcpServer> {
|
||||
let Ok(text) = std::fs::read_to_string(path) else {
|
||||
return BTreeMap::new();
|
||||
@@ -1137,7 +1088,15 @@ pub async fn probe_stdio_server(server: &AgentMcpServer, cwd: &Path) -> McpProbe
|
||||
env.push((k.clone(), v.clone()));
|
||||
}
|
||||
}
|
||||
let program = ide_jsonrpc::resolve_spawn_program(raw_cmd, &env).to_string_lossy().into_owned();
|
||||
let search_path = env
|
||||
.iter()
|
||||
.find(|(k, _)| k.eq_ignore_ascii_case("PATH"))
|
||||
.map(|(_, v)| std::ffi::OsString::from(v))
|
||||
.or_else(|| ide_core::process::host_var_os("PATH"))
|
||||
.unwrap_or_default();
|
||||
let program = ide_core::process::find_executable(raw_cmd, &search_path)
|
||||
.map(|p| p.to_string_lossy().into_owned())
|
||||
.unwrap_or_else(|| raw_cmd.to_owned());
|
||||
|
||||
let stderr_lines = std::sync::Arc::new(parking_lot::Mutex::new(Vec::<String>::new()));
|
||||
let stderr_capture = stderr_lines.clone();
|
||||
@@ -1300,10 +1259,6 @@ mod tests {
|
||||
headers: Vec::new(),
|
||||
agents: Vec::new(),
|
||||
unapproved: false,
|
||||
plugin_id: None,
|
||||
plugin_name: None,
|
||||
registry_name: None,
|
||||
registry_url: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1359,8 +1314,6 @@ mod tests {
|
||||
url: None,
|
||||
headers: Vec::new(),
|
||||
agents: Vec::new(),
|
||||
registry_name: None,
|
||||
registry_url: None,
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
@@ -1381,8 +1334,6 @@ mod tests {
|
||||
url: None,
|
||||
headers: Vec::new(),
|
||||
agents: Vec::new(),
|
||||
registry_name: None,
|
||||
registry_url: None,
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
@@ -1403,8 +1354,6 @@ mod tests {
|
||||
url: Some("https://example.com/mcp".into()),
|
||||
headers: vec![McpKeyValue { name: "Authorization".into(), value: "Bearer secret".into() }],
|
||||
agents: vec!["claude".into()],
|
||||
registry_name: None,
|
||||
registry_url: None,
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,14 +1,14 @@
|
||||
//! Unified Agent Rules & Memory hub: discovers curated instruction files, path-scoped
|
||||
//! rules, and cross-session learned auto-memories across coding agents (`claude`, `codex`,
|
||||
//! `copilot`, `cursor`, `gemini`, `hermes`, and custom ACP agents), deduplicates symlinks
|
||||
//! and `@AGENTS.md` wrapper imports, resolves per-provider auto-memory policies under
|
||||
//! Workspace Trust, and builds native per-session `_meta.openidea.memory` payloads only
|
||||
//! for drivers that enforce them (`claude`, `codex`).
|
||||
//! Unified Agent Memory hub (#6810): discovers curated instruction files, path-scoped
|
||||
//! rules, and cross-session learned auto-memories across every coding agent (`claude`,
|
||||
//! `codex`, `copilot`, `cursor`, `gemini`, `hermes`, `opencode`, and custom ACP agents),
|
||||
//! deduplicates symlinks and `@AGENTS.md` imports, resolves `[agents.memory]` policies
|
||||
//! under Workspace Trust without mutating tracked repository files, stages per-session
|
||||
//! `_meta.openidea.memory` delivery for each driver.
|
||||
|
||||
use crate::{
|
||||
AgentAutoMemoryStatus, AgentMemoryCatalog, AgentMemoryCreateTarget, AgentMemoryEntry, AgentMemoryKind,
|
||||
AgentMemoryOrigin, AgentMemoryOverrides, AgentMemorySettings, AgentMemorySource, AutoMemoryMode,
|
||||
CreateAgentMemoryInput, McpScope, PromoteAgentMemoryInput, hermes,
|
||||
AgentAutoMemoryStatus, AgentMemoryCatalog, AgentMemoryCreateTarget, AgentMemoryEntry, AgentMemoryEntryPolicy,
|
||||
AgentMemoryKind, AgentMemoryMode, AgentMemoryOrigin, AgentMemoryOverrides, AgentMemorySettings, AgentMemorySource,
|
||||
AgentMemoryState, AutoMemoryMode, CreateAgentMemoryInput, McpScope, PromoteAgentMemoryInput, hermes,
|
||||
};
|
||||
use ide_core::output_encoding::strip_ansi;
|
||||
use serde::{Deserialize, Serialize};
|
||||
@@ -21,11 +21,7 @@ const CLAUDE_MEMORY_INDEX_WARN_LINES: u32 = 180;
|
||||
const CLAUDE_MEMORY_INDEX_BYTE_CAP: u64 = 25 * 1024;
|
||||
const CLAUDE_MEMORY_INDEX_WARN_BYTES: u64 = 22 * 1024;
|
||||
const INSTRUCTION_WARN_LINES: u32 = 200;
|
||||
|
||||
const CLAUDE_AUTO_MODES: &[AutoMemoryMode] = &[AutoMemoryMode::Inherit, AutoMemoryMode::ReadWrite, AutoMemoryMode::Off];
|
||||
const CODEX_AUTO_MODES: &[AutoMemoryMode] =
|
||||
&[AutoMemoryMode::Inherit, AutoMemoryMode::ReadWrite, AutoMemoryMode::ReadOnly, AutoMemoryMode::Off];
|
||||
const HERMES_AUTO_MODES: &[AutoMemoryMode] = &[AutoMemoryMode::ReadWrite, AutoMemoryMode::Off];
|
||||
const MAX_STAGED_SYSTEM_BYTES: usize = 32 * 1024;
|
||||
|
||||
const SKIP_MONOREPO_DIRS: &[&str] =
|
||||
&["node_modules", "target", "dist", "build", "out", "vendor", "coverage", ".git", ".openidea", ".idea"];
|
||||
@@ -50,43 +46,56 @@ impl Default for MemoryPolicy {
|
||||
}
|
||||
}
|
||||
|
||||
/// Per-session auto-memory payload attached to `session/new`, `session/load`, and `session/fork`
|
||||
/// at `_meta.openidea.memory` for native drivers that enforce it (`claude`, `codex`).
|
||||
/// Per-session memory payload attached to `session/new`, `session/load`, and `session/fork`
|
||||
/// at `_meta.openidea.memory`.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", default)]
|
||||
pub struct Delivery {
|
||||
pub auto_memory: AutoMemoryMode,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub claude_auto_memory: Option<bool>,
|
||||
#[serde(skip_serializing_if = "Vec::is_empty")]
|
||||
pub claude_md_excludes: Vec<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub claude_instruction_files: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub claude_add_dir: Option<PathBuf>,
|
||||
#[serde(skip_serializing_if = "is_false")]
|
||||
pub claude_additional_dirs_claude_md: bool,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub codex_use_memories: Option<bool>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub codex_generate_memories: Option<bool>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub codex_developer_instructions: Option<String>,
|
||||
#[serde(skip_serializing_if = "is_false")]
|
||||
pub copilot_exclude_store_memory: bool,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub copilot_enable_memory: Option<bool>,
|
||||
#[serde(skip_serializing_if = "is_false")]
|
||||
pub copilot_disable_custom_instructions: bool,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub copilot_system_message: Option<String>,
|
||||
}
|
||||
|
||||
/// Normalizes a provider id to its auto-memory policy key.
|
||||
/// Native `claude` and `codex` keep their exact ids (distinct from `claude-acp` / `codex-acp`,
|
||||
/// whose external ACP adapters do not consume `_meta.openidea.memory`); Hermes profiles collapse
|
||||
/// onto `"hermes"`.
|
||||
pub fn provider_key(provider: &str) -> &str {
|
||||
let trimmed = provider.trim();
|
||||
if trimmed == "hermes" || trimmed.starts_with("hermes-") { "hermes" } else { trimmed }
|
||||
fn is_false(b: &bool) -> bool {
|
||||
!*b
|
||||
}
|
||||
|
||||
/// Auto-memory modes enforced by `provider`. Empty means the agent manages auto-memory itself.
|
||||
pub fn supported_auto_memory_modes(provider: &str) -> &'static [AutoMemoryMode] {
|
||||
match provider_key(provider) {
|
||||
"claude" => CLAUDE_AUTO_MODES,
|
||||
"codex" => CODEX_AUTO_MODES,
|
||||
"hermes" => HERMES_AUTO_MODES,
|
||||
_ => &[],
|
||||
pub fn normalize_provider_id(provider: &str) -> &str {
|
||||
let base = provider.strip_suffix("-acp").unwrap_or(provider);
|
||||
if base == "hermes" || base.starts_with("hermes-") { "hermes" } else { base }
|
||||
}
|
||||
|
||||
pub fn matches_agent_filter(agents: &[String], provider: &str) -> bool {
|
||||
if agents.is_empty() {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/// True when `provider`'s auto-memory mode is persisted directly in its own native config file
|
||||
/// (e.g. `~/.hermes/config.yaml`) rather than per-project settings or per-session overrides.
|
||||
pub fn is_native_config_auto_memory(provider: &str) -> bool {
|
||||
provider_key(provider) == "hermes"
|
||||
let target = normalize_provider_id(provider);
|
||||
agents.iter().any(|raw| {
|
||||
let trimmed = raw.trim();
|
||||
trimmed.eq_ignore_ascii_case(provider) || normalize_provider_id(trimmed).eq_ignore_ascii_case(target)
|
||||
})
|
||||
}
|
||||
|
||||
fn source_key(source: AgentMemorySource) -> &'static str {
|
||||
@@ -444,27 +453,7 @@ pub fn discover_memories(workspaces: &[PathBuf], home: Option<&Path>) -> Vec<Age
|
||||
out
|
||||
}
|
||||
|
||||
/// Discovers all standalone memory entries across `workspaces` and `home`, then appends
|
||||
/// projected rule/context entries from enabled agent plugins (deduplicated by canonical path).
|
||||
pub fn discover_memories_with_plugins(
|
||||
workspaces: &[PathBuf],
|
||||
home: Option<&Path>,
|
||||
projected: Vec<AgentMemoryEntry>,
|
||||
) -> Vec<AgentMemoryEntry> {
|
||||
let mut out = discover_memories(workspaces, home);
|
||||
let mut seen: HashSet<PathBuf> =
|
||||
out.iter().map(|e| dunce::canonicalize(&e.path.0).unwrap_or_else(|_| e.path.0.clone())).collect();
|
||||
for mut entry in projected {
|
||||
let canon = dunce::canonicalize(&entry.path.0).unwrap_or_else(|_| entry.path.0.clone());
|
||||
entry.path = canon.clone().into();
|
||||
if seen.insert(canon) {
|
||||
out.push(entry);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Resolves the full [`AgentMemoryCatalog`] (discovered entries + per-provider auto-memory statuses)
|
||||
/// Resolves the full [`AgentMemoryCatalog`] (entries + per-provider auto-memory statuses)
|
||||
/// against `policy` and optional per-session `session_overrides`.
|
||||
pub fn resolve_catalog(
|
||||
entries: Vec<AgentMemoryEntry>,
|
||||
@@ -472,45 +461,105 @@ pub fn resolve_catalog(
|
||||
policy: &MemoryPolicy,
|
||||
home: Option<&Path>,
|
||||
) -> AgentMemoryCatalog {
|
||||
let providers = build_provider_statuses(&entries, session_overrides, policy, home);
|
||||
AgentMemoryCatalog { entries, providers, workspace_trusted: policy.workspace_trusted }
|
||||
let resolved_entries = resolve_entries(entries, session_overrides, policy);
|
||||
let (auto_memory, auto_memory_origin) = resolve_global_auto_memory(session_overrides, policy);
|
||||
let providers = build_provider_statuses(&resolved_entries, session_overrides, policy, home);
|
||||
AgentMemoryCatalog { entries: resolved_entries, providers, auto_memory, auto_memory_origin }
|
||||
}
|
||||
|
||||
/// Resolves the effective [`AutoMemoryMode`] for one `provider` that supports OpenIDEA-managed
|
||||
/// settings/session overrides (`claude`, `codex`).
|
||||
/// Precedence: `Session Override > Workspace Settings (when trusted or Off) > User Settings > Inherit`.
|
||||
/// Resolves every discovered memory entry's effective [`AgentMemoryMode`] with precedence:
|
||||
/// `Workspace Trust > Session Override > Workspace Settings > User Settings > Default (Auto)`.
|
||||
pub fn resolve_entries(
|
||||
entries: Vec<AgentMemoryEntry>,
|
||||
session_overrides: Option<&AgentMemoryOverrides>,
|
||||
policy: &MemoryPolicy,
|
||||
) -> Vec<AgentMemoryState> {
|
||||
let mut out = Vec::with_capacity(entries.len());
|
||||
for entry in entries {
|
||||
if entry.source.is_workspace() && !policy.workspace_trusted {
|
||||
out.push(AgentMemoryState {
|
||||
entry,
|
||||
mode: AgentMemoryMode::Off,
|
||||
agents: Vec::new(),
|
||||
origin: AgentMemoryOrigin::Trust,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
let ws_pol = lookup_entry_policy(&policy.workspace.entries, &entry.id)
|
||||
.filter(|p| policy.workspace_trusted || p.mode == AgentMemoryMode::Off);
|
||||
let user_pol = lookup_entry_policy(&policy.user.entries, &entry.id);
|
||||
let agents = ws_pol
|
||||
.filter(|p| !p.agents.is_empty())
|
||||
.or_else(|| user_pol.filter(|p| !p.agents.is_empty()))
|
||||
.map(|p| p.agents.clone())
|
||||
.unwrap_or_default();
|
||||
|
||||
let (mode, origin) =
|
||||
if let Some(chosen) = session_overrides.and_then(|s| lookup_session_entry(&s.entries, &entry.id)) {
|
||||
(chosen, AgentMemoryOrigin::Session)
|
||||
} else if let Some(ws) = ws_pol {
|
||||
(ws.mode, AgentMemoryOrigin::Workspace)
|
||||
} else if let Some(us) = user_pol {
|
||||
(us.mode, AgentMemoryOrigin::User)
|
||||
} else {
|
||||
(AgentMemoryMode::Auto, AgentMemoryOrigin::None)
|
||||
};
|
||||
out.push(AgentMemoryState { entry, mode, agents, origin });
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
pub fn resolve_global_auto_memory(
|
||||
session_overrides: Option<&AgentMemoryOverrides>,
|
||||
policy: &MemoryPolicy,
|
||||
) -> (AutoMemoryMode, AgentMemoryOrigin) {
|
||||
if let Some(mode) = session_overrides.and_then(|s| s.auto_memory) {
|
||||
return (mode, AgentMemoryOrigin::Session);
|
||||
}
|
||||
let ws_mode = policy.workspace.auto_memory;
|
||||
if ws_mode != AutoMemoryMode::Inherit && (policy.workspace_trusted || ws_mode == AutoMemoryMode::Off) {
|
||||
return (ws_mode, AgentMemoryOrigin::Workspace);
|
||||
}
|
||||
if policy.user.auto_memory != AutoMemoryMode::Inherit {
|
||||
return (policy.user.auto_memory, AgentMemoryOrigin::User);
|
||||
}
|
||||
(AutoMemoryMode::Inherit, AgentMemoryOrigin::None)
|
||||
}
|
||||
|
||||
/// Resolves the effective [`AutoMemoryMode`] for one `provider` (`claude`, `codex`, `copilot`, `hermes`, etc.).
|
||||
pub fn resolve_provider_auto_memory(
|
||||
provider: &str,
|
||||
session_overrides: Option<&AgentMemoryOverrides>,
|
||||
policy: &MemoryPolicy,
|
||||
) -> (AutoMemoryMode, AgentMemoryOrigin) {
|
||||
let supported = supported_auto_memory_modes(provider);
|
||||
if supported.is_empty() || is_native_config_auto_memory(provider) {
|
||||
return (AutoMemoryMode::Inherit, AgentMemoryOrigin::None);
|
||||
}
|
||||
let accepts = |mode: AutoMemoryMode| mode != AutoMemoryMode::Inherit && supported.contains(&mode);
|
||||
if let Some(mode) = session_overrides.and_then(|s| s.auto_memory)
|
||||
&& accepts(mode)
|
||||
{
|
||||
if let Some(mode) = session_overrides.and_then(|s| s.auto_memory) {
|
||||
return (mode, AgentMemoryOrigin::Session);
|
||||
}
|
||||
let key = provider_key(provider);
|
||||
let key = normalize_provider_id(provider);
|
||||
if let Some(ws_prov) = policy.workspace.providers.get(key)
|
||||
&& accepts(ws_prov.auto_memory)
|
||||
&& ws_prov.auto_memory != AutoMemoryMode::Inherit
|
||||
&& (policy.workspace_trusted || ws_prov.auto_memory == AutoMemoryMode::Off)
|
||||
{
|
||||
return (ws_prov.auto_memory, AgentMemoryOrigin::Workspace);
|
||||
}
|
||||
if policy.workspace.auto_memory != AutoMemoryMode::Inherit
|
||||
&& (policy.workspace_trusted || policy.workspace.auto_memory == AutoMemoryMode::Off)
|
||||
{
|
||||
return (policy.workspace.auto_memory, AgentMemoryOrigin::Workspace);
|
||||
}
|
||||
if let Some(user_prov) = policy.user.providers.get(key)
|
||||
&& accepts(user_prov.auto_memory)
|
||||
&& user_prov.auto_memory != AutoMemoryMode::Inherit
|
||||
{
|
||||
return (user_prov.auto_memory, AgentMemoryOrigin::User);
|
||||
}
|
||||
if policy.user.auto_memory != AutoMemoryMode::Inherit {
|
||||
return (policy.user.auto_memory, AgentMemoryOrigin::User);
|
||||
}
|
||||
(AutoMemoryMode::Inherit, AgentMemoryOrigin::None)
|
||||
}
|
||||
|
||||
fn build_provider_statuses(
|
||||
entries: &[AgentMemoryEntry],
|
||||
states: &[AgentMemoryState],
|
||||
session_overrides: Option<&AgentMemoryOverrides>,
|
||||
policy: &MemoryPolicy,
|
||||
home: Option<&Path>,
|
||||
@@ -518,9 +567,11 @@ fn build_provider_statuses(
|
||||
let stats_for = |src: AgentMemorySource| -> (u32, u32) {
|
||||
let mut count = 0u32;
|
||||
let mut tokens = 0u32;
|
||||
for e in entries.iter().filter(|e| e.source == src) {
|
||||
for s in states.iter().filter(|s| s.entry.source == src) {
|
||||
count += 1;
|
||||
tokens = tokens.saturating_add(e.approx_tokens);
|
||||
if s.mode != AgentMemoryMode::Off {
|
||||
tokens = tokens.saturating_add(s.entry.approx_tokens);
|
||||
}
|
||||
}
|
||||
(count, tokens)
|
||||
};
|
||||
@@ -543,12 +594,19 @@ fn build_provider_statuses(
|
||||
codex_dir.as_ref().map(|d| markdown_files(&d.join("rollout_summaries"), 1).len() as u32).unwrap_or(0);
|
||||
let (codex_mode, codex_origin) = resolve_provider_auto_memory("codex", session_overrides, policy);
|
||||
|
||||
let (copilot_mode, copilot_origin) = resolve_provider_auto_memory("copilot", session_overrides, policy);
|
||||
|
||||
let (hermes_notes, hermes_tokens) = stats_for(AgentMemorySource::HermesAuto);
|
||||
let hermes_dir = hermes_root(home).map(|r| r.join("memories"));
|
||||
let (hermes_mode, hermes_origin) = match hermes_root(home).and_then(|root| read_hermes_config_memory_mode(&root)) {
|
||||
Some(cfg_mode) => (cfg_mode, AgentMemoryOrigin::Native),
|
||||
None => (AutoMemoryMode::ReadWrite, AgentMemoryOrigin::Native),
|
||||
};
|
||||
let (mut hermes_mode, hermes_origin) = resolve_provider_auto_memory("hermes", session_overrides, policy);
|
||||
if hermes_mode == AutoMemoryMode::Inherit
|
||||
&& let Some(root) = hermes_root(home)
|
||||
&& let Some(cfg_mode) = read_hermes_config_memory_mode(&root)
|
||||
{
|
||||
hermes_mode = cfg_mode;
|
||||
}
|
||||
|
||||
let (acp_mode, acp_origin) = resolve_provider_auto_memory("acp", session_overrides, policy);
|
||||
|
||||
vec![
|
||||
AgentAutoMemoryStatus {
|
||||
@@ -556,12 +614,12 @@ fn build_provider_statuses(
|
||||
label: "Claude Code".into(),
|
||||
mode: claude_mode,
|
||||
origin: claude_origin,
|
||||
supported_modes: CLAUDE_AUTO_MODES.to_vec(),
|
||||
native_config_only: false,
|
||||
note_count: claude_notes,
|
||||
rollout_count: 0,
|
||||
approx_tokens: claude_tokens,
|
||||
storage_path: claude_dir.map(Into::into),
|
||||
supports_auto_control: true,
|
||||
supports_file_exclusion: true,
|
||||
supports_reset: true,
|
||||
},
|
||||
AgentAutoMemoryStatus {
|
||||
@@ -569,81 +627,295 @@ fn build_provider_statuses(
|
||||
label: "Codex".into(),
|
||||
mode: codex_mode,
|
||||
origin: codex_origin,
|
||||
supported_modes: CODEX_AUTO_MODES.to_vec(),
|
||||
native_config_only: false,
|
||||
note_count: codex_notes,
|
||||
rollout_count: codex_rollouts,
|
||||
approx_tokens: codex_tokens,
|
||||
storage_path: codex_dir.map(Into::into),
|
||||
supports_auto_control: true,
|
||||
supports_file_exclusion: false,
|
||||
supports_reset: true,
|
||||
},
|
||||
AgentAutoMemoryStatus {
|
||||
provider: "copilot".into(),
|
||||
label: "GitHub Copilot".into(),
|
||||
mode: copilot_mode,
|
||||
origin: copilot_origin,
|
||||
note_count: 0,
|
||||
rollout_count: 0,
|
||||
approx_tokens: 0,
|
||||
storage_path: home.map(|h| h.join(".copilot").into()),
|
||||
supports_auto_control: true,
|
||||
supports_file_exclusion: false,
|
||||
supports_reset: false,
|
||||
},
|
||||
AgentAutoMemoryStatus {
|
||||
provider: "hermes".into(),
|
||||
label: "Hermes Agent".into(),
|
||||
mode: hermes_mode,
|
||||
origin: hermes_origin,
|
||||
supported_modes: HERMES_AUTO_MODES.to_vec(),
|
||||
native_config_only: true,
|
||||
note_count: hermes_notes,
|
||||
rollout_count: 0,
|
||||
approx_tokens: hermes_tokens,
|
||||
storage_path: hermes_dir.map(Into::into),
|
||||
supports_auto_control: true,
|
||||
supports_file_exclusion: false,
|
||||
supports_reset: true,
|
||||
},
|
||||
AgentAutoMemoryStatus {
|
||||
provider: "acp".into(),
|
||||
label: "Cursor / Gemini / ACP".into(),
|
||||
mode: acp_mode,
|
||||
origin: acp_origin,
|
||||
note_count: 0,
|
||||
rollout_count: 0,
|
||||
approx_tokens: 0,
|
||||
storage_path: None,
|
||||
supports_auto_control: false,
|
||||
supports_file_exclusion: false,
|
||||
supports_reset: false,
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
/// Builds the per-session [`Delivery`] payload (`_meta.openidea.memory`) for a native driver
|
||||
/// (`"claude"` or `"codex"`). Returns `None` when `auto_memory` is `Inherit` or the driver
|
||||
/// does not consume `_meta.openidea.memory`.
|
||||
pub fn build_delivery(driver_key: &str, auto_memory: AutoMemoryMode) -> Option<Delivery> {
|
||||
if auto_memory == AutoMemoryMode::Inherit {
|
||||
return None;
|
||||
}
|
||||
match driver_key {
|
||||
"claude" => match auto_memory {
|
||||
AutoMemoryMode::ReadWrite => {
|
||||
Some(Delivery { auto_memory, claude_auto_memory: Some(true), ..Delivery::default() })
|
||||
}
|
||||
AutoMemoryMode::Off => {
|
||||
Some(Delivery { auto_memory, claude_auto_memory: Some(false), ..Delivery::default() })
|
||||
}
|
||||
AutoMemoryMode::Inherit | AutoMemoryMode::ReadOnly => None,
|
||||
},
|
||||
"codex" => match auto_memory {
|
||||
AutoMemoryMode::ReadWrite => Some(Delivery {
|
||||
auto_memory,
|
||||
codex_use_memories: Some(true),
|
||||
codex_generate_memories: Some(true),
|
||||
..Delivery::default()
|
||||
}),
|
||||
AutoMemoryMode::ReadOnly => Some(Delivery {
|
||||
auto_memory,
|
||||
codex_use_memories: Some(true),
|
||||
codex_generate_memories: Some(false),
|
||||
..Delivery::default()
|
||||
}),
|
||||
AutoMemoryMode::Off => Some(Delivery {
|
||||
auto_memory,
|
||||
codex_use_memories: Some(false),
|
||||
codex_generate_memories: Some(false),
|
||||
..Delivery::default()
|
||||
}),
|
||||
AutoMemoryMode::Inherit => None,
|
||||
},
|
||||
_ => None,
|
||||
}
|
||||
/// Directory under `<store_dir>/session-memory/<task_id>` holding per-session staged rules.
|
||||
pub fn farm_dir(store_dir: &Path, task_id: &str) -> PathBuf {
|
||||
store_dir.join("session-memory").join(task_id)
|
||||
}
|
||||
|
||||
/// Explicitly updates Hermes's native `config.yaml` (`memory_enabled` and `user_profile_enabled`).
|
||||
/// Never called during session startup — only when the user changes Hermes's setting directly.
|
||||
pub fn set_hermes_auto_memory(provider: &str, mode: AutoMemoryMode, home: Option<&Path>) -> Result<(), String> {
|
||||
if !matches!(mode, AutoMemoryMode::ReadWrite | AutoMemoryMode::Off) {
|
||||
return Err("Hermes auto-memory supports only On (readWrite) or Off".into());
|
||||
/// Removes a deleted task's staged memory folder, if any.
|
||||
pub fn remove_farm(store_dir: &Path, task_id: &str) {
|
||||
let _ = std::fs::remove_dir_all(farm_dir(store_dir, task_id));
|
||||
}
|
||||
|
||||
/// Computes the per-session [`Delivery`] payload (`_meta.openidea.memory`) for `provider`,
|
||||
/// staging non-native rules into `farm` where needed (e.g. Claude `.claude/rules/`).
|
||||
pub fn stage(
|
||||
farm: &Path,
|
||||
provider: &str,
|
||||
states: &[AgentMemoryState],
|
||||
auto_memory: AutoMemoryMode,
|
||||
cwd: &Path,
|
||||
home: Option<&Path>,
|
||||
) -> std::io::Result<Delivery> {
|
||||
let norm = normalize_provider_id(provider);
|
||||
let mut out = Delivery { auto_memory, ..Delivery::default() };
|
||||
|
||||
let claude_rules_dir = farm.join(".claude/rules");
|
||||
match std::fs::remove_dir_all(&claude_rules_dir) {
|
||||
Err(e) if e.kind() != std::io::ErrorKind::NotFound => return Err(e),
|
||||
_ => {}
|
||||
}
|
||||
let root = hermes_root(home).ok_or("Home directory is unavailable")?;
|
||||
let prof_home = hermes::profile_home(&root, provider).unwrap_or(root);
|
||||
write_hermes_config_memory_mode(&prof_home, mode).map_err(|e| e.to_string())
|
||||
|
||||
match norm {
|
||||
"claude" => {
|
||||
out.claude_auto_memory = match auto_memory {
|
||||
AutoMemoryMode::Inherit => None,
|
||||
AutoMemoryMode::ReadWrite => Some(true),
|
||||
// Claude Code has one boolean (`autoMemoryEnabled`): ReadOnly and Off both stop background writes;
|
||||
// existing `MEMORY.md` entries that remain `Auto`/`Always` can still be staged as read-only rules.
|
||||
AutoMemoryMode::ReadOnly | AutoMemoryMode::Off => Some(false),
|
||||
};
|
||||
|
||||
let mut agents_md_active = false;
|
||||
let mut agents_md_off = false;
|
||||
let mut claude_md_active = false;
|
||||
|
||||
for state in states {
|
||||
let effective_on = state.mode != AgentMemoryMode::Off && matches_agent_filter(&state.agents, provider);
|
||||
let p = state.entry.path.0.as_path();
|
||||
let fname = file_name(p).unwrap_or_default();
|
||||
|
||||
if matches!(state.entry.source, AgentMemorySource::Workspace) && fname == "AGENTS.md" {
|
||||
if effective_on {
|
||||
agents_md_active = true;
|
||||
} else {
|
||||
agents_md_off = true;
|
||||
}
|
||||
}
|
||||
if matches!(state.entry.source, AgentMemorySource::ClaudeWorkspace)
|
||||
&& matches!(fname.as_str(), "CLAUDE.md" | "CLAUDE.local.md")
|
||||
&& effective_on
|
||||
{
|
||||
claude_md_active = true;
|
||||
}
|
||||
|
||||
if !effective_on {
|
||||
if !state.entry.source.is_auto() {
|
||||
out.claude_md_excludes.push(p.to_string_lossy().replace('\\', "/"));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
// Stage `Always` rules from other agents, or a `ReadOnly` `ClaudeAuto` `MEMORY.md`,
|
||||
// into `<farm>/.claude/rules/`.
|
||||
let stage_into_claude = (auto_memory == AutoMemoryMode::ReadOnly
|
||||
&& state.entry.source == AgentMemorySource::ClaudeAuto
|
||||
&& fname == "MEMORY.md")
|
||||
|| (state.mode == AgentMemoryMode::Always
|
||||
&& !matches!(
|
||||
state.entry.source,
|
||||
AgentMemorySource::ClaudeWorkspace | AgentMemorySource::ClaudeUser
|
||||
));
|
||||
|
||||
if stage_into_claude {
|
||||
stage_claude_rule(&claude_rules_dir, state)?;
|
||||
}
|
||||
}
|
||||
|
||||
if agents_md_active && claude_md_active {
|
||||
out.claude_instruction_files = Some("claude-md-and-agents-md".into());
|
||||
} else if agents_md_off {
|
||||
out.claude_instruction_files = Some("claude-md".into());
|
||||
}
|
||||
|
||||
if claude_rules_dir.exists() {
|
||||
out.claude_add_dir = Some(farm.to_path_buf());
|
||||
out.claude_additional_dirs_claude_md = true;
|
||||
}
|
||||
}
|
||||
"codex" => {
|
||||
match auto_memory {
|
||||
AutoMemoryMode::Inherit => {}
|
||||
AutoMemoryMode::ReadWrite => {
|
||||
out.codex_use_memories = Some(true);
|
||||
out.codex_generate_memories = Some(true);
|
||||
}
|
||||
AutoMemoryMode::ReadOnly => {
|
||||
out.codex_use_memories = Some(true);
|
||||
out.codex_generate_memories = Some(false);
|
||||
}
|
||||
AutoMemoryMode::Off => {
|
||||
out.codex_use_memories = Some(false);
|
||||
out.codex_generate_memories = Some(false);
|
||||
}
|
||||
}
|
||||
let extra = collect_staged_text(states, provider, cwd, home, |s| {
|
||||
s.mode == AgentMemoryMode::Always
|
||||
&& !matches!(s.entry.source, AgentMemorySource::CodexUser | AgentMemorySource::CodexAuto)
|
||||
});
|
||||
if !extra.is_empty() {
|
||||
out.codex_developer_instructions = Some(extra);
|
||||
}
|
||||
}
|
||||
"copilot" => {
|
||||
match auto_memory {
|
||||
AutoMemoryMode::Inherit => {}
|
||||
AutoMemoryMode::ReadWrite => {
|
||||
out.copilot_enable_memory = Some(true);
|
||||
}
|
||||
AutoMemoryMode::ReadOnly => {
|
||||
out.copilot_enable_memory = Some(true);
|
||||
out.copilot_exclude_store_memory = true;
|
||||
}
|
||||
AutoMemoryMode::Off => {
|
||||
out.copilot_enable_memory = Some(false);
|
||||
out.copilot_exclude_store_memory = true;
|
||||
}
|
||||
}
|
||||
let native_instructions: Vec<&AgentMemoryState> = states
|
||||
.iter()
|
||||
.filter(|s| {
|
||||
matches!(
|
||||
s.entry.source,
|
||||
AgentMemorySource::Workspace
|
||||
| AgentMemorySource::ClaudeWorkspace
|
||||
| AgentMemorySource::GithubWorkspace
|
||||
| AgentMemorySource::CopilotUser
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
if !native_instructions.is_empty()
|
||||
&& native_instructions
|
||||
.iter()
|
||||
.all(|s| s.mode == AgentMemoryMode::Off || !matches_agent_filter(&s.agents, provider))
|
||||
{
|
||||
out.copilot_disable_custom_instructions = true;
|
||||
}
|
||||
let extra = collect_staged_text(states, provider, cwd, home, |s| {
|
||||
s.mode == AgentMemoryMode::Always
|
||||
&& !matches!(s.entry.source, AgentMemorySource::GithubWorkspace | AgentMemorySource::CopilotUser)
|
||||
});
|
||||
if !extra.is_empty() {
|
||||
out.copilot_system_message = Some(extra);
|
||||
}
|
||||
}
|
||||
"hermes" => {
|
||||
if auto_memory != AutoMemoryMode::Inherit
|
||||
&& let Some(root) = hermes_root(home)
|
||||
&& let Some(prof_home) = hermes::profile_home(&root, provider)
|
||||
{
|
||||
let _ = write_hermes_config_memory_mode(&prof_home, auto_memory);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn stage_claude_rule(rules_dir: &Path, state: &AgentMemoryState) -> std::io::Result<()> {
|
||||
let Ok(raw) = std::fs::read_to_string(&state.entry.path.0) else {
|
||||
return Ok(());
|
||||
};
|
||||
std::fs::create_dir_all(rules_dir)?;
|
||||
let fm = Frontmatter::parse(&raw);
|
||||
let body = raw.get(fm.body..).unwrap_or(raw.as_str()).trim();
|
||||
if body.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let slug = sanitize_slug(&state.entry.id);
|
||||
let out_text = if state.mode != AgentMemoryMode::Always && !state.entry.paths.is_empty() {
|
||||
let mut header = String::from("---\npaths:\n");
|
||||
for p in &state.entry.paths {
|
||||
header.push_str(&format!(" - \"{}\"\n", p.replace('"', "\\\"")));
|
||||
}
|
||||
header.push_str("---\n\n");
|
||||
header.push_str(body);
|
||||
header.push('\n');
|
||||
header
|
||||
} else {
|
||||
format!("{body}\n")
|
||||
};
|
||||
std::fs::write(rules_dir.join(format!("{slug}.md")), out_text)
|
||||
}
|
||||
|
||||
fn collect_staged_text<F>(
|
||||
states: &[AgentMemoryState],
|
||||
provider: &str,
|
||||
_cwd: &Path,
|
||||
_home: Option<&Path>,
|
||||
include: F,
|
||||
) -> String
|
||||
where
|
||||
F: Fn(&AgentMemoryState) -> bool,
|
||||
{
|
||||
let mut buf = String::new();
|
||||
for state in states {
|
||||
if state.mode == AgentMemoryMode::Off || !matches_agent_filter(&state.agents, provider) {
|
||||
continue;
|
||||
}
|
||||
if !include(state) {
|
||||
continue;
|
||||
}
|
||||
// Path-scoped rules only enter un-scoped system prompts when explicitly set to `Always`.
|
||||
if state.mode != AgentMemoryMode::Always && !state.entry.paths.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let Ok(raw) = std::fs::read_to_string(&state.entry.path.0) else {
|
||||
continue;
|
||||
};
|
||||
let fm = Frontmatter::parse(&raw);
|
||||
let body = raw.get(fm.body..).unwrap_or(raw.as_str()).trim();
|
||||
if body.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let chunk = format!("## Memory ({})\n{}\n\n", state.entry.title, body);
|
||||
if buf.len() + chunk.len() > MAX_STAGED_SYSTEM_BYTES {
|
||||
break;
|
||||
}
|
||||
buf.push_str(&chunk);
|
||||
}
|
||||
buf.trim().to_owned()
|
||||
}
|
||||
|
||||
// ─── File Operations: Create, Promote, Delete & Reset ───────────────────────────────
|
||||
@@ -772,7 +1044,9 @@ pub fn promote_memory(
|
||||
pub fn delete_memory(id: &str, entries: &[AgentMemoryEntry]) -> Result<(), String> {
|
||||
let entry = entries.iter().find(|e| e.id == id).ok_or_else(|| format!("Memory entry `{id}` was not found"))?;
|
||||
if !entry.writable {
|
||||
return Err("Curated instruction and rule files cannot be deleted here; open the file in the editor.".into());
|
||||
return Err(
|
||||
"Curated instruction and rule files cannot be deleted here; open the file or set its mode to Off.".into()
|
||||
);
|
||||
}
|
||||
match std::fs::remove_file(&entry.path.0) {
|
||||
Ok(()) => Ok(()),
|
||||
@@ -785,7 +1059,7 @@ pub fn delete_memory(id: &str, entries: &[AgentMemoryEntry]) -> Result<(), Strin
|
||||
pub fn reset_provider_memory(provider: &str, workspaces: &[PathBuf], home: Option<&Path>) -> Result<u32, String> {
|
||||
let home = home.ok_or("Home directory is unavailable")?;
|
||||
let mut removed = 0u32;
|
||||
match provider_key(provider) {
|
||||
match normalize_provider_id(provider) {
|
||||
"claude" => {
|
||||
for dir in claude_auto_memory_dirs(&home.join(".claude"), home, workspaces) {
|
||||
for f in markdown_files(&dir, 2) {
|
||||
@@ -840,6 +1114,19 @@ fn validate_slug(raw: &str) -> Result<String, String> {
|
||||
Ok(trimmed.to_owned())
|
||||
}
|
||||
|
||||
fn sanitize_slug(raw: &str) -> String {
|
||||
let mut out = String::new();
|
||||
for ch in raw.chars() {
|
||||
if ch.is_ascii_alphanumeric() || ch == '-' || ch == '_' {
|
||||
out.push(ch.to_ascii_lowercase());
|
||||
} else if !out.ends_with('-') {
|
||||
out.push('-');
|
||||
}
|
||||
}
|
||||
let trimmed = out.trim_matches('-');
|
||||
if trimmed.is_empty() { "memory".into() } else { trimmed.to_owned() }
|
||||
}
|
||||
|
||||
fn format_markdown_with_frontmatter(
|
||||
description: Option<&str>,
|
||||
paths_key: &str,
|
||||
@@ -894,6 +1181,17 @@ fn format_cursor_mdc(description: Option<&str>, globs: &[String], always_apply:
|
||||
out
|
||||
}
|
||||
|
||||
fn lookup_entry_policy<'a>(
|
||||
map: &'a BTreeMap<String, AgentMemoryEntryPolicy>,
|
||||
id: &str,
|
||||
) -> Option<&'a AgentMemoryEntryPolicy> {
|
||||
map.get(id).or_else(|| map.iter().find(|(k, _)| k.eq_ignore_ascii_case(id)).map(|(_, v)| v))
|
||||
}
|
||||
|
||||
fn lookup_session_entry(map: &BTreeMap<String, AgentMemoryMode>, id: &str) -> Option<AgentMemoryMode> {
|
||||
map.get(id).copied().or_else(|| map.iter().find(|(k, _)| k.eq_ignore_ascii_case(id)).map(|(_, v)| *v))
|
||||
}
|
||||
|
||||
fn claude_auto_memory_dirs(claude_home: &Path, home: &Path, workspaces: &[PathBuf]) -> Vec<PathBuf> {
|
||||
let mut dirs = Vec::new();
|
||||
let mut seen = HashSet::new();
|
||||
@@ -1114,8 +1412,6 @@ fn parse_cursor_mdc(path: &Path, rel: &str) -> Option<AgentMemoryEntry> {
|
||||
writable: false,
|
||||
valid: true,
|
||||
warnings,
|
||||
plugin_id: None,
|
||||
plugin_name: None,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1186,8 +1482,6 @@ fn parse_entry(
|
||||
writable,
|
||||
valid: true,
|
||||
warnings,
|
||||
plugin_id: None,
|
||||
plugin_name: None,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1581,114 +1875,113 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn policy_resolution_enforces_workspace_trust_and_provider_capabilities() {
|
||||
fn policy_resolution_enforces_workspace_trust_and_precedence() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let ws = tmp.path().join("ws");
|
||||
let home = tmp.path().join("home");
|
||||
write(&ws.join("AGENTS.md"), "Workspace instructions\n");
|
||||
write(&home.join(".hermes/profile.yaml"), "display_name: default\n");
|
||||
write(&home.join(".claude/CLAUDE.md"), "User memory\n");
|
||||
|
||||
let entries = discover_memories(std::slice::from_ref(&ws), Some(&home));
|
||||
|
||||
let mut ws_settings = AgentMemorySettings::default();
|
||||
ws_settings
|
||||
.providers
|
||||
.insert("claude".into(), crate::AgentProviderMemoryPolicy { auto_memory: AutoMemoryMode::ReadWrite });
|
||||
ws_settings
|
||||
.providers
|
||||
.insert("codex".into(), crate::AgentProviderMemoryPolicy { auto_memory: AutoMemoryMode::Off });
|
||||
let mut ws_settings = AgentMemorySettings { auto_memory: AutoMemoryMode::ReadWrite, ..Default::default() };
|
||||
// Untrusted workspace tries to turn user memory `Always` on (ignored!) and another `Off` (honored).
|
||||
ws_settings.entries.insert(
|
||||
"claudeUser::CLAUDE.md".into(),
|
||||
AgentMemoryEntryPolicy { mode: AgentMemoryMode::Always, agents: Vec::new() },
|
||||
);
|
||||
|
||||
let untrusted = MemoryPolicy {
|
||||
user: AgentMemorySettings::default(),
|
||||
workspace: ws_settings,
|
||||
workspace: ws_settings.clone(),
|
||||
workspace_trusted: false,
|
||||
workspace_roots: vec![ws.clone()],
|
||||
};
|
||||
let cat = resolve_catalog(entries.clone(), None, &untrusted, Some(&home));
|
||||
assert!(!cat.workspace_trusted);
|
||||
// Untrusted workspace cannot enable Claude auto-memory, but can turn Codex auto-memory off.
|
||||
let claude = cat.providers.iter().find(|p| p.provider == "claude").unwrap();
|
||||
assert_eq!((claude.mode, claude.origin), (AutoMemoryMode::Inherit, AgentMemoryOrigin::None));
|
||||
assert_eq!(claude.supported_modes, [AutoMemoryMode::Inherit, AutoMemoryMode::ReadWrite, AutoMemoryMode::Off]);
|
||||
let codex = cat.providers.iter().find(|p| p.provider == "codex").unwrap();
|
||||
assert_eq!((codex.mode, codex.origin), (AutoMemoryMode::Off, AgentMemoryOrigin::Workspace));
|
||||
let hermes = cat.providers.iter().find(|p| p.provider == "hermes").unwrap();
|
||||
assert!(hermes.native_config_only);
|
||||
assert_eq!((hermes.mode, hermes.origin), (AutoMemoryMode::ReadWrite, AgentMemoryOrigin::Native));
|
||||
// Workspace entry locked `Off` by Trust
|
||||
let ws_state = cat.entries.iter().find(|s| s.entry.id == "workspace::AGENTS.md").unwrap();
|
||||
assert_eq!((ws_state.mode, ws_state.origin), (AgentMemoryMode::Off, AgentMemoryOrigin::Trust));
|
||||
// Untrusted workspace could NOT escalate `claudeUser::CLAUDE.md` or `autoMemory`
|
||||
let user_state = cat.entries.iter().find(|s| s.entry.id == "claudeUser::CLAUDE.md").unwrap();
|
||||
assert_eq!((user_state.mode, user_state.origin), (AgentMemoryMode::Auto, AgentMemoryOrigin::None));
|
||||
assert_eq!(cat.auto_memory, AutoMemoryMode::Inherit);
|
||||
|
||||
// Session override wins in a trusted workspace, and unsupported modes are ignored.
|
||||
// Session override wins in a trusted workspace
|
||||
let trusted = MemoryPolicy { workspace_trusted: true, ..untrusted };
|
||||
let session_ro = AgentMemoryOverrides { auto_memory: Some(AutoMemoryMode::ReadOnly) };
|
||||
assert_eq!(
|
||||
resolve_provider_auto_memory("claude", Some(&session_ro), &trusted),
|
||||
(AutoMemoryMode::ReadWrite, AgentMemoryOrigin::Workspace)
|
||||
);
|
||||
assert_eq!(
|
||||
resolve_provider_auto_memory("codex", Some(&session_ro), &trusted),
|
||||
(AutoMemoryMode::ReadOnly, AgentMemoryOrigin::Session)
|
||||
);
|
||||
// External ACP adapters and unsupported providers never report OpenIDEA auto-memory control.
|
||||
assert!(supported_auto_memory_modes("claude-acp").is_empty());
|
||||
assert!(supported_auto_memory_modes("codex-acp").is_empty());
|
||||
assert!(supported_auto_memory_modes("copilot").is_empty());
|
||||
assert!(supported_auto_memory_modes("cursor").is_empty());
|
||||
let session = AgentMemoryOverrides {
|
||||
auto_memory: Some(AutoMemoryMode::ReadOnly),
|
||||
entries: BTreeMap::from([("workspace::AGENTS.md".into(), AgentMemoryMode::Off)]),
|
||||
};
|
||||
let cat2 = resolve_catalog(entries, Some(&session), &trusted, Some(&home));
|
||||
assert_eq!((cat2.auto_memory, cat2.auto_memory_origin), (AutoMemoryMode::ReadOnly, AgentMemoryOrigin::Session));
|
||||
let ws_state2 = cat2.entries.iter().find(|s| s.entry.id == "workspace::AGENTS.md").unwrap();
|
||||
assert_eq!((ws_state2.mode, ws_state2.origin), (AgentMemoryMode::Off, AgentMemoryOrigin::Session));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn builds_delivery_only_for_native_claude_and_codex_and_keeps_hermes_explicit() {
|
||||
fn stages_per_driver_delivery_for_claude_codex_copilot_and_hermes() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let ws = tmp.path().join("ws");
|
||||
let home = tmp.path().join("home");
|
||||
let farm = tmp.path().join("farm");
|
||||
|
||||
write(&ws.join("AGENTS.md"), "Shared workspace rule\n");
|
||||
write(&ws.join("CLAUDE.md"), "Claude-specific rule\n");
|
||||
write(&ws.join("CLAUDE.local.md"), "Noisy local note\n");
|
||||
write(
|
||||
&ws.join(".github/instructions/ipc.instructions.md"),
|
||||
"---\napplyTo: \"crates/**/*.rs\"\n---\nUse async IPC for disk ops.\n",
|
||||
);
|
||||
write(&home.join(".gemini/GEMINI.md"), "Keep PRs focused.\n");
|
||||
write(&home.join(".hermes/profile.yaml"), "display_name: default\n");
|
||||
|
||||
// Claude: Inherit -> None, ReadWrite -> true, Off -> false, ReadOnly -> None
|
||||
assert_eq!(build_delivery("claude", AutoMemoryMode::Inherit), None);
|
||||
assert_eq!(build_delivery("claude", AutoMemoryMode::ReadOnly), None);
|
||||
assert_eq!(build_delivery("claude", AutoMemoryMode::ReadWrite).unwrap().claude_auto_memory, Some(true));
|
||||
assert_eq!(build_delivery("claude", AutoMemoryMode::Off).unwrap().claude_auto_memory, Some(false));
|
||||
let entries = discover_memories(std::slice::from_ref(&ws), Some(&home));
|
||||
let session = AgentMemoryOverrides {
|
||||
auto_memory: Some(AutoMemoryMode::ReadOnly),
|
||||
entries: BTreeMap::from([
|
||||
("claudeWorkspace::CLAUDE.local.md".into(), AgentMemoryMode::Off),
|
||||
// `Always` delivers another agent's files to every agent, path scope dropped.
|
||||
("githubWorkspace::.github/instructions/ipc.instructions.md".into(), AgentMemoryMode::Always),
|
||||
("geminiUser::GEMINI.md".into(), AgentMemoryMode::Always),
|
||||
]),
|
||||
};
|
||||
let policy = MemoryPolicy { workspace_roots: vec![ws.clone()], workspace_trusted: true, ..Default::default() };
|
||||
let cat = resolve_catalog(entries, Some(&session), &policy, Some(&home));
|
||||
|
||||
// Codex: ReadWrite / ReadOnly / Off
|
||||
assert_eq!(build_delivery("codex", AutoMemoryMode::Inherit), None);
|
||||
let codex_ro = build_delivery("codex", AutoMemoryMode::ReadOnly).unwrap();
|
||||
assert_eq!(codex_ro.codex_use_memories, Some(true));
|
||||
assert_eq!(codex_ro.codex_generate_memories, Some(false));
|
||||
let codex_off = build_delivery("codex", AutoMemoryMode::Off).unwrap();
|
||||
assert_eq!(codex_off.codex_use_memories, Some(false));
|
||||
assert_eq!(codex_off.codex_generate_memories, Some(false));
|
||||
// 1. Claude delivery
|
||||
let claude = stage(&farm, "claude", &cat.entries, AutoMemoryMode::ReadOnly, &ws, Some(&home)).unwrap();
|
||||
assert_eq!(claude.claude_auto_memory, Some(false));
|
||||
assert_eq!(claude.claude_instruction_files.as_deref(), Some("claude-md-and-agents-md"));
|
||||
assert!(claude.claude_md_excludes.iter().any(|p| p.ends_with("CLAUDE.local.md")));
|
||||
assert!(claude.claude_add_dir.is_some());
|
||||
assert!(claude.claude_additional_dirs_claude_md);
|
||||
let staged_rule = std::fs::read_to_string(
|
||||
farm.join(".claude/rules/githubworkspace-github-instructions-ipc-instructions-md.md"),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(staged_rule, "Use async IPC for disk ops.\n");
|
||||
assert!(farm.join(".claude/rules/geminiuser-gemini-md.md").is_file());
|
||||
|
||||
// Copilot, ACP, Hermes produce no session delivery and never touch Hermes config.yaml
|
||||
assert_eq!(build_delivery("copilot", AutoMemoryMode::Off), None);
|
||||
assert_eq!(build_delivery("acp", AutoMemoryMode::Off), None);
|
||||
assert_eq!(build_delivery("hermes", AutoMemoryMode::Off), None);
|
||||
assert!(!home.join(".hermes/config.yaml").exists());
|
||||
// 2. Codex delivery
|
||||
let codex = stage(&farm, "codex", &cat.entries, AutoMemoryMode::ReadOnly, &ws, Some(&home)).unwrap();
|
||||
assert_eq!(codex.codex_use_memories, Some(true));
|
||||
assert_eq!(codex.codex_generate_memories, Some(false));
|
||||
assert!(codex.codex_developer_instructions.as_deref().unwrap().contains("Keep PRs focused."));
|
||||
|
||||
// Explicit Hermes toggle updates config.yaml directly and rejects unsupported modes
|
||||
assert!(set_hermes_auto_memory("hermes", AutoMemoryMode::ReadOnly, Some(&home)).is_err());
|
||||
set_hermes_auto_memory("hermes", AutoMemoryMode::Off, Some(&home)).unwrap();
|
||||
// 3. Copilot delivery
|
||||
let copilot = stage(&farm, "copilot", &cat.entries, AutoMemoryMode::ReadOnly, &ws, Some(&home)).unwrap();
|
||||
assert_eq!(copilot.copilot_enable_memory, Some(true));
|
||||
assert!(copilot.copilot_exclude_store_memory);
|
||||
let copilot_message = copilot.copilot_system_message.as_deref().unwrap();
|
||||
assert!(copilot_message.contains("Keep PRs focused."));
|
||||
// Copilot reads `.github/instructions` natively: not repeated in the system message.
|
||||
assert!(!copilot_message.contains("Use async IPC"));
|
||||
|
||||
// 4. Hermes delivery updates config.yaml
|
||||
let _ = stage(&farm, "hermes", &cat.entries, AutoMemoryMode::Off, &ws, Some(&home)).unwrap();
|
||||
assert_eq!(read_hermes_config_memory_mode(&home.join(".hermes")), Some(AutoMemoryMode::Off));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_settings_and_overrides_deserialize_cleanly() {
|
||||
let legacy_settings: AgentMemorySettings = serde_json::from_str(
|
||||
r#"{
|
||||
"autoMemory": "readOnly",
|
||||
"providers": { "codex": { "autoMemory": "off" } },
|
||||
"entries": { "workspace::AGENTS.md": { "mode": "off" } }
|
||||
}"#,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(legacy_settings.providers["codex"].auto_memory, AutoMemoryMode::Off);
|
||||
|
||||
let legacy_overrides: AgentMemoryOverrides = serde_json::from_str(
|
||||
r#"{
|
||||
"autoMemory": "off",
|
||||
"entries": { "workspace::AGENTS.md": "off" }
|
||||
}"#,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(legacy_overrides.auto_memory, Some(AutoMemoryMode::Off));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn create_promote_delete_and_reset_roundtrip() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -71,7 +71,6 @@ pub enum InterruptionReason {
|
||||
BackendStop,
|
||||
UnexpectedExit,
|
||||
NetworkTimeout,
|
||||
CursorCapacity,
|
||||
}
|
||||
|
||||
impl From<AgentShutdownReason> for InterruptionReason {
|
||||
@@ -200,14 +199,6 @@ pub struct AgentTask {
|
||||
/// Per-session recovery / network auto-retry window override in minutes (`0` = Off; `None` = inherit global).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub recovery_window_mins: Option<u32>,
|
||||
/// Provenance metadata when this task was created or continued by an [`crate::automation::AgentAutomation`].
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub automation: Option<Box<crate::automation::AgentTaskAutomation>>,
|
||||
/// Ephemeral next-prompt suggestions from ACP `prompt_suggestions_update`.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
#[specta(optional)]
|
||||
pub prompt_suggestions: Box<Vec<String>>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
@@ -436,9 +427,6 @@ pub struct AgentImage {
|
||||
/// Base64, without a `data:` prefix.
|
||||
pub data: String,
|
||||
pub name: Option<String>,
|
||||
/// The `[Image #n]` label in the prompt text for an inline attachment.
|
||||
#[specta(optional)]
|
||||
pub inline_number: Option<u32>,
|
||||
}
|
||||
|
||||
impl AgentImage {
|
||||
@@ -466,29 +454,11 @@ pub struct AgentPrompt {
|
||||
pub images: Vec<AgentImage>,
|
||||
}
|
||||
|
||||
/// Provenance carried with a scheduled turn (`SameTask`, `Send Later`, or `/loop`), including
|
||||
/// while queued behind a busy turn, so trust and approval ceilings are re-checked at dispatch.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ScheduledTurnMeta {
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub permissions: Option<crate::automation::AutomationPermissionMode>,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub extra_choices: Vec<AgentConfigChoice>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub automation_id: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub session_schedule_id: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentQueued {
|
||||
pub id: String,
|
||||
pub prompt: AgentPrompt,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(skip)]
|
||||
pub scheduled: Option<ScheduledTurnMeta>,
|
||||
}
|
||||
|
||||
/// A setting chosen for a new task, by [`AgentConfigOption::id`].
|
||||
@@ -646,9 +616,6 @@ pub enum AgentEntry {
|
||||
/// Set when this turn was started automatically or via 1-click Resume to recover an interrupted turn.
|
||||
#[serde(default)]
|
||||
recovery: Option<InterruptionReason>,
|
||||
/// One-based automatic retry number for this continuation.
|
||||
#[serde(default)]
|
||||
retry_attempt: Option<u32>,
|
||||
},
|
||||
Agent {
|
||||
text: String,
|
||||
@@ -764,21 +731,12 @@ pub struct AgentProvider {
|
||||
pub command_read_only_reason: Option<AgentCommandReadOnlyReason>,
|
||||
/// Whether the command was found (on `PATH`).
|
||||
pub installed: bool,
|
||||
/// Command the project host can run to install this missing built-in CLI.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub cli_install_command: Option<String>,
|
||||
/// Whether OpenIDEA can run this agent's sign-in flow directly in an embedded terminal.
|
||||
#[serde(default)]
|
||||
pub can_sign_in: bool,
|
||||
/// The built-in command can be owned by a global npm package.
|
||||
#[serde(default)]
|
||||
pub can_check_cli_update: bool,
|
||||
/// The built-in agent this one is an instance of.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub base: Option<String>,
|
||||
/// A built-in agent, of which another instance can be added.
|
||||
#[serde(default)]
|
||||
pub can_duplicate: bool,
|
||||
/// Environment variables it starts with (from its agent file).
|
||||
pub env: BTreeMap<String, String>,
|
||||
/// Settings (models, modes…) the agent offered last time it ran; empty before its first session.
|
||||
@@ -874,10 +832,6 @@ pub struct NewAgentTask {
|
||||
pub isolation: Isolation,
|
||||
/// Branch to start the worktree from; the current branch when `None`.
|
||||
pub base: Option<String>,
|
||||
/// Reuse an existing managed worktree directory instead of creating a new one (`Isolation::Worktree` only).
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub worktree_path: Option<IpcPath>,
|
||||
/// Per-session MCP server enable/disable overrides (`server_name` -> `enabled`).
|
||||
#[serde(default)]
|
||||
pub mcp_overrides: BTreeMap<String, bool>,
|
||||
@@ -966,7 +920,7 @@ pub struct AgentModelCatalog {
|
||||
}
|
||||
|
||||
/// Streamed to the window that subscribed (`AgentManager::subscribe_as`).
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[derive(Clone, Debug, Serialize, Type)]
|
||||
#[serde(tag = "type", rename_all = "camelCase", rename_all_fields = "camelCase")]
|
||||
pub enum AgentEvent {
|
||||
/// A task was created or its metadata changed.
|
||||
@@ -1064,22 +1018,6 @@ pub struct McpServer {
|
||||
/// True when this Workspace server was added outside OpenIDEA and has not been approved yet.
|
||||
#[serde(default)]
|
||||
pub unapproved: bool,
|
||||
/// Parent agent plugin ID when this server is live-projected from an enabled agent plugin bundle.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub plugin_id: Option<String>,
|
||||
/// Display name of the parent agent plugin.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub plugin_name: Option<String>,
|
||||
/// Canonical MCP registry server identifier when installed from an MCP registry.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub registry_name: Option<String>,
|
||||
/// Normalized MCP registry base URL when installed from an MCP registry.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub registry_url: Option<String>,
|
||||
}
|
||||
|
||||
/// Payload for creating or updating a user or workspace MCP server.
|
||||
@@ -1106,14 +1044,6 @@ pub struct McpServerInput {
|
||||
/// Agent provider ids this server is enabled for; empty means enabled for all agents.
|
||||
#[serde(default)]
|
||||
pub agents: Vec<String>,
|
||||
/// Canonical MCP registry server identifier when installed from an MCP registry.
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub registry_name: Option<String>,
|
||||
/// Normalized MCP registry base URL when installed from an MCP registry.
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub registry_url: Option<String>,
|
||||
}
|
||||
|
||||
fn default_true() -> bool {
|
||||
@@ -1121,7 +1051,7 @@ fn default_true() -> bool {
|
||||
}
|
||||
|
||||
pub use ide_core::settings::{
|
||||
AgentMemorySettings, AgentPluginEntryPolicy, AgentPluginSettings, AgentProviderMemoryPolicy, AgentSkillMode,
|
||||
AgentMemoryEntryPolicy, AgentMemoryMode, AgentMemorySettings, AgentProviderMemoryPolicy, AgentSkillMode,
|
||||
AgentSkillPolicy, AutoMemoryMode,
|
||||
};
|
||||
|
||||
@@ -1188,7 +1118,7 @@ impl AgentMemorySource {
|
||||
}
|
||||
}
|
||||
|
||||
/// Which layer decided a provider's effective [`AutoMemoryMode`].
|
||||
/// Which layer decided an [`AgentMemoryState::mode`] or [`AutoMemoryMode`].
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum AgentMemoryOrigin {
|
||||
@@ -1197,8 +1127,8 @@ pub enum AgentMemoryOrigin {
|
||||
Session,
|
||||
Workspace,
|
||||
User,
|
||||
/// Configured directly in the agent's own native config file (e.g. `~/.hermes/config.yaml`).
|
||||
Native,
|
||||
/// Locked `Off` because the workspace is untrusted.
|
||||
Trust,
|
||||
}
|
||||
|
||||
/// One discovered instruction file, rule file, or learned auto-memory note.
|
||||
@@ -1235,14 +1165,18 @@ pub struct AgentMemoryEntry {
|
||||
pub valid: bool,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub warnings: Vec<String>,
|
||||
/// Parent agent plugin ID when this rule/instruction is live-projected from an enabled agent plugin bundle.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub plugin_id: Option<String>,
|
||||
/// Display name of the parent agent plugin.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub plugin_name: Option<String>,
|
||||
}
|
||||
|
||||
/// A discovered memory entry paired with its resolved [`AgentMemoryMode`] and origin.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentMemoryState {
|
||||
pub entry: AgentMemoryEntry,
|
||||
pub mode: AgentMemoryMode,
|
||||
/// Optional provider filter from `[agents.memory.entries.<id>]`; empty means all agents.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub agents: Vec<String>,
|
||||
pub origin: AgentMemoryOrigin,
|
||||
}
|
||||
|
||||
/// Live auto-memory status and capability summary for one agent family.
|
||||
@@ -1253,43 +1187,41 @@ pub struct AgentAutoMemoryStatus {
|
||||
pub label: String,
|
||||
pub mode: AutoMemoryMode,
|
||||
pub origin: AgentMemoryOrigin,
|
||||
/// Auto-memory modes this provider enforces (empty when the agent manages auto-memory itself).
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub supported_modes: Vec<AutoMemoryMode>,
|
||||
/// True when changing the mode edits the agent's own global config (e.g. `~/.hermes/config.yaml`)
|
||||
/// rather than a project or per-session override.
|
||||
#[serde(default)]
|
||||
pub native_config_only: bool,
|
||||
pub note_count: u32,
|
||||
pub rollout_count: u32,
|
||||
pub approx_tokens: u32,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub storage_path: Option<IpcPath>,
|
||||
pub supports_auto_control: bool,
|
||||
pub supports_file_exclusion: bool,
|
||||
pub supports_reset: bool,
|
||||
}
|
||||
|
||||
/// Full catalog returned to Settings › Agents › Rules & Memory and the Composer `MemoryPicker`.
|
||||
/// Full catalog returned to Settings › Agents › Memory and the Composer `MemoryPicker`.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentMemoryCatalog {
|
||||
pub entries: Vec<AgentMemoryEntry>,
|
||||
pub entries: Vec<AgentMemoryState>,
|
||||
pub providers: Vec<AgentAutoMemoryStatus>,
|
||||
pub workspace_trusted: bool,
|
||||
pub auto_memory: AutoMemoryMode,
|
||||
pub auto_memory_origin: AgentMemoryOrigin,
|
||||
}
|
||||
|
||||
/// Per-session auto-memory override stored on an [`AgentTask`] or automation.
|
||||
/// Per-session memory overrides stored on an [`AgentTask`].
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct AgentMemoryOverrides {
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub auto_memory: Option<AutoMemoryMode>,
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub entries: BTreeMap<String, AgentMemoryMode>,
|
||||
}
|
||||
|
||||
impl AgentMemoryOverrides {
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.auto_memory.is_none()
|
||||
self.auto_memory.is_none() && self.entries.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1405,14 +1337,6 @@ pub struct AgentSkill {
|
||||
pub valid: bool,
|
||||
/// What validation found (`name` mismatch, missing or over-long description…).
|
||||
pub warnings: Vec<String>,
|
||||
/// Parent agent plugin ID when this skill comes from an agent plugin bundle.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub plugin_id: Option<String>,
|
||||
/// Display name of the parent agent plugin.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub plugin_name: Option<String>,
|
||||
}
|
||||
|
||||
/// A skill as Settings › Agents › Skills shows it: discovery plus the effective mode and
|
||||
@@ -1474,383 +1398,6 @@ pub struct McpDiscoveredServer {
|
||||
pub header_keys: Vec<String>,
|
||||
}
|
||||
|
||||
/// Which workspace, user, or CLI store an agent plugin bundle was discovered in.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum AgentPluginSource {
|
||||
/// `~/.copilot/installed-plugins/{<marketplace>,_direct}/*`.
|
||||
#[default]
|
||||
CopilotUser,
|
||||
/// `~/.claude/plugins/installed_plugins.json` & `~/.claude/plugins/cache/*`.
|
||||
ClaudeUser,
|
||||
/// `~/.codex/plugins/cache/*`.
|
||||
CodexUser,
|
||||
/// `~/.gemini/extensions/*`.
|
||||
GeminiUser,
|
||||
}
|
||||
|
||||
/// Manifest format(s) recognized inside an agent plugin directory.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum AgentPluginFormat {
|
||||
/// Vendor-neutral Agent Plugins 1.0 / 1.1 (`plugin.json` with `$schema`).
|
||||
#[default]
|
||||
AgentPluginsV1,
|
||||
/// `.openidea/plugin.json`.
|
||||
OpenIdea,
|
||||
/// `.claude-plugin/plugin.json`.
|
||||
Claude,
|
||||
/// `.plugin/plugin.json`, `.github/plugin/plugin.json`, or legacy root `plugin.json`.
|
||||
Copilot,
|
||||
/// `.codex-plugin/plugin.json`.
|
||||
Codex,
|
||||
/// `gemini-extension.json`.
|
||||
GeminiExtension,
|
||||
}
|
||||
|
||||
/// Which policy layer decided an [`AgentPluginState::enabled`] status.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum AgentPluginOrigin {
|
||||
/// Native harness configuration owns the enabled state.
|
||||
#[default]
|
||||
None,
|
||||
/// Locked `Off` because the workspace is untrusted.
|
||||
Trust,
|
||||
/// Locked `Off` until executable capabilities (stdio MCP / lifecycle hooks) are approved.
|
||||
Consent,
|
||||
}
|
||||
|
||||
/// Data type of a plugin `userConfig` / `variables` / `settings` option.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum AgentPluginConfigFieldKind {
|
||||
#[default]
|
||||
String,
|
||||
Number,
|
||||
Boolean,
|
||||
Secret,
|
||||
}
|
||||
|
||||
/// One configurable option declared by an agent plugin (`userConfig`, `variables`, or Gemini `settings`).
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentPluginConfigField {
|
||||
pub key: String,
|
||||
pub title: String,
|
||||
#[serde(default)]
|
||||
pub description: String,
|
||||
pub kind: AgentPluginConfigFieldKind,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub default_value: Option<String>,
|
||||
#[serde(default)]
|
||||
pub required: bool,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub env_var: Option<String>,
|
||||
/// Current non-sensitive value (always empty when `kind == Secret`).
|
||||
#[serde(default)]
|
||||
pub value: String,
|
||||
/// True when a secret is stored in OS Keychain for this field.
|
||||
#[serde(default)]
|
||||
pub has_secret: bool,
|
||||
}
|
||||
|
||||
/// Summary of components and executable capabilities bundled inside an agent plugin.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentPluginCapabilities {
|
||||
pub skill_count: u32,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub skill_names: Vec<String>,
|
||||
pub mcp_count: u32,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub mcp_names: Vec<String>,
|
||||
pub rule_count: u32,
|
||||
pub subagent_count: u32,
|
||||
pub command_count: u32,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub hook_files: Vec<String>,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub stdio_commands: Vec<String>,
|
||||
#[serde(default)]
|
||||
pub has_lsp: bool,
|
||||
#[serde(default)]
|
||||
pub has_canvas_or_app: bool,
|
||||
/// Harnesses that have native non-portable components (hooks, subagents, canvases/apps, LSP) in this bundle.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub native_harnesses: Vec<String>,
|
||||
/// Deterministic BLAKE3 hex digest of executable capabilities (`stdio_commands` + `hook_files` contents).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub capability_hash: Option<String>,
|
||||
#[serde(default)]
|
||||
pub requires_consent: bool,
|
||||
}
|
||||
|
||||
/// One discovered agent plugin bundle on disk (or built-in).
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentPlugin {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub display_name: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub version: Option<String>,
|
||||
pub description: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub author: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub homepage: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub repository: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub license: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub marketplace: Option<String>,
|
||||
pub source: AgentPluginSource,
|
||||
/// Scope this bundle is installed in. Native plugin folders and enablement config are
|
||||
/// resolved relative to this scope.
|
||||
pub scope: McpScope,
|
||||
/// Workspace whose native configuration owns this row's enablement (workspace scope only).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub workspace_root: Option<IpcPath>,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub also_in: Vec<AgentPluginSource>,
|
||||
pub formats: Vec<AgentPluginFormat>,
|
||||
pub root_path: IpcPath,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub manifest_path: Option<IpcPath>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub readme_path: Option<IpcPath>,
|
||||
pub default_enabled: bool,
|
||||
pub approx_tokens: u32,
|
||||
pub capabilities: AgentPluginCapabilities,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub config_fields: Vec<AgentPluginConfigField>,
|
||||
pub valid: bool,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub warnings: Vec<String>,
|
||||
}
|
||||
|
||||
/// Resolved agent plugin state paired with its policy origin and consent status.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentPluginState {
|
||||
pub plugin: AgentPlugin,
|
||||
pub enabled: bool,
|
||||
pub origin: AgentPluginOrigin,
|
||||
/// True when executable stdio MCP / hook capabilities require user approval before enabling.
|
||||
pub consent_required: bool,
|
||||
}
|
||||
|
||||
/// Summary of a configured or repository-discovered plugin marketplace.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentMarketplaceInfo {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub source: String,
|
||||
pub scope: McpScope,
|
||||
/// True when discovered from a harness-native marketplace/configuration file.
|
||||
pub discovered: bool,
|
||||
}
|
||||
|
||||
/// Full catalog returned to Settings › Agents › Plugins.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentPluginCatalog {
|
||||
pub plugins: Vec<AgentPluginState>,
|
||||
pub marketplaces: Vec<AgentMarketplaceInfo>,
|
||||
pub projected_skills: u32,
|
||||
pub projected_mcp_servers: u32,
|
||||
pub projected_rules: u32,
|
||||
}
|
||||
|
||||
/// One installable plugin entry listed inside a marketplace or repository.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentMarketplaceCandidate {
|
||||
pub name: String,
|
||||
pub display_name: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub version: Option<String>,
|
||||
pub description: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub author: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub marketplace: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub icon_url: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub icon_dark_url: Option<String>,
|
||||
/// Source spec to pass to preview (`"owner/repo[/subpath][@ref]"` or local directory path).
|
||||
pub source_spec: String,
|
||||
pub subpath: String,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub keywords: Vec<String>,
|
||||
pub already_installed_user: bool,
|
||||
pub already_installed_workspace: bool,
|
||||
}
|
||||
|
||||
/// Result of browsing a marketplace (`owner/repo`, local marketplace path, or direct plugin repo).
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentMarketplaceBrowseResult {
|
||||
pub source: String,
|
||||
pub marketplace_name: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub owner: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub repo: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub git_ref: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub tree_sha: Option<String>,
|
||||
pub candidates: Vec<AgentMarketplaceCandidate>,
|
||||
}
|
||||
|
||||
/// Whether a previewed plugin can be installed for one harness, and where it is already installed.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentPluginInstallTarget {
|
||||
pub harness: String,
|
||||
pub supported: bool,
|
||||
/// Why the harness cannot install this plugin.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub reason: Option<String>,
|
||||
/// Whether this harness can enable the plugin for just one workspace.
|
||||
pub workspace_supported: bool,
|
||||
/// This harness already records the plugin for the user / for the current workspace.
|
||||
pub installed_user: bool,
|
||||
pub installed_workspace: bool,
|
||||
/// The harness store already holds this plugin version's folder, so installing replaces it.
|
||||
pub overwrite_required: bool,
|
||||
}
|
||||
|
||||
/// Security and capability preview of an agent plugin bundle before installation.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentPluginPreview {
|
||||
/// `"github"` or `"local"`.
|
||||
pub source_kind: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub owner: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub repo: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub git_ref: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub tree_sha: Option<String>,
|
||||
/// Pinned commit SHA from preview when `source_kind == "github"`.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub commit_sha: Option<String>,
|
||||
#[serde(default)]
|
||||
pub subpath: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub local_path: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub marketplace: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub marketplace_source: Option<String>,
|
||||
pub name: String,
|
||||
pub display_name: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub version: Option<String>,
|
||||
pub description: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub icon_url: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub icon_dark_url: Option<String>,
|
||||
pub formats: Vec<AgentPluginFormat>,
|
||||
pub capabilities: AgentPluginCapabilities,
|
||||
pub files: Vec<crate::skill_installer::RemoteSkillFile>,
|
||||
pub scan_warnings: Vec<crate::skill_installer::SkillScanWarning>,
|
||||
/// Per-harness install eligibility and existing installs for this plugin and marketplace.
|
||||
pub targets: Vec<AgentPluginInstallTarget>,
|
||||
}
|
||||
|
||||
/// Request payload to install a previewed agent plugin into a selected harness's native plugin directory.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct InstallAgentPluginRequest {
|
||||
/// `"github"` or `"local"`.
|
||||
pub source_kind: String,
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub owner: Option<String>,
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub repo: Option<String>,
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub git_ref: Option<String>,
|
||||
/// Pinned root tree SHA from preview when `source_kind == "github"`.
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub tree_sha: Option<String>,
|
||||
/// Pinned commit SHA from preview when `source_kind == "github"`.
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub commit_sha: Option<String>,
|
||||
#[serde(default)]
|
||||
pub subpath: String,
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub local_path: Option<String>,
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub marketplace: Option<String>,
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub marketplace_source: Option<String>,
|
||||
pub scope: McpScope,
|
||||
/// Native harness the plugin is installed for (`claude`, `copilot`, `codex`, or `gemini`).
|
||||
pub harness: String,
|
||||
#[serde(default)]
|
||||
pub approve_capabilities: bool,
|
||||
/// The preview's `capabilityHash` the user approved; the install is refused if the installed
|
||||
/// folder resolves to different executable capabilities.
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub approved_capability_hash: Option<String>,
|
||||
#[serde(default)]
|
||||
pub confirm_warnings: bool,
|
||||
#[serde(default)]
|
||||
pub overwrite: bool,
|
||||
}
|
||||
|
||||
/// Selection of one server from an external MCP configuration source to import.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
@@ -1880,16 +1427,13 @@ pub struct McpProbeResult {
|
||||
pub error: Option<String>,
|
||||
}
|
||||
|
||||
/// Payload for creating a custom ACP agent, or an instance of built-in `base` (which
|
||||
/// launches as its base does when `command` is empty); the id becomes the
|
||||
/// `<config>/agents/<id>.toml` file name.
|
||||
/// Payload for creating a custom ACP agent (always the ACP driver); the id
|
||||
/// becomes the `<config>/agents/<id>.toml` file name.
|
||||
#[derive(Clone, Debug, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct CustomAgentInput {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
#[serde(default)]
|
||||
pub base: Option<String>,
|
||||
pub command: String,
|
||||
#[serde(default)]
|
||||
pub args: Vec<String>,
|
||||
|
||||
@@ -209,17 +209,6 @@ pub(super) fn cut(chain: &[&Value], turns: usize) -> Result<Option<String>, Stri
|
||||
Ok(parent(first_dropped).map(str::to_owned))
|
||||
}
|
||||
|
||||
/// Where to fork `chain` to keep only its first `turns` turns: the entry the last kept
|
||||
/// turn ends with, as [`cut`] reports it. `None` when the chain has fewer turns.
|
||||
pub(super) fn keep(chain: &[&Value], turns: usize) -> Option<Option<String>> {
|
||||
let total = chain.iter().filter(|e| is_turn_start(e)).count();
|
||||
if turns > total {
|
||||
return None;
|
||||
}
|
||||
// A turn that runs now is in the chain up to where it got: it is dropped like any other.
|
||||
cut(chain, total - turns).ok()
|
||||
}
|
||||
|
||||
/// The newest title Claude Code gave the session.
|
||||
pub(crate) fn title(entries: &[Value]) -> Option<String> {
|
||||
entries
|
||||
|
||||
@@ -58,7 +58,7 @@ pub(crate) fn connect(
|
||||
on_stderr: Box<dyn Fn(String) + Send + Sync>,
|
||||
) -> std::io::Result<Peer> {
|
||||
let config = Config {
|
||||
program: super::newest_install(spec.executable()),
|
||||
program: super::newest_install(&spec.command),
|
||||
args: spec.args.clone(),
|
||||
env: spec.env.clone(),
|
||||
config_dir: cli::config_dir(&spec.env),
|
||||
@@ -174,9 +174,13 @@ struct Session {
|
||||
mcp_off: Vec<String>,
|
||||
/// The staged skills folder passed as `--add-dir` (its `.claude/skills` holds the copies).
|
||||
skills_add_dir: Option<PathBuf>,
|
||||
/// The staged memory rules folder passed as `--add-dir` (its `.claude/rules` holds shared rules).
|
||||
memory_add_dir: Option<PathBuf>,
|
||||
/// Load `.claude/rules` from `--add-dir` folders (`CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD=1`).
|
||||
additional_dirs_claude_md: bool,
|
||||
/// The workspace's other roots, each passed as `--add-dir`.
|
||||
additional_dirs: Vec<String>,
|
||||
/// Combined `--settings` JSON (`skillOverrides`, `autoMemoryEnabled`).
|
||||
/// Combined `--settings` JSON (`skillOverrides`, `autoMemoryEnabled`, `claudeMdExcludes`, `instructionFiles`).
|
||||
cli_settings: Option<String>,
|
||||
/// `_meta.openidea.ephemeral`: `--no-session-persistence`, nothing saved under `~/.claude`.
|
||||
ephemeral: bool,
|
||||
@@ -343,24 +347,6 @@ impl Shim {
|
||||
}
|
||||
|
||||
/// The conversation a session started with `start` begins with.
|
||||
/// `start` (a fork's) cut after the source's first `turns` turns; `None` when the
|
||||
/// transcript can't be read or has fewer turns.
|
||||
fn pin_fork(&self, cwd: &Path, start: &Start, id: &str, turns: usize) -> Option<Start> {
|
||||
let chain = match self.base_chain(cwd, start) {
|
||||
Ok(chain) => chain,
|
||||
Err(e) => {
|
||||
tracing::debug!("Claude Code fork {id}: can't read the source transcript: {e}");
|
||||
return None;
|
||||
}
|
||||
};
|
||||
let refs: Vec<&Value> = chain.iter().collect();
|
||||
Some(match (start, history::keep(&refs, turns)?) {
|
||||
(_, None) => Start::New { id: id.to_owned() },
|
||||
(Start::Fork { from, .. }, Some(at)) => Start::Fork { from: from.clone(), id: id.to_owned(), at: Some(at) },
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
fn base_chain(&self, cwd: &Path, start: &Start) -> Result<Vec<Value>, String> {
|
||||
let (id, at) = match start {
|
||||
Start::New { .. } => return Ok(Vec::new()),
|
||||
@@ -396,6 +382,11 @@ impl Shim {
|
||||
mcp_config,
|
||||
mcp_off,
|
||||
skills_add_dir: skills.and_then(|s| s.get("claudeAddDir")).and_then(Value::as_str).map(PathBuf::from),
|
||||
memory_add_dir: memory.and_then(|m| m.get("claudeAddDir")).and_then(Value::as_str).map(PathBuf::from),
|
||||
additional_dirs_claude_md: memory
|
||||
.and_then(|m| m.get("claudeAdditionalDirsClaudeMd"))
|
||||
.and_then(Value::as_bool)
|
||||
.unwrap_or(false),
|
||||
additional_dirs: additional_dirs(params),
|
||||
cli_settings,
|
||||
ephemeral: params.pointer("/_meta/openidea/ephemeral").and_then(Value::as_bool).unwrap_or(false),
|
||||
@@ -518,28 +509,11 @@ impl Shim {
|
||||
// from its transcript on disk when the task's first prompt starts it.
|
||||
None => (Start::Fork { from: source_id.to_owned(), id: id.clone(), at: None }, Settings::default()),
|
||||
};
|
||||
// Pinned now: the source may go on (or be running a turn) before the fork starts.
|
||||
let wanted = params.pointer("/_meta/openidea/forkTurns").and_then(Value::as_u64);
|
||||
let mut kept = None;
|
||||
let start = match wanted {
|
||||
Some(turns) => match self.pin_fork(&cwd, &start, &id, turns as usize) {
|
||||
Some(pinned) => {
|
||||
kept = Some(turns);
|
||||
pinned
|
||||
}
|
||||
None => start,
|
||||
},
|
||||
None => start,
|
||||
};
|
||||
self.save_pending(&id, Some(&start));
|
||||
let session = self.add_session(&id, cwd, start, true, ¶ms);
|
||||
session.st.lock().settings = settings;
|
||||
let options = session.st.lock().settings.options();
|
||||
let mut reply = json!({ "sessionId": id, "configOptions": options });
|
||||
if let Some(turns) = kept {
|
||||
reply["_meta"] = json!({ "openidea": { "forkTurns": turns } });
|
||||
}
|
||||
Ok(reply)
|
||||
Ok(json!({ "sessionId": id, "configOptions": options }))
|
||||
}
|
||||
"session/set_config_option" | "session/set_mode" => {
|
||||
let session = self.session(¶ms)?;
|
||||
@@ -765,6 +739,11 @@ impl Session {
|
||||
if let Some(dir) = &self.skills_add_dir {
|
||||
args.extend(["--add-dir".to_owned(), dir.to_string_lossy().into_owned()]);
|
||||
}
|
||||
if let Some(dir) = &self.memory_add_dir
|
||||
&& self.skills_add_dir.as_ref() != Some(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()]);
|
||||
}
|
||||
@@ -775,7 +754,12 @@ impl Session {
|
||||
args.push("--no-session-persistence".to_owned());
|
||||
}
|
||||
args.extend(start.args());
|
||||
let env = shim.config.env.clone();
|
||||
let mut env = shim.config.env.clone();
|
||||
if self.additional_dirs_claude_md
|
||||
&& !env.iter().any(|(k, _)| k == "CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD")
|
||||
{
|
||||
env.push(("CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD".to_owned(), "1".to_owned()));
|
||||
}
|
||||
let launch = Launch { program: shim.config.program.clone(), args, cwd: self.cwd.clone(), env };
|
||||
let io = shim
|
||||
.cli
|
||||
@@ -963,7 +947,7 @@ impl Session {
|
||||
fn steer(&self, prompt: Value) -> Result<(), String> {
|
||||
let uuid = new_uuid(true);
|
||||
let mut message = user_message(&prompt, &uuid, true);
|
||||
message["priority"] = json!("next");
|
||||
message["priority"] = json!("now");
|
||||
let mut st = self.st.lock();
|
||||
let proc = st.proc.clone().ok_or("Claude Code is not running")?;
|
||||
let turn = st.turn.as_mut().filter(|t| !t.cancelled).ok_or("no turn is running")?;
|
||||
@@ -1638,8 +1622,8 @@ fn write_mcp_config(json: &str) -> std::io::Result<tempfile::TempPath> {
|
||||
/// The servers switched off for the session (`_meta.openidea.mcpServersOff`) as Claude Code
|
||||
/// permission rules that deny all of a server's tools (`mcp__<server>`), so a server of
|
||||
/// Claude Code's own configuration stays off too.
|
||||
/// Combines `skillOverrides` from `_meta.openidea.skills.claudeSettings` with
|
||||
/// `autoMemoryEnabled` from `_meta.openidea.memory` into one `--settings` JSON.
|
||||
/// Combines `skillOverrides` from `_meta.openidea.skills.claudeSettings` with memory
|
||||
/// settings (`autoMemoryEnabled`, `claudeMdExcludes`, `instructionFiles`) into one `--settings` JSON.
|
||||
fn build_cli_settings(skills: Option<&Value>, memory: Option<&Value>) -> Option<String> {
|
||||
let mut root = skills
|
||||
.and_then(|s| s.get("claudeSettings"))
|
||||
@@ -1647,8 +1631,27 @@ fn build_cli_settings(skills: Option<&Value>, memory: Option<&Value>) -> Option<
|
||||
.and_then(|raw| serde_json::from_str::<serde_json::Map<String, Value>>(raw).ok())
|
||||
.unwrap_or_default();
|
||||
|
||||
if let Some(auto) = memory.and_then(|m| m.get("claudeAutoMemory")).and_then(Value::as_bool) {
|
||||
root.insert("autoMemoryEnabled".into(), json!(auto));
|
||||
if let Some(mem) = memory {
|
||||
if let Some(auto) = mem.get("claudeAutoMemory").and_then(Value::as_bool) {
|
||||
root.insert("autoMemoryEnabled".into(), json!(auto));
|
||||
}
|
||||
if let Some(excludes) = mem.get("claudeMdExcludes").and_then(Value::as_array) {
|
||||
let clean: Vec<Value> =
|
||||
excludes.iter().filter_map(Value::as_str).filter(|s| !s.is_empty()).map(|s| json!(s)).collect();
|
||||
if !clean.is_empty() {
|
||||
root.insert("claudeMdExcludes".into(), Value::Array(clean));
|
||||
}
|
||||
}
|
||||
if let Some(inst) = mem.get("claudeInstructionFiles").and_then(Value::as_str).filter(|s| !s.is_empty()) {
|
||||
root.insert(
|
||||
"pluginConfigs".into(),
|
||||
json!({
|
||||
"cc-plugin-agents-md@builtin": {
|
||||
"options": { "instructionFiles": inst }
|
||||
}
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
(!root.is_empty()).then(|| serde_json::to_string(&Value::Object(root)).expect("settings serialize"))
|
||||
|
||||
@@ -212,30 +212,6 @@ async fn steer(h: &Harness) -> (Outcome, String) {
|
||||
(vec![outcome("prompt", r), outcome("steer", steered)], s)
|
||||
}
|
||||
|
||||
/// Stops the turn while a steered message waits for the running tool.
|
||||
async fn steer_stop(h: &Harness) -> (Outcome, String) {
|
||||
let s = h.new_session().await;
|
||||
let prompt = h.prompt(&s, "Run the Bash command `sleep 5 && echo done`, then tell me its output in one line.");
|
||||
let steer_and_stop = async {
|
||||
tokio::time::sleep(Duration::from_millis(3000)).await;
|
||||
let steered = h
|
||||
.request(
|
||||
"_openidea/steer",
|
||||
json!({ "sessionId": s, "prompt": [{ "type": "text", "text": "Also end your answer with the word BANANA." }] }),
|
||||
)
|
||||
.await;
|
||||
tokio::time::sleep(Duration::from_millis(500)).await;
|
||||
h.client.notify("session/cancel", json!({ "sessionId": s })).unwrap();
|
||||
steered
|
||||
};
|
||||
let (r, steered) = tokio::join!(prompt, steer_and_stop);
|
||||
if h.recording {
|
||||
// Long enough for the CLI to run the steered message, had it kept it.
|
||||
tokio::time::sleep(Duration::from_secs(8)).await;
|
||||
}
|
||||
(vec![outcome("prompt", r), outcome("steer", steered)], s)
|
||||
}
|
||||
|
||||
async fn subagent(h: &Harness) -> (Outcome, String) {
|
||||
let s = h.new_session().await;
|
||||
h.answer(&[Some("allow"), Some("allow")]);
|
||||
@@ -277,7 +253,6 @@ const SCENARIOS: &[(&str, ScenarioFn)] = &[
|
||||
("tool_approval", |h| Box::pin(tool_approval(h))),
|
||||
("interrupt", |h| Box::pin(interrupt(h))),
|
||||
("steer", |h| Box::pin(steer(h))),
|
||||
("steer_stop", |h| Box::pin(steer_stop(h))),
|
||||
("subagent", |h| Box::pin(subagent(h))),
|
||||
("resume", |h| Box::pin(resume(h))),
|
||||
];
|
||||
@@ -645,20 +620,10 @@ async fn replay_steer() {
|
||||
assert_eq!(r.stop("prompt"), "end_turn");
|
||||
assert!(r.h.text(&r.session, "agent_message_chunk").contains("BANANA"));
|
||||
let steer = r.sent(0).into_iter().filter(|m| m["type"] == "user").nth(1).unwrap();
|
||||
assert_eq!(steer["priority"], "next");
|
||||
assert_eq!(steer["priority"], "now");
|
||||
assert!(steer["uuid"].as_str().unwrap().ends_with(history::STEER_MARK));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn replay_steer_stop() {
|
||||
let r = replay("steer_stop").await;
|
||||
assert!(r.result("steer").is_ok(), "{:?}", r.result("steer"));
|
||||
assert_eq!(r.stop("prompt"), "cancelled");
|
||||
assert!(!r.h.text(&r.session, "agent_message_chunk").contains("BANANA"));
|
||||
let interrupt = r.sent(0).into_iter().find(|m| m["request"]["subtype"] == "interrupt").unwrap();
|
||||
assert_eq!(interrupt["request"]["cancel_queued"], true);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn replay_subagent() {
|
||||
let r = replay("subagent").await;
|
||||
@@ -730,73 +695,6 @@ async fn fork_session_can_start_a_recorded_session_under_the_hosts_id() {
|
||||
assert_eq!(saved, json!({ "fork": source, "id": target, "at": null }));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn fork_session_pins_the_cut_to_the_kept_turns() {
|
||||
struct NoLaunch;
|
||||
impl Cli for NoLaunch {
|
||||
fn launch(&self, _: &Launch, _: OnStderr) -> std::io::Result<cli::CliIo> {
|
||||
panic!("session/fork must not launch the CLI")
|
||||
}
|
||||
}
|
||||
|
||||
let config = tempfile::tempdir().unwrap();
|
||||
let pending = tempfile::tempdir().unwrap();
|
||||
let h = Harness::connect(
|
||||
Arc::new(NoLaunch),
|
||||
config.path().to_path_buf(),
|
||||
pending.path().to_path_buf(),
|
||||
std::env::temp_dir(),
|
||||
Vec::new(),
|
||||
)
|
||||
.await;
|
||||
let source = "11111111-1111-4111-8111-111111111111";
|
||||
// Two finished turns and a third still running.
|
||||
let dir = config.path().join("projects").join(history::escape(&h.cwd));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let mut parent = Value::Null;
|
||||
let mut lines = String::new();
|
||||
for (uuid, kind, text) in [
|
||||
("u1", "user", "one"),
|
||||
("a1", "assistant", "1"),
|
||||
("u2", "user", "two"),
|
||||
("a2", "assistant", "2"),
|
||||
("u3", "user", "three"),
|
||||
("a3", "assistant", "partial"),
|
||||
] {
|
||||
let entry = json!({"type": kind, "uuid": uuid, "parentUuid": parent,
|
||||
"message": {"role": kind, "content": [{"type": "text", "text": text}]}});
|
||||
lines += &format!("{entry}\n");
|
||||
parent = json!(uuid);
|
||||
}
|
||||
std::fs::write(dir.join(format!("{source}.jsonl")), lines).unwrap();
|
||||
|
||||
let fork = |target: &'static str, turns: u64| {
|
||||
h.request(
|
||||
"session/fork",
|
||||
json!({
|
||||
"sessionId": source,
|
||||
"cwd": h.cwd,
|
||||
"mcpServers": [],
|
||||
"_meta": { "openidea": { "forkSessionId": target, "forkTurns": turns } }
|
||||
}),
|
||||
)
|
||||
};
|
||||
let saved = |target: &str| -> Value {
|
||||
serde_json::from_slice(&std::fs::read(pending.path().join(format!("{target}.json"))).unwrap()).unwrap()
|
||||
};
|
||||
|
||||
let target = "22222222-2222-4222-8222-222222222222";
|
||||
let reply = fork(target, 2).await.unwrap();
|
||||
assert_eq!(reply.pointer("/_meta/openidea/forkTurns"), Some(&json!(2)));
|
||||
assert_eq!(saved(target), json!({ "fork": source, "id": target, "at": "a2" }));
|
||||
|
||||
// More turns than the transcript holds: left to the host to settle.
|
||||
let target = "33333333-3333-4333-8333-333333333333";
|
||||
let reply = fork(target, 4).await.unwrap();
|
||||
assert_eq!(reply.pointer("/_meta/openidea/forkTurns"), None);
|
||||
assert_eq!(saved(target), json!({ "fork": source, "id": target, "at": null }));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn fork_session_rejects_a_requested_id_that_is_not_canonical() {
|
||||
struct NoLaunch;
|
||||
@@ -901,14 +799,7 @@ fn scrub(frame: &mut Value) -> bool {
|
||||
json!([{ "name": "review", "description": "Review a pull request", "argumentHint": "" },
|
||||
{ "name": "init", "description": "Write a CLAUDE.md", "argumentHint": "" }]),
|
||||
);
|
||||
for k in [
|
||||
"agents",
|
||||
"account",
|
||||
"stored_login_organization_uuid",
|
||||
"available_output_styles",
|
||||
"user_output_styles_dir",
|
||||
"output_style",
|
||||
] {
|
||||
for k in ["agents", "account", "available_output_styles", "user_output_styles_dir", "output_style"] {
|
||||
o.remove(k);
|
||||
}
|
||||
}
|
||||
@@ -1553,7 +1444,7 @@ async fn an_ephemeral_session_is_not_saved() {
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn session_merges_skills_and_auto_memory_into_claude_settings() {
|
||||
async fn session_merges_skills_and_memory_into_claude_settings_and_add_dir_env() {
|
||||
let cli = replay_cli(load_fixture("simple"));
|
||||
let (config, cwd) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
|
||||
let cwd_path = std::fs::canonicalize(cwd.path()).unwrap();
|
||||
@@ -1569,21 +1460,27 @@ async fn session_merges_skills_and_auto_memory_into_claude_settings() {
|
||||
"claudeSettings": "{\"skillOverrides\":{\"tdd\":\"user-invocable-only\"}}"
|
||||
},
|
||||
"memory": {
|
||||
"autoMemory": "off",
|
||||
"claudeAutoMemory": false
|
||||
},
|
||||
"plugins": { "activePlugins": ["azure", "linear@mkt"] }
|
||||
"autoMemory": "readOnly",
|
||||
"claudeAutoMemory": false,
|
||||
"claudeMdExcludes": ["/repo/CLAUDE.local.md"],
|
||||
"claudeInstructionFiles": "claude-md-and-agents-md",
|
||||
"claudeAddDir": "/tmp/farm-memory",
|
||||
"claudeAdditionalDirsClaudeMd": true
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
h.request("session/new", params).await.unwrap();
|
||||
let args = cli.launched.lock()[0].clone();
|
||||
assert!(args.windows(2).any(|w| w == ["--add-dir", "/tmp/farm-skills"]), "{args:?}");
|
||||
assert!(!args.iter().any(|a| a == "--plugin-dir"), "{args:?}");
|
||||
assert!(args.windows(2).any(|w| w == ["--add-dir", "/tmp/farm-memory"]), "{args:?}");
|
||||
let settings_idx = args.iter().position(|a| a == "--settings").expect("--settings flag");
|
||||
let parsed: Value = serde_json::from_str(&args[settings_idx + 1]).unwrap();
|
||||
assert_eq!(parsed["skillOverrides"]["tdd"], "user-invocable-only");
|
||||
assert_eq!(parsed["autoMemoryEnabled"], false);
|
||||
assert!(parsed.get("claudeMdExcludes").is_none());
|
||||
assert!(parsed.get("pluginConfigs").is_none());
|
||||
assert_eq!(parsed["claudeMdExcludes"], json!(["/repo/CLAUDE.local.md"]));
|
||||
assert_eq!(
|
||||
parsed["pluginConfigs"]["cc-plugin-agents-md@builtin"]["options"]["instructionFiles"],
|
||||
"claude-md-and-agents-md"
|
||||
);
|
||||
}
|
||||
@@ -34,14 +34,6 @@ const OUTPUT_EVERY: Duration = Duration::from_millis(200);
|
||||
const EARLY_CANCEL: Duration = Duration::from_secs(1);
|
||||
/// How long the client's connection outlives codex.
|
||||
const EXIT_GRACE: Duration = Duration::from_millis(100);
|
||||
/// How often running background terminals are listed again: codex announces neither a
|
||||
/// terminal that outlives its turn nor its end.
|
||||
#[cfg(not(test))]
|
||||
const TERMINAL_POLL: Duration = Duration::from_secs(3);
|
||||
#[cfg(test)]
|
||||
const TERMINAL_POLL: Duration = Duration::from_millis(20);
|
||||
/// How long closing the connection waits for codex to stop the background terminals.
|
||||
const TERMINAL_CLEAN: Duration = Duration::from_secs(3);
|
||||
/// 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.";
|
||||
@@ -74,7 +66,7 @@ pub(crate) fn connect(
|
||||
on_stderr: Box<dyn Fn(String) + Send + Sync>,
|
||||
) -> std::io::Result<Peer> {
|
||||
attach(client, |events| {
|
||||
let command = super::newest_install(spec.executable());
|
||||
let command = super::newest_install(&spec.command);
|
||||
Peer::spawn_framed(&command, &spec.args, cwd, &spec.env, events, on_stderr, Framing::Lines)
|
||||
})
|
||||
}
|
||||
@@ -195,10 +187,6 @@ fn attach(
|
||||
}
|
||||
tokio::spawn(async move {
|
||||
to_client.closed().await;
|
||||
// Background terminals run in process groups of their own: stopping codex alone
|
||||
// would leave them running with nothing left to report or stop them.
|
||||
let threads: Vec<String> = shim.state.lock().threads.keys().cloned().collect();
|
||||
shim.clean_terminals(&threads).await;
|
||||
codex.kill();
|
||||
});
|
||||
Ok(ours)
|
||||
@@ -260,14 +248,6 @@ struct Thread {
|
||||
token_usage: Option<Value>,
|
||||
/// The thread has a name.
|
||||
named: bool,
|
||||
/// Running background terminals of this session and its subagents, by task id:
|
||||
/// `(thread, processId)`.
|
||||
terminals: HashMap<String, (String, String)>,
|
||||
/// The background tasks reported last.
|
||||
shown_tasks: Vec<Value>,
|
||||
/// The background terminals are being followed; `relist` asks for another listing.
|
||||
watching: bool,
|
||||
relist: bool,
|
||||
/// A name is being asked for.
|
||||
naming: bool,
|
||||
}
|
||||
@@ -385,25 +365,18 @@ fn apply_thread_config(params: &Value, request: &mut Value) {
|
||||
if let Some(mem) = params.pointer("/_meta/openidea/memory")
|
||||
&& let Some(map) = config.as_object_mut()
|
||||
{
|
||||
let use_m = mem.get("codexUseMemories").and_then(Value::as_bool);
|
||||
let gen_m = mem.get("codexGenerateMemories").and_then(Value::as_bool);
|
||||
let mut mem_cfg = serde_json::Map::new();
|
||||
if let Some(v) = use_m {
|
||||
mem_cfg.insert("use_memories".into(), json!(v));
|
||||
if let Some(use_m) = mem.get("codexUseMemories").and_then(Value::as_bool) {
|
||||
mem_cfg.insert("use_memories".into(), json!(use_m));
|
||||
}
|
||||
if let Some(v) = gen_m {
|
||||
mem_cfg.insert("generate_memories".into(), json!(v));
|
||||
if let Some(gen_m) = mem.get("codexGenerateMemories").and_then(Value::as_bool) {
|
||||
mem_cfg.insert("generate_memories".into(), json!(gen_m));
|
||||
}
|
||||
if !mem_cfg.is_empty() {
|
||||
map.insert("memories".into(), Value::Object(mem_cfg));
|
||||
}
|
||||
// Codex's `memories` feature flag defaults to `false`; turn it on whenever the user
|
||||
// explicitly asks to read or generate memories.
|
||||
if use_m == Some(true) || gen_m == Some(true) {
|
||||
let features = map.entry("features".to_owned()).or_insert_with(|| Value::Object(serde_json::Map::new()));
|
||||
if let Some(f) = features.as_object_mut() {
|
||||
f.insert("memories".into(), json!(true));
|
||||
}
|
||||
if let Some(dev) = mem.get("codexDeveloperInstructions").and_then(Value::as_str).filter(|s| !s.is_empty()) {
|
||||
map.insert("developer_instructions".into(), json!(dev));
|
||||
}
|
||||
}
|
||||
if !config.as_object().is_some_and(|m| m.is_empty()) {
|
||||
@@ -443,7 +416,6 @@ impl CodexShim {
|
||||
"session/prompt" => self.prompt(¶ms).await,
|
||||
"_openidea/steer" => self.steer(¶ms).await,
|
||||
"_openidea/rollback" => self.rollback(¶ms).await,
|
||||
"_openidea/stop_task" => self.stop_task(¶ms).await,
|
||||
"session/close" => self.close(¶ms).await,
|
||||
_ => Err(error(codes::METHOD_NOT_FOUND, format!("unsupported method {method}"))),
|
||||
}
|
||||
@@ -467,7 +439,7 @@ impl CodexShim {
|
||||
"promptCapabilities": { "image": true, "audio": false, "embeddedContext": true },
|
||||
"mcpCapabilities": { "http": false, "sse": false, "stdio": true },
|
||||
"sessionCapabilities": { "fork": {}, "close": {}, "additionalDirectories": {} },
|
||||
"_meta": { "openidea": { "rollback": true, "steer": true, "backgroundTasks": true } },
|
||||
"_meta": { "openidea": { "rollback": true, "steer": true } },
|
||||
},
|
||||
"agentInfo": { "name": "codex", "title": "Codex", "version": version },
|
||||
"authMethods": [],
|
||||
@@ -596,26 +568,9 @@ impl CodexShim {
|
||||
}
|
||||
let result = self.call("thread/fork", request).await?;
|
||||
let (id, options) = self.open_thread(&result, &models, settings);
|
||||
// Cut by what the fork holds: a turn the source runs now may or may not be in it.
|
||||
let wanted = params.pointer("/_meta/openidea/forkTurns").and_then(Value::as_u64);
|
||||
let held = result.pointer("/thread/turns").and_then(Value::as_array).map(|t| t.len() as u64);
|
||||
let mut kept = None;
|
||||
if let (Some(turns), Some(held)) = (wanted, held)
|
||||
&& turns <= held
|
||||
{
|
||||
let dropped = held - turns;
|
||||
if dropped > 0 {
|
||||
self.rollback(&json!({ "sessionId": id, "turns": dropped })).await?;
|
||||
}
|
||||
kept = Some(turns);
|
||||
}
|
||||
self.apply_skill_roots(&id, params).await;
|
||||
self.publish_skills(&id).await;
|
||||
let mut reply = json!({ "sessionId": id, "configOptions": options });
|
||||
if let Some(turns) = kept {
|
||||
reply["_meta"] = json!({ "openidea": { "forkTurns": turns } });
|
||||
}
|
||||
Ok(reply)
|
||||
Ok(json!({ "sessionId": id, "configOptions": options }))
|
||||
}
|
||||
|
||||
async fn set_config(&self, params: &Value) -> Result<Value, ResponseError> {
|
||||
@@ -960,16 +915,6 @@ impl CodexShim {
|
||||
/// Stops following the session's thread (codex unloads it once nothing follows it).
|
||||
async fn close(&self, params: &Value) -> Result<Value, ResponseError> {
|
||||
let session = str_param(params, "sessionId")?;
|
||||
let threads: Vec<String> = {
|
||||
let state = self.state.lock();
|
||||
state
|
||||
.threads
|
||||
.iter()
|
||||
.filter(|(id, t)| *id == session || t.parent.as_deref() == Some(session))
|
||||
.map(|(id, _)| id.clone())
|
||||
.collect()
|
||||
};
|
||||
self.clean_terminals(&threads).await;
|
||||
let known = self.state.lock().threads.remove(session).is_some();
|
||||
if known && let Err(e) = self.call("thread/unsubscribe", json!({ "threadId": session })).await {
|
||||
tracing::debug!("codex: unsubscribing from {session}: {}", e.message);
|
||||
@@ -977,129 +922,6 @@ impl CodexShim {
|
||||
Ok(json!({}))
|
||||
}
|
||||
|
||||
/// Follows the background terminals of `session` and its subagents until none runs:
|
||||
/// codex keeps them running after the turn that started them.
|
||||
fn watch_terminals(self: &Arc<Self>, session: &str) {
|
||||
{
|
||||
let mut state = self.state.lock();
|
||||
if state.gone {
|
||||
return;
|
||||
}
|
||||
let Some(t) = state.threads.get_mut(session) else { return };
|
||||
if t.watching {
|
||||
t.relist = true;
|
||||
return;
|
||||
}
|
||||
t.watching = true;
|
||||
}
|
||||
let (shim, session) = (self.clone(), session.to_owned());
|
||||
self.runtime.spawn(async move {
|
||||
loop {
|
||||
let running = shim.list_terminals(&session).await;
|
||||
let relist = {
|
||||
let mut state = shim.state.lock();
|
||||
let Some(t) = state.threads.get_mut(&session) else { return };
|
||||
let relist = std::mem::take(&mut t.relist);
|
||||
if !relist && !running {
|
||||
t.watching = false;
|
||||
return;
|
||||
}
|
||||
relist
|
||||
};
|
||||
if !relist {
|
||||
tokio::time::sleep(TERMINAL_POLL).await;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Reports the running background terminals of `session` and its subagents as the
|
||||
/// session's background tasks; whether any runs. A codex without the (experimental)
|
||||
/// listing has none to report.
|
||||
async fn list_terminals(&self, session: &str) -> bool {
|
||||
let threads: Vec<String> = {
|
||||
let state = self.state.lock();
|
||||
let children = state.threads.iter().filter(|(_, t)| t.parent.as_deref() == Some(session));
|
||||
std::iter::once(session.to_owned()).chain(children.map(|(id, _)| id.clone())).collect()
|
||||
};
|
||||
let mut terminals = HashMap::new();
|
||||
let mut tasks = Vec::new();
|
||||
for thread in &threads {
|
||||
let listed = match self.terminals_of(thread).await {
|
||||
Ok(listed) => listed,
|
||||
Err(e) => {
|
||||
tracing::debug!("codex: listing the background terminals of {thread}: {}", e.message);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
for (process, description) in listed {
|
||||
let id = if thread == session { process.clone() } else { format!("{thread}:{process}") };
|
||||
tasks.push(json!({ "task_id": id, "task_type": "local_bash", "description": description }));
|
||||
terminals.insert(id, (thread.clone(), process));
|
||||
}
|
||||
}
|
||||
let running = !tasks.is_empty();
|
||||
let changed = {
|
||||
let mut state = self.state.lock();
|
||||
let Some(t) = state.threads.get_mut(session) else { return false };
|
||||
t.terminals = terminals;
|
||||
let changed = t.shown_tasks != tasks;
|
||||
if changed {
|
||||
t.shown_tasks = tasks.clone();
|
||||
}
|
||||
changed
|
||||
};
|
||||
if changed {
|
||||
self.emit(session, json!({ "sessionUpdate": crate::BACKGROUND_TASKS_UPDATE, "tasks": tasks }));
|
||||
}
|
||||
running
|
||||
}
|
||||
|
||||
/// The running background terminals of `thread`, as `(processId, description)`.
|
||||
async fn terminals_of(&self, thread: &str) -> Result<Vec<(String, String)>, ResponseError> {
|
||||
let mut all = Vec::new();
|
||||
let mut cursor = Value::Null;
|
||||
let mut seen = HashSet::new();
|
||||
loop {
|
||||
let page =
|
||||
self.call("thread/backgroundTerminals/list", json!({ "threadId": thread, "cursor": cursor })).await?;
|
||||
all.extend(translate::background_terminals(&page));
|
||||
match page.get("nextCursor").and_then(Value::as_str) {
|
||||
Some(next) if !next.is_empty() && seen.insert(next.to_owned()) => cursor = json!(next),
|
||||
_ => return Ok(all),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `_openidea/stop_task`: stops one background terminal.
|
||||
async fn stop_task(&self, params: &Value) -> Result<Value, ResponseError> {
|
||||
let session = str_param(params, "sessionId")?;
|
||||
let task = str_param(params, "taskId")?;
|
||||
let known = self.state.lock().threads.get(session).and_then(|t| t.terminals.get(task).cloned());
|
||||
let (thread, process) = known.unwrap_or_else(|| (session.to_owned(), task.to_owned()));
|
||||
self.call("thread/backgroundTerminals/terminate", json!({ "threadId": thread, "processId": process })).await?;
|
||||
self.list_terminals(session).await;
|
||||
Ok(json!({}))
|
||||
}
|
||||
|
||||
/// Stops the background terminals of `threads`; a codex without the (experimental)
|
||||
/// method has none.
|
||||
async fn clean_terminals(&self, threads: &[String]) {
|
||||
if threads.is_empty() || self.state.lock().gone {
|
||||
return;
|
||||
}
|
||||
let clean = async {
|
||||
for thread in threads {
|
||||
if let Err(e) = self.call("thread/backgroundTerminals/clean", json!({ "threadId": thread })).await {
|
||||
tracing::debug!("codex: stopping the background terminals of {thread}: {}", e.message);
|
||||
}
|
||||
}
|
||||
};
|
||||
if tokio::time::timeout(TERMINAL_CLEAN, clean).await.is_err() {
|
||||
tracing::warn!("codex: stopping the background terminals timed out");
|
||||
}
|
||||
}
|
||||
|
||||
/// `session/cancel`: interrupts the session's turn, or the one about to start.
|
||||
fn cancel(&self, session: &str) {
|
||||
let mut state = self.state.lock();
|
||||
@@ -1439,19 +1261,6 @@ impl CodexShim {
|
||||
t.turn = None;
|
||||
}
|
||||
t.completed = Some(id.to_owned());
|
||||
// A command still open when its turn completed goes on in the background (a
|
||||
// background terminal): its call returned, so it didn't fail with the turn. Its
|
||||
// own completion reports how it ended. Sent before the prompt's answer settles the
|
||||
// turn.
|
||||
if completed {
|
||||
let commands = t.items.values().filter(|i| i["type"] == "commandExecution");
|
||||
for id in commands.filter_map(|i| i["id"].as_str()) {
|
||||
self.emit(
|
||||
thread,
|
||||
json!({ "sessionUpdate": "tool_call_update", "toolCallId": id, "status": "completed" }),
|
||||
);
|
||||
}
|
||||
}
|
||||
t.items.clear();
|
||||
t.last_chunk = None;
|
||||
let error = t.error.take();
|
||||
@@ -1466,7 +1275,6 @@ impl CodexShim {
|
||||
t.naming |= name;
|
||||
(t.parent.clone(), (answer, error), name)
|
||||
};
|
||||
self.watch_terminals(parent.as_deref().unwrap_or(thread));
|
||||
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 });
|
||||
|
||||
@@ -66,7 +66,6 @@ fn manager(dir: &Path, runtime: Arc<Runtime>) -> AgentManager {
|
||||
store_dir: dir.join("store"),
|
||||
worktrees_dir: dir.join("worktrees"),
|
||||
models_file: dir.join("models.json"),
|
||||
cli_dir: dir.join("agent-cli"),
|
||||
custom_agents_dir: Some(agents),
|
||||
home_dir: Some(dir.into()),
|
||||
env_secrets: None,
|
||||
|
||||
@@ -125,13 +125,11 @@ for line in sys.stdin:
|
||||
name: "Codex".into(),
|
||||
driver: crate::provider::Driver::Codex,
|
||||
command: script.to_string_lossy().into_owned(),
|
||||
managed_cli: None,
|
||||
args: Vec::new(),
|
||||
additional_args_len: 0,
|
||||
env: Vec::new(),
|
||||
login_hint: String::new(),
|
||||
source: crate::AgentSource::Builtin,
|
||||
base: None,
|
||||
};
|
||||
let found = discover(spec, tmp.path().to_path_buf()).await.unwrap();
|
||||
let models: Vec<_> = found
|
||||
@@ -1021,12 +1019,10 @@ async fn play<R: AsyncRead + Unpin, W: AsyncWrite + Unpin>(
|
||||
.unwrap()
|
||||
.unwrap_or_else(|| panic!("the shim closed before {frame}"));
|
||||
let actual: Value = serde_json::from_str(&line).unwrap();
|
||||
// Older recordings predate config inspection, skill discovery, thread naming and
|
||||
// background terminals; play an unsupported server.
|
||||
// Older recordings predate config inspection, skill discovery and thread naming; play an
|
||||
// unsupported server.
|
||||
let method = actual["method"].as_str().unwrap_or_default();
|
||||
let unrecorded = matches!(method, "config/read" | "skills/list" | "thread/sample")
|
||||
|| method.starts_with("thread/backgroundTerminals/");
|
||||
if unrecorded && frame["method"] != method {
|
||||
if matches!(method, "config/read" | "skills/list" | "thread/sample") && frame["method"] != method {
|
||||
let reply = json!({ "id": actual["id"], "error": { "code": -32601, "message": "unsupported" } });
|
||||
write.write_all(format!("{reply}\n").as_bytes()).await.unwrap();
|
||||
continue;
|
||||
@@ -1166,60 +1162,6 @@ impl Handler for TrustServer {
|
||||
}
|
||||
}
|
||||
|
||||
/// Forks a thread holding two finished turns and one cut off by the fork.
|
||||
#[derive(Default)]
|
||||
struct ForkServer {
|
||||
calls: Mutex<Vec<(String, Value)>>,
|
||||
}
|
||||
|
||||
impl Handler for ForkServer {
|
||||
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" | "thread/rollback" => Ok(json!({})),
|
||||
"model/list" | "skills/list" => Ok(json!({"data": []})),
|
||||
"config/read" => Ok(json!({"layers": []})),
|
||||
"thread/fork" => Ok(json!({"thread": {"id": "copy", "turns": [
|
||||
{"id": "t1", "status": "completed"},
|
||||
{"id": "t2", "status": "completed"},
|
||||
{"id": "t3", "status": "interrupted"},
|
||||
]}})),
|
||||
_ => Err((codes::METHOD_NOT_FOUND, method.to_owned())),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn fork_keeps_the_asked_turns_of_what_the_fork_holds() {
|
||||
for (turns, rolled_back, kept) in [(Some(2), Some(1), Some(2)), (Some(3), None, Some(3)), (Some(4), None, None)] {
|
||||
let server = Arc::new(ForkServer::default());
|
||||
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(Arc::new(Client::default()), |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": "/tmp", "sessionId": "source", "mcpServers": [],
|
||||
"_meta": {"openidea": {"forkTurns": turns}}});
|
||||
let reply = request(&acp, "session/fork", params).await.unwrap();
|
||||
assert_eq!(reply["sessionId"], "copy");
|
||||
assert_eq!(reply.pointer("/_meta/openidea/forkTurns").and_then(Value::as_u64), kept);
|
||||
let rollbacks: Vec<Value> =
|
||||
server.calls.lock().iter().filter(|(m, _)| m == "thread/rollback").map(|(_, p)| p.clone()).collect();
|
||||
assert_eq!(
|
||||
rollbacks,
|
||||
rolled_back.map(|n| json!({"threadId": "copy", "numTurns": n})).into_iter().collect::<Vec<_>>()
|
||||
);
|
||||
acp.kill();
|
||||
native.kill();
|
||||
}
|
||||
}
|
||||
|
||||
#[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"] {
|
||||
@@ -1301,10 +1243,7 @@ async fn auth_failure_names_auth() {
|
||||
let (results, _client, frames, _) = replay(Scenario::AuthFailure).await;
|
||||
let init = result(&results, "initialize").as_ref().unwrap();
|
||||
assert_eq!(init["agentCapabilities"]["loadSession"], true);
|
||||
assert_eq!(
|
||||
init["agentCapabilities"]["_meta"]["openidea"],
|
||||
json!({"rollback": true, "steer": true, "backgroundTasks": true})
|
||||
);
|
||||
assert_eq!(init["agentCapabilities"]["_meta"]["openidea"], json!({"rollback": true, "steer": true}));
|
||||
assert!(init["agentCapabilities"]["sessionCapabilities"]["fork"].is_object());
|
||||
let new = result(&results, "new").as_ref().unwrap();
|
||||
let categories: Vec<&str> =
|
||||
@@ -2227,7 +2166,8 @@ fn workspace_roots_join_the_thread_roots() {
|
||||
"skills": { "codexOff": [["noisy", "/repo/.agents/skills/noisy/SKILL.md"]] },
|
||||
"memory": {
|
||||
"codexUseMemories": true,
|
||||
"codexGenerateMemories": false
|
||||
"codexGenerateMemories": false,
|
||||
"codexDeveloperInstructions": "## Memory (style)\nUse targeted selectors."
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2235,27 +2175,8 @@ fn workspace_roots_join_the_thread_roots() {
|
||||
&mut mem_req,
|
||||
);
|
||||
assert_eq!(mem_req["config"]["memories"], json!({ "use_memories": true, "generate_memories": false }));
|
||||
assert_eq!(mem_req["config"]["features"]["memories"], true);
|
||||
assert_eq!(mem_req["config"]["developer_instructions"], "## Memory (style)\nUse targeted selectors.");
|
||||
assert_eq!(mem_req["config"]["skills"]["config"][0]["enabled"], false);
|
||||
|
||||
let mut off_req = json!({});
|
||||
apply_thread_config(
|
||||
&json!({
|
||||
"cwd": "/w/api",
|
||||
"mcpServers": [],
|
||||
"_meta": {
|
||||
"openidea": {
|
||||
"memory": {
|
||||
"codexUseMemories": false,
|
||||
"codexGenerateMemories": false
|
||||
}
|
||||
}
|
||||
}
|
||||
}),
|
||||
&mut off_req,
|
||||
);
|
||||
assert_eq!(off_req["config"]["memories"], json!({ "use_memories": false, "generate_memories": false }));
|
||||
assert!(off_req["config"].get("features").is_none());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
@@ -2294,179 +2215,3 @@ async fn an_ephemeral_session_starts_an_ephemeral_thread() {
|
||||
native.kill();
|
||||
}
|
||||
}
|
||||
|
||||
/// A codex whose background terminals listings come from `pages` (an empty list after
|
||||
/// them); `None` answers like a codex without the method.
|
||||
struct TerminalServer {
|
||||
pages: Mutex<VecDeque<Value>>,
|
||||
supported: bool,
|
||||
calls: Mutex<Vec<(String, Value)>>,
|
||||
}
|
||||
|
||||
impl TerminalServer {
|
||||
fn new(pages: Vec<Value>, supported: bool) -> Arc<Self> {
|
||||
Arc::new(Self { pages: Mutex::new(pages.into()), supported, calls: Mutex::default() })
|
||||
}
|
||||
|
||||
fn calls_of(&self, method: &str) -> Vec<Value> {
|
||||
self.calls.lock().iter().filter(|(m, _)| m == method).map(|(_, p)| p.clone()).collect()
|
||||
}
|
||||
}
|
||||
|
||||
impl Handler for TerminalServer {
|
||||
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" => Ok(json!({"layers": []})),
|
||||
"thread/start" => Ok(json!({"thread": {"id": "s", "turns": []}, "cwd": "/w"})),
|
||||
"skills/list" => Ok(json!({"data": []})),
|
||||
"thread/unsubscribe" => Ok(json!({})),
|
||||
m if m.starts_with("thread/backgroundTerminals/") && !self.supported => {
|
||||
Err((codes::INVALID_REQUEST, format!("Invalid request: unknown variant `{m}`")))
|
||||
}
|
||||
"thread/backgroundTerminals/list" => {
|
||||
Ok(self.pages.lock().pop_front().unwrap_or_else(|| json!({"data": [], "nextCursor": null})))
|
||||
}
|
||||
"thread/backgroundTerminals/terminate" => Ok(json!({"terminated": true})),
|
||||
"thread/backgroundTerminals/clean" => Ok(json!({})),
|
||||
_ => Err((codes::METHOD_NOT_FOUND, method.to_owned())),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn terminal(process: &str, command: &str) -> Value {
|
||||
json!({"itemId": format!("item-{process}"), "processId": process, "command": command, "cwd": "/w", "osPid": 4242})
|
||||
}
|
||||
|
||||
/// A session over a codex playing `server`; the codex peer and the ACP peer.
|
||||
async fn terminal_session(server: Arc<TerminalServer>, client: Arc<Client>) -> (Peer, Peer) {
|
||||
let (ours, theirs) = tokio::io::duplex(1 << 16);
|
||||
let (read, write) = tokio::io::split(theirs);
|
||||
let native = Peer::connect_framed(read, write, server, Framing::Lines);
|
||||
let acp = attach(client, |events| {
|
||||
let (read, write) = tokio::io::split(ours);
|
||||
Ok(Peer::connect_framed(read, write, events, Framing::Lines))
|
||||
})
|
||||
.unwrap();
|
||||
let init = request(&acp, "initialize", json!({})).await.unwrap();
|
||||
assert_eq!(init["agentCapabilities"]["_meta"]["openidea"]["backgroundTasks"], true);
|
||||
request(&acp, "session/new", json!({"cwd": "/w", "mcpServers": []})).await.unwrap();
|
||||
(native, acp)
|
||||
}
|
||||
|
||||
fn shown_tasks(client: &Client) -> Vec<Value> {
|
||||
client
|
||||
.of("s")
|
||||
.into_iter()
|
||||
.filter(|u| u["sessionUpdate"] == crate::BACKGROUND_TASKS_UPDATE)
|
||||
.map(|u| u["tasks"].clone())
|
||||
.collect()
|
||||
}
|
||||
|
||||
async fn until(what: &str, mut done: impl FnMut() -> bool) {
|
||||
for _ in 0..200 {
|
||||
if done() {
|
||||
return;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
panic!("timed out waiting for {what}");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn background_terminals_outlive_their_turn_as_background_tasks_until_they_end() {
|
||||
let running = json!({"data": [terminal("p1", "/bin/zsh -lc 'sleep 600; echo done'")], "nextCursor": null});
|
||||
let server = TerminalServer::new(vec![running.clone(), running.clone(), running], true);
|
||||
let client = Arc::new(Client::default());
|
||||
let (native, acp) = terminal_session(server.clone(), client.clone()).await;
|
||||
native.notify("turn/completed", json!({"threadId": "s", "turn": {"id": "t1", "status": "interrupted"}})).unwrap();
|
||||
until("the terminal to end", || shown_tasks(&client).len() == 2).await;
|
||||
assert_eq!(
|
||||
shown_tasks(&client),
|
||||
[json!([{"task_id": "p1", "task_type": "local_bash", "description": "sleep 600; echo done"}]), json!([])]
|
||||
);
|
||||
let listed = server.calls_of("thread/backgroundTerminals/list").len();
|
||||
assert!(listed >= 4, "listed until none ran, got {listed}");
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
assert_eq!(server.calls_of("thread/backgroundTerminals/list").len(), listed, "stops listing once none runs");
|
||||
acp.kill();
|
||||
native.kill();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_background_terminal_stops_on_request_and_all_stop_with_the_connection() {
|
||||
let running = json!({"data": [terminal("p1", "cargo nextest run")], "nextCursor": null});
|
||||
let server = TerminalServer::new(vec![running; 1000], true);
|
||||
let client = Arc::new(Client::default());
|
||||
let (native, acp) = terminal_session(server.clone(), client.clone()).await;
|
||||
native.notify("turn/completed", json!({"threadId": "s", "turn": {"id": "t1", "status": "interrupted"}})).unwrap();
|
||||
until("the terminal to show", || !shown_tasks(&client).is_empty()).await;
|
||||
request(&acp, "_openidea/stop_task", json!({"sessionId": "s", "taskId": "p1"})).await.unwrap();
|
||||
assert_eq!(server.calls_of("thread/backgroundTerminals/terminate"), [json!({"threadId": "s", "processId": "p1"})]);
|
||||
assert!(server.calls_of("thread/backgroundTerminals/clean").is_empty());
|
||||
acp.kill();
|
||||
until("the terminals to be cleaned", || !server.calls_of("thread/backgroundTerminals/clean").is_empty()).await;
|
||||
assert_eq!(server.calls_of("thread/backgroundTerminals/clean"), [json!({"threadId": "s"})]);
|
||||
native.kill();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn closing_a_session_stops_its_background_terminals() {
|
||||
let server = TerminalServer::new(Vec::new(), true);
|
||||
let client = Arc::new(Client::default());
|
||||
let (native, acp) = terminal_session(server.clone(), client).await;
|
||||
request(&acp, "session/close", json!({"sessionId": "s"})).await.unwrap();
|
||||
let calls: Vec<String> = server.calls.lock().iter().map(|(m, _)| m.clone()).collect();
|
||||
let clean = calls.iter().position(|m| m == "thread/backgroundTerminals/clean").expect("cleaned");
|
||||
let unsubscribe = calls.iter().position(|m| m == "thread/unsubscribe").expect("unsubscribed");
|
||||
assert!(clean < unsubscribe);
|
||||
acp.kill();
|
||||
native.kill();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_codex_without_background_terminals_reports_none() {
|
||||
let server = TerminalServer::new(Vec::new(), false);
|
||||
let client = Arc::new(Client::default());
|
||||
let (native, acp) = terminal_session(server.clone(), client.clone()).await;
|
||||
native.notify("turn/completed", json!({"threadId": "s", "turn": {"id": "t1", "status": "interrupted"}})).unwrap();
|
||||
until("the listing", || !server.calls_of("thread/backgroundTerminals/list").is_empty()).await;
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
assert_eq!(server.calls_of("thread/backgroundTerminals/list").len(), 1);
|
||||
assert!(shown_tasks(&client).is_empty());
|
||||
assert!(request(&acp, "_openidea/stop_task", json!({"sessionId": "s", "taskId": "p1"})).await.is_err());
|
||||
acp.kill();
|
||||
native.kill();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_command_left_running_by_a_completed_turn_is_not_a_failure() {
|
||||
for (status, settled) in [("completed", true), ("interrupted", false)] {
|
||||
let server = TerminalServer::new(Vec::new(), true);
|
||||
let client = Arc::new(Client::default());
|
||||
let (native, acp) = terminal_session(server, client.clone()).await;
|
||||
let item = json!({"type": "commandExecution", "id": "call_1", "command": "/bin/zsh -lc 'sleep 240'",
|
||||
"cwd": "/w", "status": "inProgress", "commandActions": []});
|
||||
native.notify("item/started", json!({"threadId": "s", "turnId": "t1", "item": item})).unwrap();
|
||||
native.notify("turn/completed", json!({"threadId": "s", "turn": {"id": "t1", "status": status}})).unwrap();
|
||||
until("the command card", || client.of("s").iter().any(|u| u["sessionUpdate"] == "tool_call")).await;
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
let updates: Vec<Value> = client
|
||||
.of("s")
|
||||
.into_iter()
|
||||
.filter(|u| u["sessionUpdate"] == "tool_call_update" && u["toolCallId"] == "call_1")
|
||||
.collect();
|
||||
let expected = if settled {
|
||||
vec![json!({"sessionUpdate": "tool_call_update", "toolCallId": "call_1", "status": "completed"})]
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
assert_eq!(updates, expected, "turn {status}");
|
||||
acp.kill();
|
||||
native.kill();
|
||||
}
|
||||
}
|
||||
@@ -553,12 +553,7 @@ fn image_content(image: &crate::model::AgentImage) -> Value {
|
||||
/// A generated image: inline (base64 PNG) or, when codex saved it, the file.
|
||||
fn generated_image(item: &Value) -> Option<crate::model::AgentImage> {
|
||||
if let Some(data) = item.get("result").and_then(Value::as_str).filter(|d| !d.is_empty()) {
|
||||
let image = crate::model::AgentImage {
|
||||
mime_type: "image/png".into(),
|
||||
data: data.into(),
|
||||
name: None,
|
||||
inline_number: None,
|
||||
};
|
||||
let image = crate::model::AgentImage { mime_type: "image/png".into(), data: data.into(), name: None };
|
||||
return Some(crate::model::AgentImage { mime_type: image.media_type().into(), ..image });
|
||||
}
|
||||
crate::images::from_file(std::path::Path::new(item.get("savedPath")?.as_str()?))
|
||||
@@ -881,20 +876,6 @@ pub(super) fn decisions(params: &Value, command: bool) -> Vec<Choice> {
|
||||
out
|
||||
}
|
||||
|
||||
/// One page of `thread/backgroundTerminals/list`: the running terminals as
|
||||
/// `(processId, description)`.
|
||||
pub(super) fn background_terminals(page: &Value) -> Vec<(String, String)> {
|
||||
let data = page.get("data").and_then(Value::as_array).map(Vec::as_slice).unwrap_or_default();
|
||||
data.iter()
|
||||
.filter_map(|t| {
|
||||
let process = t.get("processId").and_then(Value::as_str).filter(|p| !p.is_empty())?;
|
||||
let command = t.get("command").and_then(Value::as_str).unwrap_or_default();
|
||||
let description = crate::shell_script(command).unwrap_or_else(|| command.to_owned());
|
||||
Some((process.to_owned(), description))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A command prefix as typed: the script of a `<shell> -lc <script>` wrapper, else the words.
|
||||
fn shell_unwrapped(argv: &[&str]) -> String {
|
||||
match argv {
|
||||
|
||||
@@ -37,15 +37,6 @@ const DISCOVER_TIMEOUT: Duration = if cfg!(test) { Duration::from_secs(5) } else
|
||||
const EARLY_CANCEL: Duration = Duration::from_secs(2);
|
||||
const EXIT_GRACE: Duration = Duration::from_millis(100);
|
||||
|
||||
/// Copilot's configuration directory (`COPILOT_HOME`, otherwise `<home>/.copilot`).
|
||||
pub(crate) fn config_dir(env: &[(String, String)], home: Option<&Path>) -> Option<PathBuf> {
|
||||
env.iter()
|
||||
.find(|(key, _)| key == "COPILOT_HOME")
|
||||
.map(|(_, value)| PathBuf::from(value))
|
||||
.or_else(|| std::env::var_os("COPILOT_HOME").map(PathBuf::from))
|
||||
.or_else(|| home.map(|home| home.join(".copilot")))
|
||||
}
|
||||
|
||||
/// Pre-session discovery result for `Shared::fetch_settings`.
|
||||
pub(crate) struct Discovered {
|
||||
pub commands: Vec<Value>,
|
||||
@@ -68,7 +59,7 @@ pub(crate) fn connect(
|
||||
) -> std::io::Result<Peer> {
|
||||
let launch_args = spec.args.clone();
|
||||
attach_with_args(client, launch_args, |events| {
|
||||
let command = super::newest_install(spec.executable());
|
||||
let command = super::newest_install(&spec.command);
|
||||
let args = headless_args(&spec.args);
|
||||
Peer::spawn_framed(&command, &args, cwd, &spec.env, events, on_stderr, Framing::ContentLength)
|
||||
})
|
||||
@@ -471,6 +462,38 @@ fn apply_skills(params: &Value, req: &mut Value) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Applies `_meta.openidea.memory` to Copilot's `session.create` / `session.resume` payload:
|
||||
/// gates `store_memory` when auto-memory is `ReadOnly` or `Off`, disables custom instructions
|
||||
/// when all workspace/user instructions are muted, and appends shared OpenIDEA memories.
|
||||
fn apply_memory(params: &Value, req: &mut Value) {
|
||||
let Some(mem) = params.pointer("/_meta/openidea/memory") else {
|
||||
return;
|
||||
};
|
||||
if mem.get("copilotExcludeStoreMemory").and_then(Value::as_bool) == Some(true) {
|
||||
let mut excluded: Vec<String> = req
|
||||
.get("excludedTools")
|
||||
.and_then(Value::as_array)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(Value::as_str)
|
||||
.map(str::to_owned)
|
||||
.collect();
|
||||
if !excluded.iter().any(|t| t == "store_memory") {
|
||||
excluded.push("store_memory".into());
|
||||
}
|
||||
req["excludedTools"] = json!(excluded);
|
||||
}
|
||||
if mem.get("copilotDisableCustomInstructions").and_then(Value::as_bool) == Some(true) {
|
||||
req["customInstructions"] = json!(false);
|
||||
}
|
||||
if let Some(sys) = mem.get("copilotSystemMessage").and_then(Value::as_str).filter(|s| !s.is_empty()) {
|
||||
req["systemMessage"] = json!({
|
||||
"mode": "append",
|
||||
"content": sys,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn invalid(message: impl Into<String>) -> ResponseError {
|
||||
error(codes::INVALID_PARAMS, message)
|
||||
}
|
||||
@@ -528,7 +551,6 @@ impl CopilotShim {
|
||||
"initialize" => self.initialize().await,
|
||||
"session/new" => self.new_session(¶ms).await,
|
||||
"session/load" => self.load_session(¶ms).await,
|
||||
"session/fork" => self.fork_session(¶ms).await,
|
||||
"session/set_config_option" => self.set_config(¶ms).await,
|
||||
"session/prompt" => self.prompt(¶ms, false).await,
|
||||
"_openidea/steer" => self.prompt(¶ms, true).await,
|
||||
@@ -547,7 +569,7 @@ impl CopilotShim {
|
||||
"loadSession": true,
|
||||
"promptCapabilities": { "image": true, "audio": false, "embeddedContext": true },
|
||||
"mcpCapabilities": { "http": true, "sse": true, "stdio": true },
|
||||
"sessionCapabilities": { "fork": {}, "close": {}, "list": {} },
|
||||
"sessionCapabilities": { "close": {}, "list": {} },
|
||||
"_meta": { "openidea": { "steer": true, "backgroundTasks": true, "contextUsage": true } },
|
||||
},
|
||||
"agentInfo": {
|
||||
@@ -598,6 +620,7 @@ impl CopilotShim {
|
||||
req["disabledMcpServers"] = disabled;
|
||||
}
|
||||
apply_skills(params, &mut req);
|
||||
apply_memory(params, &mut req);
|
||||
|
||||
let created = self.call("session.create", req).await?;
|
||||
let session_id = created
|
||||
@@ -626,25 +649,6 @@ impl CopilotShim {
|
||||
|
||||
async fn load_session(self: &Arc<Self>, params: &Value) -> Result<Value, ResponseError> {
|
||||
let session_id = str_param(params, "sessionId")?.to_owned();
|
||||
let loaded = self.resume_session(params, &session_id).await?;
|
||||
let actual_id = loaded.get("sessionId").and_then(Value::as_str).unwrap_or(&session_id).to_owned();
|
||||
self.replay_history(&actual_id).await;
|
||||
Ok(loaded)
|
||||
}
|
||||
|
||||
async fn fork_session(self: &Arc<Self>, params: &Value) -> Result<Value, ResponseError> {
|
||||
let source = str_param(params, "sessionId")?;
|
||||
let forked = self.call("sessions.fork", json!({ "sessionId": source })).await?;
|
||||
let target = forked
|
||||
.get("sessionId")
|
||||
.and_then(Value::as_str)
|
||||
.filter(|id| !id.is_empty())
|
||||
.ok_or_else(|| error(codes::INTERNAL_ERROR, "Copilot fork returned no sessionId"))?
|
||||
.to_owned();
|
||||
self.resume_session(params, &target).await
|
||||
}
|
||||
|
||||
async fn resume_session(self: &Arc<Self>, params: &Value, session_id: &str) -> Result<Value, ResponseError> {
|
||||
let cwd = str_param(params, "cwd")?;
|
||||
let catalog = self.models().await?;
|
||||
let defaults = fetch_user_defaults(self.copilot(), &self.args).await;
|
||||
@@ -668,10 +672,10 @@ impl CopilotShim {
|
||||
req["disabledMcpServers"] = disabled;
|
||||
}
|
||||
apply_skills(params, &mut req);
|
||||
apply_memory(params, &mut req);
|
||||
|
||||
let resumed = self.call("session.resume", req).await?;
|
||||
let actual_id = resumed.get("sessionId").and_then(Value::as_str).unwrap_or(session_id).to_owned();
|
||||
if let Ok(current) = self.call("session.model.getCurrent", json!({ "sessionId": actual_id })).await {
|
||||
if let Ok(current) = self.call("session.model.getCurrent", json!({ "sessionId": session_id })).await {
|
||||
if let Some(model_id) = current.get("modelId").or_else(|| current.get("model")).and_then(Value::as_str) {
|
||||
let _ = settings.set(&catalog, MODEL, model_id);
|
||||
}
|
||||
@@ -682,6 +686,7 @@ impl CopilotShim {
|
||||
let _ = settings.set(&catalog, CONTEXT_TIER, tier);
|
||||
}
|
||||
}
|
||||
let actual_id = resumed.get("sessionId").and_then(Value::as_str).unwrap_or(&session_id).to_owned();
|
||||
let options = models::config_options(&catalog, &settings);
|
||||
self.state.lock().sessions.insert(actual_id.clone(), SessionEntry::new(settings));
|
||||
self.publish_commands(&actual_id, cwd);
|
||||
@@ -692,28 +697,6 @@ impl CopilotShim {
|
||||
}))
|
||||
}
|
||||
|
||||
async fn replay_history(&self, session_id: &str) {
|
||||
let history = match self.call("session.getMessages", json!({ "sessionId": session_id })).await {
|
||||
Ok(history) => history,
|
||||
Err(error) => {
|
||||
tracing::warn!("copilot session {session_id}: could not load history: {}", error.message);
|
||||
return;
|
||||
}
|
||||
};
|
||||
let events = history.get("events").and_then(Value::as_array).map(Vec::as_slice).unwrap_or_default();
|
||||
let updates = {
|
||||
let mut state = self.state.lock();
|
||||
let Some(entry) = state.sessions.get_mut(session_id) else { return };
|
||||
events
|
||||
.iter()
|
||||
.flat_map(|event| entry.translator.translate_history(session_id, event, None).updates)
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
for (target_session, update) in updates {
|
||||
self.send_update(&target_session, update);
|
||||
}
|
||||
}
|
||||
|
||||
fn sync_usage_metrics(self: &Arc<Self>, session_id: &str) {
|
||||
let shim = self.clone();
|
||||
let sid = session_id.to_owned();
|
||||
@@ -1338,10 +1321,6 @@ fn build_prompt_payload(session_id: &str, blocks: &[Value]) -> (String, Vec<Valu
|
||||
{
|
||||
let path_str = saved.to_string_lossy().into_owned();
|
||||
let name = saved.file_name().and_then(|n| n.to_str()).unwrap_or("image").to_owned();
|
||||
// Copilot takes one text prompt and a separate attachments array.
|
||||
if let Some(number) = block.pointer("/_meta/openideaImageNumber").and_then(Value::as_u64) {
|
||||
text_parts.push(format!("[Image #{number}: {name}]"));
|
||||
}
|
||||
attachments.push(json!({ "type": "file", "path": path_str, "displayName": name }));
|
||||
temp_files.push(saved);
|
||||
}
|
||||
|
||||
@@ -115,18 +115,6 @@ fn sample_price_units() -> Value {
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolves_copilot_home_from_agent_env_or_user_home() {
|
||||
let home = std::path::Path::new("/home/test");
|
||||
assert_eq!(
|
||||
super::config_dir(&[("COPILOT_HOME".into(), "/custom/copilot".into())], Some(home)).as_deref(),
|
||||
Some(std::path::Path::new("/custom/copilot"))
|
||||
);
|
||||
if std::env::var_os("COPILOT_HOME").is_none() {
|
||||
assert_eq!(super::config_dir(&[], Some(home)), Some(home.join(".copilot")));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_an_enabled_auto_only_catalog() {
|
||||
let list = json!({
|
||||
@@ -446,39 +434,6 @@ impl Handler for FakeCopilotServer {
|
||||
"skills.discover" => Ok(json!({ "skills": [] })),
|
||||
"session.create" => Ok(json!({ "sessionId": "cop-sess-1" })),
|
||||
"session.resume" => Ok(json!({ "sessionId": params["sessionId"] })),
|
||||
"sessions.fork" => Ok(json!({ "sessionId": "cop-sess-fork" })),
|
||||
"session.getMessages" => Ok(json!({
|
||||
"events": [
|
||||
{
|
||||
"type": "user.message",
|
||||
"data": { "content": "Fix the parser" }
|
||||
},
|
||||
{
|
||||
"type": "assistant.message",
|
||||
"data": {
|
||||
"messageId": "history-message",
|
||||
"reasoningText": "Inspect the grammar first.",
|
||||
"content": "I fixed the parser."
|
||||
}
|
||||
},
|
||||
{
|
||||
"type": "tool.execution_start",
|
||||
"data": {
|
||||
"toolCallId": "history-tool",
|
||||
"toolName": "view",
|
||||
"arguments": { "path": "/tmp/parser.rs" }
|
||||
}
|
||||
},
|
||||
{
|
||||
"type": "tool.execution_complete",
|
||||
"data": {
|
||||
"toolCallId": "history-tool",
|
||||
"success": true,
|
||||
"result": { "content": "fn parse() {}" }
|
||||
}
|
||||
}
|
||||
]
|
||||
})),
|
||||
"session.model.getCurrent" => Ok(json!({ "modelId": "gemini-4-carbon" })),
|
||||
"session.model.switchTo" => Ok(json!({ "modelId": params["modelId"] })),
|
||||
"session.mode.set" => Ok(json!({})),
|
||||
@@ -719,81 +674,6 @@ async fn shim_creates_session_with_copilot_defaults_switches_tiers_and_streams_t
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn shim_loads_and_replays_copilot_history() {
|
||||
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!(init["agentCapabilities"]["sessionCapabilities"]["fork"].is_object());
|
||||
let loaded: Value = client
|
||||
.request("session/load", json!({ "sessionId": "cop-sess-1", "cwd": "/tmp", "mcpServers": [] }), None)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(loaded["sessionId"], "cop-sess-1");
|
||||
|
||||
assert!(
|
||||
server
|
||||
.calls
|
||||
.lock()
|
||||
.iter()
|
||||
.any(|(method, params)| { method == "session.getMessages" && params["sessionId"] == "cop-sess-1" })
|
||||
);
|
||||
let seen = updates.0.lock();
|
||||
assert!(
|
||||
seen.iter().any(|u| u["sessionUpdate"] == "user_message_chunk" && u["content"]["text"] == "Fix the parser")
|
||||
);
|
||||
assert!(
|
||||
seen.iter().any(
|
||||
|u| u["sessionUpdate"] == "agent_thought_chunk" && u["content"]["text"] == "Inspect the grammar first."
|
||||
)
|
||||
);
|
||||
assert!(
|
||||
seen.iter()
|
||||
.any(|u| u["sessionUpdate"] == "agent_message_chunk" && u["content"]["text"] == "I fixed the parser.")
|
||||
);
|
||||
assert!(seen.iter().any(|u| u["sessionUpdate"] == "tool_call" && u["toolCallId"] == "history-tool"));
|
||||
assert!(seen.iter().any(|u| u["sessionUpdate"] == "tool_call_update" && u["toolCallId"] == "history-tool"));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn shim_forks_copilot_sessions_and_resumes_the_new_id() {
|
||||
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 forked: Value = client
|
||||
.request("session/fork", json!({ "sessionId": "cop-sess-1", "cwd": "/tmp", "mcpServers": [] }), None)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(forked["sessionId"], "cop-sess-fork");
|
||||
let calls = server.calls.lock();
|
||||
assert!(calls.iter().any(|(method, params)| method == "sessions.fork" && params["sessionId"] == "cop-sess-1"));
|
||||
assert!(calls.iter().any(|(method, params)| method == "session.resume" && params["sessionId"] == "cop-sess-fork"));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn shim_forwards_disabled_mcp_servers_on_create_and_resume() {
|
||||
let server =
|
||||
@@ -953,6 +833,56 @@ async fn session_new_and_load_forward_staged_skill_directories_and_disabled_skil
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn session_new_and_load_apply_copilot_memory_gating_and_system_message() {
|
||||
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 meta = json!({
|
||||
"openidea": {
|
||||
"memory": {
|
||||
"autoMemory": "readOnly",
|
||||
"copilotExcludeStoreMemory": true,
|
||||
"copilotDisableCustomInstructions": true,
|
||||
"copilotSystemMessage": "## Memory (shared)\nRun targeted tests."
|
||||
}
|
||||
}
|
||||
});
|
||||
let _: Value =
|
||||
client.request("session/new", json!({ "cwd": "/tmp", "mcpServers": [], "_meta": meta }), None).await.unwrap();
|
||||
let _: Value = client
|
||||
.request(
|
||||
"session/load",
|
||||
json!({ "sessionId": "cop-sess-1", "cwd": "/tmp", "mcpServers": [], "_meta": meta }),
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let calls = server.calls.lock();
|
||||
for method in ["session.create", "session.resume"] {
|
||||
let params = calls.iter().find_map(|(m, p)| (m == method).then_some(p)).expect(method);
|
||||
assert_eq!(params["excludedTools"], json!(["store_memory"]), "{method}: {params}");
|
||||
assert_eq!(params["customInstructions"], json!(false), "{method}: {params}");
|
||||
assert_eq!(
|
||||
params["systemMessage"],
|
||||
json!({ "mode": "append", "content": "## Memory (shared)\nRun targeted tests." }),
|
||||
"{method}: {params}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn translates_context_attribution_without_double_counting_parent_rollups() {
|
||||
let payload = json!({
|
||||
|
||||
@@ -370,55 +370,6 @@ impl EventTranslator {
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Translates one persisted Copilot event returned by `session.getMessages`. The live
|
||||
/// event stream omits historical user messages and emits reasoning deltas, while the
|
||||
/// persisted form has complete user and assistant messages.
|
||||
pub fn translate_history(&mut self, main_session: &str, event: &Value, fallback_limit: Option<u32>) -> Translated {
|
||||
let event_type = str_of(event, "type").unwrap_or_default();
|
||||
let data = event.get("data").unwrap_or(&Value::Null);
|
||||
if event_type == "user.message" {
|
||||
let Some(text) = str_of(data, "content").map(str::trim).filter(|text| !text.is_empty()) else {
|
||||
return Translated { updates: Vec::new(), terminal: None };
|
||||
};
|
||||
let target_session = str_of(event, "agentId")
|
||||
.filter(|id| !id.is_empty())
|
||||
.map(|id| format!("{main_session}:sub:{id}"))
|
||||
.unwrap_or_else(|| main_session.to_owned());
|
||||
return Translated {
|
||||
updates: vec![(
|
||||
target_session,
|
||||
json!({
|
||||
"sessionUpdate": "user_message_chunk",
|
||||
"content": { "type": "text", "text": text },
|
||||
}),
|
||||
)],
|
||||
terminal: None,
|
||||
};
|
||||
}
|
||||
|
||||
let mut translated = self.translate(main_session, event, fallback_limit);
|
||||
if event_type == "assistant.message"
|
||||
&& !(data.get("parentToolCallId").and_then(Value::as_str).is_some() && str_of(event, "agentId").is_none())
|
||||
&& let Some(reasoning) = str_of(data, "reasoningText").map(str::trim).filter(|text| !text.is_empty())
|
||||
{
|
||||
let target_session = str_of(event, "agentId")
|
||||
.filter(|id| !id.is_empty())
|
||||
.map(|id| format!("{main_session}:sub:{id}"))
|
||||
.unwrap_or_else(|| main_session.to_owned());
|
||||
translated.updates.insert(
|
||||
0,
|
||||
(
|
||||
target_session,
|
||||
json!({
|
||||
"sessionUpdate": "agent_thought_chunk",
|
||||
"content": { "type": "text", "text": reasoning },
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
translated
|
||||
}
|
||||
}
|
||||
|
||||
fn describe_tool(name: &str, args: &Value) -> ToolInfo {
|
||||
|
||||
@@ -4,9 +4,7 @@
|
||||
//!
|
||||
//! A shim speaks ACP v1 as the agent side, plus:
|
||||
//! - `agentCapabilities.sessionCapabilities.fork` and `session/fork`
|
||||
//! (`{ sessionId, cwd, mcpServers }` → a `session/new` result for the copy). With
|
||||
//! `_meta.openidea.forkTurns`, the copy keeps only the source's first that many turns;
|
||||
//! the result repeats it in its `_meta.openidea.forkTurns` when the shim cut the copy;
|
||||
//! (`{ sessionId, cwd, mcpServers }` → a `session/new` result for the copy);
|
||||
//! - `agentCapabilities._meta.openidea.rollback` and `_openidea/rollback`
|
||||
//! (`{ sessionId, turns }`: drops the last `turns` user turns from the session);
|
||||
//! - `agentCapabilities._meta.openidea.steer` and `_openidea/steer`
|
||||
@@ -18,49 +16,8 @@ pub(crate) mod codex;
|
||||
pub(crate) mod copilot;
|
||||
|
||||
use ide_jsonrpc::{Framing, Handler, Peer};
|
||||
use parking_lot::Mutex;
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Arc, OnceLock};
|
||||
use std::time::{Duration, Instant, SystemTime};
|
||||
|
||||
const VERSION_CACHE_TTL: Duration = Duration::from_secs(60);
|
||||
|
||||
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
|
||||
struct VersionCacheKey {
|
||||
path: PathBuf,
|
||||
modified: Option<SystemTime>,
|
||||
len: Option<u64>,
|
||||
#[cfg(unix)]
|
||||
ino: Option<u64>,
|
||||
}
|
||||
|
||||
impl VersionCacheKey {
|
||||
fn of(real: &Path) -> Self {
|
||||
let meta = std::fs::metadata(real).ok();
|
||||
#[cfg(unix)]
|
||||
let ino = meta.as_ref().map(std::os::unix::fs::MetadataExt::ino);
|
||||
Self {
|
||||
path: real.to_path_buf(),
|
||||
modified: meta.as_ref().and_then(|m| m.modified().ok()),
|
||||
len: meta.as_ref().map(std::fs::Metadata::len),
|
||||
#[cfg(unix)]
|
||||
ino,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct CachedVersion {
|
||||
version: Vec<u64>,
|
||||
checked_at: Instant,
|
||||
}
|
||||
|
||||
type VersionSlot = Arc<Mutex<Option<CachedVersion>>>;
|
||||
|
||||
fn version_cache() -> &'static Mutex<HashMap<VersionCacheKey, VersionSlot>> {
|
||||
static CACHE: OnceLock<Mutex<HashMap<VersionCacheKey, VersionSlot>>> = OnceLock::new();
|
||||
CACHE.get_or_init(Default::default)
|
||||
}
|
||||
use std::sync::Arc;
|
||||
|
||||
/// The newest install of `command` on the `PATH` a child sees, by its `--version`.
|
||||
/// Several installs are common (npm, Homebrew, the vendor's own installer), and the first
|
||||
@@ -68,7 +25,11 @@ fn version_cache() -> &'static Mutex<HashMap<VersionCacheKey, VersionSlot>> {
|
||||
/// A path, or a name not found on `PATH`, is used as it is; a single match returns its
|
||||
/// resolved path so Windows `PATHEXT` shims (`claude.cmd`, `codex.cmd`) start.
|
||||
pub(crate) fn newest_install(command: &str) -> String {
|
||||
newest_install_in(command, &ide_core::tool_path::search_path())
|
||||
let path = ide_core::process::host_var_os("PATH")
|
||||
.or_else(|| ide_core::process::shell_env().find(|(k, _)| *k == "PATH").map(|(_, v)| v.to_owned()))
|
||||
.unwrap_or_default();
|
||||
// Windows: read afresh, so a tool the user installed since the IDE started is found too.
|
||||
newest_install_in(command, &ide_core::process::with_user_path(&path))
|
||||
}
|
||||
|
||||
fn newest_install_in(command: &str, search: &std::ffi::OsStr) -> String {
|
||||
@@ -79,69 +40,27 @@ fn newest_install_in(command: &str, search: &std::ffi::OsStr) -> String {
|
||||
let names =
|
||||
ide_core::process::executable_names(command, cfg!(windows), pathext.as_deref().and_then(|p| p.to_str()));
|
||||
let mut seen = Vec::new();
|
||||
let candidates: Vec<(PathBuf, PathBuf)> = std::env::split_paths(search)
|
||||
let candidates: Vec<PathBuf> = std::env::split_paths(search)
|
||||
.filter(|d| !d.as_os_str().is_empty())
|
||||
.flat_map(|dir| names.iter().map(move |n| dir.join(n)))
|
||||
.filter(|p| p.is_file())
|
||||
.filter_map(|p| {
|
||||
let real = dunce::canonicalize(&p).unwrap_or_else(|_| p.clone());
|
||||
if seen.contains(&real) {
|
||||
return None;
|
||||
}
|
||||
seen.push(real.clone());
|
||||
Some((p, real))
|
||||
.filter(|p| {
|
||||
let real = dunce::canonicalize(p).unwrap_or_else(|_| p.clone());
|
||||
let new = !seen.contains(&real);
|
||||
seen.push(real);
|
||||
new
|
||||
})
|
||||
.collect();
|
||||
if candidates.len() < 2 {
|
||||
return candidates
|
||||
.into_iter()
|
||||
.next()
|
||||
.map_or_else(|| command.to_owned(), |(p, _)| p.to_string_lossy().into_owned());
|
||||
return candidates.into_iter().next().map_or_else(|| command.to_owned(), |p| p.to_string_lossy().into_owned());
|
||||
}
|
||||
// Probe distinct installs in parallel; per-binary cache + single-flight avoids re-spawning
|
||||
// `--version` on concurrent or repeated lookups while still noticing upgraded binaries.
|
||||
let versions: Vec<Option<Vec<u64>>> = std::thread::scope(|s| {
|
||||
let handles: Vec<_> = candidates.iter().map(|(p, real)| s.spawn(|| cached_version_of(p, real))).collect();
|
||||
handles.into_iter().map(|h| h.join().ok().flatten()).collect()
|
||||
});
|
||||
candidates
|
||||
.into_iter()
|
||||
.zip(versions)
|
||||
.filter_map(|((p, _), v)| v.map(|v| (v, p)))
|
||||
.filter_map(|p| version_of(&p).map(|v| (v, p)))
|
||||
.max_by(|a, b| a.0.cmp(&b.0))
|
||||
.map_or_else(|| command.to_owned(), |(_, p)| p.to_string_lossy().into_owned())
|
||||
}
|
||||
|
||||
fn cached_version_of(program: &Path, real: &Path) -> Option<Vec<u64>> {
|
||||
let key = VersionCacheKey::of(real);
|
||||
let slot = {
|
||||
let mut cache = version_cache().lock();
|
||||
if cache.len() > 64 {
|
||||
cache.retain(|_, slot| {
|
||||
slot.try_lock()
|
||||
.is_none_or(|guard| guard.as_ref().is_some_and(|c| c.checked_at.elapsed() < VERSION_CACHE_TTL))
|
||||
});
|
||||
}
|
||||
cache.entry(key).or_default().clone()
|
||||
};
|
||||
let mut guard = slot.lock();
|
||||
if let Some(cached) = guard.as_ref()
|
||||
&& cached.checked_at.elapsed() < VERSION_CACHE_TTL
|
||||
{
|
||||
return Some(cached.version.clone());
|
||||
}
|
||||
match version_of(program) {
|
||||
Some(version) => {
|
||||
*guard = Some(CachedVersion { version: version.clone(), checked_at: Instant::now() });
|
||||
Some(version)
|
||||
}
|
||||
None => {
|
||||
*guard = None;
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `x.y.z` from `<program> --version` ("codex-cli 0.164.0", "2.1.312 (Claude Code)").
|
||||
fn version_of(program: &Path) -> Option<Vec<u64>> {
|
||||
let mut cmd = std::process::Command::new(program);
|
||||
@@ -227,77 +146,4 @@ mod tests {
|
||||
assert_eq!(newest_install_in("agent", &search), new.join("agent").to_string_lossy());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn newest_install_caches_versions_and_invalidates_on_change() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let old = dir.path().join("old");
|
||||
let new = dir.path().join("new");
|
||||
let old_log = dir.path().join("old.log");
|
||||
let new_log = dir.path().join("new.log");
|
||||
for (path, log, version) in [(&old, &old_log, "2.9.0"), (&new, &new_log, "2.10.0")] {
|
||||
std::fs::create_dir_all(path).unwrap();
|
||||
let executable = path.join("agent");
|
||||
std::fs::write(&executable, format!("#!/bin/sh\nprintf 'x\\n' >> '{}'\necho {version}\n", log.display()))
|
||||
.unwrap();
|
||||
std::fs::set_permissions(&executable, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
}
|
||||
let search = std::env::join_paths([&old, &new]).unwrap();
|
||||
assert_eq!(newest_install_in("agent", &search), new.join("agent").to_string_lossy());
|
||||
assert_eq!(newest_install_in("agent", &search), new.join("agent").to_string_lossy());
|
||||
assert_eq!(std::fs::read_to_string(&old_log).unwrap().lines().count(), 1);
|
||||
assert_eq!(std::fs::read_to_string(&new_log).unwrap().lines().count(), 1);
|
||||
|
||||
// Replacing the older binary with a newer version invalidates only its cache entry.
|
||||
let upgraded = old.join("agent");
|
||||
std::fs::write(&upgraded, format!("#!/bin/sh\nprintf 'x\\n' >> '{}'\necho 2.11.0\n", old_log.display()))
|
||||
.unwrap();
|
||||
std::fs::set_permissions(&upgraded, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
assert_eq!(newest_install_in("agent", &search), upgraded.to_string_lossy());
|
||||
assert_eq!(std::fs::read_to_string(&old_log).unwrap().lines().count(), 2);
|
||||
assert_eq!(std::fs::read_to_string(&new_log).unwrap().lines().count(), 1);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn newest_install_deduplicates_concurrent_probes() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let old = dir.path().join("old");
|
||||
let new = dir.path().join("new");
|
||||
let old_log = dir.path().join("old.log");
|
||||
let new_log = dir.path().join("new.log");
|
||||
for (path, log, version) in [(&old, &old_log, "2.9.0"), (&new, &new_log, "2.10.0")] {
|
||||
std::fs::create_dir_all(path).unwrap();
|
||||
let executable = path.join("agent");
|
||||
std::fs::write(
|
||||
&executable,
|
||||
format!("#!/bin/sh\nsleep 0.05\nprintf 'x\\n' >> '{}'\necho {version}\n", log.display()),
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::set_permissions(&executable, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
}
|
||||
let search = std::env::join_paths([&old, &new]).unwrap();
|
||||
let expected = new.join("agent").to_string_lossy().into_owned();
|
||||
let barrier = std::sync::Barrier::new(4);
|
||||
std::thread::scope(|s| {
|
||||
let handles: Vec<_> = (0..4)
|
||||
.map(|_| {
|
||||
s.spawn(|| {
|
||||
barrier.wait();
|
||||
newest_install_in("agent", &search)
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
for handle in handles {
|
||||
assert_eq!(handle.join().unwrap(), expected);
|
||||
}
|
||||
});
|
||||
assert_eq!(std::fs::read_to_string(&old_log).unwrap().lines().count(), 1);
|
||||
assert_eq!(std::fs::read_to_string(&new_log).unwrap().lines().count(), 1);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -35,7 +35,6 @@ pub(crate) struct ProviderSpec {
|
||||
pub name: String,
|
||||
pub driver: Driver,
|
||||
pub command: String,
|
||||
pub managed_cli: Option<String>,
|
||||
pub args: Vec<String>,
|
||||
/// Number of trailing arguments added by the built-in agent's settings.
|
||||
pub additional_args_len: usize,
|
||||
@@ -43,8 +42,6 @@ pub(crate) struct ProviderSpec {
|
||||
/// How to sign in when the agent reports it needs authentication.
|
||||
pub login_hint: String,
|
||||
pub source: AgentSource,
|
||||
/// The built-in agent an instance copies (its identity); `None` for every other agent.
|
||||
pub base: Option<String>,
|
||||
}
|
||||
|
||||
/// `(id, name, driver, command line, sign-in hint)`. npm adapters are pinned so a
|
||||
@@ -93,7 +90,6 @@ const BUILTIN: &[(&str, &str, Driver, &[&str], &str)] = &[
|
||||
("vibe", "Mistral Vibe", Driver::Acp, &["vibe-acp"], "Run `vibe` in a terminal and sign in."),
|
||||
("omp", "OMP", Driver::Acp, &["omp", "acp"], "Run `omp` in a terminal and sign in."),
|
||||
("hermes", "Hermes Agent", Driver::Acp, &["hermes", "acp"], "Run `hermes model` in a terminal."),
|
||||
("antigravity-acp", "Google Antigravity", Driver::Acp, &["agy", "acp"], "Run `agy acp --login` in a terminal."),
|
||||
];
|
||||
|
||||
fn builtins() -> Vec<ProviderSpec> {
|
||||
@@ -104,33 +100,22 @@ fn builtins() -> Vec<ProviderSpec> {
|
||||
name: (*name).into(),
|
||||
driver: *driver,
|
||||
command: cmd[0].into(),
|
||||
managed_cli: None,
|
||||
args: cmd[1..].iter().map(|a| (*a).to_owned()).collect(),
|
||||
additional_args_len: 0,
|
||||
env: Vec::new(),
|
||||
login_hint: (*hint).into(),
|
||||
source: AgentSource::Builtin,
|
||||
base: None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
impl ProviderSpec {
|
||||
/// The built-in id this agent is an instance of, or else its own id.
|
||||
pub(crate) fn base_id(&self) -> &str {
|
||||
self.base.as_deref().unwrap_or(&self.id)
|
||||
}
|
||||
|
||||
pub(crate) fn executable(&self) -> &str {
|
||||
self.managed_cli.as_deref().unwrap_or(&self.command)
|
||||
}
|
||||
|
||||
pub(crate) fn login_hint(&self, program: &Path) -> String {
|
||||
if !program.is_absolute() {
|
||||
return self.login_hint.clone();
|
||||
}
|
||||
let search = ide_core::tool_path::search_path();
|
||||
let builtin = builtin_spec(self.base_id());
|
||||
let search = ide_core::process::host_var_os("PATH").unwrap_or_default();
|
||||
let builtin = builtin_spec(&self.id);
|
||||
let on_path = builtin.as_ref().and_then(|b| ide_core::process::find_executable(&b.command, &search));
|
||||
render_login_hint(self, program, on_path.as_deref(), cfg!(windows))
|
||||
}
|
||||
@@ -150,7 +135,7 @@ impl ProviderSpec {
|
||||
.flatten();
|
||||
let hint = match terminal_args {
|
||||
Some(args) => {
|
||||
let command = render_shell_command(program, args, cfg!(windows));
|
||||
let command = render_login_command(program, args, cfg!(windows));
|
||||
format!("Run `{command}` in a terminal.")
|
||||
}
|
||||
None => self.login_hint(program),
|
||||
@@ -169,7 +154,7 @@ impl ProviderSpec {
|
||||
cwd: &Path,
|
||||
strip_ambient_tokens: bool,
|
||||
) -> Result<Self, String> {
|
||||
let is_copilot = is_copilot_provider(self.base_id());
|
||||
let is_copilot = is_copilot_provider(&self.id);
|
||||
let account = is_copilot.then(|| copilot_github_account(&self.env)).flatten();
|
||||
let explicit_copilot_token =
|
||||
self.env.iter().any(|(name, value)| name == "COPILOT_GITHUB_TOKEN" && !value.is_empty());
|
||||
@@ -194,12 +179,10 @@ impl ProviderSpec {
|
||||
}
|
||||
|
||||
fn resolve_for_launch_base(mut self, cwd: &Path, strip_ambient_tokens: bool) -> Self {
|
||||
if let Some(program) = self.managed_cli.take() {
|
||||
self.command = program;
|
||||
} else if self.driver != Driver::Acp {
|
||||
if self.driver != Driver::Acp {
|
||||
self.command = crate::native::newest_install(&self.command);
|
||||
}
|
||||
if is_copilot_provider(self.base_id()) {
|
||||
if is_copilot_provider(&self.id) {
|
||||
self.env = sanitized_copilot_env(&self.env, cwd, strip_ambient_tokens);
|
||||
self.env.retain(|(name, _)| name != COPILOT_GITHUB_ACCOUNT_ENV);
|
||||
}
|
||||
@@ -225,7 +208,7 @@ impl ProviderSpec {
|
||||
ide_core::tool_path::find_command(&candidate.to_string_lossy(), &search, cwd)
|
||||
};
|
||||
|
||||
if let Some((separate_cmd, separate_args)) = match self.base_id() {
|
||||
if let Some((separate_cmd, separate_args)) = match self.id.as_str() {
|
||||
"claude-acp" => Some(("claude", &[][..])),
|
||||
"codex-acp" => Some(("codex", &["login"][..])),
|
||||
"vibe" => Some(("vibe", &[][..])),
|
||||
@@ -239,9 +222,7 @@ impl ProviderSpec {
|
||||
});
|
||||
}
|
||||
|
||||
if let Some(builtin) = builtin_spec(self.base_id())
|
||||
&& !(matches!(self.source, AgentSource::Registry { .. }) && registry_uses_separate_binary(&self.id))
|
||||
{
|
||||
if let Some(builtin) = builtin_spec(&self.id) {
|
||||
let args = terminal_auth_args
|
||||
.filter(|_| matches!(self.source, AgentSource::Registry { .. }))
|
||||
.map(<[String]>::to_vec)
|
||||
@@ -249,7 +230,7 @@ impl ProviderSpec {
|
||||
let resolved = self.clone().resolve_for_launch_base(cwd, true);
|
||||
let program = resolve_exe(&resolved.command, &resolved.env)?;
|
||||
let mut env: BTreeMap<String, String> = resolved.env.into_iter().collect();
|
||||
if is_copilot_provider(self.base_id()) {
|
||||
if is_copilot_provider(&self.id) {
|
||||
for key in AMBIENT_COPILOT_AUTH_VARS {
|
||||
env.insert(key.to_owned(), String::new());
|
||||
}
|
||||
@@ -540,7 +521,7 @@ pub(crate) fn sanitize_copilot_env_with(
|
||||
}
|
||||
|
||||
fn render_login_hint(spec: &ProviderSpec, program: &Path, on_path: Option<&Path>, windows: bool) -> String {
|
||||
let Some(builtin) = builtin_spec(spec.base_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 Some(rest) = spec.login_hint.strip_prefix(&prefix).filter(|rest| rest.starts_with([' ', '`'])) else {
|
||||
return spec.login_hint.clone();
|
||||
@@ -552,7 +533,7 @@ fn render_login_hint(spec: &ProviderSpec, program: &Path, on_path: Option<&Path>
|
||||
return spec.login_hint.clone();
|
||||
}
|
||||
let (args, suffix) = rest.split_once('`').expect("built-in login hints delimit their command");
|
||||
let command = render_shell_command(program, args.split_whitespace(), windows);
|
||||
let command = render_login_command(program, args.split_whitespace(), windows);
|
||||
match suffix {
|
||||
" in a terminal." => format!("Run `{command}` in a terminal."),
|
||||
" in a terminal and sign in." => format!("Run `{command}` in a terminal and sign in."),
|
||||
@@ -560,11 +541,7 @@ fn render_login_hint(spec: &ProviderSpec, program: &Path, on_path: Option<&Path>
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn render_shell_command<'a>(
|
||||
program: &Path,
|
||||
args: impl IntoIterator<Item = &'a str>,
|
||||
windows: bool,
|
||||
) -> String {
|
||||
fn render_login_command<'a>(program: &Path, args: impl IntoIterator<Item = &'a str>, windows: bool) -> String {
|
||||
let quote = |word: &str| {
|
||||
if windows { format!("'{}'", word.replace('\'', "''")) } else { format!("'{}'", word.replace('\'', "'\\''")) }
|
||||
};
|
||||
@@ -608,13 +585,6 @@ pub(crate) fn is_unlisted(spec: &ProviderSpec) -> bool {
|
||||
UNLISTED.contains(&spec.id.as_str()) && builtin_spec(&spec.id).as_ref() == Some(spec)
|
||||
}
|
||||
|
||||
/// Built-in CLI agents whose ACP Registry archive ships a separate ACP server binary
|
||||
/// rather than the CLI itself, so the built-in CLI's login subcommand does not apply
|
||||
/// to a registry install.
|
||||
fn registry_uses_separate_binary(id: &str) -> bool {
|
||||
id == "antigravity-acp"
|
||||
}
|
||||
|
||||
fn uses_package_runner(command: &str) -> bool {
|
||||
matches!(command, "npx" | "bunx" | "uvx")
|
||||
}
|
||||
@@ -628,8 +598,6 @@ pub(crate) fn describe(spec: &ProviderSpec) -> AgentProvider {
|
||||
let builtin = builtin_spec(&spec.id);
|
||||
let reason = if matches!(spec.source, AgentSource::Registry { .. }) {
|
||||
Some(AgentCommandReadOnlyReason::Registry)
|
||||
} else if spec.base.is_some() {
|
||||
Some(AgentCommandReadOnlyReason::CustomAgent)
|
||||
} else if let Some(default) = &builtin {
|
||||
uses_package_runner(&default.command).then_some(AgentCommandReadOnlyReason::PackageRunner)
|
||||
} else {
|
||||
@@ -642,25 +610,22 @@ pub(crate) fn describe(spec: &ProviderSpec) -> AgentProvider {
|
||||
AgentProvider {
|
||||
id: spec.id.clone(),
|
||||
name: spec.name.clone(),
|
||||
command: std::iter::once(spec.executable())
|
||||
command: std::iter::once(spec.command.as_str())
|
||||
.chain(spec.args.iter().map(String::as_str))
|
||||
.collect::<Vec<_>>()
|
||||
.join(" "),
|
||||
program: spec.executable().to_owned(),
|
||||
program: spec.command.clone(),
|
||||
args: spec.args.clone(),
|
||||
additional_args,
|
||||
default_program: builtin.as_ref().map(|b| b.command.clone()),
|
||||
default_args: builtin.as_ref().map(|b| b.args.clone()).unwrap_or_default(),
|
||||
login_hint: Some(spec.login_hint(&ide_jsonrpc::resolve_spawn_program(spec.executable(), &spec.env))),
|
||||
login_hint: Some(spec.login_hint(&ide_jsonrpc::resolve_spawn_program(&spec.command, &spec.env))),
|
||||
command_overridden: builtin.as_ref().is_some_and(|b| b.command != spec.command),
|
||||
command_editable: reason.is_none(),
|
||||
command_read_only_reason: reason,
|
||||
installed: installed_with_env(spec.executable(), &spec.env),
|
||||
cli_install_command: None,
|
||||
installed: installed(&spec.command),
|
||||
can_sign_in: spec.can_sign_in(Path::new("."), None),
|
||||
can_check_cli_update: spec.source == AgentSource::Builtin && crate::cli_update::package(&spec.id).is_some(),
|
||||
base: spec.base.clone(),
|
||||
can_duplicate: builtin.is_some(),
|
||||
env: spec.env.iter().cloned().collect(),
|
||||
config: vec![],
|
||||
thought_levels: BTreeMap::new(),
|
||||
@@ -699,17 +664,13 @@ pub(crate) fn set_builtin_additional_args(
|
||||
})
|
||||
}
|
||||
|
||||
/// The environment built-in `id` (or an instance of one) starts with, through its agent file
|
||||
/// (empty clears it).
|
||||
/// The environment built-in `id` starts with, through its agent file (empty clears it).
|
||||
pub(crate) fn set_builtin_env(
|
||||
custom_dir: &Path,
|
||||
secrets: Option<&dyn EnvSecrets>,
|
||||
id: &str,
|
||||
env: BTreeMap<String, String>,
|
||||
) -> IdeResult<()> {
|
||||
if builtin_spec(id).is_none() {
|
||||
return set_instance_env(custom_dir, secrets, id, env);
|
||||
}
|
||||
if id == "copilot" {
|
||||
let file = custom_dir.join("copilot.toml");
|
||||
if file.try_exists()?
|
||||
@@ -741,26 +702,6 @@ pub(crate) fn set_builtin_env(
|
||||
})
|
||||
}
|
||||
|
||||
/// An instance's environment is all its own: never merged with its base's.
|
||||
fn set_instance_env(
|
||||
custom_dir: &Path,
|
||||
secrets: Option<&dyn EnvSecrets>,
|
||||
id: &str,
|
||||
env: BTreeMap<String, String>,
|
||||
) -> IdeResult<()> {
|
||||
let id = validated_custom_id(id)?;
|
||||
let _lock = lock_custom_agents(custom_dir)?;
|
||||
let file = custom_dir.join(format!("{id}.toml"));
|
||||
let mut agent = match CustomAgent::read_with(&file, &id, secrets) {
|
||||
Ok(agent) if agent.registry.is_none() && agent.base.as_deref().is_some_and(|b| builtin_spec(b).is_some()) => {
|
||||
agent
|
||||
}
|
||||
_ => return Err(IdeError::invalid(format!("{id} is not a built-in agent or an instance of one"))),
|
||||
};
|
||||
agent.env = env;
|
||||
agent.write_with(&file, &id, secrets)
|
||||
}
|
||||
|
||||
/// Changes built-in `id`'s agent file; a file left with only the built-in's values is removed.
|
||||
fn update_builtin(
|
||||
custom_dir: &Path,
|
||||
@@ -777,7 +718,6 @@ fn update_builtin(
|
||||
} else {
|
||||
CustomAgent {
|
||||
name: Some(builtin.name.clone()),
|
||||
base: None,
|
||||
driver: builtin.driver,
|
||||
command: builtin.command.clone(),
|
||||
args: builtin.args.clone(),
|
||||
@@ -807,24 +747,9 @@ fn update_builtin(
|
||||
agent.write_with(&file, id, secrets)
|
||||
}
|
||||
|
||||
/// Project backends can share a config directory. Keep the ID check, credential
|
||||
/// changes and file write in the same critical section.
|
||||
fn lock_custom_agents(custom_dir: &Path) -> std::io::Result<std::fs::File> {
|
||||
std::fs::create_dir_all(custom_dir)?;
|
||||
let lock = std::fs::OpenOptions::new()
|
||||
.read(true)
|
||||
.write(true)
|
||||
.create(true)
|
||||
.truncate(false)
|
||||
.open(custom_dir.join(".custom-agents.lock"))?;
|
||||
lock.lock()?;
|
||||
Ok(lock)
|
||||
}
|
||||
|
||||
/// Saves a new custom agent; refuses built-in and ACP Registry ids, taken ids
|
||||
/// and an empty command. The id is also the agent file's name, so it must be
|
||||
/// a safe file stem. An instance of a built-in (`base`) may leave the command
|
||||
/// empty to launch as its base does.
|
||||
/// a safe file stem.
|
||||
pub(crate) fn save_custom(
|
||||
custom_dir: &Path,
|
||||
secrets: Option<&dyn EnvSecrets>,
|
||||
@@ -834,20 +759,9 @@ pub(crate) fn save_custom(
|
||||
if builtin_spec(&id).is_some() {
|
||||
return Err(IdeError::invalid(format!("{id} is a built-in agent; change its command instead")));
|
||||
}
|
||||
let base = match input.base.as_deref() {
|
||||
Some(base) => {
|
||||
Some(builtin_spec(base).ok_or_else(|| IdeError::invalid(format!("{base} is not a built-in agent")))?)
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
let inherits = input.command.trim().is_empty();
|
||||
if inherits && base.is_none() {
|
||||
if input.command.trim().is_empty() {
|
||||
return Err(IdeError::invalid("the agent command must not be empty"));
|
||||
}
|
||||
if inherits && !input.args.is_empty() {
|
||||
return Err(IdeError::invalid("an agent without its own command takes no arguments"));
|
||||
}
|
||||
let _lock = lock_custom_agents(custom_dir)?;
|
||||
let file = custom_dir.join(format!("{id}.toml"));
|
||||
if file.try_exists()? {
|
||||
if CustomAgent::read(&file).is_ok_and(|a| a.registry.is_some()) {
|
||||
@@ -859,9 +773,8 @@ pub(crate) fn save_custom(
|
||||
}
|
||||
CustomAgent {
|
||||
name: Some(input.name.clone()),
|
||||
driver: base.as_ref().filter(|_| !inherits).map_or(Driver::Acp, |b| b.driver),
|
||||
command: if inherits { String::new() } else { input.command.clone() },
|
||||
base: base.map(|b| b.id),
|
||||
driver: Driver::Acp,
|
||||
command: input.command.clone(),
|
||||
args: input.args.clone(),
|
||||
additional_args: Vec::new(),
|
||||
env: input.env.clone(),
|
||||
@@ -877,7 +790,6 @@ pub(crate) fn remove_custom(custom_dir: &Path, secrets: Option<&dyn EnvSecrets>,
|
||||
if builtin_spec(id).is_some() {
|
||||
return Err(IdeError::invalid(format!("{id} is a built-in agent and cannot be removed")));
|
||||
}
|
||||
let _lock = lock_custom_agents(custom_dir)?;
|
||||
let file = custom_dir.join(format!("{id}.toml"));
|
||||
let agent =
|
||||
CustomAgent::read(&file).map_err(|_| IdeError::not_found(format!("there is no custom agent '{id}'")))?;
|
||||
@@ -917,7 +829,6 @@ pub(crate) fn import_acp(
|
||||
}
|
||||
let parsed: AcpJson =
|
||||
serde_json::from_str(text).map_err(|e| IdeError::invalid(format!("not an acp.json file: {e}")))?;
|
||||
let _lock = lock_custom_agents(custom_dir)?;
|
||||
let mut outcomes = Vec::with_capacity(parsed.agent_servers.len());
|
||||
for (name, server) in parsed.agent_servers {
|
||||
let id = slugify_id(&name);
|
||||
@@ -933,7 +844,6 @@ pub(crate) fn import_acp(
|
||||
} else {
|
||||
CustomAgent {
|
||||
name: Some(outcome.name.clone()),
|
||||
base: None,
|
||||
driver: Driver::Acp,
|
||||
command: server.command,
|
||||
args: server.args,
|
||||
@@ -976,12 +886,8 @@ pub(crate) fn slugify_id(name: &str) -> String {
|
||||
pub(crate) struct CustomAgent {
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub name: Option<String>,
|
||||
/// The built-in agent this one is an instance of; without a `command` it launches as the base does.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub base: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Driver::is_acp")]
|
||||
pub driver: Driver,
|
||||
#[serde(default, skip_serializing_if = "String::is_empty")]
|
||||
pub command: String,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub args: Vec<String>,
|
||||
@@ -1010,13 +916,9 @@ impl Driver {
|
||||
|
||||
impl CustomAgent {
|
||||
pub(crate) fn read(path: &Path) -> Result<Self, String> {
|
||||
let agent = std::fs::read_to_string(path)
|
||||
std::fs::read_to_string(path)
|
||||
.map_err(|e| e.to_string())
|
||||
.and_then(|t| toml::from_str::<CustomAgent>(&t).map_err(|e| e.to_string()))?;
|
||||
if agent.command.is_empty() && agent.base.is_none() {
|
||||
return Err("missing field `command`".into());
|
||||
}
|
||||
Ok(agent)
|
||||
.and_then(|t| toml::from_str::<CustomAgent>(&t).map_err(|e| e.to_string()))
|
||||
}
|
||||
|
||||
/// Writes the file atomically (a reader never sees half of it).
|
||||
@@ -1088,8 +990,7 @@ fn forget_env(secrets: Option<&dyn EnvSecrets>, id: &str, keep: &[String]) {
|
||||
}
|
||||
|
||||
/// Built-in agents, then the `*.toml` agents of `custom_dir`; a custom agent with a
|
||||
/// built-in id replaces it. Instances of a built-in (`base`) are resolved last, against
|
||||
/// the built-in as its own file left it, so file order does not matter.
|
||||
/// built-in id replaces it.
|
||||
pub(crate) fn load(custom_dir: Option<&Path>, secrets: Option<&dyn EnvSecrets>) -> Vec<ProviderSpec> {
|
||||
let mut specs = builtins();
|
||||
let mut files: Vec<PathBuf> = custom_dir
|
||||
@@ -1101,7 +1002,6 @@ pub(crate) fn load(custom_dir: Option<&Path>, secrets: Option<&dyn EnvSecrets>)
|
||||
.filter(|p| p.extension().is_some_and(|e| e == "toml"))
|
||||
.collect();
|
||||
files.sort();
|
||||
let mut instances = Vec::new();
|
||||
for path in files {
|
||||
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)
|
||||
@@ -1115,18 +1015,6 @@ pub(crate) fn load(custom_dir: Option<&Path>, secrets: Option<&dyn EnvSecrets>)
|
||||
continue;
|
||||
}
|
||||
};
|
||||
if let Some(base) = agent.base.clone() {
|
||||
if builtin_spec(&id).is_some() {
|
||||
tracing::warn!("skipping agent {}: a built-in agent cannot have a base", path.display());
|
||||
} else if agent.registry.is_some() {
|
||||
tracing::warn!("skipping agent {}: an ACP Registry install cannot have a base", path.display());
|
||||
} else if builtin_spec(&base).is_none() {
|
||||
tracing::warn!("skipping agent {}: {base} is not a built-in agent", path.display());
|
||||
} else {
|
||||
instances.push((id, agent));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let env: Vec<(String, String)> = agent.env.into_iter().collect();
|
||||
let source = match agent.registry {
|
||||
Some(r) => AgentSource::Registry { version: r.version, update: None },
|
||||
@@ -1136,20 +1024,16 @@ pub(crate) fn load(custom_dir: Option<&Path>, secrets: Option<&dyn EnvSecrets>)
|
||||
name: agent.name.unwrap_or_else(|| id.clone()),
|
||||
driver: agent.driver,
|
||||
command: agent.command,
|
||||
managed_cli: None,
|
||||
args: agent.args,
|
||||
additional_args_len: 0,
|
||||
env,
|
||||
login_hint: "Sign in with the agent's own command line first.".into(),
|
||||
source,
|
||||
base: None,
|
||||
id,
|
||||
};
|
||||
match specs.iter_mut().find(|s| s.id == spec.id) {
|
||||
Some(existing) => {
|
||||
if !(matches!(spec.source, AgentSource::Registry { .. }) && registry_uses_separate_binary(&spec.id)) {
|
||||
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
|
||||
@@ -1170,54 +1054,22 @@ pub(crate) fn load(custom_dir: Option<&Path>, secrets: Option<&dyn EnvSecrets>)
|
||||
None => specs.push(spec),
|
||||
}
|
||||
}
|
||||
for (id, agent) in instances {
|
||||
let base = agent.base.expect("instances have a base");
|
||||
let Some(base_spec) = specs.iter().find(|s| s.id == base && s.base.is_none()) else { continue };
|
||||
let (driver, command, args) = if agent.command.is_empty() {
|
||||
(base_spec.driver, base_spec.command.clone(), base_spec.args.clone())
|
||||
} else {
|
||||
(agent.driver, agent.command, agent.args)
|
||||
};
|
||||
let login_hint = base_spec.login_hint.clone();
|
||||
// Copies of one agent follow it, in the order of their file names.
|
||||
let at = specs.iter().rposition(|s| s.base_id() == base).map_or(specs.len(), |i| i + 1);
|
||||
specs.insert(
|
||||
at,
|
||||
ProviderSpec {
|
||||
name: agent.name.unwrap_or_else(|| id.clone()),
|
||||
driver,
|
||||
command,
|
||||
managed_cli: None,
|
||||
args,
|
||||
additional_args_len: 0,
|
||||
env: agent.env.into_iter().collect(),
|
||||
login_hint,
|
||||
source: AgentSource::Custom,
|
||||
base: Some(base),
|
||||
id,
|
||||
},
|
||||
);
|
||||
}
|
||||
specs
|
||||
}
|
||||
|
||||
/// Whether `command` resolves to an executable (a path, or a name on [`ide_core::tool_path::search_path`]).
|
||||
#[cfg(test)]
|
||||
/// Whether `command` resolves to an executable (a path, or a name on `PATH`).
|
||||
pub(crate) fn installed(command: &str) -> bool {
|
||||
installed_with_env(command, &[])
|
||||
}
|
||||
|
||||
pub(crate) fn installed_with_env(command: &str, env: &[(String, String)]) -> bool {
|
||||
let p = Path::new(command);
|
||||
if p.components().count() > 1 || p.is_absolute() {
|
||||
if p.components().count() > 1 {
|
||||
return is_executable(p);
|
||||
}
|
||||
if let Some((_, path)) = env.iter().find(|(k, _)| k.eq_ignore_ascii_case("PATH"))
|
||||
&& ide_core::process::find_executable(command, std::ffi::OsStr::new(path)).is_some()
|
||||
{
|
||||
return true;
|
||||
}
|
||||
ide_core::process::find_executable(command, &ide_core::tool_path::search_path()).is_some()
|
||||
let exts: &[&str] = if cfg!(windows) { &["exe", "cmd", "bat"] } else { &[] };
|
||||
std::env::var_os("PATH").is_some_and(|path| {
|
||||
std::env::split_paths(&path).any(|dir| {
|
||||
let c = dir.join(command);
|
||||
is_executable(&c) || exts.iter().any(|e| is_executable(&c.with_extension(e)))
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
fn is_executable(p: &Path) -> bool {
|
||||
@@ -1246,56 +1098,6 @@ mod tests {
|
||||
assert_eq!(info.login_hint.as_deref(), Some("Run `hermes model` in a terminal."));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn antigravity_is_built_in_over_acp() {
|
||||
let spec = builtin_spec("antigravity-acp").unwrap();
|
||||
assert_eq!(spec.driver, Driver::Acp);
|
||||
assert!(!is_builtin("antigravity-acp"));
|
||||
let info = describe(&spec);
|
||||
assert_eq!((info.name.as_str(), info.command.as_str()), ("Google Antigravity", "agy acp"));
|
||||
assert_eq!(info.login_hint.as_deref(), Some("Run `agy acp --login` in a terminal."));
|
||||
assert!(info.command_editable);
|
||||
assert_eq!(info.additional_args, Some(vec![]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn registry_antigravity_does_not_inherit_cli_login_subcommand() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let bin = dir.path().join(if cfg!(windows) { "agy_acp_server.exe" } else { "agy_acp_server.par" });
|
||||
std::fs::write(&bin, "#!/bin/sh\n").unwrap();
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::set_permissions(&bin, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
}
|
||||
CustomAgent {
|
||||
name: Some("Google Antigravity".into()),
|
||||
base: None,
|
||||
driver: Driver::Acp,
|
||||
command: bin.to_string_lossy().into_owned(),
|
||||
args: Vec::new(),
|
||||
additional_args: Vec::new(),
|
||||
env: BTreeMap::new(),
|
||||
registry: Some(RegistryRef { id: "antigravity-acp".into(), version: "1.5.2".into() }),
|
||||
}
|
||||
.write(&dir.path().join("antigravity-acp.toml"))
|
||||
.unwrap();
|
||||
|
||||
let reg = load(Some(dir.path()), None).into_iter().find(|s| s.id == "antigravity-acp").unwrap();
|
||||
assert_eq!(reg.source, AgentSource::Registry { version: "1.5.2".into(), update: None });
|
||||
assert_eq!(reg.login_hint, "Sign in with the agent's own command line first.");
|
||||
assert_eq!(describe(®).login_hint.as_deref(), Some("Sign in with the agent's own command line first."));
|
||||
assert!(reg.login_launch(dir.path(), None).is_none());
|
||||
let terminal_launch = reg.login_launch(dir.path(), Some(&["--login".into()])).unwrap();
|
||||
assert_eq!(terminal_launch.program, bin);
|
||||
assert_eq!(terminal_launch.args, ["--login"]);
|
||||
|
||||
std::fs::remove_file(dir.path().join("antigravity-acp.toml")).unwrap();
|
||||
let builtin = load(Some(dir.path()), None).into_iter().find(|s| s.id == "antigravity-acp").unwrap();
|
||||
assert_eq!(builtin.source, AgentSource::Builtin);
|
||||
assert_eq!((builtin.command.as_str(), builtin.args.as_slice()), ("agy", &["acp".to_owned()][..]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qoder_global_and_cn_editions_are_both_built_in() {
|
||||
let info = |id: &str| describe(&load(None, None).into_iter().find(|s| s.id == id).unwrap());
|
||||
@@ -1348,7 +1150,6 @@ mod tests {
|
||||
assert_eq!(args("copilot"), ["login"]);
|
||||
assert_eq!(args("goose"), ["configure"]);
|
||||
assert_eq!(args("hermes"), ["model"]);
|
||||
assert_eq!(args("antigravity-acp"), ["acp", "--login"]);
|
||||
assert!(args("qwen").is_empty());
|
||||
}
|
||||
|
||||
@@ -1423,7 +1224,7 @@ mod tests {
|
||||
(true, "& '/agent''s tools/$cli' auth login --account 'user name' 'a''b' '$token' ''"),
|
||||
] {
|
||||
assert_eq!(
|
||||
render_shell_command(
|
||||
render_login_command(
|
||||
Path::new("/agent's tools/$cli"),
|
||||
["auth", "login", "--account", "user name", "a'b", "$token", ""],
|
||||
windows
|
||||
@@ -1475,10 +1276,10 @@ mod tests {
|
||||
for p in &defaults {
|
||||
assert_eq!(p.source, AgentSource::Builtin);
|
||||
assert!(p.default_program.is_some());
|
||||
assert_eq!(p.command_editable, !uses_package_runner(&p.program));
|
||||
assert_eq!(p.command_editable, !p.id.ends_with("-acp"));
|
||||
assert_eq!(
|
||||
p.command_read_only_reason,
|
||||
uses_package_runner(&p.program).then_some(AgentCommandReadOnlyReason::PackageRunner)
|
||||
p.id.ends_with("-acp").then_some(AgentCommandReadOnlyReason::PackageRunner)
|
||||
);
|
||||
}
|
||||
set_builtin_command(dir.path(), None, "codex", Some("/path with spaces/codex")).unwrap();
|
||||
@@ -1525,22 +1326,6 @@ mod tests {
|
||||
assert!(installed("sh"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn installed_with_env_resolves_executables_on_provider_path() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let name = if cfg!(windows) { "fake-agent.cmd" } else { "fake-agent" };
|
||||
let exe = dir.path().join(name);
|
||||
std::fs::write(&exe, "").unwrap();
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::set_permissions(&exe, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
}
|
||||
assert!(!installed("fake-agent"));
|
||||
let env = vec![("PATH".to_owned(), dir.path().to_string_lossy().into_owned())];
|
||||
assert!(installed_with_env("fake-agent", &env));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_builtin_env_writes_and_clears_the_environment() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
@@ -1611,7 +1396,6 @@ mod tests {
|
||||
let file = dir.path().join("copilot.toml");
|
||||
CustomAgent {
|
||||
name: Some("GitHub Copilot".into()),
|
||||
base: None,
|
||||
driver: Driver::Acp,
|
||||
command: "/tools/copilot".into(),
|
||||
args: vec!["--acp".into()],
|
||||
@@ -1669,7 +1453,6 @@ mod tests {
|
||||
let path = dir.path().join("codex.toml");
|
||||
CustomAgent {
|
||||
name: None,
|
||||
base: None,
|
||||
driver: Driver::Acp,
|
||||
command: "amp".into(),
|
||||
args: vec![],
|
||||
@@ -1696,7 +1479,6 @@ mod tests {
|
||||
for field in ["name", "driver", "args", "env", "unnamed"] {
|
||||
let mut agent = CustomAgent {
|
||||
name: Some("Claude Code".into()),
|
||||
base: None,
|
||||
driver: Driver::Claude,
|
||||
command: "/old/claude".into(),
|
||||
args: vec![],
|
||||
@@ -1751,7 +1533,6 @@ mod tests {
|
||||
let path = dir.path().join("agents").join("amp-acp.toml");
|
||||
let agent = CustomAgent {
|
||||
name: Some("Amp".into()),
|
||||
base: None,
|
||||
driver: Driver::Acp,
|
||||
command: "/data/agents/tools/amp-acp/0.10.0/amp-acp".into(),
|
||||
args: vec!["acp".into()],
|
||||
@@ -1772,7 +1553,6 @@ mod tests {
|
||||
CustomAgentInput {
|
||||
id: id.into(),
|
||||
name: "Mine".into(),
|
||||
base: None,
|
||||
command: "/opt/mine".into(),
|
||||
args: vec!["acp".into()],
|
||||
env: BTreeMap::from([("K".to_owned(), "v".to_owned())]),
|
||||
@@ -1994,188 +1774,4 @@ github.com
|
||||
assert_eq!(launch.env.get("GH_TOKEN").map(String::as_str), Some(""));
|
||||
assert_eq!(launch.env.get("COPILOT_GITHUB_TOKEN").map(String::as_str), Some(""));
|
||||
}
|
||||
|
||||
fn write_agent(dir: &Path, id: &str, text: &str) {
|
||||
std::fs::write(dir.join(format!("{id}.toml")), text).unwrap();
|
||||
}
|
||||
|
||||
fn spec_of(dir: &Path, id: &str) -> Option<ProviderSpec> {
|
||||
load(Some(dir), None).into_iter().find(|s| s.id == id)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn instances_inherit_the_base_launch_whatever_the_file_order() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let instance =
|
||||
"base = \"claude\"\nname = \"Claude Work\"\n[env]\nCLAUDE_CONFIG_DIR = \"/home/me/.claude-work\"\n";
|
||||
// `a-claude` sorts before the base's own file, `z-claude` after it.
|
||||
write_agent(dir.path(), "a-claude", instance);
|
||||
write_agent(dir.path(), "z-claude", instance);
|
||||
write_agent(
|
||||
dir.path(),
|
||||
"claude",
|
||||
"name = \"Claude Code\"\ndriver = \"claude\"\ncommand = \"/opt/claude\"\n[env]\nB = \"1\"\n",
|
||||
);
|
||||
let builtin = builtin_spec("claude").unwrap();
|
||||
for id in ["a-claude", "z-claude"] {
|
||||
let spec = spec_of(dir.path(), id).unwrap();
|
||||
assert_eq!((spec.driver, spec.command.as_str()), (Driver::Claude, "/opt/claude"), "{id}");
|
||||
assert_eq!(spec.args, builtin.args);
|
||||
assert_eq!(spec.env, [("CLAUDE_CONFIG_DIR".to_owned(), "/home/me/.claude-work".to_owned())]);
|
||||
assert_eq!(spec.login_hint, builtin.login_hint);
|
||||
assert_eq!(
|
||||
(&spec.source, spec.base.as_deref(), spec.base_id()),
|
||||
(&AgentSource::Custom, Some("claude"), "claude")
|
||||
);
|
||||
assert_eq!(spec.name, "Claude Work");
|
||||
}
|
||||
std::fs::remove_file(dir.path().join("claude.toml")).unwrap();
|
||||
assert_eq!(spec_of(dir.path(), "a-claude").unwrap().command, "claude");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn instances_follow_their_base_in_the_list() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
write_agent(dir.path(), "z-claude", "base = \"claude\"\n");
|
||||
write_agent(dir.path(), "a-claude", "base = \"claude\"\n");
|
||||
write_agent(dir.path(), "codex-2", "base = \"codex\"\n");
|
||||
write_agent(dir.path(), "mine", "command = \"/opt/mine\"\n");
|
||||
let ids: Vec<String> = load(Some(dir.path()), None).into_iter().map(|s| s.id).collect();
|
||||
let at = |id: &str| ids.iter().position(|i| i == id).unwrap();
|
||||
assert_eq!((at("a-claude"), at("z-claude")), (at("claude") + 1, at("claude") + 2));
|
||||
assert_eq!(at("codex-2"), at("codex") + 1);
|
||||
assert_eq!(at("mine"), ids.len() - 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_instance_with_its_own_command_keeps_it() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
write_agent(
|
||||
dir.path(),
|
||||
"codex-2",
|
||||
"base = \"codex\"\ndriver = \"codex\"\ncommand = \"/opt/codex2\"\nargs = [\"app-server\", \"-v\"]\n",
|
||||
);
|
||||
write_agent(dir.path(), "codex", "driver = \"codex\"\ncommand = \"/opt/codex\"\nargs = [\"app-server\"]\n");
|
||||
let spec = spec_of(dir.path(), "codex-2").unwrap();
|
||||
assert_eq!((spec.driver, spec.command.as_str()), (Driver::Codex, "/opt/codex2"));
|
||||
assert_eq!(spec.args, ["app-server", "-v"]);
|
||||
assert_eq!(spec.base.as_deref(), Some("codex"));
|
||||
assert_eq!(spec.login_hint, builtin_spec("codex").unwrap().login_hint);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_instances_are_skipped() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
write_agent(dir.path(), "unknown-base", "base = \"nope\"\n");
|
||||
write_agent(dir.path(), "first", "base = \"claude\"\n");
|
||||
write_agent(dir.path(), "chained", "base = \"first\"\n");
|
||||
write_agent(dir.path(), "codex", "base = \"claude\"\n");
|
||||
write_agent(dir.path(), "no-command", "name = \"Nothing\"\n");
|
||||
let specs = load(Some(dir.path()), None);
|
||||
let ids: Vec<&str> = specs.iter().filter(|s| s.source != AgentSource::Builtin).map(|s| s.id.as_str()).collect();
|
||||
assert_eq!(ids, ["first"]);
|
||||
assert_eq!(specs.iter().find(|s| s.id == "codex").unwrap(), &builtin_spec("codex").unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn save_custom_writes_instances() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let instance = |id: &str, base: &str| CustomAgentInput {
|
||||
base: Some(base.into()),
|
||||
command: String::new(),
|
||||
args: Vec::new(),
|
||||
..custom_input(id)
|
||||
};
|
||||
save_custom(dir.path(), None, &instance("work", "claude")).unwrap();
|
||||
let text = std::fs::read_to_string(dir.path().join("work.toml")).unwrap();
|
||||
assert!(text.contains("base = \"claude\"") && !text.contains("command") && !text.contains("driver"), "{text}");
|
||||
let spec = spec_of(dir.path(), "work").unwrap();
|
||||
assert_eq!(
|
||||
(spec.driver, spec.command.as_str(), spec.base.as_deref()),
|
||||
(Driver::Claude, "claude", Some("claude"))
|
||||
);
|
||||
|
||||
save_custom(dir.path(), None, &CustomAgentInput { command: "/opt/codex".into(), ..instance("own", "codex") })
|
||||
.unwrap();
|
||||
let own = spec_of(dir.path(), "own").unwrap();
|
||||
assert_eq!((own.driver, own.command.as_str()), (Driver::Codex, "/opt/codex"));
|
||||
|
||||
save_custom(dir.path(), None, &instance("work", "claude")).unwrap_err();
|
||||
save_custom(dir.path(), None, &instance("other", "nope")).unwrap_err();
|
||||
save_custom(dir.path(), None, &instance("other", "work")).unwrap_err();
|
||||
save_custom(dir.path(), None, &instance("codex", "claude")).unwrap_err();
|
||||
save_custom(dir.path(), None, &CustomAgentInput { args: vec!["x".into()], ..instance("other", "claude") })
|
||||
.unwrap_err();
|
||||
assert!(!dir.path().join("other.toml").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn instances_describe_their_base() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
write_agent(dir.path(), "work", "base = \"claude\"\n");
|
||||
save_custom(dir.path(), None, &custom_input("mine")).unwrap();
|
||||
let info = |id: &str| describe(&spec_of(dir.path(), id).unwrap());
|
||||
let work = info("work");
|
||||
assert_eq!(work.base.as_deref(), Some("claude"));
|
||||
assert!(!work.can_duplicate && !work.can_check_cli_update && !work.command_editable);
|
||||
assert_eq!(work.command_read_only_reason, Some(AgentCommandReadOnlyReason::CustomAgent));
|
||||
assert_eq!(work.login_hint.as_deref(), Some("Run `claude` in a terminal and sign in."));
|
||||
let claude = info("claude");
|
||||
assert!(claude.can_duplicate && claude.base.is_none());
|
||||
let mine = info("mine");
|
||||
assert!(!mine.can_duplicate && mine.base.is_none());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn instances_sign_in_with_their_own_environment() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let bin = dir.path().join("claude");
|
||||
std::fs::write(&bin, "#!/bin/sh\n").unwrap();
|
||||
std::fs::set_permissions(&bin, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
write_agent(dir.path(), "claude", &format!("driver = \"claude\"\ncommand = {:?}\n", bin.to_string_lossy()));
|
||||
write_agent(dir.path(), "work", "base = \"claude\"\n[env]\nCLAUDE_CONFIG_DIR = \"/home/me/.claude-work\"\n");
|
||||
let spec = spec_of(dir.path(), "work").unwrap();
|
||||
assert!(spec.can_sign_in(dir.path(), None));
|
||||
let launch = spec.login_launch(dir.path(), None).unwrap();
|
||||
assert_eq!(launch.program, bin);
|
||||
assert!(launch.args.is_empty());
|
||||
assert_eq!(launch.env.get("CLAUDE_CONFIG_DIR").map(String::as_str), Some("/home/me/.claude-work"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn instance_environment_is_set_and_forgotten_through_the_secrets() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let secrets = MemorySecrets::default();
|
||||
let s = Some(&secrets as &dyn EnvSecrets);
|
||||
let instance = CustomAgentInput {
|
||||
base: Some("copilot".into()),
|
||||
command: String::new(),
|
||||
args: Vec::new(),
|
||||
env: BTreeMap::new(),
|
||||
..custom_input("copilot-work")
|
||||
};
|
||||
save_custom(dir.path(), s, &instance).unwrap();
|
||||
let env = BTreeMap::from([
|
||||
(COPILOT_GITHUB_ACCOUNT_ENV.to_owned(), "octo-work".to_owned()),
|
||||
("COPILOT_HOME".to_owned(), "/home/me/.copilot-work".to_owned()),
|
||||
]);
|
||||
set_builtin_env(dir.path(), s, "copilot-work", env.clone()).unwrap();
|
||||
let text = std::fs::read_to_string(dir.path().join("copilot-work.toml")).unwrap();
|
||||
assert!(text.contains("base = \"copilot\"") && !text.contains("octo-work"), "{text}");
|
||||
let spec = load(Some(dir.path()), s).into_iter().find(|p| p.id == "copilot-work").unwrap();
|
||||
assert_eq!(describe(&spec).env, env);
|
||||
assert_eq!(copilot_github_account(&spec.env).as_deref(), Some("octo-work"));
|
||||
assert!(load(Some(dir.path()), s).iter().find(|p| p.id == "copilot").unwrap().env.is_empty());
|
||||
|
||||
save_custom(dir.path(), s, &custom_input("mine")).unwrap();
|
||||
set_builtin_env(dir.path(), s, "mine", env.clone()).unwrap_err();
|
||||
write_agent(dir.path(), "bad-base", "base = \"nope\"\n");
|
||||
set_builtin_env(dir.path(), s, "bad-base", env).unwrap_err();
|
||||
assert!(secrets.keys("agent/bad-base/").is_empty());
|
||||
remove_custom(dir.path(), s, "copilot-work").unwrap();
|
||||
assert!(!dir.path().join("copilot-work.toml").exists());
|
||||
assert!(secrets.keys("agent/copilot-work/").is_empty());
|
||||
}
|
||||
}
|
||||
@@ -320,7 +320,7 @@ fn is_builtin(id: &str) -> bool {
|
||||
}
|
||||
|
||||
fn on_path(command: &str) -> bool {
|
||||
ide_core::process::find_executable(command, &ide_core::tool_path::search_path()).is_some()
|
||||
which::which(command).is_ok()
|
||||
}
|
||||
|
||||
/// `1.10.0` > `1.9.2`; a release is newer than its pre-releases.
|
||||
@@ -587,7 +587,6 @@ fn install_entry_with(
|
||||
}
|
||||
let agent = CustomAgent {
|
||||
name: Some(entry.name.clone()),
|
||||
base: None,
|
||||
driver: Driver::Acp,
|
||||
command: exe.to_string_lossy().into_owned(),
|
||||
args,
|
||||
@@ -709,8 +708,7 @@ fn install_npm(
|
||||
emit: Emit,
|
||||
) -> IdeResult<PathBuf> {
|
||||
let (name, _) = split_npm_spec(&p.package);
|
||||
let npm = ide_core::process::find_executable("npm", &ide_core::tool_path::search_path())
|
||||
.ok_or_else(|| IdeError::unavailable(format!("npm is required to install {name}")))?;
|
||||
let npm = which::which("npm").map_err(|_| IdeError::unavailable(format!("npm is required to install {name}")))?;
|
||||
install_npm_with(&npm, p, entry, dir, platform, public_fallback, cancel, emit)
|
||||
}
|
||||
|
||||
@@ -791,8 +789,7 @@ fn install_uv(
|
||||
_ => format!("{name}=={}", entry.version),
|
||||
};
|
||||
check_spec(&spec)?;
|
||||
let uv = ide_core::process::find_executable("uv", &ide_core::tool_path::search_path())
|
||||
.ok_or_else(|| IdeError::unavailable(format!("uv is required to install {name}")))?;
|
||||
let uv = which::which("uv").map_err(|_| IdeError::unavailable(format!("uv is required to install {name}")))?;
|
||||
let bin = dir.join("bin");
|
||||
let mut cmd = Command::new(uv);
|
||||
cmd.args(["tool", "install", "--force"])
|
||||
@@ -986,7 +983,6 @@ mod tests {
|
||||
let entries = parse(INDEX).unwrap();
|
||||
let installed = |id: &str, version: &str| CustomAgent {
|
||||
name: None,
|
||||
base: None,
|
||||
driver: Driver::Acp,
|
||||
command: "/x".into(),
|
||||
args: vec![],
|
||||
@@ -1224,7 +1220,6 @@ esac
|
||||
|
||||
CustomAgent {
|
||||
name: Some("GitHub Copilot".into()),
|
||||
base: None,
|
||||
driver: Driver::Acp,
|
||||
command: "/data/tools/copilot/1.0.104/node_modules/.bin/copilot".into(),
|
||||
args: vec!["--acp".into()],
|
||||
|
||||
@@ -185,7 +185,22 @@ pub(crate) fn recorder(out: PathBuf) -> Connector {
|
||||
let file = Arc::new(Mutex::new(String::new()));
|
||||
let connections = Arc::new(Mutex::new(0u32));
|
||||
Arc::new(move |spec, cwd, client, on_stderr| {
|
||||
let program = ide_jsonrpc::resolve_spawn_program(&spec.command, &spec.env);
|
||||
let program = {
|
||||
let path = Path::new(&spec.command);
|
||||
if path.components().count() > 1 || path.is_absolute() {
|
||||
path.to_path_buf()
|
||||
} else {
|
||||
let search = spec
|
||||
.env
|
||||
.iter()
|
||||
.find(|(k, _)| k.eq_ignore_ascii_case("PATH"))
|
||||
.map(|(_, v)| std::ffi::OsString::from(v))
|
||||
.or_else(|| ide_core::process::shell_env().find(|(k, _)| k == "PATH").map(|(_, v)| v))
|
||||
.or_else(|| ide_core::process::host_var_os("PATH"))
|
||||
.unwrap_or_default();
|
||||
ide_core::process::find_executable(&spec.command, &search).unwrap_or_else(|| path.to_path_buf())
|
||||
}
|
||||
};
|
||||
let mut cmd = tokio::process::Command::new(&program);
|
||||
ide_core::process::prepare(cmd.as_std_mut());
|
||||
let mut child = cmd
|
||||
|
||||
@@ -22,7 +22,6 @@ fn paths(dir: &Path) -> AgentPaths {
|
||||
store_dir: dir.join("store"),
|
||||
worktrees_dir: dir.join("worktrees"),
|
||||
models_file: dir.join("models.json"),
|
||||
cli_dir: dir.join("agent-cli"),
|
||||
custom_agents_dir: None,
|
||||
home_dir: None,
|
||||
env_secrets: None,
|
||||
|
||||
@@ -163,15 +163,6 @@ pub struct RepoRef<'a> {
|
||||
|
||||
pub trait SkillSourceFetcher: Send + Sync {
|
||||
fn default_branch(&self, owner: &str, repo: &str, cancel: &CancellationToken) -> IdeResult<String>;
|
||||
fn git_commit_sha(&self, target: RepoRef<'_>, cancel: &CancellationToken) -> IdeResult<String>;
|
||||
/// The root tree SHA recorded in commit `commit_sha`.
|
||||
fn git_commit_tree_sha(
|
||||
&self,
|
||||
owner: &str,
|
||||
repo: &str,
|
||||
commit_sha: &str,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<String>;
|
||||
fn git_tree(&self, target: RepoRef<'_>, cancel: &CancellationToken) -> IdeResult<GitTree>;
|
||||
fn read_blob(
|
||||
&self,
|
||||
@@ -247,63 +238,6 @@ impl SkillSourceFetcher for GitHubHttpFetcher {
|
||||
.map_err(|e| IdeError::new(ErrorKind::Protocol, format!("{owner}/{repo}@{git_ref}: invalid Git tree: {e}")))
|
||||
}
|
||||
|
||||
fn git_commit_sha(&self, target: RepoRef<'_>, cancel: &CancellationToken) -> IdeResult<String> {
|
||||
#[derive(Deserialize)]
|
||||
struct CommitMeta {
|
||||
sha: String,
|
||||
}
|
||||
|
||||
let RepoRef { owner, repo, git_ref } = target;
|
||||
validate_repo_coord(owner, "owner")?;
|
||||
validate_repo_coord(repo, "repository")?;
|
||||
validate_git_ref(git_ref)?;
|
||||
let encoded_ref = encode_url_segment(git_ref);
|
||||
let url = format!("https://api.github.com/repos/{owner}/{repo}/commits/{encoded_ref}");
|
||||
let body = self.get_github_json(&url, MAX_REPO_META_BYTES, cancel)?;
|
||||
let meta: CommitMeta = serde_json::from_str(&body).map_err(|e| {
|
||||
IdeError::new(ErrorKind::Protocol, format!("{owner}/{repo}@{git_ref}: invalid GitHub commit: {e}"))
|
||||
})?;
|
||||
if !is_git_object_id(&meta.sha) {
|
||||
return Err(IdeError::new(
|
||||
ErrorKind::Protocol,
|
||||
format!("{owner}/{repo}@{git_ref}: invalid GitHub commit SHA"),
|
||||
));
|
||||
}
|
||||
Ok(meta.sha)
|
||||
}
|
||||
|
||||
fn git_commit_tree_sha(
|
||||
&self,
|
||||
owner: &str,
|
||||
repo: &str,
|
||||
commit_sha: &str,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<String> {
|
||||
#[derive(Deserialize)]
|
||||
struct TreeRef {
|
||||
sha: String,
|
||||
}
|
||||
#[derive(Deserialize)]
|
||||
struct GitCommit {
|
||||
tree: TreeRef,
|
||||
}
|
||||
|
||||
validate_repo_coord(owner, "owner")?;
|
||||
validate_repo_coord(repo, "repository")?;
|
||||
if !is_git_object_id(commit_sha) {
|
||||
return Err(IdeError::invalid("Invalid commit SHA"));
|
||||
}
|
||||
let url = format!("https://api.github.com/repos/{owner}/{repo}/git/commits/{commit_sha}");
|
||||
let body = self.get_github_json(&url, MAX_REPO_META_BYTES, cancel)?;
|
||||
let commit: GitCommit = serde_json::from_str(&body).map_err(|e| {
|
||||
IdeError::new(ErrorKind::Protocol, format!("{owner}/{repo}@{commit_sha}: invalid Git commit: {e}"))
|
||||
})?;
|
||||
if !is_git_object_id(&commit.tree.sha) {
|
||||
return Err(IdeError::new(ErrorKind::Protocol, format!("{owner}/{repo}@{commit_sha}: invalid tree SHA")));
|
||||
}
|
||||
Ok(commit.tree.sha)
|
||||
}
|
||||
|
||||
fn read_blob(
|
||||
&self,
|
||||
target: RepoRef<'_>,
|
||||
@@ -682,17 +616,6 @@ fn sanitize_repo_as_skill_name(repo: &str) -> String {
|
||||
out.trim_matches('-').to_owned()
|
||||
}
|
||||
|
||||
pub(crate) struct FetchedSubtree {
|
||||
pub tree_sha: String,
|
||||
pub normalized_subpath: String,
|
||||
pub files: Vec<RemoteSkillFile>,
|
||||
pub scan_warnings: Vec<SkillScanWarning>,
|
||||
/// `(relative_path, bytes, executable)` for safe non-symlink files to write on disk.
|
||||
pub regular_files: Vec<(PathBuf, Vec<u8>, bool)>,
|
||||
/// `(relative_path, relative_target)` for safe internal symlinks.
|
||||
pub in_root_symlinks: Vec<(PathBuf, PathBuf)>,
|
||||
}
|
||||
|
||||
struct PreparedSkillBundle {
|
||||
tree_sha: String,
|
||||
skill_name: String,
|
||||
@@ -706,19 +629,14 @@ struct PreparedSkillBundle {
|
||||
in_root_symlinks: Vec<(PathBuf, PathBuf)>,
|
||||
}
|
||||
|
||||
/// Fetches `target`'s tree (or exactly `pinned_tree_sha` when set) and scans `subpath` with hardened
|
||||
/// symlink-graph, executable-script, and hidden-Unicode checks.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(crate) fn fetch_and_scan_subtree(
|
||||
/// Fetches `target`'s tree (or exactly the tree `pinned_tree_sha` when set) and scans the `subpath` subtree.
|
||||
fn fetch_and_scan_bundle(
|
||||
fetcher: &dyn SkillSourceFetcher,
|
||||
target: RepoRef<'_>,
|
||||
subpath: &str,
|
||||
pinned_tree_sha: Option<&str>,
|
||||
max_files: usize,
|
||||
max_subtree_bytes: u64,
|
||||
noun: &str,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<FetchedSubtree> {
|
||||
) -> IdeResult<PreparedSkillBundle> {
|
||||
let RepoRef { owner, repo, git_ref } = target;
|
||||
validate_repo_coord(owner, "owner")?;
|
||||
validate_repo_coord(repo, "repository")?;
|
||||
@@ -728,8 +646,9 @@ pub(crate) fn fetch_and_scan_subtree(
|
||||
let tree = match pinned_tree_sha {
|
||||
Some(sha) => {
|
||||
if !is_git_object_id(sha) {
|
||||
return Err(IdeError::invalid(format!("Preview the {noun} again before installing it")));
|
||||
return Err(IdeError::invalid("Preview the skill again before installing it"));
|
||||
}
|
||||
// The Git trees API accepts a tree SHA in place of a ref.
|
||||
let tree = fetcher.git_tree(RepoRef { owner, repo, git_ref: sha }, cancel)?;
|
||||
if !tree.sha.eq_ignore_ascii_case(sha) {
|
||||
return Err(IdeError::new(
|
||||
@@ -741,14 +660,6 @@ pub(crate) fn fetch_and_scan_subtree(
|
||||
}
|
||||
None => fetcher.git_tree(target, cancel)?,
|
||||
};
|
||||
if tree.truncated {
|
||||
return Err(IdeError::new(
|
||||
ErrorKind::Protocol,
|
||||
format!(
|
||||
"{owner}/{repo}@{git_ref}: GitHub returned a truncated file listing; the {noun} cannot be verified"
|
||||
),
|
||||
));
|
||||
}
|
||||
let prefix = if normalized_subpath.is_empty() { String::new() } else { format!("{normalized_subpath}/") };
|
||||
|
||||
let subtree_entries: Vec<&GitTreeEntry> = tree
|
||||
@@ -761,32 +672,27 @@ pub(crate) fn fetch_and_scan_subtree(
|
||||
|
||||
if subtree_entries.is_empty() {
|
||||
return Err(IdeError::not_found(format!(
|
||||
"{} path {:?} was not found in {owner}/{repo}@{git_ref}",
|
||||
capitalize(noun),
|
||||
"Skill path {:?} was not found in {owner}/{repo}@{git_ref}",
|
||||
normalized_subpath
|
||||
)));
|
||||
}
|
||||
if subtree_entries.len() > max_files {
|
||||
if subtree_entries.len() > MAX_SKILL_FILES {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"{} exceeds maximum of {max_files} files ({} found)",
|
||||
capitalize(noun),
|
||||
"Skill exceeds maximum of {MAX_SKILL_FILES} files ({} found)",
|
||||
subtree_entries.len()
|
||||
)));
|
||||
}
|
||||
|
||||
let declared_total: u64 = subtree_entries.iter().map(|e| e.size.unwrap_or(0)).sum();
|
||||
if declared_total > max_subtree_bytes {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"{} exceeds {} MiB size cap",
|
||||
capitalize(noun),
|
||||
max_subtree_bytes >> 20
|
||||
)));
|
||||
if declared_total > MAX_SKILL_SUBTREE_BYTES {
|
||||
return Err(IdeError::invalid(format!("Skill exceeds {} MiB size cap", MAX_SKILL_SUBTREE_BYTES >> 20)));
|
||||
}
|
||||
|
||||
let mut files = Vec::with_capacity(subtree_entries.len());
|
||||
let mut scan_warnings = Vec::new();
|
||||
let mut regular_files = Vec::new();
|
||||
let mut symlinks: Vec<(PathBuf, String, String)> = Vec::new();
|
||||
let mut skill_markdown: Option<String> = None;
|
||||
let mut actual_total = 0u64;
|
||||
|
||||
for entry in subtree_entries {
|
||||
@@ -803,16 +709,12 @@ pub(crate) fn fetch_and_scan_subtree(
|
||||
target,
|
||||
&entry.path,
|
||||
&entry.sha,
|
||||
MAX_SINGLE_BLOB_BYTES.min(max_subtree_bytes - actual_total),
|
||||
MAX_SINGLE_BLOB_BYTES.min(MAX_SKILL_SUBTREE_BYTES - actual_total),
|
||||
cancel,
|
||||
)?;
|
||||
actual_total = actual_total.saturating_add(bytes.len() as u64);
|
||||
if actual_total > max_subtree_bytes {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"{} exceeds {} MiB size cap",
|
||||
capitalize(noun),
|
||||
max_subtree_bytes >> 20
|
||||
)));
|
||||
if actual_total > MAX_SKILL_SUBTREE_BYTES {
|
||||
return Err(IdeError::invalid(format!("Skill exceeds {} MiB size cap", MAX_SKILL_SUBTREE_BYTES >> 20)));
|
||||
}
|
||||
|
||||
if is_symlink {
|
||||
@@ -846,15 +748,11 @@ pub(crate) fn fetch_and_scan_subtree(
|
||||
|
||||
if let Ok(text) = std::str::from_utf8(&bytes) {
|
||||
scan_hidden_unicode(rel_str, text, &mut scan_warnings);
|
||||
if rel_str == "SKILL.md" || rel_str.ends_with("/SKILL.md") {
|
||||
for tool in frontmatter_shell_tools(text) {
|
||||
scan_warnings.push(SkillScanWarning {
|
||||
kind: SkillScanWarningKind::AllowedToolsShell,
|
||||
file: rel_str.to_owned(),
|
||||
message: format!("`allowed-tools` grants shell/command execution (`{tool}`)"),
|
||||
});
|
||||
}
|
||||
if rel_str == "SKILL.md" {
|
||||
skill_markdown = Some(text.to_owned());
|
||||
}
|
||||
} else if rel_str == "SKILL.md" {
|
||||
return Err(IdeError::invalid("SKILL.md is not valid UTF-8 text"));
|
||||
}
|
||||
|
||||
files.push(RemoteSkillFile {
|
||||
@@ -869,12 +767,13 @@ pub(crate) fn fetch_and_scan_subtree(
|
||||
files.sort_by(|a, b| a.path.cmp(&b.path));
|
||||
regular_files.sort_by(|a, b| a.0.cmp(&b.0));
|
||||
|
||||
// Symlinks are judged together: one link may point through another, and an entry placed beneath
|
||||
// a symlink would be written wherever that link points.
|
||||
let graph = SymlinkGraph::new(symlinks.iter().map(|(path, _, target)| (path.as_path(), target.as_str())));
|
||||
for path in regular_files.iter().map(|(p, _, _)| p).chain(symlinks.iter().map(|(p, _, _)| p)) {
|
||||
if let Some(link) = graph.symlink_ancestor(path) {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"{} entry {:?} is inside symlink {link:?}; the repository tree is malformed",
|
||||
capitalize(noun),
|
||||
"Skill entry {:?} is inside symlink {link:?}; the repository tree is malformed",
|
||||
path.display().to_string()
|
||||
)));
|
||||
}
|
||||
@@ -887,65 +786,26 @@ pub(crate) fn fetch_and_scan_subtree(
|
||||
scan_warnings.push(SkillScanWarning {
|
||||
kind: SkillScanWarningKind::OutOfRootSymlink,
|
||||
file: rel_str,
|
||||
message: format!("Symlink target {target_raw:?} leaves the {noun} folder (omitted on install)"),
|
||||
message: format!("Symlink target {target_raw:?} leaves the skill folder (omitted on install)"),
|
||||
});
|
||||
}
|
||||
}
|
||||
in_root_symlinks.sort();
|
||||
|
||||
Ok(FetchedSubtree { tree_sha: tree.sha, normalized_subpath, files, scan_warnings, regular_files, in_root_symlinks })
|
||||
}
|
||||
let Some(skill_markdown) = skill_markdown else {
|
||||
return Err(IdeError::invalid("Selected folder does not contain a regular SKILL.md file"));
|
||||
};
|
||||
|
||||
fn capitalize(s: &str) -> String {
|
||||
let mut c = s.chars();
|
||||
match c.next() {
|
||||
None => String::new(),
|
||||
Some(f) => f.to_uppercase().collect::<String>() + c.as_str(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Fetches `target`'s tree (or exactly the tree `pinned_tree_sha` when set) and scans the `subpath` subtree.
|
||||
fn fetch_and_scan_bundle(
|
||||
fetcher: &dyn SkillSourceFetcher,
|
||||
target: RepoRef<'_>,
|
||||
subpath: &str,
|
||||
pinned_tree_sha: Option<&str>,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<PreparedSkillBundle> {
|
||||
let RepoRef { repo, .. } = target;
|
||||
let mut sub = fetch_and_scan_subtree(
|
||||
fetcher,
|
||||
target,
|
||||
subpath,
|
||||
pinned_tree_sha,
|
||||
MAX_SKILL_FILES,
|
||||
MAX_SKILL_SUBTREE_BYTES,
|
||||
"skill",
|
||||
cancel,
|
||||
)?;
|
||||
|
||||
let skill_bytes = sub
|
||||
.regular_files
|
||||
.iter()
|
||||
.find(|(p, _, _)| p == Path::new("SKILL.md"))
|
||||
.map(|(_, b, _)| b.as_slice())
|
||||
.ok_or_else(|| IdeError::invalid("Selected folder does not contain a regular SKILL.md file"))?;
|
||||
let skill_markdown =
|
||||
std::str::from_utf8(skill_bytes).map_err(|_| IdeError::invalid("SKILL.md is not valid UTF-8 text"))?.to_owned();
|
||||
|
||||
let folder_hint = sub
|
||||
.normalized_subpath
|
||||
let folder_hint = normalized_subpath
|
||||
.rsplit('/')
|
||||
.next()
|
||||
.filter(|s| !s.is_empty())
|
||||
.map(str::to_owned)
|
||||
.unwrap_or_else(|| sanitize_repo_as_skill_name(repo));
|
||||
|
||||
// Strip any `SKILL.md` shell-tool warnings already collected so `parse_skill_markdown_metadata` emits them in order.
|
||||
sub.scan_warnings.retain(|w| !(w.kind == SkillScanWarningKind::AllowedToolsShell && w.file == "SKILL.md"));
|
||||
let parsed_meta = parse_skill_markdown_metadata(&folder_hint, &skill_markdown)?;
|
||||
for tool in &parsed_meta.shell_tools {
|
||||
sub.scan_warnings.push(SkillScanWarning {
|
||||
scan_warnings.push(SkillScanWarning {
|
||||
kind: SkillScanWarningKind::AllowedToolsShell,
|
||||
file: "SKILL.md".into(),
|
||||
message: format!("`allowed-tools` grants shell/command execution (`{tool}`)"),
|
||||
@@ -953,14 +813,14 @@ fn fetch_and_scan_bundle(
|
||||
}
|
||||
|
||||
Ok(PreparedSkillBundle {
|
||||
tree_sha: sub.tree_sha,
|
||||
tree_sha: tree.sha,
|
||||
skill_name: parsed_meta.name,
|
||||
description: parsed_meta.description,
|
||||
skill_markdown,
|
||||
files: sub.files,
|
||||
scan_warnings: sub.scan_warnings,
|
||||
regular_files: sub.regular_files,
|
||||
in_root_symlinks: sub.in_root_symlinks,
|
||||
files,
|
||||
scan_warnings,
|
||||
regular_files,
|
||||
in_root_symlinks,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1280,33 +1140,6 @@ fn create_parent_dirs_no_follow(root: &Path, rel: &Path) -> IdeResult<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Creates `target` below the existing `anchor` (the home or project folder) without following a
|
||||
/// symlink in any directory between them, the harness store root included.
|
||||
fn create_dirs_below_anchor(anchor: &Path, target: &Path) -> IdeResult<()> {
|
||||
if !anchor.is_dir() {
|
||||
return Err(IdeError::not_found(format!("{} does not exist", anchor.display())));
|
||||
}
|
||||
let rel = target
|
||||
.strip_prefix(anchor)
|
||||
.map_err(|_| IdeError::invalid(format!("{} is outside {}", target.display(), anchor.display())))?;
|
||||
let mut dir = anchor.to_path_buf();
|
||||
for component in rel.components() {
|
||||
if !matches!(component, Component::Normal(_)) {
|
||||
return Err(IdeError::invalid(format!("{} is not a plain path below the store", target.display())));
|
||||
}
|
||||
dir.push(component);
|
||||
match std::fs::symlink_metadata(&dir) {
|
||||
Ok(meta) if meta.is_dir() => {}
|
||||
Ok(_) => {
|
||||
return Err(IdeError::invalid(format!("{} passes through a symlink or file", dir.display())));
|
||||
}
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => std::fs::create_dir(&dir)?,
|
||||
Err(e) => return Err(e.into()),
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Whether the symlink at `link` resolves strictly inside `root` (canonical), following links on disk.
|
||||
/// Components that do not exist are resolved lexically.
|
||||
#[cfg(unix)]
|
||||
@@ -1387,16 +1220,15 @@ pub fn install_skill(
|
||||
workspace_root: Option<&Path>,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<PathBuf> {
|
||||
// Anchored at the home or project folder: nothing below it may be a symlink, store included.
|
||||
let (anchor, target_root) = match req.scope {
|
||||
let target_root = match req.scope {
|
||||
McpScope::User => {
|
||||
let home = user_home.ok_or_else(|| IdeError::unavailable("Cannot locate user home directory"))?;
|
||||
(home.to_path_buf(), home.join(".agents").join("skills"))
|
||||
home.join(".agents").join("skills")
|
||||
}
|
||||
McpScope::Workspace => {
|
||||
let ws = workspace_root
|
||||
.ok_or_else(|| IdeError::invalid("Open a trusted project to install workspace skills"))?;
|
||||
(ws.to_path_buf(), ws.join(".agents").join("skills"))
|
||||
ws.join(".agents").join("skills")
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1413,60 +1245,20 @@ pub fn install_skill(
|
||||
));
|
||||
}
|
||||
|
||||
write_staged_subtree(
|
||||
&anchor,
|
||||
&target_root,
|
||||
&bundle.skill_name,
|
||||
req.overwrite,
|
||||
"Skill",
|
||||
&bundle.regular_files,
|
||||
&bundle.in_root_symlinks,
|
||||
&[],
|
||||
)
|
||||
}
|
||||
|
||||
/// Atomically writes `regular_files`, `in_root_symlinks`, and `extra_files` into a staging folder
|
||||
/// under `target_root`, verifies created symlinks stay inside the folder, and swaps into `<target_root>/<folder_name>`.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(crate) fn write_staged_subtree(
|
||||
anchor: &Path,
|
||||
target_root: &Path,
|
||||
folder_name: &str,
|
||||
overwrite: bool,
|
||||
noun_cap: &str,
|
||||
regular_files: &[(PathBuf, Vec<u8>, bool)],
|
||||
in_root_symlinks: &[(PathBuf, PathBuf)],
|
||||
extra_files: &[(&str, &[u8])],
|
||||
) -> IdeResult<PathBuf> {
|
||||
create_dirs_below_anchor(anchor, target_root)?;
|
||||
if folder_name.is_empty() || !Path::new(folder_name).components().all(|c| matches!(c, Component::Normal(_))) {
|
||||
return Err(IdeError::invalid(format!("Invalid {} folder name", noun_cap.to_ascii_lowercase())));
|
||||
}
|
||||
let final_dir = target_root.join(folder_name);
|
||||
let existing = match std::fs::symlink_metadata(&final_dir) {
|
||||
Ok(meta) if meta.is_dir() => true,
|
||||
Ok(_) => {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"{} is a symlink or file, not a {} folder",
|
||||
final_dir.display(),
|
||||
noun_cap.to_ascii_lowercase()
|
||||
)));
|
||||
}
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => false,
|
||||
Err(e) => return Err(e.into()),
|
||||
};
|
||||
if existing && !overwrite {
|
||||
std::fs::create_dir_all(&target_root)?;
|
||||
let final_dir = target_root.join(&bundle.skill_name);
|
||||
if final_dir.exists() && !req.overwrite {
|
||||
return Err(IdeError::new(
|
||||
ErrorKind::AlreadyExists,
|
||||
format!("{noun_cap} `{folder_name}` is already installed in {}", target_root.display()),
|
||||
format!("Skill `{}` is already installed in {}", bundle.skill_name, target_root.display()),
|
||||
));
|
||||
}
|
||||
|
||||
let nonce = SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or_default();
|
||||
let staging = target_root.join(format!(".staging-{folder_name}-{nonce}-{}", std::process::id()));
|
||||
let staging = target_root.join(format!(".staging-{}-{nonce}-{}", bundle.skill_name, std::process::id()));
|
||||
let write_res = (|| -> IdeResult<()> {
|
||||
std::fs::create_dir_all(&staging)?;
|
||||
for (rel_path, bytes, is_exec) in regular_files {
|
||||
for (rel_path, bytes, is_exec) in &bundle.regular_files {
|
||||
create_parent_dirs_no_follow(&staging, rel_path)?;
|
||||
let dest = staging.join(rel_path);
|
||||
std::fs::write(&dest, bytes)?;
|
||||
@@ -1478,12 +1270,7 @@ pub(crate) fn write_staged_subtree(
|
||||
#[cfg(not(unix))]
|
||||
let _ = is_exec;
|
||||
}
|
||||
for (rel_str, bytes) in extra_files {
|
||||
let rel_path = validate_rel_skill_file(rel_str)?;
|
||||
create_parent_dirs_no_follow(&staging, &rel_path)?;
|
||||
std::fs::write(staging.join(&rel_path), bytes)?;
|
||||
}
|
||||
for (rel_link, target) in in_root_symlinks {
|
||||
for (rel_link, target) in &bundle.in_root_symlinks {
|
||||
create_parent_dirs_no_follow(&staging, rel_link)?;
|
||||
let dest = staging.join(rel_link);
|
||||
#[cfg(unix)]
|
||||
@@ -1501,18 +1288,17 @@ pub(crate) fn write_staged_subtree(
|
||||
#[cfg(unix)]
|
||||
{
|
||||
let root = std::fs::canonicalize(&staging)?;
|
||||
for (rel_link, _) in in_root_symlinks {
|
||||
for (rel_link, _) in &bundle.in_root_symlinks {
|
||||
if !link_resolves_inside(&root, &staging.join(rel_link)) {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"Symlink {:?} leaves the {} folder",
|
||||
rel_link.display().to_string(),
|
||||
noun_cap.to_ascii_lowercase()
|
||||
"Symlink {:?} leaves the skill folder",
|
||||
rel_link.display().to_string()
|
||||
)));
|
||||
}
|
||||
}
|
||||
}
|
||||
let backup = if existing {
|
||||
let bak = target_root.join(format!(".old-{folder_name}-{nonce}"));
|
||||
let backup = if final_dir.exists() {
|
||||
let bak = target_root.join(format!(".old-{}-{nonce}", bundle.skill_name));
|
||||
std::fs::rename(&final_dir, &bak)?;
|
||||
Some(bak)
|
||||
} else {
|
||||
@@ -1537,179 +1323,6 @@ pub(crate) fn write_staged_subtree(
|
||||
Ok(final_dir)
|
||||
}
|
||||
|
||||
/// Scans a local directory on disk with the same symlink-graph, executable-script, and hidden-Unicode
|
||||
/// checks used for remote GitHub subtrees.
|
||||
/// Content digest of a scanned local folder, used to pin a local preview to its install.
|
||||
fn local_subtree_digest(regular_files: &[(PathBuf, Vec<u8>, bool)], symlinks: &[(PathBuf, PathBuf)]) -> String {
|
||||
let mut hasher = blake3::Hasher::new();
|
||||
hasher.update(b"openidea-local-subtree-v1\0");
|
||||
for (path, bytes, executable) in regular_files {
|
||||
hasher.update(b"f\0");
|
||||
hasher.update(path.to_string_lossy().replace('\\', "/").as_bytes());
|
||||
hasher.update(&[0, u8::from(*executable)]);
|
||||
hasher.update(&(bytes.len() as u64).to_le_bytes());
|
||||
hasher.update(bytes);
|
||||
}
|
||||
for (path, target) in symlinks {
|
||||
hasher.update(b"l\0");
|
||||
hasher.update(path.to_string_lossy().replace('\\', "/").as_bytes());
|
||||
hasher.update(b"\0");
|
||||
hasher.update(target.to_string_lossy().replace('\\', "/").as_bytes());
|
||||
hasher.update(b"\0");
|
||||
}
|
||||
format!("local-blake3:{}", hasher.finalize().to_hex())
|
||||
}
|
||||
|
||||
pub(crate) fn scan_local_subtree(
|
||||
dir: &Path,
|
||||
max_files: usize,
|
||||
max_subtree_bytes: u64,
|
||||
noun: &str,
|
||||
) -> IdeResult<FetchedSubtree> {
|
||||
if !dir.is_dir() {
|
||||
return Err(IdeError::not_found(format!("Directory {} does not exist", dir.display())));
|
||||
}
|
||||
let mut files = Vec::new();
|
||||
let mut scan_warnings = Vec::new();
|
||||
let mut regular_files = Vec::new();
|
||||
let mut symlinks: Vec<(PathBuf, String, String)> = Vec::new();
|
||||
let mut actual_total = 0u64;
|
||||
|
||||
let mut stack = vec![(dir.to_path_buf(), String::new())];
|
||||
while let Some((cur_dir, rel_prefix)) = stack.pop() {
|
||||
let mut entries: Vec<_> = std::fs::read_dir(&cur_dir)?.filter_map(Result::ok).collect();
|
||||
entries.sort_by_key(|e| e.file_name());
|
||||
for entry in entries {
|
||||
let name = entry.file_name();
|
||||
let Some(name_str) = name.to_str() else {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"{} contains a file name that is not valid UTF-8: {}",
|
||||
capitalize(noun),
|
||||
entry.path().display()
|
||||
)));
|
||||
};
|
||||
if name_str == ".git" || name_str == "node_modules" || name_str == "target" {
|
||||
continue;
|
||||
}
|
||||
let rel_str = if rel_prefix.is_empty() { name_str.to_owned() } else { format!("{rel_prefix}/{name_str}") };
|
||||
let rel_path = validate_rel_skill_file(&rel_str)?;
|
||||
let full = entry.path();
|
||||
let meta = std::fs::symlink_metadata(&full)?;
|
||||
if (meta.file_type().is_symlink() || meta.file_type().is_file())
|
||||
&& regular_files.len() + symlinks.len() >= max_files
|
||||
{
|
||||
return Err(IdeError::invalid(format!("{} exceeds maximum of {max_files} files", capitalize(noun))));
|
||||
}
|
||||
if meta.file_type().is_symlink() {
|
||||
let target_raw = std::fs::read_link(&full)?.to_string_lossy().replace('\\', "/");
|
||||
symlinks.push((rel_path, rel_str.clone(), target_raw));
|
||||
files.push(RemoteSkillFile { path: rel_str, size: 0, executable: false, symlink: true });
|
||||
continue;
|
||||
}
|
||||
if meta.file_type().is_dir() {
|
||||
stack.push((full, rel_str));
|
||||
continue;
|
||||
}
|
||||
if !meta.file_type().is_file() {
|
||||
continue;
|
||||
}
|
||||
if meta.len() > MAX_SINGLE_BLOB_BYTES {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"File {rel_str:?} exceeds {} MiB size cap",
|
||||
MAX_SINGLE_BLOB_BYTES >> 20
|
||||
)));
|
||||
}
|
||||
let bytes = std::fs::read(&full)?;
|
||||
actual_total = actual_total.saturating_add(bytes.len() as u64);
|
||||
if actual_total > max_subtree_bytes {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"{} exceeds {} MiB size cap",
|
||||
capitalize(noun),
|
||||
max_subtree_bytes >> 20
|
||||
)));
|
||||
}
|
||||
#[cfg(unix)]
|
||||
let is_exec_mode = {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
meta.permissions().mode() & 0o111 != 0
|
||||
};
|
||||
#[cfg(not(unix))]
|
||||
let is_exec_mode = false;
|
||||
let has_shebang = bytes.starts_with(b"#!");
|
||||
let is_script_path = is_executable_or_script_path(&rel_path);
|
||||
if is_exec_mode || has_shebang || is_script_path {
|
||||
let reason = if is_exec_mode {
|
||||
"executable file mode"
|
||||
} else if has_shebang {
|
||||
"script with `#!` interpreter header"
|
||||
} else {
|
||||
"bundled script or native binary"
|
||||
};
|
||||
scan_warnings.push(SkillScanWarning {
|
||||
kind: SkillScanWarningKind::ExecutableScript,
|
||||
file: rel_str.clone(),
|
||||
message: format!("Contains {reason}"),
|
||||
});
|
||||
}
|
||||
if let Ok(text) = std::str::from_utf8(&bytes) {
|
||||
scan_hidden_unicode(&rel_str, text, &mut scan_warnings);
|
||||
if rel_str == "SKILL.md" || rel_str.ends_with("/SKILL.md") {
|
||||
for tool in frontmatter_shell_tools(text) {
|
||||
scan_warnings.push(SkillScanWarning {
|
||||
kind: SkillScanWarningKind::AllowedToolsShell,
|
||||
file: rel_str.clone(),
|
||||
message: format!("`allowed-tools` grants shell/command execution (`{tool}`)"),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
files.push(RemoteSkillFile {
|
||||
path: rel_str,
|
||||
size: bytes.len() as u64,
|
||||
executable: is_exec_mode || has_shebang,
|
||||
symlink: false,
|
||||
});
|
||||
regular_files.push((rel_path, bytes, is_exec_mode));
|
||||
}
|
||||
}
|
||||
|
||||
files.sort_by(|a, b| a.path.cmp(&b.path));
|
||||
regular_files.sort_by(|a, b| a.0.cmp(&b.0));
|
||||
|
||||
let graph = SymlinkGraph::new(symlinks.iter().map(|(path, _, target)| (path.as_path(), target.as_str())));
|
||||
for path in regular_files.iter().map(|(p, _, _)| p).chain(symlinks.iter().map(|(p, _, _)| p)) {
|
||||
if let Some(link) = graph.symlink_ancestor(path) {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"{} entry {:?} is inside symlink {link:?}",
|
||||
capitalize(noun),
|
||||
path.display().to_string()
|
||||
)));
|
||||
}
|
||||
}
|
||||
let mut in_root_symlinks = Vec::new();
|
||||
for (rel_path, rel_str, target_raw) in symlinks {
|
||||
if graph.stays_inside(&rel_path, &target_raw) {
|
||||
in_root_symlinks.push((rel_path, PathBuf::from(target_raw)));
|
||||
} else {
|
||||
scan_warnings.push(SkillScanWarning {
|
||||
kind: SkillScanWarningKind::OutOfRootSymlink,
|
||||
file: rel_str,
|
||||
message: format!("Symlink target {target_raw:?} leaves the {noun} folder (omitted on install)"),
|
||||
});
|
||||
}
|
||||
}
|
||||
in_root_symlinks.sort();
|
||||
|
||||
Ok(FetchedSubtree {
|
||||
tree_sha: local_subtree_digest(®ular_files, &in_root_symlinks),
|
||||
normalized_subpath: String::new(),
|
||||
files,
|
||||
scan_warnings,
|
||||
regular_files,
|
||||
in_root_symlinks,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -1761,25 +1374,6 @@ mod tests {
|
||||
.cloned()
|
||||
.ok_or_else(|| IdeError::not_found(format!("unknown ref {}", target.git_ref)))
|
||||
}
|
||||
fn git_commit_sha(&self, target: RepoRef<'_>, _cancel: &CancellationToken) -> IdeResult<String> {
|
||||
self.trees
|
||||
.get(target.git_ref)
|
||||
.map(|_| git_blob_id(format!("commit:{}", target.git_ref).as_bytes()))
|
||||
.ok_or_else(|| IdeError::not_found(format!("unknown ref {}", target.git_ref)))
|
||||
}
|
||||
fn git_commit_tree_sha(
|
||||
&self,
|
||||
_owner: &str,
|
||||
_repo: &str,
|
||||
commit_sha: &str,
|
||||
_cancel: &CancellationToken,
|
||||
) -> IdeResult<String> {
|
||||
self.trees
|
||||
.iter()
|
||||
.find(|(git_ref, _)| git_blob_id(format!("commit:{git_ref}").as_bytes()) == commit_sha)
|
||||
.map(|(_, tree)| tree.sha.clone())
|
||||
.ok_or_else(|| IdeError::not_found(format!("unknown commit {commit_sha}")))
|
||||
}
|
||||
|
||||
fn read_blob(
|
||||
&self,
|
||||
@@ -1846,9 +1440,7 @@ mod tests {
|
||||
let cancel = CancellationToken::new();
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let home = tmp.path().join("home");
|
||||
std::fs::create_dir_all(&home).unwrap();
|
||||
let ws = tmp.path().join("ws");
|
||||
std::fs::create_dir_all(&ws).unwrap();
|
||||
|
||||
// Bare `owner/repo` lists both skills; `owner/repo@clean-skill` falls back from ref lookup to skill filter!
|
||||
let all = browse_skills(&fetcher, "acme/skills", &cancel).unwrap();
|
||||
@@ -2204,66 +1796,4 @@ mod tests {
|
||||
.unwrap();
|
||||
assert!(dest.join("SKILL.md").is_file());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn local_scan_counts_symlinks_toward_the_file_cap() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
std::fs::write(tmp.path().join("SKILL.md"), "x").unwrap();
|
||||
for i in 0..3 {
|
||||
std::os::unix::fs::symlink("SKILL.md", tmp.path().join(format!("link-{i}"))).unwrap();
|
||||
}
|
||||
let Err(err) = scan_local_subtree(tmp.path(), 3, 1 << 20, "plugin") else { panic!("symlinks must count") };
|
||||
assert!(err.to_string().contains("maximum of 3 files"), "{err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn truncated_tree_listings_are_rejected() {
|
||||
let mut fetcher = FakeFetcher::new();
|
||||
fetcher.add_tree("main", vec![("skills/a/SKILL.md", "100644", b"---\nname: a\ndescription: a\n---\n")]);
|
||||
fetcher.trees.get_mut("main").unwrap().truncated = true;
|
||||
let cancel = CancellationToken::new();
|
||||
let target = RepoRef { owner: "o", repo: "r", git_ref: "main" };
|
||||
let Err(err) = fetch_and_scan_subtree(&fetcher, target, "skills/a", None, 10, 1 << 20, "skill", &cancel) else {
|
||||
panic!("a truncated listing cannot be verified")
|
||||
};
|
||||
assert!(err.to_string().contains("truncated"), "{err}");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn staged_installs_do_not_follow_symlinks_below_the_store() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let store = tmp.path().join("store");
|
||||
let outside = tmp.path().join("outside");
|
||||
std::fs::create_dir_all(&store).unwrap();
|
||||
std::fs::create_dir_all(&outside).unwrap();
|
||||
std::os::unix::fs::symlink(&outside, store.join("mkt")).unwrap();
|
||||
let files = vec![(PathBuf::from("plugin.json"), b"{}".to_vec(), false)];
|
||||
let Err(err) = write_staged_subtree(&store, &store.join("mkt"), "plugin", false, "Plugin", &files, &[], &[])
|
||||
else {
|
||||
panic!("a symlinked marketplace folder must not be written through")
|
||||
};
|
||||
assert!(err.to_string().contains("symlink"), "{err}");
|
||||
assert!(std::fs::read_dir(&outside).unwrap().next().is_none(), "nothing was written outside the store");
|
||||
|
||||
// The store root itself (`<home>/.claude/plugins` → elsewhere) is checked as well.
|
||||
let home = tmp.path().join("home");
|
||||
std::fs::create_dir_all(home.join(".claude")).unwrap();
|
||||
std::os::unix::fs::symlink(&outside, home.join(".claude/plugins")).unwrap();
|
||||
let store_root = home.join(".claude/plugins/cache/mkt");
|
||||
let Err(err) = write_staged_subtree(&home, &store_root, "plugin", false, "Plugin", &files, &[], &[]) else {
|
||||
panic!("a symlinked store root must not be written through")
|
||||
};
|
||||
assert!(err.to_string().contains("symlink"), "{err}");
|
||||
assert!(std::fs::read_dir(&outside).unwrap().next().is_none());
|
||||
|
||||
std::fs::create_dir_all(store.join("real")).unwrap();
|
||||
std::os::unix::fs::symlink(&outside, store.join("real/plugin")).unwrap();
|
||||
let Err(err) = write_staged_subtree(&store, &store.join("real"), "plugin", true, "Plugin", &files, &[], &[])
|
||||
else {
|
||||
panic!("an existing symlinked plugin folder must not be replaced through")
|
||||
};
|
||||
assert!(err.to_string().contains("symlink"), "{err}");
|
||||
}
|
||||
}
|
||||
@@ -275,45 +275,12 @@ pub fn discover_skills_in(workspaces: &[PathBuf], home: Option<&Path>) -> Vec<Ag
|
||||
}
|
||||
|
||||
/// [`discover_skills_in`] plus the `<dir>` skill folders contributed by enabled OpenIDEA
|
||||
/// plugins (`[[contributes.skills]]`) and unified agent plugin bundles (`plugins.rs`).
|
||||
/// Workspace and user skills take precedence on a name clash; a plugin skill is never silently renamed.
|
||||
/// plugins (`[[contributes.skills]]`). Workspace and user skills take precedence on a name
|
||||
/// clash; a plugin skill is never silently renamed.
|
||||
pub fn discover_skills_with_plugins(
|
||||
workspaces: &[PathBuf],
|
||||
home: Option<&Path>,
|
||||
plugin_skill_dirs: &[PathBuf],
|
||||
) -> Vec<AgentSkill> {
|
||||
let default_policy = crate::plugins::PluginsPolicy { workspace_roots: workspaces.to_vec(), ..Default::default() };
|
||||
let states =
|
||||
crate::plugins::resolve_plugins(crate::plugins::discover_plugins(workspaces, home), &default_policy, None);
|
||||
let projected = crate::plugins::projected_skill_roots(&states, None);
|
||||
discover_skills_with_agent_plugins(workspaces, home, plugin_skill_dirs, &projected)
|
||||
}
|
||||
|
||||
/// Discovers skills across `workspaces`, `home`, OpenIDEA IDE-plugin skill folders (`plugin_skill_dirs`),
|
||||
/// and resolved agent plugin bundle roots (`agent_plugin_roots`).
|
||||
pub fn discover_skills_with_agent_plugins(
|
||||
workspaces: &[PathBuf],
|
||||
home: Option<&Path>,
|
||||
plugin_skill_dirs: &[PathBuf],
|
||||
agent_plugin_roots: &[crate::plugins::ProjectedSkillRoot],
|
||||
) -> Vec<AgentSkill> {
|
||||
discover_skills_with_indexed_files(workspaces, home, plugin_skill_dirs, agent_plugin_roots, &[])
|
||||
}
|
||||
|
||||
/// Discovers skills across `workspaces`, `home`, OpenIDEA IDE-plugin skill folders (`plugin_skill_dirs`),
|
||||
/// resolved agent plugin bundle roots (`agent_plugin_roots`), and deeply nested workspace packages
|
||||
/// inferred from `indexed_skill_files` (typically `ProjectIndex::files_with_names(&["SKILL.md"])`).
|
||||
///
|
||||
/// Direct workspace roots and shallow monorepo packages (depth 1–2) are scanned directly on disk
|
||||
/// first so discovery works before indexing finishes and preserves shallow-over-deep precedence.
|
||||
/// Any deeper package roots discovered via `indexed_skill_files` are scanned next, sorted from
|
||||
/// shallowest to deepest and deduplicated by canonical path.
|
||||
pub fn discover_skills_with_indexed_files(
|
||||
workspaces: &[PathBuf],
|
||||
home: Option<&Path>,
|
||||
plugin_skill_dirs: &[PathBuf],
|
||||
agent_plugin_roots: &[crate::plugins::ProjectedSkillRoot],
|
||||
indexed_skill_files: &[PathBuf],
|
||||
) -> Vec<AgentSkill> {
|
||||
let mut out: Vec<AgentSkill> = Vec::new();
|
||||
let mut seen_paths: HashSet<PathBuf> = HashSet::new();
|
||||
@@ -339,13 +306,6 @@ pub fn discover_skills_with_indexed_files(
|
||||
}
|
||||
}
|
||||
}
|
||||
// Deeply nested packages (arbitrary depth) surfaced by the project file index.
|
||||
for sub in indexed_package_roots(&all_workspaces, indexed_skill_files) {
|
||||
let sub_canon = dunce::canonicalize(&sub).unwrap_or_else(|_| sub.clone());
|
||||
if seen_workspaces.insert(sub_canon) {
|
||||
roots.extend(WORKSPACE_ROOTS.iter().map(|(rel, source)| (sub.join(rel), *source)));
|
||||
}
|
||||
}
|
||||
if let Some(home) = home {
|
||||
roots.extend(HOME_ROOTS.iter().map(|(rel, source)| (home.join(rel), *source)));
|
||||
}
|
||||
@@ -378,19 +338,9 @@ pub fn discover_skills_with_indexed_files(
|
||||
let Ok(text) = std::fs::read_to_string(dir.join("SKILL.md")) else { continue };
|
||||
push_skill(parse_skill_file(dir, &folder, &text, AgentSkillSource::Plugin));
|
||||
}
|
||||
for proj in agent_plugin_roots {
|
||||
if proj.dir.join("SKILL.md").is_file() && proj.dir.file_name().and_then(|s| s.to_str()) != Some("skills") {
|
||||
let Some(folder) = file_name(&proj.dir) else { continue };
|
||||
if let Ok(text) = std::fs::read_to_string(proj.dir.join("SKILL.md")) {
|
||||
let mut skill = parse_skill_file(&proj.dir, &folder, &text, proj.source);
|
||||
skill.plugin_id = Some(proj.plugin_id.clone());
|
||||
skill.plugin_name = Some(proj.plugin_name.clone());
|
||||
push_skill(skill);
|
||||
}
|
||||
} else {
|
||||
for mut skill in skills_of(&proj.dir, proj.source) {
|
||||
skill.plugin_id = Some(proj.plugin_id.clone());
|
||||
skill.plugin_name = Some(proj.plugin_name.clone());
|
||||
if let Some(home) = home {
|
||||
for (root, source) in copilot_installed_plugin_roots(&home.join(".copilot")) {
|
||||
for skill in skills_of(&root, source) {
|
||||
push_skill(skill);
|
||||
}
|
||||
}
|
||||
@@ -438,72 +388,81 @@ fn monorepo_subdirs(root: &Path, max_depth: usize) -> Vec<PathBuf> {
|
||||
out
|
||||
}
|
||||
|
||||
/// Extracts workspace package roots from indexed `SKILL.md` file paths.
|
||||
///
|
||||
/// Only accepts `SKILL.md` files located inside one of [`WORKSPACE_ROOTS`] at depth 0, 1, or 2
|
||||
/// below `<dot_dir>/skills` (`skills/SKILL.md`, `skills/<name>/SKILL.md`, or
|
||||
/// `skills/<category>/<name>/SKILL.md`), rejecting unrelated fixture/doc `SKILL.md` files as well
|
||||
/// as packages under hidden directories or [`SKIP_MONOREPO_DIRS`]. Returns roots sorted from
|
||||
/// shallowest to deepest (then lexicographically) so shallower packages always win on name clashes.
|
||||
fn indexed_package_roots(workspaces: &[PathBuf], indexed_skill_files: &[PathBuf]) -> Vec<PathBuf> {
|
||||
if workspaces.is_empty() || indexed_skill_files.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
let workspace_pairs: Vec<(&Path, Option<PathBuf>)> =
|
||||
workspaces.iter().map(|ws| (ws.as_path(), dunce::canonicalize(ws).ok())).collect();
|
||||
let mut candidates: Vec<(usize, PathBuf)> = Vec::new();
|
||||
for file in indexed_skill_files {
|
||||
let Some(pkg_root) = package_root_of_skill_file(file) else { continue };
|
||||
let Some(rel) = relative_within_workspaces(&pkg_root, &workspace_pairs) else { continue };
|
||||
if rel.components().any(|c| match c {
|
||||
std::path::Component::Normal(seg) => {
|
||||
seg.to_str().is_none_or(|s| s.starts_with('.') || SKIP_MONOREPO_DIRS.contains(&s))
|
||||
/// Discovers skill roots inside `~/.copilot/installed-plugins`, supporting both Copilot CLI's
|
||||
/// 2-level `<marketplace-or-_direct>/<plugin>` layout (and `config.json` `installedPlugins`
|
||||
/// enablement) and flat 1-level `<plugin>` folders.
|
||||
fn copilot_installed_plugin_roots(copilot_dir: &Path) -> Vec<(PathBuf, AgentSkillSource)> {
|
||||
let mut disabled_paths: HashSet<PathBuf> = HashSet::new();
|
||||
let mut plugin_dirs: Vec<PathBuf> = Vec::new();
|
||||
let mut seen_dirs: HashSet<PathBuf> = HashSet::new();
|
||||
let mut push_plugin = |dir: PathBuf, disabled: &HashSet<PathBuf>| {
|
||||
if !dir.is_dir() {
|
||||
return;
|
||||
}
|
||||
let canon = dunce::canonicalize(&dir).unwrap_or_else(|_| dir.clone());
|
||||
if disabled.contains(&canon) || !seen_dirs.insert(canon) {
|
||||
return;
|
||||
}
|
||||
plugin_dirs.push(dir);
|
||||
};
|
||||
|
||||
if let Ok(text) = std::fs::read_to_string(copilot_dir.join("config.json"))
|
||||
&& let Ok(root) = serde_json::from_str::<serde_json::Value>(&ide_core::jsonc::strip(&text))
|
||||
&& let Some(installed) = root.get("installedPlugins").and_then(serde_json::Value::as_array)
|
||||
{
|
||||
for entry in installed {
|
||||
let Some(raw_cache) = entry.get("cache_path").and_then(serde_json::Value::as_str).map(str::trim) else {
|
||||
continue;
|
||||
};
|
||||
if raw_cache.is_empty() {
|
||||
continue;
|
||||
}
|
||||
_ => true,
|
||||
}) {
|
||||
let dir =
|
||||
if Path::new(raw_cache).is_relative() { copilot_dir.join(raw_cache) } else { PathBuf::from(raw_cache) };
|
||||
if entry.get("enabled").and_then(serde_json::Value::as_bool) == Some(false) {
|
||||
disabled_paths.insert(dunce::canonicalize(&dir).unwrap_or(dir));
|
||||
} else {
|
||||
push_plugin(dir, &disabled_paths);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let plugins_root = copilot_dir.join("installed-plugins");
|
||||
for entry in sorted(&plugins_root) {
|
||||
if !entry.is_dir() {
|
||||
continue;
|
||||
}
|
||||
if !pkg_root.is_dir() {
|
||||
continue;
|
||||
if looks_like_plugin_dir(&entry) {
|
||||
push_plugin(entry, &disabled_paths);
|
||||
} else {
|
||||
// 2-level `<marketplace>/<plugin>` or `_direct/<plugin>`.
|
||||
for sub in sorted(&entry) {
|
||||
if sub.is_dir() {
|
||||
push_plugin(sub, &disabled_paths);
|
||||
}
|
||||
}
|
||||
}
|
||||
candidates.push((rel.components().count(), pkg_root));
|
||||
}
|
||||
candidates.sort_by(|a, b| a.0.cmp(&b.0).then_with(|| a.1.cmp(&b.1)));
|
||||
candidates.dedup_by(|a, b| a.1 == b.1);
|
||||
candidates.into_iter().map(|(_, p)| p).collect()
|
||||
|
||||
let mut roots = Vec::new();
|
||||
for plugin in plugin_dirs {
|
||||
let skills_sub = plugin.join("skills");
|
||||
if skills_sub.is_dir() {
|
||||
roots.push((skills_sub, AgentSkillSource::CopilotUser));
|
||||
} else {
|
||||
roots.push((plugin, AgentSkillSource::CopilotUser));
|
||||
}
|
||||
}
|
||||
roots
|
||||
}
|
||||
|
||||
/// If `skill_md` sits inside `<pkg>/<dot_dir>/skills[/<category>][/<name>]/SKILL.md` for one of
|
||||
/// [`WORKSPACE_ROOTS`], returns `<pkg>`.
|
||||
fn package_root_of_skill_file(skill_md: &Path) -> Option<PathBuf> {
|
||||
if skill_md.file_name().and_then(|n| n.to_str()) != Some("SKILL.md") {
|
||||
return None;
|
||||
}
|
||||
let mut cur = skill_md.parent()?;
|
||||
for _ in 0..=2 {
|
||||
if cur.file_name().and_then(|n| n.to_str()) == Some("skills")
|
||||
&& let Some(dot_dir) = cur.parent()
|
||||
&& let Some(dot_name) = dot_dir.file_name().and_then(|n| n.to_str())
|
||||
&& WORKSPACE_ROOTS.iter().any(|(rel, _)| rel.split('/').next() == Some(dot_name))
|
||||
&& let Some(pkg_root) = dot_dir.parent()
|
||||
{
|
||||
return Some(pkg_root.to_path_buf());
|
||||
}
|
||||
cur = cur.parent()?;
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn relative_within_workspaces(pkg_root: &Path, workspaces: &[(&Path, Option<PathBuf>)]) -> Option<PathBuf> {
|
||||
let pick_shortest =
|
||||
|iter: &mut dyn Iterator<Item = &Path>| iter.min_by_key(|rel| rel.components().count()).map(Path::to_path_buf);
|
||||
let mut direct = workspaces.iter().filter_map(|(ws, _)| pkg_root.strip_prefix(ws).ok());
|
||||
if let Some(rel) = pick_shortest(&mut direct) {
|
||||
return Some(rel);
|
||||
}
|
||||
let canon_pkg = dunce::canonicalize(pkg_root).ok()?;
|
||||
let mut canonical = workspaces.iter().filter_map(|(_, canon_ws)| canon_pkg.strip_prefix(canon_ws.as_ref()?).ok());
|
||||
pick_shortest(&mut canonical)
|
||||
fn looks_like_plugin_dir(dir: &Path) -> bool {
|
||||
dir.join("skills").is_dir()
|
||||
|| dir.join("plugin.json").is_file()
|
||||
|| dir.join(".plugin").is_dir()
|
||||
|| dir.join(".claude-plugin").is_dir()
|
||||
|| dir.join(".cursor-plugin").is_dir()
|
||||
|| dir.join("SKILL.md").is_file()
|
||||
}
|
||||
|
||||
/// The skills of one root: `<name>/SKILL.md` folders and `<category>/<name>/SKILL.md`
|
||||
@@ -585,8 +544,6 @@ fn parse_skill_file(dir: &Path, folder: &str, text: &str, source: AgentSkillSour
|
||||
paths,
|
||||
valid: warnings.is_empty(),
|
||||
warnings,
|
||||
plugin_id: None,
|
||||
plugin_name: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1113,8 +1070,6 @@ mod tests {
|
||||
paths: Vec::new(),
|
||||
valid: true,
|
||||
warnings: Vec::new(),
|
||||
plugin_id: None,
|
||||
plugin_name: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1562,65 +1517,4 @@ mod tests {
|
||||
let staged_md = std::fs::read_to_string(farm.join("copilot/verify-ux/SKILL.md")).unwrap();
|
||||
assert_eq!(staged_md, raw_md);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn indexed_skill_files_discover_deep_monorepo_skills_and_respect_filters_and_precedence() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let ws = root.join("ws");
|
||||
|
||||
let deep_grafana =
|
||||
ws.join("mango/tools/mai-grafana-dashboards/.github/skills/edit-grafana-dashboards/SKILL.md");
|
||||
let deep_category = ws.join("a/b/c/.agents/skills/ops/deploy/SKILL.md");
|
||||
let deep_named_skills = ws.join("a/b/c/.claude/skills/skills/SKILL.md");
|
||||
let shallow_clash = ws.join("pkg/.agents/skills/shared/SKILL.md");
|
||||
let deep_clash = ws.join("a/b/c/.github/skills/shared/SKILL.md");
|
||||
let depth3_clash = ws.join("x/y/z/.github/skills/depth-race/SKILL.md");
|
||||
let depth4_clash = ws.join("x/y/z/w/.agents/skills/depth-race/SKILL.md");
|
||||
let fixture_skill = ws.join("crates/ide-plugin/tests/fixtures/agent-skills/skills/fixture-only/SKILL.md");
|
||||
let hidden_dir_skill = ws.join(".worktrees/branch/.github/skills/wt-only/SKILL.md");
|
||||
let target_dir_skill = ws.join("crates/app/target/gen/.github/skills/build-only/SKILL.md");
|
||||
|
||||
write(&deep_grafana, "---\nname: edit-grafana-dashboards\ndescription: Edit Grafana dashboards\n---\n");
|
||||
write(&deep_category, "---\nname: deploy\ndescription: Deploy service\n---\n");
|
||||
write(&deep_named_skills, "---\nname: skills\ndescription: Skill named skills\n---\n");
|
||||
write(&shallow_clash, "---\nname: shared\ndescription: Shallow copy\n---\n");
|
||||
write(&deep_clash, "---\nname: shared\ndescription: Deep copy\n---\n");
|
||||
write(&depth3_clash, "---\nname: depth-race\ndescription: Depth 3 wins\n---\n");
|
||||
write(&depth4_clash, "---\nname: depth-race\ndescription: Depth 4 loses\n---\n");
|
||||
write(&fixture_skill, "---\nname: fixture-only\ndescription: Fixture not under a skill root\n---\n");
|
||||
write(&hidden_dir_skill, "---\nname: wt-only\ndescription: Inside hidden dir\n---\n");
|
||||
write(&target_dir_skill, "---\nname: build-only\ndescription: Inside target dir\n---\n");
|
||||
|
||||
// Without indexed files, depth-3+ packages are beyond the 2-level direct walk.
|
||||
let shallow_only = discover_skills(&ws, None);
|
||||
assert!(shallow_only.iter().all(|s| s.name != "edit-grafana-dashboards"));
|
||||
assert!(shallow_only.iter().any(|s| s.name == "shared" && s.description == "Shallow copy"));
|
||||
|
||||
// Passing indexed `SKILL.md` paths (even in reversed depth order) surfaces deep skills
|
||||
// while keeping shallow-over-deep precedence and ignoring fixtures/hidden/build dirs.
|
||||
let indexed = vec![
|
||||
depth4_clash,
|
||||
depth3_clash,
|
||||
deep_clash,
|
||||
deep_grafana,
|
||||
deep_category,
|
||||
deep_named_skills,
|
||||
fixture_skill,
|
||||
hidden_dir_skill,
|
||||
target_dir_skill,
|
||||
];
|
||||
let found = discover_skills_with_indexed_files(std::slice::from_ref(&ws), None, &[], &[], &indexed);
|
||||
let by = |n: &str| found.iter().find(|s| s.name == n);
|
||||
|
||||
let grafana = by("edit-grafana-dashboards").expect("depth-3 .github/skills discovered");
|
||||
assert_eq!(grafana.source, AgentSkillSource::GithubWorkspace);
|
||||
assert!(by("deploy").is_some(), "category skill under depth-3 package discovered");
|
||||
assert!(by("skills").is_some(), "skill named `skills` under depth-3 package discovered");
|
||||
assert_eq!(by("shared").unwrap().description, "Shallow copy", "shallow package beats deep package");
|
||||
assert_eq!(by("depth-race").unwrap().description, "Depth 3 wins", "depth 3 beats depth 4");
|
||||
assert!(by("fixture-only").is_none(), "unrelated fixture SKILL.md ignored");
|
||||
assert!(by("wt-only").is_none(), "hidden directory tree ignored");
|
||||
assert!(by("build-only").is_none(), "SKIP_MONOREPO_DIRS tree ignored");
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -20,8 +20,6 @@ pub(crate) struct Timeline {
|
||||
cards: HashMap<String, usize>,
|
||||
/// Session messages, by message id.
|
||||
messages: HashMap<String, usize>,
|
||||
/// The next agent text starts an entry of its own (see [`Timeline::seal`]).
|
||||
sealed: bool,
|
||||
}
|
||||
|
||||
/// What a `session/update` changed in the timeline.
|
||||
@@ -140,17 +138,10 @@ impl Timeline {
|
||||
out
|
||||
}
|
||||
|
||||
/// A prompt is being sent: text the agent sent before it (a startup notice) is not the
|
||||
/// start of the reply, so the reply's text gets an entry of its own.
|
||||
pub fn seal(&mut self) {
|
||||
self.sealed = true;
|
||||
}
|
||||
|
||||
fn append_text(&mut self, thought: bool, text: &str) -> usize {
|
||||
let sealed = std::mem::take(&mut self.sealed);
|
||||
match self.entries.last_mut() {
|
||||
Some(AgentEntry::Agent { text: t }) if !thought && !sealed => t.push_str(text),
|
||||
Some(AgentEntry::Thought { text: t, .. }) if thought && !sealed => 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),
|
||||
_ => {
|
||||
let text = text.to_owned();
|
||||
return self.push(if thought {
|
||||
@@ -532,7 +523,7 @@ mod tests {
|
||||
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, inline_number: None }]);
|
||||
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();
|
||||
@@ -655,7 +646,6 @@ mod tests {
|
||||
done_ms: None,
|
||||
steered: false,
|
||||
recovery: None,
|
||||
retry_attempt: None,
|
||||
};
|
||||
let mut t = Timeline::default();
|
||||
t.push(user(1.0));
|
||||
@@ -678,7 +668,6 @@ mod tests {
|
||||
done_ms: None,
|
||||
steered,
|
||||
recovery: None,
|
||||
retry_attempt: None,
|
||||
};
|
||||
let mut t = Timeline::default();
|
||||
t.push(user(1.0, false));
|
||||
|
||||
@@ -9,34 +9,12 @@ use std::path::{Path, PathBuf};
|
||||
use std::time::{Duration, UNIX_EPOCH};
|
||||
|
||||
pub(crate) struct Created {
|
||||
#[cfg_attr(not(test), allow(dead_code))]
|
||||
pub path: PathBuf,
|
||||
pub cwd: PathBuf,
|
||||
pub branch: String,
|
||||
pub base: String,
|
||||
pub base_commit: String,
|
||||
}
|
||||
|
||||
const OWNERSHIP_MARKER: &str = "openidea-worktree.json";
|
||||
const OWNERSHIP_TAG: &str = "openidea-agent";
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct WorktreeOwnership {
|
||||
owner: String,
|
||||
task_id: String,
|
||||
worktree_root: PathBuf,
|
||||
repo_root: PathBuf,
|
||||
}
|
||||
|
||||
/// Returns the canonical root of the Git repository containing `project_root`, if any.
|
||||
pub fn canonical_repo_root(project_root: &Path) -> IdeResult<Option<PathBuf>> {
|
||||
match Repo::discover(project_root)? {
|
||||
Some(repo) => Ok(Some(dunce::canonicalize(repo.root())?)),
|
||||
None => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
/// The repository of `path`, free to execute: the host runs every agent command that
|
||||
/// reaches a repository only in a trusted project.
|
||||
fn discover(path: &Path) -> IdeResult<Option<Repo>> {
|
||||
@@ -179,38 +157,9 @@ pub(crate) fn head_commit(cwd: &Path) -> IdeResult<Option<String>> {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn create(project_root: &Path, worktrees_dir: &Path, title: &str, base: Option<&str>) -> IdeResult<Created> {
|
||||
create_for_task(project_root, worktrees_dir, "", title, base)
|
||||
}
|
||||
|
||||
/// `git worktree add -b agent/<slug> <dir>/<slug> <base>`.
|
||||
/// Records an ownership marker in the linked worktree's private `git_dir` and preserves any
|
||||
/// project-relative subdirectory inside `project_root` when `project_root` is below `repo.root()`.
|
||||
pub(crate) fn create_for_task(
|
||||
project_root: &Path,
|
||||
worktrees_dir: &Path,
|
||||
task_id: &str,
|
||||
title: &str,
|
||||
base: Option<&str>,
|
||||
) -> IdeResult<Created> {
|
||||
pub(crate) fn create(project_root: &Path, worktrees_dir: &Path, title: &str, base: Option<&str>) -> IdeResult<Created> {
|
||||
let repo = repo_at(project_root)?;
|
||||
let canon_repo = dunce::canonicalize(repo.root())?;
|
||||
let canon_proj = dunce::canonicalize(project_root)?;
|
||||
let rel_subdir = if canon_proj != canon_repo {
|
||||
canon_proj
|
||||
.strip_prefix(&canon_repo)
|
||||
.map_err(|_| {
|
||||
IdeError::invalid(format!(
|
||||
"{} is outside git repository {}",
|
||||
canon_proj.display(),
|
||||
canon_repo.display()
|
||||
))
|
||||
})?
|
||||
.to_path_buf()
|
||||
} else {
|
||||
PathBuf::new()
|
||||
};
|
||||
let (base, base_commit) = match base.map(str::trim).filter(|b| !b.is_empty()) {
|
||||
Some(b) => {
|
||||
let commit =
|
||||
@@ -228,244 +177,7 @@ pub(crate) fn create_for_task(
|
||||
let path = worktrees_dir.join(&slug);
|
||||
let branch = format!("agent/{slug}");
|
||||
repo.add_worktree(&path, &base_commit, Some(&branch))?;
|
||||
|
||||
let canon_wt = match dunce::canonicalize(&path) {
|
||||
Ok(p) => p,
|
||||
Err(e) => {
|
||||
let _ = repo.remove_worktree(&path, false);
|
||||
return Err(e.into());
|
||||
}
|
||||
};
|
||||
let wt_repo = match repo_at(&canon_wt) {
|
||||
Ok(r) => r,
|
||||
Err(e) => {
|
||||
let _ = repo.remove_worktree(&path, false);
|
||||
return Err(e);
|
||||
}
|
||||
};
|
||||
let [git_dir, common_dir] = match wt_repo.metadata_dirs() {
|
||||
Ok(dirs) => dirs,
|
||||
Err(e) => {
|
||||
let _ = repo.remove_worktree(&path, false);
|
||||
return Err(e);
|
||||
}
|
||||
};
|
||||
if dunce::canonicalize(&git_dir).ok() == dunce::canonicalize(&common_dir).ok() {
|
||||
let _ = repo.remove_worktree(&path, false);
|
||||
return Err(IdeError::internal("linked worktree did not receive a separate git metadata directory"));
|
||||
}
|
||||
let marker = WorktreeOwnership {
|
||||
owner: OWNERSHIP_TAG.to_owned(),
|
||||
task_id: task_id.to_owned(),
|
||||
worktree_root: canon_wt.clone(),
|
||||
repo_root: canon_repo,
|
||||
};
|
||||
if let Err(e) = serde_json::to_vec_pretty(&marker)
|
||||
.map_err(|e| IdeError::internal(e.to_string()))
|
||||
.and_then(|bytes| ide_vfs::write_atomic(&git_dir.join(OWNERSHIP_MARKER), &bytes))
|
||||
{
|
||||
let _ = repo.remove_worktree(&path, false);
|
||||
return Err(e);
|
||||
}
|
||||
|
||||
let raw_cwd = if rel_subdir.as_os_str().is_empty() { canon_wt.clone() } else { canon_wt.join(&rel_subdir) };
|
||||
if !raw_cwd.is_dir() {
|
||||
let _ = repo.remove_worktree(&path, false);
|
||||
return Err(IdeError::invalid(format!(
|
||||
"project folder {} does not exist in base revision {}",
|
||||
rel_subdir.display(),
|
||||
base
|
||||
)));
|
||||
}
|
||||
let canon_cwd = match verify_confined_worktree_subdir(&canon_wt, &raw_cwd) {
|
||||
Ok(c) => c,
|
||||
Err(e) => {
|
||||
let _ = repo.remove_worktree(&path, false);
|
||||
return Err(e);
|
||||
}
|
||||
};
|
||||
Ok(Created { path, cwd: canon_cwd, branch, base, base_commit })
|
||||
}
|
||||
|
||||
/// Validates and opens an existing managed worktree under `worktrees_dir` so a new task can
|
||||
/// reuse it. Rejects paths outside `worktrees_dir`, non-directories, non-linked repositories,
|
||||
/// or worktrees belonging to a different Git repository than `project_root`. Preserves any
|
||||
/// project-relative subdirectory inside `project_root` just like [`create_for_task`].
|
||||
pub(crate) fn reuse_for_task(project_root: &Path, worktrees_dir: &Path, worktree_path: &Path) -> IdeResult<Created> {
|
||||
let canon_input = verify_confined_worktree_cwd(worktrees_dir, worktree_path)?;
|
||||
if !canon_input.is_dir() {
|
||||
return Err(IdeError::not_found(format!("worktree {} does not exist", worktree_path.display())));
|
||||
}
|
||||
let project_repo = repo_at(project_root)?;
|
||||
let wt_repo = repo_at(&canon_input)?;
|
||||
let [_, project_common] = project_repo.metadata_dirs()?;
|
||||
let [wt_git_dir, wt_common] = wt_repo.metadata_dirs()?;
|
||||
let canon_wt_git_dir = dunce::canonicalize(&wt_git_dir)?;
|
||||
let canon_wt_common = dunce::canonicalize(&wt_common)?;
|
||||
let canon_project_common = dunce::canonicalize(&project_common)?;
|
||||
if canon_wt_git_dir == canon_wt_common || canon_wt_common != canon_project_common {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"worktree {} is not a linked worktree of this repository",
|
||||
worktree_path.display()
|
||||
)));
|
||||
}
|
||||
let canon_wt_root = dunce::canonicalize(wt_repo.root())?;
|
||||
let canon_wt_dir = dunce::canonicalize(worktrees_dir)?;
|
||||
if !canon_wt_root.starts_with(&canon_wt_dir)
|
||||
|| canon_wt_root == canon_wt_dir
|
||||
|| canon_wt_root.parent() != Some(canon_wt_dir.as_path())
|
||||
{
|
||||
return Err(IdeError::invalid("worktree root does not match managed worktrees directory"));
|
||||
}
|
||||
let canon_repo = dunce::canonicalize(project_repo.root())?;
|
||||
let canon_proj = dunce::canonicalize(project_root)?;
|
||||
let rel_subdir = if canon_proj != canon_repo {
|
||||
canon_proj
|
||||
.strip_prefix(&canon_repo)
|
||||
.map_err(|_| {
|
||||
IdeError::invalid(format!(
|
||||
"{} is outside git repository {}",
|
||||
canon_proj.display(),
|
||||
canon_repo.display()
|
||||
))
|
||||
})?
|
||||
.to_path_buf()
|
||||
} else {
|
||||
PathBuf::new()
|
||||
};
|
||||
let raw_cwd =
|
||||
if rel_subdir.as_os_str().is_empty() { canon_wt_root.clone() } else { canon_wt_root.join(&rel_subdir) };
|
||||
if !raw_cwd.is_dir() {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"project folder {} does not exist in worktree {}",
|
||||
rel_subdir.display(),
|
||||
canon_wt_root.display()
|
||||
)));
|
||||
}
|
||||
let canon_cwd = verify_confined_worktree_subdir(&canon_wt_root, &raw_cwd)?;
|
||||
let (branch, base_commit) = head_of(&canon_cwd)?;
|
||||
Ok(Created { path: canon_wt_root, cwd: canon_cwd, branch: branch.clone(), base: branch, base_commit })
|
||||
}
|
||||
|
||||
/// Checks out (or creates and checks out) `branch` in `cwd` using Smart checkout so uncommitted
|
||||
/// edits are stashed and restored across the switch. Returns the resulting branch name, HEAD
|
||||
/// commit (when available), and checkout outcome.
|
||||
pub(crate) fn checkout_branch(
|
||||
cwd: &Path,
|
||||
branch: &str,
|
||||
create: bool,
|
||||
) -> IdeResult<(String, Option<String>, ide_vcs::CheckoutOutcome)> {
|
||||
let name = branch.trim();
|
||||
if name.is_empty() {
|
||||
return Err(IdeError::invalid("branch name cannot be empty"));
|
||||
}
|
||||
let repo = repo_at(cwd)?;
|
||||
let options = ide_vcs::CheckoutOptions { mode: ide_vcs::CheckoutMode::Smart, ..Default::default() };
|
||||
let outcome = repo.checkout_with(name, create, &options)?;
|
||||
let (current, head_commit) = match head_of(cwd) {
|
||||
Ok((b, commit)) => (b, Some(commit)),
|
||||
Err(_) => (name.to_owned(), None),
|
||||
};
|
||||
Ok((current, head_commit, outcome))
|
||||
}
|
||||
|
||||
fn verify_confined_worktree_subdir(canon_wt_root: &Path, target_cwd: &Path) -> IdeResult<PathBuf> {
|
||||
let canon_cwd = dunce::canonicalize(target_cwd)?;
|
||||
let real_wt = ide_core::real_path::resolve_real(canon_wt_root);
|
||||
let real_cwd = ide_core::real_path::resolve_real(target_cwd);
|
||||
if !canon_cwd.starts_with(canon_wt_root)
|
||||
|| !real_cwd.starts_with(&real_wt)
|
||||
|| ide_core::real_path::reaches_git_dir(&real_wt, &real_cwd)
|
||||
{
|
||||
return Err(IdeError::invalid(format!(
|
||||
"worktree working directory {} resolves outside worktree {}",
|
||||
target_cwd.display(),
|
||||
canon_wt_root.display()
|
||||
)));
|
||||
}
|
||||
Ok(canon_cwd)
|
||||
}
|
||||
|
||||
/// Canonicalizes `cwd` of an existing `Isolation::Worktree` task and verifies that it still
|
||||
/// resolves strictly inside its own worktree checkout root under `worktrees_dir` (preventing
|
||||
/// symlink escapes on reused sessions/turns).
|
||||
pub(crate) fn verify_confined_worktree_cwd(worktrees_dir: &Path, cwd: &Path) -> IdeResult<PathBuf> {
|
||||
let (wt_root, wt_base) = worktree_checkout_root(worktrees_dir, cwd);
|
||||
if !wt_root.starts_with(&wt_base) || wt_root == wt_base {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"worktree working directory {} is outside managed worktrees directory {}",
|
||||
cwd.display(),
|
||||
worktrees_dir.display()
|
||||
)));
|
||||
}
|
||||
let canon_wt_root = dunce::canonicalize(&wt_root)?;
|
||||
let canon_wt_dir = dunce::canonicalize(worktrees_dir)?;
|
||||
if !canon_wt_root.starts_with(&canon_wt_dir)
|
||||
|| canon_wt_root == canon_wt_dir
|
||||
|| canon_wt_root.parent() != Some(canon_wt_dir.as_path())
|
||||
{
|
||||
return Err(IdeError::invalid("worktree checkout root escaped managed worktrees directory"));
|
||||
}
|
||||
verify_confined_worktree_subdir(&canon_wt_root, cwd)
|
||||
}
|
||||
|
||||
/// Returns a canonical comparison key for the managed worktree checkout root containing `path`,
|
||||
/// so two tasks pointing to different subdirs or path casings of the same worktree match.
|
||||
pub(crate) fn shared_worktree_root(worktrees_dir: &Path, path: &Path) -> PathBuf {
|
||||
let (root, _) = worktree_checkout_root(worktrees_dir, path);
|
||||
let resolved = dunce::canonicalize(&root).unwrap_or(root);
|
||||
normalize_path_key(resolved)
|
||||
}
|
||||
|
||||
pub(crate) fn normalize_path_key(path: PathBuf) -> PathBuf {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
PathBuf::from(path.to_string_lossy().replace('/', "\\").to_lowercase())
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
path
|
||||
}
|
||||
}
|
||||
|
||||
fn first_child_under(base: &Path, path: &Path) -> Option<PathBuf> {
|
||||
if let Ok(rel) = path.strip_prefix(base)
|
||||
&& let Some(first) = rel.components().next()
|
||||
{
|
||||
return Some(base.join(first));
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
let base_comps: Vec<String> =
|
||||
base.components().map(|c| c.as_os_str().to_string_lossy().to_lowercase()).collect();
|
||||
let path_comps: Vec<std::path::Component<'_>> = path.components().collect();
|
||||
if path_comps.len() > base_comps.len()
|
||||
&& base_comps
|
||||
.iter()
|
||||
.zip(path_comps.iter())
|
||||
.all(|(a, b)| a == &b.as_os_str().to_string_lossy().to_lowercase())
|
||||
{
|
||||
return Some(base.join(path_comps[base_comps.len()]));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn worktree_checkout_root(worktrees_dir: &Path, path: &Path) -> (PathBuf, PathBuf) {
|
||||
if let Some(child) = first_child_under(worktrees_dir, path) {
|
||||
return (child, worktrees_dir.to_path_buf());
|
||||
}
|
||||
if let Ok(canon_wt_dir) = dunce::canonicalize(worktrees_dir) {
|
||||
if let Some(child) = first_child_under(&canon_wt_dir, path) {
|
||||
return (child, canon_wt_dir);
|
||||
}
|
||||
if let Ok(canon_path) = dunce::canonicalize(path)
|
||||
&& let Some(child) = first_child_under(&canon_wt_dir, &canon_path)
|
||||
{
|
||||
return (child, canon_wt_dir);
|
||||
}
|
||||
}
|
||||
(path.to_path_buf(), worktrees_dir.to_path_buf())
|
||||
Ok(Created { path, branch, base, base_commit })
|
||||
}
|
||||
|
||||
/// `git worktree remove --force -- <path>`. When git no longer recognizes the
|
||||
@@ -474,94 +186,19 @@ fn worktree_checkout_root(worktrees_dir: &Path, path: &Path) -> (PathBuf, PathBu
|
||||
/// ours, so it is removed directly to keep the task deletable (a stale
|
||||
/// registration prunes later); anything else keeps git's error.
|
||||
pub(crate) fn remove(project_root: &Path, worktrees_dir: &Path, path: &Path) -> IdeResult<()> {
|
||||
let (target, wt_base) = worktree_checkout_root(worktrees_dir, path);
|
||||
let repo = repo_at(project_root)?;
|
||||
let err = match repo.remove_worktree(&target, true) {
|
||||
let err = match repo.remove_worktree(path, true) {
|
||||
Ok(()) => return Ok(()),
|
||||
Err(e) => e,
|
||||
};
|
||||
if !target.exists() {
|
||||
if !path.exists() {
|
||||
return Ok(());
|
||||
}
|
||||
if !target.starts_with(&wt_base) || target == wt_base {
|
||||
if !path.starts_with(worktrees_dir) || path == worktrees_dir {
|
||||
return Err(err);
|
||||
}
|
||||
retrying(REMOVE_ATTEMPTS, REMOVE_PAUSE, || std::fs::remove_dir_all(&target))
|
||||
.map_err(|e| IdeError::internal(format!("{}: {e}", target.display())))
|
||||
}
|
||||
|
||||
/// Safely removes an automation worktree ONLY after verifying its private `git_dir` ownership
|
||||
/// marker (`openidea-worktree.json`) matches `task_id` and `worktrees_dir`.
|
||||
///
|
||||
/// - When `require_clean` is `true` (zero-diff GC): verifies `HEAD == base_commit` and both the
|
||||
/// Git index (staged) and working tree (unstaged + untracked) are completely clean right before
|
||||
/// running **non-forced** `git worktree remove` (`force = false`). Returns `Ok(false)` without
|
||||
/// modifying disk if the worktree has any commits, staged changes, unstaged edits, or untracked
|
||||
/// files.
|
||||
/// - Never falls back to `remove_dir_all` on any ownership or Git error: any error keeps the
|
||||
/// checkout intact.
|
||||
pub(crate) fn remove_owned_automation_worktree(
|
||||
project_root: &Path,
|
||||
worktrees_dir: &Path,
|
||||
cwd: &Path,
|
||||
task_id: &str,
|
||||
base_commit: Option<&str>,
|
||||
require_clean: bool,
|
||||
) -> IdeResult<bool> {
|
||||
if !cwd.exists() || !worktrees_dir.exists() {
|
||||
return Ok(false);
|
||||
}
|
||||
let canon_worktrees = dunce::canonicalize(worktrees_dir)?;
|
||||
let canon_cwd = dunce::canonicalize(cwd)?;
|
||||
if !canon_cwd.starts_with(&canon_worktrees) || canon_cwd == canon_worktrees {
|
||||
return Err(IdeError::invalid("refusing to clean worktree outside managed worktrees directory"));
|
||||
}
|
||||
let main_repo = repo_at(project_root)?;
|
||||
let wt_repo = repo_at(&canon_cwd)?;
|
||||
let canon_wt_root = dunce::canonicalize(wt_repo.root())?;
|
||||
if !canon_wt_root.starts_with(&canon_worktrees)
|
||||
|| canon_wt_root == canon_worktrees
|
||||
|| canon_wt_root.parent() != Some(canon_worktrees.as_path())
|
||||
{
|
||||
return Err(IdeError::invalid("worktree root does not match managed worktrees directory"));
|
||||
}
|
||||
let [git_dir, wt_common] = wt_repo.metadata_dirs()?;
|
||||
let [_, main_common] = main_repo.metadata_dirs()?;
|
||||
let canon_git_dir = dunce::canonicalize(&git_dir)?;
|
||||
let canon_wt_common = dunce::canonicalize(&wt_common)?;
|
||||
let canon_main_common = dunce::canonicalize(&main_common)?;
|
||||
if canon_git_dir == canon_wt_common || canon_wt_common != canon_main_common {
|
||||
return Err(IdeError::invalid("target checkout is not a linked worktree of this repository"));
|
||||
}
|
||||
let marker_bytes = std::fs::read(canon_git_dir.join(OWNERSHIP_MARKER))
|
||||
.map_err(|_| IdeError::invalid("refusing to remove worktree without OpenIDEA ownership marker"))?;
|
||||
let marker: WorktreeOwnership = serde_json::from_slice(&marker_bytes)
|
||||
.map_err(|_| IdeError::invalid("corrupt OpenIDEA worktree ownership marker"))?;
|
||||
let marker_root = dunce::canonicalize(&marker.worktree_root).unwrap_or(marker.worktree_root);
|
||||
if marker.owner != OWNERSHIP_TAG || marker.task_id != task_id || marker_root != canon_wt_root {
|
||||
return Err(IdeError::invalid("worktree ownership marker does not match task"));
|
||||
}
|
||||
|
||||
if require_clean {
|
||||
let Some(base) = base_commit else {
|
||||
return Ok(false);
|
||||
};
|
||||
if wt_repo.head()?.1.as_deref() != Some(base) {
|
||||
return Ok(false);
|
||||
}
|
||||
// `status()` checks BOTH HEAD↔index (staged) and index↔worktree (unstaged + untracked).
|
||||
if !wt_repo.status()?.is_empty() {
|
||||
return Ok(false);
|
||||
}
|
||||
if !wt_repo.diff_with_worktree(base)?.is_empty() {
|
||||
return Ok(false);
|
||||
}
|
||||
main_repo.remove_worktree(&canon_wt_root, false)?;
|
||||
return Ok(true);
|
||||
}
|
||||
|
||||
main_repo.remove_worktree(&canon_wt_root, true)?;
|
||||
Ok(true)
|
||||
retrying(REMOVE_ATTEMPTS, REMOVE_PAUSE, || std::fs::remove_dir_all(path))
|
||||
.map_err(|e| IdeError::internal(format!("{}: {e}", path.display())))
|
||||
}
|
||||
|
||||
/// On Windows a folder can't be deleted while a process still has a file in it open
|
||||
@@ -2307,235 +1944,4 @@ mod tests {
|
||||
changed.sort();
|
||||
assert_eq!(changed, ["edited", "new", "reverted"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn owned_worktree_cleanup_preserves_subproject_cwd_catches_staged_changes_and_verifies_ownership() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let repo = tmp.path().join("repo");
|
||||
let sub = repo.join("packages").join("subapp");
|
||||
std::fs::create_dir_all(&sub).unwrap();
|
||||
git(&repo, &["init", "-q", "-b", "main"]);
|
||||
git(&repo, &["config", "core.autocrlf", "false"]);
|
||||
std::fs::write(repo.join("root.txt"), "root\n").unwrap();
|
||||
std::fs::write(sub.join("index.ts"), "export const x = 1;\n").unwrap();
|
||||
git(&repo, &["add", "."]);
|
||||
git(&repo, &["commit", "-q", "-m", "init"]);
|
||||
|
||||
let wt_dir = tmp.path().join("wt");
|
||||
let created = create_for_task(&sub, &wt_dir, "task-1", "Sub Audit", None).unwrap();
|
||||
assert_eq!(
|
||||
dunce::canonicalize(&created.cwd).unwrap(),
|
||||
dunce::canonicalize(&created.path).unwrap().join("packages").join("subapp"),
|
||||
"project-relative cwd inside parent repo must be preserved inside worktree"
|
||||
);
|
||||
|
||||
// Wrong task_id is refused and keeps the checkout untouched.
|
||||
assert!(
|
||||
remove_owned_automation_worktree(
|
||||
&sub,
|
||||
&wt_dir,
|
||||
&created.cwd,
|
||||
"wrong-task",
|
||||
Some(&created.base_commit),
|
||||
true,
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
assert!(created.path.exists());
|
||||
|
||||
// Staged-only change (index differs from HEAD while working tree matches HEAD!) is NOT clean!
|
||||
std::fs::write(created.cwd.join("index.ts"), "export const x = 2;\n").unwrap();
|
||||
git(&created.path, &["add", "packages/subapp/index.ts"]);
|
||||
std::fs::write(created.cwd.join("index.ts"), "export const x = 1;\n").unwrap();
|
||||
let removed_staged =
|
||||
remove_owned_automation_worktree(&sub, &wt_dir, &created.cwd, "task-1", Some(&created.base_commit), true)
|
||||
.unwrap();
|
||||
assert!(!removed_staged, "staged-only index change must prevent zero-diff worktree GC");
|
||||
assert!(created.path.exists());
|
||||
|
||||
// Reset index back to HEAD -> zero-diff GC removes the worktree via non-forced `git worktree remove`.
|
||||
git(&created.path, &["reset", "-q", "HEAD", "--", "packages/subapp/index.ts"]);
|
||||
let removed_clean =
|
||||
remove_owned_automation_worktree(&sub, &wt_dir, &created.cwd, "task-1", Some(&created.base_commit), true)
|
||||
.unwrap();
|
||||
assert!(removed_clean);
|
||||
assert!(!created.path.exists());
|
||||
|
||||
// Foreign / manually created git worktree inside `wt_dir` without ownership marker is NEVER deleted.
|
||||
let manual_wt = wt_dir.join("foreign");
|
||||
git(&repo, &["worktree", "add", "-q", "-b", "manual-branch", manual_wt.to_str().unwrap(), "HEAD"]);
|
||||
assert!(
|
||||
remove_owned_automation_worktree(&repo, &wt_dir, &manual_wt, "task-2", Some(&created.base_commit), false,)
|
||||
.is_err()
|
||||
);
|
||||
assert!(manual_wt.exists(), "worktree without OpenIDEA ownership marker must never be deleted");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn symlinked_subproject_cwd_escaping_worktree_is_rejected_on_create_and_reuse() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let outside = tmp.path().join("outside");
|
||||
std::fs::create_dir_all(&outside).unwrap();
|
||||
std::fs::write(outside.join("secret.txt"), "nope\n").unwrap();
|
||||
|
||||
let repo = tmp.path().join("repo");
|
||||
let packages = repo.join("packages");
|
||||
std::fs::create_dir_all(&packages).unwrap();
|
||||
git(&repo, &["init", "-q", "-b", "main"]);
|
||||
git(&repo, &["config", "core.autocrlf", "false"]);
|
||||
|
||||
// 1a. Direct symlink pointing outside git is rejected immediately.
|
||||
let escape_link = packages.join("escape");
|
||||
std::os::unix::fs::symlink(&outside, &escape_link).unwrap();
|
||||
git(&repo, &["add", "."]);
|
||||
git(&repo, &["commit", "-q", "-m", "symlink escape"]);
|
||||
|
||||
let wt_dir = tmp.path().join("wt");
|
||||
assert!(create_for_task(&escape_link, &wt_dir, "task-escape-direct", "Escape", None).is_err());
|
||||
|
||||
// 1b. Committed symlink in `HEAD` (`packages/tricky -> ../../outside`) while the main
|
||||
// checkout temporarily has a real directory at `packages/tricky`: `git worktree add`
|
||||
// checks out `HEAD`'s symlink inside the worktree, and `verify_confined_worktree_subdir`
|
||||
// must catch the escape and clean up the worktree!
|
||||
let tricky = packages.join("tricky");
|
||||
std::os::unix::fs::symlink(&outside, &tricky).unwrap();
|
||||
git(&repo, &["add", "."]);
|
||||
git(&repo, &["commit", "-q", "-m", "committed tricky symlink"]);
|
||||
std::fs::remove_file(&tricky).unwrap();
|
||||
std::fs::create_dir_all(&tricky).unwrap();
|
||||
|
||||
let Err(err) = create_for_task(&tricky, &wt_dir, "task-escape-head", "Tricky", None) else {
|
||||
panic!("expected committed symlink escaping worktree root to be rejected");
|
||||
};
|
||||
assert!(
|
||||
err.to_string().contains("outside worktree") || err.to_string().contains("escapes worktree root"),
|
||||
"unexpected error for committed symlink cwd: {err}"
|
||||
);
|
||||
|
||||
// 2. Normal directory at creation time, later replaced with an escaping symlink before reuse,
|
||||
// must be rejected by `verify_confined_worktree_cwd`!
|
||||
let legit_sub = packages.join("legit");
|
||||
std::fs::create_dir_all(&legit_sub).unwrap();
|
||||
std::fs::write(legit_sub.join("ok.txt"), "ok\n").unwrap();
|
||||
git(&repo, &["add", "."]);
|
||||
git(&repo, &["commit", "-q", "-m", "legit sub"]);
|
||||
|
||||
let created = create_for_task(&legit_sub, &wt_dir, "task-reuse", "Legit", None).unwrap();
|
||||
let verified = super::verify_confined_worktree_cwd(&wt_dir, &created.cwd).unwrap();
|
||||
assert!(verified.starts_with(dunce::canonicalize(&created.path).unwrap()));
|
||||
|
||||
std::fs::remove_dir_all(&created.cwd).unwrap();
|
||||
std::os::unix::fs::symlink(&outside, &created.cwd).unwrap();
|
||||
let reuse_err = super::verify_confined_worktree_cwd(&wt_dir, &created.cwd).unwrap_err();
|
||||
assert!(
|
||||
reuse_err.to_string().contains("outside worktree") || reuse_err.to_string().contains("escapes"),
|
||||
"symlink swap on worktree reuse must be rejected: {reuse_err}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reuse_for_task_validates_confinement_and_repo_membership() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let repo = tmp.path().join("repo");
|
||||
std::fs::create_dir_all(&repo).unwrap();
|
||||
git(&repo, &["init", "-q", "-b", "main"]);
|
||||
std::fs::write(repo.join("a.txt"), "hello\n").unwrap();
|
||||
git(&repo, &["add", "."]);
|
||||
git(&repo, &["commit", "-q", "-m", "init"]);
|
||||
|
||||
let other = tmp.path().join("other");
|
||||
std::fs::create_dir_all(&other).unwrap();
|
||||
git(&other, &["init", "-q", "-b", "main"]);
|
||||
std::fs::write(other.join("b.txt"), "world\n").unwrap();
|
||||
git(&other, &["add", "."]);
|
||||
git(&other, &["commit", "-q", "-m", "init other"]);
|
||||
|
||||
let wt_dir = tmp.path().join("wt");
|
||||
let created = create_for_task(&repo, &wt_dir, "task-1", "Feature work", None).unwrap();
|
||||
|
||||
// Reusing a managed worktree of the same repository succeeds and reports its live branch.
|
||||
let reused = super::reuse_for_task(&repo, &wt_dir, &created.cwd).unwrap();
|
||||
assert_eq!(reused.cwd, created.cwd);
|
||||
assert_eq!(reused.branch, created.branch);
|
||||
assert_eq!(reused.base_commit, created.base_commit);
|
||||
|
||||
// Paths outside `worktrees_dir` are rejected.
|
||||
assert!(super::reuse_for_task(&repo, &wt_dir, &repo).is_err());
|
||||
|
||||
// Worktrees belonging to a different repository are rejected.
|
||||
let other_wt = create_for_task(&other, &wt_dir, "task-2", "Other work", None).unwrap();
|
||||
assert!(super::reuse_for_task(&repo, &wt_dir, &other_wt.cwd).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn checkout_branch_creates_and_switches_branches_in_worktree() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let repo = tmp.path().join("repo");
|
||||
std::fs::create_dir_all(&repo).unwrap();
|
||||
git(&repo, &["init", "-q", "-b", "main"]);
|
||||
std::fs::write(repo.join("a.txt"), "hello\n").unwrap();
|
||||
git(&repo, &["add", "."]);
|
||||
git(&repo, &["commit", "-q", "-m", "init"]);
|
||||
|
||||
let wt_dir = tmp.path().join("wt");
|
||||
let created = create_for_task(&repo, &wt_dir, "task-1", "Feature work", None).unwrap();
|
||||
|
||||
let (branch, head_commit, outcome) = super::checkout_branch(&created.cwd, "feat/follow-up", true).unwrap();
|
||||
assert_eq!(outcome, ide_vcs::CheckoutOutcome::Done);
|
||||
assert_eq!(branch, "feat/follow-up");
|
||||
assert_eq!(head_commit.as_deref(), Some(created.base_commit.as_str()));
|
||||
|
||||
let (back, back_commit, outcome) = super::checkout_branch(&created.cwd, &created.branch, false).unwrap();
|
||||
assert_eq!(outcome, ide_vcs::CheckoutOutcome::Done);
|
||||
assert_eq!(back, created.branch);
|
||||
assert_eq!(back_commit.as_deref(), Some(created.base_commit.as_str()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reuse_for_task_resolves_subdir_consistently_and_rejects_standalone_repo() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let repo = tmp.path().join("repo");
|
||||
let sub = repo.join("packages").join("app");
|
||||
std::fs::create_dir_all(&sub).unwrap();
|
||||
git(&repo, &["init", "-q", "-b", "main"]);
|
||||
std::fs::write(sub.join("a.txt"), "hello\n").unwrap();
|
||||
git(&repo, &["add", "."]);
|
||||
git(&repo, &["commit", "-q", "-m", "init"]);
|
||||
|
||||
let wt_dir = tmp.path().join("wt");
|
||||
let created = create_for_task(&sub, &wt_dir, "task-sub", "Subdir work", None).unwrap();
|
||||
assert!(created.cwd.ends_with(Path::new("packages").join("app")));
|
||||
|
||||
// Passing either the worktree root or the subdir cwd resolves to the same subdir cwd.
|
||||
let reused_from_root = super::reuse_for_task(&sub, &wt_dir, &created.path).unwrap();
|
||||
assert_eq!(reused_from_root.cwd, created.cwd);
|
||||
assert_eq!(reused_from_root.path, dunce::canonicalize(&created.path).unwrap());
|
||||
|
||||
let reused_from_sub = super::reuse_for_task(&sub, &wt_dir, &created.cwd).unwrap();
|
||||
assert_eq!(reused_from_sub.cwd, created.cwd);
|
||||
|
||||
// `shared_worktree_root` matches root and subdir (and mixed casing on Windows).
|
||||
assert_eq!(
|
||||
super::shared_worktree_root(&wt_dir, &created.path),
|
||||
super::shared_worktree_root(&wt_dir, &created.cwd)
|
||||
);
|
||||
#[cfg(windows)]
|
||||
{
|
||||
let upper = PathBuf::from(created.cwd.to_string_lossy().to_uppercase());
|
||||
assert_eq!(
|
||||
super::shared_worktree_root(&wt_dir, &created.path),
|
||||
super::shared_worktree_root(&wt_dir, &upper)
|
||||
);
|
||||
}
|
||||
|
||||
// A standalone repo placed directly inside `worktrees_dir` (not a linked worktree) is rejected.
|
||||
let standalone = wt_dir.join("standalone");
|
||||
std::fs::create_dir_all(&standalone).unwrap();
|
||||
git(&standalone, &["init", "-q", "-b", "main"]);
|
||||
std::fs::write(standalone.join("x.txt"), "x\n").unwrap();
|
||||
git(&standalone, &["add", "."]);
|
||||
git(&standalone, &["commit", "-q", "-m", "standalone"]);
|
||||
assert!(super::reuse_for_task(&standalone, &wt_dir, &standalone).is_err());
|
||||
}
|
||||
}
|
||||
+111
-107
@@ -1,108 +1,112 @@
|
||||
{"launch":["--model","haiku","-p","--input-format","stream-json","--output-format","stream-json","--verbose","--permission-prompt-tool","stdio","--include-partial-messages","--thinking-display","summarized","--allow-dangerously-skip-permissions","--session-id","a89e008b-23b6-41ea-bebb-612440f38e3c"]}
|
||||
{"from":"shim","msg":{"request":{"perTaskStopAffordance":true,"subtype":"initialize"},"request_id":"req_1","type":"control_request"}}
|
||||
{"from":"cli","msg":{"response":{"pending_permission_requests":[],"pending_user_dialog_requests":[],"request_id":"req_1","response":{"analytics_disabled":false,"capabilities":["ui_surface_v1","mcp_call_result_not_for_model_v1","mcp_call_soft_error_result_v1","mcp_call_check_permissions_v1","voice_call_talk_line_v1","ui_pane_widget_v1","reload_plugins_refuse_if_busy_v1","get_usage_detached_v1"],"claude_code_version":"2.1.335","commands":[{"argumentHint":"","description":"Review a pull request","name":"review"},{"argumentHint":"","description":"Write a CLAUDE.md","name":"init"}],"current_permission_mode":"default","fast_mode_state":"off","feedback_mode":{"kind":"post"},"hook_on_failure_supported":true,"hooks_when_unanswered_kept":0,"ide_rc_auto_enable_gate":true,"models":[{"description":"Opus 5.5 · Best for everyday, complex tasks","displayName":"Default (recommended)","resolvedModel":"claude-opus-5-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsFastMode":true,"supportsThinkingOff":false,"value":"default"},{"description":"For complex work and everyday tasks","displayName":"Opus 5.5","resolvedModel":"claude-opus-5-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsFastMode":true,"supportsThinkingOff":false,"value":"opus"},{"description":"For your toughest challenges","displayName":"Fable 5.2","resolvedModel":"claude-fable-5-2","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsFastMode":true,"supportsThinkingOff":false,"value":"fable"},{"description":"Most efficient for simpler tasks","displayName":"Sonnet 5.5","resolvedModel":"claude-sonnet-5-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":false,"value":"sonnet"},{"description":"Fastest for quick answers","displayName":"Haiku 5.5","resolvedModel":"claude-haiku-5-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":false,"value":"haiku"},{"description":"Most capable for your hardest and longest-running tasks","displayName":"Fable 5.1","overflow":true,"resolvedModel":"claude-fable-5-1","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":false,"value":"claude-fable-5-1"},{"description":"Fastest for quick answers","displayName":"Haiku 4.5","overflow":true,"resolvedModel":"claude-haiku-4-5-20251001","supportsThinkingOff":true,"value":"claude-haiku-4-5-20251001"},{"description":"Efficient for routine tasks","displayName":"Sonnet 5","overflow":true,"resolvedModel":"claude-sonnet-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":true,"value":"claude-sonnet-5"},{"description":"Best for everyday, complex tasks","displayName":"Opus 5","overflow":true,"resolvedModel":"claude-opus-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsFastMode":true,"supportsThinkingOff":true,"value":"claude-opus-5"},{"description":"Most capable for your hardest and longest-running tasks","displayName":"Fable 5","overflow":true,"resolvedModel":"claude-fable-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":false,"value":"claude-fable-5"},{"description":"Best for everyday, complex tasks","displayName":"Opus 4.8","overflow":true,"resolvedModel":"claude-opus-4-8","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsFastMode":true,"supportsThinkingOff":true,"value":"claude-opus-4-8"},{"description":"Best for everyday, complex tasks","displayName":"Opus 4.7","overflow":true,"resolvedModel":"claude-opus-4-7","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":true,"value":"claude-opus-4-7"},{"description":"Best for everyday, complex tasks","displayName":"Opus 4.6","overflow":true,"resolvedModel":"claude-opus-4-6","supportedEffortLevels":["low","medium","high","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":true,"value":"claude-opus-4-6"},{"description":"Efficient for routine tasks","displayName":"Sonnet 4.6","overflow":true,"resolvedModel":"claude-sonnet-4-6","supportedEffortLevelsLine truncated
|
||||
{"launch":["--model","haiku","-p","--input-format","stream-json","--output-format","stream-json","--verbose","--permission-prompt-tool","stdio","--include-partial-messages","--thinking-display","summarized","--allow-dangerously-skip-permissions","--session-id","5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6"]}
|
||||
{"from":"shim","msg":{"request":{"subtype":"initialize"},"request_id":"req_1","type":"control_request"}}
|
||||
{"from":"cli","msg":{"response":{"pending_permission_requests":[],"pending_user_dialog_requests":[],"request_id":"req_1","response":{"analytics_disabled":false,"capabilities":["ui_surface_v1","mcp_call_result_not_for_model_v1"],"claude_code_version":"2.1.312","commands":[{"argumentHint":"","description":"Review a pull request","name":"review"},{"argumentHint":"","description":"Write a CLAUDE.md","name":"init"}],"current_permission_mode":"default","fast_mode_disabled_reason":"sdk_opt_in_required","fast_mode_state":"off","feedback_mode":{"kind":"post"},"ide_rc_auto_enable_gate":true,"models":[{"description":"Sonnet 5.5 · Efficient for routine tasks","displayName":"Default (recommended)","resolvedModel":"claude-sonnet-5-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":false,"value":"default"},{"description":"For complex work and everyday tasks","displayName":"Opus 5.5","resolvedModel":"claude-opus-5-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsFastMode":true,"supportsThinkingOff":false,"value":"opus"},{"description":"For your toughest challenges","displayName":"Fable 5.1","resolvedModel":"claude-fable-5-1","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":false,"value":"fable"},{"description":"Most efficient for simpler tasks","displayName":"Sonnet 5.5","resolvedModel":"claude-sonnet-5-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":false,"value":"sonnet"},{"description":"Fastest for quick answers","displayName":"Haiku 5.5","resolvedModel":"claude-haiku-5-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":false,"value":"haiku"},{"description":"Fastest for quick answers","displayName":"Haiku 4.5","resolvedModel":"claude-haiku-4-5-20251001","supportsThinkingOff":true,"value":"claude-haiku-4-5-20251001"},{"description":"Efficient for routine tasks","displayName":"Sonnet 5","resolvedModel":"claude-sonnet-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":true,"value":"claude-sonnet-5"},{"description":"Best for everyday, complex tasks","displayName":"Opus 5","resolvedModel":"claude-opus-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsFastMode":true,"supportsThinkingOff":true,"value":"claude-opus-5"},{"description":"Most capable for your hardest and longest-running tasks","displayName":"Fable 5","resolvedModel":"claude-fable-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":false,"value":"claude-fable-5"},{"description":"Best for everyday, complex tasks","displayName":"Opus 4.8","resolvedModel":"claude-opus-4-8","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsFastMode":true,"supportsThinkingOff":true,"value":"claude-opus-4-8"},{"description":"Best for everyday, complex tasks","displayName":"Opus 4.7","resolvedModel":"claude-opus-4-7","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":true,"value":"claude-opus-4-7"},{"description":"Best for everyday, complex tasks","displayName":"Opus 4.6","resolvedModel":"claude-opus-4-6","supportedEffortLevels":["low","medium","high","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":true,"value":"claude-opus-4-6"},{"description":"Efficient for routine tasks","displayName":"Sonnet 4.6","resolvedModel":"claude-sonnet-4-6","supportedEffortLevels":["low","medium","high","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":true,"value":"claude-sonnet-4-6"}],"pid":23982,"remote_control_auto_connect_default":false,"remote_control_auto_enable":false,"remote_control_auto_on_by_default":false,"remote_control_available":true,"session_state":"idle"},"subtype":"success"},"type":"control_response"}}
|
||||
{"from":"shim","msg":{"request":{"subtype":"get_settings"},"request_id":"req_2","type":"control_request"}}
|
||||
{"from":"cli","msg":{"response":{"request_id":"req_2","response":{"applied":{"advisor":null,"apiProvider":"firstParty","effort":"medium","launchEnvLeftOwnFilesInPlace":false,"model":"claude-haiku-5-5","outsideBlocksCountLaunchFoldersOnly":false,"outsideFileToolReadsBlocked":false,"outsideFileToolWritesBlocked":false,"ultracode":false,"ultracodeAvailable":true,"ultracodeRequested":false,"ultrathinkAvailable":false},"effective":{"model":null}},"subtype":"success"},"type":"control_response"}}
|
||||
{"from":"shim","msg":{"message":{"content":[{"text":"Run the Bash command `sleep 3 && echo done`, then tell me its output in one line.","type":"text"}],"role":"user"},"origin":{"kind":"human"},"parent_tool_use_id":null,"session_id":"","type":"user","uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d"}}
|
||||
{"from":"cli","msg":{"command_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","state":"queued","type":"command_lifecycle","uuid":"e745940b-18ac-4078-b11e-72be2ae6401b","written_at":"2026-12-03T13:51:32.578Z"}}
|
||||
{"from":"cli","msg":{"command_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","state":"started","type":"command_lifecycle","uuid":"f85c6752-6469-4ce7-bbb2-0349f3fabfa8","written_at":"2026-12-03T13:51:32.579Z"}}
|
||||
{"from":"cli","msg":{"additional_directories":[],"analytics_disabled":false,"apiKeySource":"none","capabilities":["interrupt_receipt_v1","interrupt_cancel_queued_v1","interrupt_send_now_v1","interrupt_requeue_taken_v1","msg_lifecycle_v1","request_marker_lists_v1","ask_user_question_unanswered_v1","lifecycle_wakeup_source_v1","sdk_mcp_tools_list_changed","sdk_mcp_manifests","mcp_read_resource_v1","mcp_tool_ui_meta_v1","ui_surface_v1","mcp_call_result_not_for_model_v1","mcp_call_soft_error_result_v1","mcp_call_check_permissions_v1","voice_call_talk_line_v1","withdrawn_files_note_v2","withdrawn_tools_v1","ui_pane_widget_v1","reload_plugins_refuse_if_busy_v1","get_usage_detached_v1","silent_resend_files_v1","lifecycle_idle_v1","comment_images_v1"],"claude_code_version":"2.1.335","cwd":"/private/var/folders/vh/wtcmszn53mvbqcdfy6xrrg5w0000gn/T/.tmpX66GLs","fast_mode_state":"off","model":"claude-haiku-5-5","original_cwd":"/private/var/folders/vh/wtcmszn53mvbqcdfy6xrrg5w0000gn/T/.tmpX66GLs","output_style":"default","per_turn_effort_active":true,"permissionMode":"default","product_feedback_disabled":false,"sandbox_enabled":false,"scratchpad_path":"/private/tmp/claude-501/s/992375695253/scratchpad","served_by_anthropic":true,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","startup_timing":{"entrypoint":"claude-vscode","flag_fetch_kick":"not_eligible","flag_fetch_kick_judged_at_ms":84,"hooks_init_origin_ms":{"official_plugin":69,"other_plugin":17,"user_settings":37},"hooks_init_source":"startup","hooks_init_without_silent_ms":{"any":69,"own":69},"phase_start_ms":{"first_message_handle_ms":282,"first_message_read_ms":0,"grove_check_ms":187,"headless_post_load_ms":257,"headless_prologue_ms":186,"hooks_init_ms":178,"init_emit_ms":343,"initial_messages_load_ms":189,"input_ready_ms":0,"mcp_client_module_load_ms":192,"mcp_config_wait_ms":170,"mcp_connect_ms":182,"mcp_prewait_ms":283,"model_catalog_decision_ms":166,"node_boot_ms":0,"permission_context_ms":89,"pre_action_client_data_url_ms":84,"pre_action_init_ms":46,"pre_action_managed_settings_ms":84,"pre_action_mdm_keychain_ms":45,"pre_action_migrations_ms":84,"pre_action_ms":45,"print_import_ms":183,"prompt_submit_hooks_ms":301,"qe_plugin_skills_load_ms":341,"qe_system_prompt_ms":286,"sdk_mcp_update_ms":282,"settings_load_ms":44,"setup_file_watcher_ms":118,"setup_hooks_snapshot_ms":118,"setup_import_ms":93,"setup_ms":96,"setup_release_notes_ms":119,"setup_uds_dir_ms":96,"setup_uds_listen_ms":114,"setup_uds_messaging_ms":95,"setup_uds_publish_ms":117,"skills_load_ms":95,"tools_commands_load_ms":130},"phases":{"first_message_handle_cpu_ms":0,"first_message_handle_loop_lag_ms":0,"first_message_handle_ms":0,"first_message_read_ms":282,"grove_check_ms":1,"headless_post_load_ms":1,"headless_prologue_ms":2,"hooks_init_ms":78,"init_emit_ms":1,"initial_messages_load_ms":68,"input_ready_ms":265,"mcp_client_module_load_ms":0,"mcp_config_load_ms":62,"mcp_config_wait_ms":2,"mcp_connect_ms":1,"mcp_prewait_ms":0,"model_catalog_decision_ms":3,"node_boot_ms":43,"permission_context_ms":3,"pre_action_client_data_url_ms":0,"pre_action_init_ms":37,"pre_action_managed_settings_ms":1,"pre_action_mdm_keychain_ms":1,"pre_action_migrations_ms":0,"pre_action_ms":43,"print_import_ms":3,"prompt_submit_hooks_ms":37,"qe_plugin_skills_load_ms":1,"qe_system_prompt_ms":4,"sdk_mcp_update_ms":0,"settings_load_ms":0,"setup_file_watcher_ms":0,"setup_hooks_snapshot_ms":0,"setup_import_ms":0,"setup_ms":31,"setup_release_notes_ms":8,"setup_uds_dir_ms":18,"setup_uds_listen_ms":3,"setup_uds_messaging_ms":23,"setup_uds_publish_ms":0,"skills_load_ms":66,"tools_commands_load_ms":35},"plugin_full_loads":0,"sdk_mcp_dial_runs":0,"sdk_mcp_servers_dialed":0,"time_origin_ms":1796305892295.906,"user_context_builds":2,"warm_spare_claimed":false},"subtype":"init","terminal_slash_commands":["doctor","send-to-project","color","focus","reload-plugins"],"type":"system","ultrathink_available":false,"ultrathink_typed_raises":false,"user_message_uuids":["85d18ab2-e0be-452f-8db8-5f5cfa76152d"],"uuid":"488f600b-a63e-4882-99b1-8dcdfe076157","view_mode":"default","written_at":"2026-12-03T13:51:32.639Z"}}
|
||||
{"from":"cli","msg":{"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","status":"requesting","subtype":"status","type":"system","user_message_uuids":["85d18ab2-e0be-452f-8db8-5f5cfa76152d"],"uuid":"b6a40890-0e2f-40ab-afc9-8a609749d59e","written_at":"2026-12-03T13:51:32.642Z"}}
|
||||
{"from":"cli","msg":{"rate_limit_info":{"isUsingOverage":false,"overageDisabledReason":"out_of_credits","overageStatus":"rejected","rateLimitType":"five_hour","resetsAt":1796320200,"status":"allowed","unifiedWindows":{"five_hour":{"resetsAt":1796320200,"status":"allowed","utilization":0.21},"seven_day":{"resetsAt":1796889600,"status":"allowed","utilization":0.13}}},"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"rate_limit_event","uuid":"0cafd103-637f-4025-913d-3d23ec776453","written_at":"2026-12-03T13:51:33.412Z"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"message":{"container":null,"content":[],"context_management":null,"diagnostics":null,"id":"msg_011CheuFeb6zou7Nmj7hYFnf","input_transformations":[],"model":"claude-haiku-5-5","role":"assistant","stop_details":null,"stop_reason":null,"stop_sequence":null,"type":"message","usage":{"cache_creation":{"ephemeral_1h_input_tokens":16761,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":16761,"cache_read_input_tokens":26096,"inference_geo":"global","input_tokens":2,"output_tokens":8,"service_tier":"standard","speed":"standard"}},"type":"message_start"},"owed_rows":[],"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","ttft_ms":1089,"type":"stream_event","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","user_message_uuids":["85d18ab2-e0be-452f-8db8-5f5cfa76152d"],"uuid":"1eba9396-f0bb-4de5-8627-5cebfc962d2a"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"content_block":{"thinking":"","type":"thinking"},"index":0,"type":"content_block_start"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"8b5abf5f-2492-4471-b355-ffb886685b08"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":1,"estimated_tokens_delta":1,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"3df5ecdd-e701-43ab-8ad3-90428c0a9bf4"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"estimated_tokens":null,"thinking":"The","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"a78c66ea-06f0-4c08-93c3-073ac79ce208"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":3,"estimated_tokens_delta":2,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"58e5f0b8-1cae-4e6e-8142-28c83c20d09c"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"estimated_tokens":null,"thinking":" user w","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"a66bf075-7a36-4bb4-9b94-090567a1047e"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":5,"estimated_tokens_delta":2,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"c1baabcf-b72e-438b-8b98-42b628a6c14b"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"estimated_tokens":null,"thinking":"ants a","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"25f84cb1-9180-49b0-b722-0ae6617e00f5"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":11,"estimated_tokens_delta":6,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"9d1b3935-0637-45ca-a613-f1d02b08bf36"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"estimated_tokens":null,"thinking":" Bash command run. The","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"de8666db-803f-4a33-8cb2-9faa68ff3e2a"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":13,"estimated_tokens_delta":2,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"e0d0e6f0-dad3-4075-95d3-cf993ac621d9"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"estimated_tokens":null,"thinking":" session","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"85784fb7-e5a4-4e17-acb8-2018e82e8458"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":18,"estimated_tokens_delta":5,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"962c83d1-069c-4ff4-b27f-1199d1b3d1b9"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"estimated_tokens":null,"thinking":"-start hook points","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"bd405da7-abb7-443d-b309-ac6e805014ed"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":19,"estimated_tokens_delta":1,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"c77e142c-8284-48f4-b67f-24f6fd1cc99b"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"estimated_tokens":null,"thinking":" to","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"4957baf5-5e7a-4e23-bfe6-7bd1be56cee1"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":24,"estimated_tokens_delta":5,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"2f3e6875-f0b9-4da6-806b-6420f8e11801"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"estimated_tokens":null,"thinking":"ward skills, but n","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"ec0306de-6581-4dcb-8ef0-8bc9a2dffe5b"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":28,"estimated_tokens_delta":4,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"08432ff1-c798-4640-bb4e-9c6bcb1fa879"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"estimated_tokens":null,"thinking":"othing here cal","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"934bdb11-4eac-4db8-ba78-d751a132767a"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":33,"estimated_tokens_delta":5,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"b68b320e-d34a-4dd2-a52f-d4eb23b6e631"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"estimated_tokens":null,"thinking":"ls for one, so I'll","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"1a0911c3-5d56-4df6-a490-ca853de74fe0"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":40,"estimated_tokens_delta":7,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"a0659fe6-3f44-4ee7-8f28-86561a981c00"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"estimated_tokens":null,"thinking":" just run the command direct","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"d243b5f8-2ad4-4137-abc0-993b12b30faf"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":41,"estimated_tokens_delta":1,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"0ff88c48-df4d-4fb0-9e10-aad67ea6f912"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"estimated_tokens":null,"thinking":"ly.","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"43859418-f19d-4dab-b439-e24db14015f1"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":42,"estimated_tokens_delta":1,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"bcb9947d-4522-4206-bc6c-2fe20b0ee3f0"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"estimated_tokens":null,"thinking":"\n\n","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"480e67e5-6243-4a07-80dc-5e7218eea10d"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":198,"estimated_tokens_delta":156,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"72763f2b-38bb-45f8-b9b4-6dce76fe87dd"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"type":"signature_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"2c35aff5-f8f1-423d-ab16-a50fe7f92d2c"}}
|
||||
{"from":"cli","msg":{"message":{"container":null,"content":[{"thinking":"The user wants a Bash command run. The session-start hook points toward skills, but nothing here calls for one, so I'll just run the command directly.\n\n","type":"thinking"}],"context_management":null,"diagnostics":null,"id":"msg_011CheuFeb6zou7Nmj7hYFnf","input_transformations":[],"model":"claude-haiku-5-5","role":"assistant","stop_details":null,"stop_reason":null,"stop_sequence":null,"type":"message","usage":{"cache_creation":{"ephemeral_1h_input_tokens":16761,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":16761,"cache_read_input_tokens":26096,"inference_geo":"global","input_tokens":2,"output_tokens":8,"service_tier":"standard","speed":"standard"}},"parent_tool_use_id":null,"request_id":"req_011CheuFePCVDFQ6Zs47Mqbi","session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","thinking_duration_ms":1155,"timestamp":"2026-12-03T13:51:35.067Z","type":"assistant","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","user_message_uuids":["85d18ab2-e0be-452f-8db8-5f5cfa76152d"],"uuid":"f53249a7-87bb-48d3-8a4d-46fb2bc373c3"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"index":0,"type":"content_block_stop"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"50eafebf-1675-454d-b48d-4c33f9c46fd0"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"content_block":{"caller":{"type":"direct"},"id":"toolu_012tPQXDR9Kw59zBCFJqSuXP","input":{},"name":"Bash","type":"tool_use"},"index":1,"type":"content_block_start"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"df423477-fdd3-40b4-bd3f-a6e5e2f4285a"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"partial_json":"","type":"input_json_delta"},"index":1,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"2840ddf3-7a52-45a6-bcee-28d02c695ce1"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"partial_json":"{\"command\": \"sleep 3 && ech","type":"input_json_delta"},"index":1,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"f279d761-fe64-4811-ba7a-d3389c7fa1d6"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"partial_json":"o done","type":"input_json_delta"},"index":1,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"2d7cc471-fe87-49cc-975e-5aefe894bd35"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"partial_json":"\", \"description\": \"S","type":"input_json_delta"},"index":1,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"77a255b8-8924-4cd2-8239-13d56352e157"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"partial_json":"leep 3 seconds","type":"input_json_delta"},"index":1,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"5ddf158c-a8ed-475e-b425-4d6aa69d9216"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"partial_json":" then echo done","type":"input_json_delta"},"index":1,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"8c902fdc-adb0-4db8-91fd-a3c9f799193b"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"partial_json":"\"}","type":"input_json_delta"},"index":1,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"1019a3dc-64e5-4166-981a-f57347563c32"}}
|
||||
{"from":"cli","msg":{"message":{"container":null,"content":[{"caller":{"type":"direct"},"id":"toolu_012tPQXDR9Kw59zBCFJqSuXP","input":{"command":"sleep 3 && echo done","description":"Sleep 3 seconds then echo done"},"name":"Bash","type":"tool_use"}],"context_management":null,"diagnostics":null,"id":"msg_011CheuFeb6zou7Nmj7hYFnf","input_transformations":[],"model":"claude-haiku-5-5","role":"assistant","stop_details":null,"stop_reason":null,"stop_sequence":null,"type":"message","usage":{"cache_creation":{"ephemeral_1h_input_tokens":16761,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":16761,"cache_read_input_tokens":26096,"inference_geo":"global","input_tokens":2,"output_tokens":8,"service_tier":"standard","speed":"standard"}},"parent_tool_use_id":null,"request_id":"req_011CheuFePCVDFQ6Zs47Mqbi","session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","timestamp":"2026-12-03T13:51:35.072Z","type":"assistant","uuid":"717bc1de-feb1-41aa-81d7-3ac47c772112","wire_tool_inputs":{"toolu_012tPQXDR9Kw59zBCFJqSuXP":{"command":"sleep 3 && echo done","description":"Sleep 3 seconds then echo done"}}}}
|
||||
{"from":"shim","msg":{"message":{"content":[{"text":"Also end your answer with the word BANANA.","type":"text"}],"role":"user"},"origin":{"kind":"human"},"parent_tool_use_id":null,"priority":"next","session_id":"","type":"user","uuid":"5cf21cb4-f4c7-4360-8932-61818a8e57ee"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"index":1,"type":"content_block_stop"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"149df489-36d1-4db3-8f19-ae26b6733dc9"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"context_management":{"applied_edits":[]},"delta":{"container":null,"stop_details":null,"stop_reason":"tool_use","stop_sequence":null},"type":"message_delta","usage":{"cache_creation_input_tokens":16761,"cache_read_input_tokens":26096,"input_tokens":2,"iterations":[{"cache_creation":{"ephemeral_1h_input_tokens":16761,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":16761,"cache_read_input_tokens":26096,"input_tokens":2,"output_tokens":142,"type":"message"}],"output_tokens":142,"output_tokens_details":{"thinking_tokens":51}}},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"84156816-f10d-4dd6-8dca-f441fea39795"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"type":"message_stop"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"93925996-0953-4359-9383-f6db7885eb3f"}}
|
||||
{"from":"cli","msg":{"command_uuid":"5cf21cb4-f4c7-4360-8932-61818a8e57ee","session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","state":"queued","type":"command_lifecycle","uuid":"58a87b31-0fab-415d-b450-0ed1f58ec0bc","written_at":"2026-12-03T13:51:35.084Z"}}
|
||||
{"from":"cli","msg":{"content":"A hook gave no usable answer, so it didn't check this action.","hook_no_verdict":{"hook_event":"PreToolUse","timed_out":false,"tool_use_id":"toolu_012tPQXDR9Kw59zBCFJqSuXP"},"level":"warning","session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"informational","tag":"hook_no_verdict","type":"system","uuid":"1bb27652-e9f7-4277-8138-8840aa03937c","written_at":"2026-12-03T13:51:35.090Z"}}
|
||||
{"from":"cli","msg":{"description":"Sleep 3 seconds then echo done","is_backgrounded":false,"run_id":"0mx7m5ix4-f838229f","session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"task_started","task_id":"bzep4576h","task_type":"local_bash","tool_use_id":"toolu_012tPQXDR9Kw59zBCFJqSuXP","type":"system","uuid":"9f3e9fb8-34cd-4f9c-95f9-b4a7af80eb18","written_at":"2026-12-03T13:51:39.785Z"}}
|
||||
{"from":"cli","msg":{"duration_ms":3020,"output_file":"","run_id":"0mx7m5ix4-f838229f","session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","status":"completed","subtype":"task_notification","summary":"Sleep 3 seconds then echo done","task_id":"bzep4576h","tool_use_id":"toolu_012tPQXDR9Kw59zBCFJqSuXP","type":"system","uuid":"63898564-4e95-4aa3-8e90-7fc67025ddce","written_at":"2026-12-03T13:51:39.802Z"}}
|
||||
{"from":"cli","msg":{"message":{"content":[{"content":"done","is_error":false,"tool_use_id":"toolu_012tPQXDR9Kw59zBCFJqSuXP","type":"tool_result"}],"role":"user"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","timestamp":"2026-12-03T13:51:39.838Z","tool_result_meta":[{"id":"toolu_012tPQXDR9Kw59zBCFJqSuXP","permission_decision":{"decision":"accept","reason_type":"subcommandResults","source":"config"}}],"tool_use_result":{"interrupted":false,"isImage":false,"noOutputExpected":false,"stderr":"","stdout":"done"},"type":"user","uuid":"8103e7bc-d615-4e6a-9c31-c7d36db98577"}}
|
||||
{"from":"cli","msg":{"command_uuid":"5cf21cb4-f4c7-4360-8932-61818a8e57ee","session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","state":"started","type":"command_lifecycle","uuid":"93252284-65fe-4529-ba8f-485b97e6734a","written_at":"2026-12-03T13:51:39.892Z"}}
|
||||
{"from":"cli","msg":{"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","status":"requesting","subtype":"status","type":"system","user_message_uuids":["85d18ab2-e0be-452f-8db8-5f5cfa76152d","5cf21cb4-f4c7-4360-8932-61818a8e57ee"],"uuid":"1f01a672-b108-46e4-9637-57b2abd60258","written_at":"2026-12-03T13:51:39.892Z"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"message":{"container":null,"content":[],"context_management":null,"diagnostics":null,"id":"msg_011CheuGALWJsYSxwR2j7F3W","input_transformations":[],"model":"claude-haiku-5-5","role":"assistant","stop_details":null,"stop_reason":null,"stop_sequence":null,"type":"message","usage":{"cache_creation":{"ephemeral_1h_input_tokens":12165,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":12165,"cache_read_input_tokens":42857,"inference_geo":"global","input_tokens":2,"output_tokens":3,"service_tier":"standard","speed":"standard"}},"type":"message_start"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","ttft_ms":931,"type":"stream_event","uuid":"29de849c-06bb-40e5-a9ad-b70c2f061329"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"content_block":{"thinking":"","type":"thinking"},"index":0,"type":"content_block_start"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"92b49174-c189-466f-ad5d-5eea3b3afc2e"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":2,"estimated_tokens_delta":2,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"b8ec03ca-333f-4fac-a597-c43aa181360f"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"estimated_tokens":null,"thinking":"I need","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"ab10276f-535b-4f19-948c-3f31c090a94e"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":8,"estimated_tokens_delta":6,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"44beb4b3-366d-4725-8781-17a8ab0c2743"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"estimated_tokens":null,"thinking":" to make sure the answ","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"fa8db41b-008b-4779-8269-e3df396df9b2"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":10,"estimated_tokens_delta":2,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"58821ddd-b1aa-437b-b6ea-120c4a781f6b"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"estimated_tokens":null,"thinking":"er fin","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"a4b2ec90-2589-4308-b773-1d95de4e39ab"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":13,"estimated_tokens_delta":3,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"11a853c1-af93-4d0d-b600-e7f2e51a3a16"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"estimated_tokens":null,"thinking":"ishes with B","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"3a9a743b-6a39-4572-b86e-4b07355aad6c"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":17,"estimated_tokens_delta":4,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"42ca95a6-a59d-4e50-8633-8689136027ad"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"estimated_tokens":null,"thinking":"ANANA, and the","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"e1173332-7e42-470a-bba6-28348e046d10"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":21,"estimated_tokens_delta":4,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"1c94c3c4-4eba-42e7-a8a4-00c60bb98763"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"estimated_tokens":null,"thinking":" Bash result was","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"c9e62676-e267-4934-85f2-79d124d4bae8"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":25,"estimated_tokens_delta":4,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"03d96f9b-adf7-4f6f-b28b-d427db8b8630"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"estimated_tokens":null,"thinking":" just \"done.\" So","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"bcbdb107-0d53-4872-a6d0-ea0443ab46a6"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":26,"estimated_tokens_delta":1,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"383344f4-e9c7-4fc6-8156-2a455fc315d4"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"estimated_tokens":null,"thinking":" the","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"bd677e6a-ccc0-460c-b78c-d146e412fdfc"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":27,"estimated_tokens_delta":1,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"95673280-0801-43f2-a343-0e1e2294440d"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"estimated_tokens":null,"thinking":" re","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"3ceba820-e7a1-406d-85cc-4e737440db84"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":34,"estimated_tokens_delta":7,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"ec3fefec-de8f-49c3-832f-ee8cdb9098ba"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"estimated_tokens":null,"thinking":"ply will start with \"Output:","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"479a0469-81c6-44ed-901f-3b5ba5919286"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":38,"estimated_tokens_delta":4,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"f1187702-1431-4c3f-b55b-b5d6b6e1b4cf"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"estimated_tokens":null,"thinking":" done\" and close","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"256ff2f5-a3c1-4c39-ba87-85a6f8a66995"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":43,"estimated_tokens_delta":5,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"db91d155-3a27-4751-8f44-9f55e24a2d56"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"estimated_tokens":null,"thinking":" with BANANA on the","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"96de0914-3708-4b8f-afcd-6b1834e0a46a"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":46,"estimated_tokens_delta":3,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"f315f874-841c-471a-aa95-c7b30c4ecca9"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"estimated_tokens":null,"thinking":" last line.","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"8b5125ea-c014-4134-9967-bfc89d40f300"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":47,"estimated_tokens_delta":1,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"7be0f157-678f-462f-b2ed-f69ee1306d62"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"estimated_tokens":null,"thinking":"\n\n","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"e17e4edd-aef5-4819-ae50-94d9b359f5e9"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":199,"estimated_tokens_delta":152,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"344c71df-0721-4f7a-bf9d-a2c9ac2b0431"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"type":"signature_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"5e790c6d-4323-451b-9dbf-9f36e94b59d0"}}
|
||||
{"from":"cli","msg":{"message":{"container":null,"content":[{"thinking":"I need to make sure the answer finishes with BANANA, and the Bash result was just \"done.\" So the reply will start with \"Output: done\" and close with BANANA on the last line.\n\n","type":"thinking"}],"context_management":null,"diagnostics":null,"id":"msg_011CheuGALWJsYSxwR2j7F3W","input_transformations":[],"model":"claude-haiku-5-5","role":"assistant","stop_details":null,"stop_reason":null,"stop_sequence":null,"type":"message","usage":{"cache_creation":{"ephemeral_1h_input_tokens":12165,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":12165,"cache_read_input_tokens":42857,"inference_geo":"global","input_tokens":2,"output_tokens":3,"service_tier":"standard","speed":"standard"}},"parent_tool_use_id":null,"request_id":"req_011CheuGA4t6XHrNhvpU1gjW","session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","thinking_duration_ms":1170,"timestamp":"2026-12-03T13:51:42.004Z","type":"assistant","uuid":"19f7c707-0b92-43f4-a1ff-6f6ba28c9158"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"index":0,"type":"content_block_stop"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"66f6946c-8aa7-4893-8a3f-fc7c023ea3f6"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"content_block":{"text":"","type":"text"},"index":1,"type":"content_block_start"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"6bef1d9a-bcfa-42d8-b3fa-865bbe31804e"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"text":"The command print","type":"text_delta"},"index":1,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"5866afb3-f9f8-42ba-9ae6-928e88f63709"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"text":"ed `done`.","type":"text_delta"},"index":1,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"22c7b7dc-dfa8-49c6-a931-a2a5f179eebe"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"text":" BANANA","type":"text_delta"},"index":1,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"265276d2-0f17-4bd8-8719-b6c0464079fc"}}
|
||||
{"from":"cli","msg":{"message":{"container":null,"content":[{"text":"The command printed `done`. BANANA","type":"text"}],"context_management":null,"diagnostics":null,"id":"msg_011CheuGALWJsYSxwR2j7F3W","input_transformations":[],"model":"claude-haiku-5-5","role":"assistant","stop_details":null,"stop_reason":null,"stop_sequence":null,"type":"message","usage":{"cache_creation":{"ephemeral_1h_input_tokens":12165,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":12165,"cache_read_input_tokens":42857,"inference_geo":"global","input_tokens":2,"output_tokens":3,"service_tier":"standard","speed":"standard"}},"parent_tool_use_id":null,"request_id":"req_011CheuGA4t6XHrNhvpU1gjW","session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","timestamp":"2026-12-03T13:51:42.006Z","type":"assistant","uuid":"4edeb5e3-ae9c-4e64-ab43-dd864db6636c"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"index":1,"type":"content_block_stop"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"950b3a05-26db-4a0b-bb6e-62d584a38638"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"context_management":{"applied_edits":[]},"delta":{"container":null,"stop_details":null,"stop_reason":"end_turn","stop_sequence":null},"type":"message_delta","usage":{"cache_creation_input_tokens":12165,"cache_read_input_tokens":42857,"input_tokens":2,"iterations":[{"cache_creation":{"ephemeral_1h_input_tokens":12165,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":12165,"cache_read_input_tokens":42857,"input_tokens":2,"output_tokens":72,"type":"message"}],"output_tokens":72,"output_tokens_details":{"thinking_tokens":58}}},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"3fb8dfd0-35eb-49ff-a0f9-94c6cff59bcd"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"type":"message_stop"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"eafb6e94-6aeb-4c20-929f-6d5dc4f8df6a"}}
|
||||
{"from":"cli","msg":{"command_uuid":"5cf21cb4-f4c7-4360-8932-61818a8e57ee","session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","state":"completed","type":"command_lifecycle","uuid":"e5548a7e-c304-42d1-a536-2e123ebd58d4","written_at":"2026-12-03T13:51:42.067Z"}}
|
||||
{"from":"cli","msg":{"api_error_status":null,"begun_message_ids":["msg_011CheuFeb6zou7Nmj7hYFnf","msg_011CheuGALWJsYSxwR2j7F3W"],"credential_expires_at":"2026-12-30T17:21:30.368Z","duration_api_ms":4974,"duration_ms":9488,"fast_mode_state":"off","first_content_frame_ms":1332,"first_request_cache_read_input_tokens":26096,"first_request_input_tokens":42859,"input_attachments_detail":{"ambient_start_ms":1,"ambient_wait_ms":5,"cpu_ms":15,"major_faults":0,"producers":44,"prompt_producers_ms":0,"render_ms":0,"setup_ms":0,"slowest_producer":"deferred_tools_delta","slowest_producer_ms":6,"token_counts":0},"is_error":false,"message_normalization_detail":{"after_ms":0,"before_ms":0,"images_ms":0,"messages":19,"normalize_ms":0,"other_ms":1,"post_process_ms":0,"wire_messages":2},"modelUsage":{"claude-haiku-5-5":{"cacheCreationEphemeral1hInputTokens":28926,"cacheCreationEphemeral5mInputTokens":0,"cacheCreationInputTokens":28926,"cacheReadInputTokens":68953,"canonicalModel":"claude-haiku-5-5","contextWindow":1000000,"costBasis":"list","costUSD":0.0067110300000000015,"inputTokens":1198,"maxOutputTokens":128000,"outputTokens":233,"provider":"firstParty","thinkingTokens":109,"webSearchRequests":0}},"model_usage_since_last_result":{"claude-haiku-5-5":{"cacheCreationEphemeral1hInputTokens":28926,"cacheCreationEphemeral5mInputTokens":0,"cacheCreationInputTokens":28926,"cacheReadInputTokens":68953,"canonicalModel":"claude-haiku-5-5","contextWindow":1000000,"costBasis":"list","costUSD":0.0067110300000000015,"inputTokens":1198,"maxOutputTokens":128000,"outputTokens":233,"provider":"firstParty","thinkingTokens":109,"webSearchRequests":0}},"num_turns":2,"origin":{"kind":"human"},"permission_denials":[],"process_turn_index":0,"queued_turn_count":0,"request_build_detail":{"cache_break_record_ms":1,"headers_ms":0,"other_ms":0,"plans_ms":0,"record_attempt_ms":0,"records_ms":0,"retry_setup_ms":0,"sent_build_cache_breakpoints_ms":0,"sent_build_ms":1,"sent_build_safety_context_ms":0,"sent_build_surrogate_scan_ms":0,"system_ms":0},"request_sent_wall_ms":1796305892823,"result":"The command printed `done`. BANANA","result_index":0,"safety_stops":0,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","stop_reason":"end_turn","subagent_stats":{"by_type":{},"completed":0,"failed":0,"killed":{"parent":0,"system":0,"user":0},"max_depth":0,"refused":{"budget":0,"concurrency_limit":0,"depth_limit":0},"requested":{"background":0,"foreground":0,"unset":0},"spawned":0,"spawned_by_subagents":0,"started_in_background":0},"subtype":"success","terminal_reason":"completed","time_to_request_cpu_ms":107,"time_to_request_loop_lag_ms":1,"time_to_request_major_faults":1,"time_to_request_ms":243,"time_to_request_phases_ms":{"autocompact":1,"client_creation":2,"conversation_append":1,"engine_pickup":1,"init_frame_send":1,"init_message":2,"input_attachments":8,"input_hooks":37,"loop_entry":1,"message_normalization":1,"message_prep":1,"model_config_wait":0,"model_gates":163,"other":2,"process_user_input":2,"query_setup":0,"request_announcements":3,"request_build":2,"resume_other":0,"system_prompt":5,"tool_pool_refresh":1,"tool_schema_build":8,"transcript_persist":1},"tool_schema_build_detail":{"after_ms":0,"betas_ms":0,"new_schemas":13,"other_ms":0,"placement_ms":2,"render_ms":3,"tools":13,"waits_ms":3},"total_cost_usd":0.0067110300000000015,"ttft_ms":2487,"ttft_stream_ms":1331,"turn_start_resume_kind":"none","type":"result","usage":{"cache_creation":{"ephemeral_1h_input_tokens":28926,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":28926,"cache_read_input_tokens":68953,"fallback_credit":null,"inference_geo":"global","input_tokens":4,"iterations":[{"cache_creation":{"ephemeral_1h_input_tokens":12165,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":12165,"cache_read_input_tokens":42857,"input_tokens":2,"output_tokens":72,"type":"message"}],"output_tokens":214,"output_tokens_details":{"thinking_tokens":109},"server_tool_use":{"web_fetch_requests":0,"web_search_requests":0},"service_tier":"standard","speed":"standard"},"user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","user_message_uuids":["85d18ab2-e0be-452f-8db8-5f5cfa76152d","5cf21cb4-f4c7-4360-8932-61818a8e57ee"],"uuid":"d3f210c9-67ad-4ec5-b122-3d4477ae65b5","written_at":"2026-12-03T13:51:42.069Z"}}
|
||||
{"from":"cli","msg":{"command_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","state":"completed","type":"command_lifecycle","uuid":"32e0888f-d2b7-4721-bc7c-6c5320d3c99c","written_at":"2026-12-03T13:51:42.070Z"}}
|
||||
{"from":"cli","msg":{"response":{"request_id":"req_2","response":{"applied":{"advisor":null,"effort":"medium","model":"claude-haiku-5-5","ultracode":false,"ultracodeAvailable":true,"ultracodeRequested":false},"effective":{"model":"opus"}},"subtype":"success"},"type":"control_response"}}
|
||||
{"from":"shim","msg":{"message":{"content":[{"text":"Run the Bash command `sleep 3 && echo done`, then tell me its output in one line.","type":"text"}],"role":"user"},"origin":{"kind":"human"},"parent_tool_use_id":null,"session_id":"","type":"user","uuid":"f5f7de43-8575-4db0-a20d-7890bc534ace"}}
|
||||
{"from":"cli","msg":{"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","state":"running","subtype":"session_state_changed","type":"system","uuid":"5e39fde0-9f18-47f0-8b7e-21007ec957c0"}}
|
||||
{"from":"cli","msg":{"command_uuid":"f5f7de43-8575-4db0-a20d-7890bc534ace","session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","state":"queued","type":"command_lifecycle","uuid":"ad1291e3-8d79-4048-a10c-599eafd30c9b"}}
|
||||
{"from":"cli","msg":{"command_uuid":"f5f7de43-8575-4db0-a20d-7890bc534ace","session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","state":"started","type":"command_lifecycle","uuid":"0ed63980-6c4a-40b9-b94d-3bc062cddd58"}}
|
||||
{"from":"cli","msg":{"additional_directories":[],"analytics_disabled":false,"apiKeySource":"none","capabilities":["interrupt_receipt_v1","interrupt_cancel_queued_v1","interrupt_send_now_v1","interrupt_requeue_taken_v1","msg_lifecycle_v1","request_marker_lists_v1","ask_user_question_unanswered_v1","lifecycle_wakeup_source_v1","sdk_mcp_tools_list_changed","sdk_mcp_manifests","mcp_read_resource_v1","mcp_tool_ui_meta_v1","ui_surface_v1","mcp_call_result_not_for_model_v1"],"claude_code_version":"2.1.312","cwd":"/private/var/folders/gx/1228y8wj7bx6dl6m9syzrb340000gn/T/.tmpC932yI","fast_mode_disabled_reason":"sdk_opt_in_required","fast_mode_state":"off","model":"claude-haiku-5-5","original_cwd":"/private/var/folders/gx/1228y8wj7bx6dl6m9syzrb340000gn/T/.tmpC932yI","output_style":"Concise","per_turn_effort_active":true,"permissionMode":"default","product_feedback_disabled":false,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"init","terminal_slash_commands":["doctor","color","focus","reload-plugins"],"type":"system","user_message_uuids":["f5f7de43-8575-4db0-a20d-7890bc534ace"],"uuid":"17b7ad4c-6ad3-4d9c-aeef-2e027b0d75ae","view_mode":"default"}}
|
||||
{"from":"cli","msg":{"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","status":"requesting","subtype":"status","type":"system","user_message_uuids":["f5f7de43-8575-4db0-a20d-7890bc534ace"],"uuid":"7b8f8fcd-669e-4606-ad6f-3368116e7a75"}}
|
||||
{"from":"cli","msg":{"rate_limit_info":{"isUsingOverage":false,"overageDisabledReason":"org_level_disabled","overageStatus":"rejected","rateLimitType":"five_hour","resetsAt":1793203800,"status":"allowed","unifiedWindows":{"five_hour":{"resetsAt":1793203800,"status":"allowed","utilization":0.31},"seven_day":{"resetsAt":1793631600,"status":"allowed","utilization":0.32}}},"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"rate_limit_event","uuid":"b3ef3e2a-11ad-46f9-8ea5-fd01f8d0fe39"}}
|
||||
{"from":"cli","msg":{"commands":[{"argumentHint":"","description":"Review a pull request","name":"review"}],"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"commands_changed","type":"system","uuid":"5f60f663-94ff-4885-9167-b12cae835fca"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhj5mGEZkoUv4HmADLr","event":{"message":{"container":null,"content":[],"context_management":null,"diagnostics":null,"id":"msg_011CgUhj5mGEZkoUv4HmADLr","input_transformations":[],"model":"claude-haiku-5-5","role":"assistant","stop_details":null,"stop_reason":null,"stop_sequence":null,"type":"message","usage":{"cache_creation":{"ephemeral_1h_input_tokens":15110,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":15110,"cache_read_input_tokens":14824,"inference_geo":"global","input_tokens":2,"output_tokens":16,"service_tier":"standard","speed":"standard"}},"type":"message_start"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","ttft_ms":1661,"type":"stream_event","user_message_uuid":"f5f7de43-8575-4db0-a20d-7890bc534ace","user_message_uuids":["f5f7de43-8575-4db0-a20d-7890bc534ace"],"uuid":"4fb86b8a-bfa9-439b-b46b-6ef6e381d243"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhj5mGEZkoUv4HmADLr","event":{"content_block":{"caller":{"type":"direct"},"id":"toolu_01RLgKZhL3rEQrnb6R4yD7LH","input":{},"name":"Bash","type":"tool_use"},"index":0,"type":"content_block_start"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"0bc16cbc-fcbb-4d52-bd5b-4d864b307bbd"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhj5mGEZkoUv4HmADLr","event":{"delta":{"partial_json":"","type":"input_json_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"0510612a-2068-496a-85f4-f61706fb8cd5"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhj5mGEZkoUv4HmADLr","event":{"delta":{"partial_json":"{\"command\": \"sleep 3","type":"input_json_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"281a35ac-8285-4591-8c60-5ddc743b7036"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhj5mGEZkoUv4HmADLr","event":{"delta":{"partial_json":" && echo done","type":"input_json_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"44c02159-084d-48d1-a23c-5bd3628e69e7"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhj5mGEZkoUv4HmADLr","event":{"delta":{"partial_json":"\", \"description\": \"S","type":"input_json_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"ca641c1e-c60b-4943-a07b-9ea03c9b8845"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhj5mGEZkoUv4HmADLr","event":{"delta":{"partial_json":"leep 3 se","type":"input_json_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"bc5c34f0-653a-4041-a6cf-42c0dcd0fc2c"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhj5mGEZkoUv4HmADLr","event":{"delta":{"partial_json":"conds then echo done","type":"input_json_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"00cd396e-f45d-4b60-b484-9fb0ddfc3384"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhj5mGEZkoUv4HmADLr","event":{"delta":{"partial_json":"\"}","type":"input_json_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"6987c232-0dbf-43be-83fe-2164d6d701ee"}}
|
||||
{"from":"cli","msg":{"message":{"container":null,"content":[{"caller":{"type":"direct"},"id":"toolu_01RLgKZhL3rEQrnb6R4yD7LH","input":{"command":"sleep 3 && echo done","description":"Sleep 3 seconds then echo done"},"name":"Bash","type":"tool_use"}],"context_management":null,"diagnostics":null,"id":"msg_011CgUhj5mGEZkoUv4HmADLr","input_transformations":[],"model":"claude-haiku-5-5","role":"assistant","stop_details":null,"stop_reason":null,"stop_sequence":null,"type":"message","usage":{"cache_creation":{"ephemeral_1h_input_tokens":15110,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":15110,"cache_read_input_tokens":14824,"inference_geo":"global","input_tokens":2,"output_tokens":16,"service_tier":"standard","speed":"standard"}},"parent_tool_use_id":null,"request_id":"req_011CgUhj5SvXJc5aP46FPBxn","session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","timestamp":"2026-10-28T13:20:00.931Z","type":"assistant","user_message_uuid":"f5f7de43-8575-4db0-a20d-7890bc534ace","user_message_uuids":["f5f7de43-8575-4db0-a20d-7890bc534ace"],"uuid":"b7befa90-ef05-44ff-9822-ec00f61130b2","wire_tool_inputs":{"toolu_01RLgKZhL3rEQrnb6R4yD7LH":{"command":"sleep 3 && echo done","description":"Sleep 3 seconds then echo done"}}}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhj5mGEZkoUv4HmADLr","event":{"index":0,"type":"content_block_stop"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"01897941-b66d-4657-a87b-14dde2420f38"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhj5mGEZkoUv4HmADLr","event":{"context_management":{"applied_edits":[]},"delta":{"container":null,"stop_details":null,"stop_reason":"tool_use","stop_sequence":null},"type":"message_delta","usage":{"cache_creation_input_tokens":15110,"cache_read_input_tokens":14824,"input_tokens":2,"iterations":[{"cache_creation":{"ephemeral_1h_input_tokens":15110,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":15110,"cache_read_input_tokens":14824,"input_tokens":2,"output_tokens":90,"type":"message"}],"output_tokens":90,"output_tokens_details":{"thinking_tokens":0}}},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"daf07992-fd3c-46c2-8fe7-3014bf6e6cf0"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhj5mGEZkoUv4HmADLr","event":{"type":"message_stop"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"6c4b9511-1539-45a7-9184-9efc1ce9384d"}}
|
||||
{"from":"shim","msg":{"message":{"content":[{"text":"Also end your answer with the word BANANA.","type":"text"}],"role":"user"},"origin":{"kind":"human"},"parent_tool_use_id":null,"priority":"now","session_id":"","type":"user","uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee"}}
|
||||
{"from":"cli","msg":{"command_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","state":"queued","type":"command_lifecycle","uuid":"6ae9f6be-c8d5-4feb-8c17-71bfc3d4880e"}}
|
||||
{"from":"cli","msg":{"description":"Sleep 3 seconds then echo done","is_backgrounded":false,"run_id":"0mvs568cx-76274178","session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"task_started","task_id":"bk6c5st9v","task_type":"local_bash","tool_use_id":"toolu_01RLgKZhL3rEQrnb6R4yD7LH","type":"system","uuid":"e45f0b55-eb72-4cc6-8bb7-0ba207583cc7"}}
|
||||
{"from":"cli","msg":{"output_file":"","run_id":"0mvs568cx-76274178","session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","status":"completed","subtype":"task_notification","summary":"Sleep 3 seconds then echo done","task_id":"bk6c5st9v","tool_use_id":"toolu_01RLgKZhL3rEQrnb6R4yD7LH","type":"system","uuid":"0d23dced-54be-49b0-963b-a9e67ae4b75c"}}
|
||||
{"from":"cli","msg":{"message":{"content":[{"content":"done","is_error":false,"tool_use_id":"toolu_01RLgKZhL3rEQrnb6R4yD7LH","type":"tool_result"}],"role":"user"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","timestamp":"2026-10-28T13:20:04.328Z","tool_result_meta":[{"id":"toolu_01RLgKZhL3rEQrnb6R4yD7LH","permission_decision":{"decision":"accept","reason_type":"subcommandResults","source":"config"}}],"tool_use_result":{"interrupted":false,"isImage":false,"noOutputExpected":false,"stderr":"","stdout":"done"},"type":"user","uuid":"998e4d6c-47bf-4e81-b630-1eb86398d192"}}
|
||||
{"from":"cli","msg":{"api_error_status":null,"duration_api_ms":2891,"duration_ms":5544,"fast_mode_disabled_reason":"sdk_opt_in_required","fast_mode_state":"off","first_content_frame_ms":1797,"first_request_input_tokens":29936,"is_error":false,"modelUsage":{"claude-haiku-5-5":{"cacheCreationEphemeral1hInputTokens":15110,"cacheCreationEphemeral5mInputTokens":0,"cacheCreationInputTokens":15110,"cacheReadInputTokens":14824,"canonicalModel":"claude-haiku-5-5","contextWindow":1000000,"costBasis":"list","costUSD":0.0033443400000000003,"inputTokens":1196,"maxOutputTokens":128000,"outputTokens":109,"provider":"firstParty","thinkingTokens":0,"webSearchRequests":0}},"model_usage_since_last_result":{"claude-haiku-5-5":{"cacheCreationEphemeral1hInputTokens":15110,"cacheCreationEphemeral5mInputTokens":0,"cacheCreationInputTokens":15110,"cacheReadInputTokens":14824,"canonicalModel":"claude-haiku-5-5","contextWindow":1000000,"costBasis":"list","costUSD":0.0033443400000000003,"inputTokens":1196,"maxOutputTokens":128000,"outputTokens":109,"provider":"firstParty","thinkingTokens":0,"webSearchRequests":0}},"num_turns":2,"origin":{"kind":"human"},"permission_denials":[],"queued_turn_count":1,"request_sent_wall_ms":1793193598927,"result":"","result_index":0,"safety_stops":0,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","stop_reason":"tool_use","subagent_stats":{"by_type":{},"completed":0,"failed":0,"killed":{"parent":0,"system":0,"user":0},"max_depth":0,"refused":{"budget":0,"concurrency_limit":0,"depth_limit":0},"requested":{"background":0,"foreground":0,"unset":0},"spawned":0,"spawned_by_subagents":0,"started_in_background":0},"subtype":"success","terminal_reason":"aborted_tools","time_to_request_ms":138,"total_cost_usd":0.0033443400000000003,"ttft_ms":2142,"ttft_stream_ms":1797,"type":"result","usage":{"cache_creation":{"ephemeral_1h_input_tokens":15110,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":15110,"cache_read_input_tokens":14824,"fallback_credit":null,"inference_geo":"global","input_tokens":2,"iterations":[{"cache_creation":{"ephemeral_1h_input_tokens":15110,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":15110,"cache_read_input_tokens":14824,"input_tokens":2,"output_tokens":90,"type":"message"}],"output_tokens":90,"output_tokens_details":{"thinking_tokens":0},"server_tool_use":{"web_fetch_requests":0,"web_search_requests":0},"service_tier":"standard","speed":"standard"},"user_message_uuid":"f5f7de43-8575-4db0-a20d-7890bc534ace","user_message_uuids":["f5f7de43-8575-4db0-a20d-7890bc534ace"],"uuid":"a4afa59a-be05-41e3-bc85-4cc8e9b28506"}}
|
||||
{"from":"cli","msg":{"command_uuid":"f5f7de43-8575-4db0-a20d-7890bc534ace","session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","state":"cancelled","type":"command_lifecycle","uuid":"4911bef5-6b3d-4c0e-803e-5f21202ce766"}}
|
||||
{"from":"cli","msg":{"command_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","state":"started","type":"command_lifecycle","uuid":"89c8590f-1c08-4183-b430-5e888745fbfc"}}
|
||||
{"from":"cli","msg":{"additional_directories":[],"analytics_disabled":false,"apiKeySource":"none","capabilities":["interrupt_receipt_v1","interrupt_cancel_queued_v1","interrupt_send_now_v1","interrupt_requeue_taken_v1","msg_lifecycle_v1","request_marker_lists_v1","ask_user_question_unanswered_v1","lifecycle_wakeup_source_v1","sdk_mcp_tools_list_changed","sdk_mcp_manifests","mcp_read_resource_v1","mcp_tool_ui_meta_v1","ui_surface_v1","mcp_call_result_not_for_model_v1"],"claude_code_version":"2.1.312","cwd":"/private/var/folders/gx/1228y8wj7bx6dl6m9syzrb340000gn/T/.tmpC932yI","fast_mode_disabled_reason":"sdk_opt_in_required","fast_mode_state":"off","model":"claude-haiku-5-5","original_cwd":"/private/var/folders/gx/1228y8wj7bx6dl6m9syzrb340000gn/T/.tmpC932yI","output_style":"Concise","per_turn_effort_active":true,"permissionMode":"default","product_feedback_disabled":false,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"init","terminal_slash_commands":["doctor","color","focus","reload-plugins"],"type":"system","user_message_uuids":["5a435507-7a2d-49cd-9399-6d6e640c57ee"],"uuid":"a05d013f-558f-4581-9ac1-49e4329e9d7d","view_mode":"default"}}
|
||||
{"from":"cli","msg":{"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","status":"requesting","subtype":"status","type":"system","user_message_uuids":["5a435507-7a2d-49cd-9399-6d6e640c57ee"],"uuid":"d00d3b7f-227d-4373-9092-676090723763"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"message":{"container":null,"content":[],"context_management":null,"diagnostics":null,"id":"msg_011CgUhjUjtfNy2NL2chxrF5","input_transformations":[],"model":"claude-haiku-5-5","role":"assistant","stop_details":null,"stop_reason":null,"stop_sequence":null,"type":"message","usage":{"cache_creation":{"ephemeral_1h_input_tokens":3932,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":3932,"cache_read_input_tokens":29934,"inference_geo":"global","input_tokens":2,"output_tokens":4,"service_tier":"standard","speed":"standard"}},"type":"message_start"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","ttft_ms":1500,"type":"stream_event","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","user_message_uuids":["5a435507-7a2d-49cd-9399-6d6e640c57ee"],"uuid":"c634f9c8-ff1c-44fa-9138-5d357a418f58"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"content_block":{"thinking":"","type":"thinking"},"index":0,"type":"content_block_start"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"0db4c93b-e0cb-4fcf-857f-c79fed9a2609"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":1,"estimated_tokens_delta":1,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"e7d95fb9-826f-45e1-8e7c-4e6abcdef7c9"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":"The","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"27c0c433-3ee8-42fc-830a-90d67cb371d1"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":2,"estimated_tokens_delta":1,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"cc8a606b-0251-4927-96c5-160880f430f6"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":" s","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"1c859e8c-52fe-4fb3-8ad1-0122752cdccf"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":5,"estimated_tokens_delta":3,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"202bcadf-3533-4744-a259-97bfc7bef0e3"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":"leep task","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"2a273607-1f22-4a49-860c-30184e6bfe01"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":9,"estimated_tokens_delta":4,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"63d703f5-6eec-4a89-a6c7-c38245001004"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":" completed with","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"dba1141d-78a3-406a-9125-bf02b5b4a2a3"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":13,"estimated_tokens_delta":4,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"2618ae50-9e26-4724-89f6-7fda1f105f42"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":" output \"done.\"","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"ba6f0b4d-aa70-4347-903e-46119eaa15e6"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":16,"estimated_tokens_delta":3,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"beaeb52e-0825-47b9-ba7e-e09d6de4818c"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":" The user as","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"3408f5ca-fe05-4bbf-8ae0-b1bc4db97033"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":18,"estimated_tokens_delta":2,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"b5f0f099-f629-469e-a51b-bcb1abaf5f66"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":"ked me","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"32b263d1-ff54-48f3-a61d-96e98eddce23"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":22,"estimated_tokens_delta":4,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"581160fb-90e0-4831-b087-d702a7a42fa4"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":" to end my answ","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"af0f7710-cb0d-4192-85b6-2a458a17a463"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":25,"estimated_tokens_delta":3,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"1ea97064-de2c-4b80-9f32-09ce3a9ce60b"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":"er with the","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"ad449330-cf10-4919-b4a0-9f510c259d38"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":28,"estimated_tokens_delta":3,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"9c7d8148-ced4-4647-bdb0-fca91d88aab9"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":" word BAN","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"2e4fed14-2110-4d2c-81d0-033f66954ed6"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":29,"estimated_tokens_delta":1,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"dea229d8-9c12-4bf9-9cea-bf9813d41840"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":"AN","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"a4c1bb86-c884-4f6b-b752-3d57bbb36b1c"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":31,"estimated_tokens_delta":2,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"1cbe8e9c-f44c-4dfb-b6e0-8032d35991db"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":"A, which","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"0a79f76a-a558-4de1-8323-7547d8628d28"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":34,"estimated_tokens_delta":3,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"1961a504-ee75-484f-9c2d-8418496ff795"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":" is a har","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"5fa188a2-6e70-4af5-8900-13c30c78c7ad"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":41,"estimated_tokens_delta":7,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"a4d053b7-4485-4d18-8fd2-2354b2a22310"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":"mless request, and there's a","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"d734fe28-ce41-4002-ad2f-ea0dbc0857a0"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":43,"estimated_tokens_delta":2,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"7fa6189b-3633-4814-9755-a93619616466"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":" note","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"6dfd60d4-172b-456e-bb66-4f2d6c966233"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":45,"estimated_tokens_delta":2,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"4aa94d3f-16be-48dc-aa05-1a85105921bb"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":" about","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"9eb2805d-f684-40ee-b368-468facc4890a"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":47,"estimated_tokens_delta":2,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"992053c7-e234-4d72-9c11-d00786dd2c52"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":" repl","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"10f0c715-33ad-44fc-8818-7d1a4549fef3"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":49,"estimated_tokens_delta":2,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"e1dad1ff-ec95-4ce1-b07b-b3b42c5f0a15"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":"ying in","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"244ce6fc-4dfd-4f6e-abf5-57f860663fdc"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":54,"estimated_tokens_delta":5,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"6f4e3a68-8a38-4ef1-a1d8-5d16b0bdb9e0"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":" Chinese per inst","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"6fce552c-bfa4-4705-b50e-1e162b487f9d"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":58,"estimated_tokens_delta":4,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"491e90c9-da11-4f2f-96d1-2e6c501a13b9"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":"ructions, but","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"cee9edc1-dac1-4997-9b0e-a64e6cc17173"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":61,"estimated_tokens_delta":3,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"2ad92491-7893-4f66-9f8c-8e0c49a0dd21"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":" the user w","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"0d10f6b1-daf3-4c40-92cc-78a3b7addc0d"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":65,"estimated_tokens_delta":4,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"48d2ff82-0a78-43f7-bd6e-41170fd9be53"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":"rote in English—","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"7af06734-f004-4264-aa76-0e5404fb1da7"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":66,"estimated_tokens_delta":1,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"a607027c-4b06-467b-bd39-99a40085c05b"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":"I","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"f651bfee-b7bb-4d2f-8872-bc43aff55c2b"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":72,"estimated_tokens_delta":6,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"862b7d4a-8d66-48ce-a954-764541537982"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":"'ll decide how to handle","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"f9a8266d-7203-49f1-b14e-cdbcd5311bda"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":75,"estimated_tokens_delta":3,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"c5bc3ec1-229c-4acc-8a9a-b1184be9a1bf"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":" that bal","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"1ea067e9-fbb8-4685-a217-e42170c35740"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":80,"estimated_tokens_delta":5,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"ce143939-c780-4938-ba2c-f6a54b8f4a6f"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":"ance while including","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"77668dd2-c3ad-4df5-87a3-4b76a2219c65"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":81,"estimated_tokens_delta":1,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"0475f779-b12b-4ae0-a42a-4ae723a6d468"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":" B","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"49727b38-d58a-4ad0-9728-aa4bc223b54d"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":86,"estimated_tokens_delta":5,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"02f8ee0c-36d8-4de5-af74-fe7d19969366"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":"ANANA at the end.","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"2adc15b2-5b1c-4add-b3ad-1ceaaa665bae"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":87,"estimated_tokens_delta":1,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"eb0ae205-deb6-4b79-9726-98fd9d1d533c"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":"\n\n","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"40e6df26-1321-45ea-8ca5-9d96ca00087b"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":287,"estimated_tokens_delta":200,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"57a445b0-9671-4073-89c6-f72835125be3"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"type":"signature_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"aaf131b8-99e0-4fd9-9169-00be0b4e360a"}}
|
||||
{"from":"cli","msg":{"message":{"container":null,"content":[{"thinking":"The sleep task completed with output \"done.\" The user asked me to end my answer with the word BANANA, which is a harmless request, and there's a note about replying in Chinese per instructions, but the user wrote in English—I'll decide how to handle that balance while including BANANA at the end.\n\n","type":"thinking"}],"context_management":null,"diagnostics":null,"id":"msg_011CgUhjUjtfNy2NL2chxrF5","input_transformations":[],"model":"claude-haiku-5-5","role":"assistant","stop_details":null,"stop_reason":null,"stop_sequence":null,"type":"message","usage":{"cache_creation":{"ephemeral_1h_input_tokens":3932,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":3932,"cache_read_input_tokens":29934,"inference_geo":"global","input_tokens":2,"output_tokens":4,"service_tier":"standard","speed":"standard"}},"parent_tool_use_id":null,"request_id":"req_011CgUhjUTmHT72RxnP7ze5J","session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","thinking_duration_ms":3423,"timestamp":"2026-10-28T13:20:09.346Z","type":"assistant","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","user_message_uuids":["5a435507-7a2d-49cd-9399-6d6e640c57ee"],"uuid":"ecaa1288-7581-48ad-9c59-89e4bb9f063f"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"index":0,"type":"content_block_stop"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"549a0ef9-e0b3-40af-bb4a-8aba4c08eb8d"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"content_block":{"text":"","type":"text"},"index":1,"type":"content_block_start"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"d3049aaf-53af-4878-b273-68835033ff92"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"text":"命","type":"text_delta"},"index":1,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"4a3271f3-0c7d-427c-9407-c610ad454b15"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"text":"令输出为 `done`","type":"text_delta"},"index":1,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"3558f94f-6fcb-4c7a-96a5-6f6e415a5f93"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"text":"。\n\nB","type":"text_delta"},"index":1,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"fea97b73-1f25-4f88-94db-0f0fdd401d2b"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"text":"ANANA","type":"text_delta"},"index":1,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"303a047a-fc87-48ea-9524-e102e112b10a"}}
|
||||
{"from":"cli","msg":{"message":{"container":null,"content":[{"text":"命令输出为 `done`。\n\nBANANA","type":"text"}],"context_management":null,"diagnostics":null,"id":"msg_011CgUhjUjtfNy2NL2chxrF5","input_transformations":[],"model":"claude-haiku-5-5","role":"assistant","stop_details":null,"stop_reason":null,"stop_sequence":null,"type":"message","usage":{"cache_creation":{"ephemeral_1h_input_tokens":3932,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":3932,"cache_read_input_tokens":29934,"inference_geo":"global","input_tokens":2,"output_tokens":4,"service_tier":"standard","speed":"standard"}},"parent_tool_use_id":null,"request_id":"req_011CgUhjUTmHT72RxnP7ze5J","session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","timestamp":"2026-10-28T13:20:09.358Z","type":"assistant","uuid":"73a78906-d0d9-432d-b1d7-a34ac4d05707"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"index":1,"type":"content_block_stop"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"d665c80a-e37f-476e-ac86-e12d44f26fad"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"context_management":{"applied_edits":[]},"delta":{"container":null,"stop_details":null,"stop_reason":"end_turn","stop_sequence":null},"type":"message_delta","usage":{"cache_creation_input_tokens":3932,"cache_read_input_tokens":29934,"input_tokens":2,"iterations":[{"cache_creation":{"ephemeral_1h_input_tokens":3932,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":3932,"cache_read_input_tokens":29934,"input_tokens":2,"output_tokens":209,"type":"message"}],"output_tokens":209,"output_tokens_details":{"thinking_tokens":192}}},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"46798358-6519-4878-af21-22006f465f53"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"type":"message_stop"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"fe0e0673-335a-41a0-b7c2-7b5d78e99739"}}
|
||||
{"from":"cli","msg":{"api_error_status":null,"duration_api_ms":7859,"duration_ms":5066,"fast_mode_disabled_reason":"sdk_opt_in_required","fast_mode_state":"off","first_content_frame_ms":1586,"first_request_input_tokens":33868,"is_error":false,"modelUsage":{"claude-haiku-5-5":{"cacheCreationEphemeral1hInputTokens":19042,"cacheCreationEphemeral5mInputTokens":0,"cacheCreationInputTokens":19042,"cacheReadInputTokens":44758,"canonicalModel":"claude-haiku-5-5","contextWindow":1000000,"costBasis":"list","costUSD":0.00453478,"inputTokens":1198,"maxOutputTokens":128000,"outputTokens":318,"provider":"firstParty","thinkingTokens":192,"webSearchRequests":0}},"model_usage_since_last_result":{"claude-haiku-5-5":{"cacheCreationEphemeral1hInputTokens":3932,"cacheCreationEphemeral5mInputTokens":0,"cacheCreationInputTokens":3932,"cacheReadInputTokens":29934,"canonicalModel":"claude-haiku-5-5","contextWindow":1000000,"costBasis":"list","costUSD":0.00119044,"inputTokens":2,"maxOutputTokens":128000,"outputTokens":209,"provider":"firstParty","thinkingTokens":192,"webSearchRequests":0}},"num_turns":1,"origin":{"kind":"human"},"permission_denials":[],"queued_turn_count":0,"request_sent_wall_ms":1793193604397,"result":"命令输出为 `done`。\n\nBANANA","result_index":1,"safety_stops":0,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","stop_reason":"end_turn","subagent_stats":{"by_type":{},"completed":0,"failed":0,"killed":{"parent":0,"system":0,"user":0},"max_depth":0,"refused":{"budget":0,"concurrency_limit":0,"depth_limit":0},"requested":{"background":0,"foreground":0,"unset":0},"spawned":0,"spawned_by_subagents":0,"started_in_background":0},"subtype":"success","terminal_reason":"completed","time_to_request_ms":59,"total_cost_usd":0.00453478,"ttft_ms":5008,"ttft_stream_ms":1563,"type":"result","usage":{"cache_creation":{"ephemeral_1h_input_tokens":3932,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":3932,"cache_read_input_tokens":29934,"fallback_credit":null,"inference_geo":"global","input_tokens":2,"iterations":[{"cache_creation":{"ephemeral_1h_input_tokens":3932,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":3932,"cache_read_input_tokens":29934,"input_tokens":2,"output_tokens":209,"type":"message"}],"output_tokens":209,"output_tokens_details":{"thinking_tokens":192},"server_tool_use":{"web_fetch_requests":0,"web_search_requests":0},"service_tier":"standard","speed":"standard"},"user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","user_message_uuids":["5a435507-7a2d-49cd-9399-6d6e640c57ee"],"uuid":"8172897e-6304-4855-9480-f4e579da730f"}}
|
||||
{"from":"cli","msg":{"command_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","state":"completed","type":"command_lifecycle","uuid":"3c5163f4-90c0-4939-a3e5-aba1cf13bca3"}}
|
||||
{"from":"cli","msg":{"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","state":"idle","subtype":"session_state_changed","type":"system","uuid":"57c31a3d-da32-4a0c-9124-372c880779b7"}}
|
||||
@@ -1,34 +0,0 @@
|
||||
{"launch":["--model","haiku","-p","--input-format","stream-json","--output-format","stream-json","--verbose","--permission-prompt-tool","stdio","--include-partial-messages","--thinking-display","summarized","--allow-dangerously-skip-permissions","--session-id","f782ff38-9bfe-4bd7-a857-f3cb10b38bcf"]}
|
||||
{"from":"shim","msg":{"request":{"perTaskStopAffordance":true,"subtype":"initialize"},"request_id":"req_1","type":"control_request"}}
|
||||
{"from":"cli","msg":{"response":{"pending_permission_requests":[],"pending_user_dialog_requests":[],"request_id":"req_1","response":{"analytics_disabled":false,"capabilities":["ui_surface_v1","mcp_call_result_not_for_model_v1","mcp_call_soft_error_result_v1","mcp_call_check_permissions_v1","voice_call_talk_line_v1","ui_pane_widget_v1","reload_plugins_refuse_if_busy_v1","get_usage_detached_v1"],"claude_code_version":"2.1.335","commands":[{"argumentHint":"","description":"Review a pull request","name":"review"},{"argumentHint":"","description":"Write a CLAUDE.md","name":"init"}],"current_permission_mode":"default","fast_mode_state":"off","feedback_mode":{"kind":"post"},"hook_on_failure_supported":true,"hooks_when_unanswered_kept":0,"ide_rc_auto_enable_gate":true,"models":[{"description":"Opus 5.5 · Best for everyday, complex tasks","displayName":"Default (recommended)","resolvedModel":"claude-opus-5-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsFastMode":true,"supportsThinkingOff":false,"value":"default"},{"description":"For complex work and everyday tasks","displayName":"Opus 5.5","resolvedModel":"claude-opus-5-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsFastMode":true,"supportsThinkingOff":false,"value":"opus"},{"description":"For your toughest challenges","displayName":"Fable 5.2","resolvedModel":"claude-fable-5-2","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsFastMode":true,"supportsThinkingOff":false,"value":"fable"},{"description":"Most efficient for simpler tasks","displayName":"Sonnet 5.5","resolvedModel":"claude-sonnet-5-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":false,"value":"sonnet"},{"description":"Fastest for quick answers","displayName":"Haiku 5.5","resolvedModel":"claude-haiku-5-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":false,"value":"haiku"},{"description":"Most capable for your hardest and longest-running tasks","displayName":"Fable 5.1","overflow":true,"resolvedModel":"claude-fable-5-1","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":false,"value":"claude-fable-5-1"},{"description":"Fastest for quick answers","displayName":"Haiku 4.5","overflow":true,"resolvedModel":"claude-haiku-4-5-20251001","supportsThinkingOff":true,"value":"claude-haiku-4-5-20251001"},{"description":"Efficient for routine tasks","displayName":"Sonnet 5","overflow":true,"resolvedModel":"claude-sonnet-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":true,"value":"claude-sonnet-5"},{"description":"Best for everyday, complex tasks","displayName":"Opus 5","overflow":true,"resolvedModel":"claude-opus-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsFastMode":true,"supportsThinkingOff":true,"value":"claude-opus-5"},{"description":"Most capable for your hardest and longest-running tasks","displayName":"Fable 5","overflow":true,"resolvedModel":"claude-fable-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":false,"value":"claude-fable-5"},{"description":"Best for everyday, complex tasks","displayName":"Opus 4.8","overflow":true,"resolvedModel":"claude-opus-4-8","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsFastMode":true,"supportsThinkingOff":true,"value":"claude-opus-4-8"},{"description":"Best for everyday, complex tasks","displayName":"Opus 4.7","overflow":true,"resolvedModel":"claude-opus-4-7","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":true,"value":"claude-opus-4-7"},{"description":"Best for everyday, complex tasks","displayName":"Opus 4.6","overflow":true,"resolvedModel":"claude-opus-4-6","supportedEffortLevels":["low","medium","high","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":true,"value":"claude-opus-4-6"},{"description":"Efficient for routine tasks","displayName":"Sonnet 4.6","overflow":true,"resolvedModel":"claude-sonnet-4-6","supportedEffortLevelsLine truncated
|
||||
{"from":"shim","msg":{"request":{"subtype":"get_settings"},"request_id":"req_2","type":"control_request"}}
|
||||
{"from":"cli","msg":{"response":{"request_id":"req_2","response":{"applied":{"advisor":null,"apiProvider":"firstParty","effort":"medium","launchEnvLeftOwnFilesInPlace":false,"model":"claude-haiku-5-5","outsideBlocksCountLaunchFoldersOnly":false,"outsideFileToolReadsBlocked":false,"outsideFileToolWritesBlocked":false,"ultracode":false,"ultracodeAvailable":true,"ultracodeRequested":false,"ultrathinkAvailable":false},"effective":{"model":null}},"subtype":"success"},"type":"control_response"}}
|
||||
{"from":"shim","msg":{"message":{"content":[{"text":"Run the Bash command `sleep 5 && echo done`, then tell me its output in one line.","type":"text"}],"role":"user"},"origin":{"kind":"human"},"parent_tool_use_id":null,"session_id":"","type":"user","uuid":"750456ba-c54c-493b-bb61-40a9d825a457"}}
|
||||
{"from":"cli","msg":{"command_uuid":"750456ba-c54c-493b-bb61-40a9d825a457","session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","state":"queued","type":"command_lifecycle","uuid":"b57b173d-a184-4e10-8ac6-46bd57c905b2","written_at":"2026-12-03T13:52:52.103Z"}}
|
||||
{"from":"cli","msg":{"command_uuid":"750456ba-c54c-493b-bb61-40a9d825a457","session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","state":"started","type":"command_lifecycle","uuid":"cd26e730-c57b-49c0-bfed-0ed2202ba6f5","written_at":"2026-12-03T13:52:52.104Z"}}
|
||||
{"from":"cli","msg":{"additional_directories":[],"analytics_disabled":false,"apiKeySource":"none","capabilities":["interrupt_receipt_v1","interrupt_cancel_queued_v1","interrupt_send_now_v1","interrupt_requeue_taken_v1","msg_lifecycle_v1","request_marker_lists_v1","ask_user_question_unanswered_v1","lifecycle_wakeup_source_v1","sdk_mcp_tools_list_changed","sdk_mcp_manifests","mcp_read_resource_v1","mcp_tool_ui_meta_v1","ui_surface_v1","mcp_call_result_not_for_model_v1","mcp_call_soft_error_result_v1","mcp_call_check_permissions_v1","voice_call_talk_line_v1","withdrawn_files_note_v2","withdrawn_tools_v1","ui_pane_widget_v1","reload_plugins_refuse_if_busy_v1","get_usage_detached_v1","silent_resend_files_v1","lifecycle_idle_v1","comment_images_v1"],"claude_code_version":"2.1.335","cwd":"/private/var/folders/vh/wtcmszn53mvbqcdfy6xrrg5w0000gn/T/.tmpbIsGYj","fast_mode_state":"off","model":"claude-haiku-5-5","original_cwd":"/private/var/folders/vh/wtcmszn53mvbqcdfy6xrrg5w0000gn/T/.tmpbIsGYj","output_style":"default","per_turn_effort_active":true,"permissionMode":"default","product_feedback_disabled":false,"sandbox_enabled":false,"scratchpad_path":"/private/tmp/claude-501/s/443805216073/scratchpad","served_by_anthropic":true,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","startup_timing":{"entrypoint":"claude-vscode","flag_fetch_kick":"not_eligible","flag_fetch_kick_judged_at_ms":84,"hooks_init_origin_ms":{"official_plugin":79,"other_plugin":23,"user_settings":51},"hooks_init_source":"startup","hooks_init_without_silent_ms":{"any":79,"own":79},"phase_start_ms":{"first_message_handle_ms":299,"first_message_read_ms":0,"grove_check_ms":193,"headless_post_load_ms":273,"headless_prologue_ms":192,"hooks_init_ms":184,"init_emit_ms":361,"initial_messages_load_ms":196,"input_ready_ms":0,"mcp_client_module_load_ms":200,"mcp_config_wait_ms":175,"mcp_connect_ms":188,"mcp_prewait_ms":300,"model_catalog_decision_ms":170,"node_boot_ms":0,"permission_context_ms":90,"pre_action_client_data_url_ms":84,"pre_action_init_ms":45,"pre_action_managed_settings_ms":84,"pre_action_mdm_keychain_ms":44,"pre_action_migrations_ms":84,"pre_action_ms":44,"print_import_ms":189,"prompt_submit_hooks_ms":319,"qe_plugin_skills_load_ms":360,"qe_system_prompt_ms":302,"sdk_mcp_update_ms":299,"settings_load_ms":43,"setup_file_watcher_ms":119,"setup_hooks_snapshot_ms":119,"setup_import_ms":93,"setup_ms":96,"setup_release_notes_ms":120,"setup_uds_dir_ms":97,"setup_uds_listen_ms":116,"setup_uds_messaging_ms":95,"setup_uds_publish_ms":119,"skills_load_ms":96,"tools_commands_load_ms":132},"phases":{"first_message_handle_cpu_ms":0,"first_message_handle_loop_lag_ms":0,"first_message_handle_ms":0,"first_message_read_ms":299,"grove_check_ms":2,"headless_post_load_ms":1,"headless_prologue_ms":3,"hooks_init_ms":89,"init_emit_ms":1,"initial_messages_load_ms":77,"input_ready_ms":280,"mcp_client_module_load_ms":0,"mcp_config_load_ms":67,"mcp_config_wait_ms":2,"mcp_connect_ms":1,"mcp_prewait_ms":0,"model_catalog_decision_ms":2,"node_boot_ms":43,"permission_context_ms":3,"pre_action_client_data_url_ms":0,"pre_action_init_ms":39,"pre_action_managed_settings_ms":1,"pre_action_mdm_keychain_ms":1,"pre_action_migrations_ms":0,"pre_action_ms":45,"print_import_ms":3,"prompt_submit_hooks_ms":38,"qe_plugin_skills_load_ms":1,"qe_system_prompt_ms":5,"sdk_mcp_update_ms":0,"settings_load_ms":0,"setup_file_watcher_ms":0,"setup_hooks_snapshot_ms":0,"setup_import_ms":0,"setup_ms":32,"setup_release_notes_ms":9,"setup_uds_dir_ms":19,"setup_uds_listen_ms":3,"setup_uds_messaging_ms":24,"setup_uds_publish_ms":0,"skills_load_ms":69,"tools_commands_load_ms":38},"plugin_full_loads":0,"sdk_mcp_dial_runs":0,"sdk_mcp_servers_dialed":0,"time_origin_ms":1796305971804.1318,"user_context_builds":2,"warm_spare_claimed":false},"subtype":"init","terminal_slash_commands":["doctor","send-to-project","color","focus","reload-plugins"],"type":"system","ultrathink_available":false,"ultrathink_typed_raises":false,"user_message_uuids":["750456ba-c54c-493b-bb61-40a9d825a457"],"uuid":"4614d51b-c114-4e3a-87c1-474dd3221ccb","view_mode":"default","written_at":"2026-12-03T13:52:52.166Z"}}
|
||||
{"from":"cli","msg":{"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","status":"requesting","subtype":"status","type":"system","user_message_uuids":["750456ba-c54c-493b-bb61-40a9d825a457"],"uuid":"1334ad42-52e2-4940-a881-df02701bbce2","written_at":"2026-12-03T13:52:52.168Z"}}
|
||||
{"from":"cli","msg":{"rate_limit_info":{"isUsingOverage":false,"overageDisabledReason":"out_of_credits","overageStatus":"rejected","rateLimitType":"five_hour","resetsAt":1796320200,"status":"allowed","unifiedWindows":{"five_hour":{"resetsAt":1796320200,"status":"allowed","utilization":0.22},"seven_day":{"resetsAt":1796889600,"status":"allowed","utilization":0.13}}},"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","type":"rate_limit_event","uuid":"2d31cd09-90af-4542-9ab8-d6d35208343a","written_at":"2026-12-03T13:52:52.848Z"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuMVnw6EQjt4etKk278","event":{"message":{"container":null,"content":[],"context_management":null,"diagnostics":null,"id":"msg_011CheuMVnw6EQjt4etKk278","input_transformations":[],"model":"claude-haiku-5-5","role":"assistant","stop_details":null,"stop_reason":null,"stop_sequence":null,"type":"message","usage":{"cache_creation":{"ephemeral_1h_input_tokens":14749,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":14749,"cache_read_input_tokens":28109,"inference_geo":"global","input_tokens":2,"output_tokens":16,"service_tier":"standard","speed":"standard"}},"type":"message_start"},"owed_rows":[],"parent_tool_use_id":null,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","thinking_display":"summarized","ttft_ms":870,"type":"stream_event","user_message_uuid":"750456ba-c54c-493b-bb61-40a9d825a457","user_message_uuids":["750456ba-c54c-493b-bb61-40a9d825a457"],"uuid":"a07fd809-d225-4ae9-8a9a-1cfcd3ba452b"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuMVnw6EQjt4etKk278","event":{"content_block":{"caller":{"type":"direct"},"id":"toolu_013cYTr5SPmttma9grssUDvs","input":{},"name":"Bash","type":"tool_use"},"index":0,"type":"content_block_start"},"parent_tool_use_id":null,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","type":"stream_event","uuid":"d87d4b0c-0817-44f3-ba3d-506b145416eb"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuMVnw6EQjt4etKk278","event":{"delta":{"partial_json":"","type":"input_json_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","type":"stream_event","uuid":"7ebaa4fa-4334-42cd-87b9-86efb45b06fd"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuMVnw6EQjt4etKk278","event":{"delta":{"partial_json":"{\"command\": \"sleep 5","type":"input_json_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","type":"stream_event","uuid":"92f03d38-e933-444a-af9e-5d97a3bc17e1"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuMVnw6EQjt4etKk278","event":{"delta":{"partial_json":" && echo done","type":"input_json_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","type":"stream_event","uuid":"156dfb71-8647-402b-81f1-d28209de7f6b"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuMVnw6EQjt4etKk278","event":{"delta":{"partial_json":"\", \"description\": \"S","type":"input_json_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","type":"stream_event","uuid":"f2218947-8767-4812-b6e9-5081d444668e"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuMVnw6EQjt4etKk278","event":{"delta":{"partial_json":"leep 5 seconds","type":"input_json_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","type":"stream_event","uuid":"645079d4-6f4f-403c-aef0-add49e320bdb"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuMVnw6EQjt4etKk278","event":{"delta":{"partial_json":" then echo done","type":"input_json_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","type":"stream_event","uuid":"fc1582cb-4fe7-4747-b65a-5d57351c1749"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuMVnw6EQjt4etKk278","event":{"delta":{"partial_json":"\"}","type":"input_json_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","type":"stream_event","uuid":"8de2ab6a-1c5f-43be-99c5-accf562bded5"}}
|
||||
{"from":"cli","msg":{"message":{"container":null,"content":[{"caller":{"type":"direct"},"id":"toolu_013cYTr5SPmttma9grssUDvs","input":{"command":"sleep 5 && echo done","description":"Sleep 5 seconds then echo done"},"name":"Bash","type":"tool_use"}],"context_management":null,"diagnostics":null,"id":"msg_011CheuMVnw6EQjt4etKk278","input_transformations":[],"model":"claude-haiku-5-5","role":"assistant","stop_details":null,"stop_reason":null,"stop_sequence":null,"type":"message","usage":{"cache_creation":{"ephemeral_1h_input_tokens":14749,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":14749,"cache_read_input_tokens":28109,"inference_geo":"global","input_tokens":2,"output_tokens":16,"service_tier":"standard","speed":"standard"}},"parent_tool_use_id":null,"request_id":"req_011CheuMVa2bRTBYmxzHrdZU","session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","timestamp":"2026-12-03T13:52:53.341Z","type":"assistant","user_message_uuid":"750456ba-c54c-493b-bb61-40a9d825a457","user_message_uuids":["750456ba-c54c-493b-bb61-40a9d825a457"],"uuid":"543df181-f94c-4c59-8a54-6790d7c146fe","wire_tool_inputs":{"toolu_013cYTr5SPmttma9grssUDvs":{"command":"sleep 5 && echo done","description":"Sleep 5 seconds then echo done"}}}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuMVnw6EQjt4etKk278","event":{"index":0,"type":"content_block_stop"},"parent_tool_use_id":null,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","type":"stream_event","uuid":"c95ced13-7ba7-4081-96dc-72e2e1ee9c67"}}
|
||||
{"from":"cli","msg":{"content":"A hook gave no usable answer, so it didn't check this action.","hook_no_verdict":{"hook_event":"PreToolUse","timed_out":false,"tool_use_id":"toolu_013cYTr5SPmttma9grssUDvs"},"level":"warning","session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","subtype":"informational","tag":"hook_no_verdict","type":"system","uuid":"c5ce69e8-b5c8-4e04-b6af-b1a4d9760a3d","written_at":"2026-12-03T13:52:53.356Z"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuMVnw6EQjt4etKk278","event":{"context_management":{"applied_edits":[]},"delta":{"container":null,"stop_details":null,"stop_reason":"tool_use","stop_sequence":null},"type":"message_delta","usage":{"cache_creation_input_tokens":14749,"cache_read_input_tokens":28109,"input_tokens":2,"iterations":[{"cache_creation":{"ephemeral_1h_input_tokens":14749,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":14749,"cache_read_input_tokens":28109,"input_tokens":2,"output_tokens":90,"type":"message"}],"output_tokens":90,"output_tokens_details":{"thinking_tokens":0}}},"parent_tool_use_id":null,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","type":"stream_event","uuid":"f1c31fc2-e095-4a52-a92c-752feb90d83c"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuMVnw6EQjt4etKk278","event":{"type":"message_stop"},"parent_tool_use_id":null,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","type":"stream_event","uuid":"5fd7d71c-5822-414a-b3e1-d11395fd7022"}}
|
||||
{"from":"shim","msg":{"message":{"content":[{"text":"Also end your answer with the word BANANA.","type":"text"}],"role":"user"},"origin":{"kind":"human"},"parent_tool_use_id":null,"priority":"next","session_id":"","type":"user","uuid":"6e50c1f5-335e-4d89-a2ef-725e845b57ee"}}
|
||||
{"from":"cli","msg":{"command_uuid":"6e50c1f5-335e-4d89-a2ef-725e845b57ee","session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","state":"queued","type":"command_lifecycle","uuid":"d4038320-e65f-4937-b14c-8948234e08c4","written_at":"2026-12-03T13:52:55.103Z"}}
|
||||
{"from":"shim","msg":{"request":{"cancel_queued":true,"subtype":"interrupt"},"request_id":"req_3","type":"control_request"}}
|
||||
{"from":"cli","msg":{"command_uuid":"6e50c1f5-335e-4d89-a2ef-725e845b57ee","session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","state":"cancelled","type":"command_lifecycle","uuid":"24e8c7aa-31e8-455f-a456-12ee15e0e8f9","written_at":"2026-12-03T13:52:55.604Z"}}
|
||||
{"from":"cli","msg":{"response":{"request_id":"req_3","response":{"cancelled":["6e50c1f5-335e-4d89-a2ef-725e845b57ee"],"still_queued":[]},"subtype":"success"},"type":"control_response"}}
|
||||
{"from":"cli","msg":{"message":{"content":[{"content":"The user doesn't want to proceed with this tool use. The tool use was rejected (eg. if it was a file edit, the new_string was NOT written to the file). STOP what you are doing and wait for the user to tell you how to proceed. Correction to the text above: this call was stopped while running, not refused before it ran. It may have run in part or in full, and its changes may have been written. No permission prompt was involved. Work it started elsewhere (a remote command, a background process) may still be running, so check before starting the same work again. The instruction to stop and wait still stands.","is_error":true,"tool_use_id":"toolu_013cYTr5SPmttma9grssUDvs","type":"tool_result"}],"role":"user"},"parent_tool_use_id":null,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","timestamp":"2026-12-03T13:52:55.608Z","tool_result_meta":[{"id":"toolu_013cYTr5SPmttma9grssUDvs","non_execution_kind":"user-rejected"}],"tool_use_result":"User rejected tool use","type":"user","uuid":"087df73f-b2fe-42d9-9de4-f3fab77aefe0"}}
|
||||
{"from":"cli","msg":{"message":{"content":[{"text":"[Request interrupted by user for tool use]","type":"text"}],"role":"user"},"parent_tool_use_id":null,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","timestamp":"2026-12-03T13:52:55.610Z","type":"user","uuid":"900c03e1-b662-4e5f-aaf6-384263031910"}}
|
||||
{"from":"cli","msg":{"begun_message_ids":["msg_011CheuMVnw6EQjt4etKk278"],"credential_expires_at":"2026-12-30T17:21:30.368Z","duration_api_ms":1721,"duration_ms":3506,"errors":["[ede_diagnostic] result_type=user last_content_type=n/a stop_reason=tool_use"],"fast_mode_state":"off","is_error":true,"modelUsage":{"claude-haiku-5-5":{"cacheCreationEphemeral1hInputTokens":14749,"cacheCreationEphemeral5mInputTokens":0,"cacheCreationInputTokens":14749,"cacheReadInputTokens":28109,"canonicalModel":"claude-haiku-5-5","contextWindow":1000000,"costBasis":"list","costUSD":0.00340499,"inputTokens":1196,"maxOutputTokens":128000,"outputTokens":109,"provider":"firstParty","thinkingTokens":0,"webSearchRequests":0}},"model_usage_since_last_result":{"claude-haiku-5-5":{"cacheCreationEphemeral1hInputTokens":14749,"cacheCreationEphemeral5mInputTokens":0,"cacheCreationInputTokens":14749,"cacheReadInputTokens":28109,"canonicalModel":"claude-haiku-5-5","contextWindow":1000000,"costBasis":"list","costUSD":0.00340499,"inputTokens":1196,"maxOutputTokens":128000,"outputTokens":109,"provider":"firstParty","thinkingTokens":0,"webSearchRequests":0}},"num_turns":3,"origin":{"kind":"human"},"permission_denials":[],"queued_turn_count":0,"result_index":0,"safety_stops":0,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","stop_reason":"tool_use","subagent_stats":{"by_type":{},"completed":0,"failed":0,"killed":{"parent":0,"system":0,"user":0},"max_depth":0,"refused":{"budget":0,"concurrency_limit":0,"depth_limit":0},"requested":{"background":0,"foreground":0,"unset":0},"spawned":0,"spawned_by_subagents":0,"started_in_background":0},"subtype":"error_during_execution","terminal_reason":"aborted_tools","total_cost_usd":0.00340499,"type":"result","usage":{"cache_creation":{"ephemeral_1h_input_tokens":14749,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":14749,"cache_read_input_tokens":28109,"fallback_credit":null,"inference_geo":"global","input_tokens":2,"iterations":[{"cache_creation":{"ephemeral_1h_input_tokens":14749,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":14749,"cache_read_input_tokens":28109,"input_tokens":2,"output_tokens":90,"type":"message"}],"output_tokens":90,"output_tokens_details":{"thinking_tokens":0},"server_tool_use":{"web_fetch_requests":0,"web_search_requests":0},"service_tier":"standard","speed":"standard"},"user_message_uuid":"750456ba-c54c-493b-bb61-40a9d825a457","user_message_uuids":["750456ba-c54c-493b-bb61-40a9d825a457"],"uuid":"5c62e1de-fdfc-44f7-ae20-cd70b87590e5","written_at":"2026-12-03T13:52:55.613Z"}}
|
||||
{"from":"cli","msg":{"command_uuid":"750456ba-c54c-493b-bb61-40a9d825a457","idle":true,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","state":"cancelled","type":"command_lifecycle","uuid":"53cf7918-cf6e-4c94-984c-8401081fa93e","written_at":"2026-12-03T13:52:55.615Z"}}
|
||||
-24
@@ -1,24 +0,0 @@
|
||||
{
|
||||
"version": 2,
|
||||
"plugins": {
|
||||
"evidence-plugin@evidence-mkt": [
|
||||
{
|
||||
"scope": "user",
|
||||
"installPath": "$HOME/.claude/plugins/cache/evidence-mkt/evidence-plugin/1.2.3",
|
||||
"version": "1.2.3",
|
||||
"installedAt": "2026-11-30T21:50:25.665Z",
|
||||
"lastUpdated": "2026-11-30T21:50:25.665Z",
|
||||
"gitCommitSha": "1111111111111111111111111111111111111111"
|
||||
},
|
||||
{
|
||||
"scope": "project",
|
||||
"projectPath": "$WORKSPACE",
|
||||
"installPath": "$HOME/.claude/plugins/cache/evidence-mkt/evidence-plugin/1.2.3",
|
||||
"version": "1.2.3",
|
||||
"installedAt": "2026-11-30T21:50:25.665Z",
|
||||
"lastUpdated": "2026-11-30T21:50:25.665Z",
|
||||
"gitCommitSha": "1111111111111111111111111111111111111111"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
[marketplaces.evidence-mkt]
|
||||
source_type = "local"
|
||||
source = "$HOME/.codex/.tmp/marketplaces/evidence-mkt"
|
||||
|
||||
[plugins."evidence-plugin@evidence-mkt"]
|
||||
enabled = false
|
||||
@@ -1,19 +0,0 @@
|
||||
// This file is managed automatically.
|
||||
{
|
||||
"installedPlugins": [
|
||||
{
|
||||
"name": "evidence-plugin",
|
||||
"marketplace": "evidence-mkt",
|
||||
"installed_at": "2026-11-30T21:50:25.665Z",
|
||||
"enabled": true,
|
||||
"version": "1.2.3",
|
||||
"cache_path": "$HOME/.copilot/installed-plugins/evidence-mkt/evidence-plugin",
|
||||
"source": {
|
||||
"source": "github",
|
||||
"repo": "acme/plugins",
|
||||
"sha": "1111111111111111111111111111111111111111",
|
||||
"path": "plugins/evidence-plugin"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
{
|
||||
"evidence-extension": {
|
||||
"overrides": [
|
||||
"$HOME/*",
|
||||
"!$WORKSPACE/*"
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -63,7 +63,7 @@ pub(crate) fn stream_batched<T>(
|
||||
}
|
||||
}
|
||||
flush(&mut batch, on_batch);
|
||||
Ok((lines.finish(cancel)?.success(), stderr_tail))
|
||||
Ok((lines.finish(cancel)?, stderr_tail))
|
||||
}
|
||||
|
||||
#[cfg(all(test, unix))]
|
||||
|
||||
@@ -29,7 +29,7 @@ pub fn plan(root: &Path, model: &BuildModel, module: &Path, cache: &Path) -> Ide
|
||||
let repo = crate::maven::local_repository_for(&p.options);
|
||||
args.extend([
|
||||
"process-resources".into(),
|
||||
crate::maven::plugin_goal("help:evaluate", repo.as_deref(), crate::maven::maven_version(&p.command)),
|
||||
crate::maven::plugin_goal("help:evaluate", repo.as_deref()),
|
||||
"-Dexpression=project.build.outputDirectory".into(),
|
||||
format!("-Doutput={}", manifest.display()),
|
||||
]);
|
||||
|
||||
@@ -17,13 +17,12 @@ pub use launch_resources::process_launch_resources;
|
||||
pub use modules::record_module_build;
|
||||
pub use single::{
|
||||
SingleFileTarget, compile_file_plan, compile_file_plan_cancellable, find_javac, gradle_compile_file_plan,
|
||||
has_gradle_file_target, javac_step, maven_system_classpath, module_classpath, module_classpath_without_build,
|
||||
module_classpaths, single_file_classpath, single_file_target,
|
||||
has_gradle_file_target, javac_step, module_classpath, module_classpath_without_build, module_classpaths,
|
||||
single_file_classpath, single_file_target,
|
||||
};
|
||||
pub use structure::{
|
||||
StructureBuildContext, StructureJdk, StructureRoots, artifact_file, artifact_output, language_release,
|
||||
structure_build, structure_build_war, structure_compile_file_plan, structure_outputs, structure_plan,
|
||||
structure_war_plan, structure_web_artifacts,
|
||||
StructureJdk, StructureRoots, artifact_file, artifact_output, language_release, structure_compile_file_plan,
|
||||
structure_outputs, structure_plan, structure_war_plan, structure_web_artifacts,
|
||||
};
|
||||
pub use tsc_watch::{tsc_watch, tsc_watch_roots};
|
||||
pub use up_to_date::{menu_up_to_date, record_menu_build};
|
||||
@@ -359,14 +358,16 @@ pub(super) fn maven_steps(
|
||||
};
|
||||
// The reactor root containing the module builds it with what it depends on (`-pl … -am`).
|
||||
let rel = rel_str(root, module);
|
||||
let Some(target) = m.projects.iter().find(|p| p.dir == rel) else {
|
||||
if !m.projects.iter().any(|p| p.dir == rel) {
|
||||
return Err(IdeError::not_found("no linked Maven project found for module"));
|
||||
};
|
||||
let top = maven_reactor(m, &rel).ok_or_else(|| IdeError::not_found("no linked Maven project found for module"))?;
|
||||
if let Some(pl) = maven::module_selector(root, top, target) {
|
||||
return Ok(vec![step(top, &["-pl".into(), pl, "-am".into()])]);
|
||||
}
|
||||
Ok(vec![step(top, &[])])
|
||||
let top = maven_reactor(m, &rel).ok_or_else(|| IdeError::not_found("no linked Maven project found for module"))?;
|
||||
let top_dir = subdir(root, &top.dir);
|
||||
if module == top_dir {
|
||||
return Ok(vec![step(top, &[])]);
|
||||
}
|
||||
let pl = module.strip_prefix(&top_dir).map(|r| r.to_string_lossy().replace('\\', "/")).unwrap_or(rel);
|
||||
Ok(vec![step(top, &["-pl".into(), pl, "-am".into()])])
|
||||
}
|
||||
|
||||
fn gradle_steps(root: &Path, model: &BuildModel, kind: BuildKind, module: Option<&Path>) -> IdeResult<Vec<BuildStep>> {
|
||||
@@ -420,14 +421,13 @@ fn cargo_steps(dir: &Path, kind: BuildKind) -> Vec<BuildStep> {
|
||||
}
|
||||
|
||||
/// CLion's Build Project for a CMake project: configures the build directory when it has no
|
||||
/// `CMakeCache.txt` or no File API reply yet, then `cmake --build` (`--clean-first` to rebuild), one job per
|
||||
/// `CMakeCache.txt` yet, then `cmake --build` (`--clean-first` to rebuild), one job per
|
||||
/// logical CPU unless the profile's build arguments choose a count. The directory and
|
||||
/// options come from the CMake profile; without one, a configured directory of the project
|
||||
/// (the first by name), else `build`, as the generated run configurations use.
|
||||
fn cmake_steps(dir: &Path, kind: BuildKind, profile: Option<&CMakeProfile>) -> Vec<BuildStep> {
|
||||
let build_dir = match profile {
|
||||
Some(p) if !p.build_dir.trim().is_empty() => p.build_dir.trim().to_owned(),
|
||||
Some(p) if p.build_type.is_empty() => "cmake-build-default".into(),
|
||||
Some(p) => format!("cmake-build-{}", p.build_type.to_lowercase()),
|
||||
None => {
|
||||
let mut configured: Vec<String> = std::fs::read_dir(dir)
|
||||
@@ -444,49 +444,18 @@ fn cmake_steps(dir: &Path, kind: BuildKind, profile: Option<&CMakeProfile>) -> V
|
||||
let build_type = profile.map_or("Debug", |p| p.build_type.as_str());
|
||||
let env = profile.map(|p| p.env.clone()).unwrap_or_default();
|
||||
let mut steps = Vec::new();
|
||||
let preset = profile.and_then(|p| p.preset.as_ref());
|
||||
// The profile's toolchain may bring its own cmake.
|
||||
let cmake = profile.and_then(|p| p.cmake_program.as_ref()).map_or("cmake".into(), |c| c.to_string_lossy());
|
||||
let cmake = cmake.as_ref();
|
||||
let build_path = dir.join(&build_dir);
|
||||
// Configured without the File API queries (by another tool, or before they were written):
|
||||
// configure again so the targets, and their run configurations, become known.
|
||||
let fresh = !build_path.join("CMakeCache.txt").is_file();
|
||||
if fresh || !build_path.join(ide_core::cmake_file_api::REPLY).is_dir() {
|
||||
// Best effort: without the queries the build still runs, only the targets stay unknown.
|
||||
let _ = ide_core::cmake_file_api::write_queries(&build_path);
|
||||
let mut configure = match preset {
|
||||
// The preset sets the generator and cache variables.
|
||||
Some(preset) => BuildStep::new(cmake, &["--preset", &preset.configure], dir, Format::Gcc),
|
||||
None => {
|
||||
let mut configure = BuildStep::new(cmake, &["-S", ".", "-B", &build_dir], dir, Format::Gcc);
|
||||
// A configured directory keeps its generator (CMake refuses another one) and,
|
||||
// without a profile, its build type.
|
||||
if let Some(p) = profile.filter(|p| fresh && !p.generator.trim().is_empty()) {
|
||||
configure.args.extend(["-G".into(), p.generator.clone()]);
|
||||
}
|
||||
if fresh || profile.is_some() {
|
||||
configure.args.push(format!("-DCMAKE_BUILD_TYPE={build_type}"));
|
||||
}
|
||||
configure
|
||||
}
|
||||
};
|
||||
if !dir.join(&build_dir).join("CMakeCache.txt").is_file() {
|
||||
let mut configure = BuildStep::new("cmake", &["-S", ".", "-B", &build_dir], dir, Format::Gcc);
|
||||
if let Some(p) = profile.filter(|p| !p.generator.trim().is_empty()) {
|
||||
configure.args.extend(["-G".into(), p.generator.clone()]);
|
||||
}
|
||||
configure.args.push(format!("-DCMAKE_BUILD_TYPE={build_type}"));
|
||||
configure.args.push("-DCMAKE_EXPORT_COMPILE_COMMANDS=ON".into());
|
||||
configure.args.extend(profile.map(|p| p.cmake_args.clone()).unwrap_or_default());
|
||||
configure.env = env.clone();
|
||||
steps.push(configure);
|
||||
}
|
||||
let mut build = match preset.and_then(|p| p.build.as_deref()) {
|
||||
Some(build) => BuildStep::new(cmake, &["--build", "--preset", build], dir, Format::Gcc),
|
||||
None => {
|
||||
let mut build = BuildStep::new(cmake, &["--build", &build_dir], dir, Format::Gcc);
|
||||
// CLion's "Default" build type: no configuration at all.
|
||||
if !build_type.is_empty() {
|
||||
build.args.extend(["--config".into(), build_type.into()]);
|
||||
}
|
||||
build
|
||||
}
|
||||
};
|
||||
let mut build = BuildStep::new("cmake", &["--build", &build_dir, "--config", build_type], dir, Format::Gcc);
|
||||
if kind == BuildKind::Rebuild {
|
||||
build.args.push("--clean-first".into());
|
||||
}
|
||||
@@ -569,77 +538,6 @@ fn dotnet_steps(dir: &Path, kind: BuildKind) -> IdeResult<Vec<BuildStep>> {
|
||||
Ok(vec![step])
|
||||
}
|
||||
|
||||
/// A `dotnet` command the .NET tool window runs on a solution or project file.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum DotnetCommand {
|
||||
Build,
|
||||
Clean,
|
||||
Restore,
|
||||
}
|
||||
|
||||
/// `dotnet build` / `clean` / `restore` of one solution or project file, followed by `options`
|
||||
/// (`--configuration`, `--framework`, `-p:…`).
|
||||
pub fn dotnet_command_plan(file: &Path, command: DotnetCommand, options: &[String]) -> IdeResult<BuildPlan> {
|
||||
let verb = match command {
|
||||
DotnetCommand::Build => "build",
|
||||
DotnetCommand::Clean => "clean",
|
||||
DotnetCommand::Restore => "restore",
|
||||
};
|
||||
dotnet_file_plan(file, verb, true, options)
|
||||
}
|
||||
|
||||
/// `dotnet publish` of one project file with the publish dialog's `options` (`-p:PublishProfile=…`,
|
||||
/// or `--configuration` / `--runtime` / `--output`).
|
||||
pub fn dotnet_publish_plan(file: &Path, options: &[String]) -> IdeResult<BuildPlan> {
|
||||
dotnet_file_plan(file, "publish", false, options)
|
||||
}
|
||||
|
||||
fn dotnet_file_plan(file: &Path, verb: &str, solutions: bool, options: &[String]) -> IdeResult<BuildPlan> {
|
||||
let ext = file.extension().map(|e| e.to_string_lossy().to_ascii_lowercase()).unwrap_or_default();
|
||||
let accepted = match ext.as_str() {
|
||||
"csproj" | "fsproj" | "vbproj" => true,
|
||||
"sln" | "slnx" => solutions,
|
||||
_ => false,
|
||||
};
|
||||
let (Some(dir), Some(name), true) = (file.parent(), file.file_name(), accepted) else {
|
||||
return Err(IdeError::invalid(if solutions {
|
||||
format!("dotnet {verb} needs a solution or a C#, F# or VB project")
|
||||
} else {
|
||||
format!("dotnet {verb} needs a C#, F# or VB project")
|
||||
}));
|
||||
};
|
||||
if !file.is_file() {
|
||||
return Err(IdeError::not_found(format!("{} does not exist", file.display())));
|
||||
}
|
||||
let name = name.to_string_lossy();
|
||||
let mut step = BuildStep::new("dotnet", &[verb, &name, "-nologo", "-clp:NoSummary"], dir, Format::Msbuild);
|
||||
step.args.extend_from_slice(options);
|
||||
step.env.insert("MSBUILDTERMINALLOGGER".into(), "off".into());
|
||||
Ok(BuildPlan { system: BuildSystem::Dotnet, title: format!("dotnet {verb} {name}"), steps: vec![step] })
|
||||
}
|
||||
|
||||
/// `dotnet format` of a solution or C# / VB project file; `verify` only reports what it would
|
||||
/// change and fails when there is anything.
|
||||
pub fn dotnet_format_plan(file: &Path, verify: bool) -> IdeResult<BuildPlan> {
|
||||
let ext = file.extension().map(|e| e.to_string_lossy().to_ascii_lowercase()).unwrap_or_default();
|
||||
let (Some(dir), Some(name), true) =
|
||||
(file.parent(), file.file_name(), matches!(ext.as_str(), "sln" | "slnx" | "csproj" | "vbproj"))
|
||||
else {
|
||||
return Err(IdeError::invalid("dotnet format needs a solution or a C# / VB project"));
|
||||
};
|
||||
if !file.is_file() {
|
||||
return Err(IdeError::not_found(format!("{} does not exist", file.display())));
|
||||
}
|
||||
let name = name.to_string_lossy();
|
||||
// Verbose output names the files it changed; verifying changes none.
|
||||
let options: &[&str] = if verify { &["--verify-no-changes"] } else { &["--verbosity", "normal"] };
|
||||
let mut step = BuildStep::new("dotnet", &["format", &name], dir, Format::Msbuild);
|
||||
step.args.extend(options.iter().map(|o| (*o).to_owned()));
|
||||
step.env.insert("MSBUILDTERMINALLOGGER".into(), "off".into());
|
||||
Ok(BuildPlan { system: BuildSystem::Dotnet, title: format!("dotnet format {name}"), steps: vec![step] })
|
||||
}
|
||||
|
||||
fn ts_steps(dir: &Path, kind: BuildKind) -> Vec<BuildStep> {
|
||||
let script = has_build_script(dir);
|
||||
if script && (kind == BuildKind::Artifacts || !dir.join("tsconfig.json").is_file()) {
|
||||
@@ -1028,7 +926,17 @@ pub fn has_non_java_sources(module: &Path) -> bool {
|
||||
}
|
||||
|
||||
fn reactor_projects<'a>(m: &'a maven::MavenModel, top: &'a maven::MavenProject) -> Vec<&'a maven::MavenProject> {
|
||||
maven::reactor_projects(m, top)
|
||||
let mut projects = Vec::new();
|
||||
let mut pending = vec![top];
|
||||
let mut seen = HashSet::new();
|
||||
while let Some(p) = pending.pop() {
|
||||
if !seen.insert(&p.pom) {
|
||||
continue;
|
||||
}
|
||||
projects.push(p);
|
||||
pending.extend(m.projects.iter().filter(|child| p.modules.contains(&child.pom)));
|
||||
}
|
||||
projects
|
||||
}
|
||||
|
||||
/// A step running Maven, its output parsed as Maven's.
|
||||
@@ -1054,7 +962,7 @@ pub(crate) fn reactor_projects_of<'a>(
|
||||
}
|
||||
|
||||
fn maven_reactor<'a>(m: &'a maven::MavenModel, module: &str) -> Option<&'a maven::MavenProject> {
|
||||
maven::reactor_for_dir(m, module)
|
||||
m.projects.iter().filter(|p| !p.aggregated).find(|top| reactor_projects(m, top).iter().any(|p| p.dir == module))
|
||||
}
|
||||
|
||||
/// Launch module first, followed by its upstream modules in the same Maven reactor.
|
||||
@@ -1078,7 +986,7 @@ fn maven_launch_projects<'a>(
|
||||
}
|
||||
projects.push(p);
|
||||
for dep in &p.dependencies {
|
||||
if !dep.resolved() || dep.scope == "system" || (dep.scope == "test" && (!test || p.pom != start.pom)) {
|
||||
if !dep.resolved() || (dep.scope == "test" && (!test || p.pom != start.pom)) {
|
||||
continue;
|
||||
}
|
||||
if let Some(upstream) = reactor.iter().find(|u| {
|
||||
@@ -1751,15 +1659,6 @@ mod tests {
|
||||
"an unconfigured project is configured first"
|
||||
);
|
||||
write(&cm, "cmake-build-release/CMakeCache.txt", "");
|
||||
let p =
|
||||
plan(&cm, &BuildModel::default(), BuildKind::Rebuild, None, None, None, &CancellationToken::new()).unwrap();
|
||||
assert_eq!(
|
||||
p.steps[0].args,
|
||||
["-S", ".", "-B", "cmake-build-release", "-DCMAKE_EXPORT_COMPILE_COMMANDS=ON"],
|
||||
"configured again, as it was, when it has no File API reply"
|
||||
);
|
||||
assert!(cm.join("cmake-build-release/.cmake/api/v1/query/client-openidea/codemodel-v2").is_file());
|
||||
std::fs::create_dir_all(cm.join("cmake-build-release").join(ide_core::cmake_file_api::REPLY)).unwrap();
|
||||
let p =
|
||||
plan(&cm, &BuildModel::default(), BuildKind::Rebuild, None, None, None, &CancellationToken::new()).unwrap();
|
||||
assert_eq!(
|
||||
@@ -1795,33 +1694,6 @@ mod tests {
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(p.steps[0].args[..4], ["-S", ".", "-B", "cmake-build-debug"]);
|
||||
let preset = CMakeProfile {
|
||||
build_dir: "out/dev".into(),
|
||||
preset: Some(ide_core::settings::CMakePresetRef {
|
||||
configure: "dev".into(),
|
||||
build: Some("dev-build".into()),
|
||||
..Default::default()
|
||||
}),
|
||||
..CMakeProfile::default()
|
||||
};
|
||||
let p = plan(
|
||||
&cm,
|
||||
&BuildModel::default(),
|
||||
BuildKind::Build,
|
||||
None,
|
||||
Some(std::slice::from_ref(&preset)),
|
||||
None,
|
||||
&CancellationToken::new(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
args(&p),
|
||||
[
|
||||
"--preset dev -DCMAKE_EXPORT_COMPILE_COMMANDS=ON".to_owned(),
|
||||
format!("--build --preset dev-build {jobs}")
|
||||
],
|
||||
"a preset profile configures and builds with its presets"
|
||||
);
|
||||
|
||||
let siblings = tmp.path().join("siblings");
|
||||
write(&siblings, "core/pom.xml", "<project><artifactId>core</artifactId></project>");
|
||||
@@ -2121,34 +1993,6 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sibling_reactor_launch_uses_relative_module_selector() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
write(
|
||||
root,
|
||||
"parent/pom.xml",
|
||||
"<project><modelVersion>4.0.0</modelVersion><groupId>t</groupId><artifactId>parent</artifactId><version>1</version><packaging>pom</packaging><modules><module>../common</module><module>../app</module></modules></project>",
|
||||
);
|
||||
write(
|
||||
root,
|
||||
"common/pom.xml",
|
||||
"<project><modelVersion>4.0.0</modelVersion><parent><groupId>t</groupId><artifactId>parent</artifactId><version>1</version><relativePath>../parent/pom.xml</relativePath></parent><artifactId>common</artifactId></project>",
|
||||
);
|
||||
write(
|
||||
root,
|
||||
"app/pom.xml",
|
||||
"<project><modelVersion>4.0.0</modelVersion><parent><groupId>t</groupId><artifactId>parent</artifactId><version>1</version><relativePath>../parent/pom.xml</relativePath></parent><artifactId>app</artifactId></project>",
|
||||
);
|
||||
let model = BuildModel { maven: Some(maven::load(root)), ..Default::default() };
|
||||
let plan =
|
||||
launch_plan(root, &model, &root.join("app"), false, BuildKind::Build, &CancellationToken::new()).unwrap();
|
||||
assert_eq!(plan.steps.len(), 1);
|
||||
assert_eq!(plan.steps[0].cwd, root.join("parent"));
|
||||
let pl = plan.steps[0].args.iter().position(|a| a == "-pl").unwrap();
|
||||
assert_eq!(&plan.steps[0].args[pl..pl + 3], &["-pl", "../app", "-am"]);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn external_launch_returns_upstream_outputs_and_blocks_failure_or_cancellation() {
|
||||
@@ -2318,142 +2162,4 @@ mod tests {
|
||||
assert_eq!(whole.steps[0].cwd, root);
|
||||
assert_eq!(whole.steps[0].args, ["build", "./..."]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dotnet_format_runs_on_the_given_solution_or_project() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
for name in ["App.sln", "App.slnx", "App.csproj", "App.vbproj", "App.fsproj", "A.cs"] {
|
||||
std::fs::write(dir.path().join(name), "").unwrap();
|
||||
}
|
||||
for name in ["App.sln", "App.slnx", "App.csproj", "App.vbproj"] {
|
||||
let plan = super::dotnet_format_plan(&dir.path().join(name), false).unwrap();
|
||||
assert_eq!(plan.steps[0].args, ["format", name, "--verbosity", "normal"]);
|
||||
assert_eq!(plan.steps[0].cwd, dir.path());
|
||||
let verify = super::dotnet_format_plan(&dir.path().join(name), true).unwrap();
|
||||
assert_eq!(verify.steps[0].args, ["format", name, "--verify-no-changes"]);
|
||||
}
|
||||
for name in ["App.fsproj", "A.cs", "Missing.sln"] {
|
||||
assert!(super::dotnet_format_plan(&dir.path().join(name), false).is_err(), "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The real `dotnet format` (`-- --ignored`): verifying reports and changes nothing, formatting rewrites.
|
||||
#[test]
|
||||
#[ignore = "needs the .NET SDK"]
|
||||
fn dotnet_format_reports_and_rewrites_with_the_real_sdk() {
|
||||
let found = std::process::Command::new("dotnet").arg("--version").output().is_ok_and(|o| o.status.success());
|
||||
if !found {
|
||||
return;
|
||||
}
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap();
|
||||
for args in [
|
||||
&["new", "console", "-n", "App", "-o", "App"][..],
|
||||
&["new", "sln", "-n", "Sln", "--format", "slnx"],
|
||||
&["new", "sln", "-n", "Classic", "--format", "sln"],
|
||||
&["sln", "Sln.slnx", "add", "App/App.csproj"],
|
||||
&["sln", "Classic.sln", "add", "App/App.csproj"],
|
||||
] {
|
||||
assert!(std::process::Command::new("dotnet").args(args).current_dir(&root).status().unwrap().success());
|
||||
}
|
||||
let source = root.join("App").join("中 A.cs");
|
||||
let messy = "class A{void M( ){var x=1;}}\n";
|
||||
for target in ["Sln.slnx", "Classic.sln", "App/App.csproj"] {
|
||||
std::fs::write(&source, messy).unwrap();
|
||||
let run = |verify| {
|
||||
let plan = super::dotnet_format_plan(&root.join(target), verify).unwrap();
|
||||
super::run(&root, &plan, &CancellationToken::new(), &|_| {}).unwrap()
|
||||
};
|
||||
let verified = run(true);
|
||||
assert!(!verified.success, "{target}");
|
||||
let message = verified.messages.iter().find(|m| m.code.as_deref() == Some("WHITESPACE")).unwrap();
|
||||
assert!(message.path.as_ref().unwrap().ends_with("中 A.cs"), "{message:?}");
|
||||
assert_eq!(std::fs::read_to_string(&source).unwrap(), messy);
|
||||
assert!(run(false).success, "{target}");
|
||||
assert_ne!(std::fs::read_to_string(&source).unwrap(), messy);
|
||||
assert!(run(true).success, "{target}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dotnet_publish_runs_on_one_project_file() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
for name in ["App.csproj", "App.fsproj", "App.vbproj", "Sln.slnx"] {
|
||||
std::fs::write(dir.path().join(name), "").unwrap();
|
||||
}
|
||||
let options = ["-p:PublishProfile=My Folder".to_owned()];
|
||||
for name in ["App.csproj", "App.fsproj", "App.vbproj"] {
|
||||
let plan = super::dotnet_publish_plan(&dir.path().join(name), &options).unwrap();
|
||||
assert_eq!(
|
||||
plan.steps[0].args,
|
||||
["publish", name, "-nologo", "-clp:NoSummary", "-p:PublishProfile=My Folder"]
|
||||
);
|
||||
}
|
||||
for name in ["Sln.slnx", "Missing.csproj"] {
|
||||
assert!(super::dotnet_publish_plan(&dir.path().join(name), &[]).is_err(), "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dotnet_commands_run_on_one_solution_or_project_file() {
|
||||
use super::DotnetCommand;
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
for name in ["App.csproj", "Sln.sln", "Sln.slnx", "notes.txt"] {
|
||||
std::fs::write(dir.path().join(name), "").unwrap();
|
||||
}
|
||||
let options = ["--configuration".to_owned(), "Release".to_owned()];
|
||||
for (name, command, verb) in [
|
||||
("Sln.sln", DotnetCommand::Build, "build"),
|
||||
("Sln.slnx", DotnetCommand::Clean, "clean"),
|
||||
("App.csproj", DotnetCommand::Restore, "restore"),
|
||||
] {
|
||||
let plan = super::dotnet_command_plan(&dir.path().join(name), command, &options).unwrap();
|
||||
assert_eq!(plan.title, format!("dotnet {verb} {name}"));
|
||||
assert_eq!(plan.steps[0].args, [verb, name, "-nologo", "-clp:NoSummary", "--configuration", "Release"]);
|
||||
assert_eq!(plan.steps[0].cwd, dir.path());
|
||||
}
|
||||
for name in ["notes.txt", "Missing.sln"] {
|
||||
assert!(super::dotnet_command_plan(&dir.path().join(name), DotnetCommand::Build, &[]).is_err(), "{name}");
|
||||
}
|
||||
assert!(super::dotnet_publish_plan(&dir.path().join("Sln.sln"), &[]).is_err(), "publish takes a project");
|
||||
}
|
||||
|
||||
/// The real `dotnet publish` (`-- --ignored`): publishes, reports compile errors, and stops
|
||||
/// when cancelled.
|
||||
#[test]
|
||||
#[ignore = "needs the .NET SDK"]
|
||||
fn dotnet_publish_publishes_fails_and_cancels_with_the_real_sdk() {
|
||||
let found = std::process::Command::new("dotnet").arg("--version").output().is_ok_and(|o| o.status.success());
|
||||
if !found {
|
||||
return;
|
||||
}
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let new = ["new", "console", "-n", "App", "-o", "App"];
|
||||
assert!(std::process::Command::new("dotnet").args(new).current_dir(&root).status().unwrap().success());
|
||||
let project = root.join("App").join("App.csproj");
|
||||
let options = ["--output".to_owned(), "out dir".to_owned()];
|
||||
let plan = super::dotnet_publish_plan(&project, &options).unwrap();
|
||||
|
||||
let published = super::run(&root, &plan, &CancellationToken::new(), &|_| {}).unwrap();
|
||||
assert!(published.success);
|
||||
let output = root.join("App").join("out dir").join("App.dll");
|
||||
assert!(output.is_file());
|
||||
|
||||
std::fs::remove_dir_all(root.join("App").join("out dir")).unwrap();
|
||||
let token = CancellationToken::new();
|
||||
let cancel = token.clone();
|
||||
let result = super::run(&root, &plan, &token, &|e| {
|
||||
if matches!(e, BuildEvent::Output { .. }) {
|
||||
cancel.cancel();
|
||||
}
|
||||
});
|
||||
assert!(result.is_err(), "a cancelled publish is not a result");
|
||||
assert!(!output.exists());
|
||||
|
||||
std::fs::write(root.join("App").join("Program.cs"), "nope\n").unwrap();
|
||||
let failed = super::run(&root, &plan, &CancellationToken::new(), &|_| {}).unwrap();
|
||||
assert!(!failed.success);
|
||||
assert!(failed.messages.iter().any(|m| m.path.as_ref().is_some_and(|p| p.ends_with("Program.cs"))));
|
||||
}
|
||||
}
|
||||
@@ -72,19 +72,15 @@ fn affected_projects(reactor: &[&maven::MavenProject], changed: &HashSet<String>
|
||||
/// `-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(
|
||||
root: &Path,
|
||||
top: &maven::MavenProject,
|
||||
reactor: &[&maven::MavenProject],
|
||||
affected: &HashSet<String>,
|
||||
) -> String {
|
||||
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))
|
||||
.filter_map(|p| maven::module_selector(root, top, p))
|
||||
.map(|p| {
|
||||
Path::new(&p.dir).strip_prefix(top_dir).unwrap_or(Path::new(&p.dir)).to_string_lossy().replace('\\', "/")
|
||||
})
|
||||
.collect();
|
||||
entries.sort();
|
||||
entries.dedup();
|
||||
entries.join(",")
|
||||
}
|
||||
|
||||
@@ -134,12 +130,8 @@ pub(super) fn narrowed_maven_steps(
|
||||
if affected.len() >= reactor.len() || affected.contains(&top.dir) {
|
||||
steps.push(step(top, &[]));
|
||||
} else {
|
||||
let pl = selection(root, top, &reactor, &affected);
|
||||
if pl.is_empty() {
|
||||
steps.push(step(top, &[]));
|
||||
} else {
|
||||
steps.push(step(top, &["-pl".into(), pl, "-am".into()]));
|
||||
}
|
||||
let pl = selection(&reactor, &top.dir, &affected);
|
||||
steps.push(step(top, &["-pl".into(), pl, "-am".into()]));
|
||||
}
|
||||
}
|
||||
Ok(Some(steps))
|
||||
@@ -413,36 +405,4 @@ mod tests {
|
||||
assert_eq!(steps.len(), 1);
|
||||
assert_eq!(steps[0].cwd, subdir(root, "solo"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sibling_reactor_narrows_with_relative_module_selectors() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
write(
|
||||
root,
|
||||
"parent/pom.xml",
|
||||
r#"<project><modelVersion>4.0.0</modelVersion><groupId>t</groupId><artifactId>parent</artifactId><version>1</version><packaging>pom</packaging><modules><module>../common</module><module>../app</module></modules></project>"#,
|
||||
);
|
||||
write(
|
||||
root,
|
||||
"common/pom.xml",
|
||||
r#"<project><modelVersion>4.0.0</modelVersion><parent><groupId>t</groupId><artifactId>parent</artifactId><version>1</version><relativePath>../parent/pom.xml</relativePath></parent><artifactId>common</artifactId></project>"#,
|
||||
);
|
||||
write(
|
||||
root,
|
||||
"app/pom.xml",
|
||||
r#"<project><modelVersion>4.0.0</modelVersion><parent><groupId>t</groupId><artifactId>parent</artifactId><version>1</version><relativePath>../parent/pom.xml</relativePath></parent><artifactId>app</artifactId><dependencies><dependency><groupId>t</groupId><artifactId>common</artifactId><version>1</version></dependency></dependencies></project>"#,
|
||||
);
|
||||
write(root, "common/src/main/java/t/C.java", "package t; public class C {}");
|
||||
write(root, "app/src/main/java/t/A.java", "package t; public class A {}");
|
||||
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, "common/src/main/java/t/C.java", "package t; public class C { int x; }");
|
||||
let steps = steps(&cache, root, &model).unwrap();
|
||||
assert_eq!(steps.len(), 1);
|
||||
assert_eq!(steps[0].cwd, subdir(root, "parent"));
|
||||
assert_eq!(pl_arg(&steps[0]), "../app,../common");
|
||||
assert!(steps[0].args.contains(&"-am".into()));
|
||||
}
|
||||
}
|
||||
@@ -64,7 +64,6 @@ pub(super) fn build_javac_step(
|
||||
cwd: &Path,
|
||||
out_dir: &Path,
|
||||
classpath: &str,
|
||||
encoding: &str,
|
||||
sources: &[PathBuf],
|
||||
release: Vec<String>,
|
||||
file: &Path,
|
||||
@@ -74,7 +73,7 @@ pub(super) fn build_javac_step(
|
||||
.map_err(|e| IdeError::internal(format!("cannot create {} ({e})", out_dir.display())))?;
|
||||
// Raw `javac` prints `path:line: error: …`, the same form Gradle forwards.
|
||||
let mut step = BuildStep::new(javac, &[], cwd, Format::Gradle);
|
||||
step.args.extend(["-encoding".into(), encoding.to_owned(), "-g".into()]);
|
||||
step.args.extend(["-encoding".into(), "UTF-8".into(), "-g".into()]);
|
||||
step.args.extend(["-d".into(), out_dir.to_string_lossy().into_owned()]);
|
||||
if !classpath.is_empty() {
|
||||
step.args.extend(["-cp".into(), classpath.to_owned()]);
|
||||
@@ -119,8 +118,6 @@ pub struct SingleFileTarget {
|
||||
pub pl: String,
|
||||
/// `maven.compiler.release` (or equivalent) of the module's project.
|
||||
pub java_version: Option<u32>,
|
||||
/// `project.build.sourceEncoding` of the module's project, as the POM spells it.
|
||||
pub source_encoding: Option<String>,
|
||||
}
|
||||
|
||||
/// Locates the linked Maven module owning a `.java` source file.
|
||||
@@ -146,19 +143,12 @@ pub fn single_file_target(root: &Path, model: &BuildModel, file: &Path) -> IdeRe
|
||||
let module = subdir(root, &project.dir);
|
||||
let top = maven_reactor(m, &project.dir)
|
||||
.ok_or_else(|| IdeError::not_found("no linked Maven project found for module"))?;
|
||||
let pl = maven::module_selector(root, top, project).unwrap_or_default();
|
||||
let top_dir = subdir(root, &top.dir);
|
||||
let pl = module.strip_prefix(&top_dir).map(|r| r.to_string_lossy().replace('\\', "/")).unwrap_or_default();
|
||||
// Test sources see the test classpath and compile into test classes.
|
||||
let test = is_test_source(&rel);
|
||||
let out_dir = module.join("target").join(if test { "test-classes" } else { "classes" });
|
||||
Ok(SingleFileTarget {
|
||||
module,
|
||||
test,
|
||||
out_dir,
|
||||
top: top.clone(),
|
||||
pl,
|
||||
java_version: project.java_version,
|
||||
source_encoding: project.source_encoding.clone(),
|
||||
})
|
||||
Ok(SingleFileTarget { module, test, out_dir, top: top.clone(), pl, java_version: project.java_version })
|
||||
}
|
||||
|
||||
/// The Maven reactor target for a launch module whose source file is not known yet.
|
||||
@@ -174,17 +164,10 @@ fn module_target(root: &Path, model: &BuildModel, module: &Path, test: bool) ->
|
||||
.ok_or_else(|| IdeError::not_found("no linked Maven project found for module"))?;
|
||||
let top = maven_reactor(m, &project.dir)
|
||||
.ok_or_else(|| IdeError::not_found("no linked Maven reactor found for module"))?;
|
||||
let pl = maven::module_selector(root, top, project).unwrap_or_default();
|
||||
let top_dir = subdir(root, &top.dir);
|
||||
let pl = module.strip_prefix(&top_dir).map(|r| r.to_string_lossy().replace('\\', "/")).unwrap_or_default();
|
||||
let out_dir = module.join("target").join(if test { "test-classes" } else { "classes" });
|
||||
Ok(SingleFileTarget {
|
||||
module,
|
||||
test,
|
||||
out_dir,
|
||||
top: top.clone(),
|
||||
pl,
|
||||
java_version: project.java_version,
|
||||
source_encoding: project.source_encoding.clone(),
|
||||
})
|
||||
Ok(SingleFileTarget { module, test, out_dir, top: top.clone(), pl, java_version: project.java_version })
|
||||
}
|
||||
|
||||
/// `javac` for the module: its `JAVA_HOME`, else `PATH`.
|
||||
@@ -197,30 +180,6 @@ pub fn find_javac(env: &BTreeMap<String, String>) -> String {
|
||||
exe.to_owned()
|
||||
}
|
||||
|
||||
/// Existing system-scope dependencies of this module. Maven resolves these from
|
||||
/// their local files and does not pass them transitively to reactor dependents.
|
||||
pub fn maven_system_classpath(root: &Path, model: &BuildModel, module: &Path) -> Vec<PathBuf> {
|
||||
let Some(maven) = &model.maven else { return Vec::new() };
|
||||
let module = root.join(module);
|
||||
maven
|
||||
.projects
|
||||
.iter()
|
||||
.find(|p| root.join(&p.dir) == module)
|
||||
.into_iter()
|
||||
.flat_map(|p| &p.system_paths)
|
||||
.filter(|p| p.is_file())
|
||||
.cloned()
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn with_system_classpath(root: &Path, model: &BuildModel, module: &Path, classpath: String) -> String {
|
||||
let system = maven_system_classpath(root, model, module);
|
||||
if system.is_empty() {
|
||||
return classpath;
|
||||
}
|
||||
join_classpath(std::env::split_paths(&classpath).chain(system).map(|p| p.to_string_lossy().into_owned()))
|
||||
}
|
||||
|
||||
/// Dependency classpath of the module: existing reactor class directories plus
|
||||
/// `mvn dependency:build-classpath` (which resolves without compiling anything,
|
||||
/// so `-am` stays cheap). Entries are platform-separated (`;` on Windows).
|
||||
@@ -274,7 +233,7 @@ pub fn module_classpath_without_build(
|
||||
&& cached.version == CLASSPATH_CACHE_VERSION
|
||||
&& classpath_entries_exist(root, &cached.classpath)
|
||||
{
|
||||
return Ok(with_system_classpath(root, model, &target.module, cached.classpath));
|
||||
return Ok(cached.classpath);
|
||||
}
|
||||
classpath(root, model, &target, if test { "test" } else { "runtime" }, false, cancel)
|
||||
}
|
||||
@@ -311,7 +270,7 @@ pub fn module_classpaths(
|
||||
&& classpath_entries_exist(root, &cached.classpath)
|
||||
{
|
||||
if i == 0 {
|
||||
return Ok(with_system_classpath(root, model, &target.module, cached.classpath));
|
||||
return Ok(cached.classpath);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
@@ -339,7 +298,7 @@ pub fn module_classpaths(
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(with_system_classpath(root, model, &modules[0], classpaths.into_iter().next().unwrap()))
|
||||
Ok(classpaths.into_iter().next().unwrap())
|
||||
}
|
||||
|
||||
/// A module whose classpath the Maven probe resolves, with its cache key and file.
|
||||
@@ -387,8 +346,7 @@ fn classpath(
|
||||
compile_first: bool,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<String> {
|
||||
let classpath = classpaths(root, model, &[target], scope, compile_first, cancel)?.pop().unwrap();
|
||||
Ok(with_system_classpath(root, model, &target.module, classpath))
|
||||
Ok(classpaths(root, model, &[target], scope, compile_first, cancel)?.pop().unwrap())
|
||||
}
|
||||
|
||||
/// The classpath of each of `targets` (modules of one reactor) from one Maven probe.
|
||||
@@ -424,11 +382,8 @@ fn classpaths(
|
||||
if compile_first {
|
||||
args.push("compile");
|
||||
}
|
||||
let build_classpath = maven::plugin_goal(
|
||||
"dependency:build-classpath",
|
||||
maven::local_repository_for(&top.options).as_deref(),
|
||||
maven::maven_version(&top.command),
|
||||
);
|
||||
let build_classpath =
|
||||
maven::plugin_goal("dependency:build-classpath", maven::local_repository_for(&top.options).as_deref());
|
||||
args.extend([build_classpath.as_str(), output_arg.as_str(), scope_arg.as_str(), "-q"]);
|
||||
let top_dir = subdir(root, &top.dir);
|
||||
let owned_args: Vec<String> = args.into_iter().map(str::to_owned).collect();
|
||||
@@ -490,17 +445,7 @@ fn target_classpath(root: &Path, model: &BuildModel, target: &SingleFileTarget)
|
||||
pub fn javac_step(target: &SingleFileTarget, file: &Path, classpath: &str, javac: &str) -> IdeResult<BuildStep> {
|
||||
let sources = source_roots(target);
|
||||
let release = release_args(target.java_version, java_home_major(&target.top.env));
|
||||
build_javac_step(
|
||||
javac,
|
||||
&target.module,
|
||||
&target.out_dir,
|
||||
classpath,
|
||||
target.source_encoding.as_deref().unwrap_or("UTF-8"),
|
||||
&sources,
|
||||
release,
|
||||
file,
|
||||
target.top.env.clone(),
|
||||
)
|
||||
build_javac_step(javac, &target.module, &target.out_dir, classpath, &sources, release, file, target.top.env.clone())
|
||||
}
|
||||
|
||||
/// The module's Java source folders that exist, generated ones included; test sources see
|
||||
@@ -676,17 +621,8 @@ pub fn gradle_compile_file_plan(
|
||||
}
|
||||
let javac = find_javac(&gradle.env);
|
||||
let release = release_args(cp.release.or(gradle.java_version), java_home_major(&gradle.env));
|
||||
let step = build_javac_step(
|
||||
&javac,
|
||||
&module_dir,
|
||||
&out_dir,
|
||||
&classpath,
|
||||
"UTF-8",
|
||||
&sources,
|
||||
release,
|
||||
file,
|
||||
gradle.env.clone(),
|
||||
)?;
|
||||
let step =
|
||||
build_javac_step(&javac, &module_dir, &out_dir, &classpath, &sources, release, file, gradle.env.clone())?;
|
||||
Ok(BuildPlan { system: BuildSystem::Gradle, title: format!("Compile {name}"), steps: vec![step] })
|
||||
}
|
||||
|
||||
@@ -747,28 +683,6 @@ mod tests {
|
||||
assert_eq!(test.out_dir, root.join("app/target/test-classes"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn javac_reads_sources_in_the_encoding_of_the_module_pom() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root_buf = dunce::canonicalize(dir.path()).unwrap();
|
||||
let root = root_buf.as_path();
|
||||
fixture(root);
|
||||
write(
|
||||
root,
|
||||
"app/pom.xml",
|
||||
r#"<project><parent><groupId>demo</groupId><artifactId>parent</artifactId><version>1</version></parent>
|
||||
<artifactId>app</artifactId>
|
||||
<properties><project.build.sourceEncoding>ISO-8859-15</project.build.sourceEncoding></properties></project>"#,
|
||||
);
|
||||
let model = crate::load(root, &root.join("cache"), None);
|
||||
let file = root.join("app/src/main/java/demo/Main.java");
|
||||
let target = single_file_target(root, &model, &file).unwrap();
|
||||
let step = javac_step(&target, &file, "", "javac").unwrap();
|
||||
let at = step.args.iter().position(|a| a == "-encoding").expect("an -encoding");
|
||||
assert_eq!(step.args[at + 1], "ISO-8859-15");
|
||||
assert_eq!(target.source_encoding.as_deref(), Some("ISO-8859-15"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn target_rejects_non_java_missing_and_unlinked_files() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
@@ -998,64 +912,6 @@ mod tests {
|
||||
assert!(args.lines().any(|a| a == "-Dmdep.includeScope=test"), "{args}");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn system_jars_augment_maven_javac_and_launch_classpaths() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(dir.path()).unwrap();
|
||||
write(
|
||||
&root,
|
||||
"pom.xml",
|
||||
r#"<project><groupId>demo</groupId><artifactId>parent</artifactId><version>1</version>
|
||||
<packaging>pom</packaging><modules><module>app</module></modules>
|
||||
<properties><lib.dir>src/main/resources/lib</lib.dir></properties></project>"#,
|
||||
);
|
||||
write(
|
||||
&root,
|
||||
"app/pom.xml",
|
||||
r#"<project><parent><groupId>demo</groupId><artifactId>parent</artifactId><version>1</version></parent>
|
||||
<artifactId>app</artifactId>
|
||||
<properties><lib.file>${lib.dir}/offline.jar</lib.file></properties>
|
||||
<dependencies>
|
||||
<dependency><groupId>local</groupId><artifactId>offline</artifactId><version>1</version>
|
||||
<scope>system</scope><systemPath>${pom.basedir}/${lib.file}</systemPath></dependency>
|
||||
<dependency><groupId>local</groupId><artifactId>late</artifactId><version>1</version>
|
||||
<scope>system</scope><systemPath>${project.basedir}/${lib.dir}/late.jar</systemPath></dependency>
|
||||
<dependency><groupId>local</groupId><artifactId>directory</artifactId><version>1</version>
|
||||
<scope>system</scope><systemPath>${project.basedir}/${lib.dir}</systemPath></dependency>
|
||||
</dependencies></project>"#,
|
||||
);
|
||||
let jars = "app/src/main/resources/lib";
|
||||
write(&root, &format!("{jars}/offline.jar"), "");
|
||||
write(&root, "app/src/main/java/demo/Main.java", "class Main {}");
|
||||
// The scope-filtered Maven classpath can contain no dependencies.
|
||||
write(&root, "mvnw", "#!/bin/sh\nmkdir -p app/target\n: > app/target/ide-compile-cp.txt\n");
|
||||
fs::set_permissions(root.join("mvnw"), fs::Permissions::from_mode(0o755)).unwrap();
|
||||
|
||||
let cache = root.join("cache");
|
||||
let model = crate::load(&root, &cache, None);
|
||||
let module = root.join("app");
|
||||
let file = module.join("src/main/java/demo/Main.java");
|
||||
let jar = root.join(jars).join("offline.jar");
|
||||
let plan = compile_file_plan(&root, &model, &file).unwrap();
|
||||
assert!(plan.steps[0].args.windows(2).any(|arg| arg[0] == "-cp" && Path::new(&arg[1]) == jar));
|
||||
let cancel = CancellationToken::new();
|
||||
let cp = module_classpath(&root, &model, &module, false, None, &cache, &cancel).unwrap();
|
||||
let paths: Vec<_> = std::env::split_paths(&cp).collect();
|
||||
assert_eq!(paths, [module.join("target/classes"), jar.clone()]);
|
||||
assert!(maven_system_classpath(&root, &model, &root).is_empty());
|
||||
|
||||
// Adding a previously absent jar or deleting an old one updates a no-build launch.
|
||||
fs::remove_file(jar).unwrap();
|
||||
write(&root, &format!("{jars}/late.jar"), "");
|
||||
fs::remove_file(root.join("mvnw")).unwrap();
|
||||
let cp = module_classpath_without_build(&root, &model, &module, false, &cache, &cancel).unwrap();
|
||||
let paths: Vec<_> = std::env::split_paths(&cp).collect();
|
||||
assert_eq!(paths, [module.join("target/classes"), root.join(jars).join("late.jar")]);
|
||||
}
|
||||
|
||||
/// 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)]
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -234,7 +234,9 @@ fn members(r: &mut Bytes, pool: &Pool, refs: &mut BTreeSet<String>) -> Option<Ve
|
||||
Some(out)
|
||||
}
|
||||
|
||||
fn read_pool(r: &mut Bytes<'_>) -> Option<Pool> {
|
||||
/// Parses a class file; `None` when it isn't a well-formed one.
|
||||
pub fn parse(data: &[u8]) -> Option<ClassFile> {
|
||||
let mut r = Bytes { data, pos: 0 };
|
||||
if r.u4()? != 0xCAFE_BABE {
|
||||
return None;
|
||||
}
|
||||
@@ -281,28 +283,11 @@ fn read_pool(r: &mut Bytes<'_>) -> Option<Pool> {
|
||||
entries.push(entry);
|
||||
i += 1;
|
||||
if wide {
|
||||
if i == count {
|
||||
return None;
|
||||
}
|
||||
entries.push(Entry::Empty);
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
Some(Pool(entries))
|
||||
}
|
||||
|
||||
/// Reads the internal class name (e.g. `com/acme/Order$Line`) from `this_class`.
|
||||
pub fn class_file_name(data: &[u8]) -> Option<String> {
|
||||
let mut r = Bytes { data, pos: 0 };
|
||||
let pool = read_pool(&mut r)?;
|
||||
r.u2()?; // access_flags
|
||||
Some(pool.class(r.u2()?)?.to_owned())
|
||||
}
|
||||
|
||||
/// Parses a class file; `None` when it isn't a well-formed one.
|
||||
pub fn parse(data: &[u8]) -> Option<ClassFile> {
|
||||
let mut r = Bytes { data, pos: 0 };
|
||||
let pool = read_pool(&mut r)?;
|
||||
let pool = Pool(entries);
|
||||
let mut refs = BTreeSet::new();
|
||||
for entry in &pool.0 {
|
||||
match entry {
|
||||
|
||||
@@ -22,7 +22,7 @@ mod incremental;
|
||||
mod javac;
|
||||
mod model;
|
||||
|
||||
pub use classfile::{ClassFile, class_file_name};
|
||||
pub use classfile::ClassFile;
|
||||
pub use javac::{JavacPool, Reply, ServerKey};
|
||||
|
||||
use incremental::{ClassRecord, SetStamp, SetState};
|
||||
@@ -64,300 +64,9 @@ pub struct JavaBuildService {
|
||||
}
|
||||
|
||||
impl JavaBuildService {
|
||||
pub(crate) fn lock(&self, dir: &Path) -> Arc<Mutex<()>> {
|
||||
fn lock(&self, dir: &Path) -> Arc<Mutex<()>> {
|
||||
self.locks.lock().unwrap().entry(dir.to_path_buf()).or_default().clone()
|
||||
}
|
||||
|
||||
/// Compiles what changed in one source set (see [`incremental`]).
|
||||
pub fn compile_incremental(
|
||||
&self,
|
||||
set: &IncrementalSet<'_>,
|
||||
cancel: &CancellationToken,
|
||||
on_event: &(dyn Fn(BuildEvent) + Sync),
|
||||
messages: &mut Vec<BuildMessage>,
|
||||
) -> IdeResult<IncrementalOutcome> {
|
||||
if set.clean {
|
||||
remove_classes(&set.output);
|
||||
let _ = std::fs::remove_dir_all(&set.generated_dir);
|
||||
let _ = std::fs::remove_file(&set.state_file);
|
||||
}
|
||||
let source_stamps: BTreeMap<PathBuf, FileStamp> =
|
||||
set.sources.iter().filter_map(|s| Some((s.clone(), file_stamp(s)?))).collect();
|
||||
let previous = incremental::load_state(&set.state_file);
|
||||
let reactor: Vec<PathBuf> = set.upstream_states.iter().map(|(o, _)| o.clone()).collect();
|
||||
let stamp = SetStamp {
|
||||
options: set.options.clone(),
|
||||
libraries: set.libraries.iter().map(|e| (e.clone(), file_stamp(e))).collect(),
|
||||
reactor,
|
||||
processor_path: set.processor_path.iter().map(|p| (p.clone(), file_stamp(p))).collect(),
|
||||
java_home: set.java_home.clone(),
|
||||
};
|
||||
|
||||
// What the upstream outputs it compiles against changed since it last compiled.
|
||||
let mut upstream = BTreeMap::new();
|
||||
let mut upstream_changed = BTreeSet::new();
|
||||
let mut upstream_all = false;
|
||||
for (entry, up_state_file) in &set.upstream_states {
|
||||
let state = incremental::load_state(up_state_file);
|
||||
let generation = state.as_ref().map_or(0, |s| s.generation);
|
||||
upstream.insert(entry.clone(), generation);
|
||||
let recorded = previous.as_ref().and_then(|p| p.upstream.get(entry)).copied();
|
||||
if recorded == Some(generation) {
|
||||
continue;
|
||||
}
|
||||
match (recorded, state.and_then(|s| s.changes_since(recorded?))) {
|
||||
(Some(_), Some(changed)) => upstream_changed.extend(changed),
|
||||
_ => upstream_all = true,
|
||||
}
|
||||
}
|
||||
|
||||
let had_state = previous.is_some();
|
||||
let previous = previous.unwrap_or_default();
|
||||
let mut changed: BTreeSet<PathBuf> = source_stamps
|
||||
.iter()
|
||||
.filter(|(path, stamp)| {
|
||||
previous.sources.get(*path) != Some(*stamp)
|
||||
|| previous.dirty.contains(*path)
|
||||
|| set.force.contains(*path)
|
||||
})
|
||||
.map(|(path, _)| path.clone())
|
||||
.collect();
|
||||
let removed: BTreeSet<PathBuf> =
|
||||
previous.sources.keys().filter(|p| !source_stamps.contains_key(*p)).cloned().collect();
|
||||
let mut from_scratch = !had_state
|
||||
|| previous.stamp != stamp
|
||||
|| upstream_all
|
||||
|| !set.output.is_dir()
|
||||
|| (!previous.success && previous.dirty.is_empty());
|
||||
if had_state && !from_scratch {
|
||||
for record in previous.classes.values() {
|
||||
if !record.file.is_file() {
|
||||
match &record.source {
|
||||
Some(src) if source_stamps.contains_key(src) => {
|
||||
changed.insert(src.clone());
|
||||
}
|
||||
Some(src) if removed.contains(src) => {}
|
||||
_ => {
|
||||
from_scratch = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if !from_scratch && changed.is_empty() && removed.is_empty() && upstream_changed.is_empty() {
|
||||
return Ok(IncrementalOutcome { failed: false, compiled_files: 0, outputs_changed: false });
|
||||
}
|
||||
// Processors that aggregate (or name no originating source) can't be followed class by class.
|
||||
let has_changes = !changed.is_empty() || !removed.is_empty() || !upstream_changed.is_empty();
|
||||
let from_scratch =
|
||||
from_scratch || ((!previous.generated.is_empty() || !previous.unowned.is_empty()) && has_changes);
|
||||
|
||||
let mut state = SetState {
|
||||
stamp,
|
||||
sources: source_stamps.clone(),
|
||||
generation: previous.generation,
|
||||
upstream,
|
||||
classes: previous.classes,
|
||||
changes: previous.changes,
|
||||
..Default::default()
|
||||
};
|
||||
let mut api_changed = BTreeSet::new();
|
||||
let mut constants_changed = false;
|
||||
// Classes of removed sources go first, and count as changed.
|
||||
let gone: Vec<String> = state
|
||||
.classes
|
||||
.iter()
|
||||
.filter(|(_, r)| r.source.as_ref().is_some_and(|s| removed.contains(s)))
|
||||
.map(|(n, _)| n.clone())
|
||||
.collect();
|
||||
let gone_empty = gone.is_empty();
|
||||
for name in gone {
|
||||
let record = state.classes.remove(&name).expect("listed");
|
||||
let _ = std::fs::remove_file(&record.file);
|
||||
constants_changed |= record.constants != incremental::NO_CONSTANTS;
|
||||
api_changed.insert(name);
|
||||
}
|
||||
let mut to_compile: BTreeSet<PathBuf> = if from_scratch || constants_changed {
|
||||
remove_classes(&set.output);
|
||||
for file in previous.generated.iter().chain(&previous.unowned) {
|
||||
let _ = std::fs::remove_file(file);
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&set.generated_dir);
|
||||
state.classes.retain(|_, r| r.source.is_some());
|
||||
source_stamps.keys().cloned().collect()
|
||||
} else {
|
||||
let affected =
|
||||
incremental::with_subclasses(&state.classes, &upstream_changed.union(&api_changed).cloned().collect());
|
||||
changed.iter().cloned().chain(incremental::dependent_sources(&state.classes, &affected)).collect()
|
||||
};
|
||||
std::fs::create_dir_all(&set.output)?;
|
||||
std::fs::create_dir_all(&set.generated_dir)?;
|
||||
|
||||
let total = source_stamps.len();
|
||||
let mut compiled: BTreeSet<PathBuf> = BTreeSet::new();
|
||||
let mut server = None;
|
||||
loop {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
let batch: BTreeSet<PathBuf> = to_compile
|
||||
.iter()
|
||||
.filter(|s| !compiled.contains(*s) && source_stamps.contains_key(*s))
|
||||
.cloned()
|
||||
.collect();
|
||||
if batch.is_empty() {
|
||||
break;
|
||||
}
|
||||
// The classes the batch replaces: their files go first, so nothing stale is left.
|
||||
let replaced: BTreeMap<String, ClassRecord> = state
|
||||
.classes
|
||||
.iter()
|
||||
.filter(|(_, r)| r.source.as_ref().is_some_and(|s| batch.contains(s)))
|
||||
.map(|(n, r)| (n.clone(), r.clone()))
|
||||
.collect();
|
||||
for (name, record) in &replaced {
|
||||
let _ = std::fs::remove_file(&record.file);
|
||||
state.classes.remove(name);
|
||||
}
|
||||
let files: Vec<PathBuf> = batch.iter().cloned().collect();
|
||||
let noun = if total == 1 { "file" } else { "files" };
|
||||
let count = if files.len() == total {
|
||||
format!("{total} {noun}")
|
||||
} else {
|
||||
format!("{} of {total} {noun}", files.len())
|
||||
};
|
||||
on_event(BuildEvent::Step {
|
||||
command: format!("javac {} ({}, {count})", set.module_name, set.set_name),
|
||||
cwd: set.cwd.clone().into(),
|
||||
});
|
||||
if server.is_none() {
|
||||
let key = ServerKey { java_home: set.java_home.clone(), jvm_args: set.jvm_args.clone() };
|
||||
server = Some(self.servers.server(set.jar, &key)?);
|
||||
}
|
||||
let mut written: Vec<(PathBuf, Option<PathBuf>)> = Vec::new();
|
||||
let result =
|
||||
server.as_ref().expect("started").compile(&set.options, &files, set.encoding, cancel, |reply| {
|
||||
match reply {
|
||||
Reply::Output { path, source } => written.push((path.clone(), source.clone())),
|
||||
Reply::Generated { path, .. } => state.generated.push(path.clone()),
|
||||
Reply::OutputText { text } => {
|
||||
on_event(BuildEvent::Output { text: text.clone(), stderr: false })
|
||||
}
|
||||
Reply::Diagnostic { .. } => {
|
||||
if let Some(m) = diagnostic(reply) {
|
||||
on_event(BuildEvent::Output {
|
||||
text: message_text(&m),
|
||||
stderr: m.severity == Severity::Error,
|
||||
});
|
||||
on_event(BuildEvent::Message { message: m.clone() });
|
||||
messages.push(m);
|
||||
}
|
||||
}
|
||||
Reply::Done { .. } => {}
|
||||
}
|
||||
});
|
||||
if !matches!(result, Ok(true)) {
|
||||
for (path, _) in &written {
|
||||
let _ = std::fs::remove_file(path);
|
||||
}
|
||||
// The next build starts from the state this one started from, with whatever this
|
||||
// one had to compile still to compile. Its earlier rounds' classes are not the
|
||||
// baseline: compared with them, the API and constant changes those rounds found
|
||||
// would never reach this set's dependents or the sets compiled against it.
|
||||
let mut retry = incremental::load_state(&set.state_file).unwrap_or_default();
|
||||
retry.dirty.extend(to_compile.union(&compiled).filter(|s| source_stamps.contains_key(*s)).cloned());
|
||||
retry.success = false;
|
||||
let _ = model::write_json(&set.state_file, &retry);
|
||||
return result.map(|_| IncrementalOutcome {
|
||||
failed: true,
|
||||
compiled_files: compiled.len(),
|
||||
outputs_changed: false,
|
||||
});
|
||||
}
|
||||
// javac names sources as they were passed; other spellings are matched canonically,
|
||||
// and classes of sources outside the set (processors' output) are unowned.
|
||||
let canonical: HashMap<PathBuf, &PathBuf> =
|
||||
batch.iter().filter_map(|s| Some((dunce::canonicalize(s).ok()?, s))).collect();
|
||||
let own = |source: PathBuf| -> Option<PathBuf> {
|
||||
if source_stamps.contains_key(&source) {
|
||||
return Some(source);
|
||||
}
|
||||
canonical.get(&dunce::canonicalize(&source).ok()?).map(|s| (*s).clone())
|
||||
};
|
||||
let mut fresh = BTreeMap::new();
|
||||
for (path, source) in written {
|
||||
let source = source.and_then(own);
|
||||
let class = (path.extension().is_some_and(|e| e == "class"))
|
||||
.then(|| std::fs::read(&path).ok())
|
||||
.flatten()
|
||||
.and_then(|bytes| classfile::parse(&bytes));
|
||||
match (class, source) {
|
||||
(Some(class), Some(source)) => {
|
||||
let (name, record) = ClassRecord::new(class, path, Some(source));
|
||||
fresh.insert(name, record);
|
||||
}
|
||||
_ => state.unowned.push(path),
|
||||
}
|
||||
}
|
||||
let round = incremental::diff(&replaced, &fresh);
|
||||
constants_changed |= round.constants;
|
||||
api_changed.extend(round.api.iter().cloned());
|
||||
state.classes.extend(fresh);
|
||||
compiled.extend(batch);
|
||||
if constants_changed {
|
||||
// Constants are copied into the classes that use them: compile the rest too.
|
||||
to_compile.extend(source_stamps.keys().cloned());
|
||||
continue;
|
||||
}
|
||||
let affected =
|
||||
incremental::with_subclasses(&state.classes, &round.api.union(&upstream_changed).cloned().collect());
|
||||
to_compile.extend(incremental::dependent_sources(&state.classes, &affected));
|
||||
to_compile.extend(incremental::shadowed_sources(&state.classes, &round.added));
|
||||
}
|
||||
state.success = true;
|
||||
if !compiled.is_empty() || !api_changed.is_empty() {
|
||||
let changed =
|
||||
incremental::with_subclasses(&state.classes, &api_changed.union(&upstream_changed).cloned().collect());
|
||||
state.log(now_generation(), changed, !had_state || constants_changed);
|
||||
}
|
||||
model::write_json(&set.state_file, &state)?;
|
||||
Ok(IncrementalOutcome {
|
||||
failed: false,
|
||||
compiled_files: compiled.len(),
|
||||
outputs_changed: !compiled.is_empty() || !gone_empty,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Inputs for compiling one source set incrementally with the resident `javac` server.
|
||||
pub struct IncrementalSet<'a> {
|
||||
pub module_name: String,
|
||||
pub set_name: &'static str,
|
||||
pub cwd: PathBuf,
|
||||
pub sources: Vec<PathBuf>,
|
||||
pub output: PathBuf,
|
||||
pub options: Vec<String>,
|
||||
pub libraries: Vec<PathBuf>,
|
||||
/// Upstream `(output_dir, state_file)` pairs this set compiles against.
|
||||
pub upstream_states: Vec<(PathBuf, PathBuf)>,
|
||||
pub processor_path: Vec<PathBuf>,
|
||||
pub java_home: PathBuf,
|
||||
pub jvm_args: Vec<String>,
|
||||
pub encoding: Option<&'a str>,
|
||||
pub state_file: PathBuf,
|
||||
pub generated_dir: PathBuf,
|
||||
pub force: &'a BTreeSet<PathBuf>,
|
||||
pub jar: &'a Path,
|
||||
pub clean: bool,
|
||||
}
|
||||
|
||||
/// Result of compiling one source set incrementally.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct IncrementalOutcome {
|
||||
pub failed: bool,
|
||||
pub compiled_files: usize,
|
||||
pub outputs_changed: bool,
|
||||
}
|
||||
|
||||
/// One build of the IDE's Java build service.
|
||||
@@ -370,8 +79,6 @@ pub struct JavaBuild<'a> {
|
||||
/// Changes when the jar does, so models recorded by an older extension are prepared again.
|
||||
pub jar_version: &'a str,
|
||||
pub local_repo: Option<PathBuf>,
|
||||
/// Explicit Maven goals the project's settings allow the IDE to skip in compile phases.
|
||||
pub ignored_maven_compile_goals: &'a [String],
|
||||
pub service: &'a JavaBuildService,
|
||||
/// The JDK home that compiles for a release, when Maven's environment names none.
|
||||
pub jdk: &'a (dyn Fn(Option<u32>) -> Option<PathBuf> + Sync),
|
||||
@@ -543,11 +250,15 @@ fn java_sources(set: &SourceSet, cancel: &CancellationToken) -> IdeResult<Vec<Pa
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// A javac debug-info option (`-g`, `-g:none`, `-g:lines,vars`). The IDE's build always
|
||||
/// compiles with `-g`: breakpoints need line numbers and local variables, whatever
|
||||
/// maven-compiler-plugin's `<debug>` / `<debuglevel>` ask of Maven's own build (#7786).
|
||||
fn is_debug_option(arg: &str) -> bool {
|
||||
arg == "-g" || arg.starts_with("-g:")
|
||||
/// `-g`, `-g:lines,vars` or `-g:none`, as maven-compiler-plugin passes them.
|
||||
fn debug_args(c: &CompilerConfig) -> Vec<String> {
|
||||
if c.debug == Some(false) {
|
||||
return vec!["-g:none".into()];
|
||||
}
|
||||
match c.debuglevel.as_deref().map(str::trim).filter(|l| !l.is_empty()) {
|
||||
Some(level) => vec![format!("-g:{level}")],
|
||||
None => vec!["-g".into()],
|
||||
}
|
||||
}
|
||||
|
||||
/// The JDK feature version of `release` / `source` (`1.8` → 8).
|
||||
@@ -583,7 +294,7 @@ fn javac_options(set: &SourceSet, classpath: &[PathBuf], generated: &Path, jdk_m
|
||||
if let Some(proc) = c.proc.as_deref().filter(|p| !p.is_empty()) {
|
||||
args.push(format!("-proc:{proc}"));
|
||||
}
|
||||
args.push("-g".into());
|
||||
args.extend(debug_args(&c));
|
||||
if c.parameters == Some(true) {
|
||||
args.push("-parameters".into());
|
||||
}
|
||||
@@ -612,19 +323,15 @@ fn javac_options(set: &SourceSet, classpath: &[PathBuf], generated: &Path, jdk_m
|
||||
}
|
||||
}
|
||||
for (key, value) in &c.compiler_arguments {
|
||||
let key = if key.starts_with('-') { key.clone() } else { format!("-{key}") };
|
||||
if is_debug_option(&key) {
|
||||
continue;
|
||||
}
|
||||
args.push(key);
|
||||
args.push(if key.starts_with('-') { key.clone() } else { format!("-{key}") });
|
||||
if let Some(value) = value.as_ref().filter(|v| !v.is_empty()) {
|
||||
args.push(value.clone());
|
||||
}
|
||||
}
|
||||
if let Some(argument) = &c.compiler_argument {
|
||||
args.extend(argument.split_whitespace().filter(|a| !is_debug_option(a)).map(str::to_owned));
|
||||
args.extend(argument.split_whitespace().map(str::to_owned));
|
||||
}
|
||||
args.extend(c.compiler_args.iter().filter(|a| !a.is_empty() && !is_debug_option(a)).cloned());
|
||||
args.extend(c.compiler_args.iter().filter(|a| !a.is_empty()).cloned());
|
||||
args
|
||||
}
|
||||
|
||||
@@ -851,7 +558,7 @@ impl JavaBuild<'_> {
|
||||
}
|
||||
};
|
||||
for (project, test) in &projects {
|
||||
if let Some(reason) = project.unsupported(*test, self.ignored_maven_compile_goals) {
|
||||
if let Some(reason) = project.unsupported(*test) {
|
||||
return Ok(Built::Unsupported(reason));
|
||||
}
|
||||
// A launch of a Java module runs it from the module path, which the language server reports.
|
||||
@@ -960,7 +667,6 @@ impl JavaBuild<'_> {
|
||||
for project in &reactor_model.projects {
|
||||
for test in [false, true] {
|
||||
let stamp = resource_stamp(project.set(test), cancel)?;
|
||||
self.prune_resources(dir, project, test, cancel)?;
|
||||
model::write_json(&state_path(dir, project, test, "resources"), &stamp)?;
|
||||
}
|
||||
}
|
||||
@@ -996,11 +702,7 @@ impl JavaBuild<'_> {
|
||||
let step = match top {
|
||||
Reactor::Maven(top) => {
|
||||
let selection = maven_project_selection(changed.iter().map(|(p, _, _)| *p));
|
||||
// The resources plugin copies a file only when it is newer than the copy; content
|
||||
// replaced without moving the mtime (a sync tool, PowerShell `Copy-Item`) would stay
|
||||
// stale while its stamp is recorded as processed.
|
||||
let mut extra =
|
||||
vec!["-q".to_owned(), "-pl".to_owned(), selection, "-Dmaven.resources.overwrite=true".to_owned()];
|
||||
let mut extra = vec!["-q".to_owned(), "-pl".to_owned(), selection];
|
||||
extra.push("resources:resources".into());
|
||||
if changed.iter().any(|(_, test, _)| *test) {
|
||||
extra.push("resources:testResources".into());
|
||||
@@ -1028,42 +730,11 @@ impl JavaBuild<'_> {
|
||||
}));
|
||||
}
|
||||
for (project, test, stamp) in changed {
|
||||
self.prune_resources(dir, project, test, cancel)?;
|
||||
model::write_json(&state_path(dir, project, test, "resources"), &stamp)?;
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
/// Removes what the sources no longer have from a source set's output: the resources step
|
||||
/// copies and overwrites, it never deletes, so a file deleted from the sources would stay on
|
||||
/// the launch's classpath (a stale `META-INF/spring.factories` then fails the application).
|
||||
fn prune_resources(
|
||||
&self,
|
||||
dir: &Path,
|
||||
project: &ProjectModel,
|
||||
test: bool,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<()> {
|
||||
let set = project.set(test);
|
||||
let expected = resource_outputs(set, cancel)?;
|
||||
let recorded: BTreeSet<PathBuf> = std::fs::read(state_path(dir, project, test, "resource-outputs"))
|
||||
.ok()
|
||||
.and_then(|b| serde_json::from_slice(&b).ok())
|
||||
.unwrap_or_default();
|
||||
for stale in recorded.difference(&expected) {
|
||||
let _ = std::fs::remove_file(stale);
|
||||
// The folders a removed resource leaves empty are not part of the output either.
|
||||
let mut parent = stale.parent();
|
||||
while let Some(folder) = parent.filter(|d| d.starts_with(&set.output) && *d != set.output) {
|
||||
if std::fs::remove_dir(folder).is_err() {
|
||||
break;
|
||||
}
|
||||
parent = folder.parent();
|
||||
}
|
||||
}
|
||||
model::write_json(&state_path(dir, project, test, "resource-outputs"), &expected)
|
||||
}
|
||||
|
||||
/// Removes the classes of a source set and its record: the next build compiles it from scratch.
|
||||
fn clean(&self, dir: &Path, project: &ProjectModel, test: bool) -> IdeResult<()> {
|
||||
let set = project.set(test);
|
||||
@@ -1087,46 +758,244 @@ impl JavaBuild<'_> {
|
||||
return Ok(false);
|
||||
}
|
||||
let sources = java_sources(set, cancel)?;
|
||||
let source_stamps: BTreeMap<PathBuf, FileStamp> =
|
||||
sources.iter().filter_map(|s| Some((s.clone(), file_stamp(s)?))).collect();
|
||||
let state_file = state_path(dir, project, test, "compile");
|
||||
let previous = incremental::load_state(&state_file);
|
||||
let config = set.compiler.clone().unwrap_or_default();
|
||||
let release = config.release.as_deref().or(config.source.as_deref()).and_then(feature);
|
||||
let java_home = self.java_home(top, &config, release)?;
|
||||
let generated_dir = generated_dir(dir, project, test);
|
||||
let generated = generated_dir(dir, project, test);
|
||||
let classpath: Vec<PathBuf> = if test {
|
||||
std::iter::once(project.main.output.clone()).chain(set.classpath.iter().cloned()).collect()
|
||||
} else {
|
||||
set.classpath.clone()
|
||||
};
|
||||
let options = javac_options(set, &classpath, &generated_dir, jdk_major(&java_home));
|
||||
let upstream_states: Vec<(PathBuf, PathBuf)> = classpath
|
||||
.iter()
|
||||
.filter(|e| **e != set.output)
|
||||
.filter_map(|e| {
|
||||
outputs.get(e).map(|(key, entry_test)| (e.clone(), state_path_of(dir, key, *entry_test, "compile")))
|
||||
})
|
||||
.collect();
|
||||
let libraries: Vec<PathBuf> =
|
||||
classpath.iter().filter(|e| **e != set.output && !outputs.contains_key(*e)).cloned().collect();
|
||||
let incremental_set = IncrementalSet {
|
||||
module_name: project.artifact_id.clone(),
|
||||
set_name: if test { "tests" } else { "main" },
|
||||
cwd: project.dir.clone(),
|
||||
sources,
|
||||
output: set.output.clone(),
|
||||
options,
|
||||
libraries,
|
||||
upstream_states,
|
||||
processor_path: config.processor_path.unwrap_or_default(),
|
||||
jvm_args: jvm_config(top, &subdir(self.root, top.rel_dir())),
|
||||
java_home,
|
||||
encoding: config.encoding.as_deref(),
|
||||
state_file: state_path(dir, project, test, "compile"),
|
||||
generated_dir,
|
||||
force,
|
||||
jar: self.jar,
|
||||
clean: false,
|
||||
let options = javac_options(set, &classpath, &generated, jdk_major(&java_home));
|
||||
let reactor: Vec<PathBuf> =
|
||||
classpath.iter().filter(|e| **e != set.output && outputs.contains_key(*e)).cloned().collect();
|
||||
let stamp = SetStamp {
|
||||
options: options.clone(),
|
||||
libraries: classpath
|
||||
.iter()
|
||||
.filter(|e| **e != set.output && !outputs.contains_key(*e))
|
||||
.map(|e| (e.clone(), file_stamp(e)))
|
||||
.collect(),
|
||||
reactor: reactor.clone(),
|
||||
processor_path: config.processor_path.iter().flatten().map(|p| (p.clone(), file_stamp(p))).collect(),
|
||||
java_home: java_home.clone(),
|
||||
};
|
||||
let outcome = self.service.compile_incremental(&incremental_set, cancel, on_event, messages)?;
|
||||
Ok(outcome.failed)
|
||||
|
||||
// What the reactor outputs it compiles against changed since it last compiled.
|
||||
let mut upstream = BTreeMap::new();
|
||||
let mut upstream_changed = BTreeSet::new();
|
||||
let mut upstream_all = false;
|
||||
for entry in &reactor {
|
||||
let (key, entry_test) = &outputs[entry];
|
||||
let state = incremental::load_state(&state_path_of(dir, key, *entry_test, "compile"));
|
||||
let generation = state.as_ref().map_or(0, |s| s.generation);
|
||||
upstream.insert(entry.clone(), generation);
|
||||
let recorded = previous.as_ref().and_then(|p| p.upstream.get(entry)).copied();
|
||||
if recorded == Some(generation) {
|
||||
continue;
|
||||
}
|
||||
match (recorded, state.and_then(|s| s.changes_since(recorded?))) {
|
||||
(Some(_), Some(changed)) => upstream_changed.extend(changed),
|
||||
_ => upstream_all = true,
|
||||
}
|
||||
}
|
||||
|
||||
let had_state = previous.is_some();
|
||||
let previous = previous.unwrap_or_default();
|
||||
let changed: BTreeSet<PathBuf> = source_stamps
|
||||
.iter()
|
||||
.filter(|(path, stamp)| {
|
||||
previous.sources.get(*path) != Some(*stamp) || previous.dirty.contains(*path) || force.contains(*path)
|
||||
})
|
||||
.map(|(path, _)| path.clone())
|
||||
.collect();
|
||||
let removed: BTreeSet<PathBuf> =
|
||||
previous.sources.keys().filter(|p| !source_stamps.contains_key(*p)).cloned().collect();
|
||||
let from_scratch = !had_state
|
||||
|| previous.stamp != stamp
|
||||
|| upstream_all
|
||||
|| !set.output.is_dir()
|
||||
|| (!previous.success && previous.dirty.is_empty());
|
||||
if !from_scratch && changed.is_empty() && removed.is_empty() && upstream_changed.is_empty() {
|
||||
return Ok(false);
|
||||
}
|
||||
// Processors that aggregate (or name no originating source) can't be followed class by class.
|
||||
let from_scratch = from_scratch
|
||||
|| (!previous.generated.is_empty() || !previous.unowned.is_empty())
|
||||
&& !(changed.is_empty() && removed.is_empty() && upstream_changed.is_empty());
|
||||
|
||||
let mut state = SetState {
|
||||
stamp,
|
||||
sources: source_stamps.clone(),
|
||||
generation: previous.generation,
|
||||
upstream,
|
||||
classes: previous.classes,
|
||||
changes: previous.changes,
|
||||
..Default::default()
|
||||
};
|
||||
let mut api_changed = BTreeSet::new();
|
||||
let mut constants_changed = false;
|
||||
// Classes of removed sources go first, and count as changed.
|
||||
let gone: Vec<String> = state
|
||||
.classes
|
||||
.iter()
|
||||
.filter(|(_, r)| r.source.as_ref().is_some_and(|s| removed.contains(s)))
|
||||
.map(|(n, _)| n.clone())
|
||||
.collect();
|
||||
for name in gone {
|
||||
let record = state.classes.remove(&name).expect("listed");
|
||||
let _ = std::fs::remove_file(&record.file);
|
||||
constants_changed |= record.constants != incremental::NO_CONSTANTS;
|
||||
api_changed.insert(name);
|
||||
}
|
||||
let mut to_compile: BTreeSet<PathBuf> = if from_scratch || constants_changed {
|
||||
remove_classes(&set.output);
|
||||
for file in previous.generated.iter().chain(&previous.unowned) {
|
||||
let _ = std::fs::remove_file(file);
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&generated);
|
||||
state.classes.retain(|_, r| r.source.is_some());
|
||||
source_stamps.keys().cloned().collect()
|
||||
} else {
|
||||
let affected =
|
||||
incremental::with_subclasses(&state.classes, &upstream_changed.union(&api_changed).cloned().collect());
|
||||
changed.iter().cloned().chain(incremental::dependent_sources(&state.classes, &affected)).collect()
|
||||
};
|
||||
std::fs::create_dir_all(&set.output)?;
|
||||
std::fs::create_dir_all(&generated)?;
|
||||
|
||||
let set_name = if test { "tests" } else { "main" };
|
||||
let total = source_stamps.len();
|
||||
let mut compiled: BTreeSet<PathBuf> = BTreeSet::new();
|
||||
let mut server = None;
|
||||
loop {
|
||||
let batch: BTreeSet<PathBuf> = to_compile
|
||||
.iter()
|
||||
.filter(|s| !compiled.contains(*s) && source_stamps.contains_key(*s))
|
||||
.cloned()
|
||||
.collect();
|
||||
if batch.is_empty() {
|
||||
break;
|
||||
}
|
||||
// The classes the batch replaces: their files go first, so nothing stale is left.
|
||||
let replaced: BTreeMap<String, ClassRecord> = state
|
||||
.classes
|
||||
.iter()
|
||||
.filter(|(_, r)| r.source.as_ref().is_some_and(|s| batch.contains(s)))
|
||||
.map(|(n, r)| (n.clone(), r.clone()))
|
||||
.collect();
|
||||
for (name, record) in &replaced {
|
||||
let _ = std::fs::remove_file(&record.file);
|
||||
state.classes.remove(name);
|
||||
}
|
||||
let files: Vec<PathBuf> = batch.iter().cloned().collect();
|
||||
let noun = if total == 1 { "file" } else { "files" };
|
||||
let count = if files.len() == total {
|
||||
format!("{total} {noun}")
|
||||
} else {
|
||||
format!("{} of {total} {noun}", files.len())
|
||||
};
|
||||
on_event(BuildEvent::Step {
|
||||
command: format!("javac {} ({set_name}, {count})", project.artifact_id),
|
||||
cwd: project.dir.clone().into(),
|
||||
});
|
||||
if server.is_none() {
|
||||
let key = ServerKey {
|
||||
java_home: java_home.clone(),
|
||||
jvm_args: jvm_config(top, &subdir(self.root, top.rel_dir())),
|
||||
};
|
||||
server = Some(self.service.servers.server(self.jar, &key)?);
|
||||
}
|
||||
let mut written: Vec<(PathBuf, Option<PathBuf>)> = Vec::new();
|
||||
let result = server.as_ref().expect("started").compile(
|
||||
&options,
|
||||
&files,
|
||||
config.encoding.as_deref(),
|
||||
cancel,
|
||||
|reply| match reply {
|
||||
Reply::Output { path, source } => written.push((path.clone(), source.clone())),
|
||||
Reply::Generated { path, .. } => state.generated.push(path.clone()),
|
||||
Reply::OutputText { text } => on_event(BuildEvent::Output { text: text.clone(), stderr: false }),
|
||||
Reply::Diagnostic { .. } => {
|
||||
if let Some(m) = diagnostic(reply) {
|
||||
on_event(BuildEvent::Output {
|
||||
text: message_text(&m),
|
||||
stderr: m.severity == Severity::Error,
|
||||
});
|
||||
on_event(BuildEvent::Message { message: m.clone() });
|
||||
messages.push(m);
|
||||
}
|
||||
}
|
||||
Reply::Done { .. } => {}
|
||||
},
|
||||
);
|
||||
if !matches!(result, Ok(true)) {
|
||||
for (path, _) in &written {
|
||||
let _ = std::fs::remove_file(path);
|
||||
}
|
||||
// The next build starts from the state this one started from, with whatever this
|
||||
// one had to compile still to compile. Its earlier rounds' classes are not the
|
||||
// baseline: compared with them, the API and constant changes those rounds found
|
||||
// would never reach this set's dependents or the sets compiled against it.
|
||||
let mut retry = incremental::load_state(&state_file).unwrap_or_default();
|
||||
retry.dirty.extend(to_compile.union(&compiled).filter(|s| source_stamps.contains_key(*s)).cloned());
|
||||
retry.success = false;
|
||||
let _ = model::write_json(&state_file, &retry);
|
||||
return result.map(|_| true);
|
||||
}
|
||||
// javac names sources as they were passed; other spellings are matched canonically,
|
||||
// and classes of sources outside the set (processors' output) are unowned.
|
||||
let canonical: HashMap<PathBuf, &PathBuf> =
|
||||
batch.iter().filter_map(|s| Some((dunce::canonicalize(s).ok()?, s))).collect();
|
||||
let own = |source: PathBuf| -> Option<PathBuf> {
|
||||
if source_stamps.contains_key(&source) {
|
||||
return Some(source);
|
||||
}
|
||||
canonical.get(&dunce::canonicalize(&source).ok()?).map(|s| (*s).clone())
|
||||
};
|
||||
let mut fresh = BTreeMap::new();
|
||||
for (path, source) in written {
|
||||
let source = source.and_then(own);
|
||||
let class = (path.extension().is_some_and(|e| e == "class"))
|
||||
.then(|| std::fs::read(&path).ok())
|
||||
.flatten()
|
||||
.and_then(|bytes| classfile::parse(&bytes));
|
||||
match (class, source) {
|
||||
(Some(class), Some(source)) => {
|
||||
let (name, record) = ClassRecord::new(class, path, Some(source));
|
||||
fresh.insert(name, record);
|
||||
}
|
||||
_ => state.unowned.push(path),
|
||||
}
|
||||
}
|
||||
let round = incremental::diff(&replaced, &fresh);
|
||||
constants_changed |= round.constants;
|
||||
api_changed.extend(round.api.iter().cloned());
|
||||
state.classes.extend(fresh);
|
||||
compiled.extend(batch);
|
||||
if constants_changed {
|
||||
// Constants are copied into the classes that use them: compile the rest too.
|
||||
to_compile.extend(source_stamps.keys().cloned());
|
||||
continue;
|
||||
}
|
||||
let affected =
|
||||
incremental::with_subclasses(&state.classes, &round.api.union(&upstream_changed).cloned().collect());
|
||||
to_compile.extend(incremental::dependent_sources(&state.classes, &affected));
|
||||
to_compile.extend(incremental::shadowed_sources(&state.classes, &round.added));
|
||||
}
|
||||
state.success = true;
|
||||
if !compiled.is_empty() || !api_changed.is_empty() {
|
||||
let changed =
|
||||
incremental::with_subclasses(&state.classes, &api_changed.union(&upstream_changed).cloned().collect());
|
||||
state.log(now_generation(), changed, !had_state || constants_changed);
|
||||
}
|
||||
model::write_json(&state_file, &state)?;
|
||||
Ok(false)
|
||||
}
|
||||
|
||||
/// The JDK compiling a source set: the compiler plugin's forked `executable`, else Maven's
|
||||
@@ -1260,35 +1129,5 @@ fn resource_stamp(set: &SourceSet, cancel: &CancellationToken) -> IdeResult<BTre
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Where `process-resources` puts each file of a source set's resource folders: the output folder,
|
||||
/// the root's target path, then the path under the root, filtered by its includes and excludes.
|
||||
fn resource_outputs(set: &SourceSet, cancel: &CancellationToken) -> IdeResult<BTreeSet<PathBuf>> {
|
||||
let mut out = BTreeSet::new();
|
||||
for root in &set.resources {
|
||||
let mut pending = vec![root.directory.clone()];
|
||||
while let Some(dir) = pending.pop() {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
let Ok(entries) = std::fs::read_dir(&dir) else { continue };
|
||||
for entry in entries.flatten() {
|
||||
let path = entry.path();
|
||||
if entry.file_type().is_ok_and(|t| t.is_dir()) {
|
||||
pending.push(path);
|
||||
continue;
|
||||
}
|
||||
let rel = path.strip_prefix(&root.directory).unwrap_or(&path).to_string_lossy().replace('\\', "/");
|
||||
let included = root.includes.is_empty() || root.includes.iter().any(|p| ant_match(p, &rel));
|
||||
if !included || root.excludes.iter().any(|p| ant_match(p, &rel)) {
|
||||
continue;
|
||||
}
|
||||
let target = root.target_path.as_deref().unwrap_or("").replace('\\', "/");
|
||||
out.insert(set.output.join(target.trim_matches('/')).join(&rel));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -105,26 +105,13 @@ impl ProjectModel {
|
||||
}
|
||||
|
||||
/// Why the IDE can't compile this project with javac itself, if it can't.
|
||||
pub fn unsupported(&self, test: bool, ignored_maven_compile_goals: &[String]) -> Option<String> {
|
||||
pub fn unsupported(&self, test: bool) -> Option<String> {
|
||||
// What the build tool couldn't resolve or read: the model would be incomplete.
|
||||
if let Some(problem) = self.problems.first() {
|
||||
return Some(format!("{}: {problem}", self.artifact_id));
|
||||
}
|
||||
// Keep the recorded model intact: adding or removing a project override must also
|
||||
// affect an already prepared model. Gradle tasks never use Maven overrides.
|
||||
let other_compilers: Vec<&str> = self
|
||||
.other_compilers
|
||||
.iter()
|
||||
.filter(|execution| {
|
||||
!(self.gradle_path.is_none()
|
||||
&& execution.split_once('@').is_some_and(|(goal, _)| {
|
||||
ignored_maven_compile_goals.iter().any(|ignored| ignored.trim() == goal)
|
||||
}))
|
||||
})
|
||||
.map(String::as_str)
|
||||
.collect();
|
||||
if !other_compilers.is_empty() {
|
||||
return Some(format!("{} also compiles with {}", self.artifact_id, other_compilers.join(", ")));
|
||||
if !self.other_compilers.is_empty() {
|
||||
return Some(format!("{} also compiles with {}", self.artifact_id, self.other_compilers.join(", ")));
|
||||
}
|
||||
if test && !self.test_generators.is_empty() {
|
||||
return Some(format!(
|
||||
|
||||
@@ -55,75 +55,6 @@ fn maven_resources_select_projects_by_coordinates_not_by_basedir() {
|
||||
assert_eq!(maven_project_selection(projects.iter()), "org.starry:cloud,org.starry:organ");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maven_compile_goal_overrides_apply_to_cached_models_and_can_be_removed() {
|
||||
let goal = "org.apache.maven.plugins:maven-jar-plugin:jar";
|
||||
let project = ProjectModel {
|
||||
artifact_id: "app".into(),
|
||||
other_compilers: vec![format!("{goal}@default-jar"), format!("{goal}@extra-jar")],
|
||||
..Default::default()
|
||||
};
|
||||
let cached: ProjectModel = serde_json::from_str(&serde_json::to_string(&project).unwrap()).unwrap();
|
||||
assert!(cached.unsupported(false, &[]).unwrap().contains(goal));
|
||||
assert_eq!(cached.unsupported(false, &[goal.into()]), None);
|
||||
assert_eq!(cached.unsupported(false, &[format!(" {goal} ")]), None);
|
||||
assert!(cached.unsupported(false, &[]).unwrap().contains(goal));
|
||||
assert_eq!(cached.other_compilers, project.other_compilers);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maven_compile_goal_overrides_match_exact_goals_and_keep_other_executions() {
|
||||
let jar = "org.apache.maven.plugins:maven-jar-plugin:jar";
|
||||
let kotlin = "org.jetbrains.kotlin:kotlin-maven-plugin:compile";
|
||||
let mut project = ProjectModel {
|
||||
artifact_id: "app".into(),
|
||||
other_compilers: vec![format!("{jar}@default-jar")],
|
||||
..Default::default()
|
||||
};
|
||||
for unmatched in [
|
||||
"",
|
||||
"*",
|
||||
"org.apache.maven.plugins:maven-jar-plugin",
|
||||
"maven-jar-plugin:jar",
|
||||
"org.apache.maven.plugins:maven-jar-plugin:test-jar",
|
||||
"org.apache.maven.plugins:*:jar",
|
||||
] {
|
||||
assert!(project.unsupported(false, &[unmatched.into()]).is_some(), "{unmatched}");
|
||||
}
|
||||
project.other_compilers.push(format!("{kotlin}@compile"));
|
||||
let reason = project.unsupported(false, &[jar.into()]).unwrap();
|
||||
assert!(reason.contains(kotlin));
|
||||
assert!(!reason.contains(jar));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maven_compile_goal_overrides_do_not_affect_gradle_or_other_safety_checks() {
|
||||
let goal = "org.apache.maven.plugins:maven-jar-plugin:jar";
|
||||
let ignored = [goal.into()];
|
||||
let mut project = ProjectModel {
|
||||
artifact_id: "app".into(),
|
||||
other_compilers: vec![format!("{goal}@default-jar")],
|
||||
..Default::default()
|
||||
};
|
||||
project.gradle_path = Some(":app".into());
|
||||
assert!(project.unsupported(false, &ignored).is_some());
|
||||
project.gradle_path = None;
|
||||
project.problems.push("unresolved dependency".into());
|
||||
assert!(project.unsupported(false, &ignored).unwrap().contains("unresolved dependency"));
|
||||
project.problems.clear();
|
||||
project.test_generators.push("org.example:generator:test@tests".into());
|
||||
assert_eq!(project.unsupported(false, &ignored), None);
|
||||
assert!(project.unsupported(true, &ignored).unwrap().contains("generates test sources"));
|
||||
project.test_generators.clear();
|
||||
project.main.compiler = Some(CompilerConfig { compiler_id: Some("eclipse".into()), ..Default::default() });
|
||||
assert!(project.unsupported(false, &ignored).unwrap().contains("eclipse"));
|
||||
project.main.compiler = Some(CompilerConfig { multi_release_output: Some(true), ..Default::default() });
|
||||
assert!(project.unsupported(false, &ignored).unwrap().contains("multi-release"));
|
||||
project.main.compiler =
|
||||
Some(CompilerConfig { processor_path_error: Some("missing processor".into()), ..Default::default() });
|
||||
assert!(project.unsupported(false, &ignored).unwrap().contains("missing processor"));
|
||||
}
|
||||
|
||||
/// A JDK (`JAVA_HOME`) and Maven on the search path, else `None` (the test is skipped).
|
||||
fn tools() -> Option<(PathBuf, PathBuf)> {
|
||||
let home = std::env::var_os("JAVA_HOME").map(PathBuf::from).filter(|h| h.join("bin").is_dir())?;
|
||||
@@ -238,17 +169,6 @@ impl Fixture {
|
||||
}
|
||||
|
||||
fn build(&self, target: Target) -> LaunchOutputs {
|
||||
match self.try_build(target, &[]) {
|
||||
Ok(Built::Done(outputs)) => outputs,
|
||||
Ok(Built::Unsupported(reason)) => {
|
||||
let output = build_output_tail(&self.events.lock().unwrap());
|
||||
panic!("unsupported: {reason}\n{output}");
|
||||
}
|
||||
Err(e) => panic!("{e:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn try_build(&self, target: Target, ignored_maven_compile_goals: &[String]) -> IdeResult<Built> {
|
||||
let jdk = |_: Option<u32>| None;
|
||||
let build = JavaBuild {
|
||||
root: &self.root,
|
||||
@@ -257,12 +177,18 @@ impl Fixture {
|
||||
jar: Path::new(JAR),
|
||||
jar_version: "test",
|
||||
local_repo: None,
|
||||
ignored_maven_compile_goals,
|
||||
service: &self.service,
|
||||
jdk: &jdk,
|
||||
};
|
||||
let on_event = |e: BuildEvent| self.events.lock().unwrap().push(e);
|
||||
build.build(target, BuildKind::Build, &CancellationToken::new(), &on_event)
|
||||
match build.build(target, BuildKind::Build, &CancellationToken::new(), &on_event) {
|
||||
Ok(Built::Done(outputs)) => outputs,
|
||||
Ok(Built::Unsupported(reason)) => {
|
||||
let output = build_output_tail(&self.events.lock().unwrap());
|
||||
panic!("unsupported: {reason}\n{output}");
|
||||
}
|
||||
Err(e) => panic!("{e:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The steps of the launch builds since the last call.
|
||||
@@ -287,37 +213,6 @@ impl Fixture {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_real_maven_compile_goal_can_be_skipped_with_a_cached_reactor() {
|
||||
let pom = APP_POM.replace(
|
||||
"</build>",
|
||||
concat!(
|
||||
"<plugins><plugin><groupId>org.apache.maven.plugins</groupId>",
|
||||
"<artifactId>maven-jar-plugin</artifactId><version>3.4.1</version>",
|
||||
"<executions><execution><id>early-jar</id><phase>compile</phase>",
|
||||
"<goals><goal>jar</goal></goals></execution></executions></plugin></plugins></build>",
|
||||
),
|
||||
);
|
||||
let Some(f) = Fixture::new(&[
|
||||
("app/pom.xml", &pom),
|
||||
("lib/src/main/java/l/L.java", "package l; public class L {}"),
|
||||
("app/src/main/java/a/A.java", "package a; public class A { l.L dependency; }"),
|
||||
]) else {
|
||||
return;
|
||||
};
|
||||
let module = f.root.join("app");
|
||||
let go = |ignored: &[String]| f.try_build(Target::Launch { module: &module, test: false }, ignored).unwrap();
|
||||
let goal = "org.apache.maven.plugins:maven-jar-plugin:jar";
|
||||
assert!(matches!(go(&[]), Built::Unsupported(reason) if reason.contains(goal)));
|
||||
f.steps();
|
||||
let Built::Done(output) = go(&[goal.into()]) else { panic!("expected the configured build to use javac") };
|
||||
assert!(output.failure.is_none(), "{:?}", output.messages);
|
||||
assert!(f.out("t.app/classes/a/A.class").is_file());
|
||||
assert!(!f.root.join("app/target/app-1.jar").exists());
|
||||
assert!(f.steps().iter().all(|step| step.starts_with("javac")), "the prepared model was reused");
|
||||
assert!(matches!(go(&[]), Built::Unsupported(reason) if reason.contains(goal)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn builds_maven_modules_with_javac_and_only_what_changed() {
|
||||
let Some(f) = Fixture::new(&[
|
||||
@@ -363,8 +258,6 @@ fn builds_maven_modules_with_javac_and_only_what_changed() {
|
||||
let steps = f.steps_of_launch();
|
||||
assert_eq!(steps.len(), 1, "{steps:?}");
|
||||
assert!(steps[0].contains("resources:resources") && steps[0].contains("-pl t:app"), "{steps:?}");
|
||||
// #7340: content replaced without a newer mtime is copied too.
|
||||
assert!(steps[0].contains("-Dmaven.resources.overwrite=true"), "{steps:?}");
|
||||
assert_eq!(fs::read_to_string(f.out("t.app/classes/app.properties")).unwrap(), "version=1\nmore=1\n");
|
||||
|
||||
// A deleted source leaves no class behind.
|
||||
@@ -416,104 +309,6 @@ fn builds_maven_modules_with_javac_and_only_what_changed() {
|
||||
assert!(f.out("t.app/test-classes/a/AggTest.class").is_file());
|
||||
}
|
||||
|
||||
/// #7743: a dependency's own dependencies come before its next sibling on the classpath, as in
|
||||
/// `mvn compile`, so of two artifacts with the same classes (`dom4j:dom4j` 1.x and
|
||||
/// `org.dom4j:dom4j` 2.x) javac sees the one Maven does.
|
||||
#[test]
|
||||
fn maven_classpath_lists_dependencies_in_maven_order() {
|
||||
let module = |name: &str, deps: &[&str]| {
|
||||
let deps: String = deps
|
||||
.iter()
|
||||
.map(|d| {
|
||||
format!("<dependency><groupId>t</groupId><artifactId>{d}</artifactId><version>1</version></dependency>")
|
||||
})
|
||||
.collect();
|
||||
format!(
|
||||
"<project><modelVersion>4.0.0</modelVersion><parent><groupId>t</groupId><artifactId>root</artifactId>\
|
||||
<version>1</version></parent><artifactId>{name}</artifactId><dependencies>{deps}</dependencies></project>"
|
||||
)
|
||||
};
|
||||
let root = ROOT_POM.replace(
|
||||
"<module>lib</module>",
|
||||
"<module>newdom</module><module>olddom</module><module>x</module><module>lib</module>",
|
||||
);
|
||||
let (newdom, olddom, x, lib) =
|
||||
(module("newdom", &[]), module("olddom", &[]), module("x", &["newdom"]), module("lib", &["x", "olddom"]));
|
||||
let Some(f) = Fixture::new(&[
|
||||
("pom.xml", &root),
|
||||
("newdom/pom.xml", &newdom),
|
||||
("olddom/pom.xml", &olddom),
|
||||
("x/pom.xml", &x),
|
||||
("lib/pom.xml", &lib),
|
||||
("newdom/src/main/java/d/Element.java", "package d;\npublic class Element { public void fresh() {} }\n"),
|
||||
("olddom/src/main/java/d/Element.java", "package d;\npublic class Element {}\n"),
|
||||
("app/src/main/java/a/A.java", "package a;\nclass A { void f() { new d.Element().fresh(); } }\n"),
|
||||
]) else {
|
||||
return;
|
||||
};
|
||||
let built = f.launch(false);
|
||||
assert_eq!(built.failure, None, "{:?}", built.messages);
|
||||
let position = |name: &str| built.class_paths.iter().position(|p| *p == f.out(&format!("t.{name}/classes")));
|
||||
assert!(position("newdom") < position("olddom"), "{:?}", built.class_paths);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maps_resources_to_the_output_paths_the_build_tool_writes() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap();
|
||||
write(&root, "src/main/resources/app.properties", "a=1");
|
||||
write(&root, "src/main/resources/notes.txt", "n");
|
||||
write(&root, "src/main/resources/deep/app.properties", "b=2");
|
||||
let resources = root.join("src/main/resources");
|
||||
let output = root.join("out/classes");
|
||||
let set = SourceSet {
|
||||
output: output.clone(),
|
||||
resources: vec![
|
||||
ResourceRoot { directory: resources.clone(), ..Default::default() },
|
||||
// A `<targetPath>` and an `<includes>` pattern, as a POM can configure them.
|
||||
ResourceRoot {
|
||||
directory: resources,
|
||||
target_path: Some("META-INF".into()),
|
||||
includes: vec!["*.properties".into()],
|
||||
..Default::default()
|
||||
},
|
||||
],
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(
|
||||
resource_outputs(&set, &CancellationToken::new()).unwrap(),
|
||||
BTreeSet::from([
|
||||
output.join("app.properties"),
|
||||
output.join("notes.txt"),
|
||||
output.join("deep/app.properties"),
|
||||
output.join("META-INF/app.properties"),
|
||||
])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deletes_the_output_of_a_resource_removed_from_the_sources() {
|
||||
let Some(f) = Fixture::new(&[
|
||||
("app/src/main/java/a/A.java", "package a;\npublic class A {}\n"),
|
||||
("app/src/main/resources/app.properties", "version=${project.version}\n"),
|
||||
("app/src/main/resources/META-INF/spring.factories", "a.A\n"),
|
||||
]) else {
|
||||
return;
|
||||
};
|
||||
assert_eq!(f.launch(false).failure, None);
|
||||
assert_eq!(fs::read_to_string(f.out("t.app/classes/META-INF/spring.factories")).unwrap(), "a.A\n");
|
||||
assert!(f.steps_of_launch().is_empty());
|
||||
|
||||
// A deleted resource leaves no copy behind: the launch would read a file the sources no longer have.
|
||||
fs::remove_file(f.root.join("app/src/main/resources/META-INF/spring.factories")).unwrap();
|
||||
let steps = f.steps_of_launch();
|
||||
assert!(steps.iter().any(|s| s.contains("resources:resources")), "{steps:?}");
|
||||
assert!(!f.out("t.app/classes/META-INF/spring.factories").exists(), "the removed resource stays on the classpath");
|
||||
// The resource that is still there keeps its copy, and a launch with nothing changed runs nothing.
|
||||
assert_eq!(fs::read_to_string(f.out("t.app/classes/app.properties")).unwrap(), "version=1\n");
|
||||
assert!(f.steps_of_launch().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recompiles_the_classes_an_api_change_reaches() {
|
||||
let Some(f) = Fixture::new(&[
|
||||
@@ -690,7 +485,7 @@ fn javac_options_follow_the_compiler_configuration() {
|
||||
"-processorpath /p.jar",
|
||||
"-processor a.P",
|
||||
"-proc:none",
|
||||
"-g",
|
||||
"-g:lines,vars",
|
||||
"-parameters",
|
||||
"-nowarn",
|
||||
"-encoding UTF-8",
|
||||
@@ -705,28 +500,6 @@ fn javac_options_follow_the_compiler_configuration() {
|
||||
assert!(old.contains("-source 1.8") && !old.contains("--release"), "{old}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn javac_options_always_keep_debug_info() {
|
||||
// `<debug>false</debug>` makes Maven pass `-g:none`; the IDE's build still emits the line
|
||||
// numbers and variables the debugger needs (#7786).
|
||||
let set = SourceSet {
|
||||
output: PathBuf::from("/o"),
|
||||
compiler: Some(CompilerConfig {
|
||||
debug: Some(false),
|
||||
debuglevel: Some("source".into()),
|
||||
compiler_args: vec!["-g:none".into(), "-Xlint:all".into()],
|
||||
compiler_argument: Some("-g:source -Xlint:none".into()),
|
||||
compiler_arguments: [("g:none".to_owned(), None)].into(),
|
||||
..Default::default()
|
||||
}),
|
||||
..Default::default()
|
||||
};
|
||||
let args = javac_options(&set, &[], Path::new("/gen"), Some(21));
|
||||
let debug: Vec<_> = args.iter().filter(|a| a.starts_with("-g")).collect();
|
||||
assert_eq!(debug, ["-g"], "{args:?}");
|
||||
assert!(args.iter().any(|a| a == "-Xlint:all") && args.iter().any(|a| a == "-Xlint:none"), "{args:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn builds_gradle_projects_with_javac_and_only_what_changed() {
|
||||
let Some(f) = Fixture::gradle(&[
|
||||
@@ -808,7 +581,6 @@ fn leaves_gradle_projects_with_other_compilers_to_gradle() {
|
||||
jar: Path::new(JAR),
|
||||
jar_version: "test",
|
||||
local_repo: None,
|
||||
ignored_maven_compile_goals: &[],
|
||||
service: &f.service,
|
||||
jdk: &jdk,
|
||||
};
|
||||
|
||||
@@ -103,19 +103,9 @@ pub fn load_linked_with_jdk(
|
||||
let mut m = maven::load_with_linked_jdk(root, repo, &profiles, maven_jdk_version, &settings.linked_projects);
|
||||
maven::UnlinkedProjects::from_model(&m, settings).filter(&mut m);
|
||||
// The user settings' profiles can be chosen too (`-P` applies to them as well).
|
||||
if let Some(settings_file) = maven::user_settings_file(root, settings) {
|
||||
for p in maven::settings_profiles(&settings_file) {
|
||||
if let Some(existing) = m.profiles.iter_mut().find(|x| x.id == p.id) {
|
||||
existing.active_by_default |= p.active_by_default;
|
||||
} else {
|
||||
m.profiles.push(p);
|
||||
}
|
||||
}
|
||||
let active_in_settings = maven::settings_active_profiles(&settings_file);
|
||||
for existing in &mut m.profiles {
|
||||
if active_in_settings.iter().any(|id| id == &existing.id) {
|
||||
existing.active_by_default = true;
|
||||
}
|
||||
for p in maven::user_settings_file(root, settings).map(|f| maven::settings_profiles(&f)).unwrap_or_default() {
|
||||
if !m.profiles.iter().any(|x| x.id == p.id) {
|
||||
m.profiles.push(p);
|
||||
}
|
||||
}
|
||||
sync::apply_maven_cache(root, cache_dir, &mut m);
|
||||
@@ -368,49 +358,6 @@ mod tests {
|
||||
assert!(modules(&settings).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn settings_xml_active_profiles_mark_pom_profiles_active_by_default() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
std::fs::create_dir(root.join("child")).unwrap();
|
||||
std::fs::write(
|
||||
root.join("pom.xml"),
|
||||
r#"<project><groupId>demo</groupId><artifactId>root</artifactId><version>1.0</version><packaging>pom</packaging>
|
||||
<modules><module>child</module></modules>
|
||||
<profiles>
|
||||
<profile><id>test3</id></profile>
|
||||
<profile><id>dev</id><activation><activeByDefault>TRUE</activeByDefault></activation></profile>
|
||||
</profiles></project>"#,
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::write(
|
||||
root.join("child/pom.xml"),
|
||||
r#"<project><parent><groupId>demo</groupId><artifactId>root</artifactId><version>1.0</version></parent>
|
||||
<artifactId>child</artifactId>
|
||||
<profiles><profile><id>child-default</id><activation><activeByDefault>true</activeByDefault></activation></profile></profiles></project>"#,
|
||||
)
|
||||
.unwrap();
|
||||
let settings_xml = root.join("settings.xml");
|
||||
std::fs::write(
|
||||
&settings_xml,
|
||||
r#"<settings><activeProfiles><activeProfile>test3</activeProfile></activeProfiles></settings>"#,
|
||||
)
|
||||
.unwrap();
|
||||
let cache = root.join("cache");
|
||||
let settings = ide_core::settings::MavenSettings {
|
||||
user_settings: settings_xml.to_string_lossy().into_owned(),
|
||||
..Default::default()
|
||||
};
|
||||
let model = load_linked(root, &cache, None, &settings, &Default::default()).maven.unwrap();
|
||||
let flags: Vec<(&str, bool)> = model.profiles.iter().map(|p| (p.id.as_str(), p.active_by_default)).collect();
|
||||
assert!(
|
||||
flags.contains(&("test3", true)),
|
||||
"activeProfile from settings.xml marks POM profile active: {flags:?}"
|
||||
);
|
||||
assert!(flags.contains(&("dev", true)), "case-insensitive activeByDefault: {flags:?}");
|
||||
assert!(flags.contains(&("child-default", true)), "child module activeByDefault: {flags:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn detects_build_systems_and_build_files() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -43,10 +43,6 @@ pub struct MavenModel {
|
||||
/// Build files changed since that sync.
|
||||
pub stale: bool,
|
||||
pub sync_error: Option<String>,
|
||||
/// The `<activation><jdk>` values of the projects' own POMs that the JDK matches.
|
||||
#[serde(skip)]
|
||||
#[specta(skip)]
|
||||
pub(crate) jdk_activations: std::collections::BTreeSet<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
@@ -73,15 +69,10 @@ pub struct MavenProject {
|
||||
pub aggregated: bool,
|
||||
pub plugins: Vec<MavenPlugin>,
|
||||
pub dependencies: Vec<MavenDependency>,
|
||||
/// Local classpath entries from the POM. The synced dependency tree has coordinates only.
|
||||
#[serde(skip)]
|
||||
pub system_paths: Vec<PathBuf>,
|
||||
/// Profile ids declared in this POM.
|
||||
pub profiles: Vec<String>,
|
||||
/// Java feature version the project compiles for (`maven.compiler.release`, `java.version`…).
|
||||
pub java_version: Option<u32>,
|
||||
/// `project.build.sourceEncoding` as the POM spells it (a Java charset name such as `ISO-8859-15`).
|
||||
pub source_encoding: Option<String>,
|
||||
/// Maven launcher: the nearest `mvnw` (absolute), else `mvn`. Inside the opened
|
||||
/// project the search stops at its root; outside it, the search stops before
|
||||
/// that root so a linked project keeps its own wrapper.
|
||||
@@ -98,100 +89,6 @@ impl MavenProject {
|
||||
}
|
||||
}
|
||||
|
||||
/// All projects belonging to the Maven reactor rooted at `top`, traversed through `<modules>`.
|
||||
pub(crate) fn reactor_projects<'a>(m: &'a MavenModel, top: &'a MavenProject) -> Vec<&'a MavenProject> {
|
||||
let mut projects = Vec::new();
|
||||
let mut pending = vec![top];
|
||||
let mut seen = HashSet::new();
|
||||
while let Some(p) = pending.pop() {
|
||||
if !seen.insert(&p.pom) {
|
||||
continue;
|
||||
}
|
||||
projects.push(p);
|
||||
pending.extend(m.projects.iter().filter(|child| p.modules.contains(&child.pom)));
|
||||
}
|
||||
projects
|
||||
}
|
||||
|
||||
fn reactor_for<'a>(m: &'a MavenModel, target: &'a MavenProject) -> &'a MavenProject {
|
||||
if !target.aggregated {
|
||||
return target;
|
||||
}
|
||||
let mut matches =
|
||||
m.projects.iter().filter(|top| !top.aggregated && reactor_projects(m, top).iter().any(|p| p.pom == target.pom));
|
||||
let first = matches.next();
|
||||
let ancestor = first
|
||||
.into_iter()
|
||||
.chain(matches)
|
||||
.filter(|top| top.dir.is_empty() || target.dir == top.dir || target.dir.starts_with(&format!("{}/", top.dir)))
|
||||
.max_by_key(|top| top.dir.len());
|
||||
ancestor.or(first).unwrap_or(target)
|
||||
}
|
||||
|
||||
/// The linked reactor root owning the project at `pom` (project-relative).
|
||||
pub(crate) fn reactor_for_pom<'a>(m: &'a MavenModel, pom: &str) -> Option<&'a MavenProject> {
|
||||
m.projects.iter().find(|p| p.pom == pom).map(|target| reactor_for(m, target))
|
||||
}
|
||||
|
||||
/// The linked reactor root owning the project at `dir` (project-relative).
|
||||
pub(crate) fn reactor_for_dir<'a>(m: &'a MavenModel, dir: &str) -> Option<&'a MavenProject> {
|
||||
m.projects.iter().find(|p| p.dir == dir).map(|target| reactor_for(m, target))
|
||||
}
|
||||
|
||||
/// `/`-separated relative path from `from` to `to`, supporting sibling (`../app`) and parent (`..`)
|
||||
/// module layouts. Returns `None` when the paths do not share a root/drive.
|
||||
pub(crate) fn relative_module_path(from: &Path, to: &Path) -> Option<String> {
|
||||
use std::path::Component;
|
||||
let from = crate::gradle::normalize(from);
|
||||
let to = crate::gradle::normalize(to);
|
||||
let from_comps: Vec<_> = from.components().collect();
|
||||
let to_comps: Vec<_> = to.components().collect();
|
||||
let common = from_comps.iter().zip(&to_comps).take_while(|(a, b)| a == b).count();
|
||||
let mut parts = Vec::new();
|
||||
for comp in &from_comps[common..] {
|
||||
match comp {
|
||||
Component::Normal(_) => parts.push("..".into()),
|
||||
Component::CurDir => {}
|
||||
Component::ParentDir | Component::Prefix(_) | Component::RootDir => return None,
|
||||
}
|
||||
}
|
||||
for comp in &to_comps[common..] {
|
||||
match comp {
|
||||
Component::Normal(s) => parts.push(s.to_string_lossy().into_owned()),
|
||||
Component::ParentDir => parts.push("..".into()),
|
||||
Component::CurDir => {}
|
||||
Component::Prefix(_) | Component::RootDir => return None,
|
||||
}
|
||||
}
|
||||
Some(parts.join("/"))
|
||||
}
|
||||
|
||||
/// Maven `-pl` selector for `module` when invoked from reactor `top` (`None` when `module` is `top`).
|
||||
pub(crate) fn module_selector(root: &Path, top: &MavenProject, module: &MavenProject) -> Option<String> {
|
||||
if top.pom == module.pom {
|
||||
return None;
|
||||
}
|
||||
let base = dunce::canonicalize(root).unwrap_or_else(|_| root.to_path_buf());
|
||||
let resolve_dir = |dir: &str| {
|
||||
let raw = if dir.is_empty() { base.clone() } else { base.join(dir) };
|
||||
dunce::canonicalize(&raw).unwrap_or(raw)
|
||||
};
|
||||
let from = resolve_dir(&top.dir);
|
||||
let to = resolve_dir(&module.dir);
|
||||
if let Some(rel) = relative_module_path(&from, &to)
|
||||
&& !rel.is_empty()
|
||||
{
|
||||
return Some(rel);
|
||||
}
|
||||
if !module.group_id.is_empty() && !module.artifact_id.is_empty() {
|
||||
Some(format!("{}:{}", module.group_id, module.artifact_id))
|
||||
} else if !module.artifact_id.is_empty() {
|
||||
Some(format!(":{}", module.artifact_id))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct MavenPlugin {
|
||||
@@ -279,7 +176,6 @@ struct RawDep {
|
||||
kind: Option<String>,
|
||||
classifier: Option<String>,
|
||||
scope: Option<String>,
|
||||
system_path: Option<String>,
|
||||
optional: bool,
|
||||
}
|
||||
|
||||
@@ -352,7 +248,6 @@ fn read_dep(e: &Element) -> Option<RawDep> {
|
||||
kind: e.text_of("type"),
|
||||
classifier: e.text_of("classifier"),
|
||||
scope: e.text_of("scope"),
|
||||
system_path: e.text_of("systemPath"),
|
||||
optional: e.text_of("optional").is_some_and(|o| o == "true"),
|
||||
})
|
||||
}
|
||||
@@ -439,9 +334,7 @@ fn read_raw(project: &Element) -> RawPom {
|
||||
for p in project.list("profiles", "profile") {
|
||||
let mut profile = RawProfile {
|
||||
id: p.text_of("id").unwrap_or_else(|| "default".into()),
|
||||
active_by_default: p
|
||||
.at("activation/activeByDefault")
|
||||
.is_some_and(|a| a.text.trim().eq_ignore_ascii_case("true")),
|
||||
active_by_default: p.at("activation/activeByDefault").is_some_and(|a| a.text.trim() == "true"),
|
||||
activation_jdk: p.at("activation/jdk").map(|jdk| jdk.text.trim().to_owned()).filter(|jdk| !jdk.is_empty()),
|
||||
modules: module_names(p),
|
||||
properties: read_properties(p.child("properties")),
|
||||
@@ -605,25 +498,12 @@ pub fn settings_profiles(settings: &Path) -> Vec<MavenProfile> {
|
||||
if profiles.iter().any(|p| p.id == id) {
|
||||
continue;
|
||||
}
|
||||
let by_default =
|
||||
profile.at("activation/activeByDefault").is_some_and(|e| e.text.trim().eq_ignore_ascii_case("true"));
|
||||
let by_default = profile.at("activation/activeByDefault").is_some_and(|e| e.text.trim() == "true");
|
||||
profiles.push(MavenProfile { active_by_default: by_default || active.contains(&id), id, ..Default::default() });
|
||||
}
|
||||
profiles
|
||||
}
|
||||
|
||||
/// Profile IDs listed under `<activeProfiles>` in `settings.xml` (may refer to profiles defined in POMs).
|
||||
pub fn settings_active_profiles(settings: &Path) -> Vec<String> {
|
||||
let Some(root) = xml::read_text(settings).as_deref().and_then(xml::parse) else {
|
||||
return Vec::new();
|
||||
};
|
||||
root.list("activeProfiles", "activeProfile")
|
||||
.iter()
|
||||
.map(|e| e.text.trim().to_owned())
|
||||
.filter(|id| !id.is_empty())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// `<localRepository>` of a settings file, when it names one: the repository a build
|
||||
/// with `-s <file>` resolves into, which is not necessarily the user's default.
|
||||
pub fn local_repository_of(settings: &Path) -> Option<PathBuf> {
|
||||
@@ -659,88 +539,25 @@ pub fn local_repository_for(options: &[String]) -> Option<PathBuf> {
|
||||
/// A goal of the IDE's own (`help:evaluate`, `dependency:build-classpath`, …) by its plugin's
|
||||
/// coordinates rather than its prefix: offline, Maven resolves a prefix only from group metadata
|
||||
/// in the local repository, which a repository filled from a private mirror often lacks even when
|
||||
/// the plugin itself is there. Uses the newest 3.x version already in `repo` that `maven` (the
|
||||
/// version of the Maven that runs it, when known) can load, so nothing is downloaded, else a
|
||||
/// pinned one for that Maven.
|
||||
pub fn plugin_goal(goal: &str, repo: Option<&Path>, maven: Option<MavenVersion>) -> String {
|
||||
/// the plugin itself is there. Uses the newest 3.x version already in `repo`, so nothing is
|
||||
/// downloaded, else a pinned one.
|
||||
pub fn plugin_goal(goal: &str, repo: Option<&Path>) -> String {
|
||||
let (prefix, goal) = goal.split_once(':').expect("prefix:goal");
|
||||
let artifact = match prefix {
|
||||
"help" => "maven-help-plugin",
|
||||
"dependency" => "maven-dependency-plugin",
|
||||
let (artifact, pinned) = match prefix {
|
||||
"help" => ("maven-help-plugin", "3.5.1"),
|
||||
"dependency" => ("maven-dependency-plugin", "3.8.1"),
|
||||
_ => unreachable!("not a goal of the IDE's own: {prefix}"),
|
||||
};
|
||||
let version = repo
|
||||
.and_then(|repo| newest_local_plugin(repo, artifact, 3, maven))
|
||||
.unwrap_or_else(|| pinned_plugin(artifact, maven).to_owned());
|
||||
let version = repo.and_then(|repo| newest_local_plugin(repo, artifact, 3)).unwrap_or_else(|| pinned.to_owned());
|
||||
format!("org.apache.maven.plugins:{artifact}:{version}:{goal}")
|
||||
}
|
||||
|
||||
/// The version of the IDE's own plugin `artifact` to download for `maven`: the current one,
|
||||
/// or the newest that still loads in an older Maven (their `requiredMavenVersion`).
|
||||
pub(crate) fn pinned_plugin(artifact: &str, maven: Option<MavenVersion>) -> &'static str {
|
||||
let at_least = |v: MavenVersion| maven.is_none_or(|m| m >= v);
|
||||
match artifact {
|
||||
"maven-help-plugin" if at_least((3, 6, 3)) => "3.5.1",
|
||||
"maven-help-plugin" if at_least((3, 2, 5)) => "3.3.0",
|
||||
"maven-help-plugin" => "3.2.0",
|
||||
"maven-dependency-plugin" if at_least((3, 6, 3)) => "3.8.1",
|
||||
"maven-dependency-plugin" if at_least((3, 2, 5)) => "3.6.1",
|
||||
"maven-dependency-plugin" => "3.1.2",
|
||||
_ => unreachable!("not a plugin of the IDE's own: {artifact}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// A Maven version as `(major, minor, patch)`.
|
||||
pub type MavenVersion = (u64, u64, u64);
|
||||
|
||||
fn parse_maven_version(v: &str) -> Option<MavenVersion> {
|
||||
let mut parts = v.trim().split(['.', '-']).map(str::parse::<u64>);
|
||||
let major = parts.next()?.ok()?;
|
||||
let minor = parts.next().and_then(Result::ok).unwrap_or(0);
|
||||
let patch = parts.next().and_then(Result::ok).unwrap_or(0);
|
||||
Some((major, minor, patch))
|
||||
}
|
||||
|
||||
/// The version of the Maven that `command` starts: a wrapper's `distributionUrl`, else the
|
||||
/// `maven-core` jar of the installation the launcher belongs to (`<home>/lib`, or
|
||||
/// `<home>/libexec/lib` for Homebrew's layout). `None` when it can't be told (mvnd, another
|
||||
/// layout); callers then keep their defaults.
|
||||
pub fn maven_version(command: &str) -> Option<MavenVersion> {
|
||||
let path = Path::new(command);
|
||||
let name = path.file_name()?.to_str()?;
|
||||
if name.eq_ignore_ascii_case("mvnw") || name.eq_ignore_ascii_case("mvnw.cmd") {
|
||||
let props = path.parent()?.join(".mvn").join("wrapper").join("maven-wrapper.properties");
|
||||
let text = std::fs::read_to_string(props).ok()?;
|
||||
let url = text.lines().find_map(|l| l.trim().strip_prefix("distributionUrl"))?;
|
||||
let version = url.split("apache-maven-").nth(1)?.split("-bin").next()?;
|
||||
return parse_maven_version(version);
|
||||
}
|
||||
let launcher = if path.components().count() > 1 {
|
||||
path.to_path_buf()
|
||||
} else {
|
||||
ide_core::process::find_executable(command, &ide_core::tool_path::search_path())?
|
||||
};
|
||||
let launcher = dunce::canonicalize(launcher).ok()?;
|
||||
let home = launcher.parent()?.parent()?;
|
||||
[home.join("lib"), home.join("libexec").join("lib")].iter().find_map(|lib| {
|
||||
std::fs::read_dir(lib).ok()?.flatten().find_map(|e| {
|
||||
let name = e.file_name().into_string().ok()?;
|
||||
parse_maven_version(name.strip_prefix("maven-core-")?.strip_suffix(".jar")?)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// The newest release of `org.apache.maven.plugins:<artifact>` whose jar is in `repo`,
|
||||
/// from major version `min_major` up, that `maven` can load (when it is known).
|
||||
pub(crate) fn newest_local_plugin(
|
||||
repo: &Path,
|
||||
artifact: &str,
|
||||
min_major: u64,
|
||||
maven: Option<MavenVersion>,
|
||||
) -> Option<String> {
|
||||
/// from major version `min_major` up.
|
||||
pub(crate) fn newest_local_plugin(repo: &Path, artifact: &str, min_major: u64) -> Option<String> {
|
||||
let dir = repo.join("org/apache/maven/plugins").join(artifact);
|
||||
let parse = |v: &str| v.split('.').map(|n| n.parse::<u64>().ok()).collect::<Option<Vec<u64>>>();
|
||||
let mut versions: Vec<(Vec<u64>, String)> = std::fs::read_dir(&dir)
|
||||
std::fs::read_dir(&dir)
|
||||
.ok()?
|
||||
.flatten()
|
||||
.filter_map(|e| e.file_name().into_string().ok())
|
||||
@@ -749,24 +566,8 @@ pub(crate) fn newest_local_plugin(
|
||||
n.first().is_some_and(|&major| major >= min_major)
|
||||
&& dir.join(v).join(format!("{artifact}-{v}.jar")).is_file()
|
||||
})
|
||||
.collect();
|
||||
versions.sort();
|
||||
versions.into_iter().rev().map(|(_, v)| v).find(|v| {
|
||||
maven.is_none_or(|maven| {
|
||||
required_maven_version(&dir.join(v).join(format!("{artifact}-{v}.jar"))).is_none_or(|need| maven >= need)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// The `requiredMavenVersion` a plugin jar's descriptor declares (plugins built since
|
||||
/// maven-plugin-plugin 3.x do; older ones run on any Maven 3).
|
||||
fn required_maven_version(jar: &Path) -> Option<MavenVersion> {
|
||||
let file = std::fs::File::open(jar).ok()?;
|
||||
let mut archive = zip::ZipArchive::new(file).ok()?;
|
||||
let mut entry = archive.by_name("META-INF/maven/plugin.xml").ok()?;
|
||||
let mut text = String::new();
|
||||
entry.read_to_string(&mut text).ok()?;
|
||||
parse_maven_version(&xml::parse(&text)?.text_of("requiredMavenVersion")?)
|
||||
.max()
|
||||
.map(|(_, v)| v)
|
||||
}
|
||||
|
||||
impl Resolver {
|
||||
@@ -1534,22 +1335,6 @@ pub fn external_pom_dirs(root: &Path, linked: &[String]) -> Vec<PathBuf> {
|
||||
out
|
||||
}
|
||||
|
||||
/// Linked POMs inside the opened root that a folder scan doesn't reach: it stops at the
|
||||
/// first folder with a `pom.xml` and follows only that project's modules, so a POM linked
|
||||
/// below another Maven project's folder (a deployable module its parent doesn't list) is
|
||||
/// never found. jdtls imports this way.
|
||||
pub fn linked_poms_below_projects(root: &Path, linked: &[String]) -> Vec<PathBuf> {
|
||||
let base = dunce::canonicalize(root).unwrap_or_else(|_| root.to_path_buf());
|
||||
linked_poms(root, linked)
|
||||
.into_iter()
|
||||
.filter(|pom| {
|
||||
let Some(dir) = pom.parent() else { return false };
|
||||
dir.starts_with(&base)
|
||||
&& dir.ancestors().skip(1).take_while(|d| d.starts_with(&base)).any(|d| is_pom_file(&d.join("pom.xml")))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
type FileStamp = Option<(Option<std::time::SystemTime>, u64)>;
|
||||
|
||||
fn file_stamp(path: &Path) -> FileStamp {
|
||||
@@ -1720,8 +1505,6 @@ pub fn load_with_linked_jdk(
|
||||
for p in resolver.active(&pom.profiles) {
|
||||
module_names.extend(p.modules.iter().cloned());
|
||||
}
|
||||
let jdks = pom.profiles.iter().filter_map(|p| p.activation_jdk.as_ref());
|
||||
model.jdk_activations.extend(jdks.filter(|spec| jdk_matches(spec, jdk_version)).cloned());
|
||||
let mut modules: Vec<PathBuf> = Vec::new();
|
||||
for m in module_names {
|
||||
let mut mp = crate::gradle::normalize(&dir.join(i(&m)));
|
||||
@@ -1736,13 +1519,7 @@ pub fn load_with_linked_jdk(
|
||||
let packaging = i(pom.packaging.as_deref().unwrap_or("jar"));
|
||||
let managed: HashMap<String, &RawDep> = ctx.managed.iter().map(|m| (m.key(), m)).collect();
|
||||
let managed_version = |d: &RawDep| managed.get(&d.key()).and_then(|m| m.version.clone());
|
||||
let scope = |d: &RawDep| {
|
||||
d.scope
|
||||
.as_deref()
|
||||
.or_else(|| managed.get(&d.key()).and_then(|m| m.scope.as_deref()))
|
||||
.map(i)
|
||||
.unwrap_or_else(|| "compile".into())
|
||||
};
|
||||
let managed_scope = |d: &RawDep| managed.get(&d.key()).and_then(|m| m.scope.clone());
|
||||
let dependencies = ctx
|
||||
.deps
|
||||
.iter()
|
||||
@@ -1752,26 +1529,11 @@ pub fn load_with_linked_jdk(
|
||||
version: d.version.clone().or_else(|| managed_version(d)).map(|v| i(&v)),
|
||||
kind: d.kind.clone().unwrap_or_else(|| "jar".into()),
|
||||
classifier: d.classifier.clone(),
|
||||
scope: scope(d),
|
||||
scope: d.scope.clone().or_else(|| managed_scope(d)).unwrap_or_else(|| "compile".into()),
|
||||
optional: d.optional,
|
||||
..MavenDependency::default()
|
||||
})
|
||||
.collect();
|
||||
let system_paths = ctx
|
||||
.deps
|
||||
.iter()
|
||||
.filter(|d| scope(d) == "system")
|
||||
.filter_map(|d| {
|
||||
let path = d
|
||||
.system_path
|
||||
.as_deref()
|
||||
.or_else(|| managed.get(&d.key()).and_then(|m| m.system_path.as_deref()))?;
|
||||
let path = i(path);
|
||||
// Rebuilt from its components: `${pom.basedir}/lib/x.jar` on Windows mixes `\\` and `/`.
|
||||
(!path.contains("${") && Path::new(&path).is_absolute())
|
||||
.then(|| Path::new(&path).components().collect::<PathBuf>())
|
||||
})
|
||||
.collect();
|
||||
|
||||
let mut plugins: Vec<RawPlugin> = ctx.plugins.clone();
|
||||
for a in lifecycle_plugins(&packaging) {
|
||||
@@ -1801,16 +1563,10 @@ pub fn load_with_linked_jdk(
|
||||
.find_map(|k| props.get(*k).map(|v| i(v)))
|
||||
.or_else(|| ctx.compiler_release.as_deref().map(i))
|
||||
.and_then(|v| java_version(&v));
|
||||
let source_encoding = props
|
||||
.get("project.build.sourceEncoding")
|
||||
.map(|v| i(v).trim().to_owned())
|
||||
.filter(|v| !v.is_empty() && !v.contains("${"));
|
||||
|
||||
// The project can activate the profiles of its own POM and its ancestors'.
|
||||
for (id, active) in &ctx.profiles {
|
||||
if let Some(existing) = model.profiles.iter_mut().find(|x| x.id == *id) {
|
||||
existing.active_by_default |= *active;
|
||||
} else {
|
||||
if !model.profiles.iter().any(|x| x.id == *id) {
|
||||
model.profiles.push(MavenProfile { id: id.clone(), active_by_default: *active, ..Default::default() });
|
||||
}
|
||||
}
|
||||
@@ -1836,10 +1592,8 @@ pub fn load_with_linked_jdk(
|
||||
aggregated,
|
||||
plugins,
|
||||
dependencies,
|
||||
system_paths,
|
||||
profiles: ctx.profiles.iter().map(|(id, _)| id.clone()).collect(),
|
||||
java_version: jv,
|
||||
source_encoding,
|
||||
command: wrapper(&canonical_root, &dir_canon),
|
||||
options: Vec::new(),
|
||||
env: BTreeMap::new(),
|
||||
@@ -2806,84 +2560,6 @@ mod tests {
|
||||
zip.finish().unwrap();
|
||||
}
|
||||
|
||||
/// A plugin jar whose descriptor declares `requiredMavenVersion` (none when `None`).
|
||||
fn write_plugin_requiring(repo: &Path, artifact: &str, version: &str, maven: Option<&str>) {
|
||||
let dir = repo.join("org/apache/maven/plugins").join(artifact).join(version);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let required = maven.map(|m| format!("<requiredMavenVersion>{m}</requiredMavenVersion>")).unwrap_or_default();
|
||||
let file = std::fs::File::create(dir.join(format!("{artifact}-{version}.jar"))).unwrap();
|
||||
let mut zip = zip::ZipWriter::new(file);
|
||||
zip.start_file("META-INF/maven/plugin.xml", zip::write::SimpleFileOptions::default()).unwrap();
|
||||
std::io::Write::write_all(&mut zip, format!("<plugin>{required}<mojos/></plugin>").as_bytes()).unwrap();
|
||||
zip.finish().unwrap();
|
||||
}
|
||||
|
||||
/// #8114: with Maven 3.3.9, a cached maven-help-plugin 3.6.0 (needs Maven 3.9.0) made every
|
||||
/// sync fail; the newest cached version that Maven can load is used, else an older pinned one.
|
||||
#[test]
|
||||
fn plugin_goals_skip_plugins_the_maven_cannot_load() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let repo = tmp.path();
|
||||
let old = Some((3, 3, 9));
|
||||
assert_eq!(
|
||||
plugin_goal("help:effective-pom", Some(repo), old),
|
||||
"org.apache.maven.plugins:maven-help-plugin:3.3.0:effective-pom"
|
||||
);
|
||||
assert_eq!(
|
||||
plugin_goal("dependency:build-classpath", None, old),
|
||||
"org.apache.maven.plugins:maven-dependency-plugin:3.6.1:build-classpath"
|
||||
);
|
||||
assert_eq!(pinned_plugin("maven-help-plugin", Some((3, 0, 5))), "3.2.0");
|
||||
assert_eq!(pinned_plugin("maven-dependency-plugin", Some((3, 9, 6))), "3.8.1");
|
||||
write_plugin_requiring(repo, "maven-help-plugin", "3.6.0", Some("3.9.0"));
|
||||
write_plugin_requiring(repo, "maven-help-plugin", "3.4.1", Some("3.6.3"));
|
||||
write_plugin_requiring(repo, "maven-help-plugin", "3.3.0", None);
|
||||
assert_eq!(
|
||||
plugin_goal("help:effective-pom", Some(repo), old),
|
||||
"org.apache.maven.plugins:maven-help-plugin:3.3.0:effective-pom"
|
||||
);
|
||||
assert_eq!(
|
||||
plugin_goal("help:effective-pom", Some(repo), Some((3, 9, 6))),
|
||||
"org.apache.maven.plugins:maven-help-plugin:3.6.0:effective-pom"
|
||||
);
|
||||
// An unknown Maven keeps the newest, as before.
|
||||
assert_eq!(
|
||||
plugin_goal("help:effective-pom", Some(repo), None),
|
||||
"org.apache.maven.plugins:maven-help-plugin:3.6.0:effective-pom"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maven_version_comes_from_the_wrapper_or_the_installation() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let project = tmp.path().join("project");
|
||||
std::fs::create_dir_all(project.join(".mvn/wrapper")).unwrap();
|
||||
std::fs::write(
|
||||
project.join(".mvn/wrapper/maven-wrapper.properties"),
|
||||
"distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.3.9/apache-maven-3.3.9-bin.zip\n",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(maven_version(&project.join("mvnw").to_string_lossy()), Some((3, 3, 9)));
|
||||
assert_eq!(maven_version(&project.join("mvnw.cmd").to_string_lossy()), Some((3, 3, 9)));
|
||||
|
||||
let home = tmp.path().join("apache-maven-3.9.6");
|
||||
std::fs::create_dir_all(home.join("bin")).unwrap();
|
||||
std::fs::create_dir_all(home.join("lib")).unwrap();
|
||||
std::fs::write(home.join("bin/mvn"), "").unwrap();
|
||||
std::fs::write(home.join("lib/maven-core-3.9.6.jar"), "").unwrap();
|
||||
assert_eq!(maven_version(&home.join("bin/mvn").to_string_lossy()), Some((3, 9, 6)));
|
||||
|
||||
// Homebrew: `<prefix>/bin/mvn` starts `libexec/bin/mvn`; the jars are in `libexec/lib`.
|
||||
let brew = tmp.path().join("Cellar/maven/4.0.0");
|
||||
std::fs::create_dir_all(brew.join("bin")).unwrap();
|
||||
std::fs::create_dir_all(brew.join("libexec/lib")).unwrap();
|
||||
std::fs::write(brew.join("bin/mvn"), "").unwrap();
|
||||
std::fs::write(brew.join("libexec/lib/maven-core-4.0.0-rc-5.jar"), "").unwrap();
|
||||
assert_eq!(maven_version(&brew.join("bin/mvn").to_string_lossy()), Some((4, 0, 0)));
|
||||
|
||||
assert_eq!(maven_version(&tmp.path().join("nowhere/bin/mvn").to_string_lossy()), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_plugin_lists_the_goals_its_jar_declares() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
@@ -2969,7 +2645,7 @@ mod tests {
|
||||
assert_eq!(local_repository_for(&explicit), Some(PathBuf::from("/tmp/r")));
|
||||
// No repository known: a pinned version, still by coordinates.
|
||||
assert_eq!(
|
||||
plugin_goal("dependency:build-classpath", None, None),
|
||||
plugin_goal("dependency:build-classpath", None),
|
||||
"org.apache.maven.plugins:maven-dependency-plugin:3.8.1:build-classpath"
|
||||
);
|
||||
}
|
||||
@@ -3156,55 +2832,6 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn source_encoding_comes_from_the_pom_properties_and_is_inherited() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
write(
|
||||
root,
|
||||
"pom.xml",
|
||||
r#"<project><groupId>demo</groupId><artifactId>parent</artifactId><version>1.0</version>
|
||||
<packaging>pom</packaging><modules><module>legacy</module><module>modern</module></modules>
|
||||
<properties><legacy.charset>ISO-8859-15</legacy.charset>
|
||||
<project.build.sourceEncoding>${legacy.charset}</project.build.sourceEncoding></properties>
|
||||
</project>"#,
|
||||
);
|
||||
write(
|
||||
root,
|
||||
"legacy/pom.xml",
|
||||
r#"<project><parent><groupId>demo</groupId><artifactId>parent</artifactId><version>1.0</version></parent>
|
||||
<artifactId>legacy</artifactId></project>"#,
|
||||
);
|
||||
write(
|
||||
root,
|
||||
"modern/pom.xml",
|
||||
r#"<project><parent><groupId>demo</groupId><artifactId>parent</artifactId><version>1.0</version></parent>
|
||||
<artifactId>modern</artifactId>
|
||||
<properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties></project>"#,
|
||||
);
|
||||
write(
|
||||
root,
|
||||
"plain/pom.xml",
|
||||
r#"<project><artifactId>plain</artifactId>
|
||||
<properties><project.build.sourceEncoding>${undefined.charset}</project.build.sourceEncoding></properties></project>"#,
|
||||
);
|
||||
let encodings = |root: &Path| -> Vec<(String, Option<String>)> {
|
||||
load_with_repo(root, None).projects.into_iter().map(|p| (p.dir, p.source_encoding)).collect()
|
||||
};
|
||||
assert_eq!(
|
||||
encodings(root),
|
||||
[
|
||||
(String::new(), Some("ISO-8859-15".to_owned())),
|
||||
("legacy".to_owned(), Some("ISO-8859-15".to_owned())),
|
||||
("modern".to_owned(), Some("UTF-8".to_owned())),
|
||||
]
|
||||
);
|
||||
assert_eq!(encodings(&root.join("plain")), [(String::new(), None)]);
|
||||
assert_eq!(encodings(&root.join("legacy")), [(String::new(), Some("ISO-8859-15".to_owned()))]);
|
||||
write(root, "bare/pom.xml", "<project><artifactId>bare</artifactId></project>");
|
||||
assert_eq!(encodings(&root.join("bare")), [(String::new(), None)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multi_module_parent_properties_and_managed_versions() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -8,6 +8,7 @@ use std::fs::{self, File};
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
use std::time::SystemTime;
|
||||
|
||||
const DEPENDENCY_PLUGIN: &str = "org.apache.maven.plugins:maven-dependency-plugin:3.8.1";
|
||||
const SOURCE_REFRESH_WORKERS: usize = 4;
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
@@ -43,15 +44,7 @@ impl Artifact {
|
||||
|
||||
/// Resolve only jars inside the selected local repository, including custom repositories.
|
||||
pub fn artifact(jar: &Path, repository: &Path) -> Option<Artifact> {
|
||||
let (jar, relative) = match jar.strip_prefix(repository) {
|
||||
Ok(rel) => (jar.to_path_buf(), rel.to_path_buf()),
|
||||
Err(_) => {
|
||||
let canon_repo = dunce::canonicalize(repository).ok()?;
|
||||
let canon_jar = dunce::canonicalize(jar).unwrap_or_else(|_| jar.to_path_buf());
|
||||
let rel = canon_jar.strip_prefix(&canon_repo).ok()?.to_path_buf();
|
||||
(canon_jar, rel)
|
||||
}
|
||||
};
|
||||
let relative = jar.strip_prefix(repository).ok()?;
|
||||
let parts: Vec<&str> = relative
|
||||
.components()
|
||||
.map(|c| match c {
|
||||
@@ -71,8 +64,8 @@ pub fn artifact(jar: &Path, repository: &Path) -> Option<Artifact> {
|
||||
group: parts[..n - 3].join("."),
|
||||
name: name.into(),
|
||||
version: version.into(),
|
||||
binary: jar.to_owned(),
|
||||
sources: jar.with_file_name(format!("{name}-{version}-sources.jar")),
|
||||
binary: jar,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -106,11 +99,6 @@ fn resolve(
|
||||
args.extend(profile_args.iter().cloned());
|
||||
args.push(format!("-Dmaven.repo.local={}", repository.display()));
|
||||
let coordinate = format!("-Dartifact={}:{}:{}:jar:sources", artifact.group, artifact.name, artifact.version);
|
||||
// The newest `maven-dependency-plugin` the project's Maven can load (#8114).
|
||||
let plugin = format!(
|
||||
"org.apache.maven.plugins:maven-dependency-plugin:{}",
|
||||
super::pinned_plugin("maven-dependency-plugin", super::maven_version(&project.command))
|
||||
);
|
||||
let stage = if let Some(binary) = stale {
|
||||
// Keep the existing attachment readable while Maven resolves the timestamped snapshot.
|
||||
// Disable Resolver's in-place copy to the base -SNAPSHOT filename.
|
||||
@@ -119,14 +107,14 @@ fn resolve(
|
||||
args.extend([
|
||||
"-U".into(),
|
||||
"-Daether.artifactResolver.snapshotNormalization=false".into(),
|
||||
format!("{plugin}:copy"),
|
||||
format!("{DEPENDENCY_PLUGIN}:copy"),
|
||||
coordinate,
|
||||
"-Dmdep.useBaseVersion=true".into(),
|
||||
format!("-DoutputDirectory={}", stage.path().display()),
|
||||
]);
|
||||
Some((stage, binary))
|
||||
} else {
|
||||
args.extend([format!("{plugin}:get"), coordinate, "-Dtransitive=false".into()]);
|
||||
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, |_, _| {})?;
|
||||
@@ -302,34 +290,6 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolves_canonicalized_jar_against_non_canonical_repository() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let real_repo = dir.path().join("real-repo");
|
||||
let sibling = dir.path().join("other");
|
||||
let jar = real_repo.join("org/example/demo/1.2.3/demo-1.2.3.jar");
|
||||
fs::create_dir_all(jar.parent().unwrap()).unwrap();
|
||||
fs::create_dir_all(&sibling).unwrap();
|
||||
fs::write(&jar, b"").unwrap();
|
||||
let canon_jar = dunce::canonicalize(&jar).unwrap();
|
||||
let non_canon_repo = sibling.join("..").join("real-repo");
|
||||
|
||||
let found = artifact(&canon_jar, &non_canon_repo).expect("should match via canonicalized repo fallback");
|
||||
assert_eq!(found.group, "org.example");
|
||||
assert_eq!(found.name, "demo");
|
||||
assert_eq!(found.version, "1.2.3");
|
||||
assert_eq!(found.sources, canon_jar.with_file_name("demo-1.2.3-sources.jar"));
|
||||
|
||||
#[cfg(unix)]
|
||||
{
|
||||
let link_repo = dir.path().join("m2-link");
|
||||
std::os::unix::fs::symlink(&real_repo, &link_repo).unwrap();
|
||||
let linked = artifact(&canon_jar, &link_repo).expect("should match through symlinked Maven repo");
|
||||
assert_eq!(linked.group, "org.example");
|
||||
assert_eq!(linked.sources, canon_jar.with_file_name("demo-1.2.3-sources.jar"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selects_existing_snapshot_attachments_from_the_resolved_tree() {
|
||||
use crate::maven::{MavenDependency, Omission};
|
||||
|
||||
@@ -10,7 +10,7 @@ use crate::process::{self, Output};
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult};
|
||||
use serde::{Deserialize, Serialize, de::DeserializeOwned};
|
||||
use specta::Type;
|
||||
use std::collections::{BTreeMap, BTreeSet, HashMap};
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Arc, LazyLock, Mutex};
|
||||
use std::time::SystemTime;
|
||||
@@ -32,8 +32,6 @@ pub struct SyncOptions {
|
||||
pub profiles: Vec<String>,
|
||||
/// Extra environment (`JAVA_HOME`).
|
||||
pub env: BTreeMap<String, String>,
|
||||
/// Major version of the JDK Maven runs on, the same as the model is loaded with.
|
||||
pub jdk_version: Option<u32>,
|
||||
/// Maven launcher replacing the project's `mvnw` / `mvn` (Settings › Maven home).
|
||||
pub maven_command: Option<String>,
|
||||
/// Resolved Gradle launcher from Settings.
|
||||
@@ -64,9 +62,6 @@ struct MavenCache {
|
||||
/// The trees list omitted occurrences (`-Dverbose`); older caches are reloaded.
|
||||
#[serde(default)]
|
||||
verbose: bool,
|
||||
/// [`MavenModel::jdk_activations`] of the sync; `None` in caches from before they were recorded.
|
||||
#[serde(default)]
|
||||
jdk_activations: Option<BTreeSet<String>>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
|
||||
@@ -89,39 +84,34 @@ const MODEL_INIT_SCRIPT: &str = include_str!("gradle-model.gradle");
|
||||
const MAVEN_CACHE: &str = "maven.json";
|
||||
const MAVEN_CACHE_VERSION: u32 = 1;
|
||||
|
||||
/// `dependency:tree` of a plugin version whose `-Dverbose` lists the occurrences Maven
|
||||
/// omitted (conflicts, duplicates): verbose output was dropped in 3.0 and is back since 3.2.
|
||||
/// Offline, it is used only when an earlier sync downloaded it; otherwise the newest version
|
||||
/// in the local repository is.
|
||||
const DEPENDENCY_TREE: &str = "org.apache.maven.plugins:maven-dependency-plugin:3.8.1:tree";
|
||||
const DEPENDENCY_TREE_JAR: &str =
|
||||
"org/apache/maven/plugins/maven-dependency-plugin/3.8.1/maven-dependency-plugin-3.8.1.jar";
|
||||
|
||||
/// The goals that read the effective POM into `effective` and the verbose dependency trees;
|
||||
/// `repo` is the local repository the build resolves from and `maven` the version of the Maven
|
||||
/// that runs them, when known. Both goals name their plugin by coordinates: offline, a prefix
|
||||
/// resolves only from group metadata the repository may lack. The tree uses a pinned
|
||||
/// `maven-dependency-plugin` whose `-Dverbose` lists the occurrences Maven omitted (conflicts,
|
||||
/// duplicates; dropped in 3.0, back since 3.2), the newest that `maven` can load; offline it is
|
||||
/// used only when an earlier sync downloaded it, otherwise the newest compatible version in the
|
||||
/// local repository is. Offline without a cached compatible 3.x `maven-help-plugin`,
|
||||
/// `effective-pom` is skipped so `mvn -o` still resolves the dependency tree instead of failing
|
||||
/// to download the help plugin.
|
||||
fn maven_sync_goals(
|
||||
effective: &Path,
|
||||
offline: bool,
|
||||
repo: Option<&Path>,
|
||||
maven: Option<maven::MavenVersion>,
|
||||
) -> Vec<String> {
|
||||
let version = maven::pinned_plugin("maven-dependency-plugin", maven);
|
||||
let jar =
|
||||
format!("org/apache/maven/plugins/maven-dependency-plugin/{version}/maven-dependency-plugin-{version}.jar");
|
||||
let pinned = !offline || repo.is_some_and(|repo| repo.join(jar).is_file());
|
||||
/// `repo` is the local repository the build resolves from. Both goals name their plugin by
|
||||
/// coordinates: offline, a prefix resolves only from group metadata the repository may lack.
|
||||
/// Offline without a cached 3.x `maven-help-plugin`, `effective-pom` is skipped so `mvn -o`
|
||||
/// still resolves the dependency tree instead of failing to download the help plugin.
|
||||
fn maven_sync_goals(effective: &Path, offline: bool, repo: Option<&Path>) -> Vec<String> {
|
||||
let pinned = !offline || repo.is_some_and(|repo| repo.join(DEPENDENCY_TREE_JAR).is_file());
|
||||
let tree = if pinned {
|
||||
format!("org.apache.maven.plugins:maven-dependency-plugin:{version}:tree")
|
||||
DEPENDENCY_TREE.to_owned()
|
||||
} else {
|
||||
repo.and_then(|repo| maven::newest_local_plugin(repo, "maven-dependency-plugin", 2, maven)).map_or_else(
|
||||
repo.and_then(|repo| maven::newest_local_plugin(repo, "maven-dependency-plugin", 2)).map_or_else(
|
||||
|| "dependency:tree".to_owned(),
|
||||
|v| format!("org.apache.maven.plugins:maven-dependency-plugin:{v}:tree"),
|
||||
)
|
||||
};
|
||||
let has_help =
|
||||
!offline || repo.is_some_and(|repo| maven::newest_local_plugin(repo, "maven-help-plugin", 3, maven).is_some());
|
||||
!offline || repo.is_some_and(|repo| maven::newest_local_plugin(repo, "maven-help-plugin", 3).is_some());
|
||||
let mut goals = Vec::with_capacity(4);
|
||||
if has_help {
|
||||
goals.push(maven::plugin_goal("help:effective-pom", repo, maven));
|
||||
goals.push(maven::plugin_goal("help:effective-pom", repo));
|
||||
goals.push(format!("-Doutput={}", effective.to_string_lossy()));
|
||||
}
|
||||
goals.push(tree);
|
||||
@@ -243,9 +233,7 @@ pub fn apply_maven_cache(root: &Path, cache_dir: &Path, model: &mut MavenModel)
|
||||
}
|
||||
model.synced_at = Some(cache.at_ms);
|
||||
model.sync_error = cache.error;
|
||||
// Another JDK can switch profiles of the same build files.
|
||||
let changed = cache.hash != hash_files(&maven::build_files(root, model))
|
||||
|| cache.jdk_activations.is_some_and(|jdks| jdks != model.jdk_activations);
|
||||
let changed = cache.hash != hash_files(&maven::build_files(root, model));
|
||||
model.stale = !cache.verbose || changed;
|
||||
// A cache older than the current build files: its effective-POM plugins and
|
||||
// resolved dependencies would hide what the POMs declare now (a just added
|
||||
@@ -380,11 +368,10 @@ pub fn sync_maven(
|
||||
cancel: &CancellationToken,
|
||||
progress: &dyn Fn(SyncProgress),
|
||||
) -> IdeResult<()> {
|
||||
let mut model = maven::load_with_linked_jdk(
|
||||
let mut model = maven::load_with_linked(
|
||||
root,
|
||||
maven::default_local_repo(),
|
||||
&options.maven_settings.profiles(&options.profiles),
|
||||
options.jdk_version,
|
||||
&options.maven_settings.linked_projects,
|
||||
);
|
||||
maven::UnlinkedProjects::from_model(&model, &options.maven_settings).filter(&mut model);
|
||||
@@ -393,7 +380,6 @@ pub fn sync_maven(
|
||||
version: MAVEN_CACHE_VERSION,
|
||||
hash: hash_files(&maven::build_files(root, &model)),
|
||||
verbose: true,
|
||||
jdk_activations: Some(model.jdk_activations.clone()),
|
||||
..MavenCache::default()
|
||||
};
|
||||
// Where the build resolves its jars, and therefore where the plugin goals are read from.
|
||||
@@ -419,9 +405,9 @@ pub fn sync_maven(
|
||||
if !options.profiles.is_empty() {
|
||||
args.push(format!("-P{}", options.profiles.join(",")));
|
||||
}
|
||||
let command = options.maven_command.as_deref().unwrap_or(&top.command);
|
||||
args.extend(maven_sync_goals(&effective, options.offline, repo.as_deref(), maven::maven_version(command)));
|
||||
args.extend(maven_sync_goals(&effective, options.offline, repo.as_deref()));
|
||||
progress(SyncProgress { message: format!("Reading {}", top.display_name), fraction: None });
|
||||
let command = options.maven_command.as_deref().unwrap_or(&top.command);
|
||||
let out = run(command, &args, &root.join(&top.dir), &options.env, cancel, |line| {
|
||||
if let Some((name, i, total)) = maven_building(line) {
|
||||
let fraction = (i.saturating_sub(1) as f32 / total.max(1) as f32).min(1.0);
|
||||
@@ -697,7 +683,6 @@ mod tests {
|
||||
at_ms: 5.0,
|
||||
error: None,
|
||||
verbose: true,
|
||||
jdk_activations: None,
|
||||
projects: vec![CachedMavenProject {
|
||||
key: "g:a".into(),
|
||||
plugins: vec![maven::plugin(
|
||||
@@ -748,7 +733,6 @@ mod tests {
|
||||
at_ms: 5.0,
|
||||
error: None,
|
||||
verbose: true,
|
||||
jdk_activations: None,
|
||||
projects: vec![CachedMavenProject {
|
||||
key: "g:a".into(),
|
||||
plugins: vec![maven::plugin(
|
||||
@@ -964,19 +948,15 @@ mod tests {
|
||||
assert!(!save_maven_offline(&tmp.path().join("other"), false).unwrap(), "online is the default");
|
||||
}
|
||||
|
||||
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";
|
||||
|
||||
#[test]
|
||||
fn sync_reads_verbose_trees_with_a_pinned_plugin_unless_offline_without_it() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let help = "org.apache.maven.plugins:maven-help-plugin:3.5.1:effective-pom";
|
||||
let online = maven_sync_goals(Path::new("e.xml"), false, Some(tmp.path()), None);
|
||||
let online = maven_sync_goals(Path::new("e.xml"), false, Some(tmp.path()));
|
||||
assert_eq!(online, [help, "-Doutput=e.xml", DEPENDENCY_TREE, "-Dverbose"]);
|
||||
// Offline with neither plugin cached: `effective-pom` is skipped so `mvn -o` does not fail
|
||||
// on an uncached `maven-help-plugin`, and the tree falls back to the project's own version.
|
||||
let offline = maven_sync_goals(Path::new("e.xml"), true, Some(tmp.path()), None);
|
||||
let offline = maven_sync_goals(Path::new("e.xml"), true, Some(tmp.path()));
|
||||
assert_eq!(offline, ["dependency:tree", "-Dverbose"]);
|
||||
// #5757 / #5844: offline, plugins in the local repository are named by their coordinates,
|
||||
// since the prefix needs group metadata a repository filled from a private mirror may lack;
|
||||
@@ -987,37 +967,21 @@ mod tests {
|
||||
std::fs::create_dir_all(jar.parent().unwrap()).unwrap();
|
||||
std::fs::write(&jar, "").unwrap();
|
||||
}
|
||||
let offline = maven_sync_goals(Path::new("e.xml"), true, Some(tmp.path()), None);
|
||||
let offline = maven_sync_goals(Path::new("e.xml"), true, Some(tmp.path()));
|
||||
assert_eq!(offline, ["org.apache.maven.plugins:maven-dependency-plugin:3.6.1:tree", "-Dverbose"]);
|
||||
let help_jar = tmp.path().join("org/apache/maven/plugins/maven-help-plugin/3.4.0/maven-help-plugin-3.4.0.jar");
|
||||
std::fs::create_dir_all(help_jar.parent().unwrap()).unwrap();
|
||||
std::fs::write(&help_jar, "").unwrap();
|
||||
// A version folder without its jar (only the POM was fetched) doesn't count.
|
||||
std::fs::create_dir_all(tmp.path().join("org/apache/maven/plugins/maven-help-plugin/3.10.0")).unwrap();
|
||||
let offline = maven_sync_goals(Path::new("e.xml"), true, Some(tmp.path()), None);
|
||||
let offline = maven_sync_goals(Path::new("e.xml"), true, Some(tmp.path()));
|
||||
assert_eq!(offline[0], "org.apache.maven.plugins:maven-help-plugin:3.4.0:effective-pom");
|
||||
assert_eq!(offline[2], "org.apache.maven.plugins:maven-dependency-plugin:3.6.1:tree");
|
||||
// Downloaded by an online sync: offline keeps using it, the project's version may be missing.
|
||||
let jar = tmp.path().join(DEPENDENCY_TREE_JAR);
|
||||
std::fs::create_dir_all(jar.parent().unwrap()).unwrap();
|
||||
std::fs::write(&jar, "").unwrap();
|
||||
assert_eq!(maven_sync_goals(Path::new("e.xml"), true, Some(tmp.path()), None)[2], DEPENDENCY_TREE);
|
||||
}
|
||||
|
||||
/// #8114: an old Maven gets plugin versions it can load, also for the verbose tree.
|
||||
#[test]
|
||||
fn sync_goals_follow_the_maven_version() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let goals = maven_sync_goals(Path::new("e.xml"), false, Some(tmp.path()), Some((3, 3, 9)));
|
||||
assert_eq!(
|
||||
goals,
|
||||
[
|
||||
"org.apache.maven.plugins:maven-help-plugin:3.3.0:effective-pom",
|
||||
"-Doutput=e.xml",
|
||||
"org.apache.maven.plugins:maven-dependency-plugin:3.6.1:tree",
|
||||
"-Dverbose",
|
||||
]
|
||||
);
|
||||
assert_eq!(maven_sync_goals(Path::new("e.xml"), true, Some(tmp.path()))[2], DEPENDENCY_TREE);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1091,95 +1055,6 @@ mod tests {
|
||||
assert_eq!(std::fs::metadata(&mvnw).unwrap().permissions().mode() & 0o777, 0o644);
|
||||
}
|
||||
|
||||
/// `root` with module `core`, and what `profile` adds when the JDK activates it: the module
|
||||
/// `modern` or only a property. Synced with `jdk` by a launcher printing `core`'s tree.
|
||||
#[cfg(unix)]
|
||||
fn synced_with_a_jdk_profile(base: &Path, profile: &str, jdk: Option<u32>) -> (PathBuf, PathBuf) {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let (root, cache) = (base.join("p"), base.join("cache"));
|
||||
let project = "<project><groupId>g</groupId><version>1</version>";
|
||||
for module in ["core", "modern"] {
|
||||
std::fs::create_dir_all(root.join(module)).unwrap();
|
||||
let pom = format!("{project}<artifactId>{module}</artifactId></project>");
|
||||
std::fs::write(root.join(module).join("pom.xml"), pom).unwrap();
|
||||
}
|
||||
let pom = format!(
|
||||
"{project}<artifactId>root</artifactId><packaging>pom</packaging><modules><module>core</module></modules>\
|
||||
<profiles><profile><id>modern</id><activation><jdk>[11,)</jdk></activation>{profile}</profile></profiles>\
|
||||
</project>"
|
||||
);
|
||||
std::fs::write(root.join("pom.xml"), pom).unwrap();
|
||||
let launcher = base.join("mvn");
|
||||
let tree = "[INFO] --- dependency:3.8.1:tree (default-cli) @ core ---\\n[INFO] g:core:jar:1\\n\
|
||||
[INFO] \\\\- g:lib:jar:1:compile\\n[INFO] \\\\- g:transitive:jar:1:compile\\n";
|
||||
std::fs::write(&launcher, format!("#!/bin/sh\nprintf '{tree}'\n")).unwrap();
|
||||
std::fs::set_permissions(&launcher, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
let options = SyncOptions {
|
||||
maven_command: Some(launcher.to_string_lossy().into_owned()),
|
||||
jdk_version: jdk,
|
||||
..Default::default()
|
||||
};
|
||||
sync_maven(&root, &cache, &options, &CancellationToken::new(), &|_| {}).unwrap();
|
||||
(root, cache)
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn loaded_with_jdk((root, cache): &(PathBuf, PathBuf), jdk: Option<u32>) -> MavenModel {
|
||||
crate::load_linked_with_jdk(root, cache, None, &Default::default(), &Default::default(), jdk).maven.unwrap()
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
const MODULE: &str = "<modules><module>modern</module></modules>";
|
||||
#[cfg(unix)]
|
||||
const PROPERTY: &str = "<properties><x>1</x></properties>";
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_synced_model_with_a_jdk_profile_is_current() {
|
||||
for (profile, jdk, modules) in
|
||||
[(MODULE, Some(17), 3), (MODULE, Some(8), 2), (MODULE, None, 2), (PROPERTY, Some(17), 2)]
|
||||
{
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let model = loaded_with_jdk(&synced_with_a_jdk_profile(tmp.path(), profile, jdk), jdk);
|
||||
assert_eq!(model.projects.len(), modules, "{profile} {jdk:?}");
|
||||
assert!(!model.stale, "{profile} {jdk:?}");
|
||||
let core = model.projects.iter().find(|p| p.artifact_id == "core").unwrap();
|
||||
assert_eq!(core.dependencies[0].children[0].artifact_id, "transitive", "{profile} {jdk:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_jdk_change_is_stale_when_it_switches_a_profile() {
|
||||
for profile in [MODULE, PROPERTY] {
|
||||
for (synced, loaded, stale) in [
|
||||
(Some(17), Some(21), false),
|
||||
(Some(17), Some(8), true),
|
||||
(Some(8), Some(17), true),
|
||||
(Some(17), None, true),
|
||||
(None, Some(17), true),
|
||||
(None, Some(8), false),
|
||||
] {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let model = loaded_with_jdk(&synced_with_a_jdk_profile(tmp.path(), profile, synced), loaded);
|
||||
assert_eq!(model.stale, stale, "{profile} {synced:?} {loaded:?}");
|
||||
let core = model.projects.iter().find(|p| p.artifact_id == "core").unwrap();
|
||||
assert_eq!(core.dependencies.is_empty(), stale, "{profile} {synced:?} {loaded:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_sync_from_before_jdk_profiles_were_recorded_stays_current() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let project = synced_with_a_jdk_profile(tmp.path(), PROPERTY, Some(17));
|
||||
let mut json: serde_json::Value = read_cache(&project.1, MAVEN_CACHE).unwrap();
|
||||
assert!(json.as_object_mut().unwrap().remove("jdk_activations").is_some());
|
||||
write_cache(&project.1, MAVEN_CACHE, &json).unwrap();
|
||||
assert!(!loaded_with_jdk(&project, Some(17)).stale);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn maven_sync_runs_the_daemon_command_serially() {
|
||||
|
||||
@@ -110,26 +110,35 @@ pub fn build(root: &Path, model: &BuildModel, id: &str, cache: &Path) -> IdeResu
|
||||
}
|
||||
fs::write(cache.join("artifact-id.txt"), id)?;
|
||||
if let Some(pom) = id.strip_prefix("maven:") {
|
||||
let maven = model.maven.as_ref().ok_or_else(|| IdeError::invalid("Choose a Maven WAR module"))?;
|
||||
let p = maven
|
||||
.projects
|
||||
.iter()
|
||||
.find(|p| p.pom == pom && p.packaging == "war")
|
||||
let p = model
|
||||
.maven
|
||||
.as_ref()
|
||||
.and_then(|m| m.projects.iter().find(|p| p.pom == pom && p.packaging == "war"))
|
||||
.ok_or_else(|| IdeError::invalid("Choose a Maven WAR module"))?;
|
||||
let top = crate::maven::reactor_for_pom(maven, &p.pom).unwrap_or(p);
|
||||
let projects = &model.maven.as_ref().unwrap().projects;
|
||||
let top = projects
|
||||
.iter()
|
||||
.filter(|t| {
|
||||
!t.aggregated && (t.dir.is_empty() || p.dir == t.dir || p.dir.starts_with(&format!("{}/", t.dir)))
|
||||
})
|
||||
.max_by_key(|t| t.dir.len())
|
||||
.unwrap_or(p);
|
||||
let mut args = top.options.clone();
|
||||
if let Some(module) = crate::maven::module_selector(root, top, p) {
|
||||
if top.pom != p.pom {
|
||||
let module = root
|
||||
.join(&p.dir)
|
||||
.strip_prefix(root.join(&top.dir))
|
||||
.map_err(|e| IdeError::invalid(e.to_string()))?
|
||||
.to_string_lossy()
|
||||
.replace('\\', "/");
|
||||
args.extend(["-pl".into(), module, "-am".into()]);
|
||||
}
|
||||
// help:evaluate runs once, in the reactor's first project. Query the selected
|
||||
// POM's effective identity first; profiles and -D options can change its GAV.
|
||||
let output = cache.join("artifact-project.txt");
|
||||
let mut probe = top.options.clone();
|
||||
let evaluate = crate::maven::plugin_goal(
|
||||
"help:evaluate",
|
||||
crate::maven::local_repository_for(&top.options).as_deref(),
|
||||
crate::maven::maven_version(&top.command),
|
||||
);
|
||||
let evaluate =
|
||||
crate::maven::plugin_goal("help:evaluate", crate::maven::local_repository_for(&top.options).as_deref());
|
||||
probe.extend([
|
||||
"-f".into(),
|
||||
root.join(&p.pom).to_string_lossy().into_owned(),
|
||||
@@ -307,90 +316,4 @@ mod tests {
|
||||
assert!(!action.contains("p.") && !action.contains("war."), "{action}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maven_sibling_reactor_builds_war_through_aggregator_with_relative_pl() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
for dir in ["parent", "common", "app"] {
|
||||
fs::create_dir_all(root.join(dir)).unwrap();
|
||||
}
|
||||
fs::write(
|
||||
root.join("parent/pom.xml"),
|
||||
"<project><modelVersion>4.0.0</modelVersion><groupId>test</groupId><artifactId>parent</artifactId><version>1</version><packaging>pom</packaging><modules><module>../common</module><module>../app</module></modules></project>",
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(
|
||||
root.join("common/pom.xml"),
|
||||
"<project><modelVersion>4.0.0</modelVersion><parent><groupId>test</groupId><artifactId>parent</artifactId><version>1</version><relativePath>../parent/pom.xml</relativePath></parent><artifactId>common</artifactId></project>",
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(
|
||||
root.join("app/pom.xml"),
|
||||
"<project><modelVersion>4.0.0</modelVersion><parent><groupId>test</groupId><artifactId>parent</artifactId><version>1</version><relativePath>../parent/pom.xml</relativePath></parent><artifactId>app</artifactId><packaging>war</packaging><dependencies><dependency><groupId>test</groupId><artifactId>common</artifactId><version>1</version></dependency></dependencies></project>",
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let model = crate::load(root, &root.join("cache"), None);
|
||||
let a = artifacts(root, &model);
|
||||
assert_eq!(a.len(), 1);
|
||||
assert_eq!(a[0].id, "maven:app/pom.xml");
|
||||
|
||||
let plan = build(root, &model, &a[0].id, &root.join("base")).unwrap();
|
||||
assert_eq!(plan.cwd, "parent");
|
||||
assert_eq!(&plan.args[..3], &["-pl", "../app", "-am"]);
|
||||
let (probe, _) = plan.maven_project.as_ref().unwrap();
|
||||
assert!(probe.contains(&root.join("app/pom.xml").to_string_lossy().into_owned()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maven_subfolder_aggregator_builds_root_war_with_parent_pl() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
for dir in ["parent", "common"] {
|
||||
fs::create_dir_all(root.join(dir)).unwrap();
|
||||
}
|
||||
fs::write(
|
||||
root.join("pom.xml"),
|
||||
"<project><modelVersion>4.0.0</modelVersion><parent><groupId>test</groupId><artifactId>parent</artifactId><version>1</version><relativePath>parent/pom.xml</relativePath></parent><artifactId>app</artifactId><packaging>war</packaging></project>",
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(
|
||||
root.join("parent/pom.xml"),
|
||||
"<project><modelVersion>4.0.0</modelVersion><groupId>test</groupId><artifactId>parent</artifactId><version>1</version><packaging>pom</packaging><modules><module>../</module><module>../common</module></modules></project>",
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(
|
||||
root.join("common/pom.xml"),
|
||||
"<project><modelVersion>4.0.0</modelVersion><parent><groupId>test</groupId><artifactId>parent</artifactId><version>1</version><relativePath>../parent/pom.xml</relativePath></parent><artifactId>common</artifactId></project>",
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let settings =
|
||||
ide_core::settings::MavenSettings { linked_projects: vec!["parent/pom.xml".into()], ..Default::default() };
|
||||
let model = crate::load_linked(root, &root.join("cache"), None, &settings, &Default::default());
|
||||
let plan = build(root, &model, "maven:pom.xml", &root.join("base")).unwrap();
|
||||
assert_eq!(plan.cwd, "parent");
|
||||
assert_eq!(&plan.args[..3], &["-pl", "..", "-am"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maven_independent_sibling_wars_keep_own_reactor() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
for dir in ["a", "b"] {
|
||||
fs::create_dir_all(root.join(dir)).unwrap();
|
||||
fs::write(
|
||||
root.join(dir).join("pom.xml"),
|
||||
format!("<project><modelVersion>4.0.0</modelVersion><groupId>test</groupId><artifactId>{dir}</artifactId><version>1</version><packaging>war</packaging></project>"),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
let model = crate::load(root, &root.join("cache"), None);
|
||||
for dir in ["a", "b"] {
|
||||
let plan = build(root, &model, &format!("maven:{dir}/pom.xml"), &root.join("base")).unwrap();
|
||||
assert_eq!(plan.cwd, dir);
|
||||
assert!(!plan.args.contains(&"-pl".into()));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -16,7 +16,7 @@ objc2-app-kit = { version = "0.3", default-features = false, features = ["std",
|
||||
png = "0.18"
|
||||
|
||||
[target.'cfg(target_os = "linux")'.dependencies]
|
||||
gtk = "0.19"
|
||||
gtk = "0.18"
|
||||
|
||||
[dev-dependencies]
|
||||
png = "0.18"
|
||||
@@ -27,4 +27,4 @@ libc = "0.2"
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
dirs.workspace = true
|
||||
tracing.workspace = true
|
||||
windows-sys = { version = "0.61", features = ["Wdk_System_SystemServices", "Win32_Foundation", "Win32_Globalization", "Win32_Security", "Win32_System_Console", "Win32_System_Diagnostics_ToolHelp", "Win32_System_Environment", "Win32_System_IO", "Win32_System_JobObjects", "Win32_System_LibraryLoader", "Win32_System_Registry", "Win32_Storage_FileSystem", "Win32_System_SystemInformation", "Win32_System_Threading"] }
|
||||
windows-sys = { version = "0.61", features = ["Wdk_System_SystemServices", "Win32_Foundation", "Win32_Globalization", "Win32_Security", "Win32_System_Console", "Win32_System_Diagnostics_ToolHelp", "Win32_System_IO", "Win32_System_JobObjects", "Win32_System_LibraryLoader", "Win32_System_Registry", "Win32_Storage_FileSystem", "Win32_System_SystemInformation", "Win32_System_Threading"] }
|
||||
@@ -175,7 +175,7 @@ impl CliTool {
|
||||
Poll::Finished => break,
|
||||
}
|
||||
}
|
||||
Ok((lines.finish(cancel)?.success(), stderr_tail))
|
||||
Ok((lines.finish(cancel)?, stderr_tail))
|
||||
}
|
||||
|
||||
/// Starts `cmd` with a reader thread per pipe, for a caller that drives the loop itself
|
||||
@@ -301,9 +301,9 @@ impl Lines {
|
||||
}
|
||||
}
|
||||
|
||||
/// Waits for the child to exit and returns how it exited. Fails, after killing it, when
|
||||
/// `cancel` fires first.
|
||||
pub fn finish(mut self, cancel: &CancellationToken) -> IdeResult<std::process::ExitStatus> {
|
||||
/// 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;
|
||||
@@ -314,6 +314,6 @@ impl Lines {
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
};
|
||||
Ok(status)
|
||||
Ok(status.success())
|
||||
}
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
//! The CMake File API queries the IDE writes into a build directory, shared by the run
|
||||
//! configurations (which read the replies) and Build Project (which configures).
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
/// The objects asked for: targets, cache, toolchains and the CMake files.
|
||||
pub const QUERIES: [&str; 4] = ["codemodel-v2", "cache-v2", "toolchains-v1", "cmakeFiles-v1"];
|
||||
const QUERY: &str = ".cmake/api/v1/query/client-openidea";
|
||||
/// Where CMake writes its replies, relative to the build directory.
|
||||
pub const REPLY: &str = ".cmake/api/v1/reply";
|
||||
|
||||
/// Asks CMake to answer [`QUERIES`] on the next configure of `build`.
|
||||
pub fn write_queries(build: &Path) -> std::io::Result<()> {
|
||||
let query = build.join(QUERY);
|
||||
std::fs::create_dir_all(&query)?;
|
||||
for name in QUERIES {
|
||||
std::fs::write(query.join(name), "")?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -86,8 +86,6 @@ pub struct EditorAppearanceSettings {
|
||||
pub indent_guides: bool,
|
||||
/// Colour indent guides by depth (`--syn-rainbow-*`), while `indent_guides` is on.
|
||||
pub rainbow_indent_guides: bool,
|
||||
/// Also tint each indent level's whitespace in its rainbow colour, while `rainbow_indent_guides` is on.
|
||||
pub rainbow_indent_guides_fill: bool,
|
||||
/// Right margin and visual guides from Code Style.
|
||||
pub hard_wrap_guides: bool,
|
||||
pub intention_bulb: bool,
|
||||
@@ -116,7 +114,6 @@ impl Default for EditorAppearanceSettings {
|
||||
whitespace_trailing: true,
|
||||
indent_guides: true,
|
||||
rainbow_indent_guides: false,
|
||||
rainbow_indent_guides_fill: false,
|
||||
hard_wrap_guides: true,
|
||||
intention_bulb: true,
|
||||
render_doc_comments: false,
|
||||
@@ -380,8 +377,6 @@ pub struct CodeEditingSettings {
|
||||
pub quick_doc_delay: u32,
|
||||
/// Next / previous error goes to errors only (skips warnings).
|
||||
pub next_error_errors_only: bool,
|
||||
/// Show the diagnostic producer and rule code beneath each message in editor hover tooltips.
|
||||
pub show_diagnostic_source_on_hover: bool,
|
||||
pub sticky_lines_max: u32,
|
||||
pub sticky_lines_disabled_languages: Vec<String>,
|
||||
}
|
||||
@@ -395,7 +390,6 @@ impl Default for CodeEditingSettings {
|
||||
quick_doc_on_hover: true,
|
||||
quick_doc_delay: 500,
|
||||
next_error_errors_only: true,
|
||||
show_diagnostic_source_on_hover: true,
|
||||
sticky_lines_max: 5,
|
||||
sticky_lines_disabled_languages: Vec::new(),
|
||||
}
|
||||
@@ -407,8 +401,6 @@ impl Default for CodeEditingSettings {
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct InlayHintsSettings {
|
||||
pub types: bool,
|
||||
/// Inferred variable and field types from the JavaScript and TypeScript servers (on, as in WebStorm).
|
||||
pub js_ts_types: bool,
|
||||
pub parameters: bool,
|
||||
/// Hints of other kinds (chaining, closing labels…).
|
||||
pub other: bool,
|
||||
@@ -444,7 +436,6 @@ impl Default for InlayHintsSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
types: true,
|
||||
js_ts_types: true,
|
||||
parameters: true,
|
||||
other: true,
|
||||
closing_labels: true,
|
||||
@@ -719,19 +710,6 @@ mod folding_tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod inlay_hints_tests {
|
||||
use super::InlayHintsSettings;
|
||||
|
||||
#[test]
|
||||
fn existing_settings_enable_js_ts_type_hints_by_default() {
|
||||
let settings: InlayHintsSettings = serde_json::from_str(r#"{"parameters":false}"#).unwrap();
|
||||
assert!(settings.types);
|
||||
assert!(settings.js_ts_types);
|
||||
assert!(!settings.parameters);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod sticky_lines_tests {
|
||||
use super::CodeEditingSettings;
|
||||
@@ -747,15 +725,4 @@ mod sticky_lines_tests {
|
||||
assert_eq!(saved.sticky_lines_disabled_languages, ["markdown", "rust"]);
|
||||
assert_eq!(serde_json::to_value(saved).unwrap()["stickyLinesDisabledLanguages"], json);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn diagnostic_source_on_hover_defaults_to_true_and_round_trips() {
|
||||
let legacy: CodeEditingSettings = serde_json::from_value(serde_json::json!({"quickDocOnHover": true})).unwrap();
|
||||
assert!(legacy.show_diagnostic_source_on_hover);
|
||||
let hidden: CodeEditingSettings =
|
||||
serde_json::from_value(serde_json::json!({"showDiagnosticSourceOnHover": false})).unwrap();
|
||||
assert!(!hidden.show_diagnostic_source_on_hover);
|
||||
let serialized = serde_json::to_value(&hidden).unwrap();
|
||||
assert_eq!(serialized["showDiagnosticSourceOnHover"], false);
|
||||
}
|
||||
}
|
||||
@@ -11,14 +11,6 @@ use specta::Type;
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// The execution target recorded with an MCP agent run.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(tag = "kind", rename_all = "camelCase")]
|
||||
pub enum McpAgentRunTarget {
|
||||
Host,
|
||||
Container { id: String },
|
||||
}
|
||||
|
||||
/// What a built-in MCP tool asks the project window for. `AgentRun` runs `command` (a shell
|
||||
/// line) in the Run tool window's agent tab `name`, on pipes, answered once the process
|
||||
/// started or failed to. `RunConfiguration` starts a run configuration (a serialized
|
||||
@@ -35,10 +27,6 @@ pub enum McpUiRequest {
|
||||
subject: String,
|
||||
project: String,
|
||||
detail: Option<String>,
|
||||
/// The project is served without a window: the request shows in another project's window,
|
||||
/// which names it and keeps the keyboard focus where it is.
|
||||
#[serde(default)]
|
||||
background: bool,
|
||||
},
|
||||
OpenFile {
|
||||
path: crate::IpcPath,
|
||||
@@ -50,7 +38,6 @@ pub enum McpUiRequest {
|
||||
command: String,
|
||||
cwd: crate::IpcPath,
|
||||
env: BTreeMap<String, String>,
|
||||
target: McpAgentRunTarget,
|
||||
},
|
||||
RunConfiguration {
|
||||
#[specta(type = specta_typescript::Unknown)]
|
||||
@@ -108,8 +95,6 @@ pub enum IdeEvent {
|
||||
WindowGroupsChanged,
|
||||
/// A project was loaded or unloaded for the MCP server without a window of its own.
|
||||
McpBackgroundProjectsChanged,
|
||||
/// Agent automations, run history, or session schedules changed on the host.
|
||||
AutomationsChanged,
|
||||
/// A window entered or left full screen, itself or as a member of a full-screen window group.
|
||||
WindowFullscreenChanged,
|
||||
/// This remote window's connection ended or another window took over the session.
|
||||
@@ -117,14 +102,6 @@ pub enum IdeEvent {
|
||||
host: String,
|
||||
#[serde(default)]
|
||||
taken_over: bool,
|
||||
/// Plain-language explanation when a dev container exited from the OOM killer (`OOMKilled` / exit 137).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
oom_message: Option<String>,
|
||||
/// Local configuration file (`devcontainer.json` or Compose file) that sets the container's limit.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
oom_config_path: Option<String>,
|
||||
},
|
||||
ProjectTrustChanged {
|
||||
root: crate::IpcPath,
|
||||
@@ -328,18 +305,6 @@ pub enum IdeEvent {
|
||||
AskpassDone {
|
||||
id: u64,
|
||||
},
|
||||
/// An external `/api/file` request asks the target project window to confirm opening a file;
|
||||
/// answered with `web_file_api_confirm`.
|
||||
FileApiConfirm {
|
||||
id: u64,
|
||||
source: String,
|
||||
path: crate::IpcPath,
|
||||
line: Option<u32>,
|
||||
},
|
||||
/// File-open confirmation prompt `id` was answered or cancelled.
|
||||
FileApiConfirmDone {
|
||||
id: u64,
|
||||
},
|
||||
/// The kernel of an open notebook changed state (`starting`, `idle`, `busy`,
|
||||
/// `dead`); `message` says why it failed to start or died.
|
||||
NotebookKernel {
|
||||
@@ -459,8 +424,6 @@ pub enum LspRefreshKind {
|
||||
Inheritance,
|
||||
/// The Dart server published a document's Flutter outline.
|
||||
FlutterOutline,
|
||||
/// Spring bean markers of open documents may have changed.
|
||||
SpringBeanMarkers,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
|
||||
@@ -81,61 +81,9 @@ pub fn strip(src: &str) -> String {
|
||||
cleaned
|
||||
}
|
||||
|
||||
/// Comments and a leading byte order mark turned into spaces, byte for byte, so that offsets
|
||||
/// into the result are offsets into `src`. Line breaks stay, and so do trailing commas.
|
||||
pub fn blank_comments(src: &str) -> String {
|
||||
let mut out = src.as_bytes().to_vec();
|
||||
let blank = |out: &mut [u8]| out.iter_mut().filter(|b| !matches!(b, b'\n' | b'\r')).for_each(|b| *b = b' ');
|
||||
let mut i = 0;
|
||||
if src.starts_with('\u{feff}') {
|
||||
i = '\u{feff}'.len_utf8();
|
||||
blank(&mut out[..i]);
|
||||
}
|
||||
let mut in_str = false;
|
||||
while i < src.len() {
|
||||
let rest = &src.as_bytes()[i..];
|
||||
let comment = match rest {
|
||||
[b'\\', ..] if in_str => {
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
[b'"', ..] => {
|
||||
in_str = !in_str;
|
||||
None
|
||||
}
|
||||
[b'/', b'/', ..] if !in_str => Some(rest.iter().position(|&b| b == b'\n').unwrap_or(rest.len())),
|
||||
// An unterminated block comment runs to the end, leaving a document that still parses
|
||||
// only if it was complete before it.
|
||||
[b'/', b'*', ..] if !in_str => {
|
||||
Some(rest[2..].windows(2).position(|w| w == b"*/").map_or(rest.len(), |end| end + 4))
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
match comment {
|
||||
Some(len) => {
|
||||
blank(&mut out[i..i + len]);
|
||||
i += len;
|
||||
}
|
||||
None => i += 1,
|
||||
}
|
||||
}
|
||||
// Only whole characters were replaced: comments and the mark start and end on ASCII.
|
||||
String::from_utf8(out).unwrap_or_default()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{blank_comments, strip};
|
||||
|
||||
#[test]
|
||||
fn blanking_comments_keeps_every_offset_and_trailing_commas() {
|
||||
let src = "\u{feff}{// é\r\n\"a//\\\"\": /* ü\n*/ 1,}";
|
||||
let blank = blank_comments(src);
|
||||
assert_eq!(blank.len(), src.len());
|
||||
assert_eq!(blank.split_whitespace().collect::<Vec<_>>(), ["{", "\"a//\\\"\":", "1,}"]);
|
||||
assert_eq!(blank.find('1'), src.find('1'));
|
||||
assert_eq!(blank_comments("{}/* open é"), "{} ");
|
||||
}
|
||||
use super::strip;
|
||||
|
||||
#[test]
|
||||
fn drops_comments_and_trailing_commas_outside_strings() {
|
||||
|
||||
@@ -6,7 +6,6 @@
|
||||
|
||||
pub mod build_jobs;
|
||||
pub mod cli_process;
|
||||
pub mod cmake_file_api;
|
||||
pub mod editor_settings;
|
||||
pub mod error;
|
||||
pub mod event;
|
||||
|
||||
@@ -83,24 +83,6 @@ pub fn own_group(cmd: &mut Command) -> &mut Command {
|
||||
cmd
|
||||
}
|
||||
|
||||
/// Starts the child as the leader of a session of its own on Unix. Like [`own_group`] it leads
|
||||
/// its process group, so [`kill_tree`] and [`terminate_tree`] reach what it starts; unlike it,
|
||||
/// the child has no controlling terminal, so a tool that would ask on `/dev/tty` (and be
|
||||
/// stopped there as a background job when the app was started from a shell) falls back to
|
||||
/// its pipes. Use it in place of `own_group`: a group leader cannot start a session. A no-op
|
||||
/// elsewhere.
|
||||
pub fn own_session(cmd: &mut Command) -> &mut Command {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::process::CommandExt;
|
||||
// SAFETY: `setsid` is async-signal-safe and touches none of the parent's memory.
|
||||
unsafe {
|
||||
cmd.pre_exec(|| if libc::setsid() == -1 { Err(std::io::Error::last_os_error()) } else { Ok(()) });
|
||||
}
|
||||
}
|
||||
cmd
|
||||
}
|
||||
|
||||
/// Kills the child and everything it started, then reaps it.
|
||||
///
|
||||
/// - Unix: `SIGKILL` to its process group, so spawn it with [`own_group`].
|
||||
@@ -285,190 +267,6 @@ fn taskkill_tree_of(pid: u32) {
|
||||
windows_tree::wait_all(&started, TREE_EXIT_WAIT);
|
||||
}
|
||||
|
||||
/// The registry environment behind [`registry_env_changes`], read with
|
||||
/// `CreateEnvironmentBlock` as Explorer does for the programs it starts after a
|
||||
/// `WM_SETTINGCHANGE`. It is read again only after `HKCU\Environment` or the machine's
|
||||
/// `Environment` key reports a change, so spawning a child costs two event polls.
|
||||
#[cfg(windows)]
|
||||
mod registry_env {
|
||||
use std::ffi::OsString;
|
||||
use std::os::windows::ffi::OsStringExt;
|
||||
use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle};
|
||||
use std::sync::Mutex;
|
||||
use windows_sys::Win32::Foundation::{ERROR_SUCCESS, HANDLE, WAIT_OBJECT_0};
|
||||
use windows_sys::Win32::Security::{TOKEN_DUPLICATE, TOKEN_IMPERSONATE, TOKEN_QUERY};
|
||||
use windows_sys::Win32::System::Environment::{CreateEnvironmentBlock, DestroyEnvironmentBlock};
|
||||
use windows_sys::Win32::System::Registry::{
|
||||
HKEY, HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE, KEY_NOTIFY, REG_NOTIFY_CHANGE_LAST_SET, REG_NOTIFY_CHANGE_NAME,
|
||||
REG_NOTIFY_THREAD_AGNOSTIC, RegCloseKey, RegNotifyChangeKeyValue, RegOpenKeyExW,
|
||||
};
|
||||
use windows_sys::Win32::System::Threading::{
|
||||
CreateEventW, GetCurrentProcess, OpenProcessToken, ResetEvent, WaitForSingleObject,
|
||||
};
|
||||
|
||||
type Vars = Vec<(OsString, OsString)>;
|
||||
|
||||
/// An open registry key and the event its next change signals.
|
||||
struct Watch {
|
||||
key: HKEY,
|
||||
event: OwnedHandle,
|
||||
}
|
||||
|
||||
// SAFETY: a registry key handle is a kernel handle, usable from any thread.
|
||||
unsafe impl Send for Watch {}
|
||||
|
||||
impl Watch {
|
||||
fn new(root: HKEY, path: &str) -> Option<Self> {
|
||||
let path: Vec<u16> = path.encode_utf16().chain(Some(0)).collect();
|
||||
let mut key: HKEY = std::ptr::null_mut();
|
||||
// SAFETY: `path` is NUL-terminated; `key` receives a handle the watch owns.
|
||||
if unsafe { RegOpenKeyExW(root, path.as_ptr(), 0, KEY_NOTIFY, &mut key) } != ERROR_SUCCESS {
|
||||
return None;
|
||||
}
|
||||
// SAFETY: plain call; a non-null result is a manual-reset event handle owned here.
|
||||
let event = unsafe { CreateEventW(std::ptr::null(), 1, 0, std::ptr::null()) };
|
||||
if event.is_null() {
|
||||
// SAFETY: `key` was opened above and is closed once.
|
||||
unsafe { RegCloseKey(key) };
|
||||
return None;
|
||||
}
|
||||
// SAFETY: as above.
|
||||
let watch = Watch { key, event: unsafe { OwnedHandle::from_raw_handle(event) } };
|
||||
watch.arm().then_some(watch)
|
||||
}
|
||||
|
||||
/// Asks to be told of the key's next change; `false` when it cannot be watched.
|
||||
fn arm(&self) -> bool {
|
||||
let filter = REG_NOTIFY_CHANGE_NAME | REG_NOTIFY_CHANGE_LAST_SET | REG_NOTIFY_THREAD_AGNOSTIC;
|
||||
// SAFETY: both handles are owned by the watch and open.
|
||||
let status = unsafe { RegNotifyChangeKeyValue(self.key, 0, filter, self.event.as_raw_handle(), 1) };
|
||||
status == ERROR_SUCCESS
|
||||
}
|
||||
|
||||
/// Whether the key changed since the last call; re-arms the watch when it did.
|
||||
fn changed(&self) -> bool {
|
||||
let event: HANDLE = self.event.as_raw_handle();
|
||||
// SAFETY: an event handle owned by the watch.
|
||||
if unsafe { WaitForSingleObject(event, 0) } != WAIT_OBJECT_0 {
|
||||
return false;
|
||||
}
|
||||
// SAFETY: as above.
|
||||
unsafe { ResetEvent(event) };
|
||||
self.arm();
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Watch {
|
||||
fn drop(&mut self) {
|
||||
// SAFETY: the key was opened by `Watch::new` and is closed once.
|
||||
unsafe { RegCloseKey(self.key) };
|
||||
}
|
||||
}
|
||||
|
||||
struct State {
|
||||
startup: Vars,
|
||||
current: Vars,
|
||||
watches: Vec<Watch>,
|
||||
}
|
||||
|
||||
static STATE: Mutex<Option<State>> = Mutex::new(None);
|
||||
|
||||
pub(super) fn record() {
|
||||
let mut state = STATE.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if state.is_none() {
|
||||
*state = Some(start());
|
||||
}
|
||||
}
|
||||
|
||||
fn start() -> State {
|
||||
// Watch before reading: a change in between is then read again, not missed.
|
||||
let watches = [
|
||||
(HKEY_CURRENT_USER, "Environment"),
|
||||
(HKEY_LOCAL_MACHINE, "SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment"),
|
||||
]
|
||||
.into_iter()
|
||||
.filter_map(|(root, path)| Watch::new(root, path))
|
||||
.collect();
|
||||
let startup = read().unwrap_or_default();
|
||||
State { current: startup.clone(), startup, watches }
|
||||
}
|
||||
|
||||
pub(super) fn changes() -> Vec<(OsString, Option<OsString>)> {
|
||||
let mut guard = STATE.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let state = guard.get_or_insert_with(start);
|
||||
// Poll every watch: each one that fired must be re-armed.
|
||||
let changed = state.watches.iter().fold(false, |any, watch| watch.changed() | any);
|
||||
if changed && let Some(fresh) = read() {
|
||||
state.current = fresh;
|
||||
}
|
||||
if state.current == state.startup {
|
||||
return Vec::new();
|
||||
}
|
||||
super::registry_diff(&|k| std::env::var_os(k), &state.startup, &state.current)
|
||||
}
|
||||
|
||||
/// The environment a program Explorer starts now would get; `None` when it cannot be read.
|
||||
pub(super) fn read() -> Option<Vars> {
|
||||
let mut token: HANDLE = std::ptr::null_mut();
|
||||
let access = TOKEN_QUERY | TOKEN_DUPLICATE | TOKEN_IMPERSONATE;
|
||||
// SAFETY: this process's pseudo-handle; `token` receives a handle owned here.
|
||||
if unsafe { OpenProcessToken(GetCurrentProcess(), access, &mut token) } == 0 {
|
||||
return None;
|
||||
}
|
||||
// SAFETY: as above.
|
||||
let token = unsafe { OwnedHandle::from_raw_handle(token) };
|
||||
let mut block: *mut core::ffi::c_void = std::ptr::null_mut();
|
||||
// SAFETY: an open token; `block` receives a block destroyed below.
|
||||
if unsafe { CreateEnvironmentBlock(&mut block, token.as_raw_handle(), 0) } == 0 || block.is_null() {
|
||||
return None;
|
||||
}
|
||||
// SAFETY: the block holds `NAME=VALUE` entries, each NUL-terminated, then a final NUL.
|
||||
let vars = unsafe { parse_block(block as *const u16) };
|
||||
// SAFETY: the block was created above and is destroyed once.
|
||||
unsafe { DestroyEnvironmentBlock(block) };
|
||||
Some(vars)
|
||||
}
|
||||
|
||||
/// # Safety
|
||||
/// `block` points to UTF-16 entries, each NUL-terminated, ended by an empty one.
|
||||
unsafe fn parse_block(block: *const u16) -> Vars {
|
||||
let mut vars = Vars::new();
|
||||
let mut at = block;
|
||||
loop {
|
||||
let mut len = 0;
|
||||
// SAFETY: the caller guarantees the terminating NULs.
|
||||
while unsafe { *at.add(len) } != 0 {
|
||||
len += 1;
|
||||
}
|
||||
if len == 0 {
|
||||
return vars;
|
||||
}
|
||||
// SAFETY: the `len` units before the NUL were just read.
|
||||
let entry = unsafe { std::slice::from_raw_parts(at, len) };
|
||||
// Per-drive directories (`=C:=C:\dir`) have an empty name: skip them.
|
||||
if let Some(eq) = entry.iter().skip(1).position(|&c| c == u16::from(b'=')) {
|
||||
let eq = eq + 1;
|
||||
vars.push((OsString::from_wide(&entry[..eq]), OsString::from_wide(&entry[eq + 1..])));
|
||||
}
|
||||
// SAFETY: the entry's NUL is followed by the next entry or the final NUL.
|
||||
at = unsafe { at.add(len + 1) };
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn reads_this_users_environment() {
|
||||
let vars = super::read().expect("environment block");
|
||||
let get = |k: &str| vars.iter().find(|(n, _)| n.eq_ignore_ascii_case(k)).map(|(_, v)| v.clone());
|
||||
assert!(get("SystemRoot").is_some_and(|v| !v.is_empty()), "{vars:?}");
|
||||
assert!(get("Path").is_some_and(|v| !v.is_empty()), "{vars:?}");
|
||||
assert!(vars.iter().all(|(k, _)| !k.is_empty() && !k.to_string_lossy().contains('=')));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
mod windows_tree {
|
||||
use std::collections::HashSet;
|
||||
@@ -824,30 +622,6 @@ pub fn host_vars_in(dir: &Path) -> impl Iterator<Item = (OsString, OsString)> {
|
||||
apply_changes(std::env::vars_os().collect(), &child_env_changes(Some(dir))).into_iter()
|
||||
}
|
||||
|
||||
/// Whether `(key, value)` can go into a Windows environment block (`KEY=VALUE\0`
|
||||
/// entries, then a final `\0`). `CreateProcessW` / `NtCreateUserProcess` returns
|
||||
/// `ERROR_INVALID_PARAMETER` (os error 87) when an entry has an empty name or an
|
||||
/// interior NUL. That happens when a `REG_MULTI_SZ` user environment value is
|
||||
/// loaded into the process or re-read from the registry (#6806): the extra NUL
|
||||
/// is treated as an entry separator and leaves a fragment with no `=`.
|
||||
pub fn is_spawnable_env_pair(key: &OsStr, value: &OsStr) -> bool {
|
||||
!key.is_empty() && !contains_ascii(key, 0) && !contains_ascii(key, b'=') && !contains_ascii(value, 0)
|
||||
}
|
||||
|
||||
fn contains_ascii(s: &OsStr, byte: u8) -> bool {
|
||||
s.as_encoded_bytes().contains(&byte)
|
||||
}
|
||||
|
||||
/// [`host_vars`] without pairs that a Windows PTY spawn would reject.
|
||||
pub fn spawnable_host_vars() -> impl Iterator<Item = (OsString, OsString)> {
|
||||
host_vars().filter(|(k, v)| is_spawnable_env_pair(k, v))
|
||||
}
|
||||
|
||||
/// [`host_vars_in`] without pairs that a Windows PTY spawn would reject.
|
||||
pub fn spawnable_host_vars_in(dir: &Path) -> impl Iterator<Item = (OsString, OsString)> {
|
||||
host_vars_in(dir).filter(|(k, v)| is_spawnable_env_pair(k, v))
|
||||
}
|
||||
|
||||
/// [`std::env::var_os`] as a child should see it (see [`host_env`]), the login shell's value
|
||||
/// included when this process lacks the variable.
|
||||
pub fn host_var_os(key: impl AsRef<OsStr>) -> Option<OsString> {
|
||||
@@ -860,7 +634,7 @@ pub fn host_var_os_in(dir: &Path, key: impl AsRef<OsStr>) -> Option<OsString> {
|
||||
}
|
||||
|
||||
fn host_var_os_for(dir: Option<&Path>, key: &OsStr) -> Option<OsString> {
|
||||
match child_env_changes(dir).into_iter().find(|(k, _)| same_key(k, key)) {
|
||||
match child_env_changes(dir).into_iter().find(|(k, _)| k == key) {
|
||||
Some((_, fixed)) => fixed,
|
||||
None => std::env::var_os(key).or_else(|| shell_env_for(dir).find(|(k, _)| k == key).map(|(_, v)| v)),
|
||||
}
|
||||
@@ -872,7 +646,7 @@ fn apply_changes(
|
||||
changes: &[(OsString, Option<OsString>)],
|
||||
) -> Vec<(OsString, OsString)> {
|
||||
for (key, value) in changes {
|
||||
let at = vars.iter().position(|(k, _)| same_key(k, key));
|
||||
let at = vars.iter().position(|(k, _)| k == key);
|
||||
match (at, value) {
|
||||
(Some(i), Some(v)) => vars[i].1 = v.clone(),
|
||||
(Some(i), None) => {
|
||||
@@ -885,126 +659,25 @@ fn apply_changes(
|
||||
vars
|
||||
}
|
||||
|
||||
/// The registry's changes (Windows), the AppImage fixes, the overlay, the manual proxy's,
|
||||
/// then those of the project holding `dir` (a later one wins); one entry per name.
|
||||
/// The AppImage fixes, the overlay, the manual proxy's, then those of the project holding
|
||||
/// `dir` (a later one wins); one entry per name.
|
||||
fn child_env_changes(dir: Option<&Path>) -> Vec<(OsString, Option<OsString>)> {
|
||||
let mut changes = registry_env_changes();
|
||||
changes.extend(appimage_fixes());
|
||||
let mut changes = appimage_fixes();
|
||||
let overlay = env_overlay();
|
||||
changes.retain(|(k, _)| !overlay.iter().any(|(o, _)| same_key(o, k)));
|
||||
changes.retain(|(k, _)| !overlay.iter().any(|(o, _)| o == k));
|
||||
changes.extend(overlay.iter().cloned());
|
||||
// A manual HTTP proxy reaches tools that read `HTTP_PROXY` (language servers, git, curl).
|
||||
let proxy = crate::proxy_settings::proxy().child_env();
|
||||
changes.retain(|(k, _)| !proxy.iter().any(|(p, _)| same_key(p, k)));
|
||||
changes.retain(|(k, _)| !proxy.iter().any(|(p, _)| p == k));
|
||||
changes.extend(proxy);
|
||||
if let Some(dir) = dir {
|
||||
let project = crate::project_env::for_dir(dir);
|
||||
changes.retain(|(k, _)| !project.iter().any(|(p, _)| same_key(p, k)));
|
||||
changes.retain(|(k, _)| !project.iter().any(|(p, _)| p == k));
|
||||
changes.extend(project.iter().cloned());
|
||||
}
|
||||
changes
|
||||
}
|
||||
|
||||
/// Whether two variable names are the same variable: Windows ignores case (`Path` is `PATH`).
|
||||
fn same_key(a: &OsStr, b: &OsStr) -> bool {
|
||||
if cfg!(windows) { a.eq_ignore_ascii_case(b) } else { a == b }
|
||||
}
|
||||
|
||||
/// What changed in the environment Windows gives new programs (the registry's machine and
|
||||
/// user variables) since this process started. A program installed meanwhile (Node.js, a
|
||||
/// JDK) adds its folder to `Path`; a child of the IDE must find it, as a program started
|
||||
/// from Explorer would, without restarting the IDE. Empty elsewhere.
|
||||
fn registry_env_changes() -> Vec<(OsString, Option<OsString>)> {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
registry_env::changes()
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
Vec::new()
|
||||
}
|
||||
}
|
||||
|
||||
/// Remembers the registry environment this process starts with, so that later changes reach
|
||||
/// new children. Call at startup (otherwise the first child spawn records it). Does nothing
|
||||
/// outside Windows.
|
||||
pub fn record_startup_registry_env() {
|
||||
#[cfg(windows)]
|
||||
registry_env::record();
|
||||
}
|
||||
|
||||
/// The entry of a `PATH`-like list as compared: without a trailing separator, and on
|
||||
/// Windows without case.
|
||||
#[cfg_attr(not(windows), allow(dead_code))]
|
||||
fn path_entry_key(dir: &Path) -> String {
|
||||
let text = dir.to_string_lossy();
|
||||
let text = text.trim_end_matches(['\\', '/']);
|
||||
if cfg!(windows) { text.to_ascii_lowercase() } else { text.to_owned() }
|
||||
}
|
||||
|
||||
/// `old` → `fresh` applied to this process's `PATH`-like list `process`: entries that
|
||||
/// `fresh` dropped are removed and those it added are appended, so what the IDE put on
|
||||
/// `PATH` itself (managed tools, the user's `Path`) stays where it is.
|
||||
#[cfg_attr(not(windows), allow(dead_code))]
|
||||
fn rebase_path_list(process: &OsStr, old: &OsStr, fresh: &OsStr) -> OsString {
|
||||
let entries = |list: &OsStr| -> Vec<std::path::PathBuf> {
|
||||
std::env::split_paths(list).filter(|d| !d.as_os_str().is_empty()).collect()
|
||||
};
|
||||
let old: Vec<String> = entries(old).iter().map(|d| path_entry_key(d)).collect();
|
||||
let fresh = entries(fresh);
|
||||
let fresh_keys: Vec<String> = fresh.iter().map(|d| path_entry_key(d)).collect();
|
||||
let mut out: Vec<std::path::PathBuf> = entries(process)
|
||||
.into_iter()
|
||||
.filter(|d| {
|
||||
let key = path_entry_key(d);
|
||||
!old.contains(&key) || fresh_keys.contains(&key)
|
||||
})
|
||||
.collect();
|
||||
for (dir, key) in fresh.into_iter().zip(fresh_keys) {
|
||||
if !old.contains(&key) && !out.iter().any(|d| path_entry_key(d) == key) {
|
||||
out.push(dir);
|
||||
}
|
||||
}
|
||||
std::env::join_paths(out).unwrap_or_else(|_| process.to_owned())
|
||||
}
|
||||
|
||||
/// The changes that bring this process's environment (`process`) from the registry
|
||||
/// environment it started with (`old`) to the current one (`fresh`): new and changed
|
||||
/// variables; removed ones while this process still has the value it started with; and
|
||||
/// `PATH` rebased ([`rebase_path_list`]).
|
||||
#[cfg_attr(not(windows), allow(dead_code))]
|
||||
fn registry_diff(
|
||||
process: &dyn Fn(&OsStr) -> Option<OsString>,
|
||||
old: &[(OsString, OsString)],
|
||||
fresh: &[(OsString, OsString)],
|
||||
) -> Vec<(OsString, Option<OsString>)> {
|
||||
let get =
|
||||
|vars: &[(OsString, OsString)], k: &OsStr| vars.iter().find(|(n, _)| same_key(n, k)).map(|(_, v)| v.clone());
|
||||
let mut out = Vec::new();
|
||||
for (key, value) in fresh {
|
||||
let before = get(old, key);
|
||||
if before.as_ref() == Some(value) {
|
||||
continue;
|
||||
}
|
||||
let current = process(key);
|
||||
if key.eq_ignore_ascii_case("PATH") {
|
||||
let current = current.unwrap_or_default();
|
||||
let rebased = rebase_path_list(¤t, before.as_deref().unwrap_or_default(), value);
|
||||
if rebased != current {
|
||||
out.push((key.clone(), Some(rebased)));
|
||||
}
|
||||
} else if current.as_ref() != Some(value) {
|
||||
out.push((key.clone(), Some(value.clone())));
|
||||
}
|
||||
}
|
||||
for (key, value) in old {
|
||||
if get(fresh, key).is_none() && process(key).as_ref() == Some(value) {
|
||||
out.push((key.clone(), None));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Read on every call, not cached: startup rewrites `PATH` (login shell, managed tools).
|
||||
fn appimage_fixes() -> Vec<(OsString, Option<OsString>)> {
|
||||
if !cfg!(target_os = "linux") || std::env::var_os("APPDIR").is_none() {
|
||||
@@ -1273,28 +946,6 @@ fn append_path_entries(path: &OsStr, extra: &OsStr) -> OsString {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn own_session_leaves_the_controlling_terminal_behind() {
|
||||
// `ps` prints `?` (Linux) or `??` (macOS) for a process without a controlling terminal.
|
||||
let mut cmd = Command::new("sh");
|
||||
cmd.args(["-c", "ps -o tty= -p $$"]);
|
||||
let out = own_session(&mut cmd).output().unwrap();
|
||||
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
|
||||
assert!(String::from_utf8_lossy(&out.stdout).trim().chars().all(|c| c == '?'), "{:?}", out.stdout);
|
||||
// Without a terminal (CI) the line above holds anyway: the child must lead a session
|
||||
// of its own, which only `setsid` makes it.
|
||||
let mut cmd = Command::new("sleep");
|
||||
cmd.arg("5");
|
||||
let mut child = own_session(&mut cmd).spawn().unwrap();
|
||||
let pid = libc::pid_t::try_from(child.id()).unwrap();
|
||||
// SAFETY: plain syscall on a child not reaped yet.
|
||||
let session = unsafe { libc::getsid(pid) };
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
assert_eq!(session, pid, "the child leads its own session");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn process_alive_tells_live_from_dead_pids() {
|
||||
assert!(process_alive(std::process::id()));
|
||||
@@ -1589,35 +1240,6 @@ mod tests {
|
||||
assert!(host_vars_in(root).all(|(k, _)| k != "OPENIDEA_PROJECT_VAR"));
|
||||
}
|
||||
|
||||
fn os_from_bytes(bytes: &[u8]) -> OsString {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::ffi::OsStringExt;
|
||||
OsString::from_vec(bytes.to_vec())
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::os::windows::ffi::OsStringExt;
|
||||
OsString::from_wide(&bytes.iter().copied().map(u16::from).collect::<Vec<_>>())
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spawnable_env_pairs_reject_empty_keys_equals_and_interior_nuls() {
|
||||
let ok_key = OsString::from("PATH");
|
||||
let ok_val = OsString::from("/bin");
|
||||
assert!(is_spawnable_env_pair(&ok_key, &ok_val));
|
||||
assert!(!is_spawnable_env_pair(OsStr::new(""), &ok_val));
|
||||
assert!(!is_spawnable_env_pair(OsStr::new("FOO=BAR"), &ok_val));
|
||||
// A REG_MULTI_SZ value's interior NUL would split the environment block,
|
||||
// leaving a fragment with no `=` (#6806). An empty name is also rejected.
|
||||
assert!(!is_spawnable_env_pair(&os_from_bytes(b""), &os_from_bytes(b"132786")));
|
||||
assert!(!is_spawnable_env_pair(&ok_key, &os_from_bytes(b"1788051509\x00132786")));
|
||||
assert!(!is_spawnable_env_pair(&os_from_bytes(b"132786\x00"), &ok_val));
|
||||
assert!(spawnable_host_vars().all(|(k, v)| is_spawnable_env_pair(&k, &v)));
|
||||
assert!(spawnable_host_vars().any(|(k, _)| k == "PATH" || k == "Path"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn changes_apply_in_order() {
|
||||
let vars = apply_changes(
|
||||
@@ -1744,118 +1366,6 @@ mod tests {
|
||||
assert!(fixes(&[("APPDIR", "/"), ("PATH", "/usr/bin")]).is_empty());
|
||||
}
|
||||
|
||||
fn os(vars: &[(&str, &str)]) -> Vec<(OsString, OsString)> {
|
||||
vars.iter().map(|(k, v)| ((*k).into(), (*v).into())).collect()
|
||||
}
|
||||
|
||||
fn list(dirs: &[&str]) -> OsString {
|
||||
std::env::join_paths(dirs).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn registry_path_changes_keep_what_the_ide_added_to_path() {
|
||||
// The IDE put `tools` first at startup; meanwhile an installer appended `node`
|
||||
// and an uninstaller removed `old`.
|
||||
let process = list(&["tools", "sys", "old", "user"]);
|
||||
let rebased = rebase_path_list(&process, &list(&["sys", "old", "user"]), &list(&["sys", "user", "node"]));
|
||||
assert_eq!(rebased, list(&["tools", "sys", "user", "node"]));
|
||||
// Nothing to add when the entry is already there (a trailing separator aside).
|
||||
let sep = std::path::MAIN_SEPARATOR.to_string();
|
||||
let rebased =
|
||||
rebase_path_list(&list(&["sys", "node"]), &list(&["sys"]), &list(&["sys", &format!("node{sep}")]));
|
||||
assert_eq!(rebased, list(&["sys", "node"]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn registry_changes_are_new_changed_and_removed_variables() {
|
||||
let old = os(&[("KEEP", "1"), ("CHANGED", "a"), ("GONE", "x"), ("OVERRIDDEN", "y"), ("PATH", "sys")]);
|
||||
let fresh = os(&[("KEEP", "1"), ("CHANGED", "b"), ("NEW", "n"), ("PATH", "sys")]);
|
||||
// The IDE was launched with `OVERRIDDEN` set otherwise: that value stays.
|
||||
let process = |k: &OsStr| match k.to_str()?.to_ascii_uppercase().as_str() {
|
||||
"KEEP" => Some("1".into()),
|
||||
"CHANGED" => Some("a".into()),
|
||||
"GONE" => Some("x".into()),
|
||||
"OVERRIDDEN" => Some("launcher".into()),
|
||||
"PATH" => Some(list(&["tools", "sys"])),
|
||||
_ => None,
|
||||
};
|
||||
let got = registry_diff(&process, &old, &fresh);
|
||||
let want: Vec<(OsString, Option<OsString>)> =
|
||||
vec![("CHANGED".into(), Some("b".into())), ("NEW".into(), Some("n".into())), ("GONE".into(), None)];
|
||||
assert_eq!(got, want);
|
||||
assert!(registry_diff(&process, &old, &old).is_empty());
|
||||
// A `Path` change reaches the process `PATH` (another case of the same variable).
|
||||
let got = registry_diff(&process, &os(&[("Path", "sys")]), &os(&[("Path", "sys;node")]));
|
||||
if cfg!(windows) {
|
||||
assert_eq!(got, vec![("Path".into(), Some(list(&["tools", "sys", "node"])))]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn changes_match_variable_names_as_the_platform_does() {
|
||||
let vars = os(&[("Path", "a")]);
|
||||
let got = apply_changes(vars, &[("PATH".into(), Some("b".into()))]);
|
||||
if cfg!(windows) {
|
||||
assert_eq!(got, os(&[("Path", "b")]));
|
||||
} else {
|
||||
assert_eq!(got, os(&[("Path", "a"), ("PATH", "b")]));
|
||||
}
|
||||
}
|
||||
|
||||
/// A variable set in `HKCU\Environment` after startup (as an installer or the System
|
||||
/// Properties dialog does) reaches the next child without a restart.
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn a_user_variable_set_after_startup_reaches_new_children() {
|
||||
use windows_sys::Win32::Foundation::ERROR_SUCCESS;
|
||||
use windows_sys::Win32::System::Registry::{HKEY_CURRENT_USER, REG_SZ, RegDeleteKeyValueW, RegSetKeyValueW};
|
||||
|
||||
fn wide(s: &str) -> Vec<u16> {
|
||||
s.encode_utf16().chain(Some(0)).collect()
|
||||
}
|
||||
struct Cleanup(Vec<u16>);
|
||||
impl Drop for Cleanup {
|
||||
fn drop(&mut self) {
|
||||
// SAFETY: NUL-terminated names of a value this test created.
|
||||
unsafe { RegDeleteKeyValueW(HKEY_CURRENT_USER, wide("Environment").as_ptr(), self.0.as_ptr()) };
|
||||
}
|
||||
}
|
||||
|
||||
record_startup_registry_env();
|
||||
let name = format!("OPENIDEA_REGISTRY_ENV_TEST_{}", std::process::id());
|
||||
let value = wide("installed");
|
||||
let wide_name = wide(&name);
|
||||
// SAFETY: NUL-terminated names; the data is `value`'s bytes, NUL included.
|
||||
let status = unsafe {
|
||||
RegSetKeyValueW(
|
||||
HKEY_CURRENT_USER,
|
||||
wide("Environment").as_ptr(),
|
||||
wide_name.as_ptr(),
|
||||
REG_SZ,
|
||||
value.as_ptr().cast(),
|
||||
(value.len() * 2) as u32,
|
||||
)
|
||||
};
|
||||
assert_eq!(status, ERROR_SUCCESS);
|
||||
let cleanup = Cleanup(wide_name);
|
||||
let deadline = std::time::Instant::now() + Duration::from_secs(5);
|
||||
let seen = loop {
|
||||
let seen = host_var_os(&name);
|
||||
if seen.is_some() || std::time::Instant::now() >= deadline {
|
||||
break seen;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
};
|
||||
assert_eq!(seen.as_deref(), Some(OsStr::new("installed")));
|
||||
assert!(spawnable_host_vars().any(|(k, v)| k == name.as_str() && v == "installed"));
|
||||
drop(cleanup);
|
||||
let deadline = std::time::Instant::now() + Duration::from_secs(5);
|
||||
while host_var_os(&name).is_some() && std::time::Instant::now() < deadline {
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
assert_eq!(host_var_os(&name), None, "a removed variable is gone again");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn host_env_keeps_what_the_call_site_set() {
|
||||
let mut cmd = Command::new("true");
|
||||
|
||||
@@ -5,29 +5,6 @@ use std::path::{Component, Path, PathBuf};
|
||||
|
||||
pub const SEARCH_DEPTH: usize = 3;
|
||||
|
||||
/// Folders that hold dependencies or build output rather than the project's own builds: hidden
|
||||
/// folders (`.build`, `.git`), package checkouts (`node_modules`, `SourcePackages`, `Pods`,
|
||||
/// `Carthage`) and build products (`target`, `build`, `DerivedData`, …).
|
||||
pub fn is_skipped_dir(name: &str) -> bool {
|
||||
name.starts_with('.')
|
||||
|| matches!(
|
||||
name,
|
||||
"node_modules"
|
||||
| "target"
|
||||
| "build"
|
||||
| "dist"
|
||||
| "vendor"
|
||||
| "out"
|
||||
| "bin"
|
||||
| "obj"
|
||||
| "venv"
|
||||
| "SourcePackages"
|
||||
| "Pods"
|
||||
| "Carthage"
|
||||
| "DerivedData"
|
||||
)
|
||||
}
|
||||
|
||||
pub fn children(dir: &Path) -> Vec<PathBuf> {
|
||||
let Ok(entries) = std::fs::read_dir(dir) else { return Vec::new() };
|
||||
let mut dirs: Vec<_> = entries
|
||||
@@ -36,7 +13,13 @@ pub fn children(dir: &Path) -> Vec<PathBuf> {
|
||||
if !entry.file_type().is_ok_and(|kind| kind.is_dir()) {
|
||||
return false;
|
||||
}
|
||||
!is_skipped_dir(&entry.file_name().to_string_lossy())
|
||||
let name = entry.file_name();
|
||||
let name = name.to_string_lossy();
|
||||
!name.starts_with('.')
|
||||
&& !matches!(
|
||||
name.as_ref(),
|
||||
"node_modules" | "target" | "build" | "dist" | "vendor" | "out" | "bin" | "obj" | "venv"
|
||||
)
|
||||
})
|
||||
.map(|entry| entry.path())
|
||||
.collect();
|
||||
|
||||
@@ -227,7 +227,6 @@ pub struct RunTarget {
|
||||
pub python: String,
|
||||
pub node: String,
|
||||
pub java: String,
|
||||
pub php: String,
|
||||
/// Id of a Docker connection of the Services tool window (Docker, Compose);
|
||||
/// empty = the CLI's own daemon.
|
||||
pub docker_connection: String,
|
||||
|
||||
@@ -68,8 +68,6 @@ pub struct Settings {
|
||||
/// Build, Execution, Deployment › Run Targets.
|
||||
pub run_targets: Vec<RunTarget>,
|
||||
pub cmake: CMakeSettings,
|
||||
/// Build, Execution, Deployment › Toolchains; the first is the default.
|
||||
pub toolchains: Vec<Toolchain>,
|
||||
/// Settings › Agents.
|
||||
pub agents: AgentSettings,
|
||||
/// Agents › MCP Server (global only).
|
||||
@@ -162,9 +160,6 @@ pub struct AgentSettings {
|
||||
#[serde(deserialize_with = "or_default")]
|
||||
#[specta(type = BTreeMap<String, AgentMcpServer>)]
|
||||
pub mcp_servers: BTreeMap<String, AgentMcpServer>,
|
||||
/// Custom MCP Registry base URL (`agents.mcpRegistryUrl`); empty = GitHub MCP Registry.
|
||||
#[serde(default, skip_serializing_if = "String::is_empty")]
|
||||
pub mcp_registry_url: String,
|
||||
/// How agent skills may run, keyed by skill name (`[agents.skills.<name>]`); `SKILL.md`
|
||||
/// files on disk are never modified.
|
||||
#[serde(deserialize_with = "or_default")]
|
||||
@@ -175,15 +170,6 @@ pub struct AgentSettings {
|
||||
#[serde(deserialize_with = "or_default")]
|
||||
#[specta(type = AgentMemorySettings)]
|
||||
pub memory: AgentMemorySettings,
|
||||
/// Agent plugin bundle policies (`[agents.plugins]`): registered marketplaces and non-sensitive
|
||||
/// config. Enablement lives in each harness's native config; capability consent is stored per machine.
|
||||
#[serde(deserialize_with = "or_default")]
|
||||
#[specta(type = AgentPluginSettings)]
|
||||
pub plugins: AgentPluginSettings,
|
||||
/// Scheduled agent automations and headless scheduler host policies (`[agents.automations]`).
|
||||
#[serde(deserialize_with = "or_default")]
|
||||
#[specta(type = AgentAutomationSettings)]
|
||||
pub automations: AgentAutomationSettings,
|
||||
}
|
||||
|
||||
impl Default for AgentSettings {
|
||||
@@ -214,11 +200,8 @@ impl Default for AgentSettings {
|
||||
confirm_terminate_on_close: true,
|
||||
defaults: BTreeMap::new(),
|
||||
mcp_servers: BTreeMap::new(),
|
||||
mcp_registry_url: String::new(),
|
||||
skills: BTreeMap::new(),
|
||||
memory: AgentMemorySettings::default(),
|
||||
plugins: AgentPluginSettings::default(),
|
||||
automations: AgentAutomationSettings::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -257,14 +240,6 @@ pub struct AgentMcpServer {
|
||||
/// empty means enabled for all agents.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub agents: Vec<String>,
|
||||
/// Canonical MCP registry server identifier (e.g. `microsoft/playwright-mcp`) when installed from a registry.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub registry_name: Option<String>,
|
||||
/// Normalized MCP registry base URL (e.g. `https://api.mcp.github.com`) when installed from a registry.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub registry_url: Option<String>,
|
||||
}
|
||||
|
||||
impl Default for AgentMcpServer {
|
||||
@@ -278,8 +253,6 @@ impl Default for AgentMcpServer {
|
||||
url: None,
|
||||
headers: BTreeMap::new(),
|
||||
agents: Vec::new(),
|
||||
registry_name: None,
|
||||
registry_url: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -312,7 +285,20 @@ impl Default for AgentSkillPolicy {
|
||||
}
|
||||
}
|
||||
|
||||
/// How an agent's automatic cross-session memory runs (`[agents.memory.providers.<id>]`).
|
||||
/// How an agent instruction, rule, or memory entry may load (`[agents.memory.entries.<id>] mode = …`).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum AgentMemoryMode {
|
||||
/// Load according to its native rules (always for instructions, matching files for path-scoped rules).
|
||||
#[default]
|
||||
Auto,
|
||||
/// Force-load into every session regardless of path scoping.
|
||||
Always,
|
||||
/// Exclude from sessions where the harness supports it.
|
||||
Off,
|
||||
}
|
||||
|
||||
/// How an agent's automatic cross-session memory runs (`[agents.memory] autoMemory = …`).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum AutoMemoryMode {
|
||||
@@ -327,6 +313,24 @@ pub enum AutoMemoryMode {
|
||||
Off,
|
||||
}
|
||||
|
||||
/// One memory or instruction entry's policy in Settings › Agents › Memory.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct AgentMemoryEntryPolicy {
|
||||
#[serde(deserialize_with = "or_default")]
|
||||
#[specta(type = AgentMemoryMode)]
|
||||
pub mode: AgentMemoryMode,
|
||||
/// Agent provider ids this entry applies to; empty means all agents.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub agents: Vec<String>,
|
||||
}
|
||||
|
||||
impl Default for AgentMemoryEntryPolicy {
|
||||
fn default() -> Self {
|
||||
Self { mode: AgentMemoryMode::Auto, agents: Vec::new() }
|
||||
}
|
||||
}
|
||||
|
||||
/// Per-provider auto-memory policy (`[agents.memory.providers.<id>]`).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
@@ -340,100 +344,18 @@ pub struct AgentProviderMemoryPolicy {
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct AgentMemorySettings {
|
||||
/// Per-provider cross-session auto-memory overrides (`[agents.memory.providers.<provider>]`).
|
||||
/// Default cross-session auto-memory policy across agents.
|
||||
#[serde(deserialize_with = "or_default")]
|
||||
#[specta(type = AutoMemoryMode)]
|
||||
pub auto_memory: AutoMemoryMode,
|
||||
/// Optional per-provider auto-memory overrides (`[agents.memory.providers.<provider>]`).
|
||||
#[serde(deserialize_with = "or_default", skip_serializing_if = "BTreeMap::is_empty")]
|
||||
#[specta(type = BTreeMap<String, AgentProviderMemoryPolicy>)]
|
||||
pub providers: BTreeMap<String, AgentProviderMemoryPolicy>,
|
||||
}
|
||||
|
||||
/// One agent plugin bundle's policy in Settings › Agents › Plugins
|
||||
/// (`[agents.plugins.entries."<harness>:<plugin>@<marketplace>"]`).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct AgentPluginEntryPolicy {
|
||||
/// Non-sensitive `userConfig` / `variables` key-value pairs; sensitive values live in OS Keychain.
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub config: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
/// Agent plugin bundle settings (`[agents.plugins]`).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct AgentPluginSettings {
|
||||
/// Registered plugin marketplaces (`owner/repo[#ref]`, GitHub URL, or local directory/manifest path).
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub marketplaces: Vec<String>,
|
||||
/// Per-plugin non-sensitive native option hints, keyed by `<harness>:<plugin>@<marketplace>`.
|
||||
/// Per-entry modes (`[agents.memory.entries.<id>]`).
|
||||
#[serde(deserialize_with = "or_default", skip_serializing_if = "BTreeMap::is_empty")]
|
||||
#[specta(type = BTreeMap<String, AgentPluginEntryPolicy>)]
|
||||
pub entries: BTreeMap<String, AgentPluginEntryPolicy>,
|
||||
}
|
||||
|
||||
/// When OpenIDEA holds an OS idle-sleep assertion during active automation turns.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum AutomationPreventSleep {
|
||||
/// Prevent idle sleep while plugged into AC power.
|
||||
#[default]
|
||||
Ac,
|
||||
/// Prevent idle sleep whenever an automated turn is running.
|
||||
Always,
|
||||
/// Never hold an idle-sleep assertion.
|
||||
Never,
|
||||
}
|
||||
|
||||
/// What the scheduler does when one or more scheduled occurrences fell due while asleep or offline.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum AutomationMisfirePolicy {
|
||||
/// Coalesce all missed occurrences into at most one catch-up run once awake and online.
|
||||
#[default]
|
||||
RunOnce,
|
||||
/// Skip missed occurrences and advance to the next future slot.
|
||||
Skip,
|
||||
}
|
||||
|
||||
/// Agent automation and headless scheduler settings (`[agents.automations]`).
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct AgentAutomationSettings {
|
||||
/// Automatically register the headless login/boot scheduler service while at least one
|
||||
/// automation is enabled, and unregister it when none remain enabled.
|
||||
pub auto_start_service: bool,
|
||||
/// Keep the local OpenIDEA host alive in the background when windows close while local
|
||||
/// automations are enabled.
|
||||
pub keep_alive_in_background: bool,
|
||||
/// Prevent system idle sleep while an automated turn is running.
|
||||
#[serde(deserialize_with = "or_default")]
|
||||
#[specta(type = AutomationPreventSleep)]
|
||||
pub prevent_sleep: AutomationPreventSleep,
|
||||
/// Default policy for scheduled occurrences missed during sleep, offline downtime, or reboot.
|
||||
#[serde(deserialize_with = "or_default")]
|
||||
#[specta(type = AutomationMisfirePolicy)]
|
||||
pub misfire_policy: AutomationMisfirePolicy,
|
||||
/// Keep `openidea-server --daemon` alive across disconnects while the remote host has
|
||||
/// enabled scheduled automations.
|
||||
pub keep_remote_daemon_alive: bool,
|
||||
/// Automatically remove temporary automation worktrees when a run finishes with zero diff
|
||||
/// and zero commits.
|
||||
pub auto_clean_worktrees: bool,
|
||||
/// Maximum retained non-clean automation worktrees per automation before pruning oldest
|
||||
/// finished ones.
|
||||
pub max_dirty_worktrees: u32,
|
||||
}
|
||||
|
||||
impl Default for AgentAutomationSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
auto_start_service: false,
|
||||
keep_alive_in_background: true,
|
||||
prevent_sleep: AutomationPreventSleep::Ac,
|
||||
misfire_policy: AutomationMisfirePolicy::RunOnce,
|
||||
keep_remote_daemon_alive: true,
|
||||
auto_clean_worktrees: true,
|
||||
max_dirty_worktrees: 5,
|
||||
}
|
||||
}
|
||||
#[specta(type = BTreeMap<String, AgentMemoryEntryPolicy>)]
|
||||
pub entries: BTreeMap<String, AgentMemoryEntryPolicy>,
|
||||
}
|
||||
|
||||
/// A hand-edited value these settings don't know reads as the default, rather than
|
||||
@@ -680,8 +602,6 @@ pub struct ToolDownloadSettings {
|
||||
/// Maven Central, dependency version completion from Maven Central, npm, PyPI and
|
||||
/// crates.io). Off by default.
|
||||
pub configured_registries_only: bool,
|
||||
/// The managed Vue Language Server release. Empty selects it from the project's Vue dependency.
|
||||
pub vue_language_server_version: String,
|
||||
}
|
||||
|
||||
/// Settings › Settings Sync: the Git repository the IDE settings sync through, and what syncs.
|
||||
@@ -729,42 +649,9 @@ impl Default for SettingsSyncSettings {
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct CMakeSettings {
|
||||
/// Serialized as `null` when absent, so `cmake.profiles` stays a known settings key.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub profiles: Option<Vec<CMakeProfile>>,
|
||||
/// `true` ignores `CMakePresets.json` / `CMakeUserPresets.json`; otherwise every visible
|
||||
/// configure preset whose condition holds is listed after the explicit profiles.
|
||||
pub ignore_presets: bool,
|
||||
/// Configure presets (by name) enabled as profiles. As in CLion, a preset is listed but
|
||||
/// disabled until enabled here.
|
||||
pub enabled_presets: Vec<String>,
|
||||
/// The profile (by name) that build, run and debug use, as CLion's toolbar switcher;
|
||||
/// empty or unknown = the first enabled one.
|
||||
pub active_profile: String,
|
||||
}
|
||||
|
||||
/// The presets a profile made from `CMakePresets.json` runs with.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct CMakePresetRef {
|
||||
pub configure: String,
|
||||
/// The first build preset of `configure`, used by `cmake --build --preset`.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub build: Option<String>,
|
||||
/// The first test preset of `configure`, used by `ctest --preset`.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub test: Option<String>,
|
||||
/// Cache variables the resolved preset sets itself, read when presets are loaded (never
|
||||
/// saved): a toolchain does not override them.
|
||||
#[serde(skip)]
|
||||
#[specta(skip)]
|
||||
pub cache_variables: Vec<String>,
|
||||
/// The preset names a toolchain file, which picks the compilers.
|
||||
#[serde(skip)]
|
||||
#[specta(skip)]
|
||||
pub toolchain_file: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
@@ -778,23 +665,6 @@ pub struct CMakeProfile {
|
||||
pub build_dir: String,
|
||||
pub build_args: Vec<String>,
|
||||
pub env: BTreeMap<String, String>,
|
||||
/// `false` keeps the profile listed but unused (CLion's "Enable profile").
|
||||
pub enabled: bool,
|
||||
/// Toolchain name (Settings › Toolchains); empty = the default (first) toolchain.
|
||||
pub toolchain: String,
|
||||
/// Set only on the profiles made from presets: configure with `cmake --preset`, and the
|
||||
/// generator and cache variables come from the preset.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub preset: Option<CMakePresetRef>,
|
||||
/// Resolved from the toolchain when profiles are put to use (never saved): the `cmake`
|
||||
/// to run (`ctest` next to it) and the debugger to prefer.
|
||||
#[serde(skip)]
|
||||
#[specta(skip)]
|
||||
pub cmake_program: Option<std::path::PathBuf>,
|
||||
#[serde(skip)]
|
||||
#[specta(skip)]
|
||||
pub debugger: Option<std::path::PathBuf>,
|
||||
}
|
||||
|
||||
impl Default for CMakeProfile {
|
||||
@@ -807,50 +677,10 @@ impl Default for CMakeProfile {
|
||||
build_dir: String::new(),
|
||||
build_args: Vec::new(),
|
||||
env: BTreeMap::new(),
|
||||
enabled: true,
|
||||
toolchain: String::new(),
|
||||
preset: None,
|
||||
cmake_program: None,
|
||||
debugger: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum ToolchainKind {
|
||||
/// Tools from the chosen paths, else from `PATH`.
|
||||
#[default]
|
||||
System,
|
||||
/// A MinGW / MSYS2 directory: its `bin` goes first on `PATH`, with gcc, g++,
|
||||
/// mingw32-make and gdb from there.
|
||||
#[serde(rename = "mingw")]
|
||||
MinGw,
|
||||
/// A Visual Studio installation: configure, build and run get the environment its
|
||||
/// `vcvarsall.bat` sets up (Windows only).
|
||||
#[serde(rename = "visualStudio")]
|
||||
VisualStudio,
|
||||
}
|
||||
|
||||
/// Build, Execution, Deployment › Toolchains (IDE-wide, as in CLion). Empty fields are
|
||||
/// detected from the toolchain installation when it has them, else from `PATH`.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct Toolchain {
|
||||
pub name: String,
|
||||
pub kind: ToolchainKind,
|
||||
/// The MinGW directory (the one holding `bin`), or the Visual Studio installation directory.
|
||||
pub path: String,
|
||||
/// `vcvarsall.bat`'s architecture argument (`x64`, `x86`, `x64_arm64` …); empty is the host's.
|
||||
pub arch: String,
|
||||
pub cmake: String,
|
||||
/// `CMAKE_MAKE_PROGRAM`: make, mingw32-make, nmake or ninja.
|
||||
pub build_tool: String,
|
||||
pub c_compiler: String,
|
||||
pub cxx_compiler: String,
|
||||
pub debugger: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct ToolSettings {
|
||||
@@ -962,7 +792,6 @@ impl Default for Settings {
|
||||
deployment: DeploymentSettings::default(),
|
||||
run_targets: Vec::new(),
|
||||
cmake: CMakeSettings::default(),
|
||||
toolchains: Vec::new(),
|
||||
agents: AgentSettings::default(),
|
||||
mcp_server: McpServerSettings::default(),
|
||||
agent_security: AgentSecuritySettings::default(),
|
||||
@@ -1054,8 +883,6 @@ pub struct GeneralSettings {
|
||||
pub close_tabs_with_window: bool,
|
||||
/// Where Open… puts a project while one is open: `ask` | `new` | `same` | `attach`.
|
||||
pub open_project_in: String,
|
||||
/// What closing a remote development window does with its backend: `ask` | `keep` | `stop`.
|
||||
pub close_remote_window: String,
|
||||
/// Initial folder of the Open / Clone dialogs; empty = the OS default.
|
||||
pub default_project_directory: String,
|
||||
/// Save all files after `idle_seconds` without input.
|
||||
@@ -1069,8 +896,6 @@ pub struct GeneralSettings {
|
||||
pub project_name: String,
|
||||
/// Where updates come from: `auto` (the CNB mirror for the Chinese UI, else GitHub) | `github` | `cnb`.
|
||||
pub update_source: String,
|
||||
/// `stable` | `nightly`; defaults to the running build's channel.
|
||||
pub update_channel: String,
|
||||
pub auto_check_updates: bool,
|
||||
/// System Settings › Updates: open the What's New page after the app starts a new version.
|
||||
pub show_whats_new_after_update: bool,
|
||||
@@ -1086,7 +911,6 @@ impl Default for GeneralSettings {
|
||||
close_without_welcome: false,
|
||||
close_tabs_with_window: false,
|
||||
open_project_in: "ask".into(),
|
||||
close_remote_window: "ask".into(),
|
||||
default_project_directory: String::new(),
|
||||
save_on_idle: false,
|
||||
idle_seconds: 15,
|
||||
@@ -1094,7 +918,6 @@ impl Default for GeneralSettings {
|
||||
power_save_mode: false,
|
||||
project_name: String::new(),
|
||||
update_source: "auto".into(),
|
||||
update_channel: crate::updates::UpdateChannel::of_version(env!("CARGO_PKG_VERSION")).as_str().into(),
|
||||
auto_check_updates: true,
|
||||
show_whats_new_after_update: true,
|
||||
last_run_version: String::new(),
|
||||
@@ -1334,7 +1157,6 @@ pub struct FileIconThemeOptions {
|
||||
pub hollow_folders: bool,
|
||||
pub hide_ui_icons: bool,
|
||||
pub hide_psi_icons: bool,
|
||||
pub file_icons_for_code: bool,
|
||||
pub monochrome: Option<String>,
|
||||
pub saturation: Option<u8>,
|
||||
pub opacity: Option<u8>,
|
||||
@@ -1418,10 +1240,6 @@ pub struct CustomColorScheme {
|
||||
pub struct EditorSettings {
|
||||
pub font_family: String,
|
||||
pub font_size: f32,
|
||||
/// Largest document (in MiB) eligible for syntax analysis and language-server features.
|
||||
#[serde(deserialize_with = "code_insight_limit_mb")]
|
||||
#[specta(type = u8)]
|
||||
pub max_code_insight_file_size_mb: u8,
|
||||
pub line_height: f32,
|
||||
pub tab_size: u32,
|
||||
pub insert_spaces: bool,
|
||||
@@ -1439,9 +1257,6 @@ pub struct EditorSettings {
|
||||
/// Color Scheme › Language Defaults › Semantic highlighting: local variables and
|
||||
/// parameters get a colour derived from their name (IDEA's rainbow identifiers).
|
||||
pub semantic_highlighting: bool,
|
||||
/// Color Scheme › Language Defaults › Dim inactive preprocessor code: grey out the
|
||||
/// `#if`/`#ifdef` branches clangd reports as inactive (C and C++).
|
||||
pub dim_inactive_code: bool,
|
||||
/// Docstring markup format whose tags and keywords the Python editor highlights
|
||||
/// (`plain`, `rest`, `epytext`, `google`, `numpy`).
|
||||
pub docstring_format: String,
|
||||
@@ -1478,23 +1293,11 @@ pub struct EditorSettings {
|
||||
pub encodings: EncodingSettings,
|
||||
}
|
||||
|
||||
pub const DEFAULT_CODE_INSIGHT_LIMIT_MB: u8 = 5;
|
||||
pub const MAX_CODE_INSIGHT_LIMIT_MB: u8 = 50;
|
||||
|
||||
fn code_insight_limit_mb<'de, D: serde::Deserializer<'de>>(d: D) -> Result<u8, D::Error> {
|
||||
Ok(serde_json::Value::deserialize(d)?
|
||||
.as_u64()
|
||||
.and_then(|n| u8::try_from(n).ok())
|
||||
.filter(|n| (1..=MAX_CODE_INSIGHT_LIMIT_MB).contains(n))
|
||||
.unwrap_or(DEFAULT_CODE_INSIGHT_LIMIT_MB))
|
||||
}
|
||||
|
||||
impl Default for EditorSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
font_family: "JetBrains Mono".into(),
|
||||
font_size: 13.0,
|
||||
max_code_insight_file_size_mb: DEFAULT_CODE_INSIGHT_LIMIT_MB,
|
||||
line_height: 22.0,
|
||||
tab_size: 4,
|
||||
insert_spaces: true,
|
||||
@@ -1507,7 +1310,6 @@ impl Default for EditorSettings {
|
||||
color_overrides: BTreeMap::new(),
|
||||
custom_schemes: BTreeMap::new(),
|
||||
semantic_highlighting: false,
|
||||
dim_inactive_code: true,
|
||||
docstring_format: "rest".into(),
|
||||
rainbow_brackets: false,
|
||||
rainbow_bracket_kinds: RainbowBracketKinds::default(),
|
||||
@@ -1707,11 +1509,6 @@ pub struct MarkdownSettings {
|
||||
pub preview_layout: MarkdownPreviewLayout,
|
||||
/// Preview (and notebook Markdown cell) font size in px; unset follows the editor font size.
|
||||
pub preview_font_size: Option<u32>,
|
||||
/// How single newlines inside a paragraph are rendered in the Markdown preview.
|
||||
pub soft_line_breaks: MarkdownSoftLineBreaks,
|
||||
/// Whether `.mdx` previews ask before running JSX components/imports, run automatically in
|
||||
/// trusted projects, or stay in static safe mode.
|
||||
pub mdx_execution: MdxExecutionPolicy,
|
||||
/// "Detect commands that can be run right from Markdown files": gutter run icons on
|
||||
/// shell code blocks and on command lines in code blocks.
|
||||
pub run_commands: bool,
|
||||
@@ -1724,33 +1521,12 @@ impl Default for MarkdownSettings {
|
||||
Self {
|
||||
preview_layout: MarkdownPreviewLayout::default(),
|
||||
preview_font_size: None,
|
||||
soft_line_breaks: MarkdownSoftLineBreaks::default(),
|
||||
mdx_execution: MdxExecutionPolicy::default(),
|
||||
run_commands: true,
|
||||
command_directory: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum MarkdownSoftLineBreaks {
|
||||
/// Standard Markdown: a single newline collapses into a space.
|
||||
#[default]
|
||||
Standard,
|
||||
/// Render each single newline inside a paragraph as a line break (`<br>`).
|
||||
Break,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum MdxExecutionPolicy {
|
||||
#[default]
|
||||
Ask,
|
||||
Trusted,
|
||||
Off,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum MarkdownPreviewLayout {
|
||||
@@ -1882,9 +1658,8 @@ pub struct PythonSettings {
|
||||
/// Default test runner (Settings › Python › Testing): `auto` (pytest when the project uses
|
||||
/// it, else unittest), `pytest` or `unittest`.
|
||||
pub test_runner: String,
|
||||
/// What Profile runs Python under (Settings › Python › Profiler): `auto` (yappi when the
|
||||
/// interpreter can import it, else py-spy where it is installed and samples without root, else
|
||||
/// cProfile), `cprofile`, `py-spy` or `yappi`.
|
||||
/// What Profile runs Python under (Settings › Python › Profiler): `auto` (py-spy where it
|
||||
/// is installed and samples without root, else cProfile), `cprofile` or `py-spy`.
|
||||
pub profiler: String,
|
||||
/// Show matplotlib figures of Python runs in the Plots tool window (the IDE sets `MPLBACKEND`
|
||||
/// unless the run sets it); off: matplotlib's own window.
|
||||
@@ -2160,8 +1935,6 @@ pub struct MavenSettings {
|
||||
pub active_profiles: String,
|
||||
/// Delegate IDE build/run actions to Maven: launches build with Maven (`javac`) instead of jdtls (ECJ).
|
||||
pub delegate_build: bool,
|
||||
/// Maven goals (`groupId:artifactId:goal`) the IDE may skip in compile phases. Empty by default.
|
||||
pub ignored_compile_goals: Vec<String>,
|
||||
/// Download `-sources.jar` of dependencies when the Java language server imports the
|
||||
/// project (jdtls `java.maven.downloadSources`). Off: sources are fetched on demand
|
||||
/// from a library class's Download Sources banner.
|
||||
@@ -2568,16 +2341,12 @@ mod tests {
|
||||
let old: Settings = serde_json::from_str(r#"{"languages":{"markdown":{"previewFontSize":16}}}"#).unwrap();
|
||||
assert_eq!(old.languages.markdown.preview_layout, MarkdownPreviewLayout::SideBySide);
|
||||
assert_eq!(old.languages.markdown.preview_font_size, Some(16));
|
||||
assert_eq!(old.languages.markdown.soft_line_breaks, MarkdownSoftLineBreaks::Standard);
|
||||
|
||||
let stacked: Settings =
|
||||
serde_json::from_str(r#"{"languages":{"markdown":{"previewLayout":"stacked","softLineBreaks":"break"}}}"#)
|
||||
.unwrap();
|
||||
serde_json::from_str(r#"{"languages":{"markdown":{"previewLayout":"stacked"}}}"#).unwrap();
|
||||
assert_eq!(stacked.languages.markdown.preview_layout, MarkdownPreviewLayout::Stacked);
|
||||
assert_eq!(stacked.languages.markdown.soft_line_breaks, MarkdownSoftLineBreaks::Break);
|
||||
let saved = serde_json::to_value(&stacked).unwrap();
|
||||
assert_eq!(saved["languages"]["markdown"]["previewLayout"], "stacked");
|
||||
assert_eq!(saved["languages"]["markdown"]["softLineBreaks"], "break");
|
||||
assert_eq!(serde_json::from_value::<Settings>(saved).unwrap().languages.markdown, stacked.languages.markdown);
|
||||
}
|
||||
|
||||
@@ -2604,12 +2373,12 @@ mod tests {
|
||||
let old: Settings = serde_json::from_str(r#"{"appearance":{"fileIconTheme":"p/t"}}"#).unwrap();
|
||||
assert!(old.appearance.file_icon_theme_options.is_empty());
|
||||
let json = serde_json::json!({"appearance":{"fileIconThemeOptions":{"p/t":{
|
||||
"groups":{"tests":true},"choices":{"arrows":"plusminus"},"hideFiles":true,"hideFolders":false,"hollowFolders":true,"hideUiIcons":true,"hidePsiIcons":false,"fileIconsForCode":true,
|
||||
"groups":{"tests":true},"choices":{"arrows":"plusminus"},"hideFiles":true,"hideFolders":false,"hollowFolders":true,"hideUiIcons":true,"hidePsiIcons":false,
|
||||
"monochrome":"#546e7a","saturation":5,"opacity":80,"iconSize":20,"rowHeight":30,"accent":"#009688"}}}});
|
||||
let settings: Settings = serde_json::from_value(json.clone()).unwrap();
|
||||
let options = &settings.appearance.file_icon_theme_options["p/t"];
|
||||
assert!(options.hide_files && options.hollow_folders && !options.hide_folders);
|
||||
assert!(options.hide_ui_icons && !options.hide_psi_icons && options.file_icons_for_code);
|
||||
assert!(options.hide_ui_icons && !options.hide_psi_icons);
|
||||
assert!(options.groups["tests"]);
|
||||
assert_eq!(options.choices["arrows"], "plusminus");
|
||||
assert_eq!(
|
||||
@@ -2625,7 +2394,6 @@ mod tests {
|
||||
assert_eq!(plain["hideFiles"], false);
|
||||
assert_eq!(plain["hideUiIcons"], false);
|
||||
assert_eq!(plain["hidePsiIcons"], false);
|
||||
assert_eq!(plain["fileIconsForCode"], false);
|
||||
assert_eq!(plain["monochrome"], serde_json::Value::Null);
|
||||
assert_eq!(plain["groups"], serde_json::json!({}));
|
||||
}
|
||||
@@ -2694,20 +2462,6 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dim_inactive_code_defaults_on_and_round_trips() {
|
||||
let mut settings = Settings::default();
|
||||
assert!(settings.editor.dim_inactive_code);
|
||||
settings.editor.dim_inactive_code = false;
|
||||
let json = serde_json::to_value(&settings).unwrap();
|
||||
assert_eq!(json["editor"]["dimInactiveCode"], false);
|
||||
let restored: Settings = serde_json::from_value(json).unwrap();
|
||||
assert!(!restored.editor.dim_inactive_code);
|
||||
// Settings written before the option existed keep clangd's inactive-code grey.
|
||||
let old: Settings = serde_json::from_str(r#"{"editor":{"semanticHighlighting":true}}"#).unwrap();
|
||||
assert!(old.editor.dim_inactive_code);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tool_window_badges_default_on_and_round_trip() {
|
||||
let old: Settings = serde_json::from_str(r#"{"appearance":{"showToolWindowNames":true}}"#).unwrap();
|
||||
|
||||
Loaded 100 of 2789 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Заблокувати користувача