дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-03 08:43:07 +02:00
Порівняти коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
dddef44d56 |
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
|
||||
@@ -1,20 +0,0 @@
|
||||
# Nextest runs tests in separate processes. These three tests write the same Windows clipboard.
|
||||
[test-groups.windows-clipboard]
|
||||
max-threads = 1
|
||||
|
||||
[[profile.default.overrides]]
|
||||
filter = '''
|
||||
package(=ide-clipboard) & (
|
||||
test(=tests::text_reads_on_one_thread_do_not_corrupt_the_heap)
|
||||
| test(=tests::text_reads_taking_turns_do_not_corrupt_the_heap)
|
||||
| test(=tests::concurrent_text_reads_do_not_corrupt_the_heap)
|
||||
)
|
||||
'''
|
||||
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 }
|
||||
Бінарний файл не відображається.
|
До Ширина: | Висота: | Розмір: 192 KiB Після Ширина: | Висота: | Розмір: 169 KiB |
@@ -1,9 +0,0 @@
|
||||
# Keeps the commit SHAs the workflows pin their actions to current (the trailing comment names
|
||||
# the release each SHA comes from).
|
||||
version: 2
|
||||
updates:
|
||||
- package-ecosystem: github-actions
|
||||
directory: /
|
||||
schedule: { interval: weekly }
|
||||
groups:
|
||||
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
|
||||
|
||||
|
||||
@@ -12,7 +12,7 @@ jobs:
|
||||
cancel:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
|
||||
- uses: actions/github-script@v8
|
||||
with:
|
||||
script: |
|
||||
// A merged or closed PR's remaining CI only holds runners other PRs wait for.
|
||||
|
||||
@@ -106,8 +106,7 @@ 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.
|
||||
timeout-minutes: ${{ matrix.os == 'windows-latest' && 75 || 60 }}
|
||||
timeout-minutes: 60
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
@@ -116,24 +115,22 @@ jobs:
|
||||
# SELFHOSTED_RUNNERS repository variable is 'true': runs-on cannot fall back when none is online.
|
||||
runs-on: ${{ matrix.os == 'ubuntu-latest' && vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || matrix.os }}
|
||||
steps:
|
||||
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
|
||||
- uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0
|
||||
- uses: actions/checkout@v5
|
||||
- uses: pnpm/action-setup@v5
|
||||
with: { version: 11 }
|
||||
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
|
||||
- uses: actions/setup-node@v5
|
||||
with:
|
||||
node-version: 22
|
||||
cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }}
|
||||
package-manager-cache: ${{ runner.environment != 'self-hosted' }}
|
||||
- uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
with: { components: "clippy, rustfmt" }
|
||||
# Self-hosted runners keep persistent local Cargo caches; GitHub-hosted runners use Actions cache
|
||||
# (only main saves it because saving takes minutes on Windows; PRs restore main's).
|
||||
# A failing test run on main still saves it, so the next PR doesn't compile from scratch.
|
||||
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
if: runner.environment != 'self-hosted'
|
||||
with:
|
||||
save-if: ${{ github.ref == 'refs/heads/main' }}
|
||||
cache-on-failure: true
|
||||
# The persistent target dir makes incremental builds pay off; cap its size so it can't fill the disk.
|
||||
- name: Persistent Cargo target dir
|
||||
if: runner.environment == 'self-hosted'
|
||||
@@ -145,23 +142,12 @@ jobs:
|
||||
echo "$CARGO_TARGET_DIR is ${size} MB; clearing it"
|
||||
rm -rf "$CARGO_TARGET_DIR"
|
||||
fi
|
||||
- uses: taiki-e/install-action@073e1fd0bc889c9aee68dbaaa927cde1b5653a83 # v2.90.11
|
||||
with: { tool: nextest }
|
||||
- uses: taiki-e/install-action@nextest
|
||||
- name: Linux deps
|
||||
if: runner.os == 'Linux'
|
||||
run: |
|
||||
pkgs=(libwebkit2gtk-4.1-dev libayatana-appindicator3-dev librsvg2-dev libxdo-dev libssl-dev patchelf 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
|
||||
@@ -173,10 +159,10 @@ jobs:
|
||||
- name: Restore Maven artifacts for Java build tests
|
||||
id: jbuild-maven-cache
|
||||
if: runner.environment == 'github-hosted'
|
||||
uses: actions/cache/restore@caa296126883cff596d87d8935842f9db880ef25 # v5.1.0
|
||||
uses: actions/cache/restore@v5
|
||||
with:
|
||||
path: ${{ runner.temp }}/jbuild-maven-repository
|
||||
key: jbuild-maven-v2-${{ runner.os }}-${{ hashFiles('crates/ide-build/tests/fixtures/jbuild-maven/**/pom.xml') }}
|
||||
key: jbuild-maven-${{ runner.os }}-${{ hashFiles('crates/ide-build/tests/fixtures/jbuild-maven/**/pom.xml') }}
|
||||
- name: Prepare Maven artifacts for Java build tests
|
||||
id: jbuild-maven
|
||||
if: runner.environment == 'github-hosted'
|
||||
@@ -193,13 +179,10 @@ jobs:
|
||||
if [[ "$CACHE_HIT" == true ]]; then
|
||||
exit 0
|
||||
fi
|
||||
# The Java tests read the compiler descriptor and run Maven launch and rebuild.
|
||||
# The IDE also reads the compiler plugin descriptor when it builds the Maven model.
|
||||
for delay in 0 10 30; do
|
||||
sleep "$delay"
|
||||
if mvn -B -ntp -U -N -f crates/ide-build/tests/fixtures/jbuild-maven/pom.xml \
|
||||
clean resources:resources compiler:compile \
|
||||
org.apache.maven.plugins:maven-dependency-plugin:3.8.1:get \
|
||||
-Dartifact=org.slf4j:slf4j-api:1.7.36; then
|
||||
if mvn -B -ntp -U -N -f crates/ide-build/tests/fixtures/jbuild-maven/pom.xml resources:resources compiler:compile; then
|
||||
echo "prepared=true" >> "$GITHUB_OUTPUT"
|
||||
exit 0
|
||||
fi
|
||||
@@ -207,7 +190,7 @@ jobs:
|
||||
exit 1
|
||||
- name: Save Maven artifacts for Java build tests
|
||||
if: steps.jbuild-maven.outputs.prepared == 'true'
|
||||
uses: actions/cache/save@caa296126883cff596d87d8935842f9db880ef25 # v5.1.0
|
||||
uses: actions/cache/save@v5
|
||||
with:
|
||||
path: ${{ runner.temp }}/jbuild-maven-repository
|
||||
key: ${{ steps.jbuild-maven-cache.outputs.cache-primary-key }}
|
||||
@@ -252,10 +235,10 @@ jobs:
|
||||
timeout-minutes: 40
|
||||
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
|
||||
steps:
|
||||
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
|
||||
- uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable
|
||||
- uses: actions/checkout@v5
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
with: { targets: x86_64-unknown-linux-musl }
|
||||
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
if: runner.environment != 'self-hosted'
|
||||
with: { key: server-musl }
|
||||
- name: Persistent Cargo target dir
|
||||
@@ -281,13 +264,13 @@ jobs:
|
||||
timeout-minutes: 30
|
||||
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
|
||||
steps:
|
||||
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
|
||||
- uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable
|
||||
- uses: actions/checkout@v5
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
with: { targets: wasm32-wasip2, components: "clippy, rustfmt" }
|
||||
- if: runner.environment != 'self-hosted'
|
||||
shell: bash
|
||||
run: echo "CARGO_TARGET_DIR=$GITHUB_WORKSPACE/target-plugins" >> "$GITHUB_ENV"
|
||||
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
if: runner.environment != 'self-hosted'
|
||||
with:
|
||||
key: plugins
|
||||
@@ -317,9 +300,9 @@ jobs:
|
||||
cargo test --locked --manifest-path "$dir/Cargo.toml"
|
||||
echo "::endgroup::"
|
||||
done
|
||||
- uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0
|
||||
- uses: pnpm/action-setup@v5
|
||||
with: { version: 11 }
|
||||
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
|
||||
- uses: actions/setup-node@v5
|
||||
with: { node-version: 22, package-manager-cache: false }
|
||||
# Plugin web pages (`web-src/`, their own pnpm projects): typecheck and test.
|
||||
- name: Web pages typecheck and test
|
||||
@@ -346,10 +329,9 @@ jobs:
|
||||
timeout-minutes: 15
|
||||
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
|
||||
steps:
|
||||
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
|
||||
- uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable
|
||||
- uses: taiki-e/install-action@073e1fd0bc889c9aee68dbaaa927cde1b5653a83 # v2.90.11
|
||||
with: { tool: cargo-deny }
|
||||
- uses: actions/checkout@v5
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
- uses: taiki-e/install-action@cargo-deny
|
||||
- run: cargo deny check
|
||||
|
||||
frontend:
|
||||
@@ -359,23 +341,17 @@ jobs:
|
||||
timeout-minutes: 30
|
||||
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
|
||||
steps:
|
||||
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
|
||||
- uses: actions/checkout@v5
|
||||
# scripts/smoke-paths.test.ts runs `cargo metadata`, which is not preinstalled in the runner container.
|
||||
- uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
if: runner.environment == 'self-hosted'
|
||||
- uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0
|
||||
- uses: pnpm/action-setup@v5
|
||||
with: { version: 11 }
|
||||
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
|
||||
- uses: actions/setup-node@v5
|
||||
with:
|
||||
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
|
||||
@@ -392,10 +368,10 @@ jobs:
|
||||
timeout-minutes: 15
|
||||
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
|
||||
steps:
|
||||
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
|
||||
- uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0
|
||||
- uses: actions/checkout@v5
|
||||
- uses: pnpm/action-setup@v5
|
||||
with: { version: 11 }
|
||||
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
|
||||
- uses: actions/setup-node@v5
|
||||
with:
|
||||
node-version: 22
|
||||
cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }}
|
||||
@@ -414,10 +390,10 @@ jobs:
|
||||
matrix:
|
||||
shard: [1, 2, 3, 4]
|
||||
steps:
|
||||
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
|
||||
- uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0
|
||||
- uses: actions/checkout@v5
|
||||
- uses: pnpm/action-setup@v5
|
||||
with: { version: 11 }
|
||||
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
|
||||
- uses: actions/setup-node@v5
|
||||
with:
|
||||
node-version: 22
|
||||
cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }}
|
||||
@@ -425,7 +401,7 @@ jobs:
|
||||
- run: pnpm install --frozen-lockfile
|
||||
- run: pnpm exec playwright install --with-deps chromium
|
||||
- run: pnpm e2e --shard=${{ matrix.shard }}/4
|
||||
- uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
|
||||
- uses: actions/upload-artifact@v6
|
||||
if: failure()
|
||||
with:
|
||||
name: playwright-report-${{ matrix.shard }}
|
||||
|
||||
@@ -21,7 +21,6 @@ concurrency:
|
||||
|
||||
jobs:
|
||||
mirror:
|
||||
environment: release
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 120
|
||||
env:
|
||||
@@ -36,10 +35,10 @@ jobs:
|
||||
echo "::notice::CNB_TOKEN unset: not mirroring $TAG"
|
||||
echo "skip=true" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
|
||||
- uses: actions/checkout@v5
|
||||
if: steps.token.outputs.skip != 'true'
|
||||
with: { sparse-checkout: scripts }
|
||||
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
|
||||
- uses: actions/setup-node@v5
|
||||
if: steps.token.outputs.skip != 'true'
|
||||
with: { node-version: 22 }
|
||||
- name: Download release
|
||||
|
||||
@@ -23,7 +23,6 @@ concurrency:
|
||||
|
||||
jobs:
|
||||
cask:
|
||||
environment: release
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
env:
|
||||
@@ -42,16 +41,16 @@ jobs:
|
||||
echo "::notice::HOMEBREW_TAP_DEPLOY_KEY unset: not updating the cask for $TAG"
|
||||
echo "skip=true" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
|
||||
- uses: actions/checkout@v5
|
||||
if: steps.check.outputs.skip != 'true'
|
||||
with: { sparse-checkout: scripts }
|
||||
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
|
||||
- uses: actions/checkout@v5
|
||||
if: steps.check.outputs.skip != 'true'
|
||||
with:
|
||||
repository: ${{ env.TAP }}
|
||||
ssh-key: ${{ secrets.HOMEBREW_TAP_DEPLOY_KEY }}
|
||||
path: tap
|
||||
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
|
||||
- uses: actions/setup-node@v5
|
||||
if: steps.check.outputs.skip != 'true'
|
||||
with: { node-version: 22 }
|
||||
- name: Download DMGs
|
||||
|
||||
@@ -30,20 +30,15 @@ on:
|
||||
- "src/ui/**"
|
||||
- "src/editor/api.ts"
|
||||
- "src/editor/navigationProviders.ts"
|
||||
- "src/editor/refactorProviders.ts"
|
||||
- "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"
|
||||
- "src/editor/lsp/hint.ts"
|
||||
- "src/editor/lsp/lsp.ts"
|
||||
- "src/editor/lsp/positions.ts"
|
||||
- "src/editor/lsp/snippet.ts"
|
||||
- "src/bindings.ts"
|
||||
- "src/styles/tokens.css"
|
||||
- "src/test/setup.ts"
|
||||
@@ -109,9 +104,9 @@ jobs:
|
||||
# SDKs, build tools, the project model, Find Usages candidates, debug stream traces):
|
||||
# cargo metadata, ide-host's direct deps ide-search/ide-streams and the deps of
|
||||
# ide-lsp/dap/run/sdk/tools.
|
||||
unused='^crates/(ide-agent|ide-analysis|ide-android|ide-cli|ide-clipboard|ide-coverage|ide-db|ide-docker|ide-fonts|ide-github|ide-mcp|ide-notebook|ide-profiler|ide-scaffold|ide-spell|ide-ssh|ide-vcs|ide-web)/'
|
||||
unused='^crates/(ide-agent|ide-analysis|ide-android|ide-cli|ide-clipboard|ide-coverage|ide-db|ide-docker|ide-fonts|ide-github|ide-http|ide-mcp|ide-notebook|ide-profiler|ide-scaffold|ide-spell|ide-ssh|ide-vcs|ide-web)/'
|
||||
# The workflow's paths, less those handled per language below.
|
||||
smoke='^(crates/|Cargo\.(toml|lock)$|src/features/(run|debugger|build|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-tauri/icons/128x128\.png$|smoke/|vite\.config\.ts$|tsconfig\.json$|package\.json$|pnpm-(lock|workspace)\.yaml$|patches/|\.github/workflows/language-smoke\.yml$|\.github/tool-versions\.env$)'
|
||||
smoke='^(crates/|Cargo\.(toml|lock)$|src/features/(run|debugger|build|build-tools)/|src/platform/|src/workbench/|src/ui/|src/editor/(api|navigationProviders|relatedProviders|core/cm/(cornerInset|iconArea)|lsp/(availability|diagnostics|files|hint|lsp|positions))\.ts$|src/bindings\.ts$|src/styles/tokens\.css$|src/test/setup\.ts$|src-tauri/icons/128x128\.png$|smoke/|vite\.config\.ts$|tsconfig\.json$|package\.json$|pnpm-(lock|workspace)\.yaml$|patches/|\.github/workflows/language-smoke\.yml$|\.github/tool-versions\.env$)'
|
||||
langs=""
|
||||
while read -r f; do
|
||||
case "$f" in
|
||||
@@ -157,9 +152,9 @@ jobs:
|
||||
# stripping local-variable debuginfo from fixtures debugged in the smoke job (CodeLLDB).
|
||||
CARGO_PROFILE_DEV_DEBUG: line-tables-only
|
||||
steps:
|
||||
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
|
||||
- uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable
|
||||
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
|
||||
- uses: actions/checkout@v5
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
if: runner.environment != 'self-hosted'
|
||||
with:
|
||||
shared-key: language-smoke
|
||||
@@ -186,7 +181,7 @@ jobs:
|
||||
test -x smoke-bin/language_smoke && test -x smoke-bin/project_smoke
|
||||
# A tar keeps the executable bits, which artifacts drop.
|
||||
tar -cf smoke-bin.tar smoke-bin
|
||||
- uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
|
||||
- uses: actions/upload-artifact@v6
|
||||
with: { name: smoke-bin, path: smoke-bin.tar, retention-days: 1 }
|
||||
|
||||
smoke:
|
||||
@@ -205,20 +200,20 @@ jobs:
|
||||
env:
|
||||
CARGO_MANIFEST_DIR: ${{ github.workspace }}/crates/ide-host
|
||||
steps:
|
||||
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
|
||||
- uses: actions/checkout@v5
|
||||
# Tool versions, shared with the evals (pnpm eval).
|
||||
- run: grep -E '^[A-Z0-9_]+=' .github/tool-versions.env >> "$GITHUB_ENV"
|
||||
- uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
with: { components: "rust-analyzer, rustfmt" }
|
||||
- uses: actions/download-artifact@018cc2cf5baa6db3ef3c5f8a56943fffe632ef53 # v6.0.0
|
||||
- uses: actions/download-artifact@v6
|
||||
with: { name: smoke-bin }
|
||||
- run: |
|
||||
tar -xf smoke-bin.tar && rm smoke-bin.tar
|
||||
mkdir -p target/debug && mv smoke-bin/openidea-server target/debug/
|
||||
|
||||
- uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0
|
||||
- uses: pnpm/action-setup@v5
|
||||
with: { version: 11 }
|
||||
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
|
||||
- uses: actions/setup-node@v5
|
||||
with:
|
||||
node-version: 22
|
||||
cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }}
|
||||
@@ -244,19 +239,19 @@ jobs:
|
||||
fi
|
||||
|
||||
- if: matrix.language == 'python'
|
||||
uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0
|
||||
uses: actions/setup-python@v5
|
||||
with: { python-version: "3.12" }
|
||||
- if: matrix.language == 'python'
|
||||
run: pip install "basedpyright==$BASEDPYRIGHT" "ruff==$RUFF"
|
||||
|
||||
- if: matrix.language == 'go'
|
||||
uses: actions/setup-go@40f1582b2485089dde7abd97c1529aa768e1baff # v5.6.0
|
||||
uses: actions/setup-go@v5
|
||||
with: { go-version: "1.27", cache: false }
|
||||
- if: matrix.language == 'go'
|
||||
run: go install "golang.org/x/tools/gopls@$GOPLS"
|
||||
|
||||
- if: matrix.language == 'java' || matrix.language == 'kotlin'
|
||||
uses: actions/setup-java@cf277c60eb25467037889841efdb72551f06f6c3 # v4.9.1
|
||||
uses: actions/setup-java@v4
|
||||
with: { distribution: temurin, java-version: "${{ env.JAVA }}" }
|
||||
- if: matrix.language == 'java'
|
||||
run: |
|
||||
@@ -268,7 +263,7 @@ jobs:
|
||||
|
||||
# The Kotlin fixture has no Gradle wrapper: the server imports it with the Gradle on PATH.
|
||||
- if: matrix.language == 'kotlin'
|
||||
uses: gradle/actions/setup-gradle@ed408507eac070d1f99cc633dbcf757c94c7933a # v4.4.3
|
||||
uses: gradle/actions/setup-gradle@v4
|
||||
with: { gradle-version: "${{ env.GRADLE }}" }
|
||||
- if: matrix.language == 'kotlin'
|
||||
run: |
|
||||
@@ -280,7 +275,7 @@ jobs:
|
||||
|
||||
# Xdebug for the debug smoke; Composer installs the fixture's Pest for the run smoke.
|
||||
- if: matrix.language == 'php'
|
||||
uses: shivammathur/setup-php@eb7c497e18156a6bbabfef1d3a82760b9eda3962 # 2.40.0
|
||||
uses: shivammathur/setup-php@v2
|
||||
with: { php-version: "8.5", coverage: xdebug, tools: composer }
|
||||
- if: matrix.language == 'php'
|
||||
run: npm install --global "intelephense@$INTELEPHENSE"
|
||||
@@ -288,10 +283,6 @@ jobs:
|
||||
# The binaries from the build job, run from the crate directory as `cargo test` does.
|
||||
- working-directory: crates/ide-host
|
||||
run: ../../smoke-bin/language_smoke --ignored --exact ${{ matrix.language }}
|
||||
# Problems › TypeScript Project Errors runs the project's own tsc: the global install stands in.
|
||||
- if: matrix.language == 'typescript'
|
||||
working-directory: crates/ide-host
|
||||
run: ../../smoke-bin/language_smoke --ignored --exact typescript_project_errors typescript_import_style
|
||||
- if: matrix.language == 'java'
|
||||
working-directory: crates/ide-host
|
||||
run: ../../smoke-bin/project_smoke --ignored --exact maven_sync jdk maven_launch_classpath_uses_the_runner_jdk_classifier
|
||||
|
||||
@@ -1,104 +0,0 @@
|
||||
name: Nightly
|
||||
|
||||
# Builds main every night, when it has moved since the last nightly, into a prerelease
|
||||
# v<next patch>-nightly.<date> (scripts/nightly-prepare.ts: the tag points at a commit on top of
|
||||
# main that only sets the version). Nightly apps update from the rolling `nightly` release, which
|
||||
# holds the newest nightly's latest.json; stable apps read releases/latest, which is never a
|
||||
# prerelease, so they never see a nightly. The newest 14 nightlies are kept.
|
||||
on:
|
||||
schedule:
|
||||
- cron: "0 18 * * *" # 02:00 Beijing
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
force:
|
||||
description: "Build even when main has not changed since the last nightly"
|
||||
type: boolean
|
||||
default: false
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: nightly
|
||||
|
||||
jobs:
|
||||
prepare:
|
||||
if: github.repository == 'l0ng-ai/openidea'
|
||||
permissions:
|
||||
contents: write
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
tag: ${{ steps.tag.outputs.tag }}
|
||||
steps:
|
||||
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
|
||||
with: { ref: main, fetch-depth: 0 }
|
||||
- id: changed
|
||||
env:
|
||||
FORCE: ${{ inputs.force == true }}
|
||||
run: |
|
||||
last="$(git tag --list 'v*-nightly.*' --sort=-creatordate | head -1)"
|
||||
if [ "$FORCE" != true ] && [ -n "$last" ] && [ "$(git rev-parse "$last^")" = "$(git rev-parse HEAD)" ]; then
|
||||
echo "::notice::main has not changed since $last"
|
||||
echo "skip=true" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
|
||||
if: steps.changed.outputs.skip != 'true'
|
||||
with: { node-version: 22 }
|
||||
- name: Version commit and tag
|
||||
id: tag
|
||||
if: steps.changed.outputs.skip != 'true'
|
||||
env:
|
||||
BUILD: ${{ github.run_number }}
|
||||
run: |
|
||||
version="$(node scripts/nightly-prepare.ts --date "$(date -u +%Y%m%d)" --build "$BUILD" | tail -1)"
|
||||
git config user.name "github-actions[bot]"
|
||||
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
|
||||
git add -A
|
||||
git commit -q -m "chore: v$version"
|
||||
git tag "v$version"
|
||||
# Pushed with GITHUB_TOKEN, the tag does not start release.yml: the job below calls it.
|
||||
git push origin "refs/tags/v$version"
|
||||
echo "tag=v$version" >> "$GITHUB_OUTPUT"
|
||||
|
||||
release:
|
||||
needs: prepare
|
||||
if: needs.prepare.outputs.tag != ''
|
||||
permissions:
|
||||
contents: write
|
||||
uses: ./.github/workflows/release.yml
|
||||
with:
|
||||
tag: ${{ needs.prepare.outputs.tag }}
|
||||
nightly: true
|
||||
secrets: inherit
|
||||
|
||||
# Points the nightly channel at the new nightly and drops the old ones.
|
||||
channel:
|
||||
needs: [prepare, release]
|
||||
permissions:
|
||||
contents: write
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
GH_REPO: ${{ github.repository }}
|
||||
TAG: ${{ needs.prepare.outputs.tag }}
|
||||
steps:
|
||||
- name: Nightly manifest
|
||||
run: |
|
||||
if ! gh release download "$TAG" -p latest.json -D "$RUNNER_TEMP/manifest"; then
|
||||
echo "::warning::$TAG has no latest.json (unsigned build): the nightly channel stays where it was"
|
||||
exit 0
|
||||
fi
|
||||
notes="The update channel of the [nightly builds](https://github.com/$GH_REPO/releases?q=nightly&expanded=true): its latest.json is the newest nightly's, [$TAG](https://github.com/$GH_REPO/releases/tag/$TAG)."
|
||||
if gh release view nightly >/dev/null 2>&1; then
|
||||
gh release edit nightly --notes "$notes"
|
||||
else
|
||||
gh release create nightly --prerelease --target main --title "OpenIDEA Nightly" --notes "$notes"
|
||||
fi
|
||||
gh release upload nightly "$RUNNER_TEMP/manifest/latest.json" --clobber
|
||||
- name: Drop old nightlies
|
||||
run: |
|
||||
gh release list --limit 200 --json tagName,createdAt \
|
||||
--jq '[.[] | select(.tagName | test("^v.*-nightly\\."))] | sort_by(.createdAt) | reverse | .[14:][] | .tagName' |
|
||||
while read -r old; do
|
||||
gh release delete "$old" --cleanup-tag --yes
|
||||
done
|
||||
@@ -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
|
||||
@@ -18,7 +18,7 @@ jobs:
|
||||
if: github.event.pull_request.user.type != 'Bot' && !github.event.pull_request.draft
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
|
||||
- uses: actions/github-script@v8
|
||||
with:
|
||||
script: |
|
||||
const pr = context.payload.pull_request;
|
||||
@@ -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);
|
||||
|
||||
@@ -19,7 +19,6 @@ env:
|
||||
jobs:
|
||||
plugin-keys:
|
||||
permissions: {}
|
||||
environment: release
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
keys: ${{ steps.keys.outputs.keys }}
|
||||
@@ -44,7 +43,6 @@ jobs:
|
||||
contents: write
|
||||
needs: plugin-keys
|
||||
name: Build (${{ matrix.name }})
|
||||
environment: release
|
||||
env:
|
||||
OPENIDEA_OFFICIAL_PLUGIN_KEYS: ${{ needs.plugin-keys.outputs.keys }}
|
||||
strategy:
|
||||
@@ -71,15 +69,15 @@ jobs:
|
||||
target: x86_64-pc-windows-msvc
|
||||
runs-on: ${{ matrix.os }}
|
||||
steps:
|
||||
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
|
||||
- uses: actions/checkout@v5
|
||||
with: { ref: "${{ env.TAG }}" }
|
||||
- uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0
|
||||
- uses: pnpm/action-setup@v5
|
||||
with: { version: 11 }
|
||||
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
|
||||
- uses: actions/setup-node@v5
|
||||
with: { node-version: 22, cache: pnpm }
|
||||
- uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
with: { targets: "${{ matrix.target }}" }
|
||||
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
with: { key: "${{ matrix.target }}", cache-on-failure: true }
|
||||
- name: Linux deps
|
||||
if: runner.os == 'Linux'
|
||||
@@ -87,57 +85,40 @@ jobs:
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y libwebkit2gtk-4.1-dev libayatana-appindicator3-dev librsvg2-dev libxdo-dev libssl-dev patchelf
|
||||
- run: pnpm install --frozen-lockfile
|
||||
# Signing is optional: forks and unconfigured repos produce unsigned builds instead of
|
||||
# failing. The secrets go only into the steps that sign (never $GITHUB_ENV), so the other
|
||||
# steps and the actions' post steps never see them. Tauri treats a set-but-empty key as a
|
||||
# key, so the unsigned build is a separate step without the secrets.
|
||||
- name: Signing configured
|
||||
id: signing
|
||||
# Signing is optional: only secrets that are set get exported, so forks and
|
||||
# unconfigured repos produce unsigned builds instead of failing.
|
||||
- name: Signing env
|
||||
shell: bash
|
||||
env:
|
||||
UPDATER_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
|
||||
APPLE_ID: ${{ runner.os == 'macOS' && secrets.APPLE_ID || '' }}
|
||||
run: |
|
||||
echo "updater=$([ -n "$UPDATER_KEY" ] && echo true || echo false)" >> "$GITHUB_OUTPUT"
|
||||
echo "apple=$([ -n "$APPLE_ID" ] && echo true || echo false)" >> "$GITHUB_OUTPUT"
|
||||
- name: Build (signed)
|
||||
if: steps.signing.outputs.updater == 'true'
|
||||
uses: tauri-apps/tauri-action@84b9d35b5fc46c1e45415bdb6144030364f7ebc5 # v0.6.2
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
|
||||
TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }}
|
||||
APPLE_CERTIFICATE: ${{ runner.os == 'macOS' && secrets.APPLE_CERTIFICATE || '' }}
|
||||
APPLE_CERTIFICATE_PASSWORD: ${{ runner.os == 'macOS' && secrets.APPLE_CERTIFICATE_PASSWORD || '' }}
|
||||
APPLE_SIGNING_IDENTITY: ${{ runner.os == 'macOS' && secrets.APPLE_SIGNING_IDENTITY || '' }}
|
||||
APPLE_ID: ${{ runner.os == 'macOS' && secrets.APPLE_ID || '' }}
|
||||
APPLE_PASSWORD: ${{ runner.os == 'macOS' && secrets.APPLE_PASSWORD || '' }}
|
||||
APPLE_TEAM_ID: ${{ runner.os == 'macOS' && secrets.APPLE_TEAM_ID || '' }}
|
||||
with:
|
||||
releaseId: ${{ inputs.release_id }}
|
||||
tagName: ${{ env.TAG }}
|
||||
args: --target ${{ matrix.target }}
|
||||
# The parallel builds would race on one latest.json; `updater-manifest` writes it once.
|
||||
uploadUpdaterJson: false
|
||||
- name: Build (unsigned)
|
||||
if: steps.signing.outputs.updater != 'true'
|
||||
uses: tauri-apps/tauri-action@84b9d35b5fc46c1e45415bdb6144030364f7ebc5 # v0.6.2
|
||||
TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
|
||||
TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }}
|
||||
run: |
|
||||
for v in APPLE_CERTIFICATE APPLE_CERTIFICATE_PASSWORD APPLE_SIGNING_IDENTITY APPLE_ID \
|
||||
APPLE_PASSWORD APPLE_TEAM_ID TAURI_SIGNING_PRIVATE_KEY TAURI_SIGNING_PRIVATE_KEY_PASSWORD; do
|
||||
[ -n "${!v}" ] && { echo "$v<<__EOF__"; echo "${!v}"; echo "__EOF__"; } >> "$GITHUB_ENV"
|
||||
done
|
||||
true
|
||||
- uses: tauri-apps/tauri-action@v0
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
with:
|
||||
releaseId: ${{ inputs.release_id }}
|
||||
tagName: ${{ env.TAG }}
|
||||
args: --target ${{ matrix.target }}
|
||||
# The parallel builds would race on one latest.json; `updater-manifest` writes it once.
|
||||
uploadUpdaterJson: false
|
||||
# tauri-action notarizes the .app but not the DMG around it; notarize and
|
||||
# staple the DMG too, then replace the uploaded asset.
|
||||
- name: Notarize DMG
|
||||
if: runner.os == 'macOS' && steps.signing.outputs.apple == 'true'
|
||||
if: runner.os == 'macOS' && env.APPLE_ID != ''
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
APPLE_ID: ${{ secrets.APPLE_ID }}
|
||||
APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
|
||||
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
|
||||
run: |
|
||||
for dmg in target/${{ matrix.target }}/release/bundle/dmg/*.dmg; do
|
||||
xcrun notarytool submit "$dmg" --apple-id "$APPLE_ID" --password "$APPLE_PASSWORD" \
|
||||
@@ -156,8 +137,6 @@ jobs:
|
||||
shell: pwsh
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
|
||||
TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }}
|
||||
run: |
|
||||
$target = "${{ matrix.target }}"
|
||||
$arch = if ($target -like "x86_64*") { "x64" } else { "arm64" }
|
||||
@@ -197,11 +176,11 @@ jobs:
|
||||
- { runner: macos-latest, target: x86_64-apple-darwin, os: macos, arch: x86_64 }
|
||||
runs-on: ${{ matrix.runner }}
|
||||
steps:
|
||||
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
|
||||
- uses: actions/checkout@v5
|
||||
with: { ref: "${{ env.TAG }}" }
|
||||
- uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
with: { targets: "${{ matrix.target }}" }
|
||||
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
with: { key: "server-${{ matrix.target }}", cache-on-failure: true }
|
||||
- name: musl toolchain
|
||||
if: runner.os == 'Linux'
|
||||
@@ -222,45 +201,6 @@ jobs:
|
||||
if command -v sha256sum >/dev/null; then sha256sum "$ASSET"; else shasum -a 256 "$ASSET"; fi > "$ASSET.sha256"
|
||||
gh release upload "$TAG" "$ASSET" "$ASSET.sha256" --clobber
|
||||
|
||||
# Signs every server archive with the updater key (`<asset>.sig`), so the app verifies a
|
||||
# server from the CNB mirror as it does from GitHub (ide-tools `server::fetch`). Only this job
|
||||
# gets the key; without it the archives keep only their .sha256.
|
||||
server-signatures:
|
||||
permissions:
|
||||
contents: write
|
||||
needs: server
|
||||
environment: release
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Signing configured
|
||||
id: signing
|
||||
env:
|
||||
UPDATER_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
|
||||
run: echo "updater=$([ -n "$UPDATER_KEY" ] && echo true || echo false)" >> "$GITHUB_OUTPUT"
|
||||
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
|
||||
if: steps.signing.outputs.updater == 'true'
|
||||
with: { ref: "${{ env.TAG }}" }
|
||||
- uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0
|
||||
if: steps.signing.outputs.updater == 'true'
|
||||
with: { version: 11 }
|
||||
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
|
||||
if: steps.signing.outputs.updater == 'true'
|
||||
with: { node-version: 22, cache: pnpm }
|
||||
- if: steps.signing.outputs.updater == 'true'
|
||||
run: pnpm install --frozen-lockfile
|
||||
- name: Sign server archives
|
||||
if: steps.signing.outputs.updater == 'true'
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
|
||||
TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }}
|
||||
run: |
|
||||
gh release download "$TAG" -p 'openidea-server-*.gz' -D "$RUNNER_TEMP/server"
|
||||
for asset in "$RUNNER_TEMP"/server/*.gz; do
|
||||
pnpm exec tauri signer sign "$asset"
|
||||
done
|
||||
gh release upload "$TAG" "$RUNNER_TEMP"/server/*.gz.sig --clobber
|
||||
|
||||
# The updater manifest (latest.json), built once from the signed bundles every build uploaded.
|
||||
# Fails when a platform is missing, so a release never ships a manifest without it.
|
||||
updater-manifest:
|
||||
@@ -269,7 +209,7 @@ jobs:
|
||||
needs: build
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
|
||||
- uses: actions/github-script@v8
|
||||
env:
|
||||
RELEASE_ID: ${{ inputs.release_id }}
|
||||
with:
|
||||
@@ -284,8 +224,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`]],
|
||||
@@ -293,10 +231,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$/),
|
||||
|
||||
@@ -7,27 +7,19 @@ on:
|
||||
tag:
|
||||
description: "Tag to release (e.g. v0.1.0); must already exist"
|
||||
required: true
|
||||
# nightly.yml: a nightly is a prerelease whose notes start at the previous nightly, without the
|
||||
# official plugins, the CNB mirror or the Homebrew cask.
|
||||
workflow_call:
|
||||
inputs:
|
||||
tag: { type: string, required: true }
|
||||
nightly: { type: boolean, default: false }
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: release-${{ inputs.tag || github.ref_name }}
|
||||
group: release-${{ github.event.inputs.tag || github.ref_name }}
|
||||
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
CARGO_INCREMENTAL: 0
|
||||
TAG: ${{ inputs.tag || github.ref_name }}
|
||||
TAG: ${{ github.event.inputs.tag || github.ref_name }}
|
||||
COMMUNITY_PLUGINS_INDEX: https://github.com/l0ng-ai/openidea-plugins/releases/download/index/index.json
|
||||
|
||||
# The jobs that read a signing key or token, here and in the workflows called below, run in
|
||||
# the `release` environment, which holds those secrets.
|
||||
jobs:
|
||||
# Creates (or reuses) one draft release that every platform build uploads into.
|
||||
create-release:
|
||||
@@ -37,7 +29,7 @@ jobs:
|
||||
outputs:
|
||||
release_id: ${{ steps.release.outputs.id }}
|
||||
steps:
|
||||
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
|
||||
- uses: actions/checkout@v5
|
||||
with: { ref: "${{ env.TAG }}" }
|
||||
- name: Tag matches app version
|
||||
run: |
|
||||
@@ -57,9 +49,7 @@ jobs:
|
||||
exit 1
|
||||
fi
|
||||
- id: release
|
||||
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
|
||||
env:
|
||||
NIGHTLY: ${{ inputs.nightly == true }}
|
||||
uses: actions/github-script@v8
|
||||
with:
|
||||
script: |
|
||||
const tag = process.env.TAG;
|
||||
@@ -71,13 +61,8 @@ jobs:
|
||||
core.setOutput("id", existing.id);
|
||||
return;
|
||||
}
|
||||
// Prereleases are skipped: the notes span stable release to stable release. A
|
||||
// nightly's span from the newest published release, nightly or stable (not the
|
||||
// rolling `nightly` release, which only holds the channel's manifest).
|
||||
const nightly = process.env.NIGHTLY === "true";
|
||||
const previous = releases.find(
|
||||
(r) => !r.draft && r.tag_name !== "nightly" && (nightly || !r.prerelease),
|
||||
);
|
||||
// Prereleases are skipped: the notes span stable release to stable release.
|
||||
const previous = releases.find((r) => !r.draft && !r.prerelease);
|
||||
const { data: notes } = await github.rest.repos.generateReleaseNotes({
|
||||
owner, repo, tag_name: tag, previous_tag_name: previous?.tag_name,
|
||||
});
|
||||
@@ -93,7 +78,7 @@ jobs:
|
||||
needs: create-release
|
||||
uses: ./.github/workflows/release-build.yml
|
||||
with:
|
||||
tag: ${{ inputs.tag || github.ref_name }}
|
||||
tag: ${{ github.event.inputs.tag || github.ref_name }}
|
||||
release_id: ${{ needs.create-release.outputs.release_id }}
|
||||
secrets: inherit
|
||||
|
||||
@@ -111,34 +96,29 @@ jobs:
|
||||
contents: write
|
||||
needs: create-release
|
||||
name: Official plugins
|
||||
environment: release
|
||||
runs-on: ubuntu-22.04
|
||||
env:
|
||||
SIGNING_KEY: ${{ secrets.PLUGIN_SIGNING_KEY }}
|
||||
NIGHTLY: ${{ inputs.nightly == true }}
|
||||
steps:
|
||||
- id: key
|
||||
run: |
|
||||
if [ "$NIGHTLY" = true ]; then
|
||||
echo "a nightly does not publish the official plugins"
|
||||
echo "skip=true" >> "$GITHUB_OUTPUT"
|
||||
elif [ -z "$SIGNING_KEY" ]; then
|
||||
if [ -z "$SIGNING_KEY" ]; then
|
||||
echo "::warning::PLUGIN_SIGNING_KEY is not set: the official plugins are not published"
|
||||
echo "skip=true" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
|
||||
- uses: actions/checkout@v5
|
||||
if: steps.key.outputs.skip != 'true'
|
||||
with: { ref: "${{ env.TAG }}" }
|
||||
- uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
if: steps.key.outputs.skip != 'true'
|
||||
with: { targets: wasm32-wasip2 }
|
||||
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
if: steps.key.outputs.skip != 'true'
|
||||
with: { key: release-plugins }
|
||||
- uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0
|
||||
- uses: pnpm/action-setup@v5
|
||||
if: steps.key.outputs.skip != 'true'
|
||||
with: { version: 11 }
|
||||
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
|
||||
- uses: actions/setup-node@v5
|
||||
if: steps.key.outputs.skip != 'true'
|
||||
with: { node-version: 22 }
|
||||
# Builds the web pages; fails when a checked-in component isn't built from these sources.
|
||||
@@ -183,7 +163,7 @@ jobs:
|
||||
needs: [create-release, binaries, plugins]
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
|
||||
- uses: actions/github-script@v8
|
||||
env:
|
||||
RELEASE_ID: ${{ needs.create-release.outputs.release_id }}
|
||||
with:
|
||||
@@ -195,15 +175,13 @@ jobs:
|
||||
# The China mirror the updater's CNB source reads; a failure here leaves the GitHub release as is.
|
||||
cnb-mirror:
|
||||
needs: publish
|
||||
if: ${{ !inputs.nightly }}
|
||||
uses: ./.github/workflows/cnb-mirror.yml
|
||||
with: { tag: "${{ inputs.tag || github.ref_name }}" }
|
||||
with: { tag: "${{ github.event.inputs.tag || github.ref_name }}" }
|
||||
secrets: inherit
|
||||
|
||||
# The cask in l0ng-ai/homebrew-tap; skipped for prereleases and without HOMEBREW_TAP_DEPLOY_KEY.
|
||||
homebrew:
|
||||
needs: publish
|
||||
if: ${{ !inputs.nightly }}
|
||||
uses: ./.github/workflows/homebrew.yml
|
||||
with: { tag: "${{ inputs.tag || github.ref_name }}" }
|
||||
with: { tag: "${{ github.event.inputs.tag || github.ref_name }}" }
|
||||
secrets: inherit
|
||||
+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,7 +15,6 @@
|
||||
"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",
|
||||
|
||||
@@ -152,10 +152,7 @@
|
||||
"files": ["**/*.ts", "**/*.tsx", "**/*.mts", "**/*.cts"],
|
||||
"excludeFiles": ["e2e/**"],
|
||||
"rules": {
|
||||
"no-await-in-loop": "error",
|
||||
"react/no-array-index-key": "error",
|
||||
"react/jsx-no-constructed-context-values": "error",
|
||||
"react/no-object-type-as-default-prop": "error"
|
||||
"no-await-in-loop": "error"
|
||||
}
|
||||
}
|
||||
]
|
||||
|
||||
@@ -1,197 +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:all <remote_name> [--restart | --no-restart]` (or `mise run dogfood:all <remote_name>`) — run `dogfood:local` and `dogfood:remote <remote_name>` in parallel.
|
||||
- `cargo nextest run --workspace` (or `cargo test`), `cargo clippy --workspace --all-targets -- -D warnings`, `cargo fmt --all`.
|
||||
- `cargo test -p ide-host --test language_smoke -- --ignored --exact <language>` — code intelligence
|
||||
on `fixtures/` with that language's real server installed (CI: `Language smoke`, pinned versions).
|
||||
- `pnpm smoke smoke/run.test.ts -t <language>` — run and test that language's fixture through the
|
||||
run store and a real `openidea-server` (build it first: `cargo build -p ide-host --bin openidea-server`).
|
||||
- `pnpm smoke smoke/debug.test.ts -t <language>` — debug that fixture's entry point the same way, with
|
||||
the debugger the IDE installs (on macOS, CodeLLDB and Delve may need Developer Mode:
|
||||
`sudo DevToolsSecurity -enable`).
|
||||
- `pnpm test`, `pnpm e2e`, `pnpm lint`, `pnpm format:check`, `pnpm knip`, `pnpm typecheck`,
|
||||
`pnpm gen:bindings`.
|
||||
- `pnpm perf` (UI interaction latency / frames / leaks), `pnpm perf:rust` (criterion
|
||||
benches vs budgets). Budgets: `perf/budgets.json`.
|
||||
- `pnpm eval [--only <id>] [--runs n] [--save-baseline]` — Java code intelligence (navigation,
|
||||
usages, gutter markers) in the production workbench against a release `openidea-server` and
|
||||
jdtls: time to feedback / first result / complete, results vs `evals/<language>/golden/`.
|
||||
Report: `target/eval/report.json`. Goldens and `evals/budgets.json` are changed by people only.
|
||||
Tool versions: `.github/tool-versions.env` (shared with Language smoke).
|
||||
- `pnpm release:prepare <version>` — the release commit's changes: app version everywhere,
|
||||
`Cargo.lock`, and the plugin API snapshot when `wit/` moved to a new version.
|
||||
|
||||
## Before opening a PR
|
||||
|
||||
Run what CI runs for the parts you touched:
|
||||
|
||||
- Rust: `cargo fmt --all --check`, `cargo clippy --workspace --all-targets -- -D warnings`,
|
||||
`cargo nextest run --workspace`. After changing IPC types, run `pnpm gen:bindings` and
|
||||
commit `src/bindings.ts`; CI fails if it differs.
|
||||
- Frontend: `pnpm typecheck` (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.
|
||||
Створено
+55
-125
@@ -252,9 +252,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "async-executor"
|
||||
version = "1.14.1"
|
||||
version = "1.14.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f426a31126c735126297bc5ea7a521263c9faff4f63ca415267ee625651c4f37"
|
||||
checksum = "c96bf972d85afc50bf5ab8fe2d54d1586b4e0b46c97c50a0c9e71e2f7bcd812a"
|
||||
dependencies = [
|
||||
"async-task",
|
||||
"concurrent-queue",
|
||||
@@ -1552,9 +1552,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "curve25519-dalek"
|
||||
version = "5.1.0"
|
||||
version = "5.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "94c1aa5a9b7626ed65ac0cf5ea9d4f1547af89017fbac20bd4de40022fff516f"
|
||||
checksum = "b5eed333089e2e1c1ac8c6c0398e5e2497b4c9926ca6d0365ed1e099afa5bc23"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"cpufeatures 0.3.1",
|
||||
@@ -2766,7 +2766,6 @@ dependencies = [
|
||||
"gix-ignore",
|
||||
"gix-index",
|
||||
"gix-lock",
|
||||
"gix-mailmap",
|
||||
"gix-note",
|
||||
"gix-object",
|
||||
"gix-odb",
|
||||
@@ -3133,18 +3132,6 @@ dependencies = [
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gix-mailmap"
|
||||
version = "0.36.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a30866257cc7f0af5b85f98a9e87dc73e46de8cb1838ee18c9dbe08a2461717e"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"gix-actor",
|
||||
"gix-date",
|
||||
"gix-error",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gix-note"
|
||||
version = "0.3.1"
|
||||
@@ -4167,7 +4154,7 @@ checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
|
||||
|
||||
[[package]]
|
||||
name = "ide-agent"
|
||||
version = "0.1.56"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
@@ -4179,26 +4166,23 @@ dependencies = [
|
||||
"ide-tools",
|
||||
"ide-vcs",
|
||||
"ide-vfs",
|
||||
"jiff",
|
||||
"parking_lot 0.12.5",
|
||||
"rustix",
|
||||
"semver",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha1 0.10.7",
|
||||
"specta",
|
||||
"sqlx",
|
||||
"tempfile",
|
||||
"tokio",
|
||||
"toml 0.9.12+spec-1.1.0",
|
||||
"toml_edit 0.25.17+spec-1.1.0",
|
||||
"tracing",
|
||||
"uuid",
|
||||
"which",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ide-analysis"
|
||||
version = "0.1.56"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"ast-grep-core",
|
||||
"ide-core",
|
||||
@@ -4210,11 +4194,10 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-android"
|
||||
version = "0.1.56"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"specta",
|
||||
"tempfile",
|
||||
"which",
|
||||
@@ -4222,7 +4205,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-build"
|
||||
version = "0.1.56"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"chardetng",
|
||||
@@ -4240,7 +4223,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-cli"
|
||||
version = "0.1.56"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"serde",
|
||||
@@ -4254,7 +4237,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-clipboard"
|
||||
version = "0.1.56"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"gtk",
|
||||
"objc2 0.6.5",
|
||||
@@ -4265,7 +4248,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-command"
|
||||
version = "0.1.56"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"heck 0.5.0",
|
||||
"proc-macro2",
|
||||
@@ -4276,7 +4259,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-core"
|
||||
version = "0.1.56"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"dirs 6.0.0",
|
||||
@@ -4298,7 +4281,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-coverage"
|
||||
version = "0.1.56"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-run",
|
||||
@@ -4311,7 +4294,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-dap"
|
||||
version = "0.1.56"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"futures",
|
||||
@@ -4322,7 +4305,6 @@ dependencies = [
|
||||
"ide-jvm-attach",
|
||||
"ide-jvm-inspect",
|
||||
"ide-language",
|
||||
"ide-run",
|
||||
"libc",
|
||||
"memchr",
|
||||
"parking_lot 0.12.5",
|
||||
@@ -4341,7 +4323,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-db"
|
||||
version = "0.1.56"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"bb8",
|
||||
@@ -4380,7 +4362,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-docker"
|
||||
version = "0.1.56"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"serde",
|
||||
@@ -4393,7 +4375,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-drag-out"
|
||||
version = "0.1.56"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"gtk",
|
||||
"objc2 0.6.5",
|
||||
@@ -4407,7 +4389,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-extension"
|
||||
version = "0.1.56"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
@@ -4427,7 +4409,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-flutter"
|
||||
version = "0.1.56"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"ide-android",
|
||||
"ide-core",
|
||||
@@ -4438,7 +4420,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-fonts"
|
||||
version = "0.1.56"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"objc2-core-foundation",
|
||||
"objc2-core-text",
|
||||
@@ -4450,7 +4432,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-github"
|
||||
version = "0.1.56"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-vcs",
|
||||
@@ -4462,7 +4444,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-heap"
|
||||
version = "0.1.56"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"ide-core",
|
||||
@@ -4481,7 +4463,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-host"
|
||||
version = "0.1.56"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
@@ -4508,7 +4490,6 @@ dependencies = [
|
||||
"ide-docker",
|
||||
"ide-extension",
|
||||
"ide-flutter",
|
||||
"ide-github",
|
||||
"ide-heap",
|
||||
"ide-http",
|
||||
"ide-index",
|
||||
@@ -4528,7 +4509,6 @@ dependencies = [
|
||||
"ide-spell",
|
||||
"ide-ssh",
|
||||
"ide-streams",
|
||||
"ide-svn",
|
||||
"ide-syntax",
|
||||
"ide-terminal",
|
||||
"ide-text",
|
||||
@@ -4539,7 +4519,6 @@ dependencies = [
|
||||
"ide-workspace",
|
||||
"ignore",
|
||||
"jsonschema",
|
||||
"notify",
|
||||
"parking_lot 0.12.5",
|
||||
"quick-xml 0.42.0",
|
||||
"regex-lite",
|
||||
@@ -4565,15 +4544,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-http"
|
||||
version = "0.1.56"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"http",
|
||||
"hyper-util",
|
||||
"ide-core",
|
||||
"ide-vfs",
|
||||
"objc2-cf-network",
|
||||
"objc2-core-foundation",
|
||||
"parking_lot 0.12.5",
|
||||
"reqwest",
|
||||
"rustls",
|
||||
@@ -4588,7 +4563,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-index"
|
||||
version = "0.1.56"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"criterion",
|
||||
@@ -4611,7 +4586,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jdwp"
|
||||
version = "0.1.56"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"ide-jvm-inspect",
|
||||
"proptest",
|
||||
@@ -4623,7 +4598,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jsonrpc"
|
||||
version = "0.1.56"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"ide-core",
|
||||
@@ -4639,7 +4614,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jvm-attach"
|
||||
version = "0.1.56"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"tempfile",
|
||||
@@ -4648,7 +4623,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jvm-inspect"
|
||||
version = "0.1.56"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"futures",
|
||||
"serde",
|
||||
@@ -4659,7 +4634,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-language"
|
||||
version = "0.1.56"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"criterion",
|
||||
@@ -4700,7 +4675,6 @@ dependencies = [
|
||||
"tree-sitter-make",
|
||||
"tree-sitter-md",
|
||||
"tree-sitter-nix",
|
||||
"tree-sitter-objc",
|
||||
"tree-sitter-ocaml",
|
||||
"tree-sitter-php",
|
||||
"tree-sitter-prisma-io",
|
||||
@@ -4719,7 +4693,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-lsp"
|
||||
version = "0.1.56"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"dunce",
|
||||
@@ -4749,7 +4723,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-mcp"
|
||||
version = "0.1.56"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"dunce",
|
||||
@@ -4768,24 +4742,20 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-notebook"
|
||||
version = "0.1.56"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"futures",
|
||||
"ide-core",
|
||||
"ide-http",
|
||||
"ide-vfs",
|
||||
"jupyter-protocol",
|
||||
"jupyter-zmq-client",
|
||||
"libc",
|
||||
"parking_lot 0.12.5",
|
||||
"reqwest",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"specta",
|
||||
"specta-typescript",
|
||||
"tempfile",
|
||||
"tokio",
|
||||
"tokio-tungstenite",
|
||||
"uuid",
|
||||
"windows-sys 0.61.2",
|
||||
"zeromq",
|
||||
@@ -4793,7 +4763,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-plugin"
|
||||
version = "0.1.56"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -4815,7 +4785,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-profiler"
|
||||
version = "0.1.56"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-jvm-attach",
|
||||
@@ -4829,7 +4799,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-remote"
|
||||
version = "0.1.56"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"futures",
|
||||
@@ -4849,9 +4819,8 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-run"
|
||||
version = "0.1.56"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
"encoding_rs",
|
||||
"ide-build",
|
||||
@@ -4862,7 +4831,6 @@ dependencies = [
|
||||
"parking_lot 0.12.5",
|
||||
"portable-pty",
|
||||
"quick-xml 0.42.0",
|
||||
"regex",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"specta",
|
||||
@@ -4876,7 +4844,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-scaffold"
|
||||
version = "0.1.56"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-tools",
|
||||
@@ -4892,7 +4860,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-sdk"
|
||||
version = "0.1.56"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"dirs 6.0.0",
|
||||
@@ -4918,7 +4886,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-search"
|
||||
version = "0.1.56"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"encoding_rs",
|
||||
@@ -4939,7 +4907,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-spell"
|
||||
version = "0.1.56"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"parking_lot 0.12.5",
|
||||
@@ -4952,7 +4920,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-ssh"
|
||||
version = "0.1.56"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"flate2",
|
||||
@@ -4977,7 +4945,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-streams"
|
||||
version = "0.1.56"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-language",
|
||||
@@ -4988,24 +4956,9 @@ dependencies = [
|
||||
"tree-sitter",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ide-svn"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"encoding_rs",
|
||||
"ide-core",
|
||||
"ide-vcs",
|
||||
"parking_lot 0.12.5",
|
||||
"quick-xml 0.42.0",
|
||||
"tempfile",
|
||||
"which",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ide-syntax"
|
||||
version = "0.1.56"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-language",
|
||||
@@ -5020,7 +4973,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-terminal"
|
||||
version = "0.1.56"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"libc",
|
||||
@@ -5034,7 +4987,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-text"
|
||||
version = "0.1.56"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"ide-core",
|
||||
@@ -5047,19 +5000,15 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-tools"
|
||||
version = "0.1.56"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
"flate2",
|
||||
"hex",
|
||||
"http",
|
||||
"hyper-util",
|
||||
"ide-core",
|
||||
"ide-http",
|
||||
"ide-language",
|
||||
"libc",
|
||||
"minisign-verify",
|
||||
"parking_lot 0.12.5",
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -5074,7 +5023,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-vcs"
|
||||
version = "0.1.56"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -5096,7 +5045,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-vfs"
|
||||
version = "0.1.56"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"chardetng",
|
||||
"dunce",
|
||||
@@ -5123,7 +5072,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-web"
|
||||
version = "0.1.56"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"ide-core",
|
||||
@@ -5139,7 +5088,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-workspace"
|
||||
version = "0.1.56"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -5149,7 +5098,6 @@ dependencies = [
|
||||
"ide-text",
|
||||
"ide-vfs",
|
||||
"parking_lot 0.12.5",
|
||||
"quick-xml 0.42.0",
|
||||
"semver",
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -6371,15 +6319,6 @@ dependencies = [
|
||||
"objc2-quartz-core 0.3.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "objc2-cf-network"
|
||||
version = "0.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4b4c9e30e636e2cd7d7414f320af2e0aa86f686adfc6f1bbe50b92366e4309c8"
|
||||
dependencies = [
|
||||
"objc2-core-foundation",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "objc2-cloud-kit"
|
||||
version = "0.2.2"
|
||||
@@ -6788,7 +6727,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "openidea"
|
||||
version = "0.1.56"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
@@ -6808,6 +6747,7 @@ dependencies = [
|
||||
"ide-drag-out",
|
||||
"ide-extension",
|
||||
"ide-fonts",
|
||||
"ide-github",
|
||||
"ide-host",
|
||||
"ide-http",
|
||||
"ide-jsonrpc",
|
||||
@@ -9894,7 +9834,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
|
||||
dependencies = [
|
||||
"fastrand",
|
||||
"getrandom 0.3.4",
|
||||
"getrandom 0.4.3",
|
||||
"once_cell",
|
||||
"rustix",
|
||||
"windows-sys 0.61.2",
|
||||
@@ -10675,16 +10615,6 @@ dependencies = [
|
||||
"tree-sitter-language",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tree-sitter-objc"
|
||||
version = "3.0.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9ca8bb556423fc176f0535e79d525f783a6684d3c9da81bf9d905303c129e1d2"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"tree-sitter-language",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tree-sitter-ocaml"
|
||||
version = "0.26.0"
|
||||
|
||||
+1
-5
@@ -5,7 +5,7 @@ members = ["crates/*", "src-tauri"]
|
||||
exclude = ["sdk", "plugins"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.1.56"
|
||||
version = "0.1.54"
|
||||
edition = "2024"
|
||||
rust-version = "1.96"
|
||||
license = "Apache-2.0"
|
||||
@@ -24,8 +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" }
|
||||
ide-workspace = { path = "crates/ide-workspace" }
|
||||
@@ -91,7 +89,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 +98,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"
|
||||
|
||||
@@ -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.
|
||||
|
||||
+1
-1
@@ -71,7 +71,7 @@ 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-4.png" alt="WeChat group QR code" width="200">
|
||||
|
||||
+1
-1
@@ -71,7 +71,7 @@ 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-4.png" alt="WeChat grubu QR kodu" width="200">
|
||||
|
||||
@@ -69,7 +69,7 @@ WebAssembly 组件运行;主题、图标主题和语言无需编写代码。
|
||||
|
||||
## 社区
|
||||
|
||||
- [Discord](https://discord.gg/AsZqMgxZm):提问、反馈和版本发布消息。
|
||||
- [Discord](https://discord.gg/2Zy4yn7gP):提问、反馈和版本发布消息。
|
||||
- 微信群,扫码加入:
|
||||
|
||||
<img src=".github/assets/wechat-group-4.png" alt="微信群二维码" width="200">
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
`src/ui/brands/*.svg` use the unmodified logo paths from
|
||||
[Simple Icons](https://github.com/simple-icons/simple-icons), retrieved through
|
||||
Iconify (`simple-icons:angular`, `simple-icons:astro`, `simple-icons:cplusplus`, `simple-icons:dart`, `simple-icons:deepseek`, `simple-icons:django`, `simple-icons:dotnet`, `simple-icons:elixir`, `simple-icons:express`, `simple-icons:fastapi`, `simple-icons:flask`, `simple-icons:flutter`, `simple-icons:go`, `simple-icons:haskell`, `simple-icons:html5`, `simple-icons:kotlin`, `simple-icons:ktor`, `simple-icons:laravel`, `simple-icons:nestjs`, `simple-icons:nextdotjs`, `simple-icons:nodedotjs`, `simple-icons:nuxt`, `simple-icons:openjdk`, `simple-icons:phoenixframework`, `simple-icons:php`, `simple-icons:python`, `simple-icons:quarkus`, `simple-icons:ruby`, `simple-icons:rubyonrails`, `simple-icons:rust`, `simple-icons:scala`, `simple-icons:springboot`, `simple-icons:svelte`, `simple-icons:swift`, `simple-icons:symfony`, `simple-icons:vite`, `simple-icons: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
|
||||
|
||||
|
||||
@@ -18,18 +18,15 @@ 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"
|
||||
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
rustix = { version = "1", features = ["fs"] }
|
||||
|
||||
@@ -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!({
|
||||
|
||||
@@ -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
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -58,9 +58,7 @@ 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 Ok(npm) = which::which("npm") else { return Ok(AgentCliUpdateResult::Unmanaged) };
|
||||
let program = spec.resolve_for_launch(&self.shared.paths.project_root).command;
|
||||
match maintain(&npm, Path::new(&program), &builtin.command, pkg, offer, cancel) {
|
||||
Err(e) if e.kind == ErrorKind::Unavailable => Ok(AgentCliUpdateResult::Error { code: e.message }),
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
//! the agent reports them over ACP.
|
||||
|
||||
use crate::model::{
|
||||
AgentCommand, AgentCommandChoice, AgentCommandSource, AgentConfigOption, AgentConfigValue, AgentConfigVia,
|
||||
AgentCost, AgentLimit, AgentModelPricing, AgentTokens, AgentUsage,
|
||||
AgentCommand, AgentCommandSource, AgentConfigOption, AgentConfigValue, AgentConfigVia, AgentCost, AgentLimit,
|
||||
AgentModelPricing, AgentTokens, AgentUsage,
|
||||
};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
@@ -54,21 +54,6 @@ pub(crate) fn bypass_approvals(config: &[AgentConfigOption]) -> bool {
|
||||
.any(|category| selected(category).zip(bypass_value(category)).is_some_and(|(value, bypass)| bypass(value)))
|
||||
}
|
||||
|
||||
/// Canonical snapshot of approval-bearing config options (`mode`, `permissions`, `approval`)
|
||||
/// so auto-resume can refuse to run silently if permission policy drifted while closed.
|
||||
pub(crate) fn approval_fingerprint(config: &[AgentConfigOption]) -> Option<String> {
|
||||
let mut parts: Vec<String> = config
|
||||
.iter()
|
||||
.filter(|o| matches!(o.category.as_deref(), Some("mode" | "permissions" | "approval")))
|
||||
.filter_map(|o| Some(format!("{}={}", o.id, o.current.as_deref()?)))
|
||||
.collect();
|
||||
if parts.is_empty() {
|
||||
return None;
|
||||
}
|
||||
parts.sort();
|
||||
Some(parts.join(";"))
|
||||
}
|
||||
|
||||
/// For an option of `category` that can approve everything, what tells its approving values.
|
||||
fn bypass_value(category: &str) -> Option<fn(&str) -> bool> {
|
||||
match category {
|
||||
@@ -131,263 +116,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"))
|
||||
}
|
||||
|
||||
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`,
|
||||
@@ -549,30 +278,11 @@ pub(crate) fn commands_of(update: &Value, provider: &str) -> Vec<AgentCommand> {
|
||||
} else {
|
||||
c.get("source").and_then(|s| serde_json::from_value(s.clone()).ok()).unwrap_or_default()
|
||||
};
|
||||
let mut seen_choices = std::collections::HashSet::new();
|
||||
let choices = c
|
||||
.pointer("/input/choices")
|
||||
.and_then(Value::as_array)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|ch| {
|
||||
let choice_name =
|
||||
ch.get("name").and_then(Value::as_str).map(str::trim).filter(|n| !n.is_empty())?;
|
||||
if !seen_choices.insert(choice_name.to_ascii_lowercase()) {
|
||||
return None;
|
||||
}
|
||||
Some(AgentCommandChoice {
|
||||
name: choice_name.to_owned(),
|
||||
description: str_of(ch, "description").unwrap_or_default(),
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
Some(AgentCommand {
|
||||
name: name.to_owned(),
|
||||
source,
|
||||
description: str_of(c, "description").unwrap_or_default(),
|
||||
hint: c.pointer("/input/hint").and_then(Value::as_str).filter(|h| !h.is_empty()).map(str::to_owned),
|
||||
choices,
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
@@ -925,87 +635,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": [
|
||||
@@ -1025,7 +654,6 @@ mod tests {
|
||||
let old: AgentCommand =
|
||||
serde_json::from_value(json!({"name": "review", "description": "Review", "hint": null})).unwrap();
|
||||
assert_eq!(old.source, AgentCommandSource::Command);
|
||||
assert!(old.choices.is_empty());
|
||||
let skill = AgentCommand { source: AgentCommandSource::Skill, ..old };
|
||||
assert_eq!(serde_json::from_value::<AgentCommand>(serde_json::to_value(&skill).unwrap()).unwrap(), skill);
|
||||
}
|
||||
@@ -1035,30 +663,13 @@ mod tests {
|
||||
let cmds = commands_of(
|
||||
&json!({"availableCommands": [
|
||||
{"name": "review", "description": "Review changes", "input": {"hint": "what to review"}},
|
||||
{"name": "/init", "description": "Write CLAUDE.md", "input": null},
|
||||
{"name": "skills", "description": "Manage skills", "input": {
|
||||
"hint": "[list|info]",
|
||||
"choices": [
|
||||
{"name": "list", "description": "List all available skills"},
|
||||
{"name": "LIST", "description": "Duplicate ignored"},
|
||||
{"name": " ", "description": "Blank ignored"},
|
||||
{"name": "info", "description": "Show details for a skill"}
|
||||
]
|
||||
}}
|
||||
{"name": "/init", "description": "Write CLAUDE.md", "input": null}
|
||||
]}),
|
||||
"claude",
|
||||
);
|
||||
assert_eq!(cmds[0].source, AgentCommandSource::Command);
|
||||
assert_eq!(cmds[0].hint.as_deref(), Some("what to review"));
|
||||
assert!(cmds[0].choices.is_empty());
|
||||
assert_eq!((cmds[1].name.as_str(), cmds[1].hint.as_ref()), ("init", None));
|
||||
assert_eq!(
|
||||
cmds[2].choices,
|
||||
vec![
|
||||
AgentCommandChoice { name: "list".into(), description: "List all available skills".into() },
|
||||
AgentCommandChoice { name: "info".into(), description: "Show details for a skill".into() },
|
||||
]
|
||||
);
|
||||
let u = usage_of(&json!({"used": 1200, "size": 200000, "cost": {"amount": 0.42, "currency": "USD"}})).unwrap();
|
||||
assert_eq!((u.used, u.size), (1200, 200000));
|
||||
assert!(usage_of(&json!({"used": 1, "size": 0})).is_none());
|
||||
|
||||
@@ -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,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
+356
-2572
File diff suppressed because it is too large.
Load diff
@@ -68,25 +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,
|
||||
}
|
||||
}
|
||||
|
||||
/// 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)
|
||||
}
|
||||
@@ -415,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 {
|
||||
@@ -1062,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();
|
||||
@@ -1107,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();
|
||||
@@ -1270,8 +1259,6 @@ mod tests {
|
||||
headers: Vec::new(),
|
||||
agents: Vec::new(),
|
||||
unapproved: false,
|
||||
plugin_id: None,
|
||||
plugin_name: None,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -49,75 +49,6 @@ pub struct AgentCapabilities {
|
||||
pub context_usage: bool,
|
||||
}
|
||||
|
||||
/// Why `AgentManager` is shutting down its live tasks.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub enum AgentShutdownReason {
|
||||
WindowClose,
|
||||
#[default]
|
||||
Quit,
|
||||
Restart,
|
||||
BackendUpgrade,
|
||||
BackendStop,
|
||||
}
|
||||
|
||||
/// Why an in-flight turn stopped before completing.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum InterruptionReason {
|
||||
WindowClose,
|
||||
Quit,
|
||||
Restart,
|
||||
BackendUpgrade,
|
||||
BackendStop,
|
||||
UnexpectedExit,
|
||||
NetworkTimeout,
|
||||
CursorCapacity,
|
||||
}
|
||||
|
||||
impl From<AgentShutdownReason> for InterruptionReason {
|
||||
fn from(reason: AgentShutdownReason) -> Self {
|
||||
match reason {
|
||||
AgentShutdownReason::WindowClose => Self::WindowClose,
|
||||
AgentShutdownReason::Quit => Self::Quit,
|
||||
AgentShutdownReason::Restart => Self::Restart,
|
||||
AgentShutdownReason::BackendUpgrade => Self::BackendUpgrade,
|
||||
AgentShutdownReason::BackendStop => Self::BackendStop,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Recovery metadata recorded when an active turn was interrupted before finishing.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentInterrupted {
|
||||
pub reason: InterruptionReason,
|
||||
pub at_ms: f64,
|
||||
#[serde(default, skip_serializing_if = "is_false")]
|
||||
pub was_waiting_for_input: bool,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub approval_mode: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "is_false")]
|
||||
pub auto_resume_once: bool,
|
||||
}
|
||||
|
||||
/// Summary returned when reconciling interrupted tasks for a connected project window.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentRecoveryReport {
|
||||
/// Unique identifier of this `AgentManager` process incarnation.
|
||||
pub instance_id: String,
|
||||
/// `true` on the first reconciliation of this `AgentManager` incarnation.
|
||||
pub first_reconcile: bool,
|
||||
/// Task IDs automatically resumed during this reconciliation.
|
||||
pub auto_resumed: Vec<String>,
|
||||
/// Task IDs remaining in `Interrupted` (`Ask to resume`).
|
||||
pub interrupted: Vec<String>,
|
||||
}
|
||||
|
||||
fn is_false(b: &bool) -> bool {
|
||||
!*b
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum Isolation {
|
||||
@@ -182,28 +113,10 @@ pub struct AgentTask {
|
||||
/// Per-session skill modes (`skill name` -> mode), on top of the settings' policies.
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub skill_overrides: BTreeMap<String, AgentSkillMode>,
|
||||
/// Per-session memory overrides (auto-memory mode and per-entry modes), boxed to keep `AgentEvent::Task` small.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub memory_overrides: Option<Box<AgentMemoryOverrides>>,
|
||||
/// Token counts of the last turn and context compressions, when the agent reports them.
|
||||
// Boxed so that `AgentEvent::Task` stays within clippy's `large_enum_variant` bound on Windows.
|
||||
#[serde(default)]
|
||||
pub stats: Box<AgentSessionStats>,
|
||||
/// Set when the task's last active turn was interrupted (window close, restart, crash, or
|
||||
/// expired network retry window) and has not been resumed or dismissed yet.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub interrupted: Option<Box<AgentInterrupted>>,
|
||||
/// Persisted unseen reply / input / failure state across window closes and remote reattaches.
|
||||
#[serde(default, skip_serializing_if = "is_false")]
|
||||
pub unread: bool,
|
||||
/// 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>>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
@@ -246,9 +159,6 @@ pub struct AgentRetry {
|
||||
/// When the next attempt starts (ms since the epoch).
|
||||
pub retry_at_ms: f64,
|
||||
pub error: Option<String>,
|
||||
/// Set when OpenIDEA holds an active turn in `Waiting for network` until `deadline_ms`.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub deadline_ms: Option<f64>,
|
||||
}
|
||||
|
||||
/// Token pricing (Credits per 1M tokens) and context window capacity for one tier.
|
||||
@@ -345,14 +255,6 @@ pub enum AgentCommandSource {
|
||||
Skill,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentCommandChoice {
|
||||
pub name: String,
|
||||
#[serde(default)]
|
||||
pub description: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentCommand {
|
||||
@@ -363,9 +265,6 @@ pub struct AgentCommand {
|
||||
pub hint: Option<String>,
|
||||
#[serde(default)]
|
||||
pub source: AgentCommandSource,
|
||||
/// Fixed subcommand/argument choices advertised by the agent (e.g. `list`, `info` for `/skills`).
|
||||
#[serde(default)]
|
||||
pub choices: Vec<AgentCommandChoice>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
@@ -390,9 +289,6 @@ pub struct AgentContextUsage {
|
||||
pub model: String,
|
||||
pub is_auto_compact_enabled: Option<bool>,
|
||||
pub auto_compact_threshold: Option<u32>,
|
||||
/// Tokens reserved for model response / output buffer, when the agent reports it.
|
||||
#[serde(default)]
|
||||
pub reserved_tokens: Option<u32>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
@@ -400,16 +296,13 @@ pub struct AgentContextCategory {
|
||||
pub name: String,
|
||||
pub tokens: u32,
|
||||
pub kind: Option<String>,
|
||||
/// Visual section group (e.g. `"System"`, `"User Context"`).
|
||||
#[serde(default)]
|
||||
pub group: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentCost {
|
||||
pub amount: f64,
|
||||
/// ISO 4217 code (e.g. `USD`), or `"credits"` for AI-credit billing.
|
||||
/// ISO 4217 code, e.g. `USD`.
|
||||
pub currency: String,
|
||||
}
|
||||
|
||||
@@ -432,9 +325,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 {
|
||||
@@ -462,29 +352,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`].
|
||||
@@ -639,12 +511,6 @@ pub enum AgentEntry {
|
||||
/// Sent into a running turn rather than starting one.
|
||||
#[serde(default)]
|
||||
steered: bool,
|
||||
/// 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,
|
||||
@@ -681,9 +547,6 @@ pub enum AgentEntry {
|
||||
started_ms: Option<f64>,
|
||||
#[serde(default)]
|
||||
ended_ms: Option<f64>,
|
||||
/// The command an `execute` call runs, from its structured input; `None` when the agent gave none.
|
||||
#[serde(default)]
|
||||
command: Option<String>,
|
||||
},
|
||||
Plan {
|
||||
items: Vec<AgentPlanItem>,
|
||||
@@ -867,10 +730,6 @@ pub struct NewAgentTask {
|
||||
/// Per-session skill modes (`skill name` -> mode).
|
||||
#[serde(default)]
|
||||
pub skill_overrides: BTreeMap<String, AgentSkillMode>,
|
||||
/// Per-session memory overrides (auto-memory mode and per-entry modes).
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub memory_overrides: Option<AgentMemoryOverrides>,
|
||||
/// Creates the task without sending `prompt` (it only names the task): the composer's
|
||||
/// `!` command runs in it first.
|
||||
#[serde(default)]
|
||||
@@ -949,7 +808,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.
|
||||
@@ -1012,7 +871,7 @@ pub enum AgentEvent {
|
||||
pub use ide_core::settings::{AgentMcpServer, McpTransport};
|
||||
|
||||
/// Where an MCP server configuration is stored (`settings.toml` vs `.openidea/settings.toml`).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, Type)]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum McpScope {
|
||||
User,
|
||||
@@ -1047,14 +906,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>,
|
||||
}
|
||||
|
||||
/// Payload for creating or updating a user or workspace MCP server.
|
||||
@@ -1087,231 +938,7 @@ fn default_true() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
pub use ide_core::settings::{
|
||||
AgentMemoryEntryPolicy, AgentMemoryMode, AgentMemorySettings, AgentPluginEntryPolicy, AgentPluginSettings,
|
||||
AgentProviderMemoryPolicy, AgentSkillMode, AgentSkillPolicy, AutoMemoryMode,
|
||||
};
|
||||
|
||||
/// Kind of discovered agent memory entry.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum AgentMemoryKind {
|
||||
/// Always-loaded instruction document (`AGENTS.md`, `CLAUDE.md`, `copilot-instructions.md`, `GEMINI.md`).
|
||||
#[default]
|
||||
Instruction,
|
||||
/// Path-scoped or conditional rule (`.claude/rules/*.md`, `*.instructions.md`, `.cursor/rules/*.mdc`).
|
||||
Rule,
|
||||
/// Agent-authored cross-session memory note (`MEMORY.md`, Claude topic files, Codex summaries, Hermes `USER.md`).
|
||||
AutoNote,
|
||||
}
|
||||
|
||||
/// Which workspace, user, or CLI store a memory entry was discovered in.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum AgentMemorySource {
|
||||
/// Portable workspace instructions: `AGENTS.md`, `AGENTS.override.md`.
|
||||
#[default]
|
||||
Workspace,
|
||||
/// `CLAUDE.md`, `.claude/CLAUDE.md`, `CLAUDE.local.md`, `.claude/rules/**`.
|
||||
ClaudeWorkspace,
|
||||
/// `~/.claude/CLAUDE.md`, `~/.claude/rules/**`.
|
||||
ClaudeUser,
|
||||
/// `~/.claude/projects/<repo>/memory/**` (or custom `autoMemoryDirectory`).
|
||||
ClaudeAuto,
|
||||
/// `.github/copilot-instructions.md`, `.github/instructions/**/*.instructions.md`.
|
||||
GithubWorkspace,
|
||||
/// `~/.copilot/copilot-instructions.md`, `~/.copilot/instructions/**/*.instructions.md`.
|
||||
CopilotUser,
|
||||
/// `~/.codex/AGENTS.md`, `~/.codex/AGENTS.override.md`.
|
||||
CodexUser,
|
||||
/// `~/.codex/memories/**` / `~/.codex/memories_v2/**`.
|
||||
CodexAuto,
|
||||
/// `.cursor/rules/**/*.mdc`, `.cursorrules`.
|
||||
CursorWorkspace,
|
||||
/// `GEMINI.md`.
|
||||
GeminiWorkspace,
|
||||
/// `~/.gemini/GEMINI.md`.
|
||||
GeminiUser,
|
||||
/// `<hermes_profile>/memories/{MEMORY.md,USER.md}`.
|
||||
HermesAuto,
|
||||
}
|
||||
|
||||
impl AgentMemorySource {
|
||||
/// True when the entry lives inside the current workspace and requires Workspace Trust.
|
||||
pub fn is_workspace(self) -> bool {
|
||||
matches!(
|
||||
self,
|
||||
Self::Workspace
|
||||
| Self::ClaudeWorkspace
|
||||
| Self::GithubWorkspace
|
||||
| Self::CursorWorkspace
|
||||
| Self::GeminiWorkspace
|
||||
)
|
||||
}
|
||||
|
||||
/// True when the entry is an agent's learned cross-session auto-memory store.
|
||||
pub fn is_auto(self) -> bool {
|
||||
matches!(self, Self::ClaudeAuto | Self::CodexAuto | Self::HermesAuto)
|
||||
}
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
#[default]
|
||||
None,
|
||||
Session,
|
||||
Workspace,
|
||||
User,
|
||||
/// Locked `Off` because the workspace is untrusted.
|
||||
Trust,
|
||||
}
|
||||
|
||||
/// One discovered instruction file, rule file, or learned auto-memory note.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentMemoryEntry {
|
||||
/// Stable identifier (`"<source>::<rel_key>"`).
|
||||
pub id: String,
|
||||
pub title: String,
|
||||
pub description: String,
|
||||
pub kind: AgentMemoryKind,
|
||||
pub source: AgentMemorySource,
|
||||
/// Secondary sources whose symlink or `@AGENTS.md` import resolved to this same canonical file.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub also_in: Vec<AgentMemorySource>,
|
||||
/// Canonical file path on disk.
|
||||
pub path: IpcPath,
|
||||
/// Normalized path-scoping globs (`paths:` in Claude, `applyTo:` in Copilot, `globs:` in Cursor).
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub paths: Vec<String>,
|
||||
/// Optional memory category (`user`, `feedback`, `project`, `reference`, `profile`).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub category: Option<String>,
|
||||
/// Approximate prompt token cost (~4 chars/token).
|
||||
pub approx_tokens: u32,
|
||||
pub line_count: u32,
|
||||
pub byte_len: u64,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub modified_ms: Option<f64>,
|
||||
/// True when OpenIDEA allows deleting or promoting-and-removing this file (auto-memory notes).
|
||||
pub writable: bool,
|
||||
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.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentAutoMemoryStatus {
|
||||
pub provider: String,
|
||||
pub label: String,
|
||||
pub mode: AutoMemoryMode,
|
||||
pub origin: AgentMemoryOrigin,
|
||||
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 › Memory and the Composer `MemoryPicker`.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentMemoryCatalog {
|
||||
pub entries: Vec<AgentMemoryState>,
|
||||
pub providers: Vec<AgentAutoMemoryStatus>,
|
||||
pub auto_memory: AutoMemoryMode,
|
||||
pub auto_memory_origin: AgentMemoryOrigin,
|
||||
}
|
||||
|
||||
/// 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.entries.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
/// Target format when creating a new memory or instruction file from Settings › Agents › Memory.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum AgentMemoryCreateTarget {
|
||||
/// `<workspace>/AGENTS.md` (or `~/.codex/AGENTS.md` in User scope).
|
||||
#[default]
|
||||
AgentsMd,
|
||||
/// `<workspace>/.claude/rules/<slug>.md` or `~/.claude/rules/<slug>.md`.
|
||||
ClaudeRule,
|
||||
/// `<workspace>/.github/instructions/<slug>.instructions.md` or `~/.copilot/instructions/<slug>.instructions.md`.
|
||||
CopilotInstruction,
|
||||
/// `<workspace>/.cursor/rules/<slug>.mdc`.
|
||||
CursorRule,
|
||||
}
|
||||
|
||||
/// Payload for creating a new instruction or rule file.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct CreateAgentMemoryInput {
|
||||
pub scope: McpScope,
|
||||
pub target: AgentMemoryCreateTarget,
|
||||
#[serde(default)]
|
||||
pub name: String,
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub description: Option<String>,
|
||||
#[serde(default)]
|
||||
pub paths: Vec<String>,
|
||||
pub content: String,
|
||||
}
|
||||
|
||||
/// Payload for promoting an auto-memory note into `AGENTS.md`.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PromoteAgentMemoryInput {
|
||||
pub source_id: String,
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub heading: Option<String>,
|
||||
#[serde(default)]
|
||||
pub remove_source: bool,
|
||||
}
|
||||
pub use ide_core::settings::{AgentSkillMode, AgentSkillPolicy};
|
||||
|
||||
/// Which CLI's own folders a skill was discovered in (Settings › Agents › Skills groups by it).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
@@ -1382,14 +1009,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
|
||||
@@ -1451,371 +1070,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>,
|
||||
/// 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,
|
||||
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")]
|
||||
|
||||
@@ -174,14 +174,10 @@ 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`, `claudeMdExcludes`, `instructionFiles`).
|
||||
cli_settings: Option<String>,
|
||||
/// The staged skills' `--settings` JSON (`skillOverrides` for the native ones too).
|
||||
skills_settings: Option<String>,
|
||||
/// `_meta.openidea.ephemeral`: `--no-session-persistence`, nothing saved under `~/.claude`.
|
||||
ephemeral: bool,
|
||||
shim: Weak<Shim>,
|
||||
@@ -375,20 +371,13 @@ impl Shim {
|
||||
}
|
||||
});
|
||||
let skills = params.pointer("/_meta/openidea/skills");
|
||||
let memory = params.pointer("/_meta/openidea/memory");
|
||||
let cli_settings = build_cli_settings(skills, memory);
|
||||
let session = Arc::new(Session {
|
||||
id: id.to_owned(),
|
||||
mcp_config,
|
||||
mcp_off,
|
||||
skills_add_dir: skills.and_then(|s| s.get("claudeAddDir")).and_then(Value::as_str).map(PathBuf::from),
|
||||
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,
|
||||
skills_settings: skills.and_then(|s| s.get("claudeSettings")).and_then(Value::as_str).map(str::to_owned),
|
||||
ephemeral: params.pointer("/_meta/openidea/ephemeral").and_then(Value::as_bool).unwrap_or(false),
|
||||
shim: Arc::downgrade(self),
|
||||
st: Mutex::new(State {
|
||||
@@ -739,28 +728,18 @@ 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()]);
|
||||
}
|
||||
if let Some(settings) = &self.cli_settings {
|
||||
if let Some(settings) = &self.skills_settings {
|
||||
args.extend(["--settings".to_owned(), settings.clone()]);
|
||||
}
|
||||
if self.ephemeral {
|
||||
args.push("--no-session-persistence".to_owned());
|
||||
}
|
||||
args.extend(start.args());
|
||||
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 launch =
|
||||
Launch { program: shim.config.program.clone(), args, cwd: self.cwd.clone(), env: shim.config.env.clone() };
|
||||
let io = shim
|
||||
.cli
|
||||
.launch(&launch, shim.on_stderr.clone())
|
||||
@@ -1622,41 +1601,6 @@ fn write_mcp_config(json: &str) -> std::io::Result<tempfile::TempPath> {
|
||||
/// The servers switched off for the session (`_meta.openidea.mcpServersOff`) as Claude Code
|
||||
/// permission rules that deny all of a server's tools (`mcp__<server>`), so a server of
|
||||
/// Claude Code's own configuration stays off too.
|
||||
/// 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"))
|
||||
.and_then(Value::as_str)
|
||||
.and_then(|raw| serde_json::from_str::<serde_json::Map<String, Value>>(raw).ok())
|
||||
.unwrap_or_default();
|
||||
|
||||
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"))
|
||||
}
|
||||
|
||||
/// The session's `additionalDirectories`: the workspace's other roots.
|
||||
fn additional_dirs(params: &Value) -> Vec<String> {
|
||||
let dirs = params.get("additionalDirectories").and_then(Value::as_array);
|
||||
|
||||
@@ -1442,76 +1442,3 @@ async fn an_ephemeral_session_is_not_saved() {
|
||||
let args = cli.launched.lock()[0].clone();
|
||||
assert!(args.contains(&"--no-session-persistence".to_owned()), "{args:?}");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
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();
|
||||
let h =
|
||||
Harness::connect(cli.clone(), config.path().into(), config.path().join("pending"), cwd_path, Vec::new()).await;
|
||||
let params = json!({
|
||||
"cwd": h.cwd,
|
||||
"mcpServers": [],
|
||||
"_meta": {
|
||||
"openidea": {
|
||||
"skills": {
|
||||
"claudeAddDir": "/tmp/farm-skills",
|
||||
"claudeSettings": "{\"skillOverrides\":{\"tdd\":\"user-invocable-only\"}}"
|
||||
},
|
||||
"memory": {
|
||||
"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.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_eq!(parsed["claudeMdExcludes"], json!(["/repo/CLAUDE.local.md"]));
|
||||
assert_eq!(
|
||||
parsed["pluginConfigs"]["cc-plugin-agents-md@builtin"]["options"]["instructionFiles"],
|
||||
"claude-md-and-agents-md"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn session_merges_memory_settings_without_plugin_dir_or_plugin_config_injection() {
|
||||
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();
|
||||
let h =
|
||||
Harness::connect(cli.clone(), config.path().into(), config.path().join("pending"), cwd_path, Vec::new()).await;
|
||||
let params = json!({
|
||||
"cwd": h.cwd,
|
||||
"mcpServers": [],
|
||||
"_meta": {
|
||||
"openidea": {
|
||||
"memory": {
|
||||
"claudeInstructionFiles": "claude-md-and-agents-md"
|
||||
},
|
||||
"plugins": { "activePlugins": ["azure", "linear@mkt"] }
|
||||
}
|
||||
}
|
||||
});
|
||||
h.request("session/new", params).await.unwrap();
|
||||
let args = cli.launched.lock()[0].clone();
|
||||
assert!(!args.iter().any(|a| a == "--plugin-dir"), "{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["pluginConfigs"]["cc-plugin-agents-md@builtin"]["options"]["instructionFiles"],
|
||||
"claude-md-and-agents-md"
|
||||
);
|
||||
assert!(parsed["pluginConfigs"]["azure"].is_null());
|
||||
}
|
||||
@@ -8,80 +8,43 @@ pub(crate) struct BuiltinCommandSpec {
|
||||
pub name: &'static str,
|
||||
pub description: &'static str,
|
||||
pub hint: Option<&'static str>,
|
||||
pub choices: &'static [(&'static str, &'static str)],
|
||||
}
|
||||
|
||||
pub(crate) const BUILTIN_COMMANDS: &[BuiltinCommandSpec] = &[
|
||||
BuiltinCommandSpec { name: "plan", description: "Turn plan mode on or off.", hint: None, choices: &[] },
|
||||
BuiltinCommandSpec { name: "plan", description: "Turn plan mode on or off.", hint: None },
|
||||
BuiltinCommandSpec {
|
||||
name: "mcp",
|
||||
description: "Show the status of the MCP servers, or reconnect them.",
|
||||
hint: Some("[reconnect]"),
|
||||
choices: &[("reconnect", "Reload and reconnect MCP servers.")],
|
||||
},
|
||||
BuiltinCommandSpec { name: "skills", description: "List available skills.", hint: None, choices: &[] },
|
||||
BuiltinCommandSpec {
|
||||
name: "memories",
|
||||
description: "Show, enable, disable, or reset cross-session Codex memories.",
|
||||
hint: Some("[show|on|off|reset]"),
|
||||
choices: &[
|
||||
("show", "Show consolidated memory summary for this thread."),
|
||||
("on", "Enable memory generation for this thread."),
|
||||
("off", "Disable memory generation for this thread."),
|
||||
("reset", "Clear local Codex memory files and summaries."),
|
||||
],
|
||||
},
|
||||
BuiltinCommandSpec {
|
||||
name: "status",
|
||||
description: "Display session configuration and token usage.",
|
||||
hint: None,
|
||||
choices: &[],
|
||||
},
|
||||
BuiltinCommandSpec { name: "skills", description: "List available skills.", hint: None },
|
||||
BuiltinCommandSpec { name: "status", description: "Display session configuration and token usage.", hint: None },
|
||||
BuiltinCommandSpec {
|
||||
name: "review",
|
||||
description: "Review uncommitted changes, or review with custom instructions.",
|
||||
hint: Some("optional review instructions"),
|
||||
choices: &[],
|
||||
},
|
||||
BuiltinCommandSpec {
|
||||
name: "review-branch",
|
||||
description: "Review changes relative to a base branch.",
|
||||
hint: Some("branch name"),
|
||||
choices: &[],
|
||||
},
|
||||
BuiltinCommandSpec {
|
||||
name: "review-commit",
|
||||
description: "Review a specific commit.",
|
||||
hint: Some("commit sha"),
|
||||
choices: &[],
|
||||
},
|
||||
BuiltinCommandSpec { name: "review-commit", description: "Review a specific commit.", hint: Some("commit sha") },
|
||||
BuiltinCommandSpec {
|
||||
name: "compact",
|
||||
description: "Summarize conversation to avoid hitting the context limit.",
|
||||
hint: None,
|
||||
choices: &[],
|
||||
},
|
||||
BuiltinCommandSpec {
|
||||
name: "goal",
|
||||
description: "Set a goal to keep pursuing.",
|
||||
hint: Some("[<objective>|clear|pause|resume]"),
|
||||
choices: &[
|
||||
("clear", "Clear the current goal."),
|
||||
("pause", "Pause the current goal."),
|
||||
("resume", "Resume a paused goal."),
|
||||
],
|
||||
},
|
||||
BuiltinCommandSpec {
|
||||
name: "rename",
|
||||
description: "Rename the current session.",
|
||||
hint: Some("new name"),
|
||||
choices: &[],
|
||||
},
|
||||
BuiltinCommandSpec { name: "rename", description: "Rename the current session.", hint: Some("new name") },
|
||||
BuiltinCommandSpec {
|
||||
name: "logout",
|
||||
description: "Sign out of Codex. This option is available when you are logged in via ChatGPT.",
|
||||
hint: None,
|
||||
choices: &[],
|
||||
},
|
||||
];
|
||||
|
||||
@@ -90,7 +53,6 @@ pub(super) enum BuiltinCommand {
|
||||
Plan,
|
||||
Mcp,
|
||||
Skills,
|
||||
Memories,
|
||||
Status,
|
||||
Review,
|
||||
ReviewBranch,
|
||||
@@ -107,7 +69,6 @@ impl BuiltinCommand {
|
||||
"plan" => Self::Plan,
|
||||
"mcp" => Self::Mcp,
|
||||
"skills" => Self::Skills,
|
||||
"memories" => Self::Memories,
|
||||
"status" => Self::Status,
|
||||
"review" => Self::Review,
|
||||
"review-branch" => Self::ReviewBranch,
|
||||
@@ -163,7 +124,6 @@ mod tests {
|
||||
"plan",
|
||||
"mcp",
|
||||
"skills",
|
||||
"memories",
|
||||
"status",
|
||||
"review",
|
||||
"review-branch",
|
||||
|
||||
@@ -14,7 +14,7 @@ mod tests;
|
||||
use super::Shim;
|
||||
use crate::acp::AUTH_REQUIRED;
|
||||
use crate::provider::ProviderSpec;
|
||||
use crate::{AgentCommand, AgentCommandChoice, AgentCommandSource};
|
||||
use crate::{AgentCommand, AgentCommandSource};
|
||||
use commands::{BuiltinCommand, ParsedCommand};
|
||||
use ide_jsonrpc::{Framing, Handler, Peer, RpcError, codes};
|
||||
use parking_lot::Mutex;
|
||||
@@ -47,14 +47,6 @@ pub(crate) fn builtin_commands() -> Vec<AgentCommand> {
|
||||
description: command.description.to_owned(),
|
||||
hint: command.hint.map(str::to_owned),
|
||||
source: AgentCommandSource::Command,
|
||||
choices: command
|
||||
.choices
|
||||
.iter()
|
||||
.map(|(name, description)| AgentCommandChoice {
|
||||
name: (*name).to_owned(),
|
||||
description: (*description).to_owned(),
|
||||
})
|
||||
.collect(),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -362,23 +354,6 @@ fn apply_thread_config(params: &Value, request: &mut Value) {
|
||||
{
|
||||
map.insert("skills".into(), json!({ "config": off }));
|
||||
}
|
||||
if let Some(mem) = params.pointer("/_meta/openidea/memory")
|
||||
&& let Some(map) = config.as_object_mut()
|
||||
{
|
||||
let mut mem_cfg = serde_json::Map::new();
|
||||
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(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));
|
||||
}
|
||||
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()) {
|
||||
request["config"] = config;
|
||||
}
|
||||
@@ -725,7 +700,6 @@ impl CodexShim {
|
||||
let found = self.call("skills/list", json!({ "cwds": [cwd] })).await?;
|
||||
self.say(session, skills_text(&found));
|
||||
}
|
||||
BuiltinCommand::Memories => self.memories_command(session, &command.rest).await?,
|
||||
BuiltinCommand::Mcp => match command.rest.as_str() {
|
||||
"" => self.say(session, self.mcp_text(session).await?),
|
||||
rest if rest.eq_ignore_ascii_case("reconnect") => {
|
||||
@@ -765,36 +739,6 @@ impl CodexShim {
|
||||
Ok(json!({ "stopReason": "end_turn" }))
|
||||
}
|
||||
|
||||
async fn memories_command(&self, session: &str, rest: &str) -> Result<(), ResponseError> {
|
||||
let arg = rest.trim().to_ascii_lowercase();
|
||||
match arg.as_str() {
|
||||
"" | "show" => {
|
||||
let res = self.call("thread/memory/read", json!({ "threadId": session })).await?;
|
||||
let summary = res
|
||||
.get("summary")
|
||||
.and_then(Value::as_str)
|
||||
.map(str::trim)
|
||||
.filter(|s| !s.is_empty())
|
||||
.unwrap_or("No consolidated memories for this thread yet.");
|
||||
self.say(session, summary);
|
||||
}
|
||||
"on" => {
|
||||
self.call("thread/memoryMode/set", json!({ "threadId": session, "mode": "enabled" })).await?;
|
||||
self.say(session, "Memory generation enabled for this thread.");
|
||||
}
|
||||
"off" => {
|
||||
self.call("thread/memoryMode/set", json!({ "threadId": session, "mode": "disabled" })).await?;
|
||||
self.say(session, "Memory generation disabled for this thread.");
|
||||
}
|
||||
"reset" => {
|
||||
self.call("memory/reset", Value::Null).await?;
|
||||
self.say(session, "Reset local Codex memories.");
|
||||
}
|
||||
_ => self.say(session, command_usage(BuiltinCommand::Memories)),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn goal_command(&self, session: &str, rest: &str) -> Result<(), ResponseError> {
|
||||
let argument = rest.trim();
|
||||
if argument.is_empty() {
|
||||
@@ -1566,7 +1510,6 @@ fn command_usage(command: BuiltinCommand) -> String {
|
||||
match command {
|
||||
BuiltinCommand::Plan => "Command \"/plan\" accepts no arguments.".to_owned(),
|
||||
BuiltinCommand::Mcp => "Command \"/mcp\" accepts no arguments, or `reconnect`.".to_owned(),
|
||||
BuiltinCommand::Memories => "Command \"/memories\" accepts `[show|on|off|reset]`.".to_owned(),
|
||||
BuiltinCommand::ReviewBranch => "Command \"/review-branch\" requires branch name.".to_owned(),
|
||||
BuiltinCommand::ReviewCommit => "Command \"/review-commit\" requires commit sha.".to_owned(),
|
||||
BuiltinCommand::Goal => "Command \"/goal\" requires [<objective>|clear|pause|resume].".to_owned(),
|
||||
|
||||
@@ -1695,57 +1695,6 @@ async fn goal_commands_set_pause_resume_and_clear_through_app_server() {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn memories_commands_read_toggle_and_reset_through_app_server() {
|
||||
for (prompt, method, has_thread_id, expected_params, result, expected_text) in [
|
||||
(
|
||||
"/memories",
|
||||
"thread/memory/read",
|
||||
true,
|
||||
json!({ "threadId": "s" }),
|
||||
json!({ "summary": "Remembered: run targeted tests first." }),
|
||||
"Remembered: run targeted tests first.",
|
||||
),
|
||||
(
|
||||
"/memories show",
|
||||
"thread/memory/read",
|
||||
true,
|
||||
json!({ "threadId": "s" }),
|
||||
json!({ "summary": null }),
|
||||
"No consolidated memories for this thread yet.",
|
||||
),
|
||||
(
|
||||
"/memories on",
|
||||
"thread/memoryMode/set",
|
||||
true,
|
||||
json!({ "threadId": "s", "mode": "enabled" }),
|
||||
json!({}),
|
||||
"Memory generation enabled for this thread.",
|
||||
),
|
||||
(
|
||||
"/memories off",
|
||||
"thread/memoryMode/set",
|
||||
true,
|
||||
json!({ "threadId": "s", "mode": "disabled" }),
|
||||
json!({}),
|
||||
"Memory generation disabled for this thread.",
|
||||
),
|
||||
("/memories reset", "memory/reset", false, Value::Null, json!({}), "Reset local Codex memories."),
|
||||
] {
|
||||
let (results, client, frames, _meta, _codex) =
|
||||
replay_transcript(Scenario::Command(prompt), command_transcript(&[(method, result)])).await;
|
||||
let session = session_of(&results, "new");
|
||||
let sent = sent(&frames, method);
|
||||
assert_eq!(sent.len(), 1, "{prompt}");
|
||||
let mut expected = expected_params;
|
||||
if has_thread_id {
|
||||
expected["threadId"] = json!(session);
|
||||
assert_eq!(sent[0]["params"], expected, "{prompt}");
|
||||
}
|
||||
assert_eq!(client.text(&session, "agent_message_chunk"), expected_text, "{prompt}");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn missing_review_arguments_print_usage_without_starting_a_turn() {
|
||||
for prompt in ["/review-branch", "/review-commit", "/rename", "/goal"] {
|
||||
@@ -2135,13 +2084,6 @@ fn skills_become_commands_with_their_invocation_names() {
|
||||
let commands = crate::config::commands_of(&update, "codex");
|
||||
assert!(commands.iter().all(|c| c.source == crate::AgentCommandSource::Skill));
|
||||
assert_eq!(commands[0].name, "$review");
|
||||
let builtins = builtin_commands();
|
||||
let goal = builtins.iter().find(|c| c.name == "goal").unwrap();
|
||||
assert_eq!(goal.choices.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(), ["clear", "pause", "resume"]);
|
||||
let memories = builtins.iter().find(|c| c.name == "memories").unwrap();
|
||||
assert_eq!(memories.choices.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(), ["show", "on", "off", "reset"]);
|
||||
let mcp = builtins.iter().find(|c| c.name == "mcp").unwrap();
|
||||
assert_eq!(mcp.choices.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(), ["reconnect"]);
|
||||
assert!(skill_commands(&json!({"data": []})).unwrap()["availableCommands"].as_array().unwrap().is_empty());
|
||||
assert!(skill_commands(&json!({})).is_none());
|
||||
}
|
||||
@@ -2155,28 +2097,6 @@ fn workspace_roots_join_the_thread_roots() {
|
||||
let mut request = json!({});
|
||||
apply_thread_config(&json!({ "cwd": "/w/api", "mcpServers": [] }), &mut request);
|
||||
assert!(request.get("runtimeWorkspaceRoots").is_none());
|
||||
|
||||
let mut mem_req = json!({});
|
||||
apply_thread_config(
|
||||
&json!({
|
||||
"cwd": "/w/api",
|
||||
"mcpServers": [],
|
||||
"_meta": {
|
||||
"openidea": {
|
||||
"skills": { "codexOff": [["noisy", "/repo/.agents/skills/noisy/SKILL.md"]] },
|
||||
"memory": {
|
||||
"codexUseMemories": true,
|
||||
"codexGenerateMemories": false,
|
||||
"codexDeveloperInstructions": "## Memory (style)\nUse targeted selectors."
|
||||
}
|
||||
}
|
||||
}
|
||||
}),
|
||||
&mut mem_req,
|
||||
);
|
||||
assert_eq!(mem_req["config"]["memories"], json!({ "use_memories": true, "generate_memories": false }));
|
||||
assert_eq!(mem_req["config"]["developer_instructions"], "## Memory (style)\nUse targeted selectors.");
|
||||
assert_eq!(mem_req["config"]["skills"]["config"][0]["enabled"], false);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
|
||||
@@ -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()?))
|
||||
|
||||
@@ -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>,
|
||||
@@ -471,38 +462,6 @@ 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)
|
||||
}
|
||||
@@ -560,11 +519,9 @@ 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,
|
||||
"_openidea/context_usage" => self.context_usage(¶ms).await,
|
||||
"_openidea/stop_task" => self.stop_task(¶ms).await,
|
||||
"session/close" => self.close_session(¶ms).await,
|
||||
_ => Err(error(codes::METHOD_NOT_FOUND, format!("unsupported method {method}"))),
|
||||
@@ -579,8 +536,8 @@ impl CopilotShim {
|
||||
"loadSession": true,
|
||||
"promptCapabilities": { "image": true, "audio": false, "embeddedContext": true },
|
||||
"mcpCapabilities": { "http": true, "sse": true, "stdio": true },
|
||||
"sessionCapabilities": { "fork": {}, "close": {}, "list": {} },
|
||||
"_meta": { "openidea": { "steer": true, "backgroundTasks": true, "contextUsage": true } },
|
||||
"sessionCapabilities": { "close": {}, "list": {} },
|
||||
"_meta": { "openidea": { "steer": true, "backgroundTasks": true } },
|
||||
},
|
||||
"agentInfo": {
|
||||
"name": "copilot",
|
||||
@@ -630,7 +587,6 @@ 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
|
||||
@@ -659,25 +615,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;
|
||||
@@ -701,11 +638,9 @@ 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);
|
||||
}
|
||||
@@ -716,72 +651,16 @@ 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);
|
||||
self.sync_usage_metrics(&actual_id);
|
||||
Ok(json!({
|
||||
"sessionId": actual_id,
|
||||
"configOptions": options,
|
||||
}))
|
||||
}
|
||||
|
||||
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();
|
||||
self.runtime.spawn(async move {
|
||||
let Ok(metrics) = shim.call("session.usage.getMetrics", json!({ "sessionId": sid })).await else {
|
||||
return;
|
||||
};
|
||||
let Some(nano_aiu) = metrics.get("totalNanoAiu").and_then(Value::as_f64) else {
|
||||
return;
|
||||
};
|
||||
let catalog = shim.catalog.try_lock().ok().and_then(|g| g.clone());
|
||||
let update = {
|
||||
let mut st = shim.state.lock();
|
||||
st.sessions.get_mut(&sid).and_then(|entry| {
|
||||
entry.translator.set_total_nano_aiu(nano_aiu);
|
||||
let used = entry.translator.last_used_tokens?;
|
||||
let size = entry
|
||||
.translator
|
||||
.last_usage_snapshot
|
||||
.as_ref()
|
||||
.map(|s| s.token_limit)
|
||||
.filter(|&s| s > 0)
|
||||
.or_else(|| {
|
||||
catalog.as_deref().and_then(|m| entry.settings.active_context_tokens(m)).filter(|&s| s > 0)
|
||||
})?;
|
||||
Some(entry.translator.usage_update(used, size))
|
||||
})
|
||||
};
|
||||
if let Some(update) = update {
|
||||
shim.send_update(&sid, update);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn publish_commands(self: &Arc<Self>, session_id: &str, cwd: &str) {
|
||||
let shim = self.clone();
|
||||
let sid = session_id.to_owned();
|
||||
@@ -856,152 +735,25 @@ impl CopilotShim {
|
||||
|
||||
let new_limit = next_settings.active_context_tokens(&catalog);
|
||||
let options = models::config_options(&catalog, &next_settings);
|
||||
let usage_update = {
|
||||
{
|
||||
let mut st = self.state.lock();
|
||||
if let Some(entry) = st.sessions.get_mut(session_id) {
|
||||
entry.settings = next_settings;
|
||||
if matches!(option, MODEL | CONTEXT_TIER)
|
||||
&& let (Some(used), Some(size)) = (last_used, new_limit.filter(|&s| s > 0))
|
||||
{
|
||||
Some(entry.translator.usage_update(used, size))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
} else {
|
||||
None
|
||||
}
|
||||
};
|
||||
if let Some(update) = usage_update {
|
||||
self.send_update(session_id, update);
|
||||
}
|
||||
if matches!(option, MODEL | CONTEXT_TIER)
|
||||
&& let (Some(used), Some(size)) = (last_used, new_limit.filter(|&s| s > 0))
|
||||
{
|
||||
self.send_update(session_id, json!({ "sessionUpdate": "usage_update", "used": used, "size": size }));
|
||||
}
|
||||
Ok(json!({ "configOptions": options }))
|
||||
}
|
||||
|
||||
async fn context_usage(&self, params: &Value) -> Result<Value, ResponseError> {
|
||||
let session_id = str_param(params, "sessionId")?;
|
||||
let catalog = self.models().await.ok();
|
||||
let (model_id, fallback_limit, snapshot) = {
|
||||
let st = self.state.lock();
|
||||
let entry = st.sessions.get(session_id).ok_or_else(|| invalid(format!("unknown session {session_id}")))?;
|
||||
let limit = catalog.as_deref().and_then(|models| entry.settings.active_context_tokens(models));
|
||||
(entry.settings.model.clone(), limit, entry.translator.last_usage_snapshot.clone())
|
||||
};
|
||||
|
||||
let (attr_res, metrics_res) = tokio::join!(
|
||||
self.call("session.metadata.getContextAttribution", json!({ "sessionId": session_id })),
|
||||
self.call("session.usage.getMetrics", json!({ "sessionId": session_id })),
|
||||
);
|
||||
|
||||
if let Ok(metrics) = metrics_res
|
||||
&& let Some(nano_aiu) = metrics.get("totalNanoAiu").and_then(Value::as_f64)
|
||||
&& let Some(entry) = self.state.lock().sessions.get_mut(session_id)
|
||||
{
|
||||
entry.translator.set_total_nano_aiu(nano_aiu);
|
||||
}
|
||||
|
||||
let mut usage =
|
||||
attr_res.ok().and_then(|v| translate::context_usage_from_attribution(&v, &model_id, fallback_limit));
|
||||
|
||||
if usage.is_none()
|
||||
&& !model_id.is_empty()
|
||||
&& let Ok(info) = self
|
||||
.call("session.metadata.contextInfo", json!({ "sessionId": session_id, "modelName": model_id }))
|
||||
.await
|
||||
{
|
||||
usage = translate::context_usage_from_context_info(&info, &model_id, fallback_limit);
|
||||
}
|
||||
|
||||
let usage = usage
|
||||
.or_else(|| snapshot.as_ref().map(|snap| translate::context_usage_from_snapshot(snap, &model_id)))
|
||||
.ok_or_else(|| error(codes::INTERNAL_ERROR, "Context details are not available yet"))?;
|
||||
|
||||
let meter_update = {
|
||||
let mut st = self.state.lock();
|
||||
st.sessions.get_mut(session_id).map(|entry| {
|
||||
entry.translator.last_used_tokens = Some(usage.total_tokens);
|
||||
entry.translator.usage_update(usage.total_tokens, usage.max_tokens)
|
||||
})
|
||||
};
|
||||
if let Some(update) = meter_update {
|
||||
self.send_update(session_id, update);
|
||||
}
|
||||
|
||||
serde_json::to_value(usage).map_err(|e| error(codes::INTERNAL_ERROR, e.to_string()))
|
||||
}
|
||||
|
||||
async fn compact_session(&self, session_id: &str, instructions: Option<&str>) -> Result<Value, ResponseError> {
|
||||
let mut req = json!({
|
||||
"sessionId": session_id,
|
||||
"trigger": "manual",
|
||||
});
|
||||
if let Some(text) = instructions.map(str::trim).filter(|s| !s.is_empty()) {
|
||||
req["customInstructions"] = json!(text);
|
||||
}
|
||||
let res = self.call("session.history.compact", req).await?;
|
||||
let success = res.get("success").and_then(Value::as_bool).unwrap_or(true);
|
||||
if !success {
|
||||
let msg = res.get("error").and_then(Value::as_str).unwrap_or("Conversation compaction failed");
|
||||
return Err(error(codes::INTERNAL_ERROR, msg));
|
||||
}
|
||||
|
||||
let catalog = self.models().await.ok();
|
||||
let meter_update = {
|
||||
let mut st = self.state.lock();
|
||||
st.sessions.get_mut(session_id).and_then(|entry| {
|
||||
let cw = res.get("contextWindow")?;
|
||||
let used = cw.get("currentTokens").and_then(Value::as_u64).and_then(|n| u32::try_from(n).ok())?;
|
||||
let fallback_limit = catalog.as_deref().and_then(|models| entry.settings.active_context_tokens(models));
|
||||
let size = cw
|
||||
.get("tokenLimit")
|
||||
.and_then(Value::as_u64)
|
||||
.and_then(|n| u32::try_from(n).ok())
|
||||
.filter(|&n| n > 0)
|
||||
.or(fallback_limit.filter(|&n| n > 0))?;
|
||||
let u32_field = |k: &str| cw.get(k).and_then(Value::as_u64).and_then(|n| u32::try_from(n).ok());
|
||||
entry.translator.record_snapshot(translate::UsageSnapshot {
|
||||
current_tokens: used,
|
||||
token_limit: size,
|
||||
system_tokens: u32_field("systemTokens"),
|
||||
tool_definitions_tokens: u32_field("toolDefinitionsTokens"),
|
||||
conversation_tokens: u32_field("conversationTokens"),
|
||||
});
|
||||
Some(entry.translator.usage_update(used, size))
|
||||
})
|
||||
};
|
||||
if let Some(update) = meter_update {
|
||||
self.send_update(session_id, update);
|
||||
}
|
||||
|
||||
let tokens_removed = res.get("tokensRemoved").and_then(Value::as_u64).unwrap_or(0);
|
||||
let messages_removed = res.get("messagesRemoved").and_then(Value::as_u64).unwrap_or(0);
|
||||
let summary = if tokens_removed > 0 || messages_removed > 0 {
|
||||
format!("Compacted conversation ({tokens_removed} tokens, {messages_removed} messages removed).")
|
||||
} else {
|
||||
"Conversation compacted.".to_owned()
|
||||
};
|
||||
self.send_update(
|
||||
session_id,
|
||||
json!({ "sessionUpdate": "agent_message_chunk", "content": { "type": "text", "text": summary } }),
|
||||
);
|
||||
if let Some(entry) = self.state.lock().sessions.get_mut(session_id) {
|
||||
entry.early_cancel = None;
|
||||
}
|
||||
Ok(json!({ "stopReason": "end_turn" }))
|
||||
}
|
||||
|
||||
async fn prompt(&self, params: &Value, steer: bool) -> Result<Value, ResponseError> {
|
||||
let session_id = str_param(params, "sessionId")?.to_owned();
|
||||
let blocks = params.get("prompt").and_then(Value::as_array).ok_or_else(|| invalid("missing prompt"))?;
|
||||
let (text, attachments, temp_files) = build_prompt_payload(&session_id, blocks);
|
||||
|
||||
if !steer
|
||||
&& attachments.is_empty()
|
||||
&& let Some(instructions) = parse_compact_command(&text)
|
||||
{
|
||||
cleanup_files(&temp_files);
|
||||
return self.compact_session(&session_id, instructions).await;
|
||||
}
|
||||
|
||||
if steer {
|
||||
let (is_running, main_busy) = {
|
||||
let st = self.state.lock();
|
||||
@@ -1318,21 +1070,6 @@ impl CopilotShim {
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_compact_command(text: &str) -> Option<Option<&str>> {
|
||||
let trimmed = text.trim();
|
||||
if trimmed == "/compact" {
|
||||
return Some(None);
|
||||
}
|
||||
let rest = trimmed.strip_prefix("/compact")?;
|
||||
let first = rest.chars().next()?;
|
||||
if first.is_whitespace() {
|
||||
let focus = rest.trim();
|
||||
Some((!focus.is_empty()).then_some(focus))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn build_prompt_payload(session_id: &str, blocks: &[Value]) -> (String, Vec<Value>, Vec<PathBuf>) {
|
||||
let mut text_parts = Vec::new();
|
||||
let mut attachments = Vec::new();
|
||||
@@ -1372,10 +1109,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);
|
||||
}
|
||||
|
||||
@@ -1,11 +1,6 @@
|
||||
use super::models::{self, CONTEXT_TIER, EFFORT, MODEL, Mode, Settings, UserDefaults};
|
||||
use super::translate::{
|
||||
self, EventTranslator, UsageSnapshot, context_usage_from_attribution, context_usage_from_context_info,
|
||||
context_usage_from_snapshot,
|
||||
};
|
||||
use super::{acp_args, acp_fallback_spec, attach, headless_args};
|
||||
use crate::config;
|
||||
use crate::model::{AgentContextCategory, AgentContextUsage};
|
||||
use crate::provider::Driver;
|
||||
use ide_jsonrpc::{Framing, Handler, Peer, codes};
|
||||
use parking_lot::Mutex;
|
||||
@@ -115,18 +110,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 +429,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!({})),
|
||||
@@ -493,38 +443,6 @@ impl Handler for FakeCopilotServer {
|
||||
] })),
|
||||
"session.tasks.cancel" => Ok(json!({ "cancelled": true })),
|
||||
"session.abort" => Ok(json!({})),
|
||||
"session.usage.getMetrics" => Ok(json!({
|
||||
"totalNanoAiu": 4_211_400_000_000.0,
|
||||
"totalPremiumRequestCost": 12.0,
|
||||
})),
|
||||
"session.metadata.getContextAttribution" => Ok(json!({
|
||||
"contextAttribution": {
|
||||
"totalTokens": 405_200,
|
||||
"limit": 1_000_000,
|
||||
"promptTokenLimit": 936_000,
|
||||
"bufferTokens": 64_000,
|
||||
"compactionThreshold": 800_000,
|
||||
"modelId": "gemini-4-carbon",
|
||||
"entries": [
|
||||
{ "kind": "system", "id": "system:root", "label": "System", "tokens": 223_000 },
|
||||
{ "kind": "system", "id": "system:prompt", "label": "System Prompt", "tokens": 20_000, "parentId": "system:root" },
|
||||
{ "kind": "toolDefinition", "id": "toolDefinition:bash", "label": "bash", "tokens": 203_000, "parentId": "system:root" },
|
||||
{ "kind": "tool", "id": "tool:bash", "label": "bash", "tokens": 69_000 }
|
||||
]
|
||||
}
|
||||
})),
|
||||
"session.history.compact" => Ok(json!({
|
||||
"success": true,
|
||||
"tokensRemoved": 250_000,
|
||||
"messagesRemoved": 12,
|
||||
"contextWindow": {
|
||||
"currentTokens": 155_200,
|
||||
"tokenLimit": 1_000_000,
|
||||
"systemTokens": 20_000,
|
||||
"toolDefinitionsTokens": 100_000,
|
||||
"conversationTokens": 35_200
|
||||
}
|
||||
})),
|
||||
"session.send" if self.background_shell => {
|
||||
if let Some(peer) = self.peer.get().cloned() {
|
||||
let sid = params["sessionId"].as_str().unwrap_or("cop-sess-1").to_owned();
|
||||
@@ -719,81 +637,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 =
|
||||
@@ -952,325 +795,3 @@ async fn session_new_and_load_forward_staged_skill_directories_and_disabled_skil
|
||||
assert!(params.get("enableConfigDiscovery").is_none(), "{method} must not auto-enable workspace MCP discovery");
|
||||
}
|
||||
}
|
||||
|
||||
#[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!({
|
||||
"contextAttribution": {
|
||||
"totalTokens": 405_200,
|
||||
"limit": 1_000_000,
|
||||
"bufferTokens": 64_000,
|
||||
"compactionThreshold": 800_000,
|
||||
"modelId": "gemini-4-carbon",
|
||||
"entries": [
|
||||
{ "kind": "system", "id": "system:root", "label": "System", "tokens": 223_000 },
|
||||
{ "kind": "system", "id": "system:prompt", "label": "System Prompt", "tokens": 20_000, "parentId": "system:root" },
|
||||
{ "kind": "toolDefinition", "id": "toolDefinition:bash", "label": "bash", "tokens": 120_000, "parentId": "system:root" },
|
||||
{ "kind": "toolDefinition", "id": "toolDefinition:view", "label": "view", "tokens": 83_000, "parentId": "system:root" },
|
||||
{ "kind": "tool", "id": "tool:bash", "label": "bash", "tokens": 69_000 },
|
||||
{ "kind": "plugin", "id": "plugin:git", "label": "git", "tokens": 5_000 },
|
||||
{ "kind": "skill", "id": "skill:pr", "label": "pr", "tokens": 5_000, "parentId": "plugin:git" }
|
||||
]
|
||||
}
|
||||
});
|
||||
let usage = context_usage_from_attribution(&payload, "fallback", None).unwrap();
|
||||
assert_eq!(usage.total_tokens, 405_200);
|
||||
assert_eq!(usage.max_tokens, 1_000_000);
|
||||
assert_eq!(usage.reserved_tokens, Some(64_000));
|
||||
assert_eq!(usage.auto_compact_threshold, Some(800_000));
|
||||
assert_eq!(usage.is_auto_compact_enabled, Some(true));
|
||||
assert_eq!(
|
||||
usage.categories,
|
||||
vec![
|
||||
AgentContextCategory {
|
||||
name: "System prompt".into(),
|
||||
tokens: 20_000,
|
||||
kind: Some("used".into()),
|
||||
group: Some("System".into()),
|
||||
},
|
||||
AgentContextCategory {
|
||||
name: "Tool Definitions".into(),
|
||||
tokens: 203_000,
|
||||
kind: Some("used".into()),
|
||||
group: Some("System".into()),
|
||||
},
|
||||
AgentContextCategory {
|
||||
name: "Tool Results".into(),
|
||||
tokens: 69_000,
|
||||
kind: Some("used".into()),
|
||||
group: Some("User Context".into()),
|
||||
},
|
||||
AgentContextCategory {
|
||||
name: "Messages".into(),
|
||||
tokens: 108_200,
|
||||
kind: Some("used".into()),
|
||||
group: Some("User Context".into()),
|
||||
},
|
||||
AgentContextCategory {
|
||||
name: "Skills".into(),
|
||||
tokens: 5_000,
|
||||
kind: Some("used".into()),
|
||||
group: Some("User Context".into()),
|
||||
},
|
||||
AgentContextCategory { name: "Free space".into(), tokens: 530_800, kind: Some("free".into()), group: None },
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn translates_context_info_and_usage_snapshot_fallbacks() {
|
||||
let info = json!({
|
||||
"contextInfo": {
|
||||
"modelName": "claude-sonnet-4.5",
|
||||
"systemTokens": 12_000,
|
||||
"toolDefinitionsTokens": 48_000,
|
||||
"conversationTokens": 40_000,
|
||||
"totalTokens": 100_000,
|
||||
"limit": 200_000,
|
||||
"bufferTokens": 20_000,
|
||||
"compactionThreshold": 160_000
|
||||
}
|
||||
});
|
||||
let from_info = context_usage_from_context_info(&info, "fallback", None).unwrap();
|
||||
assert_eq!(from_info.reserved_tokens, Some(20_000));
|
||||
assert_eq!(
|
||||
from_info.categories.iter().map(|c| (c.name.as_str(), c.tokens, c.group.as_deref())).collect::<Vec<_>>(),
|
||||
vec![
|
||||
("System prompt", 12_000, Some("System")),
|
||||
("Tool Definitions", 48_000, Some("System")),
|
||||
("Messages", 40_000, Some("User Context")),
|
||||
("Free space", 80_000, None),
|
||||
]
|
||||
);
|
||||
|
||||
let from_snap = context_usage_from_snapshot(
|
||||
&UsageSnapshot {
|
||||
current_tokens: 50_000,
|
||||
token_limit: 200_000,
|
||||
system_tokens: Some(10_000),
|
||||
tool_definitions_tokens: Some(25_000),
|
||||
conversation_tokens: Some(15_000),
|
||||
},
|
||||
"gpt-5.6-sol",
|
||||
);
|
||||
assert_eq!(from_snap.total_tokens, 50_000);
|
||||
assert_eq!(from_snap.max_tokens, 200_000);
|
||||
assert_eq!(from_snap.categories.len(), 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accumulates_copilot_credits_across_turns_subagents_and_compaction() {
|
||||
let mut tr = EventTranslator::default();
|
||||
let first = tr.translate(
|
||||
"s1",
|
||||
&json!({
|
||||
"type": "session.usage_info",
|
||||
"data": { "currentTokens": 40_000, "tokenLimit": 200_000, "systemTokens": 10_000, "toolDefinitionsTokens": 20_000, "conversationTokens": 10_000 }
|
||||
}),
|
||||
Some(200_000),
|
||||
);
|
||||
assert_eq!(first.updates[0].1["used"], 40_000);
|
||||
assert!(first.updates[0].1.get("cost").is_none());
|
||||
|
||||
// Main-agent usage reports 1.5 credits; subagent usage adds 0.5 credits -> 2.0 credits total.
|
||||
let main_usage = tr.translate(
|
||||
"s1",
|
||||
&json!({
|
||||
"type": "assistant.usage",
|
||||
"data": { "inputTokens": 45_000, "copilotUsage": { "totalNanoAiu": 1_500_000_000.0 } }
|
||||
}),
|
||||
Some(200_000),
|
||||
);
|
||||
assert_eq!(main_usage.updates[0].1["cost"]["currency"], "credits");
|
||||
assert!((main_usage.updates[0].1["cost"]["amount"].as_f64().unwrap() - 1.5).abs() < 1e-6);
|
||||
|
||||
let sub_usage = tr.translate(
|
||||
"s1",
|
||||
&json!({
|
||||
"type": "assistant.usage",
|
||||
"agentId": "sub-1",
|
||||
"data": { "inputTokens": 12_000, "copilotUsage": { "totalNanoAiu": 500_000_000.0 } }
|
||||
}),
|
||||
Some(200_000),
|
||||
);
|
||||
assert_eq!(sub_usage.updates[0].1["used"], 45_000);
|
||||
assert!((sub_usage.updates[0].1["cost"]["amount"].as_f64().unwrap() - 2.0).abs() < 1e-6);
|
||||
|
||||
// Compaction updates token count while keeping accumulated credits.
|
||||
let compacted = tr.translate(
|
||||
"s1",
|
||||
&json!({
|
||||
"type": "session.compaction_complete",
|
||||
"data": { "success": true, "postCompactionTokens": 22_000, "tokenLimit": 200_000 }
|
||||
}),
|
||||
Some(200_000),
|
||||
);
|
||||
assert_eq!(compacted.updates[0].1["used"], 22_000);
|
||||
assert!((compacted.updates[0].1["cost"]["amount"].as_f64().unwrap() - 2.0).abs() < 1e-6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn available_commands_includes_compact_when_omitted_by_server() {
|
||||
let cmds = translate::available_commands(Some(&json!({ "commands": [{ "name": "review" }] })), None);
|
||||
assert!(cmds.iter().any(|c| c["name"] == "compact"));
|
||||
assert!(cmds.iter().any(|c| c["name"] == "review"));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn context_usage_rpc_and_compact_command_work_end_to_end() {
|
||||
let server =
|
||||
Arc::new(FakeCopilotServer { peer: OnceLock::new(), calls: Mutex::new(Vec::new()), background_shell: false });
|
||||
let updates = Arc::new(CollectUpdates(Mutex::new(Vec::new())));
|
||||
let server_clone = server.clone();
|
||||
let client = attach(updates.clone(), move |events| {
|
||||
let (a, b) = tokio::io::duplex(1 << 16);
|
||||
let (ar, aw) = tokio::io::split(a);
|
||||
let (br, bw) = tokio::io::split(b);
|
||||
let srv_peer = Peer::connect_framed(br, bw, server_clone.clone(), Framing::ContentLength);
|
||||
let _ = server_clone.peer.set(srv_peer);
|
||||
Ok(Peer::connect_framed(ar, aw, events, Framing::ContentLength))
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
let init: Value = client.request("initialize", json!({}), None).await.unwrap();
|
||||
assert_eq!(init["agentCapabilities"]["_meta"]["openidea"]["contextUsage"], true);
|
||||
let _: Value = client.request("session/new", json!({ "cwd": "/tmp", "mcpServers": [] }), None).await.unwrap();
|
||||
|
||||
let ctx: AgentContextUsage =
|
||||
client.request("_openidea/context_usage", json!({ "sessionId": "cop-sess-1" }), None).await.unwrap();
|
||||
assert_eq!(ctx.total_tokens, 405_200);
|
||||
assert_eq!(ctx.max_tokens, 1_000_000);
|
||||
assert_eq!(ctx.reserved_tokens, Some(64_000));
|
||||
assert!(ctx.categories.iter().any(|c| c.name == "System prompt" && c.group.as_deref() == Some("System")));
|
||||
assert!(ctx.categories.iter().any(|c| c.name == "Tool Definitions" && c.group.as_deref() == Some("System")));
|
||||
assert!(ctx.categories.iter().any(|c| c.name == "Tool Results" && c.group.as_deref() == Some("User Context")));
|
||||
assert!(ctx.categories.iter().any(|c| c.name == "Messages" && c.group.as_deref() == Some("User Context")));
|
||||
|
||||
// Syncing metrics updated usage_update with credits cost.
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
assert!(updates.0.lock().iter().any(|u| {
|
||||
u["sessionUpdate"] == "usage_update"
|
||||
&& u["used"] == 405_200
|
||||
&& u["cost"]["currency"] == "credits"
|
||||
&& (u["cost"]["amount"].as_f64().unwrap_or(0.0) - 4211.4).abs() < 0.01
|
||||
}));
|
||||
|
||||
// `/compact` invokes `session.history.compact` instead of `session.send`.
|
||||
let res: Value = client
|
||||
.request(
|
||||
"session/prompt",
|
||||
json!({ "sessionId": "cop-sess-1", "prompt": [{ "type": "text", "text": "/compact keep PR notes" }] }),
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(res["stopReason"], "end_turn");
|
||||
assert!(server.calls.lock().iter().any(|(m, p)| {
|
||||
m == "session.history.compact"
|
||||
&& p["sessionId"] == "cop-sess-1"
|
||||
&& p["trigger"] == "manual"
|
||||
&& p["customInstructions"] == "keep PR notes"
|
||||
}));
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
assert!(updates.0.lock().iter().any(|u| u["sessionUpdate"] == "usage_update" && u["used"] == 155_200));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn available_commands_preserves_input_choices() {
|
||||
let cmds = json!({
|
||||
"commands": [
|
||||
{
|
||||
"name": "skills",
|
||||
"description": "Manage skills for enhanced capabilities",
|
||||
"input": {
|
||||
"hint": "[list|info|reload]",
|
||||
"choices": [
|
||||
{ "name": "list", "description": "List all available skills" },
|
||||
{ "name": "info", "description": "Show details for a skill" },
|
||||
{ "name": "INFO", "description": "Duplicate ignored" },
|
||||
{ "name": "", "description": "Empty ignored" },
|
||||
{ "name": "reload", "description": "Reload skills from disk" }
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "subconscious",
|
||||
"description": "Manage memory",
|
||||
"input": {
|
||||
"choices": [{ "name": "run", "description": "Consolidate now" }]
|
||||
}
|
||||
}
|
||||
]
|
||||
});
|
||||
let list = super::translate::available_commands(Some(&cmds), None);
|
||||
let parsed = crate::config::commands_of(&json!({ "availableCommands": list }), "copilot");
|
||||
// Then the built-in /compact.
|
||||
assert_eq!(parsed.len(), 3);
|
||||
assert_eq!(parsed[2].name, "compact");
|
||||
assert_eq!(parsed[0].name, "skills");
|
||||
assert_eq!(parsed[0].hint.as_deref(), Some("[list|info|reload]"));
|
||||
assert_eq!(
|
||||
parsed[0].choices,
|
||||
vec![
|
||||
crate::AgentCommandChoice { name: "list".into(), description: "List all available skills".into() },
|
||||
crate::AgentCommandChoice { name: "info".into(), description: "Show details for a skill".into() },
|
||||
crate::AgentCommandChoice { name: "reload".into(), description: "Reload skills from disk".into() },
|
||||
]
|
||||
);
|
||||
assert_eq!(parsed[1].name, "subconscious");
|
||||
assert_eq!(parsed[1].hint, None);
|
||||
assert_eq!(
|
||||
parsed[1].choices,
|
||||
vec![crate::AgentCommandChoice { name: "run".into(), description: "Consolidate now".into() }]
|
||||
);
|
||||
}
|
||||
@@ -2,22 +2,11 @@
|
||||
//! permissions, slash commands, MCP servers) and ACP v1.
|
||||
|
||||
use crate::LIMITS_UPDATE;
|
||||
use crate::model::{AgentContextCategory, AgentContextUsage};
|
||||
use serde_json::{Map, Value, json};
|
||||
use std::collections::{BTreeMap, HashMap, HashSet};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::path::Path;
|
||||
|
||||
const MAX_OUTPUT: usize = 64 * 1024;
|
||||
const NANO_AIU_PER_CREDIT: f64 = 1_000_000_000.0;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub(super) struct UsageSnapshot {
|
||||
pub current_tokens: u32,
|
||||
pub token_limit: u32,
|
||||
pub system_tokens: Option<u32>,
|
||||
pub tool_definitions_tokens: Option<u32>,
|
||||
pub conversation_tokens: Option<u32>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct EventTranslator {
|
||||
@@ -29,11 +18,6 @@ pub(super) struct EventTranslator {
|
||||
subagents: HashMap<String, String>,
|
||||
/// Last reported prompt token count, used when updating context size.
|
||||
pub last_used_tokens: Option<u32>,
|
||||
/// Last reported `session.usage_info` / compaction breakdown, used as fallback when RPC metadata is absent.
|
||||
pub last_usage_snapshot: Option<UsageSnapshot>,
|
||||
/// Accumulated session AI-credit spend in nano-AIU (across main agent and subagents).
|
||||
total_nano_aiu: f64,
|
||||
has_nano_aiu: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
@@ -62,29 +46,6 @@ impl EventTranslator {
|
||||
self.streamed_messages.clear();
|
||||
}
|
||||
|
||||
pub fn set_total_nano_aiu(&mut self, nano_aiu: f64) {
|
||||
if nano_aiu.is_finite() && nano_aiu > 0.0 {
|
||||
self.total_nano_aiu = nano_aiu;
|
||||
self.has_nano_aiu = true;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn record_snapshot(&mut self, snapshot: UsageSnapshot) {
|
||||
self.last_used_tokens = Some(snapshot.current_tokens);
|
||||
self.last_usage_snapshot = Some(snapshot);
|
||||
}
|
||||
|
||||
pub fn usage_update(&self, used: u32, size: u32) -> Value {
|
||||
let mut update = json!({ "sessionUpdate": "usage_update", "used": used, "size": size });
|
||||
if self.has_nano_aiu && self.total_nano_aiu > 0.0 {
|
||||
update["cost"] = json!({
|
||||
"amount": self.total_nano_aiu / NANO_AIU_PER_CREDIT,
|
||||
"currency": "credits",
|
||||
});
|
||||
}
|
||||
update
|
||||
}
|
||||
|
||||
pub fn translate(&mut self, main_session: &str, event: &Value, fallback_limit: Option<u32>) -> Translated {
|
||||
let mut out = Translated { updates: Vec::new(), terminal: None };
|
||||
let event_type = str_of(event, "type").unwrap_or_default();
|
||||
@@ -278,75 +239,36 @@ impl EventTranslator {
|
||||
}
|
||||
}
|
||||
"session.usage_info" => {
|
||||
let used = u32_of(data, "currentTokens");
|
||||
let limit = u32_of(data, "tokenLimit").filter(|&n| n > 0).or(fallback_limit);
|
||||
let used = data.get("currentTokens").and_then(Value::as_u64).and_then(|n| u32::try_from(n).ok());
|
||||
let limit = data
|
||||
.get("tokenLimit")
|
||||
.and_then(Value::as_u64)
|
||||
.and_then(|n| u32::try_from(n).ok())
|
||||
.filter(|&n| n > 0)
|
||||
.or(fallback_limit);
|
||||
if let (Some(used), Some(size)) = (used, limit) {
|
||||
self.record_snapshot(UsageSnapshot {
|
||||
current_tokens: used,
|
||||
token_limit: size,
|
||||
system_tokens: u32_of(data, "systemTokens"),
|
||||
tool_definitions_tokens: u32_of(data, "toolDefinitionsTokens"),
|
||||
conversation_tokens: u32_of(data, "conversationTokens"),
|
||||
});
|
||||
out.updates.push((main_session.to_owned(), self.usage_update(used, size)));
|
||||
self.last_used_tokens = Some(used);
|
||||
out.updates.push((
|
||||
main_session.to_owned(),
|
||||
json!({ "sessionUpdate": "usage_update", "used": used, "size": size }),
|
||||
));
|
||||
}
|
||||
}
|
||||
"assistant.usage" => {
|
||||
let added_credits = data
|
||||
.pointer("/copilotUsage/totalNanoAiu")
|
||||
.and_then(Value::as_f64)
|
||||
.filter(|n| n.is_finite() && *n > 0.0);
|
||||
if let Some(nano_aiu) = added_credits {
|
||||
self.total_nano_aiu += nano_aiu;
|
||||
self.has_nano_aiu = true;
|
||||
}
|
||||
if agent_id.is_none() {
|
||||
let used = u32_of(data, "inputTokens").or(self.last_used_tokens);
|
||||
let size = self
|
||||
.last_usage_snapshot
|
||||
.as_ref()
|
||||
.map(|s| s.token_limit)
|
||||
.filter(|&s| s > 0)
|
||||
.or(fallback_limit.filter(|&s| s > 0));
|
||||
if let (Some(used), Some(size)) = (used, size) {
|
||||
let used = data.get("inputTokens").and_then(Value::as_u64).and_then(|n| u32::try_from(n).ok());
|
||||
if let (Some(used), Some(size)) = (used, fallback_limit.filter(|&s| s > 0)) {
|
||||
self.last_used_tokens = Some(used);
|
||||
out.updates.push((main_session.to_owned(), self.usage_update(used, size)));
|
||||
out.updates.push((
|
||||
main_session.to_owned(),
|
||||
json!({ "sessionUpdate": "usage_update", "used": used, "size": size }),
|
||||
));
|
||||
}
|
||||
} else if added_credits.is_some()
|
||||
&& let (Some(used), Some(size)) = (
|
||||
self.last_used_tokens,
|
||||
self.last_usage_snapshot
|
||||
.as_ref()
|
||||
.map(|s| s.token_limit)
|
||||
.filter(|&s| s > 0)
|
||||
.or(fallback_limit.filter(|&s| s > 0)),
|
||||
)
|
||||
{
|
||||
out.updates.push((main_session.to_owned(), self.usage_update(used, size)));
|
||||
}
|
||||
if let Some(limits) = quota_limits(data.get("quotaSnapshots")) {
|
||||
out.updates.push((main_session.to_owned(), limits));
|
||||
}
|
||||
}
|
||||
"session.compaction_complete" if agent_id.is_none() => {
|
||||
if data.get("success").and_then(Value::as_bool) == Some(true) {
|
||||
let used = u32_of(data, "postCompactionTokens");
|
||||
let size = u32_of(data, "tokenLimit")
|
||||
.filter(|&n| n > 0)
|
||||
.or_else(|| self.last_usage_snapshot.as_ref().map(|s| s.token_limit).filter(|&n| n > 0))
|
||||
.or(fallback_limit.filter(|&n| n > 0));
|
||||
if let (Some(used), Some(size)) = (used, size) {
|
||||
self.record_snapshot(UsageSnapshot {
|
||||
current_tokens: used,
|
||||
token_limit: size,
|
||||
system_tokens: u32_of(data, "systemTokens"),
|
||||
tool_definitions_tokens: u32_of(data, "toolDefinitionsTokens"),
|
||||
conversation_tokens: u32_of(data, "conversationTokens"),
|
||||
});
|
||||
out.updates.push((main_session.to_owned(), self.usage_update(used, size)));
|
||||
}
|
||||
}
|
||||
}
|
||||
"session.idle" if agent_id.is_none() => {
|
||||
let mode = str_of(data, "mode").unwrap_or_default();
|
||||
if mode != "autopilot" {
|
||||
@@ -370,55 +292,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 {
|
||||
@@ -669,34 +542,11 @@ pub(super) fn available_commands(commands_res: Option<&Value>, skills_res: Optio
|
||||
continue;
|
||||
}
|
||||
let hint = cmd.pointer("/input/hint").and_then(Value::as_str).filter(|h| !h.is_empty());
|
||||
let mut seen_choices = HashSet::new();
|
||||
let choices: Vec<Value> = cmd
|
||||
.pointer("/input/choices")
|
||||
.and_then(Value::as_array)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|ch| {
|
||||
let choice_name = str_of(ch, "name").map(str::trim).filter(|n| !n.is_empty())?;
|
||||
if !seen_choices.insert(choice_name.to_ascii_lowercase()) {
|
||||
return None;
|
||||
}
|
||||
Some(json!({
|
||||
"name": choice_name,
|
||||
"description": str_of(ch, "description").unwrap_or_default(),
|
||||
}))
|
||||
})
|
||||
.collect();
|
||||
let input = match (hint, choices.is_empty()) {
|
||||
(Some(h), false) => Some(json!({ "hint": h, "choices": choices })),
|
||||
(Some(h), true) => Some(json!({ "hint": h })),
|
||||
(None, false) => Some(json!({ "choices": choices })),
|
||||
(None, true) => None,
|
||||
};
|
||||
out.push(json!({
|
||||
"name": name,
|
||||
"description": str_of(cmd, "description").unwrap_or_default(),
|
||||
"source": "command",
|
||||
"input": input,
|
||||
"input": hint.map(|h| json!({ "hint": h })),
|
||||
}));
|
||||
}
|
||||
for skill in skills_res.and_then(|v| v.get("skills")).and_then(Value::as_array).into_iter().flatten() {
|
||||
@@ -723,252 +573,9 @@ pub(super) fn available_commands(commands_res: Option<&Value>, skills_res: Optio
|
||||
"input": hint.map(|h| json!({ "hint": h })),
|
||||
}));
|
||||
}
|
||||
if seen.insert("compact".to_owned()) {
|
||||
out.push(json!({
|
||||
"name": "compact",
|
||||
"description": "Compact conversation history to free context window space",
|
||||
"source": "command",
|
||||
"input": { "hint": "optional focus instructions" },
|
||||
}));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Converts Copilot's `session.metadata.getContextAttribution` payload into [`AgentContextUsage`],
|
||||
/// grouping items into `System` (`System prompt`, `Tool Definitions`, …) and `User Context`
|
||||
/// (`Tool Results`, `Messages`, `Skills`, …) without double-counting parent rollup entries.
|
||||
pub(super) fn context_usage_from_attribution(
|
||||
res: &Value,
|
||||
fallback_model: &str,
|
||||
fallback_limit: Option<u32>,
|
||||
) -> Option<AgentContextUsage> {
|
||||
let attr = res.get("contextAttribution").unwrap_or(res);
|
||||
if !attr.is_object() {
|
||||
return None;
|
||||
}
|
||||
let total_tokens = u32_of(attr, "totalTokens")?;
|
||||
let max_tokens = u32_of(attr, "limit")
|
||||
.filter(|&n| n > 0)
|
||||
.or_else(|| u32_of(attr, "promptTokenLimit").filter(|&n| n > 0))
|
||||
.or_else(|| fallback_limit.filter(|&n| n > 0))?;
|
||||
let reserved_tokens = u32_of(attr, "bufferTokens").filter(|&n| n > 0);
|
||||
let model = str_of(attr, "modelId").filter(|s| !s.is_empty()).unwrap_or(fallback_model).to_owned();
|
||||
let auto_compact_threshold = u32_of(attr, "compactionThreshold").filter(|&n| n > 0);
|
||||
let is_auto_compact_enabled = auto_compact_threshold.map(|_| true);
|
||||
|
||||
let mut categories = Vec::new();
|
||||
let entries = attr.get("entries").and_then(Value::as_array).filter(|e| !e.is_empty());
|
||||
|
||||
if let Some(entries) = entries {
|
||||
// Any entry referenced via `parentId` is a rollup parent whose children are accounted for individually.
|
||||
let parent_ids: HashSet<&str> = entries.iter().filter_map(|e| str_of(e, "parentId")).collect();
|
||||
let mut system_rows: Vec<(String, u32)> = Vec::new();
|
||||
let mut tool_definitions: u32 = 0;
|
||||
let mut tool_results: u32 = 0;
|
||||
let mut skills: u32 = 0;
|
||||
let mut subagents: u32 = 0;
|
||||
let mut mcp_tools: u32 = 0;
|
||||
let mut plugins: u32 = 0;
|
||||
let mut other_user: BTreeMap<String, u32> = BTreeMap::new();
|
||||
let mut accounted: u32 = 0;
|
||||
|
||||
for entry in entries {
|
||||
if let Some(id) = str_of(entry, "id")
|
||||
&& parent_ids.contains(id)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let tokens = u32_of(entry, "tokens").unwrap_or(0);
|
||||
if tokens == 0 {
|
||||
continue;
|
||||
}
|
||||
accounted = accounted.saturating_add(tokens);
|
||||
match str_of(entry, "kind").unwrap_or_default() {
|
||||
"system" => {
|
||||
let label = normalize_system_label(str_of(entry, "label").unwrap_or("System prompt"));
|
||||
if let Some((_, existing)) = system_rows.iter_mut().find(|(k, _)| k == &label) {
|
||||
*existing = existing.saturating_add(tokens);
|
||||
} else {
|
||||
system_rows.push((label, tokens));
|
||||
}
|
||||
}
|
||||
"toolDefinition" => tool_definitions = tool_definitions.saturating_add(tokens),
|
||||
"tool" => tool_results = tool_results.saturating_add(tokens),
|
||||
"skill" => skills = skills.saturating_add(tokens),
|
||||
"subagent" => subagents = subagents.saturating_add(tokens),
|
||||
"mcpServer" => mcp_tools = mcp_tools.saturating_add(tokens),
|
||||
"plugin" => plugins = plugins.saturating_add(tokens),
|
||||
kind => {
|
||||
let label = str_of(entry, "label").filter(|s| !s.is_empty()).unwrap_or(kind).to_owned();
|
||||
let slot = other_user.entry(label).or_insert(0);
|
||||
*slot = slot.saturating_add(tokens);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (name, tokens) in system_rows {
|
||||
categories.push(used_category(name, tokens, "System"));
|
||||
}
|
||||
if tool_definitions > 0 {
|
||||
categories.push(used_category("Tool Definitions", tool_definitions, "System"));
|
||||
}
|
||||
if tool_results > 0 {
|
||||
categories.push(used_category("Tool Results", tool_results, "User Context"));
|
||||
}
|
||||
let messages = total_tokens.saturating_sub(accounted);
|
||||
if messages > 0 {
|
||||
categories.push(used_category("Messages", messages, "User Context"));
|
||||
}
|
||||
if skills > 0 {
|
||||
categories.push(used_category("Skills", skills, "User Context"));
|
||||
}
|
||||
if subagents > 0 {
|
||||
categories.push(used_category("Sub-agents", subagents, "User Context"));
|
||||
}
|
||||
if mcp_tools > 0 {
|
||||
categories.push(used_category("MCP tools", mcp_tools, "User Context"));
|
||||
}
|
||||
if plugins > 0 {
|
||||
categories.push(used_category("Plugins", plugins, "User Context"));
|
||||
}
|
||||
for (name, tokens) in other_user {
|
||||
categories.push(used_category(name, tokens, "User Context"));
|
||||
}
|
||||
} else if let Some(cats) = attr.get("categories").and_then(Value::as_object) {
|
||||
let get = |k: &str| cats.get(k).and_then(Value::as_u64).and_then(|n| u32::try_from(n).ok()).unwrap_or(0);
|
||||
let sys_prompt = get("systemPrompt");
|
||||
let custom_inst = get("customInstructions");
|
||||
let tool_defs = get("systemTools").saturating_add(get("mcpTools"));
|
||||
let messages = get("messages");
|
||||
if sys_prompt > 0 {
|
||||
categories.push(used_category("System prompt", sys_prompt, "System"));
|
||||
}
|
||||
if custom_inst > 0 {
|
||||
categories.push(used_category("Custom instructions", custom_inst, "System"));
|
||||
}
|
||||
if tool_defs > 0 {
|
||||
categories.push(used_category("Tool Definitions", tool_defs, "System"));
|
||||
}
|
||||
if messages > 0 {
|
||||
categories.push(used_category("Messages", messages, "User Context"));
|
||||
}
|
||||
}
|
||||
|
||||
push_free_space(&mut categories, total_tokens, max_tokens, reserved_tokens);
|
||||
Some(AgentContextUsage {
|
||||
categories,
|
||||
total_tokens,
|
||||
max_tokens,
|
||||
model,
|
||||
is_auto_compact_enabled,
|
||||
auto_compact_threshold,
|
||||
reserved_tokens,
|
||||
})
|
||||
}
|
||||
|
||||
/// Converts Copilot's `session.metadata.contextInfo` payload into [`AgentContextUsage`].
|
||||
pub(super) fn context_usage_from_context_info(
|
||||
res: &Value,
|
||||
fallback_model: &str,
|
||||
fallback_limit: Option<u32>,
|
||||
) -> Option<AgentContextUsage> {
|
||||
let info = res.get("contextInfo").unwrap_or(res);
|
||||
if !info.is_object() {
|
||||
return None;
|
||||
}
|
||||
let total_tokens = u32_of(info, "totalTokens")?;
|
||||
let max_tokens = u32_of(info, "limit")
|
||||
.filter(|&n| n > 0)
|
||||
.or_else(|| u32_of(info, "promptTokenLimit").filter(|&n| n > 0))
|
||||
.or_else(|| fallback_limit.filter(|&n| n > 0))?;
|
||||
let reserved_tokens = u32_of(info, "bufferTokens").filter(|&n| n > 0);
|
||||
let model = str_of(info, "displayModelName")
|
||||
.or_else(|| str_of(info, "modelName"))
|
||||
.filter(|s| !s.is_empty())
|
||||
.unwrap_or(fallback_model)
|
||||
.to_owned();
|
||||
let auto_compact_threshold = u32_of(info, "compactionThreshold").filter(|&n| n > 0);
|
||||
let is_auto_compact_enabled = auto_compact_threshold.map(|_| true);
|
||||
|
||||
let mut categories = Vec::new();
|
||||
if let Some(sys) = u32_of(info, "systemTokens").filter(|&n| n > 0) {
|
||||
categories.push(used_category("System prompt", sys, "System"));
|
||||
}
|
||||
if let Some(tools) = u32_of(info, "toolDefinitionsTokens").filter(|&n| n > 0) {
|
||||
categories.push(used_category("Tool Definitions", tools, "System"));
|
||||
}
|
||||
if let Some(conv) = u32_of(info, "conversationTokens").filter(|&n| n > 0) {
|
||||
categories.push(used_category("Messages", conv, "User Context"));
|
||||
}
|
||||
push_free_space(&mut categories, total_tokens, max_tokens, reserved_tokens);
|
||||
Some(AgentContextUsage {
|
||||
categories,
|
||||
total_tokens,
|
||||
max_tokens,
|
||||
model,
|
||||
is_auto_compact_enabled,
|
||||
auto_compact_threshold,
|
||||
reserved_tokens,
|
||||
})
|
||||
}
|
||||
|
||||
/// Fallback breakdown from the latest `session.usage_info` / compaction snapshot.
|
||||
pub(super) fn context_usage_from_snapshot(snap: &UsageSnapshot, model: &str) -> AgentContextUsage {
|
||||
let mut categories = Vec::new();
|
||||
if let Some(sys) = snap.system_tokens.filter(|&n| n > 0) {
|
||||
categories.push(used_category("System prompt", sys, "System"));
|
||||
}
|
||||
if let Some(tools) = snap.tool_definitions_tokens.filter(|&n| n > 0) {
|
||||
categories.push(used_category("Tool Definitions", tools, "System"));
|
||||
}
|
||||
if let Some(conv) = snap.conversation_tokens.filter(|&n| n > 0) {
|
||||
categories.push(used_category("Messages", conv, "User Context"));
|
||||
}
|
||||
push_free_space(&mut categories, snap.current_tokens, snap.token_limit, None);
|
||||
AgentContextUsage {
|
||||
categories,
|
||||
total_tokens: snap.current_tokens,
|
||||
max_tokens: snap.token_limit,
|
||||
model: model.to_owned(),
|
||||
is_auto_compact_enabled: None,
|
||||
auto_compact_threshold: None,
|
||||
reserved_tokens: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn used_category(name: impl Into<String>, tokens: u32, group: &str) -> AgentContextCategory {
|
||||
AgentContextCategory { name: name.into(), tokens, kind: Some("used".to_owned()), group: Some(group.to_owned()) }
|
||||
}
|
||||
|
||||
fn push_free_space(
|
||||
categories: &mut Vec<AgentContextCategory>,
|
||||
total_tokens: u32,
|
||||
max_tokens: u32,
|
||||
reserved_tokens: Option<u32>,
|
||||
) {
|
||||
let free = max_tokens.saturating_sub(total_tokens.saturating_add(reserved_tokens.unwrap_or(0)));
|
||||
if free > 0 {
|
||||
categories.push(AgentContextCategory {
|
||||
name: "Free space".to_owned(),
|
||||
tokens: free,
|
||||
kind: Some("free".to_owned()),
|
||||
group: None,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn normalize_system_label(raw: &str) -> String {
|
||||
match raw.trim().to_ascii_lowercase().as_str() {
|
||||
"system prompt" | "system" | "system instructions" => "System prompt".to_owned(),
|
||||
"custom instructions" => "Custom instructions".to_owned(),
|
||||
_ => raw.trim().to_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
fn u32_of(v: &Value, key: &str) -> Option<u32> {
|
||||
v.get(key).and_then(Value::as_u64).and_then(|n| u32::try_from(n).ok())
|
||||
}
|
||||
|
||||
/// The running entries of a `session.tasks.list` result, in the background-task shape the
|
||||
/// app shows (`task_id`, `task_type`, `description`).
|
||||
pub(super) fn background_tasks(list: &Value) -> Vec<Value> {
|
||||
|
||||
@@ -25,7 +25,11 @@ use std::sync::Arc;
|
||||
/// 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 {
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -114,7 +114,7 @@ impl ProviderSpec {
|
||||
if !program.is_absolute() {
|
||||
return self.login_hint.clone();
|
||||
}
|
||||
let search = ide_core::tool_path::search_path();
|
||||
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))
|
||||
@@ -623,7 +623,7 @@ pub(crate) fn describe(spec: &ProviderSpec) -> AgentProvider {
|
||||
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.command, &spec.env),
|
||||
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(),
|
||||
env: spec.env.iter().cloned().collect(),
|
||||
@@ -1057,23 +1057,19 @@ pub(crate) fn load(custom_dir: Option<&Path>, secrets: Option<&dyn EnvSecrets>)
|
||||
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 {
|
||||
@@ -1330,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();
|
||||
|
||||
@@ -189,11 +189,6 @@ fn parse(text: &str) -> IdeResult<Vec<Entry>> {
|
||||
/// `github/copilot-cli` publishes standalone archives and `SHA256SUMS.txt` on every GitHub
|
||||
/// release. Supplying them installs Copilot without Node.js, npm, `~/.npmrc`, or mirror lag.
|
||||
fn add_copilot_release_binaries(entry: &mut Entry, release_base: &str) {
|
||||
let sys_root = if cfg!(target_os = "linux") { Some(Path::new("/")) } else { None };
|
||||
add_copilot_release_binaries_with_root(entry, release_base, sys_root);
|
||||
}
|
||||
|
||||
fn add_copilot_release_binaries_with_root(entry: &mut Entry, release_base: &str, sys_root: Option<&Path>) {
|
||||
let tag = format!("v{}", entry.version.trim_start_matches('v'));
|
||||
let base = format!("{}/{}", release_base.trim_end_matches('/'), tag);
|
||||
let sha256_url = format!("{base}/SHA256SUMS.txt");
|
||||
@@ -201,12 +196,9 @@ fn add_copilot_release_binaries_with_root(entry: &mut Entry, release_base: &str,
|
||||
Some(p) => (p.args.clone(), p.env.clone()),
|
||||
None => (vec!["--acp".into()], BTreeMap::new()),
|
||||
};
|
||||
let linux_arm = format!(
|
||||
"copilot-{}-arm64.tar.gz",
|
||||
sys_root.map_or("linux", |root| copilot_linux_variant_at(root, Arch::Arm64))
|
||||
);
|
||||
let linux_x64 =
|
||||
format!("copilot-{}-x64.tar.gz", sys_root.map_or("linux", |root| copilot_linux_variant_at(root, Arch::X64)));
|
||||
let linux = if cfg!(target_env = "musl") { "linuxmusl" } else { "linux" };
|
||||
let linux_arm = format!("copilot-{linux}-arm64.tar.gz");
|
||||
let linux_x64 = format!("copilot-{linux}-x64.tar.gz");
|
||||
let targets = [
|
||||
("darwin-aarch64", "copilot-darwin-arm64.tar.gz", "./copilot"),
|
||||
("darwin-x86_64", "copilot-darwin-x64.tar.gz", "./copilot"),
|
||||
@@ -227,22 +219,6 @@ fn add_copilot_release_binaries_with_root(entry: &mut Entry, release_base: &str,
|
||||
}
|
||||
}
|
||||
|
||||
/// Picks `linux` (glibc) or `linuxmusl` from the host's runtime dynamic linker rather than
|
||||
/// `cfg!(target_env = "musl")`: `openidea-server` on Linux is built as static musl so it runs
|
||||
/// on every distro, while Copilot's Linux archives dynamically link glibc or musl.
|
||||
fn copilot_linux_variant_at(root: &Path, arch: Arch) -> &'static str {
|
||||
let (glibc_rel, musl_rel) = match arch {
|
||||
Arch::Arm64 => ("lib/ld-linux-aarch64.so.1", "lib/ld-musl-aarch64.so.1"),
|
||||
Arch::X64 => ("lib64/ld-linux-x86-64.so.2", "lib/ld-musl-x86_64.so.1"),
|
||||
};
|
||||
let glibc = root.join(glibc_rel);
|
||||
let has_musl_name = |p: PathBuf| p.file_name().is_some_and(|n| n.to_string_lossy().contains("musl"));
|
||||
let points_to_musl =
|
||||
fs::read_link(&glibc).is_ok_and(has_musl_name) || fs::canonicalize(&glibc).is_ok_and(has_musl_name);
|
||||
let has_glibc = glibc.exists() && !points_to_musl;
|
||||
if !has_glibc && root.join(musl_rel).exists() { "linuxmusl" } else { "linux" }
|
||||
}
|
||||
|
||||
fn safe_segment(s: &str) -> bool {
|
||||
!s.is_empty()
|
||||
&& !s.starts_with('.')
|
||||
@@ -320,7 +296,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.
|
||||
@@ -708,8 +684,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)
|
||||
}
|
||||
|
||||
@@ -790,8 +765,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"])
|
||||
@@ -1330,96 +1304,4 @@ esac
|
||||
assert!(npm_bin.is_file());
|
||||
assert_eq!(CustomAgent::read(&p.agent_file("copilot")).unwrap().command, npm_bin.to_string_lossy());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selects_copilot_linux_archive_from_runtime_dynamic_linker() {
|
||||
let index = r#"{"agents":[
|
||||
{"id":"github-copilot-cli","name":"Copilot","version":"1.0.116",
|
||||
"distribution":{"npx":{"package":"@github/[email protected]","args":["--acp"]}}}
|
||||
]}"#;
|
||||
let archives_for = |root: &Path| -> (String, String) {
|
||||
let mut entry = parse(index).unwrap().remove(0);
|
||||
entry.distribution.binary.clear();
|
||||
add_copilot_release_binaries_with_root(&mut entry, "https://example.invalid/releases", Some(root));
|
||||
(
|
||||
entry.distribution.binary["linux-x86_64"].archive.clone(),
|
||||
entry.distribution.binary["linux-aarch64"].archive.clone(),
|
||||
)
|
||||
};
|
||||
let touch = |path: PathBuf| {
|
||||
fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
fs::write(path, b"").unwrap();
|
||||
};
|
||||
|
||||
// 1. Non-FHS root (neither loader present) defaults to glibc archives.
|
||||
let empty = tempfile::tempdir().unwrap();
|
||||
assert_eq!(
|
||||
archives_for(empty.path()),
|
||||
(
|
||||
"https://example.invalid/releases/v1.0.116/copilot-linux-x64.tar.gz".into(),
|
||||
"https://example.invalid/releases/v1.0.116/copilot-linux-arm64.tar.gz".into(),
|
||||
)
|
||||
);
|
||||
|
||||
// 2. Standard glibc host (and glibc host with musl-tools also installed) uses `copilot-linux-*`,
|
||||
// even when `openidea-server` itself is compiled for `*-unknown-linux-musl`.
|
||||
let glibc = tempfile::tempdir().unwrap();
|
||||
touch(glibc.path().join("lib64/ld-linux-x86-64.so.2"));
|
||||
touch(glibc.path().join("lib/ld-linux-aarch64.so.1"));
|
||||
assert_eq!(
|
||||
archives_for(glibc.path()),
|
||||
(
|
||||
"https://example.invalid/releases/v1.0.116/copilot-linux-x64.tar.gz".into(),
|
||||
"https://example.invalid/releases/v1.0.116/copilot-linux-arm64.tar.gz".into(),
|
||||
)
|
||||
);
|
||||
touch(glibc.path().join("lib/ld-musl-x86_64.so.1"));
|
||||
touch(glibc.path().join("lib/ld-musl-aarch64.so.1"));
|
||||
assert_eq!(
|
||||
archives_for(glibc.path()),
|
||||
(
|
||||
"https://example.invalid/releases/v1.0.116/copilot-linux-x64.tar.gz".into(),
|
||||
"https://example.invalid/releases/v1.0.116/copilot-linux-arm64.tar.gz".into(),
|
||||
)
|
||||
);
|
||||
|
||||
// 3. musl-only host (e.g. Alpine) uses `copilot-linuxmusl-*`.
|
||||
let musl = tempfile::tempdir().unwrap();
|
||||
touch(musl.path().join("lib/ld-musl-x86_64.so.1"));
|
||||
touch(musl.path().join("lib/ld-musl-aarch64.so.1"));
|
||||
assert_eq!(
|
||||
archives_for(musl.path()),
|
||||
(
|
||||
"https://example.invalid/releases/v1.0.116/copilot-linuxmusl-x64.tar.gz".into(),
|
||||
"https://example.invalid/releases/v1.0.116/copilot-linuxmusl-arm64.tar.gz".into(),
|
||||
)
|
||||
);
|
||||
|
||||
// 4. Alpine `libc6-compat` / `gcompat` symlinking `ld-linux` to `ld-musl` still picks `linuxmusl`.
|
||||
#[cfg(unix)]
|
||||
{
|
||||
fs::create_dir_all(musl.path().join("lib64")).unwrap();
|
||||
std::os::unix::fs::symlink("../lib/ld-musl-x86_64.so.1", musl.path().join("lib64/ld-linux-x86-64.so.2"))
|
||||
.unwrap();
|
||||
std::os::unix::fs::symlink("ld-musl-aarch64.so.1", musl.path().join("lib/ld-linux-aarch64.so.1")).unwrap();
|
||||
assert_eq!(
|
||||
archives_for(musl.path()),
|
||||
(
|
||||
"https://example.invalid/releases/v1.0.116/copilot-linuxmusl-x64.tar.gz".into(),
|
||||
"https://example.invalid/releases/v1.0.116/copilot-linuxmusl-arm64.tar.gz".into(),
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
let parsed = parse(index).unwrap().remove(0);
|
||||
let expected_x64 = format!("copilot-{}-x64.tar.gz", copilot_linux_variant_at(Path::new("/"), Arch::X64));
|
||||
assert!(
|
||||
parsed.distribution.binary["linux-x86_64"].archive.ends_with(&expected_x64),
|
||||
"unexpected linux-x86_64 archive: {}",
|
||||
parsed.distribution.binary["linux-x86_64"].archive
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -32,7 +32,7 @@ pub fn widens_access(params: &Value) -> bool {
|
||||
tool.and_then(|t| t.pointer("/rawInput/networkApprovalContext")).is_some_and(|c| !c.is_null())
|
||||
}
|
||||
|
||||
pub(crate) fn command_from_value(val: &Value) -> Option<String> {
|
||||
fn command_from_value(val: &Value) -> Option<String> {
|
||||
match val {
|
||||
Value::String(s) => {
|
||||
let trimmed = s.trim();
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -209,7 +209,6 @@ impl Frontmatter {
|
||||
source,
|
||||
description: truncate(&description),
|
||||
hint: self.get("argument-hint").filter(|h| !h.is_empty()).map(str::to_owned),
|
||||
choices: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -275,27 +274,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> {
|
||||
let mut out: Vec<AgentSkill> = Vec::new();
|
||||
let mut seen_paths: HashSet<PathBuf> = HashSet::new();
|
||||
@@ -353,19 +337,9 @@ pub fn discover_skills_with_agent_plugins(
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -413,6 +387,83 @@ fn monorepo_subdirs(root: &Path, max_depth: usize) -> Vec<PathBuf> {
|
||||
out
|
||||
}
|
||||
|
||||
/// 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;
|
||||
}
|
||||
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 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
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`
|
||||
/// category folders, validated.
|
||||
fn skills_of(root: &Path, source: AgentSkillSource) -> Vec<AgentSkill> {
|
||||
@@ -492,8 +543,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,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -864,7 +913,6 @@ pub fn menu_commands(offered: Vec<AgentCommand>, states: &[AgentSkillState]) ->
|
||||
description: state.skill.description.clone(),
|
||||
hint: state.skill.hint.clone(),
|
||||
source: AgentCommandSource::Skill,
|
||||
choices: Vec::new(),
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -890,7 +938,6 @@ mod tests {
|
||||
description: description.into(),
|
||||
hint: None,
|
||||
source: AgentCommandSource::Command,
|
||||
choices: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1020,8 +1067,6 @@ mod tests {
|
||||
paths: Vec::new(),
|
||||
valid: true,
|
||||
warnings: Vec::new(),
|
||||
plugin_id: None,
|
||||
plugin_name: None,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -91,7 +91,6 @@ impl Timeline {
|
||||
diffs: Vec::new(),
|
||||
started_ms: Some(crate::now_ms()),
|
||||
ended_ms: None,
|
||||
command: None,
|
||||
};
|
||||
let index = match self.tools.get(&id) {
|
||||
Some(&i) => {
|
||||
@@ -155,7 +154,7 @@ impl Timeline {
|
||||
}
|
||||
|
||||
fn merge_tool(&mut self, index: usize, update: &Value) {
|
||||
let AgentEntry::Tool { title, kind, status, locations: locs, output, images, diffs, ended_ms, command, .. } =
|
||||
let AgentEntry::Tool { title, kind, status, locations: locs, output, images, diffs, ended_ms, .. } =
|
||||
&mut self.entries[index]
|
||||
else {
|
||||
return;
|
||||
@@ -172,11 +171,6 @@ impl Timeline {
|
||||
*ended_ms = Some(crate::now_ms());
|
||||
}
|
||||
}
|
||||
if let Some(raw) = update.pointer("/rawInput/command").or_else(|| update.pointer("/rawInput/cmd"))
|
||||
&& let Some(cmd) = crate::security::command_from_value(raw)
|
||||
{
|
||||
*command = Some(crate::shell_script(&cmd).unwrap_or(cmd));
|
||||
}
|
||||
if update.get("locations").is_some_and(Value::is_array) {
|
||||
*locs = locations(update.get("locations"));
|
||||
}
|
||||
@@ -477,34 +471,6 @@ mod tests {
|
||||
assert!(matches!(&t.entries[0], AgentEntry::Question { chosen: Some(answer), .. } if answer == "One"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_execute_call_keeps_the_command_from_its_structured_input() {
|
||||
let mut t = Timeline::default();
|
||||
let command = |t: &Timeline, i: usize| match &t.entries[i] {
|
||||
AgentEntry::Tool { command, .. } => command.clone(),
|
||||
_ => panic!(),
|
||||
};
|
||||
t.apply(&json!({"sessionUpdate": "tool_call", "toolCallId": "a", "title": "Run command", "kind": "execute",
|
||||
"rawInput": {"command": "python hello_world.py"}}));
|
||||
assert_eq!(command(&t, 0).as_deref(), Some("python hello_world.py"));
|
||||
// An argv array whose shell wraps the script, sent with a later update.
|
||||
t.apply(&json!({"sessionUpdate": "tool_call", "toolCallId": "b", "title": "Run command", "kind": "execute"}));
|
||||
assert_eq!(command(&t, 1), None);
|
||||
t.apply(&json!({"sessionUpdate": "tool_call_update", "toolCallId": "b",
|
||||
"rawInput": {"cmd": ["bash", "-lc", "cargo test -p ide-agent"]}}));
|
||||
assert_eq!(command(&t, 1).as_deref(), Some("cargo test -p ide-agent"));
|
||||
// One shell line, unwrapped as the permission card does.
|
||||
t.apply(&json!({"sessionUpdate": "tool_call", "toolCallId": "c", "kind": "execute",
|
||||
"rawInput": {"command": "/bin/zsh -lc 'node hello.js'"}}));
|
||||
assert_eq!(command(&t, 2).as_deref(), Some("node hello.js"));
|
||||
// A later update without one keeps it; tasks saved before the field load without it.
|
||||
t.apply(&json!({"sessionUpdate": "tool_call_update", "toolCallId": "c", "status": "completed"}));
|
||||
assert_eq!(command(&t, 2).as_deref(), Some("node hello.js"));
|
||||
let mut old = serde_json::to_value(&t.entries[2]).unwrap();
|
||||
old.as_object_mut().unwrap().remove("command");
|
||||
assert!(matches!(serde_json::from_value(old).unwrap(), AgentEntry::Tool { command: None, .. }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tool_images_survive_updates_text_truncation_and_serialization() {
|
||||
use base64::Engine;
|
||||
@@ -523,7 +489,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();
|
||||
@@ -645,8 +611,6 @@ mod tests {
|
||||
sent_ms: Some(sent),
|
||||
done_ms: None,
|
||||
steered: false,
|
||||
recovery: None,
|
||||
retry_attempt: None,
|
||||
};
|
||||
let mut t = Timeline::default();
|
||||
t.push(user(1.0));
|
||||
@@ -668,8 +632,6 @@ mod tests {
|
||||
sent_ms: Some(sent),
|
||||
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,125 +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 })
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
fn worktree_checkout_root(worktrees_dir: &Path, path: &Path) -> (PathBuf, PathBuf) {
|
||||
if let Ok(rel) = path.strip_prefix(worktrees_dir)
|
||||
&& let Some(first) = rel.components().next()
|
||||
{
|
||||
return (worktrees_dir.join(first), worktrees_dir.to_path_buf());
|
||||
}
|
||||
if let Ok(canon_wt_dir) = dunce::canonicalize(worktrees_dir) {
|
||||
if let Ok(rel) = path.strip_prefix(&canon_wt_dir)
|
||||
&& let Some(first) = rel.components().next()
|
||||
{
|
||||
return (canon_wt_dir.join(first), canon_wt_dir);
|
||||
}
|
||||
if let Ok(canon_path) = dunce::canonicalize(path)
|
||||
&& let Ok(rel) = canon_path.strip_prefix(&canon_wt_dir)
|
||||
&& let Some(first) = rel.components().next()
|
||||
{
|
||||
return (canon_wt_dir.join(first), 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
|
||||
@@ -355,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
|
||||
@@ -2188,130 +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}"
|
||||
);
|
||||
}
|
||||
}
|
||||
-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/*"
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "ide-android"
|
||||
description = "Android devices and iOS Simulators and their logs for the Logcat tool window, driven through adb and simctl"
|
||||
description = "Android devices and logcat for the Logcat tool window, driven through the adb CLI"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
@@ -8,7 +8,6 @@ license.workspace = true
|
||||
[dependencies]
|
||||
ide-core.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
specta.workspace = true
|
||||
which = "8"
|
||||
|
||||
|
||||
@@ -1,199 +0,0 @@
|
||||
//! iOS Simulators and their unified log, driven through `xcrun simctl` (macOS only).
|
||||
//!
|
||||
//! A simulator's log is followed with `simctl spawn <udid> log stream --style ndjson`
|
||||
//! and parsed into the same [`LogcatLine`] the Android log uses, so the Logcat tool
|
||||
//! window shows both with one level filter and one filter language.
|
||||
|
||||
use crate::model::{LogcatLevel, LogcatLine};
|
||||
use crate::process;
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::process::Command;
|
||||
use std::time::Duration;
|
||||
|
||||
const LIST: Duration = Duration::from_secs(20);
|
||||
const BATCH_IDLE: Duration = Duration::from_millis(60);
|
||||
const BATCH_MAX: usize = 300;
|
||||
|
||||
/// A booted simulator, as `simctl list devices booted -j` reports it.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct BootedSimulator {
|
||||
pub udid: String,
|
||||
pub name: String,
|
||||
/// e.g. `iOS 27.0`.
|
||||
pub runtime: String,
|
||||
}
|
||||
|
||||
/// Booted simulators; empty off macOS or without Xcode, so nothing iOS-related shows there.
|
||||
pub fn booted_simulators() -> IdeResult<Vec<BootedSimulator>> {
|
||||
if !cfg!(target_os = "macos") {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let mut cmd = Command::new("xcrun");
|
||||
cmd.args(["simctl", "list", "devices", "booted", "-j"]);
|
||||
match process::run(cmd, LIST, None) {
|
||||
Ok(out) if out.success => Ok(parse_simulators(&out.stdout)),
|
||||
// No Xcode (only the Command Line Tools, or none): there are no simulators.
|
||||
_ => Ok(Vec::new()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Parses `simctl list devices -j`, keeping booted devices.
|
||||
pub fn parse_simulators(json: &str) -> Vec<BootedSimulator> {
|
||||
#[derive(Deserialize)]
|
||||
struct List {
|
||||
devices: std::collections::BTreeMap<String, Vec<Device>>,
|
||||
}
|
||||
#[derive(Deserialize)]
|
||||
struct Device {
|
||||
udid: String,
|
||||
name: String,
|
||||
state: String,
|
||||
}
|
||||
let Ok(list) = serde_json::from_str::<List>(json) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let mut out = Vec::new();
|
||||
for (runtime, devices) in list.devices {
|
||||
// "com.apple.CoreSimulator.SimRuntime.iOS-27-0" → "iOS 27.0"
|
||||
let short = runtime.rsplit('.').next().unwrap_or(&runtime);
|
||||
let runtime = short.split_once('-').map_or(short.to_owned(), |(os, v)| format!("{os} {}", v.replace('-', ".")));
|
||||
for d in devices.into_iter().filter(|d| d.state == "Booted") {
|
||||
out.push(BootedSimulator { udid: d.udid, name: d.name, runtime: runtime.clone() });
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Message type of the unified log → the logcat level the window filters and colors by.
|
||||
fn level(message_type: &str) -> LogcatLevel {
|
||||
match message_type {
|
||||
"Debug" => LogcatLevel::Debug,
|
||||
"Info" | "Default" => LogcatLevel::Info,
|
||||
"Error" => LogcatLevel::Error,
|
||||
"Fault" => LogcatLevel::Fatal,
|
||||
_ => LogcatLevel::Verbose,
|
||||
}
|
||||
}
|
||||
|
||||
/// One NDJSON entry of `log stream --style ndjson`; `None` for anything that is not a
|
||||
/// log message (activities, the trailing "terminated" notice). Unknown fields are ignored.
|
||||
pub fn parse_ndjson(line: &str) -> Option<LogcatLine> {
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct Entry {
|
||||
event_type: String,
|
||||
#[serde(default)]
|
||||
message_type: String,
|
||||
#[serde(default)]
|
||||
timestamp: String,
|
||||
#[serde(default)]
|
||||
process_image_path: String,
|
||||
#[serde(rename = "processID", default)]
|
||||
pid: i64,
|
||||
#[serde(rename = "threadID", default)]
|
||||
tid: i64,
|
||||
#[serde(default)]
|
||||
subsystem: String,
|
||||
#[serde(default)]
|
||||
category: String,
|
||||
#[serde(default)]
|
||||
event_message: String,
|
||||
}
|
||||
let e: Entry = serde_json::from_str(line).ok()?;
|
||||
if e.event_type != "logEvent" {
|
||||
return None;
|
||||
}
|
||||
let process = e.process_image_path.rsplit('/').next().unwrap_or_default();
|
||||
let tag = match (e.subsystem.is_empty(), e.category.is_empty()) {
|
||||
(true, _) => process.to_owned(),
|
||||
(false, true) => format!("{process} ({})", e.subsystem),
|
||||
(false, false) => format!("{process} ({}:{})", e.subsystem, e.category),
|
||||
};
|
||||
// "2026-11-29 14:39:31.696480+0900" → "11-29 14:39:31.696", logcat's shape.
|
||||
let time = e.timestamp.get(5..23).unwrap_or(&e.timestamp).to_owned();
|
||||
Some(LogcatLine {
|
||||
time,
|
||||
pid: e.pid as i32,
|
||||
tid: e.tid as i32,
|
||||
level: level(&e.message_type),
|
||||
tag,
|
||||
message: e.event_message,
|
||||
})
|
||||
}
|
||||
|
||||
/// Follows simulator `udid`'s log until `cancel` fires or the simulator shuts down.
|
||||
pub fn simulator_log(
|
||||
udid: &str,
|
||||
cancel: &CancellationToken,
|
||||
on_batch: &mut dyn FnMut(Vec<LogcatLine>),
|
||||
) -> IdeResult<()> {
|
||||
let mut cmd = Command::new("xcrun");
|
||||
cmd.args(["simctl", "spawn", udid, "log", "stream", "--style", "ndjson", "--level", "debug"]);
|
||||
match process::stream_batched(cmd, cancel, BATCH_IDLE, BATCH_MAX, parse_ndjson, on_batch) {
|
||||
Ok((ok, _)) if ok || cancel.is_cancelled() => Ok(()),
|
||||
// `log stream` is killed when the simulator shuts down: that is an end, not a failure.
|
||||
Ok((_, stderr)) if stderr.iter().any(|l| l.contains("terminated with signal")) => Ok(()),
|
||||
Ok((_, stderr)) => Err(IdeError::unavailable(format!("log stream on {udid} stopped: {}", stderr.join("\n")))),
|
||||
Err(e) if e.kind == ide_core::error::ErrorKind::Cancelled => Ok(()),
|
||||
Err(e) => Err(e),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const ENTRY: &str = r#"{"timezoneName":"","messageType":"Error","eventType":"logEvent","source":null,"subsystem":"com.apple.network","category":"endpoint","threadID":90176044,"processImagePath":"\/usr\/libexec\/remindd","timestamp":"2026-11-29 14:39:31.696480+0900","eventMessage":"endpoint has nothing to cleanup","processID":64339,"someFutureField":{"x":[1,2]}}"#;
|
||||
|
||||
#[test]
|
||||
fn parses_an_entry_and_ignores_unknown_fields() {
|
||||
let line = parse_ndjson(ENTRY).unwrap();
|
||||
assert_eq!(line.time, "11-29 14:39:31.696");
|
||||
assert_eq!(line.pid, 64339);
|
||||
assert_eq!(line.tid, 90176044);
|
||||
assert_eq!(line.level, LogcatLevel::Error);
|
||||
assert_eq!(line.tag, "remindd (com.apple.network:endpoint)");
|
||||
assert_eq!(line.message, "endpoint has nothing to cleanup");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_a_multi_line_message_whole() {
|
||||
let entry = r#"{"eventType":"logEvent","messageType":"Default","processImagePath":"/a/MyApp","processID":7,"eventMessage":"first\nsecond"}"#;
|
||||
let line = parse_ndjson(entry).unwrap();
|
||||
assert_eq!(line.message, "first\nsecond");
|
||||
assert_eq!(line.tag, "MyApp");
|
||||
assert_eq!(line.level, LogcatLevel::Info);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn skips_what_is_not_a_log_message() {
|
||||
assert!(parse_ndjson(r#"{"eventType":"activityCreateEvent","eventMessage":"x"}"#).is_none());
|
||||
assert!(parse_ndjson("Child process terminated with signal 15: Terminated").is_none());
|
||||
assert!(parse_ndjson("").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maps_message_types_to_levels() {
|
||||
assert_eq!(level("Debug"), LogcatLevel::Debug);
|
||||
assert_eq!(level("Info"), LogcatLevel::Info);
|
||||
assert_eq!(level("Default"), LogcatLevel::Info);
|
||||
assert_eq!(level("Error"), LogcatLevel::Error);
|
||||
assert_eq!(level("Fault"), LogcatLevel::Fatal);
|
||||
assert_eq!(level("Signpost"), LogcatLevel::Verbose);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_booted_simulators() {
|
||||
let json = r#"{"devices":{"com.apple.CoreSimulator.SimRuntime.iOS-27-0":[
|
||||
{"udid":"A","name":"iPhone Air","state":"Booted","isAvailable":true},
|
||||
{"udid":"B","name":"iPhone 18","state":"Shutdown"}]}}"#;
|
||||
assert_eq!(
|
||||
parse_simulators(json),
|
||||
vec![BootedSimulator { udid: "A".into(), name: "iPhone Air".into(), runtime: "iOS 27.0".into() }]
|
||||
);
|
||||
assert!(parse_simulators("not json").is_empty());
|
||||
}
|
||||
}
|
||||
@@ -7,11 +7,9 @@
|
||||
//!
|
||||
//! Every function blocks; callers run them off the UI / command threads.
|
||||
|
||||
mod ios;
|
||||
mod model;
|
||||
mod process;
|
||||
|
||||
pub use ios::{BootedSimulator, booted_simulators, parse_ndjson, parse_simulators, simulator_log};
|
||||
pub use model::*;
|
||||
|
||||
use ide_core::process::{own_group, prepare};
|
||||
|
||||
@@ -85,26 +85,13 @@ gradle.projectsEvaluated {{
|
||||
|
||||
pub fn publish(root: &Path, cache: &Path, class_paths: &[String], main_class: &str) -> IdeResult<()> {
|
||||
let output = PathBuf::from(fs::read_to_string(cache.join("resource-output.txt"))?.trim());
|
||||
let invalid_output = "The resource build did not report an output directory";
|
||||
if !output.is_absolute() {
|
||||
return Err(IdeError::invalid(invalid_output));
|
||||
if !output.is_absolute() || !output.is_dir() {
|
||||
return Err(IdeError::invalid("The resource build did not report an output directory"));
|
||||
}
|
||||
let output = match fs::metadata(&output) {
|
||||
Ok(metadata) if metadata.is_dir() => Some(dunce::canonicalize(output)?),
|
||||
// Gradle's processResources can succeed with NO-SOURCE and never create its destination.
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
|
||||
_ => return Err(IdeError::invalid(invalid_output)),
|
||||
};
|
||||
let output = dunce::canonicalize(output)?;
|
||||
let paths: Vec<_> = class_paths.iter().filter_map(|p| dunce::canonicalize(root.join(p)).ok()).collect();
|
||||
// A separate resource directory is already on the runtime classpath (e.g. build/resources/main).
|
||||
if output.as_ref().is_some_and(|dir| paths.contains(dir)) {
|
||||
return Ok(());
|
||||
}
|
||||
let previous: Vec<String> = fs::read(cache.join("published-resources.json"))
|
||||
.ok()
|
||||
.and_then(|bytes| serde_json::from_slice(&bytes).ok())
|
||||
.unwrap_or_default();
|
||||
if output.is_none() && previous.is_empty() {
|
||||
if paths.contains(&output) {
|
||||
return Ok(());
|
||||
}
|
||||
// jdtls uses bin/main for Gradle, rather than Gradle's build/resources/main.
|
||||
@@ -112,10 +99,12 @@ pub fn publish(root: &Path, cache: &Path, class_paths: &[String], main_class: &s
|
||||
let destination = paths.iter().find(|p| p.join(&class_file).is_file()).ok_or_else(|| {
|
||||
IdeError::invalid("Cannot find the running main class output directory; restart the application")
|
||||
})?;
|
||||
let previous: Vec<String> = fs::read(cache.join("published-resources.json"))
|
||||
.ok()
|
||||
.and_then(|bytes| serde_json::from_slice(&bytes).ok())
|
||||
.unwrap_or_default();
|
||||
let mut current = Vec::new();
|
||||
if let Some(output) = output {
|
||||
copy_resources(&output, &output, destination, &mut current)?;
|
||||
}
|
||||
copy_resources(&output, &output, destination, &mut current)?;
|
||||
for rel in previous.iter().filter(|p| !current.contains(p)) {
|
||||
let path = destination.join(rel);
|
||||
if path.is_file() {
|
||||
@@ -231,39 +220,6 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_resource_output_publishes_an_empty_set() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
let output = root.join("build/resources/main");
|
||||
let cache = root.join("cache");
|
||||
let runtime = root.join("bin/main");
|
||||
let class_paths = [runtime.to_string_lossy().into_owned()];
|
||||
let resource = "application.properties";
|
||||
fs::create_dir(&cache).unwrap();
|
||||
fs::create_dir_all(runtime.join("example")).unwrap();
|
||||
fs::write(cache.join("resource-output.txt"), output.to_string_lossy().as_bytes()).unwrap();
|
||||
let class = runtime.join("example/Application.class");
|
||||
fs::write(&class, "running").unwrap();
|
||||
|
||||
publish(root, &cache, &class_paths, "example.Application").unwrap();
|
||||
assert!(!output.exists());
|
||||
|
||||
fs::create_dir_all(&output).unwrap();
|
||||
fs::write(output.join(resource), "server.port=8081").unwrap();
|
||||
publish(root, &cache, &class_paths, "example.Application").unwrap();
|
||||
assert!(runtime.join(resource).is_file());
|
||||
|
||||
fs::remove_file(output.join(resource)).unwrap();
|
||||
fs::remove_dir(&output).unwrap();
|
||||
publish(root, &cache, &class_paths, "example.Application").unwrap();
|
||||
assert!(!runtime.join(resource).exists());
|
||||
assert_eq!(fs::read_to_string(class).unwrap(), "running");
|
||||
|
||||
fs::write(output, "not a directory").unwrap();
|
||||
assert!(publish(root, &cache, &class_paths, "example.Application").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn leaves_separate_runtime_resource_directories_in_place_and_rejects_jar_only_runs() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -17,8 +17,8 @@ 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::{
|
||||
StructureJdk, StructureRoots, artifact_file, artifact_output, language_release, structure_compile_file_plan,
|
||||
@@ -29,7 +29,6 @@ pub use up_to_date::{menu_up_to_date, record_menu_build};
|
||||
|
||||
use crate::process::{self, Stream};
|
||||
use crate::{BuildModel, maven};
|
||||
use ide_core::build_jobs::append_default_jobs;
|
||||
use ide_core::settings::CMakeProfile;
|
||||
use ide_core::{CancellationToken, Diagnostic, IdeError, IdeResult, Pos, Range, Severity};
|
||||
use parse::{ColUnit, Format, OutputParser, RawMessage};
|
||||
@@ -421,14 +420,12 @@ 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
|
||||
/// logical CPU unless the profile's build arguments choose a count. The directory and
|
||||
/// `CMakeCache.txt` yet, then `cmake --build` (`--clean-first` to rebuild). 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)
|
||||
@@ -445,54 +442,22 @@ 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());
|
||||
}
|
||||
build.args.extend(profile.map(|p| p.build_args.clone()).unwrap_or_default());
|
||||
append_default_jobs(&mut build.args);
|
||||
build.env = env;
|
||||
steps.push(build);
|
||||
steps
|
||||
@@ -847,74 +812,6 @@ pub fn run(
|
||||
})
|
||||
}
|
||||
|
||||
/// Messages of an `xcodebuild` whose output arrives line by line (an Xcode run configuration),
|
||||
/// each reported once: xcodebuild prints a message for every architecture and again on retries.
|
||||
pub struct XcodebuildMessages {
|
||||
parser: OutputParser,
|
||||
cwd: PathBuf,
|
||||
paths: PathMap,
|
||||
lines: Lines,
|
||||
seen: HashSet<(Option<PathBuf>, Option<Range>, String)>,
|
||||
/// xcodebuild printed its result (`** BUILD SUCCEEDED **`); what follows is the app's console.
|
||||
done: bool,
|
||||
}
|
||||
|
||||
impl XcodebuildMessages {
|
||||
/// Relative paths resolve against `cwd`; paths under `root`'s canonical form map back to `root`.
|
||||
pub fn new(root: &Path, cwd: &Path) -> Self {
|
||||
XcodebuildMessages {
|
||||
parser: OutputParser::new(Format::Xcode),
|
||||
cwd: cwd.to_path_buf(),
|
||||
paths: PathMap::new(root),
|
||||
lines: Lines::default(),
|
||||
seen: HashSet::new(),
|
||||
done: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Messages completed by `line` (without its line break).
|
||||
pub fn feed(&mut self, line: &str) -> Vec<BuildMessage> {
|
||||
if self.done {
|
||||
return Vec::new();
|
||||
}
|
||||
let result = parse::strip_ansi(line);
|
||||
let result = result.trim();
|
||||
if result.len() > 6 && result.starts_with("** ") && result.ends_with(" **") {
|
||||
self.done = true;
|
||||
return self.finish();
|
||||
}
|
||||
let raws = self.parser.feed(line).messages;
|
||||
self.resolve(raws)
|
||||
}
|
||||
|
||||
/// The message still waiting for detail lines.
|
||||
pub fn finish(&mut self) -> Vec<BuildMessage> {
|
||||
let raws = self.parser.finish();
|
||||
self.resolve(raws)
|
||||
}
|
||||
|
||||
fn resolve(&mut self, raws: Vec<RawMessage>) -> Vec<BuildMessage> {
|
||||
raws.into_iter()
|
||||
.map(|raw| {
|
||||
let mut m = resolve(raw, &self.cwd, &self.paths, &mut self.lines);
|
||||
// xcodebuild prints the folder it was started in, which may be a symlink to the project.
|
||||
if let Some(path) = m.path.clone().map(PathBuf::from)
|
||||
&& !path.starts_with(&self.paths.root)
|
||||
&& let Ok(real) = dunce::canonicalize(&path)
|
||||
&& let Some(real) = real.to_str()
|
||||
{
|
||||
let mapped = self.paths.resolve(real, &self.cwd, None);
|
||||
if mapped.starts_with(&self.paths.root) {
|
||||
m.path = Some(mapped.into());
|
||||
}
|
||||
}
|
||||
m
|
||||
})
|
||||
.filter(|m| self.seen.insert((m.path.clone().map(Into::into), m.range, m.text.clone())))
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// Per-file editor / Problems diagnostics of the messages that have a position.
|
||||
pub fn diagnostics(messages: &[BuildMessage]) -> BTreeMap<PathBuf, Vec<Diagnostic>> {
|
||||
diagnostics_from(messages, DIAGNOSTICS_SOURCE)
|
||||
@@ -1018,7 +915,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| {
|
||||
@@ -1436,73 +1333,6 @@ mod tests {
|
||||
}
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn xcodebuild_messages_once_per_build() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let file = tmp.path().join("Warn.swift");
|
||||
std::fs::write(&file, "func f() -> Int {\n var count = 1\n return count\n}\n").unwrap();
|
||||
let mut x = XcodebuildMessages::new(tmp.path(), tmp.path());
|
||||
let warning = format!("{}:2:9: warning: variable 'count' was never mutated", file.display());
|
||||
let mut out = Vec::new();
|
||||
// One copy per architecture, then the linker's per-architecture lists.
|
||||
for line in [
|
||||
warning.as_str(),
|
||||
"SwiftCompile normal arm64 Compiling\\ Warn.swift",
|
||||
warning.as_str(),
|
||||
"Undefined symbols for architecture x86_64:",
|
||||
" \"_sym\", referenced from:",
|
||||
"ld: symbol(s) not found for architecture x86_64",
|
||||
"Undefined symbols for architecture arm64:",
|
||||
" \"_sym\", referenced from:",
|
||||
] {
|
||||
out.extend(x.feed(line));
|
||||
}
|
||||
out.extend(x.finish());
|
||||
assert_eq!(out.len(), 2, "{out:?}");
|
||||
assert_eq!(out[0].path.clone().map(PathBuf::from), Some(file));
|
||||
// `count`, 0-based, underlined.
|
||||
assert_eq!(out[0].range, Some(Range::new(Pos::new(1, 8), Pos::new(1, 13))));
|
||||
assert_eq!(
|
||||
(out[1].path.is_none(), out[1].text.as_str()),
|
||||
(true, "Undefined symbols\n\"_sym\", referenced from:")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn xcodebuild_messages_stop_at_the_build_result() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mut x = XcodebuildMessages::new(tmp.path(), tmp.path());
|
||||
let mut out = Vec::new();
|
||||
// An Xcode run configuration's output: the build, then the app's own console.
|
||||
for line in [
|
||||
"/p/Demo/Demo.xcodeproj: Demo: ld: warning: Could not find or use auto-linked framework 'UIUtilities'",
|
||||
"** BUILD SUCCEEDED **",
|
||||
"error: request failed",
|
||||
"warning: low memory",
|
||||
"Demo/ContentView.swift:12: Fatal error: Unexpectedly found nil while unwrapping an Optional value",
|
||||
] {
|
||||
out.extend(x.feed(line));
|
||||
}
|
||||
out.extend(x.finish());
|
||||
let texts: Vec<_> = out.iter().map(|m| m.text.as_str()).collect();
|
||||
assert_eq!(texts, ["Could not find or use auto-linked framework 'UIUtilities'"]);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn xcodebuild_paths_through_a_symlink_map_to_the_project() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap().join("Demo");
|
||||
std::fs::create_dir(&root).unwrap();
|
||||
std::fs::write(root.join("A.swift"), "let x = y\n").unwrap();
|
||||
let link = tmp.path().join("link");
|
||||
std::os::unix::fs::symlink(&root, &link).unwrap();
|
||||
let mut x = XcodebuildMessages::new(&root, &root);
|
||||
x.feed(&format!("{}/A.swift:1:9: error: cannot find 'y' in scope", link.display()));
|
||||
let out = x.finish();
|
||||
assert_eq!(out[0].path.clone().map(PathBuf::from), Some(root.join("A.swift")));
|
||||
}
|
||||
|
||||
/// Launch outputs use the platform separator throughout, so they compare equal to
|
||||
/// the same directories as JDT LS reports them.
|
||||
#[test]
|
||||
@@ -1678,33 +1508,23 @@ mod tests {
|
||||
let cm = tmp.path().join("cm");
|
||||
write(&cm, "CMakeLists.txt", "project(app)");
|
||||
let args = |p: &BuildPlan| p.steps.iter().map(|s| s.args.join(" ")).collect::<Vec<_>>();
|
||||
let jobs = format!("-j {}", ide_core::build_jobs::default_jobs());
|
||||
let p =
|
||||
plan(&cm, &BuildModel::default(), BuildKind::Build, None, None, None, &CancellationToken::new()).unwrap();
|
||||
assert_eq!(p.system, BuildSystem::CMake);
|
||||
assert_eq!(
|
||||
args(&p),
|
||||
[
|
||||
"-S . -B build -DCMAKE_BUILD_TYPE=Debug -DCMAKE_EXPORT_COMPILE_COMMANDS=ON".to_owned(),
|
||||
format!("--build build --config Debug {jobs}"),
|
||||
"-S . -B build -DCMAKE_BUILD_TYPE=Debug -DCMAKE_EXPORT_COMPILE_COMMANDS=ON",
|
||||
"--build build --config Debug"
|
||||
],
|
||||
"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!(
|
||||
args(&p),
|
||||
[format!("--build cmake-build-release --config Debug --clean-first {jobs}")],
|
||||
["--build cmake-build-release --config Debug --clean-first"],
|
||||
"a configured directory is reused"
|
||||
);
|
||||
let profile = CMakeProfile {
|
||||
@@ -1735,33 +1555,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>");
|
||||
|
||||
@@ -27,10 +27,6 @@ pub(crate) enum Format {
|
||||
Gcc,
|
||||
/// MSBuild (`dotnet build`): `C:\p\A.cs(12,5): error CS1002: msg [C:\p\App.csproj]`.
|
||||
Msbuild,
|
||||
/// `xcodebuild`: swiftc / clang lines like [`Format::Gcc`], their notes (`path:3:6: note:` or
|
||||
/// Swift's `` `- note: `` in the code excerpt), `App.xcodeproj: App: ld: warning: msg` and
|
||||
/// `Undefined symbols for architecture arm64:` with its indented details.
|
||||
Xcode,
|
||||
}
|
||||
|
||||
/// What a printed column counts.
|
||||
@@ -335,59 +331,6 @@ fn gcc_line(line: &str) -> Option<RawMessage> {
|
||||
(!msg.is_empty()).then(|| RawMessage::new(severity, msg, ColUnit::Byte).at(path, ln, col))
|
||||
}
|
||||
|
||||
const UNDEFINED_SYMBOLS: &str = "Undefined symbols";
|
||||
|
||||
/// An `xcodebuild` message: a compiler line, a linker / build-system line without a location, or
|
||||
/// the start of an undefined symbols list. Its architecture is dropped: every one prints the same.
|
||||
fn xcode_line(line: &str) -> Option<RawMessage> {
|
||||
if let Some(m) = gcc_line(line) {
|
||||
return Some(m);
|
||||
}
|
||||
if line.starts_with("Undefined symbols for architecture ") {
|
||||
return Some(RawMessage::new(Severity::Error, UNDEFINED_SYMBOLS, ColUnit::Byte));
|
||||
}
|
||||
// `/p/App.xcodeproj: App: ld: warning: msg`, `error: msg`, `xcodebuild: error: msg`.
|
||||
let rest = [".xcodeproj: ", ".xcworkspace: "]
|
||||
.into_iter()
|
||||
.find_map(|c| line.find(c).map(|i| &line[i + c.len()..]))
|
||||
.or_else(|| (!line.starts_with(char::is_whitespace)).then_some(line))?;
|
||||
let (severity, msg) =
|
||||
[("error: ", Severity::Error), ("warning: ", Severity::Warning)].into_iter().find_map(|(word, severity)| {
|
||||
let at = rest.match_indices(word).map(|(i, _)| i).find(|&i| i == 0 || rest[..i].ends_with(": "))?;
|
||||
// Only `tool: ` / `target: ` words may come before the severity, not a sentence.
|
||||
rest[..at].split(": ").all(|w| !w.contains(' ')).then(|| (severity, rest[at + word.len()..].trim()))
|
||||
})?;
|
||||
(!msg.is_empty()).then(|| RawMessage::new(severity, msg, ColUnit::Byte))
|
||||
}
|
||||
|
||||
/// Whether `line` belongs to the pending `xcodebuild` message (and is folded into it).
|
||||
fn xcode_detail(msg: &mut RawMessage, line: &str) -> bool {
|
||||
let t = line.trim_start();
|
||||
// A `note:` with a location, as clang and `-diagnostic-style llvm` print it.
|
||||
if let Some((_, _, _, rest)) = path_line_col(line)
|
||||
&& let Some(note) = rest.strip_prefix(':').and_then(|r| r.trim_start().strip_prefix("note:"))
|
||||
{
|
||||
msg.text.push_str("\nnote: ");
|
||||
msg.text.push_str(note.trim());
|
||||
return true;
|
||||
}
|
||||
// The code excerpt: ` 9 | switch s {`, ` | `- note: add missing case`.
|
||||
let excerpt = t.trim_start_matches(|c: char| c.is_ascii_digit()).trim_start().starts_with('|');
|
||||
if excerpt {
|
||||
if let Some(i) = t.find("- note: ") {
|
||||
msg.text.push_str("\nnote: ");
|
||||
msg.text.push_str(t[i + "- note: ".len()..].trim());
|
||||
}
|
||||
return true;
|
||||
}
|
||||
if msg.text.starts_with(UNDEFINED_SYMBOLS) && t.len() < line.len() && !t.is_empty() {
|
||||
msg.text.push('\n');
|
||||
msg.text.push_str(t);
|
||||
return true;
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// rustc's JSON diagnostic (`reason: compiler-message`) → message and its rendered text.
|
||||
fn cargo_json(v: &Value) -> Option<(Option<RawMessage>, String)> {
|
||||
if v.get("reason")?.as_str()? != "compiler-message" {
|
||||
@@ -469,9 +412,6 @@ impl OutputParser {
|
||||
.map_or(line, |r| r.strip_prefix(' ').unwrap_or(r)),
|
||||
_ => line,
|
||||
};
|
||||
if format == Format::Xcode {
|
||||
return xcode_detail(&mut p.msg, line);
|
||||
}
|
||||
if matches!(format, Format::Maven | Format::Gradle | Format::Tsc)
|
||||
&& body.starts_with(" ")
|
||||
&& !body.trim().is_empty()
|
||||
@@ -507,7 +447,6 @@ impl OutputParser {
|
||||
Format::Go => go_line(&line),
|
||||
Format::Gcc => gcc_line(&line),
|
||||
Format::Msbuild => msbuild_line(&line),
|
||||
Format::Xcode => xcode_line(&line),
|
||||
Format::Cargo => None,
|
||||
};
|
||||
if let Some(msg) = parsed {
|
||||
@@ -739,103 +678,6 @@ mod tests {
|
||||
assert_eq!(out[2].text, "'missing.h' file not found");
|
||||
}
|
||||
|
||||
// Real `xcodebuild build` output (Xcode 27.1, iOS Simulator, two architectures), paths shortened.
|
||||
#[test]
|
||||
fn xcodebuild_swift_error_warning_and_note() {
|
||||
let out = parse(
|
||||
Format::Xcode,
|
||||
"SwiftCompile normal x86_64 Compiling\\ Warn.swift /p/Demo/Warn.swift (in target 'Demo' from project 'Demo')\n\
|
||||
/p/Demo/Warn.swift:2:9: warning: variable 'count' was never mutated; consider changing to 'let' constant [#VariableNeverMutated]\n\
|
||||
\x201 | func warnMe() -> Int {\n\
|
||||
\x202 | var count = 1\n\
|
||||
\x20 | `- warning: variable 'count' was never mutated; consider changing to 'let' constant [#VariableNeverMutated]\n\
|
||||
\x203 | return count\n\
|
||||
\x204 | }\n\
|
||||
\n\
|
||||
/p/Demo/Warn.swift:9:5: error: switch must be exhaustive\n\
|
||||
\x207 | \n\
|
||||
\x208 | func name(_ s: Shade) -> String {\n\
|
||||
\x209 | switch s {\n\
|
||||
\x20 | |- error: switch must be exhaustive\n\
|
||||
\x20 | `- note: add missing case: '.dark'\n\
|
||||
10 | case .light: return \"light\"\n\
|
||||
11 | }\n\
|
||||
\n\
|
||||
[#VariableNeverMutated]: <https://docs.swift.org/compiler/documentation/diagnostics/variable-never-mutated>\n\
|
||||
Failed frontend command:\n\
|
||||
note: Removed stale file '/p/dd/Demo.swiftmodule'\n",
|
||||
);
|
||||
assert_eq!(out.len(), 2, "{out:?}");
|
||||
assert_eq!(out[0].severity, Severity::Warning);
|
||||
assert_eq!((out[0].path.as_deref(), out[0].line, out[0].col), (Some("/p/Demo/Warn.swift"), Some(2), Some(9)));
|
||||
assert!(out[0].text.starts_with("variable 'count' was never mutated"), "{}", out[0].text);
|
||||
assert_eq!(out[1].severity, Severity::Error);
|
||||
assert_eq!(out[1].text, "switch must be exhaustive\nnote: add missing case: '.dark'");
|
||||
assert_eq!((out[1].line, out[1].col), (Some(9), Some(5)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn xcodebuild_clang_errors_with_note() {
|
||||
let out = parse(
|
||||
Format::Xcode,
|
||||
"/p/Demo/Legacy.m:2:29: error: use of undeclared identifier 'undeclared_thing'\n\
|
||||
\x20 2 | void legacy(void) { int x = undeclared_thing; }\n\
|
||||
\x20 | ^~~~~~~~~~~~~~~~\n\
|
||||
/p/Demo/Legacy.m:4:6: error: redefinition of 'twice'\n\
|
||||
\x20 4 | void twice(void) {}\n\
|
||||
\x20 | ^\n\
|
||||
/p/Demo/Legacy.m:3:6: note: previous definition is here\n\
|
||||
\x20 3 | void twice(void) {}\n\
|
||||
\x20 | ^\n\
|
||||
2 errors generated.\n",
|
||||
);
|
||||
assert_eq!(out.len(), 2, "{out:?}");
|
||||
assert_eq!(out[0].text, "use of undeclared identifier 'undeclared_thing'");
|
||||
assert_eq!((out[0].line, out[0].col), (Some(2), Some(29)));
|
||||
assert_eq!(out[1].text, "redefinition of 'twice'\nnote: previous definition is here");
|
||||
assert_eq!((out[1].line, out[1].col), (Some(4), Some(6)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn xcodebuild_linker_errors_without_location() {
|
||||
let out = parse(
|
||||
Format::Xcode,
|
||||
"Ld /p/dd/Demo.debug.dylib normal arm64 (in target 'Demo' from project 'Demo')\n\
|
||||
\x20 cd /p/Demo\n\
|
||||
\x20 /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang -Xlinker -reproducible -target arm64-apple-ios16.0-simulator -ferror-limit 19\n\
|
||||
/p/Demo/Demo.xcodeproj: Demo: ld: warning: Could not find or use auto-linked framework 'UIUtilities': framework 'UIUtilities' not found\n\
|
||||
Undefined symbols for architecture arm64:\n\
|
||||
\x20 \"_missing_symbol_xyz\", referenced from:\n\
|
||||
\x20 Demo.callMissing() -> () in Missing.o\n\
|
||||
ld: symbol(s) not found for architecture arm64\n\
|
||||
/p/Demo/Demo.xcodeproj: Demo: clang: error: linker command failed with exit code 1 (use -v to see invocation)\n\
|
||||
\n\
|
||||
** BUILD FAILED **\n\
|
||||
\n\
|
||||
The following build commands failed:\n\
|
||||
\tLd /p/dd/Demo.debug.dylib normal arm64 (in target 'Demo' from project 'Demo')\n\
|
||||
xcodebuild: error: Unable to find a destination matching the provided destination specifier\n",
|
||||
);
|
||||
let found: Vec<_> = out.iter().map(|m| (m.severity, m.text.as_str(), m.path.is_none())).collect();
|
||||
assert_eq!(
|
||||
found,
|
||||
[
|
||||
(
|
||||
Severity::Warning,
|
||||
"Could not find or use auto-linked framework 'UIUtilities': framework 'UIUtilities' not found",
|
||||
true
|
||||
),
|
||||
(
|
||||
Severity::Error,
|
||||
"Undefined symbols\n\"_missing_symbol_xyz\", referenced from:\nDemo.callMissing() -> () in Missing.o",
|
||||
true
|
||||
),
|
||||
(Severity::Error, "linker command failed with exit code 1 (use -v to see invocation)", true),
|
||||
(Severity::Error, "Unable to find a destination matching the provided destination specifier", true),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn go_errors() {
|
||||
let out = parse(
|
||||
|
||||
@@ -180,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).
|
||||
@@ -257,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)
|
||||
}
|
||||
@@ -294,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;
|
||||
}
|
||||
@@ -322,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.
|
||||
@@ -370,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.
|
||||
@@ -937,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)]
|
||||
|
||||
@@ -4,8 +4,7 @@
|
||||
//! same way into the test output, which also sees the production classes.
|
||||
use super::*;
|
||||
use ide_core::settings::{
|
||||
ArtifactConfig, ArtifactKind, DependencyScope, ModuleStructureSettings, ProjectStructureSettings, jar_files,
|
||||
split_jar_glob,
|
||||
ArtifactConfig, ArtifactKind, DependencyScope, ModuleStructureSettings, ProjectStructureSettings,
|
||||
};
|
||||
use std::fs;
|
||||
|
||||
@@ -105,17 +104,13 @@ fn library_entries(root: &Path, ps: &ProjectStructureSettings, test: bool) -> Ve
|
||||
module_deps.iter().find(|d| d.kind == "library" && d.target == lib.name).map_or(lib.scope, |d| d.scope);
|
||||
if wanted(scope) {
|
||||
for class in &lib.classes {
|
||||
for entry in class_entries(root, class) {
|
||||
add(entry);
|
||||
}
|
||||
add(class_entry(root, class));
|
||||
}
|
||||
}
|
||||
}
|
||||
for dep in module_deps.iter().filter(|d| d.kind == "library" && wanted(d.scope)) {
|
||||
if !ps.libraries.iter().any(|l| l.name == dep.target) && !dep.target.trim().is_empty() {
|
||||
for entry in class_entries(root, &dep.target) {
|
||||
add(entry);
|
||||
}
|
||||
add(class_entry(root, &dep.target));
|
||||
}
|
||||
}
|
||||
for facet in ps.facets.iter().filter(|f| f.kind == "web") {
|
||||
@@ -138,50 +133,29 @@ fn web_root(root: &Path, facet: &ide_core::settings::FacetConfig) -> PathBuf {
|
||||
root.join(dir)
|
||||
}
|
||||
|
||||
/// The folders under `dir` (itself included) that hold `.jar` files, in walk order.
|
||||
fn jar_dirs(dir: &Path) -> Vec<PathBuf> {
|
||||
let mut dirs: Vec<PathBuf> = Vec::new();
|
||||
for jar in jar_files(dir, true) {
|
||||
if let Some(parent) = jar.parent().filter(|p| !dirs.iter().any(|d| d == p)) {
|
||||
dirs.push(parent.to_path_buf());
|
||||
}
|
||||
}
|
||||
dirs
|
||||
}
|
||||
|
||||
/// The class archives and folders of a library path (`lib/*.jar`, `lib/**/*.jar`, or a folder
|
||||
/// containing JARs expands to those JARs; a folder without JARs stays a class folder).
|
||||
/// The class archives and folders of a library path (`lib/*.jar` lists the folder's jars).
|
||||
fn library_files(root: &Path, value: &str) -> Vec<PathBuf> {
|
||||
if let Some((base, recursive)) = split_jar_glob(value) {
|
||||
return jar_files(&root.join(base), recursive);
|
||||
}
|
||||
let path = root.join(value.trim());
|
||||
if path.is_dir() {
|
||||
let jars = jar_files(&path, true);
|
||||
if !jars.is_empty() {
|
||||
return jars;
|
||||
let entry = class_entry(root, value);
|
||||
match entry.strip_suffix('*') {
|
||||
Some(dir) => {
|
||||
let mut jars: Vec<PathBuf> = fs::read_dir(dir)
|
||||
.map(|d| d.flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|x| x == "jar")).collect())
|
||||
.unwrap_or_default();
|
||||
jars.sort();
|
||||
jars
|
||||
}
|
||||
None => vec![PathBuf::from(entry)],
|
||||
}
|
||||
vec![path]
|
||||
}
|
||||
|
||||
/// Classpath entries for a library path: `lib/*.jar` stays `lib/*` for javac to expand; a
|
||||
/// directory containing JARs expands to `<dir>/*` per folder holding JARs.
|
||||
fn class_entries(root: &Path, value: &str) -> Vec<String> {
|
||||
let wildcard = |dir: &Path| format!("{}{}*", dir.to_string_lossy(), std::path::MAIN_SEPARATOR);
|
||||
if let Some((base, recursive)) = split_jar_glob(value) {
|
||||
let dir = root.join(base);
|
||||
let dirs = if recursive { jar_dirs(&dir) } else { Vec::new() };
|
||||
return if dirs.is_empty() { vec![wildcard(&dir)] } else { dirs.iter().map(|d| wildcard(d)).collect() };
|
||||
}
|
||||
/// A classpath entry for a library path: a folder of jars (`lib/*`) stays a wildcard javac expands.
|
||||
fn class_entry(root: &Path, value: &str) -> String {
|
||||
let path = root.join(value.trim());
|
||||
if path.is_dir() {
|
||||
let dirs = jar_dirs(&path);
|
||||
if !dirs.is_empty() {
|
||||
return dirs.iter().map(|d| wildcard(d)).collect();
|
||||
}
|
||||
let text = path.to_string_lossy().into_owned();
|
||||
if text.ends_with("/*.jar") || text.ends_with("\\*.jar") {
|
||||
return text[..text.len() - 4].to_owned();
|
||||
}
|
||||
vec![path.to_string_lossy().into_owned()]
|
||||
text
|
||||
}
|
||||
|
||||
fn classpath(entries: &[String]) -> String {
|
||||
@@ -466,10 +440,7 @@ pub fn structure_web_artifacts(ps: &ProjectStructureSettings) -> Vec<&ArtifactCo
|
||||
ps.artifacts.iter().filter(|a| matches!(a.kind, ArtifactKind::War | ArtifactKind::WarExploded)).collect()
|
||||
}
|
||||
|
||||
/// A build of `artifact` for Tomcat's deployment, compiling production classes first.
|
||||
/// When `war` is `Some`, packs a WAR archive at that path; when `None`, writes to the
|
||||
/// artifact's own output (`artifact_file`: a `.war` archive for `War`, or the exploded
|
||||
/// directory for `WarExploded`).
|
||||
/// A build of `artifact` into the WAR `war` (Tomcat's deployment), compiling first.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn structure_war_plan(
|
||||
root: &Path,
|
||||
@@ -478,7 +449,7 @@ pub fn structure_war_plan(
|
||||
jdk: Option<&StructureJdk>,
|
||||
language_level: &str,
|
||||
artifact: &ArtifactConfig,
|
||||
war: Option<&Path>,
|
||||
war: &Path,
|
||||
cache: &Path,
|
||||
) -> IdeResult<BuildPlan> {
|
||||
let mut plan = structure_plan(root, ps, roots, jdk, language_level, BuildKind::Build, cache)?
|
||||
@@ -488,7 +459,7 @@ pub fn structure_war_plan(
|
||||
plan.steps.retain(|s| !s.args.iter().any(|a| a.ends_with("test.args")));
|
||||
plan.steps
|
||||
.retain(|s| !matches!(&s.action, Some((Action::CopyResources { to, .. }, _)) if !to.starts_with(&main_out)));
|
||||
plan.steps.extend(artifact_steps(root, ps, artifact, &main_out, war, cache));
|
||||
plan.steps.extend(artifact_steps(root, ps, artifact, &main_out, Some(war), cache));
|
||||
plan.title = artifact.name.clone();
|
||||
Ok(plan)
|
||||
}
|
||||
@@ -1173,53 +1144,4 @@ mod tests {
|
||||
bad_result.messages
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn expands_jar_directory_libraries_for_javac_and_artifacts() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path().join("app");
|
||||
let cache = tmp.path().join("cache");
|
||||
write(&root.join("src/A.java"), "class A {}");
|
||||
write(&root.join("WebRoot/WEB-INF/lib/gson.jar"), "jar1");
|
||||
write(&root.join("WebRoot/WEB-INF/lib/sub/extra.jar"), "jar2");
|
||||
fs::create_dir_all(root.join("plain-classes")).unwrap();
|
||||
write(&root.join("plain-classes/Helper.class"), "");
|
||||
|
||||
let ps = ProjectStructureSettings {
|
||||
libraries: vec![
|
||||
ProjectLibrary {
|
||||
name: "web-libs".into(),
|
||||
classes: vec!["WebRoot/WEB-INF/lib".into()],
|
||||
..Default::default()
|
||||
},
|
||||
ProjectLibrary { name: "classes".into(), classes: vec!["plain-classes".into()], ..Default::default() },
|
||||
],
|
||||
artifacts: vec![ArtifactConfig {
|
||||
name: "app:war exploded".into(),
|
||||
kind: ArtifactKind::WarExploded,
|
||||
module: ".".into(),
|
||||
output_directory: "out/artifacts/app_war_exploded".into(),
|
||||
main_class: String::new(),
|
||||
include_libraries: vec!["web-libs".into()],
|
||||
}],
|
||||
..Default::default()
|
||||
};
|
||||
let roots = StructureRoots { sources: vec![root.join("src")], ..Default::default() };
|
||||
let plan = structure_plan(&root, &ps, &roots, None, "17", BuildKind::Artifacts, &cache).unwrap().unwrap();
|
||||
let javac = &plan.steps[0];
|
||||
let cp = &javac.args[javac.args.iter().position(|a| a == "-cp").unwrap() + 1];
|
||||
let sep = std::path::MAIN_SEPARATOR;
|
||||
assert!(cp.contains(&format!("lib{sep}*")), "expected JAR dir wildcard in cp: {cp}");
|
||||
assert!(cp.contains(&format!("sub{sep}*")), "expected nested JAR dir wildcard in cp: {cp}");
|
||||
assert!(cp.contains("plain-classes") && !cp.contains(&format!("plain-classes{sep}*")), "cp={cp}");
|
||||
|
||||
let layout = plan.steps.iter().find_map(|s| match &s.action {
|
||||
Some((Action::Layout { entries, .. }, _)) => Some(entries),
|
||||
_ => None,
|
||||
});
|
||||
let entries = layout.expect("layout step");
|
||||
assert!(entries.iter().any(|(_, to)| to == Path::new("WEB-INF/lib/gson.jar")), "{entries:?}");
|
||||
assert!(entries.iter().any(|(_, to)| to == Path::new("WEB-INF/lib/extra.jar")), "{entries:?}");
|
||||
assert!(!entries.iter().any(|(_, to)| to == Path::new("WEB-INF/lib/lib")), "{entries:?}");
|
||||
}
|
||||
}
|
||||
@@ -323,8 +323,7 @@ mod tests {
|
||||
"exclude": [path(&root.join("node_modules"))],
|
||||
})
|
||||
);
|
||||
// Chained joins: the configurations name native paths, `packages/a` would mix separators on Windows.
|
||||
let a = root.join("packages").join("a");
|
||||
let a = root.join("packages/a");
|
||||
assert_eq!(
|
||||
copy(1),
|
||||
json!({
|
||||
@@ -337,14 +336,14 @@ mod tests {
|
||||
"exclude": [path(&a.join("node_modules"))],
|
||||
})
|
||||
);
|
||||
let b = root.join("packages").join("b");
|
||||
let b = root.join("packages/b");
|
||||
assert_eq!(
|
||||
copy(2),
|
||||
json!({
|
||||
"extends": path(&b.join("tsconfig.json")),
|
||||
"compilerOptions": {
|
||||
"outDir": path(&scratch.join("2")), "tsBuildInfoFile": s("2.tsbuildinfo"),
|
||||
"declarationDir": path(&scratch.join("2")), "outFile": path(&scratch.join("2").join("out.js")),
|
||||
"declarationDir": path(&scratch.join("2")), "outFile": path(&scratch.join("2/out.js")),
|
||||
},
|
||||
"references": [{"path": s("1.json")}],
|
||||
"exclude": [path(&b.join("node_modules")), path(&root.join("dist"))],
|
||||
|
||||
@@ -5,10 +5,8 @@
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Mutex;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
pub const SETTINGS_FILES: &[&str] = &["settings.gradle.kts", "settings.gradle"];
|
||||
pub const BUILD_FILES: &[&str] = &["build.gradle.kts", "build.gradle"];
|
||||
@@ -229,41 +227,9 @@ pub fn build_dir(root: &Path) -> Option<PathBuf> {
|
||||
build_dirs(root).into_iter().next()
|
||||
}
|
||||
|
||||
/// How long [`cached_build_dirs`] reuses a walk. Project roots, content roots and the index
|
||||
/// ask for the builds many times while a project opens; on a network share each walk is
|
||||
/// thousands of round trips. A build file changing in a project calls [`forget_build_dirs`].
|
||||
const BUILD_DIRS_TTL: Duration = Duration::from_secs(30);
|
||||
|
||||
type BuildDirsCache = HashMap<PathBuf, (Instant, Vec<PathBuf>)>;
|
||||
|
||||
static BUILD_DIRS: Mutex<Option<BuildDirsCache>> = Mutex::new(None);
|
||||
|
||||
/// Walks for builds now; the result also refreshes [`cached_build_dirs`].
|
||||
fn build_dirs(root: &Path) -> Vec<PathBuf> {
|
||||
let markers: Vec<_> = SETTINGS_FILES.iter().chain(BUILD_FILES).copied().collect();
|
||||
let dirs = ide_core::project_roots::discover(root, &markers);
|
||||
let now = Instant::now();
|
||||
let mut guard = BUILD_DIRS.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let map = guard.get_or_insert_with(HashMap::new);
|
||||
map.retain(|_, (at, _)| now.duration_since(*at) < BUILD_DIRS_TTL);
|
||||
map.insert(root.to_path_buf(), (now, dirs.clone()));
|
||||
dirs
|
||||
}
|
||||
|
||||
fn cached_build_dirs(root: &Path) -> Vec<PathBuf> {
|
||||
let cached = BUILD_DIRS.lock().unwrap_or_else(|e| e.into_inner()).as_ref().and_then(|m| m.get(root)).cloned();
|
||||
match cached {
|
||||
Some((at, dirs)) if at.elapsed() < BUILD_DIRS_TTL => dirs,
|
||||
_ => build_dirs(root),
|
||||
}
|
||||
}
|
||||
|
||||
/// Forgets the discovered Gradle builds of `root`, and of folders above or below it
|
||||
/// (after a build or settings script appeared, changed or was removed there).
|
||||
pub fn forget_build_dirs(root: &Path) {
|
||||
if let Some(map) = BUILD_DIRS.lock().unwrap_or_else(|e| e.into_inner()).as_mut() {
|
||||
map.retain(|dir, _| !dir.starts_with(root) && !root.starts_with(dir));
|
||||
}
|
||||
ide_core::project_roots::discover(root, &markers)
|
||||
}
|
||||
|
||||
fn wrapper(dir: &Path) -> String {
|
||||
@@ -540,23 +506,10 @@ pub fn linked_project_key(root: &Path, dir: &str) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// Linked build identities without reading their scripts, as of now (a sync, a build).
|
||||
/// Linked build identities without reading their scripts (also used by index hot paths).
|
||||
pub(crate) fn linked_dirs(root: &Path, settings: &ide_core::settings::GradleSettings) -> Vec<String> {
|
||||
linked_dirs_from(root, settings, build_dirs)
|
||||
}
|
||||
|
||||
/// [`linked_dirs`] for hot paths (project and index roots): discovered builds are reused for a while.
|
||||
pub(crate) fn linked_dirs_cached(root: &Path, settings: &ide_core::settings::GradleSettings) -> Vec<String> {
|
||||
linked_dirs_from(root, settings, cached_build_dirs)
|
||||
}
|
||||
|
||||
fn linked_dirs_from(
|
||||
root: &Path,
|
||||
settings: &ide_core::settings::GradleSettings,
|
||||
discover: fn(&Path) -> Vec<PathBuf>,
|
||||
) -> Vec<String> {
|
||||
match &settings.linked_projects {
|
||||
None => discover(root).iter().map(|dir| rel(root, dir)).collect(),
|
||||
None => build_dirs(root).iter().map(|dir| rel(root, dir)).collect(),
|
||||
Some(dirs) => {
|
||||
let mut out = Vec::new();
|
||||
for dir in dirs {
|
||||
@@ -1094,27 +1047,6 @@ pub(crate) fn has_war_plugin(script: &str) -> bool {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn discovered_builds_are_reused_until_forgotten() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let root = temp.path();
|
||||
std::fs::create_dir_all(root.join("a")).unwrap();
|
||||
std::fs::write(root.join("a/settings.gradle"), "").unwrap();
|
||||
assert_eq!(super::cached_build_dirs(root), vec![root.join("a")]);
|
||||
std::fs::create_dir_all(root.join("b")).unwrap();
|
||||
std::fs::write(root.join("b/build.gradle"), "").unwrap();
|
||||
// A walk per call is thousands of round trips on a network share.
|
||||
assert_eq!(super::cached_build_dirs(root), vec![root.join("a")]);
|
||||
super::forget_build_dirs(&root.join("b"));
|
||||
assert_eq!(super::cached_build_dirs(root), vec![root.join("a"), root.join("b")]);
|
||||
// A sync sees a new build at once, and so does every later lookup.
|
||||
std::fs::create_dir_all(root.join("c")).unwrap();
|
||||
std::fs::write(root.join("c/build.gradle"), "").unwrap();
|
||||
let all = vec![root.join("a"), root.join("b"), root.join("c")];
|
||||
assert_eq!(super::build_dirs(root), all);
|
||||
assert_eq!(super::cached_build_dirs(root), all);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_linkage_discovers_all_shallow_builds() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -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};
|
||||
@@ -46,16 +46,6 @@ fn subdir(root: &Path, rel: &str) -> PathBuf {
|
||||
root.join(rel).components().collect()
|
||||
}
|
||||
|
||||
/// The `-pl` value selecting `projects` in their Maven reactor, by `groupId:artifactId`. Their
|
||||
/// directories are the absolute `basedir`s Maven reported, which need not share a spelling with the
|
||||
/// opened folder (drive letter case, separators, links), so a path selector could miss the reactor.
|
||||
fn maven_project_selection<'a>(projects: impl Iterator<Item = &'a ProjectModel>) -> String {
|
||||
let mut selection: Vec<String> = projects.map(|p| format!("{}:{}", p.group_id, p.artifact_id)).collect();
|
||||
selection.sort();
|
||||
selection.dedup();
|
||||
selection.join(",")
|
||||
}
|
||||
|
||||
/// The resident part of the build: javac servers and one lock per reactor.
|
||||
#[derive(Default)]
|
||||
pub struct JavaBuildService {
|
||||
@@ -701,12 +691,17 @@ impl JavaBuild<'_> {
|
||||
let out = model::output_root(self.cache, &top.key());
|
||||
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 top_dir = subdir(self.root, &top.dir);
|
||||
let mut selection: Vec<String> = changed
|
||||
.iter()
|
||||
.map(|(p, _, _)| {
|
||||
let rel = p.dir.strip_prefix(&top_dir).unwrap_or(&p.dir).to_string_lossy().replace('\\', "/");
|
||||
if rel.is_empty() { ".".to_owned() } else { rel }
|
||||
})
|
||||
.collect();
|
||||
selection.sort();
|
||||
selection.dedup();
|
||||
let mut extra = vec!["-q".to_owned(), "-pl".to_owned(), selection.join(",")];
|
||||
extra.push("resources:resources".into());
|
||||
if changed.iter().any(|(_, test, _)| *test) {
|
||||
extra.push("resources:testResources".into());
|
||||
|
||||
@@ -11,50 +11,6 @@ fn write(root: &Path, rel: &str, text: &str) {
|
||||
fs::write(path, text).unwrap();
|
||||
}
|
||||
|
||||
fn build_output_tail(events: &[BuildEvent]) -> String {
|
||||
let mut lines: Vec<_> = events
|
||||
.iter()
|
||||
.filter_map(|event| match event {
|
||||
BuildEvent::Output { text, .. } => Some(text.as_str()),
|
||||
_ => None,
|
||||
})
|
||||
.flat_map(str::lines)
|
||||
.rev()
|
||||
.take(150)
|
||||
.collect();
|
||||
lines.reverse();
|
||||
lines.join("\n")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn build_output_tail_keeps_the_last_150_lines_across_streams() {
|
||||
let lines = |range: std::ops::Range<usize>| range.map(|n| n.to_string()).collect::<Vec<_>>().join("\n");
|
||||
let events = [
|
||||
BuildEvent::Output { text: lines(0..100), stderr: false },
|
||||
BuildEvent::Progress { message: "building".into(), fraction: None },
|
||||
BuildEvent::Output { text: lines(100..155), stderr: true },
|
||||
];
|
||||
assert_eq!(build_output_tail(&events), lines(5..155));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maven_resources_select_projects_by_coordinates_not_by_basedir() {
|
||||
// Maven reports absolute basedirs whose spelling can differ from the opened folder on Windows
|
||||
// (`D:/worktree/jxc/organ` against `d:\\worktree\\jxc`); coordinates always name a reactor project.
|
||||
let project = |dir: &str, artifact: &str| ProjectModel {
|
||||
dir: PathBuf::from(dir),
|
||||
group_id: "org.starry".into(),
|
||||
artifact_id: artifact.into(),
|
||||
..Default::default()
|
||||
};
|
||||
let projects = [
|
||||
project("D:/worktree/jxc/organ", "organ"),
|
||||
project("D:/worktree/jxc", "cloud"),
|
||||
project("D:/worktree/jxc/organ", "organ"),
|
||||
];
|
||||
assert_eq!(maven_project_selection(projects.iter()), "org.starry:cloud,org.starry:organ");
|
||||
}
|
||||
|
||||
/// 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())?;
|
||||
@@ -183,10 +139,7 @@ impl Fixture {
|
||||
let on_event = |e: BuildEvent| self.events.lock().unwrap().push(e);
|
||||
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}");
|
||||
}
|
||||
Ok(Built::Unsupported(reason)) => panic!("unsupported: {reason}"),
|
||||
Err(e) => panic!("{e:?}"),
|
||||
}
|
||||
}
|
||||
@@ -257,9 +210,7 @@ fn builds_maven_modules_with_javac_and_only_what_changed() {
|
||||
f.write("app/src/main/resources/app.properties", "version=${project.version}\nmore=1\n");
|
||||
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!(steps[0].contains("resources:resources") && steps[0].contains("-pl app"), "{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.
|
||||
|
||||
@@ -91,14 +91,12 @@ fn plan(root: &Path, model: &BuildModel, cancel: &CancellationToken) -> IdeResul
|
||||
|
||||
/// Run the project's configured wrapper/settings/JDK and lifecycle, with an output
|
||||
/// redirector loaded before Maven calculates its lifecycle execution plans.
|
||||
/// Builds the Kotlin libraries; `on_progress` gets Maven's progress (message, fraction 0..1).
|
||||
pub fn build(
|
||||
root: &Path,
|
||||
model: &BuildModel,
|
||||
bundle: &Path,
|
||||
generation: &Path,
|
||||
cancel: &CancellationToken,
|
||||
on_progress: &(dyn Fn(&str, Option<f32>) + Sync),
|
||||
) -> IdeResult<Outcome> {
|
||||
std::fs::create_dir_all(generation)?;
|
||||
let mut plan = plan(root, model, cancel)?;
|
||||
@@ -126,10 +124,10 @@ pub fn build(
|
||||
for step in &plan.steps {
|
||||
let mut reactor = plan.clone();
|
||||
reactor.steps = vec![step.clone()];
|
||||
let result = compile::run(root, &reactor, cancel, &|event| match event {
|
||||
BuildEvent::Output { text, .. } => tracing::debug!("kotlin bridge: {}", text.trim_end()),
|
||||
BuildEvent::Progress { message, fraction } => on_progress(&message, fraction),
|
||||
_ => {}
|
||||
let result = compile::run(root, &reactor, cancel, &|event| {
|
||||
if let BuildEvent::Output { text, .. } = event {
|
||||
tracing::debug!("kotlin bridge: {}", text.trim_end());
|
||||
}
|
||||
})?;
|
||||
messages.extend(result.messages);
|
||||
}
|
||||
@@ -458,7 +456,6 @@ mod tests {
|
||||
Path::new("unused.jar"),
|
||||
&directory.path().join("private"),
|
||||
&CancellationToken::new(),
|
||||
&|_, _| {},
|
||||
)
|
||||
.err()
|
||||
.unwrap();
|
||||
|
||||
@@ -129,7 +129,7 @@ pub fn gradle_external_roots(
|
||||
cache_dir: &Path,
|
||||
settings: &ide_core::settings::GradleSettings,
|
||||
) -> Vec<PathBuf> {
|
||||
let builds = gradle::linked_dirs_cached(root, settings);
|
||||
let builds = gradle::linked_dirs(root, settings);
|
||||
let dirs: Vec<String> = builds
|
||||
.iter()
|
||||
.flat_map(|dir| {
|
||||
@@ -171,7 +171,7 @@ pub fn gradle_source_roots(
|
||||
cache_dir: &Path,
|
||||
settings: &ide_core::settings::GradleSettings,
|
||||
) -> Vec<(PathBuf, gradle::ReportedRoot, PathBuf)> {
|
||||
let reported = gradle::linked_dirs_cached(root, settings)
|
||||
let reported = gradle::linked_dirs(root, settings)
|
||||
.iter()
|
||||
.flat_map(|dir| sync::reported_gradle_projects(&gradle::cache_dir(cache_dir, dir)).as_ref().clone())
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
@@ -69,9 +69,6 @@ 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`…).
|
||||
@@ -179,7 +176,6 @@ struct RawDep {
|
||||
kind: Option<String>,
|
||||
classifier: Option<String>,
|
||||
scope: Option<String>,
|
||||
system_path: Option<String>,
|
||||
optional: bool,
|
||||
}
|
||||
|
||||
@@ -252,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"),
|
||||
})
|
||||
}
|
||||
@@ -1524,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()
|
||||
@@ -1540,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) {
|
||||
@@ -1618,7 +1592,6 @@ pub fn load_with_linked_jdk(
|
||||
aggregated,
|
||||
plugins,
|
||||
dependencies,
|
||||
system_paths,
|
||||
profiles: ctx.profiles.iter().map(|(id, _)| id.clone()).collect(),
|
||||
java_version: jv,
|
||||
command: wrapper(&canonical_root, &dir_canon),
|
||||
@@ -4488,58 +4461,4 @@ mod linkage_tests {
|
||||
assert_eq!(poms, expected.map(|e| e.iter().map(|s| s.to_string()).collect::<Vec<_>>()), "{unlinked:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn child_module_inherits_parent_declared_plugin_prefix_and_coordinates() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
std::fs::create_dir_all(root.join("child")).unwrap();
|
||||
std::fs::write(
|
||||
root.join("pom.xml"),
|
||||
r#"<project>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.example</groupId>
|
||||
<artifactId>parent</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<packaging>pom</packaging>
|
||||
<modules><module>child</module></modules>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>io.spring.javaformat</groupId>
|
||||
<artifactId>spring-javaformat-maven-plugin</artifactId>
|
||||
<version>0.0.38</version>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>"#,
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::write(
|
||||
root.join("child/pom.xml"),
|
||||
r#"<project>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<parent>
|
||||
<groupId>com.example</groupId>
|
||||
<artifactId>parent</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
<artifactId>child</artifactId>
|
||||
</project>"#,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let model = load_with_repo(root, None);
|
||||
for pom in ["pom.xml", "child/pom.xml"] {
|
||||
let proj = model.projects.iter().find(|p| p.pom == pom).expect(pom);
|
||||
let plugin = proj
|
||||
.plugins
|
||||
.iter()
|
||||
.find(|p| p.prefix == "spring-javaformat")
|
||||
.unwrap_or_else(|| panic!("spring-javaformat plugin missing on {pom}: {:?}", proj.plugins));
|
||||
assert_eq!(plugin.group_id, "io.spring.javaformat");
|
||||
assert_eq!(plugin.artifact_id, "spring-javaformat-maven-plugin");
|
||||
assert_eq!(plugin.version.as_deref(), Some("0.0.38"));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -340,18 +340,6 @@ mod imp {
|
||||
const OPEN_ATTEMPTS: usize = 10;
|
||||
const OPEN_RETRY: Duration = Duration::from_millis(20);
|
||||
|
||||
/// WARNING: reading or writing the clipboard from two threads at once crashes the whole
|
||||
/// process. `OpenClipboard(NULL)` does not keep the other threads of this process out, and
|
||||
/// a second `GetClipboardData` can free the block the first thread is still reading, so
|
||||
/// `GlobalSize` finds a corrupted heap and Windows ends the app with 0xc0000374 (#6388:
|
||||
/// restoring a minimized window starts several reads). Every function below that opens the
|
||||
/// clipboard holds this lock from before `OpenClipboard` until after `CloseClipboard`.
|
||||
static CLIPBOARD: std::sync::Mutex<()> = std::sync::Mutex::new(());
|
||||
|
||||
fn lock() -> std::sync::MutexGuard<'static, ()> {
|
||||
CLIPBOARD.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
}
|
||||
|
||||
#[link(name = "user32")]
|
||||
unsafe extern "system" {
|
||||
fn OpenClipboard(owner: Handle) -> i32;
|
||||
@@ -401,7 +389,6 @@ mod imp {
|
||||
}
|
||||
|
||||
pub fn png() -> Option<Vec<u8>> {
|
||||
let _clipboard = lock();
|
||||
if !open() {
|
||||
return None;
|
||||
}
|
||||
@@ -418,7 +405,6 @@ mod imp {
|
||||
}
|
||||
|
||||
pub fn text() -> Option<String> {
|
||||
let _clipboard = lock();
|
||||
// Empty rather than None: a None falls back to the WebView, which prompts the user.
|
||||
if unsafe { IsClipboardFormatAvailable(CF_UNICODETEXT) } == 0 {
|
||||
return Some(String::new());
|
||||
@@ -461,7 +447,6 @@ mod imp {
|
||||
}
|
||||
|
||||
pub fn files() -> std::io::Result<Vec<PathBuf>> {
|
||||
let _clipboard = lock();
|
||||
if !open() {
|
||||
return Err(std::io::Error::last_os_error());
|
||||
}
|
||||
@@ -543,7 +528,6 @@ mod imp {
|
||||
}
|
||||
|
||||
pub fn set_text(text: &str, owner: usize) -> std::io::Result<()> {
|
||||
let _clipboard = lock();
|
||||
let (memory, _) = global_text(text);
|
||||
if memory.is_null() {
|
||||
return Err(std::io::Error::last_os_error());
|
||||
@@ -567,7 +551,6 @@ mod imp {
|
||||
}
|
||||
|
||||
pub fn set_png(png: &[u8], owner: usize) -> std::io::Result<()> {
|
||||
let _clipboard = lock();
|
||||
let dib = super::image::png_to_dib(png)?;
|
||||
let format = png_format();
|
||||
if format == 0 {
|
||||
@@ -610,7 +593,6 @@ mod imp {
|
||||
}
|
||||
|
||||
pub fn set_files(paths: &[PathBuf]) -> bool {
|
||||
let _clipboard = lock();
|
||||
let bytes = encode(paths);
|
||||
if bytes.len() <= HEADER {
|
||||
return false;
|
||||
@@ -941,104 +923,6 @@ mod tests {
|
||||
assert_eq!(unicode_text(&bytes), "héllo\r\n世界");
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
const READ_TEXT: &str = "clipboard read test";
|
||||
|
||||
/// Reads the clipboard's text for 5 s from `threads` threads, one at a time when
|
||||
/// `serialized`, in a child process: heap corruption ends a process, and the test
|
||||
/// keeps the result. Replaces the clipboard with text and writes the earlier text
|
||||
/// back afterwards; skipped where no clipboard can be written.
|
||||
#[cfg(windows)]
|
||||
fn reads_survive(test: &str, threads: usize, serialized: bool) {
|
||||
use std::process::Command;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::{Duration, Instant};
|
||||
const STAGE: &str = "IDE_CLIPBOARD_READ_STAGE";
|
||||
if std::env::var_os(STAGE).is_some() {
|
||||
#[link(name = "kernel32")]
|
||||
unsafe extern "system" {
|
||||
fn WerSetFlags(flags: u32) -> i32;
|
||||
}
|
||||
// WER_FAULT_REPORTING_NO_UI: a crash ends the child instead of waiting on a dialog.
|
||||
unsafe { WerSetFlags(0x20) };
|
||||
let stop = Instant::now() + Duration::from_secs(5);
|
||||
let turn = Arc::new(Mutex::new(()));
|
||||
let readers: Vec<_> = (0..threads)
|
||||
.map(|_| {
|
||||
let turn = turn.clone();
|
||||
std::thread::spawn(move || {
|
||||
let mut reads = 0usize;
|
||||
while Instant::now() < stop {
|
||||
let _turn = serialized.then(|| turn.lock().unwrap());
|
||||
// None: another reader kept the clipboard open through every retry.
|
||||
let read = text();
|
||||
assert!(matches!(read.as_deref(), None | Some(READ_TEXT)), "read {read:?}");
|
||||
reads += 1;
|
||||
}
|
||||
reads
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let reads: usize = readers.into_iter().map(|reader| reader.join().unwrap()).sum();
|
||||
println!("reads: {reads}");
|
||||
return;
|
||||
}
|
||||
// The tests share the one clipboard: one at a time, so none rewrites it under another.
|
||||
static SERIAL: Mutex<()> = Mutex::new(());
|
||||
let _serial = SERIAL.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let earlier = text();
|
||||
if let Err(error) = set_text(READ_TEXT, 0) {
|
||||
eprintln!("skipped: the clipboard cannot be written here ({error})");
|
||||
return;
|
||||
}
|
||||
let mut child = Command::new(std::env::current_exe().unwrap())
|
||||
.args(["--exact", test, "--test-threads=1", "--nocapture"])
|
||||
.env(STAGE, "1")
|
||||
.spawn()
|
||||
.unwrap();
|
||||
let deadline = Instant::now() + Duration::from_secs(60);
|
||||
let status = loop {
|
||||
if let Some(status) = child.try_wait().unwrap() {
|
||||
break Some(status);
|
||||
}
|
||||
if Instant::now() > deadline {
|
||||
let _ = child.kill();
|
||||
break None;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(100));
|
||||
};
|
||||
if let Some(earlier) = earlier.filter(|earlier| !earlier.is_empty()) {
|
||||
let _ = set_text(&earlier, 0);
|
||||
}
|
||||
let status = status.expect("the reads did not finish within 60 s");
|
||||
assert!(
|
||||
status.success(),
|
||||
"clipboard reads ended the process: exit code {:#x}",
|
||||
status.code().unwrap_or_default() as u32
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn text_reads_on_one_thread_do_not_corrupt_the_heap() {
|
||||
reads_survive("tests::text_reads_on_one_thread_do_not_corrupt_the_heap", 1, false);
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn text_reads_taking_turns_do_not_corrupt_the_heap() {
|
||||
reads_survive("tests::text_reads_taking_turns_do_not_corrupt_the_heap", 8, true);
|
||||
}
|
||||
|
||||
/// The project view reads the clipboard's text whenever a window gains focus, on
|
||||
/// whichever worker thread the command lands, so restoring a minimized window can
|
||||
/// start several reads at once (#6388).
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn concurrent_text_reads_do_not_corrupt_the_heap() {
|
||||
reads_survive("tests::concurrent_text_reads_do_not_corrupt_the_heap", 8, false);
|
||||
}
|
||||
|
||||
fn paths(list: &[&str]) -> Vec<PathBuf> {
|
||||
list.iter().map(PathBuf::from).collect()
|
||||
}
|
||||
|
||||
@@ -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_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_System_SystemInformation", "Win32_System_Threading"] }
|
||||
@@ -1,74 +0,0 @@
|
||||
//! Parallelism for build tools whose default is one compiler process at a time.
|
||||
//!
|
||||
//! `cmake --build` with a Makefile generator (the default) compiles one file at a
|
||||
//! time unless it is given `-j N`; the IDE asks for one job per logical CPU. A count
|
||||
//! the user wrote into the build arguments is left alone.
|
||||
|
||||
/// Jobs a native build tool gets when the user did not choose a count.
|
||||
pub fn default_jobs() -> usize {
|
||||
std::thread::available_parallelism().map_or(1, |jobs| jobs.get())
|
||||
}
|
||||
|
||||
/// Appends `-j <jobs>` unless `args` already carries the user's own count. The count
|
||||
/// goes before a `--` separator, so cmake's own options stay cmake's and the native
|
||||
/// build tool's options stay last.
|
||||
pub fn append_default_jobs(args: &mut Vec<String>) {
|
||||
if args.iter().any(|arg| is_jobs_flag(arg)) {
|
||||
return;
|
||||
}
|
||||
let jobs = default_jobs().to_string();
|
||||
let at = args.iter().position(|arg| arg == "--").unwrap_or(args.len());
|
||||
args.splice(at..at, ["-j".to_owned(), jobs]);
|
||||
}
|
||||
|
||||
/// `-j`, `-j8`, `--parallel`, `--parallel=8`, `--jobs`, `--jobs=8`.
|
||||
fn is_jobs_flag(arg: &str) -> bool {
|
||||
let count = |rest: &str| rest.chars().all(|c| c.is_ascii_digit());
|
||||
arg.strip_prefix("-j").is_some_and(count)
|
||||
|| arg.strip_prefix("--parallel=").is_some_and(count)
|
||||
|| arg.strip_prefix("--jobs=").is_some_and(count)
|
||||
|| arg == "--parallel"
|
||||
|| arg == "--jobs"
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn args_of(values: &[&str]) -> Vec<String> {
|
||||
values.iter().map(|value| (*value).to_owned()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_default_is_one_job_per_logical_cpu() {
|
||||
let expected = std::thread::available_parallelism().map_or(1, |jobs| jobs.get());
|
||||
assert_eq!(default_jobs(), expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_build_without_a_count_gets_one() {
|
||||
let mut argv = args_of(&["--build", "build", "--config", "Debug"]);
|
||||
append_default_jobs(&mut argv);
|
||||
assert_eq!(argv, args_of(&["--build", "build", "--config", "Debug", "-j", &default_jobs().to_string()]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_count_the_user_chose_is_left_alone() {
|
||||
let own: [&[&str]; 6] =
|
||||
[&["-j", "2"], &["-j8"], &["-j", "2"], &["--parallel", "2"], &["--parallel=2"], &["--jobs=2"]];
|
||||
for flags in own {
|
||||
let mut argv = args_of(&["--build", "build"]);
|
||||
argv.extend(flags.iter().map(|value| (*value).to_owned()));
|
||||
let expected = argv.clone();
|
||||
append_default_jobs(&mut argv);
|
||||
assert_eq!(argv, expected, "the build arguments set the count");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_count_stays_before_native_build_tool_options() {
|
||||
let mut argv = args_of(&["--build", "build", "--", "VERBOSE=1"]);
|
||||
append_default_jobs(&mut argv);
|
||||
assert_eq!(argv, args_of(&["--build", "build", "-j", &default_jobs().to_string(), "--", "VERBOSE=1"]));
|
||||
}
|
||||
}
|
||||
@@ -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(())
|
||||
}
|
||||
@@ -33,10 +33,6 @@ pub struct EditorGeneralSettings {
|
||||
pub remove_trailing_blank_lines: bool,
|
||||
/// Copy as rich text (HTML with syntax colours) by default.
|
||||
pub rich_text_copy: bool,
|
||||
/// Gutter › Highlight modified lines in the gutter: the VCS change bars next to the line numbers.
|
||||
pub highlight_modified_lines: bool,
|
||||
/// Gutter › Highlight modified lines in error stripe on the scrollbar (with `highlight_modified_lines`).
|
||||
pub highlight_modified_lines_in_scrollbar: bool,
|
||||
}
|
||||
|
||||
impl Default for EditorGeneralSettings {
|
||||
@@ -55,8 +51,6 @@ impl Default for EditorGeneralSettings {
|
||||
keep_trailing_on_caret_line: true,
|
||||
remove_trailing_blank_lines: false,
|
||||
rich_text_copy: true,
|
||||
highlight_modified_lines: true,
|
||||
highlight_modified_lines_in_scrollbar: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -302,42 +296,12 @@ pub struct SmartKeysSettings {
|
||||
pub simultaneous_tag_editing: bool,
|
||||
/// Reformat on paste: `none` | `indentBlock` | `indentEachLine`.
|
||||
pub reformat_on_paste: String,
|
||||
/// Advanced Settings: Copy/Cut without a selection copies the whole caret lines.
|
||||
pub copy_line_when_no_selection: bool,
|
||||
/// Advanced Settings: Copy selects the lines copied without a selection.
|
||||
pub select_copied_line: bool,
|
||||
/// Advanced Settings: linewise paste `above` the caret | `caret` | `trim` at mid-line.
|
||||
pub line_paste_mode: String,
|
||||
pub escape_on_paste: bool,
|
||||
pub smart_indent: bool,
|
||||
/// Enter › Insert documentation comment stub: Enter after `/**` closes the comment.
|
||||
pub insert_doc_stub: bool,
|
||||
/// Backspace › Unindent: `autoindent` (proper indent position) | `nearest` indent position | `none`.
|
||||
pub backspace_unindent: String,
|
||||
/// The styles Cycle Identifier Case goes through.
|
||||
pub cycle_case: CycleCaseSettings,
|
||||
}
|
||||
|
||||
/// Editor › General › Smart Keys › Cycle Identifier Case: the styles the action goes through.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct CycleCaseSettings {
|
||||
/// `snake_case`
|
||||
pub snake: bool,
|
||||
/// `SCREAMING_SNAKE_CASE`
|
||||
pub screaming: bool,
|
||||
/// `kebab-case`
|
||||
pub kebab: bool,
|
||||
/// `camelCase`
|
||||
pub camel: bool,
|
||||
/// `PascalCase`
|
||||
pub pascal: bool,
|
||||
}
|
||||
|
||||
impl Default for CycleCaseSettings {
|
||||
fn default() -> Self {
|
||||
Self { snake: true, screaming: true, kebab: true, camel: true, pascal: true }
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for SmartKeysSettings {
|
||||
@@ -352,14 +316,10 @@ impl Default for SmartKeysSettings {
|
||||
semicolon_at_statement_end: true,
|
||||
simultaneous_tag_editing: true,
|
||||
reformat_on_paste: "indentEachLine".into(),
|
||||
copy_line_when_no_selection: true,
|
||||
select_copied_line: true,
|
||||
line_paste_mode: "above".into(),
|
||||
escape_on_paste: true,
|
||||
smart_indent: true,
|
||||
insert_doc_stub: true,
|
||||
backspace_unindent: "autoindent".into(),
|
||||
cycle_case: CycleCaseSettings::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -401,8 +361,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,
|
||||
@@ -438,7 +396,6 @@ impl Default for InlayHintsSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
types: true,
|
||||
js_ts_types: true,
|
||||
parameters: true,
|
||||
other: true,
|
||||
closing_labels: true,
|
||||
@@ -713,19 +670,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;
|
||||
|
||||
@@ -13,70 +13,13 @@ use std::sync::Arc;
|
||||
|
||||
/// 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
|
||||
/// `RunConfig`, its before launch tasks already done) in the Run tool window as the user's
|
||||
/// Run would, answered the same way. `DebugConfiguration` does the same in Debug mode, so
|
||||
/// the window's own Debug action builds the launch. `Breakpoints` replaces the window's
|
||||
/// breakpoints, which the editor owns, persists and mirrors to the backend.
|
||||
/// started or failed to.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(tag = "type", rename_all = "camelCase", rename_all_fields = "camelCase")]
|
||||
pub enum McpUiRequest {
|
||||
Confirm {
|
||||
client: String,
|
||||
tool: String,
|
||||
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,
|
||||
line: Option<u32>,
|
||||
column: Option<u32>,
|
||||
},
|
||||
AgentRun {
|
||||
name: String,
|
||||
command: String,
|
||||
cwd: crate::IpcPath,
|
||||
env: BTreeMap<String, String>,
|
||||
},
|
||||
RunConfiguration {
|
||||
#[specta(type = specta_typescript::Unknown)]
|
||||
config: serde_json::Value,
|
||||
},
|
||||
/// Start a run configuration in Debug mode as the IDE's Debug action would.
|
||||
DebugConfiguration {
|
||||
#[specta(type = specta_typescript::Unknown)]
|
||||
config: serde_json::Value,
|
||||
},
|
||||
/// Sets one line breakpoint in the window's own list, by absolute editor path. The window
|
||||
/// applies the edit to its current list, so a user's pending edit is not overwritten.
|
||||
SetBreakpoint {
|
||||
path: String,
|
||||
breakpoint: McpBreakpoint,
|
||||
},
|
||||
/// Removes breakpoints from the window's own list. With no path, removes every line
|
||||
/// breakpoint; with a path but no line, removes all of that file's breakpoints.
|
||||
RemoveBreakpoints {
|
||||
path: Option<String>,
|
||||
line: Option<u32>,
|
||||
},
|
||||
/// Flushes the editor's pending breakpoint syncs before an agent reads the backend list.
|
||||
FlushBreakpoints,
|
||||
}
|
||||
|
||||
/// A line breakpoint in an MCP request, with a 1-based line like every other MCP tool.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct McpBreakpoint {
|
||||
pub line: u32,
|
||||
pub enabled: bool,
|
||||
pub condition: Option<String>,
|
||||
pub hit_condition: Option<String>,
|
||||
pub log_message: Option<String>,
|
||||
Confirm { client: String, tool: String, subject: String, project: String, detail: Option<String> },
|
||||
OpenFile { path: crate::IpcPath, line: Option<u32>, column: Option<u32> },
|
||||
AgentRun { name: String, command: String, cwd: crate::IpcPath, env: BTreeMap<String, String> },
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
@@ -84,10 +27,6 @@ pub struct McpBreakpoint {
|
||||
pub enum IdeEvent {
|
||||
/// Project data source settings changed; reload the Database tree.
|
||||
DbSourcesChanged,
|
||||
/// A Python run saved a matplotlib figure for the Plots tool window (a PNG file).
|
||||
PlotAdded {
|
||||
path: String,
|
||||
},
|
||||
McpRequest {
|
||||
id: u32,
|
||||
request: McpUiRequest,
|
||||
@@ -99,8 +38,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.
|
||||
@@ -161,8 +98,6 @@ pub enum IdeEvent {
|
||||
DocDiskConflict {
|
||||
doc: DocId,
|
||||
path: String,
|
||||
/// The file no longer exists: saving recreates it, and there is nothing to load.
|
||||
deleted: bool,
|
||||
},
|
||||
/// A complete workspace edit can be undone as one operation.
|
||||
WorkspaceEditApplied {
|
||||
@@ -182,15 +117,6 @@ pub enum IdeEvent {
|
||||
/// See `DocumentInfo::ui_mode`.
|
||||
ui_mode: Option<String>,
|
||||
},
|
||||
/// A reload from disk changed an open document's encoding, BOM or line ending (the file
|
||||
/// was rewritten by another program), which the editor only learns when it opens.
|
||||
DocEncoding {
|
||||
doc: DocId,
|
||||
encoding: String,
|
||||
has_bom: bool,
|
||||
/// A `LineEnding` in its serialized form: `lf`, `crLf` or `cr`.
|
||||
line_ending: String,
|
||||
},
|
||||
/// Full replacement of diagnostics for one file from one producer.
|
||||
Diagnostics {
|
||||
path: crate::IpcPath,
|
||||
@@ -253,15 +179,6 @@ pub enum IdeEvent {
|
||||
message: String,
|
||||
actions: Vec<String>,
|
||||
},
|
||||
/// A language server asked to show a document (`window/showDocument`), e.g. the
|
||||
/// expansion file of sourcekit-lsp's Expand Macro. `path` is set for a file to open in
|
||||
/// an editor, at `selection` when given; without it `uri` is a web link for the browser.
|
||||
LspShowDocument {
|
||||
uri: String,
|
||||
path: Option<crate::IpcPath>,
|
||||
selection: Option<crate::Range>,
|
||||
take_focus: bool,
|
||||
},
|
||||
/// The request was answered or timed out; every window drops its dialog.
|
||||
LspMessageRequestDone {
|
||||
id: u32,
|
||||
|
||||
@@ -4,9 +4,7 @@
|
||||
//! feature crates depend on `ide-core` and never on each other's internals.
|
||||
//! All IPC-facing types derive `specta::Type`, which generates `src/bindings.ts`.
|
||||
|
||||
pub mod build_jobs;
|
||||
pub mod cli_process;
|
||||
pub mod cmake_file_api;
|
||||
pub mod editor_settings;
|
||||
pub mod error;
|
||||
pub mod event;
|
||||
@@ -20,7 +18,6 @@ pub mod ipc_path;
|
||||
pub mod java_runtime;
|
||||
pub mod jsonc;
|
||||
pub mod memory;
|
||||
pub mod network_path;
|
||||
pub mod output_encoding;
|
||||
pub mod output_rate;
|
||||
pub mod platform;
|
||||
|
||||
@@ -1,35 +1,5 @@
|
||||
//! Returning freed heap pages to the OS.
|
||||
|
||||
use std::sync::Mutex;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// Like [`release_free_pages`], on a background thread once 2 s pass without another call:
|
||||
/// closing a project or a batch of tabs frees memory in bursts, released once.
|
||||
pub fn release_free_pages_soon() {
|
||||
static DUE: Mutex<Option<Instant>> = Mutex::new(None);
|
||||
debounce(&DUE, Duration::from_secs(2), release_free_pages);
|
||||
}
|
||||
|
||||
/// Runs `run` on a background thread once `delay` passes after the last call.
|
||||
fn debounce(due: &'static Mutex<Option<Instant>>, delay: Duration, run: fn()) {
|
||||
let idle = due.lock().unwrap().replace(Instant::now() + delay).is_none();
|
||||
if idle {
|
||||
std::thread::spawn(move || {
|
||||
loop {
|
||||
let mut slot = due.lock().unwrap();
|
||||
let left = slot.map_or(Duration::ZERO, |at| at.saturating_duration_since(Instant::now()));
|
||||
if left.is_zero() {
|
||||
*slot = None;
|
||||
drop(slot);
|
||||
return run();
|
||||
}
|
||||
drop(slot);
|
||||
std::thread::sleep(left);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// Hands pages the allocator has freed but kept back to the OS. Call after a burst of
|
||||
/// short-lived allocations (a full index scan); until then they still count towards the
|
||||
/// process's memory footprint.
|
||||
@@ -48,45 +18,3 @@ pub fn release_free_pages() {
|
||||
libc::malloc_trim(0);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering::SeqCst};
|
||||
|
||||
static DUE: Mutex<Option<Instant>> = Mutex::new(None);
|
||||
static RUNS: AtomicUsize = AtomicUsize::new(0);
|
||||
|
||||
fn count() {
|
||||
RUNS.fetch_add(1, SeqCst);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_burst_of_calls_runs_once_after_the_delay() {
|
||||
// Timing-based: a loaded CI machine can oversleep, so each check allows for that.
|
||||
let delay = Duration::from_millis(500);
|
||||
let (mut last, mut widest_gap) = (None::<Instant>, Duration::ZERO);
|
||||
for _ in 0..5 {
|
||||
debounce(&DUE, delay, count);
|
||||
let now = Instant::now();
|
||||
widest_gap = widest_gap.max(last.map_or(Duration::ZERO, |l| now - l));
|
||||
last = Some(now);
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
if last.unwrap().elapsed() < delay {
|
||||
assert_eq!(RUNS.load(SeqCst), 0, "ran before the delay passed");
|
||||
}
|
||||
let deadline = Instant::now() + Duration::from_secs(10);
|
||||
while RUNS.load(SeqCst) == 0 && Instant::now() < deadline {
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
// A second run would come within another delay.
|
||||
std::thread::sleep(delay);
|
||||
if widest_gap < delay {
|
||||
assert_eq!(RUNS.load(SeqCst), 1);
|
||||
} else {
|
||||
assert!(RUNS.load(SeqCst) >= 1);
|
||||
}
|
||||
release_free_pages_soon();
|
||||
}
|
||||
}
|
||||
@@ -1,53 +0,0 @@
|
||||
//! Whether a path is on a network file system, where every stat is a round trip to a server.
|
||||
|
||||
use std::path::{Component, Path, Prefix};
|
||||
|
||||
/// A UNC path (`\\server\share`, `\\wsl.localhost\…`) or a drive letter mapped to a network
|
||||
/// share (`Z:\`). Always `false` off Windows: there a mount point is not visible in the path.
|
||||
pub fn is_network_path(path: &Path) -> bool {
|
||||
match path.components().next() {
|
||||
Some(Component::Prefix(prefix)) => match prefix.kind() {
|
||||
Prefix::UNC(..) | Prefix::VerbatimUNC(..) => true,
|
||||
Prefix::Disk(letter) | Prefix::VerbatimDisk(letter) => is_remote_drive(letter),
|
||||
_ => false,
|
||||
},
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn is_remote_drive(letter: u8) -> bool {
|
||||
use windows_sys::Win32::Storage::FileSystem::GetDriveTypeW;
|
||||
/// `DRIVE_REMOTE` (WindowsProgramming).
|
||||
const DRIVE_REMOTE: u32 = 4;
|
||||
let root = [u16::from(letter), u16::from(b':'), u16::from(b'\\'), 0];
|
||||
// SAFETY: `root` is a NUL-terminated wide string that outlives the call.
|
||||
unsafe { GetDriveTypeW(root.as_ptr()) == DRIVE_REMOTE }
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
fn is_remote_drive(_letter: u8) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::is_network_path;
|
||||
use std::path::Path;
|
||||
|
||||
#[test]
|
||||
fn unc_paths_are_on_the_network() {
|
||||
if cfg!(windows) {
|
||||
assert!(is_network_path(Path::new(r"\\server\share\repo")));
|
||||
assert!(is_network_path(Path::new(r"\\?\UNC\server\share\repo")));
|
||||
assert!(is_network_path(Path::new(r"\\wsl.localhost\Ubuntu\home")));
|
||||
}
|
||||
assert!(!is_network_path(Path::new("relative/path")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_local_directory_is_not() {
|
||||
let dir = std::env::temp_dir();
|
||||
assert!(!is_network_path(&dir), "{}", dir.display());
|
||||
}
|
||||
}
|
||||
@@ -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`].
|
||||
@@ -640,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> {
|
||||
@@ -988,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()));
|
||||
@@ -1240,29 +1176,6 @@ mod tests {
|
||||
set_env_overlay(Vec::new());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_child_inside_a_project_gets_its_xcode() {
|
||||
let root = std::path::Path::new("/openidea-test-process/xcode");
|
||||
let xcode = "/Applications/Xcode-beta.app/Contents/Developer";
|
||||
crate::project_env::set_developer_dir(root, Some(xcode.into()));
|
||||
let developer_dir = |cmd: &Command| {
|
||||
cmd.get_envs().find(|(n, _)| *n == "DEVELOPER_DIR").and_then(|(_, v)| v.map(OsStr::to_owned))
|
||||
};
|
||||
// xcodebuild, xcrun, a language server: a `Command` started in the project.
|
||||
let mut tool = Command::new("xcodebuild");
|
||||
prepare(tool.current_dir(root.join("App")));
|
||||
assert_eq!(developer_dir(&tool), Some(xcode.into()));
|
||||
// A terminal: a PTY applies the fixes itself.
|
||||
assert!(host_env_fixes_in(root).contains(&("DEVELOPER_DIR".into(), Some(xcode.into()))));
|
||||
let mut elsewhere = Command::new("xcodebuild");
|
||||
prepare(elsewhere.current_dir("/openidea-test-process/other"));
|
||||
assert_eq!(developer_dir(&elsewhere), None);
|
||||
crate::project_env::set_developer_dir(root, None);
|
||||
let mut tool = Command::new("xcodebuild");
|
||||
prepare(tool.current_dir(root));
|
||||
assert_eq!(developer_dir(&tool), None, "empty: the system default");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_child_inside_a_project_gets_its_environment() {
|
||||
let root = std::path::Path::new("/openidea-test-process/project");
|
||||
@@ -1304,35 +1217,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(
|
||||
|
||||
@@ -16,21 +16,13 @@ struct Entry {
|
||||
root: PathBuf,
|
||||
direnv: Vec<(OsString, Option<OsString>)>,
|
||||
github_token: Option<OsString>,
|
||||
developer_dir: Option<OsString>,
|
||||
changes: Changes,
|
||||
loading: bool,
|
||||
}
|
||||
|
||||
impl Entry {
|
||||
fn new(root: PathBuf) -> Self {
|
||||
Self {
|
||||
root,
|
||||
direnv: Vec::new(),
|
||||
github_token: None,
|
||||
developer_dir: None,
|
||||
changes: Changes::default(),
|
||||
loading: false,
|
||||
}
|
||||
Self { root, direnv: Vec::new(), github_token: None, changes: Changes::default(), loading: false }
|
||||
}
|
||||
|
||||
fn rebuild(&mut self) {
|
||||
@@ -41,16 +33,11 @@ impl Entry {
|
||||
// `.envrc` entries override the project GitHub token when both define `GH_TOKEN`.
|
||||
combined.retain(|(k, _)| !self.direnv.iter().any(|(dk, _)| dk == k));
|
||||
combined.extend(self.direnv.iter().cloned());
|
||||
// The project's chosen Xcode overrides a `DEVELOPER_DIR` from `.envrc`: it is set for this project only.
|
||||
if let Some(dir) = &self.developer_dir {
|
||||
combined.retain(|(k, _)| k != DEVELOPER_DIR);
|
||||
combined.push((DEVELOPER_DIR.into(), Some(dir.clone())));
|
||||
}
|
||||
self.changes = Arc::new(combined);
|
||||
}
|
||||
|
||||
fn is_idle_empty(&self) -> bool {
|
||||
!self.loading && self.direnv.is_empty() && self.github_token.is_none() && self.developer_dir.is_none()
|
||||
!self.loading && self.direnv.is_empty() && self.github_token.is_none()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -157,31 +144,6 @@ pub fn set_github_token(root: &Path, token: Option<OsString>) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
const DEVELOPER_DIR: &str = "DEVELOPER_DIR";
|
||||
|
||||
/// Sets or clears the `DEVELOPER_DIR` (the Xcode `xcrun`, `xcodebuild` and sourcekit-lsp use)
|
||||
/// injected for children started in `root`. Returns whether it changed.
|
||||
pub fn set_developer_dir(root: &Path, dir: Option<OsString>) -> bool {
|
||||
let dir = dir.filter(|d| !d.is_empty());
|
||||
let mut entries = entries();
|
||||
let idx = match entries.iter().position(|e| e.root == root) {
|
||||
Some(idx) if entries[idx].developer_dir == dir => return false,
|
||||
Some(idx) => idx,
|
||||
None if dir.is_none() => return false,
|
||||
None => {
|
||||
entries.push(Entry::new(root.to_path_buf()));
|
||||
entries.len() - 1
|
||||
}
|
||||
};
|
||||
let entry = &mut entries[idx];
|
||||
entry.developer_dir = dir;
|
||||
entry.rebuild();
|
||||
if entry.is_idle_empty() {
|
||||
entries.remove(idx);
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// The project-scoped `GH_TOKEN` configured for the innermost project holding `dir`, if any.
|
||||
pub fn github_token(dir: &Path) -> Option<OsString> {
|
||||
find(&entries(), dir).and_then(|e| e.github_token.clone())
|
||||
@@ -240,28 +202,6 @@ mod tests {
|
||||
assert!(for_dir(inner).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_projects_xcode_wins_over_envrc_and_clears() {
|
||||
let root = Path::new("/openidea-test-env/xcode");
|
||||
set(root, vec![change("DEVELOPER_DIR", Some("/envrc")), change("A", Some("1"))]);
|
||||
assert!(set_developer_dir(root, Some("/Applications/Xcode-beta.app/Contents/Developer".into())));
|
||||
assert!(!set_developer_dir(root, Some("/Applications/Xcode-beta.app/Contents/Developer".into())));
|
||||
assert_eq!(
|
||||
*for_dir(&root.join("App")),
|
||||
[change("A", Some("1")), change("DEVELOPER_DIR", Some("/Applications/Xcode-beta.app/Contents/Developer"))]
|
||||
);
|
||||
assert!(set_developer_dir(root, None));
|
||||
assert_eq!(*for_dir(root), [change("DEVELOPER_DIR", Some("/envrc")), change("A", Some("1"))]);
|
||||
remove(root);
|
||||
assert!(for_dir(root).is_empty());
|
||||
let alone = Path::new("/openidea-test-env/xcode-alone");
|
||||
assert!(!set_developer_dir(alone, Some("".into())), "empty is the system default");
|
||||
assert!(set_developer_dir(alone, Some("/X".into())));
|
||||
assert_eq!(*for_dir(alone), [change("DEVELOPER_DIR", Some("/X"))]);
|
||||
assert!(set_developer_dir(alone, None));
|
||||
assert!(entries().iter().all(|e| e.root != alone), "an empty entry is dropped");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn waiting_ends_once_the_environment_is_read() {
|
||||
let root = Path::new("/openidea-test-env/waiting");
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -203,9 +203,6 @@ pub enum RunTargetKind {
|
||||
Docker,
|
||||
/// A new container of a Compose service (`docker compose run --rm`).
|
||||
Compose,
|
||||
/// A WSL distribution on this Windows machine (`wsl.exe -d <distro>`), the project read
|
||||
/// through `/mnt/<drive>`.
|
||||
Wsl,
|
||||
}
|
||||
|
||||
/// Build, Execution, Deployment › Run Targets: run configurations on another machine
|
||||
@@ -218,8 +215,7 @@ pub struct RunTarget {
|
||||
pub name: String,
|
||||
/// [`SshConfiguration::id`] (SSH).
|
||||
pub ssh_config: String,
|
||||
/// Remote folder the project is synchronised to and run from (SSH); the project's Linux
|
||||
/// path, empty = its `/mnt/<drive>` path (WSL).
|
||||
/// Remote folder the project is synchronised to and run from (SSH).
|
||||
pub project_root: String,
|
||||
/// Upload changed project files before each run (SSH).
|
||||
pub sync_before_run: bool,
|
||||
@@ -245,8 +241,6 @@ pub struct RunTarget {
|
||||
pub run_options: String,
|
||||
/// Run as the image's user instead of the project folder's owner (Linux).
|
||||
pub image_user: bool,
|
||||
/// Distribution name, as `wsl.exe -l -q` lists it (WSL).
|
||||
pub distro: String,
|
||||
}
|
||||
|
||||
/// A plugin-owned argv wrapper for project runs (API 1.4).
|
||||
|
||||
@@ -52,8 +52,6 @@ pub struct Settings {
|
||||
/// Per language server, by name (`rust-analyzer`): launch and protocol
|
||||
/// options on top of the language definition, or a server defined here.
|
||||
pub language_servers: BTreeMap<String, LanguageServerSettings>,
|
||||
/// Languages & Frameworks › JSON Schema Mappings: schemas for JSON and YAML files.
|
||||
pub json_schemas: Vec<JsonSchemaMapping>,
|
||||
/// Tools › Download sources: a mirror prefix for the release archives the installer fetches.
|
||||
pub tool_downloads: ToolDownloadSettings,
|
||||
/// Editor › Inspections profiles.
|
||||
@@ -68,8 +66,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).
|
||||
@@ -82,8 +78,6 @@ pub struct Settings {
|
||||
pub file_colors: FileColorSettings,
|
||||
/// Database › Query Execution, Languages & Frameworks › SQL Resolution Scopes.
|
||||
pub database: DatabaseSettings,
|
||||
/// Settings › Settings Sync (global only, never synced itself).
|
||||
pub settings_sync: SettingsSyncSettings,
|
||||
/// Plugin settings (`[contributes.settings]`): plugin id → its values by key.
|
||||
#[specta(type = BTreeMap<String, BTreeMap<String, specta_typescript::Unknown>>)]
|
||||
pub plugins: BTreeMap<String, serde_json::Map<String, serde_json::Value>>,
|
||||
@@ -105,20 +99,6 @@ pub struct AgentSettings {
|
||||
pub smooth_text: bool,
|
||||
/// Conversations and the composer expand to the full width of the pane instead of staying in a centred column.
|
||||
pub fit_window_width: bool,
|
||||
/// Chat text follows the interface font (Appearance › Use custom font).
|
||||
pub chat_use_ui_font: bool,
|
||||
/// Chat text family when it does not follow the interface font.
|
||||
pub chat_font_family: String,
|
||||
/// Covers characters the chat font lacks.
|
||||
pub chat_font_fallback: String,
|
||||
pub chat_font_size: u32,
|
||||
/// Code in chat follows the built-in code font.
|
||||
pub code_use_default_font: bool,
|
||||
/// Code family when it does not follow the built-in code font.
|
||||
pub code_font_family: String,
|
||||
/// Covers characters the code font lacks.
|
||||
pub code_font_fallback: String,
|
||||
pub code_font_size: u32,
|
||||
#[serde(deserialize_with = "or_default")]
|
||||
#[specta(type = ThinkingDisplay)]
|
||||
pub thinking: ThinkingDisplay,
|
||||
@@ -140,19 +120,6 @@ pub struct AgentSettings {
|
||||
#[serde(deserialize_with = "or_default")]
|
||||
#[specta(type = NewTaskApprovals)]
|
||||
pub new_task_approvals: NewTaskApprovals,
|
||||
/// How long an in-flight turn hit by a transient network outage waits and probes for
|
||||
/// connectivity before degrading to a manual Resume prompt.
|
||||
#[serde(deserialize_with = "or_default")]
|
||||
#[specta(type = NetworkRetryWindow)]
|
||||
pub network_retry_window: NetworkRetryWindow,
|
||||
/// What opening a project does with tasks interrupted when OpenIDEA closed or restarted.
|
||||
/// User settings only.
|
||||
#[serde(deserialize_with = "or_default")]
|
||||
#[specta(type = ResumeInterruptedPolicy)]
|
||||
pub resume_interrupted: ResumeInterruptedPolicy,
|
||||
/// Warn before closing a local window whose project still has running agent tasks.
|
||||
/// User settings only.
|
||||
pub confirm_terminate_on_close: bool,
|
||||
/// Settings new tasks of an agent start with: agent id → option id → value.
|
||||
#[serde(deserialize_with = "agent_defaults")]
|
||||
#[specta(type = BTreeMap<String, BTreeMap<String, String>>)]
|
||||
@@ -167,20 +134,6 @@ pub struct AgentSettings {
|
||||
#[serde(deserialize_with = "or_default")]
|
||||
#[specta(type = BTreeMap<String, AgentSkillPolicy>)]
|
||||
pub skills: BTreeMap<String, AgentSkillPolicy>,
|
||||
/// Agent memory policies (`[agents.memory]`): cross-session auto-memory mode, built-in
|
||||
/// MCP memory bridge, and per-entry modes; tracked files on disk are never modified.
|
||||
#[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 {
|
||||
@@ -192,29 +145,15 @@ impl Default for AgentSettings {
|
||||
show_cost: false,
|
||||
smooth_text: true,
|
||||
fit_window_width: false,
|
||||
chat_use_ui_font: true,
|
||||
chat_font_family: "Inter".into(),
|
||||
chat_font_fallback: String::new(),
|
||||
chat_font_size: 13,
|
||||
code_use_default_font: true,
|
||||
code_font_family: "JetBrains Mono".into(),
|
||||
code_font_fallback: String::new(),
|
||||
code_font_size: 13,
|
||||
thinking: ThinkingDisplay::Auto,
|
||||
tool_calls: ToolCallDisplay::Grouped,
|
||||
expand_tool_output: false,
|
||||
send_with: SendKey::Enter,
|
||||
while_running: WhileRunning::Queue,
|
||||
new_task_approvals: NewTaskApprovals::Bypass,
|
||||
network_retry_window: NetworkRetryWindow::Hour1,
|
||||
resume_interrupted: ResumeInterruptedPolicy::Ask,
|
||||
confirm_terminate_on_close: true,
|
||||
defaults: BTreeMap::new(),
|
||||
mcp_servers: BTreeMap::new(),
|
||||
skills: BTreeMap::new(),
|
||||
memory: AgentMemorySettings::default(),
|
||||
plugins: AgentPluginSettings::default(),
|
||||
automations: AgentAutomationSettings::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -298,169 +237,6 @@ impl Default for AgentSkillPolicy {
|
||||
}
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
/// Leave the agent's own configuration untouched.
|
||||
#[default]
|
||||
Inherit,
|
||||
/// Read past memories and record new ones.
|
||||
ReadWrite,
|
||||
/// Read past memories without recording new ones.
|
||||
ReadOnly,
|
||||
/// Neither read nor record cross-session auto-memories.
|
||||
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")]
|
||||
pub struct AgentProviderMemoryPolicy {
|
||||
#[serde(deserialize_with = "or_default")]
|
||||
#[specta(type = AutoMemoryMode)]
|
||||
pub auto_memory: AutoMemoryMode,
|
||||
}
|
||||
|
||||
/// Agent memory settings (`[agents.memory]`).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct AgentMemorySettings {
|
||||
/// 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>,
|
||||
/// Per-entry modes (`[agents.memory.entries.<id>]`).
|
||||
#[serde(deserialize_with = "or_default", skip_serializing_if = "BTreeMap::is_empty")]
|
||||
#[specta(type = BTreeMap<String, AgentMemoryEntryPolicy>)]
|
||||
pub entries: BTreeMap<String, AgentMemoryEntryPolicy>,
|
||||
}
|
||||
|
||||
/// 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>`.
|
||||
#[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,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A hand-edited value these settings don't know reads as the default, rather than
|
||||
/// failing the whole settings file.
|
||||
fn or_default<'de, D, T>(d: D) -> Result<T, D::Error>
|
||||
@@ -562,49 +338,6 @@ pub enum NewTaskApprovals {
|
||||
Ask,
|
||||
}
|
||||
|
||||
/// Default auto-retry window for transient network outages during an active agent turn.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
pub enum NetworkRetryWindow {
|
||||
#[serde(rename = "off")]
|
||||
Off,
|
||||
#[serde(rename = "15m")]
|
||||
Minutes15,
|
||||
#[default]
|
||||
#[serde(rename = "1h")]
|
||||
Hour1,
|
||||
#[serde(rename = "4h")]
|
||||
Hours4,
|
||||
#[serde(rename = "24h")]
|
||||
Hours24,
|
||||
}
|
||||
|
||||
impl NetworkRetryWindow {
|
||||
pub fn minutes(self) -> u32 {
|
||||
match self {
|
||||
Self::Off => 0,
|
||||
Self::Minutes15 => 15,
|
||||
Self::Hour1 => 60,
|
||||
Self::Hours4 => 240,
|
||||
Self::Hours24 => 1440,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How interrupted agent tasks are handled when a project reopens.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum ResumeInterruptedPolicy {
|
||||
/// Show Interrupted markers, banner and balloon; wait for the user to click Resume.
|
||||
#[default]
|
||||
Ask,
|
||||
/// Auto-resume tasks interrupted by an IDE restart or backend upgrade within 15 minutes.
|
||||
Restart,
|
||||
/// Auto-resume tasks interrupted by close, quit or restart within the session recovery window.
|
||||
Window,
|
||||
/// Settle quietly to Ready with no Interrupted markers or balloons.
|
||||
Off,
|
||||
}
|
||||
|
||||
/// Which folders without an open window the MCP server still serves tools for.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
@@ -705,91 +438,15 @@ 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.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct SettingsSyncSettings {
|
||||
/// Clone URL (a secret GitHub Gist's works too, though anyone with its link can read it);
|
||||
/// empty = sync off.
|
||||
pub repository: String,
|
||||
/// Sync on startup and after the settings change, besides Sync Now.
|
||||
pub auto: bool,
|
||||
pub appearance: bool,
|
||||
/// Editor settings, color schemes, code style, inspections and spelling.
|
||||
pub editor: bool,
|
||||
pub keymaps: bool,
|
||||
/// Every other setting that is not machine-specific.
|
||||
pub other: bool,
|
||||
/// Live, file and postfix templates.
|
||||
pub templates: bool,
|
||||
pub macros: bool,
|
||||
/// Tool window layouts and view options.
|
||||
pub ui: bool,
|
||||
/// The list of installed plugins: missing ones are offered, never installed or removed.
|
||||
pub plugins: bool,
|
||||
}
|
||||
|
||||
impl Default for SettingsSyncSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
repository: String::new(),
|
||||
auto: true,
|
||||
appearance: true,
|
||||
editor: true,
|
||||
keymaps: true,
|
||||
other: true,
|
||||
templates: true,
|
||||
macros: true,
|
||||
ui: true,
|
||||
plugins: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Absent profiles retain automatic discovery for existing projects.
|
||||
#[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)]
|
||||
@@ -803,23 +460,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 {
|
||||
@@ -832,44 +472,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,
|
||||
}
|
||||
|
||||
/// Build, Execution, Deployment › Toolchains (IDE-wide, as in CLion). Empty fields are
|
||||
/// detected: from the MinGW directory, 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`).
|
||||
pub path: String,
|
||||
pub cmake: String,
|
||||
/// `CMAKE_MAKE_PROGRAM`: make, mingw32-make 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 {
|
||||
@@ -981,15 +587,12 @@ 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(),
|
||||
scopes: Vec::new(),
|
||||
json_schemas: Vec::new(),
|
||||
file_colors: FileColorSettings::default(),
|
||||
database: DatabaseSettings::default(),
|
||||
settings_sync: SettingsSyncSettings::default(),
|
||||
plugins: BTreeMap::new(),
|
||||
}
|
||||
}
|
||||
@@ -1009,17 +612,6 @@ pub struct NamedScope {
|
||||
pub pattern: String,
|
||||
}
|
||||
|
||||
/// A schema for the JSON and YAML files matching `files`; wins over a built-in SchemaStore mapping.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct JsonSchemaMapping {
|
||||
pub name: String,
|
||||
/// A URL, or a file path relative to the project.
|
||||
pub schema: String,
|
||||
/// Project-relative paths or glob patterns (`config/*.json`, `**/*.app.yaml`).
|
||||
pub files: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct FileColorSettings {
|
||||
@@ -1248,8 +840,6 @@ pub struct AppearanceSettings {
|
||||
pub smooth_scrolling: bool,
|
||||
pub full_path_in_title: bool,
|
||||
pub project_colors_in_toolbar: bool,
|
||||
/// Strength of the project colour tint in the window header, in percent (10–70).
|
||||
pub project_color_strength: u8,
|
||||
pub dnd_with_alt_only: bool,
|
||||
pub menu_icons: bool,
|
||||
/// `hamburger` | `merged` | `toolbar` (a separate row): main menu presentation in the frameless title bar.
|
||||
@@ -1268,8 +858,6 @@ pub struct AppearanceSettings {
|
||||
pub widescreen_tool_windows: bool,
|
||||
/// Each tool window keeps its own size; off, the windows of a side share one.
|
||||
pub remember_tool_window_sizes: bool,
|
||||
/// Tool window shortcuts hide an open unfocused window right away instead of focusing it first.
|
||||
pub toggle_tool_windows_on_shortcut: bool,
|
||||
/// View › Appearance › Toolbar; hidden leaves IDEA's compact window header.
|
||||
pub show_main_toolbar: bool,
|
||||
pub show_status_bar: bool,
|
||||
@@ -1391,7 +979,6 @@ impl Default for AppearanceSettings {
|
||||
smooth_scrolling: true,
|
||||
full_path_in_title: false,
|
||||
project_colors_in_toolbar: true,
|
||||
project_color_strength: 22,
|
||||
dnd_with_alt_only: false,
|
||||
menu_icons: true,
|
||||
main_menu_style: "hamburger".into(),
|
||||
@@ -1404,7 +991,6 @@ impl Default for AppearanceSettings {
|
||||
show_tool_window_badges: true,
|
||||
widescreen_tool_windows: false,
|
||||
remember_tool_window_sizes: false,
|
||||
toggle_tool_windows_on_shortcut: false,
|
||||
show_main_toolbar: true,
|
||||
show_status_bar: true,
|
||||
navigation_bar: NavigationBarPosition::StatusBar,
|
||||
@@ -1642,7 +1228,6 @@ pub struct LanguagesSettings {
|
||||
pub arduino: ArduinoSettings,
|
||||
pub zig: ZigSettings,
|
||||
pub flutter: FlutterSettings,
|
||||
pub swift: SwiftSettings,
|
||||
}
|
||||
|
||||
impl Default for LanguagesSettings {
|
||||
@@ -1676,7 +1261,6 @@ impl Default for LanguagesSettings {
|
||||
arduino: ArduinoSettings::default(),
|
||||
zig: ZigSettings::default(),
|
||||
flutter: FlutterSettings::default(),
|
||||
swift: SwiftSettings::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1699,9 +1283,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>,
|
||||
/// 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,
|
||||
@@ -1714,22 +1295,12 @@ impl Default for MarkdownSettings {
|
||||
Self {
|
||||
preview_layout: MarkdownPreviewLayout::default(),
|
||||
preview_font_size: None,
|
||||
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 MdxExecutionPolicy {
|
||||
#[default]
|
||||
Ask,
|
||||
Trusted,
|
||||
Off,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum MarkdownPreviewLayout {
|
||||
@@ -1802,8 +1373,6 @@ pub struct ExternalFormatterSettings {
|
||||
/// Prefer this formatter even when a language server offers formatting.
|
||||
pub prefer: bool,
|
||||
pub run_on_save: bool,
|
||||
/// Ruff only: apply safe lint fixes (`ruff check --fix-only`) on save, independently of formatting.
|
||||
pub fix_on_save: bool,
|
||||
}
|
||||
|
||||
impl Default for ExternalFormatterSettings {
|
||||
@@ -1832,7 +1401,6 @@ impl Default for ExternalFormatterSettings {
|
||||
.collect(),
|
||||
prefer: false,
|
||||
run_on_save: false,
|
||||
fix_on_save: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1861,12 +1429,6 @@ 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` (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.
|
||||
pub show_plots_in_tool_window: bool,
|
||||
}
|
||||
|
||||
impl Default for PythonSettings {
|
||||
@@ -1880,8 +1442,6 @@ impl Default for PythonSettings {
|
||||
show_interpreter_paths: true,
|
||||
interpreter_paths: BTreeMap::new(),
|
||||
test_runner: "auto".into(),
|
||||
profiler: "auto".into(),
|
||||
show_plots_in_tool_window: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1974,26 +1534,6 @@ pub struct ZigSettings {
|
||||
pub zig: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct SwiftSettings {
|
||||
/// The Xcode (`Xcode.app` or its `Contents/Developer`) whose tools the project's sourcekit-lsp,
|
||||
/// `xcodebuild`, `xcrun` and terminals use, as `DEVELOPER_DIR`. Empty = the `xcode-select` one.
|
||||
pub xcode: String,
|
||||
}
|
||||
|
||||
impl SwiftSettings {
|
||||
/// [`Self::xcode`] as a `DEVELOPER_DIR` value (`Xcode.app` gets `/Contents/Developer`); `None` when unset.
|
||||
pub fn developer_dir(&self) -> Option<std::path::PathBuf> {
|
||||
let xcode = self.xcode.trim();
|
||||
if xcode.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let path = std::path::Path::new(xcode);
|
||||
Some(if path.extension().is_some_and(|e| e == "app") { path.join("Contents/Developer") } else { path.into() })
|
||||
}
|
||||
}
|
||||
|
||||
/// The Flutter plugin's "Flutter SDK path".
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
@@ -2200,10 +1740,6 @@ pub struct TypeScriptSettings {
|
||||
/// plugin (hybrid mode; a Vue project's program alone needs ~3 GiB, and the
|
||||
/// vtsls default 3072 dies in a GC death spiral), else unset (vtsls default).
|
||||
pub tsserver_max_memory: u32,
|
||||
/// tsserver's log (`typescript.tsserver.log`). TypeScript: Open TS Server Log opens it.
|
||||
#[serde(deserialize_with = "or_default")]
|
||||
#[specta(type = TsServerLog)]
|
||||
pub tsserver_log: TsServerLog,
|
||||
/// Problems › TypeScript project errors: the project's own `tsc --watch` per root
|
||||
/// `tsconfig.json` reports the errors of files that are not open.
|
||||
pub watch_problems: bool,
|
||||
@@ -2211,27 +1747,10 @@ pub struct TypeScriptSettings {
|
||||
|
||||
impl Default for TypeScriptSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
version: "bundled".into(),
|
||||
tsserver_max_memory: 0,
|
||||
tsserver_log: TsServerLog::Off,
|
||||
watch_problems: false,
|
||||
}
|
||||
Self { version: "bundled".into(), tsserver_max_memory: 0, watch_problems: false }
|
||||
}
|
||||
}
|
||||
|
||||
/// tsserver's log verbosity, as vtsls' `typescript.tsserver.log` spells it.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum TsServerLog {
|
||||
#[default]
|
||||
Off,
|
||||
Terse,
|
||||
Normal,
|
||||
RequestTime,
|
||||
Verbose,
|
||||
}
|
||||
|
||||
/// Dependency scope for a module dependency or project library (IDEA's Modules › Dependencies).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
@@ -2257,37 +1776,6 @@ pub struct ProjectLibrary {
|
||||
pub scope: DependencyScope,
|
||||
}
|
||||
|
||||
/// A library class entry written as a jar glob: `dir/*.jar` → `(dir, false)`, `dir/**/*.jar` → `(dir, true)`.
|
||||
pub fn split_jar_glob(entry: &str) -> Option<(&str, bool)> {
|
||||
let entry = entry.trim();
|
||||
if let Some(base) = entry.strip_suffix("/**/*.jar").or_else(|| entry.strip_suffix(r"\**\*.jar")) {
|
||||
return Some((base, true));
|
||||
}
|
||||
entry.strip_suffix("/*.jar").or_else(|| entry.strip_suffix(r"\*.jar")).map(|base| (base, false))
|
||||
}
|
||||
|
||||
/// The `.jar` files in `dir` (and its subfolders when `recursive`), sorted by name per folder.
|
||||
pub fn jar_files(dir: &std::path::Path, recursive: bool) -> Vec<std::path::PathBuf> {
|
||||
fn walk(dir: &std::path::Path, recursive: bool, out: &mut Vec<std::path::PathBuf>) {
|
||||
let Ok(entries) = std::fs::read_dir(dir) else { return };
|
||||
let mut entries: Vec<_> = entries.flatten().collect();
|
||||
entries.sort_by_key(|e| e.file_name());
|
||||
for entry in entries {
|
||||
let path = entry.path();
|
||||
match entry.file_type() {
|
||||
Ok(t) if t.is_dir() && recursive => walk(&path, true, out),
|
||||
Ok(t) if t.is_file() && path.extension().is_some_and(|x| x.eq_ignore_ascii_case("jar")) => {
|
||||
out.push(path)
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
walk(dir, recursive, &mut out);
|
||||
out
|
||||
}
|
||||
|
||||
/// Dependency entry of a module (Project Structure › Modules › Dependencies).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
@@ -2435,44 +1923,6 @@ impl Settings {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_xcode_setting_becomes_a_developer_dir() {
|
||||
let dir = |xcode: &str| SwiftSettings { xcode: xcode.into() }.developer_dir();
|
||||
assert_eq!(dir(""), None);
|
||||
assert_eq!(dir(" "), None);
|
||||
assert_eq!(dir("/Applications/Xcode-beta.app"), Some("/Applications/Xcode-beta.app/Contents/Developer".into()));
|
||||
assert_eq!(
|
||||
dir("/Applications/Xcode.app/Contents/Developer"),
|
||||
Some("/Applications/Xcode.app/Contents/Developer".into())
|
||||
);
|
||||
let s: Settings = serde_json::from_str(r#"{"languages":{"swift":{"xcode":"/X.app"}}}"#).unwrap();
|
||||
assert_eq!(s.languages.swift.xcode, "/X.app");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ruff_safe_fixes_on_save_default_off_and_round_trip() {
|
||||
let old: Settings = serde_json::from_str(r#"{"languages":{"ruff":{"runOnSave":true}}}"#).unwrap();
|
||||
assert!(old.languages.ruff.run_on_save);
|
||||
assert!(!old.languages.ruff.fix_on_save);
|
||||
let on: Settings = serde_json::from_str(r#"{"languages":{"ruff":{"fixOnSave":true}}}"#).unwrap();
|
||||
assert!(on.languages.ruff.fix_on_save);
|
||||
assert_eq!(serde_json::to_value(&on).unwrap()["languages"]["ruff"]["fixOnSave"], true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tsserver_log_reads_known_levels_and_drops_anything_else() {
|
||||
let log = |v: &str| {
|
||||
let s: Settings =
|
||||
serde_json::from_str(&format!(r#"{{"languages":{{"typescript":{{"tsserverLog":{v}}}}}}}"#)).unwrap();
|
||||
s.languages.typescript.tsserver_log
|
||||
};
|
||||
assert_eq!(log(r#""requestTime""#), TsServerLog::RequestTime);
|
||||
assert_eq!(log(r#""verbose""#), TsServerLog::Verbose);
|
||||
assert_eq!(log(r#""--trace""#), TsServerLog::Off);
|
||||
assert_eq!(log("3"), TsServerLog::Off);
|
||||
assert_eq!(serde_json::to_value(TsServerLog::RequestTime).unwrap(), "requestTime");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn python_interpreter_may_name_a_run_target() {
|
||||
let python = |interpreter: &str| PythonSettings { interpreter: interpreter.into(), ..Default::default() };
|
||||
@@ -2506,19 +1956,6 @@ mod tests {
|
||||
assert_eq!(json["appearance"]["smoothScrolling"], false);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn database_output_destination_defaults_and_round_trips() {
|
||||
let old: Settings = serde_json::from_str(r#"{"database":{"inEditorResults":true}}"#).unwrap();
|
||||
assert_eq!(old.database.output_destination, DatabaseOutputDestination::DatabaseOutput);
|
||||
assert!(old.database.in_editor_results);
|
||||
|
||||
let services: Settings = serde_json::from_str(r#"{"database":{"outputDestination":"services"}}"#).unwrap();
|
||||
assert_eq!(services.database.output_destination, DatabaseOutputDestination::Services);
|
||||
let saved = serde_json::to_value(&services).unwrap();
|
||||
assert_eq!(saved["database"]["outputDestination"], "services");
|
||||
assert_eq!(serde_json::from_value::<Settings>(saved).unwrap().database, services.database);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn window_close_settings_default_off_and_round_trip() {
|
||||
for old in [r#"{}"#, r#"{"general":{"confirmExit":false}}"#] {
|
||||
@@ -2680,21 +2117,6 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn toggle_tool_windows_on_shortcut_defaults_off_and_round_trips() {
|
||||
let old: Settings = serde_json::from_str(r#"{"appearance":{"showToolWindowNames":true}}"#).unwrap();
|
||||
assert!(!old.appearance.toggle_tool_windows_on_shortcut);
|
||||
assert!(!Settings::default().appearance.toggle_tool_windows_on_shortcut);
|
||||
for enabled in [true, false] {
|
||||
let mut settings = Settings::default();
|
||||
settings.appearance.toggle_tool_windows_on_shortcut = enabled;
|
||||
let json = serde_json::to_value(&settings).unwrap();
|
||||
assert_eq!(json["appearance"]["toggleToolWindowsOnShortcut"], enabled);
|
||||
let restored: Settings = serde_json::from_value(json).unwrap();
|
||||
assert_eq!(restored.appearance.toggle_tool_windows_on_shortcut, enabled);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn double_click_opens_diff_is_unset_by_default_and_round_trips() {
|
||||
let old: Settings = serde_json::from_str(r#"{"vcs":{"commit":{"nonModal":true}}}"#).unwrap();
|
||||
|
||||
@@ -296,14 +296,6 @@ pub struct OutlineItem {
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub visibility: Option<Visibility>,
|
||||
/// Rust `impl Trait for Type`: the trait's name in the header (its last path segment, where go-to-definition lands), from the syntax tree.
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub implements: Option<Range>,
|
||||
/// Rust `impl [Trait for] Type`: the implementing type's name (its last path segment), from the syntax tree.
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub self_type: Option<Range>,
|
||||
}
|
||||
|
||||
/// Fuzzy-match highlight: indices (in chars of the displayed string) that matched.
|
||||
|
||||
@@ -27,35 +27,6 @@ pub struct VcsSettings {
|
||||
pub mappings: VcsMappings,
|
||||
/// Settings › Version Control › GitHub: per-project GitHub CLI account selection.
|
||||
pub github: GithubSettings,
|
||||
/// Settings › Version Control › Subversion.
|
||||
pub svn: SvnSettings,
|
||||
}
|
||||
|
||||
/// Settings › Version Control › Subversion (`vcs.svn`).
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct SvnSettings {
|
||||
/// Path to the svn executable; empty = auto-detect.
|
||||
pub executable: String,
|
||||
/// Run svn as if in a terminal: its password, passphrase and certificate prompts open
|
||||
/// dialogs. Off, svn runs with `--non-interactive` and a rejected login asks once.
|
||||
pub interactive: bool,
|
||||
/// Pass `--config-dir config_dir` to every svn command.
|
||||
pub use_custom_config_dir: bool,
|
||||
pub config_dir: String,
|
||||
}
|
||||
|
||||
impl Default for SvnSettings {
|
||||
/// Interactive except on Windows: svn there asks on the console, which an IDE's child
|
||||
/// process has hidden, so a prompt could not be answered (not verified on Windows yet).
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
executable: String::new(),
|
||||
interactive: !cfg!(windows),
|
||||
use_custom_config_dir: false,
|
||||
config_dir: String::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Settings › Version Control › GitHub (`vcs.github`).
|
||||
@@ -109,7 +80,6 @@ impl Default for VcsSettings {
|
||||
issue_navigation: Vec::new(),
|
||||
mappings: VcsMappings::default(),
|
||||
github: GithubSettings::default(),
|
||||
svn: SvnSettings::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -173,9 +143,6 @@ impl Default for GitAnnotateSettings {
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct GitSettings {
|
||||
/// Git integration on: off, the IDE finds no repositories and runs no git at all
|
||||
/// (no status, log, blame, fetch, clone or agent worktrees), and hides its Git UI.
|
||||
pub enabled: bool,
|
||||
pub annotate: GitAnnotateSettings,
|
||||
/// Show blame after the current editor line.
|
||||
pub inline_blame: bool,
|
||||
@@ -234,7 +201,6 @@ pub struct GitSettings {
|
||||
impl Default for GitSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
enabled: true,
|
||||
annotate: GitAnnotateSettings::default(),
|
||||
inline_blame: false,
|
||||
inline_blame_clickable: true,
|
||||
@@ -284,8 +250,6 @@ pub struct CommitSettings {
|
||||
pub reformat: bool,
|
||||
pub optimize_imports: bool,
|
||||
pub cleanup: bool,
|
||||
/// Apply Ruff's safe lint fixes before composing the commit, independently of formatting.
|
||||
pub fix_on_commit: bool,
|
||||
pub blank_line_after_subject: bool,
|
||||
pub limit_subject: bool,
|
||||
pub subject_limit: u32,
|
||||
@@ -327,7 +291,6 @@ impl Default for CommitSettings {
|
||||
reformat: false,
|
||||
optimize_imports: false,
|
||||
cleanup: false,
|
||||
fix_on_commit: false,
|
||||
blank_line_after_subject: true,
|
||||
limit_subject: true,
|
||||
subject_limit: 72,
|
||||
@@ -439,24 +402,13 @@ impl Default for LogLevelColors {
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct DatabaseSettings {
|
||||
/// A console's result sets show under the statements that produced them, in the editor,
|
||||
/// instead of in the output window's result tabs.
|
||||
/// instead of in the Services view's result tabs.
|
||||
pub in_editor_results: bool,
|
||||
/// The tool window that receives SQL query output and plans.
|
||||
pub output_destination: DatabaseOutputDestination,
|
||||
/// Languages & Frameworks › SQL Resolution Scopes: the data source SQL in a file or folder
|
||||
/// resolves against (completion, inspections, navigation), most specific path first.
|
||||
pub resolution_scopes: Vec<SqlResolutionScope>,
|
||||
}
|
||||
|
||||
/// Database › Query Output: where SQL results open.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum DatabaseOutputDestination {
|
||||
#[default]
|
||||
DatabaseOutput,
|
||||
Services,
|
||||
}
|
||||
|
||||
/// One row of SQL Resolution Scopes.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
@@ -477,15 +429,12 @@ pub struct BuildSettings {
|
||||
pub open_tool_window: String,
|
||||
/// When to focus the Build tool window: `always` | `onError` | `never`.
|
||||
pub focus_tool_window: String,
|
||||
/// Build an Xcode project in the background when xcode-build-server has no build log to read
|
||||
/// yet, so cross-file code insight works before the first Run.
|
||||
pub xcode_index_build: bool,
|
||||
}
|
||||
|
||||
impl Default for BuildSettings {
|
||||
fn default() -> Self {
|
||||
// Builds open the tool window without taking focus.
|
||||
Self { open_tool_window: "always".into(), focus_tool_window: "never".into(), xcode_index_build: true }
|
||||
Self { open_tool_window: "always".into(), focus_tool_window: "never".into() }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -563,7 +512,6 @@ pub struct DebuggerSettings {
|
||||
/// Java: whether to reload changed classes into running debug sessions after compilation.
|
||||
pub hot_swap_after_compile: HotSwapPolicy,
|
||||
pub python: PythonDebuggerSettings,
|
||||
pub cpp: CppDebuggerSettings,
|
||||
}
|
||||
|
||||
impl Default for DebuggerSettings {
|
||||
@@ -586,7 +534,6 @@ impl Default for DebuggerSettings {
|
||||
flutter_hot_reload_on_save: true,
|
||||
hot_swap_after_compile: HotSwapPolicy::Ask,
|
||||
python: PythonDebuggerSettings::default(),
|
||||
cpp: CppDebuggerSettings::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -605,14 +552,6 @@ impl Default for PythonDebuggerSettings {
|
||||
}
|
||||
}
|
||||
|
||||
/// C/C++ debugger executables. Empty paths use automatic discovery.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct CppDebuggerSettings {
|
||||
pub gdb_executable: String,
|
||||
pub lldb_dap_executable: String,
|
||||
}
|
||||
|
||||
/// Run/Debug configuration behaviour.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
@@ -659,17 +598,11 @@ pub struct TerminalSettings {
|
||||
pub close_on_exit: bool,
|
||||
pub mouse_reporting: bool,
|
||||
pub copy_on_selection: bool,
|
||||
/// Programs may set the clipboard with OSC 52 (tmux, Neovim, TUIs over SSH); never read it.
|
||||
pub osc52_clipboard: bool,
|
||||
pub paste_on_middle_click: bool,
|
||||
/// Right-click pastes instead of opening the context menu (Ctrl or Shift + right-click still opens it).
|
||||
pub right_click_paste: bool,
|
||||
pub override_ide_shortcuts: bool,
|
||||
pub shell_integration: bool,
|
||||
pub highlight_hyperlinks: bool,
|
||||
pub highlight_selection: bool,
|
||||
/// Highlights typed commands the IDE recognises; Run Highlighted Command runs them with it.
|
||||
pub run_commands_using_ide: bool,
|
||||
pub option_as_meta: bool,
|
||||
/// Escape moves focus to the editor instead of reaching the shell.
|
||||
pub escape_to_editor: bool,
|
||||
@@ -701,14 +634,11 @@ impl Default for TerminalSettings {
|
||||
close_on_exit: true,
|
||||
mouse_reporting: true,
|
||||
copy_on_selection: false,
|
||||
osc52_clipboard: true,
|
||||
paste_on_middle_click: true,
|
||||
right_click_paste: false,
|
||||
override_ide_shortcuts: true,
|
||||
shell_integration: true,
|
||||
highlight_hyperlinks: true,
|
||||
highlight_selection: true,
|
||||
run_commands_using_ide: true,
|
||||
option_as_meta: false,
|
||||
escape_to_editor: false,
|
||||
cursor_shape: "block".into(),
|
||||
@@ -798,24 +728,6 @@ impl Default for AgentSecuritySettings {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn ruff_safe_fixes_on_commit_default_off_and_round_trip() {
|
||||
let old: CommitSettings = serde_json::from_str(r#"{"reformat":true}"#).unwrap();
|
||||
assert!(old.reformat);
|
||||
assert!(!old.fix_on_commit);
|
||||
let on: CommitSettings = serde_json::from_str(r#"{"fixOnCommit":true}"#).unwrap();
|
||||
assert!(on.fix_on_commit);
|
||||
assert_eq!(serde_json::to_value(&on).unwrap()["fixOnCommit"], true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn git_defaults_enabled_and_can_be_disabled() {
|
||||
let missing: GitSettings = serde_json::from_str("{}").unwrap();
|
||||
let off: GitSettings = serde_json::from_str(r#"{"enabled":false}"#).unwrap();
|
||||
assert!(missing.enabled);
|
||||
assert!(!off.enabled);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clone_submodules_defaults_on_and_can_be_disabled() {
|
||||
let missing: GitSettings = serde_json::from_str("{}").unwrap();
|
||||
@@ -846,17 +758,4 @@ mod tests {
|
||||
assert_eq!(serialized["hotSwapAfterCompile"], raw);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cpp_debugger_paths_default_to_empty_and_roundtrip() {
|
||||
let missing: DebuggerSettings = serde_json::from_str("{}").unwrap();
|
||||
assert!(missing.cpp.gdb_executable.is_empty());
|
||||
assert!(missing.cpp.lldb_dap_executable.is_empty());
|
||||
|
||||
let cpp = serde_json::json!({"gdbExecutable": "tools/gdb-16", "lldbDapExecutable": "/opt/llvm/bin/lldb-dap"});
|
||||
let settings: DebuggerSettings = serde_json::from_value(serde_json::json!({"cpp": cpp})).unwrap();
|
||||
assert_eq!(settings.cpp.gdb_executable, "tools/gdb-16");
|
||||
assert_eq!(settings.cpp.lldb_dap_executable, "/opt/llvm/bin/lldb-dap");
|
||||
assert_eq!(serde_json::to_value(&settings).unwrap()["cpp"], cpp);
|
||||
}
|
||||
}
|
||||
@@ -35,24 +35,6 @@ pub fn parse(path: &Path) -> Option<WslPath> {
|
||||
Some(WslPath { distro: distro.to_owned(), path: format!("/{}", tail.trim_end_matches('/')) })
|
||||
}
|
||||
|
||||
/// The Linux path of a Windows path seen from `distro`: `C:\a` → `/mnt/c/a` (WSL's default
|
||||
/// automount root), `\\wsl.localhost\<distro>\a` → `/a`. `None` for another distro's share,
|
||||
/// other network shares and relative paths.
|
||||
pub fn linux_path(path: &Path, distro: &str) -> Option<String> {
|
||||
if let Some(w) = parse(path) {
|
||||
return w.distro.eq_ignore_ascii_case(distro).then_some(w.path);
|
||||
}
|
||||
let s = path.to_string_lossy().replace('\\', "/");
|
||||
let s = s.strip_prefix("//?/").unwrap_or(&s);
|
||||
let mut chars = s.chars();
|
||||
let drive = chars.next().filter(char::is_ascii_alphabetic)?;
|
||||
let rest = chars.as_str().strip_prefix(':')?;
|
||||
if !(rest.is_empty() || rest.starts_with('/')) {
|
||||
return None;
|
||||
}
|
||||
Some(format!("/mnt/{}{}", drive.to_ascii_lowercase(), rest.trim_end_matches('/')))
|
||||
}
|
||||
|
||||
/// A distro name `wsl.exe -d` can be given safely: Windows creates them from letters, digits,
|
||||
/// `.`, `_` and `-`. A leading `-` would be read as an option, so it is refused too.
|
||||
pub fn is_valid_distro(name: &str) -> bool {
|
||||
@@ -104,57 +86,6 @@ pub fn list_distros() -> Vec<String> {
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
/// Where this machine reads `distro`'s file system.
|
||||
pub fn share_root(distro: &str) -> std::path::PathBuf {
|
||||
format!(r"\\wsl.localhost\{distro}").into()
|
||||
}
|
||||
|
||||
/// The names of a Linux path, `.` dropped and `..` taking the name before it.
|
||||
pub fn path_parts(linux: &str) -> Vec<&str> {
|
||||
let mut parts: Vec<&str> = Vec::new();
|
||||
for c in linux.split('/').filter(|c| !c.is_empty() && *c != ".") {
|
||||
if c == ".." {
|
||||
parts.pop();
|
||||
} else {
|
||||
parts.push(c);
|
||||
}
|
||||
}
|
||||
parts
|
||||
}
|
||||
|
||||
/// Where this machine reads the absolute path `linux` of `distro`: a drive mounted at
|
||||
/// `/mnt/<drive>` is read directly, anything else through [`share_root`]. `..` goes up
|
||||
/// within `linux`, never above the drive or the share.
|
||||
pub fn windows_path(linux: &str, distro: &str) -> std::path::PathBuf {
|
||||
let parts = path_parts(linux);
|
||||
let base = match parts.as_slice() {
|
||||
["mnt", drive, ..] if drive.len() == 1 && drive.chars().all(|c| c.is_ascii_alphabetic()) => {
|
||||
let base = std::path::PathBuf::from(format!("{}:\\", drive.to_ascii_uppercase()));
|
||||
return parts[2..].iter().fold(base, |p, c| p.join(c));
|
||||
}
|
||||
_ => share_root(distro),
|
||||
};
|
||||
parts.iter().fold(base, |p, c| p.join(c))
|
||||
}
|
||||
|
||||
/// Runs `args` in `distro` without its shell and returns the standard output; a failed
|
||||
/// run is an error with its output. `wsl.exe`'s own messages are UTF-16: their NULs go.
|
||||
pub fn exec(distro: &str, args: &[&str], timeout: std::time::Duration) -> crate::IdeResult<String> {
|
||||
use crate::cli_process::{CliTool, Decoding};
|
||||
if !is_valid_distro(distro) {
|
||||
return Err(crate::IdeError::invalid(format!("'{distro}' is not a WSL distribution name")));
|
||||
}
|
||||
let mut cmd = std::process::Command::new(EXE);
|
||||
cmd.args(["-d", distro, "--exec"]).args(args);
|
||||
let out = CliTool::new(EXE, Decoding::Utf8Lossy).run(cmd, timeout, None)?;
|
||||
let (stdout, stderr) = (out.stdout.replace('\0', ""), out.stderr.replace('\0', ""));
|
||||
if out.success {
|
||||
return Ok(stdout);
|
||||
}
|
||||
let detail = if stderr.trim().is_empty() { stdout.trim() } else { stderr.trim() };
|
||||
Err(crate::IdeError::internal(format!("{EXE} -d {distro} --exec {}: {detail}", args.first().unwrap_or(&""))))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -172,21 +103,6 @@ mod tests {
|
||||
assert_eq!(p(r"\\?\UNC\WSL.LOCALHOST\Ubuntu-24.04\home\me\app"), want);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn windows_paths_map_onto_the_distro() {
|
||||
let l = |s: &str| linux_path(Path::new(s), "Ubuntu");
|
||||
assert_eq!(l(r"C:\Users\me\app"), Some("/mnt/c/Users/me/app".into()));
|
||||
assert_eq!(l(r"D:\"), Some("/mnt/d".into()));
|
||||
assert_eq!(l("e:/work/x/"), Some("/mnt/e/work/x".into()));
|
||||
assert_eq!(l(r"\\?\C:\proj"), Some("/mnt/c/proj".into()));
|
||||
assert_eq!(l(r"\\wsl.localhost\ubuntu\home\me"), Some("/home/me".into()));
|
||||
assert_eq!(l(r"\\wsl$\Debian\home\me"), None);
|
||||
assert_eq!(l(r"\\server\share\a"), None);
|
||||
assert_eq!(l(r"C:relative"), None);
|
||||
assert_eq!(l("app"), None);
|
||||
assert_eq!(l("/home/me"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn distro_root_and_foreign_paths() {
|
||||
assert_eq!(p(r"\\wsl.localhost\Debian"), Some(("Debian".to_owned(), "/".to_owned())));
|
||||
@@ -211,14 +127,6 @@ mod tests {
|
||||
assert!(parse_distro_list(b"").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn linux_paths_are_read_on_their_drive_or_through_the_share() {
|
||||
use std::path::PathBuf;
|
||||
assert_eq!(windows_path("/mnt/d/lib/../x.py", "U"), PathBuf::from("D:\\").join("x.py"));
|
||||
assert_eq!(windows_path("/usr/lib/a.py", "U"), share_root("U").join("usr").join("lib").join("a.py"));
|
||||
assert_eq!(windows_path("/mnt/wsl/x", "U"), share_root("U").join("mnt").join("wsl").join("x"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn distro_names_cannot_smuggle_options_or_paths() {
|
||||
for bad in ["", "-d", "--exec", "a b", "a/b", r"a\b", "a;b", "a$(x)", "a\"b"] {
|
||||
|
||||
Loaded 100 of 2461 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Заблокувати користувача