Порівняти коміти

...
Автор SHA1 Повідомлення Дата
l0ng-ai 71e089b0fa feat(plugins): read HTTP responses as they arrive with net.fetch-stream
Plugin API 1.19 adds net.fetch-stream, which returns a response-stream once
the headers arrive; its body is read piece by piece with a timeout, so a
plugin can consume server-sent events or a model's streamed reply and stop
early. It uses the same grants, secrets and redirect checks as fetch, which
now shares the request builder. The SDK gets host::fetch_stream,
ResponseStream and an sse parser; components are rebuilt for the new WIT.
2026-11-29 22:49:30 +08:00
l0ng-aiтаrohitdanda 18860f5f98 ci: give signing secrets only to the steps that sign, and pin actions by SHA (#6854)
The updater signing key and Apple credentials were exported job-wide through GITHUB_ENV, so every later step in the release build (dependency installs, third-party actions) could read them. They now reach only the steps that sign: a signed tauri-action build when the updater key is configured (an unsigned build otherwise, since an empty key still counts as set), DMG notarization, and the portable zip. All third-party actions across the workflows are pinned to commit SHAs with their release in a comment, and Dependabot keeps the github-actions ecosystem current with weekly grouped updates.

Refs #6142, #6701

Co-authored-by: rohitdanda <[email protected]>
2026-11-29 22:46:18 +08:00
l0ng-ai 8e9c02cae6 test(e2e): expect editable artifacts in a project without a build tool (#6857)
#6834 made Project Structure › Artifacts editable when the project has no Maven or Gradle build; the settings spec still expected a disabled JAR button. It now checks the button is enabled and the Maven/Gradle note is absent.
2026-11-29 22:45:25 +08:00
l0ng-ai 28b879c668 fix(run): show the iOS Simulator chooser only in confirmed Xcode projects (#6856)
The chooser appeared whenever listing simulators failed, so Restricted Mode windows, hosts without the command and the browser e2e harness showed "Simulators unavailable" in every project's toolbar (breaking the toolbar layout e2e specs on main). A failure is now shown only after a listing has confirmed an Xcode project; later refresh failures still appear in the chooser.
2026-11-29 22:44:10 +08:00
Deng Liuтаdengliu 19aef36354 feat(agents): add Agent Memory settings and a per-session memory picker (#6826)
Adds Settings › Agents › Memory and a Session Memory picker (/memory, /memories, the composer + menu and the context meter link). They list each agent's own instruction files, path-scoped rules and auto-memory notes: AGENTS.md, CLAUDE.md and .claude/rules, .github/copilot-instructions.md and .github/instructions, .cursor/rules, GEMINI.md, and the Claude Code, Codex and Hermes auto-memory folders.

Per-file modes (Auto / Always / Off) and the auto-memory policy (Inherit / Read & Write / Read Only / Off) are stored in settings.toml at user or workspace scope and never edit tracked files. Workspace entries load only in trusted projects. Each driver receives the policy natively: Claude Code through --settings and --add-dir, Codex through its memories config and /memories, GitHub Copilot through excludedTools and the system message, and Hermes through config.yaml. A file set to Always is staged into other agents' sessions. Auto-memory notes can be promoted into the workspace AGENTS.md, and an idle session restarts when a memory policy changes.

Groups of the same agent are titled by scope, for example Claude Code (User) and Claude Code (Auto Memory).

Closes #6810

Co-authored-by: dengliu <[email protected]>
2026-11-29 22:38:20 +08:00
Muuтаmuutot c8efb2917d feat(bookmarks): select and rename lists in the popup (#6849)
List headers in the Bookmarks popup are now selectable rows; F2 on one opens the list name dialog, while file section rows stay non-selectable and are skipped by the keyboard. The popup claims F2 while its list is focused so the global Rename File shortcut does not take it.

Co-authored-by: muutot <[email protected]>
2026-11-29 22:28:40 +08:00
Vladislav Kuzmin 94ddb1807d fix(ci): cache Maven launch classpath artifacts (#6565)
The Rust job's Maven cache only held what resources:resources and compiler:compile resolve,
so the Java launch and rebuild tests on GitHub-hosted runners missed artifacts (#6561).
The preparation step now also runs clean and fetches slf4j-api 1.7.36 with
maven-dependency-plugin 3.8.1 (both pinned, from Maven Central), and the cache key gets a
v2 prefix so the incomplete caches are not restored.

Co-authored-by: principalwater <[email protected]>
2026-11-29 22:15:32 +08:00
l0ng-ai 27447d21a7 ci: keep the Windows Rust cache warm and allow a cold build 75 minutes (#6850)
A Windows run on main that ended in a test failure skipped the Rust cache save, so the next PR
compiled every dependency again (about 19 minutes of Clippy plus 30 of test binaries) and ran out
of the 60-minute limit partway through the tests.

- rust-cache in the Rust job saves on failure too; still only on main, PRs and forks restore.
- The Windows Rust job gets 75 minutes; macOS and Linux stay at 60.

Refs #6496
2026-11-29 22:07:17 +08:00
l0ng-ai 3edbcc0dcd ci(smoke): run the TypeScript project-errors and import-style smokes (#6851)
The TypeScript job in Language smoke now also runs typescript_project_errors (Problems ›
TypeScript Project Errors against the global tsc the job installs) and typescript_import_style
(the import style settings through real vtsls). Both smokes came with #6097 and #6342 but were
not run in CI yet.
2026-11-29 22:06:27 +08:00
Akbar Husain 782a0a98e3 feat(mcp): add debugger tools (#6579)
The built-in MCP server gets xdebug_* tools: debugger status, start a session for a run configuration or run point, control it (resume, pause, step, wait for pause, stop), list/set/remove breakpoints, run to line, threads, stack, frame values, values by path, evaluate and set variable. Breakpoints go through the window's editor model, so they show in the gutter, persist and are the list the user sees; sessions start through the IDE's Debug action with its before-launch tasks. Mutating tools are marked write for the trust gate.

Co-authored-by: akbar1214 <[email protected]>
2026-11-29 21:59:42 +08:00
arookieofcтаarookieofc bd0455bda5 fix(vcs): stop retrying stale git worktrees (#6794)
A failed reopen of a repository never updated the cache stamp, so every gix() call reopened it again and logged a warning, and status fell back to running git in a worktree folder that no longer existed (os error 267 on Windows). The stamp is now updated on failure too, and a repository whose worktree or git directory is missing is skipped by status, ignored-files and path status, logged once, and picked up again when both directories are back.

Fixes #5514

Co-authored-by: arookieofc <[email protected]>
2026-11-29 21:56:58 +08:00
l0ng-ai 13cd8ba006 fix(updates): flush the received bytes before a broken download returns (#6407)
append_body returned on a body error before flushing the tokio File, whose writes run on a
background thread, so a resume could measure the partial file shorter than the bytes already
received (the Linux CI flake in a_broken_download_resumes_with_range). The error is now held
until the file is flushed; the success path and signature checks are unchanged.
2026-11-29 21:53:33 +08:00
Muuтаmuutot 9b413fde11 feat(search): share text match options with Search Everywhere (#6843)
Search Everywhere's Text tab gets Match Case, Words and Regex toggles (Alt+C / Alt+W / Alt+X). They use Find in Files' option store, so both entry points send the same search flags, and the choices are persisted across restarts.

Co-authored-by: muutot <[email protected]>
2026-11-29 21:42:37 +08:00
Muuтаmuutot 29e5571186 fix(editor): extend Select Line through the next line on each call (#6839)
Select Line at Caret dropped the line where a selection ended at column 0 and kept a backward selection's direction, so invoking it again selected the same lines. It now covers every line the selection touches, including the one it ends at the start of, and leaves the caret at the selection end, so repeated calls extend line by line. Folded lines and multiple carets work as before.

Co-authored-by: muutot <[email protected]>
2026-11-29 21:37:01 +08:00
audichuang 08eb9e3ff9 fix(editor): don't save stale text over a file replaced by binary content (#6840)
reload_from_disk treated a file that now loads as binary like a document opened as binary: it refreshed the disk stamp without a disk-change report, so autosave wrote the next edit over the binary file. A detected-encoding buffer now gets the disk conflict too. Reopening a file whose closed tab kept unsaved changes shows that buffer as text instead of a binary viewer that hid what Save would write. A clean buffer gets its own disk-change wording.

Co-authored-by: audichuang <[email protected]>
2026-11-29 21:34:53 +08:00
LU XIANGRUIтаwildcatDownstairs 3d6ad2e254 feat(run): show xcodebuild errors and warnings in Problems (#6848)
Xcode run and test configurations now publish the compiler and linker messages in their xcodebuild output to Problems and the editor as they arrive. A Format::Xcode on top of the GCC/Clang line parser folds in notes, project-level lines and Undefined symbols blocks; XcodebuildMessages resolves positions, maps symlinked paths back to the project, reports each message once across architectures and stops at the build result. A new run clears the files its previous run reported; messages without a location go on the project file.

Closes #6842

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-29 21:32:42 +08:00
LU XIANGRUIтаwildcatDownstairs 55b23c90b8 feat(lsp): open documents a language server asks to show (#6846)
Advertise window/showDocument support. An existing file: URI becomes an LspShowDocument event that the frontend opens through openCodeLocation with the requested selection and focus; external http/https/mailto links open in the browser. Anything else answers success: false. This makes sourcekit-lsp's Expand Macro and Inline Macro code actions work.

Closes #6845

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-29 21:27:53 +08:00
l0ng-ai 3fb58cf69b feat(lsp): stop a language server from the status bar popup (#6847)
Running, busy and starting servers get a Stop button next to Restart in the language server popup. LspManager::stop shuts the instance down and leaves it idle, so it starts again when a file it serves is opened; a notification says it will restart when needed. Adds the lsp_stop command.

Fixes #6835
2026-11-29 21:20:31 +08:00
l0ng-ai 3b6ee66b74 fix(debugger): keep the inlay Run to Cursor button while the pointer moves to it (#6841)
The button sits left of the line's first non-space character, over the indent or the gutter, but the hover area started at the text and ended four characters in: moving the pointer to the button left the area and hid it before it could be clicked. The area now includes the gutter, and while the button is shown it reaches the button's right edge on that line.

Fixes #6832
2026-11-29 20:37:05 +08:00
l0ng-ai 243b9ffa7a fix(editor): let other X11 apps keep the primary selection while the window is inactive (#6838)
Another application taking the primary selection makes WebKitGTK clear the page's selection. An editor in an inactive window is still the active element, so CodeMirror wrote its selection back and claimed the primary selection again: terminals and other X11 apps could not keep a selection while an OpenIDEA editor had one. On Linux the editor now accepts the cleared selection while its window is inactive, keeping its carets.

Fixes #6309
2026-11-29 20:03:46 +08:00
LU XIANGRUIтаwildcatDownstairs 86fabc7d1b feat(project-structure): add Project Structure and Open Module Settings entry points (#6834)
Adds Project Structure… to the title bar gear menu (before Settings) and Open Module Settings to the Project view context menu (below Compare With, above Mark Directory as). Open Module Settings is offered on the project folder, Maven / Gradle / Project Structure module folders and sources / resources roots; it opens Project Structure › Modules with the innermost module holding the path selected, and F4 / Cmd+Down on a module folder opens it too. The action uses a new project-structure icon.

Artifacts in Project Structure are now editable when the project has no build tool, since the IDE builds and deploys them itself; with Maven or Gradle the page stays read-only with a note. The Tomcat run configuration's "No artifacts configured" Fix opens Project Structure › Artifacts and the deployment list refreshes when artifacts change.

Refs #404

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-29 19:15:50 +08:00
l0ng-ai ae3405486f fix(debugger): skip Windows Store Python aliases when starting debugpy (#6831)
The built-in python.toml starts debugpy's adapter with a bare python3. On Windows that name (and often python) resolves to an App Execution Alias in %LOCALAPPDATA%\Microsoft\WindowsApps, which fails to start unless the Store's Python is installed, so a Python Debug Server reported failed to start ...\WindowsApps\python3.exe even with Python installed and on PATH.

The adapter now takes every match on PATH of the command, then python, then the py launcher, and uses the first that is no alias or one that runs, as the IDE already does when it installs Python tools.

Fixes #6818
2026-11-29 19:03:50 +08:00
271 змінених файлів з 11096 додано та 434 видалено

No files matched your search

+9
Переглянути файл
@@ -0,0 +1,9 @@
# 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: ["*"] }
+1 -1
Переглянути файл
@@ -12,7 +12,7 @@ jobs:
cancel:
runs-on: ubuntu-latest
steps:
- uses: actions/github-script@v8
- uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
with:
script: |
// A merged or closed PR's remaining CI only holds runners other PRs wait for.
+42 -34
Переглянути файл
@@ -106,7 +106,8 @@ jobs:
if: needs.changes.outputs.rust == 'true'
permissions:
contents: read
timeout-minutes: 60
# A Windows build that misses the Rust cache spends ~50 minutes compiling before the tests run.
timeout-minutes: ${{ matrix.os == 'windows-latest' && 75 || 60 }}
strategy:
fail-fast: false
matrix:
@@ -115,22 +116,24 @@ 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@v5
- uses: pnpm/action-setup@v5
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
- uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0
with: { version: 11 }
- uses: actions/setup-node@v5
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
with:
node-version: 22
cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }}
package-manager-cache: ${{ runner.environment != 'self-hosted' }}
- uses: dtolnay/rust-toolchain@stable
- uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # 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).
- uses: Swatinem/rust-cache@v2
# 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
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'
@@ -142,7 +145,8 @@ jobs:
echo "$CARGO_TARGET_DIR is ${size} MB; clearing it"
rm -rf "$CARGO_TARGET_DIR"
fi
- uses: taiki-e/install-action@nextest
- uses: taiki-e/install-action@073e1fd0bc889c9aee68dbaaa927cde1b5653a83 # v2.90.11
with: { tool: nextest }
- name: Linux deps
if: runner.os == 'Linux'
run: |
@@ -159,10 +163,10 @@ jobs:
- name: Restore Maven artifacts for Java build tests
id: jbuild-maven-cache
if: runner.environment == 'github-hosted'
uses: actions/cache/restore@v5
uses: actions/cache/restore@caa296126883cff596d87d8935842f9db880ef25 # v5.1.0
with:
path: ${{ runner.temp }}/jbuild-maven-repository
key: jbuild-maven-${{ runner.os }}-${{ hashFiles('crates/ide-build/tests/fixtures/jbuild-maven/**/pom.xml') }}
key: jbuild-maven-v2-${{ 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'
@@ -179,10 +183,13 @@ jobs:
if [[ "$CACHE_HIT" == true ]]; then
exit 0
fi
# The IDE also reads the compiler plugin descriptor when it builds the Maven model.
# The Java tests read the compiler descriptor and run Maven launch and rebuild.
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 resources:resources compiler:compile; then
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
echo "prepared=true" >> "$GITHUB_OUTPUT"
exit 0
fi
@@ -190,7 +197,7 @@ jobs:
exit 1
- name: Save Maven artifacts for Java build tests
if: steps.jbuild-maven.outputs.prepared == 'true'
uses: actions/cache/save@v5
uses: actions/cache/save@caa296126883cff596d87d8935842f9db880ef25 # v5.1.0
with:
path: ${{ runner.temp }}/jbuild-maven-repository
key: ${{ steps.jbuild-maven-cache.outputs.cache-primary-key }}
@@ -235,10 +242,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@v5
- uses: dtolnay/rust-toolchain@stable
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
- uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable
with: { targets: x86_64-unknown-linux-musl }
- uses: Swatinem/rust-cache@v2
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
if: runner.environment != 'self-hosted'
with: { key: server-musl }
- name: Persistent Cargo target dir
@@ -264,13 +271,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@v5
- uses: dtolnay/rust-toolchain@stable
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
- uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable
with: { targets: wasm32-wasip2, components: "clippy, rustfmt" }
- if: runner.environment != 'self-hosted'
shell: bash
run: echo "CARGO_TARGET_DIR=$GITHUB_WORKSPACE/target-plugins" >> "$GITHUB_ENV"
- uses: Swatinem/rust-cache@v2
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
if: runner.environment != 'self-hosted'
with:
key: plugins
@@ -300,9 +307,9 @@ jobs:
cargo test --locked --manifest-path "$dir/Cargo.toml"
echo "::endgroup::"
done
- uses: pnpm/action-setup@v5
- uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0
with: { version: 11 }
- uses: actions/setup-node@v5
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
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
@@ -329,9 +336,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@v5
- uses: dtolnay/rust-toolchain@stable
- uses: taiki-e/install-action@cargo-deny
- 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 }
- run: cargo deny check
frontend:
@@ -341,13 +349,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@v5
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
# scripts/smoke-paths.test.ts runs `cargo metadata`, which is not preinstalled in the runner container.
- uses: dtolnay/rust-toolchain@stable
- uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable
if: runner.environment == 'self-hosted'
- uses: pnpm/action-setup@v5
- uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0
with: { version: 11 }
- uses: actions/setup-node@v5
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
with:
node-version: 22
cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }}
@@ -368,10 +376,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@v5
- uses: pnpm/action-setup@v5
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
- uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0
with: { version: 11 }
- uses: actions/setup-node@v5
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
with:
node-version: 22
cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }}
@@ -390,10 +398,10 @@ jobs:
matrix:
shard: [1, 2, 3, 4]
steps:
- uses: actions/checkout@v5
- uses: pnpm/action-setup@v5
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
- uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0
with: { version: 11 }
- uses: actions/setup-node@v5
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
with:
node-version: 22
cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }}
@@ -401,7 +409,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@v6
- uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
if: failure()
with:
name: playwright-report-${{ matrix.shard }}
+2 -2
Переглянути файл
@@ -35,10 +35,10 @@ jobs:
echo "::notice::CNB_TOKEN unset: not mirroring $TAG"
echo "skip=true" >> "$GITHUB_OUTPUT"
fi
- uses: actions/checkout@v5
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
if: steps.token.outputs.skip != 'true'
with: { sparse-checkout: scripts }
- uses: actions/setup-node@v5
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
if: steps.token.outputs.skip != 'true'
with: { node-version: 22 }
- name: Download release
+3 -3
Переглянути файл
@@ -41,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@v5
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
if: steps.check.outputs.skip != 'true'
with: { sparse-checkout: scripts }
- uses: actions/checkout@v5
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
if: steps.check.outputs.skip != 'true'
with:
repository: ${{ env.TAP }}
ssh-key: ${{ secrets.HOMEBREW_TAP_DEPLOY_KEY }}
path: tap
- uses: actions/setup-node@v5
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
if: steps.check.outputs.skip != 'true'
with: { node-version: 22 }
- name: Download DMGs
+18 -14
Переглянути файл
@@ -154,9 +154,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@v5
- uses: dtolnay/rust-toolchain@stable
- uses: Swatinem/rust-cache@v2
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
- uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
if: runner.environment != 'self-hosted'
with:
shared-key: language-smoke
@@ -183,7 +183,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@v6
- uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
with: { name: smoke-bin, path: smoke-bin.tar, retention-days: 1 }
smoke:
@@ -202,20 +202,20 @@ jobs:
env:
CARGO_MANIFEST_DIR: ${{ github.workspace }}/crates/ide-host
steps:
- uses: actions/checkout@v5
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
# Tool versions, shared with the evals (pnpm eval).
- run: grep -E '^[A-Z0-9_]+=' .github/tool-versions.env >> "$GITHUB_ENV"
- uses: dtolnay/rust-toolchain@stable
- uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable
with: { components: "rust-analyzer, rustfmt" }
- uses: actions/download-artifact@v6
- uses: actions/download-artifact@018cc2cf5baa6db3ef3c5f8a56943fffe632ef53 # v6.0.0
with: { name: smoke-bin }
- run: |
tar -xf smoke-bin.tar && rm smoke-bin.tar
mkdir -p target/debug && mv smoke-bin/openidea-server target/debug/
- uses: pnpm/action-setup@v5
- uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0
with: { version: 11 }
- uses: actions/setup-node@v5
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
with:
node-version: 22
cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }}
@@ -241,19 +241,19 @@ jobs:
fi
- if: matrix.language == 'python'
uses: actions/setup-python@v5
uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0
with: { python-version: "3.12" }
- if: matrix.language == 'python'
run: pip install "basedpyright==$BASEDPYRIGHT" "ruff==$RUFF"
- if: matrix.language == 'go'
uses: actions/setup-go@v5
uses: actions/setup-go@40f1582b2485089dde7abd97c1529aa768e1baff # v5.6.0
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@v4
uses: actions/setup-java@cf277c60eb25467037889841efdb72551f06f6c3 # v4.9.1
with: { distribution: temurin, java-version: "${{ env.JAVA }}" }
- if: matrix.language == 'java'
run: |
@@ -265,7 +265,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@v4
uses: gradle/actions/setup-gradle@ed408507eac070d1f99cc633dbcf757c94c7933a # v4.4.3
with: { gradle-version: "${{ env.GRADLE }}" }
- if: matrix.language == 'kotlin'
run: |
@@ -277,7 +277,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@v2
uses: shivammathur/setup-php@eb7c497e18156a6bbabfef1d3a82760b9eda3962 # 2.40.0
with: { php-version: "8.5", coverage: xdebug, tools: composer }
- if: matrix.language == 'php'
run: npm install --global "intelephense@$INTELEPHENSE"
@@ -285,6 +285,10 @@ 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 -1
Переглянути файл
@@ -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@v8
- uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
with:
script: |
const pr = context.payload.pull_request;
+43 -24
Переглянути файл
@@ -69,15 +69,15 @@ jobs:
target: x86_64-pc-windows-msvc
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v5
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
with: { ref: "${{ env.TAG }}" }
- uses: pnpm/action-setup@v5
- uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0
with: { version: 11 }
- uses: actions/setup-node@v5
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
with: { node-version: 22, cache: pnpm }
- uses: dtolnay/rust-toolchain@stable
- uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable
with: { targets: "${{ matrix.target }}" }
- uses: Swatinem/rust-cache@v2
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
with: { key: "${{ matrix.target }}", cache-on-failure: true }
- name: Linux deps
if: runner.os == 'Linux'
@@ -85,40 +85,57 @@ 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: only secrets that are set get exported, so forks and
# unconfigured repos produce unsigned builds instead of failing.
- name: Signing env
# 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
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 || '' }}
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
- name: Build (unsigned)
if: steps.signing.outputs.updater != 'true'
uses: tauri-apps/tauri-action@84b9d35b5fc46c1e45415bdb6144030364f7ebc5 # v0.6.2
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
releaseId: ${{ inputs.release_id }}
tagName: ${{ env.TAG }}
args: --target ${{ matrix.target }}
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' && env.APPLE_ID != ''
if: runner.os == 'macOS' && steps.signing.outputs.apple == 'true'
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" \
@@ -137,6 +154,8 @@ 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" }
@@ -176,11 +195,11 @@ jobs:
- { runner: macos-latest, target: x86_64-apple-darwin, os: macos, arch: x86_64 }
runs-on: ${{ matrix.runner }}
steps:
- uses: actions/checkout@v5
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
with: { ref: "${{ env.TAG }}" }
- uses: dtolnay/rust-toolchain@stable
- uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable
with: { targets: "${{ matrix.target }}" }
- uses: Swatinem/rust-cache@v2
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
with: { key: "server-${{ matrix.target }}", cache-on-failure: true }
- name: musl toolchain
if: runner.os == 'Linux'
@@ -209,7 +228,7 @@ jobs:
needs: build
runs-on: ubuntu-latest
steps:
- uses: actions/github-script@v8
- uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
env:
RELEASE_ID: ${{ inputs.release_id }}
with:
+8 -8
Переглянути файл
@@ -29,7 +29,7 @@ jobs:
outputs:
release_id: ${{ steps.release.outputs.id }}
steps:
- uses: actions/checkout@v5
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
with: { ref: "${{ env.TAG }}" }
- name: Tag matches app version
run: |
@@ -49,7 +49,7 @@ jobs:
exit 1
fi
- id: release
uses: actions/github-script@v8
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
with:
script: |
const tag = process.env.TAG;
@@ -106,19 +106,19 @@ jobs:
echo "::warning::PLUGIN_SIGNING_KEY is not set: the official plugins are not published"
echo "skip=true" >> "$GITHUB_OUTPUT"
fi
- uses: actions/checkout@v5
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
if: steps.key.outputs.skip != 'true'
with: { ref: "${{ env.TAG }}" }
- uses: dtolnay/rust-toolchain@stable
- uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable
if: steps.key.outputs.skip != 'true'
with: { targets: wasm32-wasip2 }
- uses: Swatinem/rust-cache@v2
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
if: steps.key.outputs.skip != 'true'
with: { key: release-plugins }
- uses: pnpm/action-setup@v5
- uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0
if: steps.key.outputs.skip != 'true'
with: { version: 11 }
- uses: actions/setup-node@v5
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
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.
@@ -163,7 +163,7 @@ jobs:
needs: [create-release, binaries, plugins]
runs-on: ubuntu-latest
steps:
- uses: actions/github-script@v8
- uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
env:
RELEASE_ID: ${{ needs.create-release.outputs.release_id }}
with:
+130 -4
Переглянути файл
@@ -18,6 +18,7 @@ mod external;
pub mod hermes;
mod images;
pub mod mcp;
pub mod memory;
mod model;
mod native;
mod provider;
@@ -239,6 +240,9 @@ impl Default for SkillsPolicy {
/// Returns the skill policies for this project.
pub type SkillsPolicyFn = dyn Fn() -> SkillsPolicy + Send + Sync;
/// Returns the memory policies for this project.
pub type MemoryPolicyFn = dyn Fn() -> memory::MemoryPolicy + Send + Sync;
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
struct CopilotBinaryKey {
command: String,
@@ -277,6 +281,7 @@ struct Shared {
mcp_servers_hook: RwLock<Option<Arc<McpServersFn>>>,
mcp_executable_hook: RwLock<Option<Arc<McpExecutableFn>>>,
skills_policy_hook: RwLock<Option<Arc<SkillsPolicyFn>>>,
memory_policy_hook: RwLock<Option<Arc<MemoryPolicyFn>>>,
/// Monotonic id for [`AgentEvent::Attention`] episodes.
attention_seq: AtomicU64,
/// Bumped on every [`AgentManager::shutdown`]: in-flight turns, session opens,
@@ -943,6 +948,8 @@ struct Task {
mcp_reload_pending: AtomicBool,
/// Turned on when per-session skill overrides changed while a turn was busy; dropped once idle.
skills_reload_pending: AtomicBool,
/// Turned on when per-session memory overrides changed while a turn was busy; dropped once idle.
memory_reload_pending: AtomicBool,
/// Settings already sent this session (`(option, value)`), so a refusal is not retried.
config_sent: Mutex<HashSet<(String, String)>>,
dirty: Mutex<BTreeSet<(Session, usize)>>,
@@ -1025,6 +1032,7 @@ impl AgentManager {
mcp_servers_hook: RwLock::new(None),
mcp_executable_hook: RwLock::new(None),
skills_policy_hook: RwLock::new(None),
memory_policy_hook: RwLock::new(None),
attention_seq: AtomicU64::new(0),
shutdown_epoch: AtomicU64::new(0),
});
@@ -1270,6 +1278,11 @@ impl AgentManager {
*self.shared.skills_policy_hook.write() = Some(Arc::from(hook));
}
/// Provides the user and workspace memory policies and the workspace's trust.
pub fn set_memory_policy_hook(&self, hook: Box<MemoryPolicyFn>) {
*self.shared.memory_policy_hook.write() = Some(Arc::from(hook));
}
/// The slash commands to complete for `provider`, in `task`'s directory or (without one)
/// in the project: what the agent offered last time there, unadvertised builtins,
/// for Claude Code the skills and custom commands on disk it has not listed (for
@@ -1450,6 +1463,7 @@ impl AgentManager {
background: Box::default(),
mcp_overrides: BTreeMap::new(),
skill_overrides: BTreeMap::new(),
memory_overrides: None,
stats: Box::default(),
interrupted: None,
unread: false,
@@ -1539,6 +1553,7 @@ impl AgentManager {
background: Box::default(),
mcp_overrides: BTreeMap::new(),
skill_overrides: BTreeMap::new(),
memory_overrides: None,
stats: Box::default(),
interrupted: None,
unread: false,
@@ -1686,6 +1701,7 @@ impl AgentManager {
background: Box::default(),
mcp_overrides: req.mcp_overrides,
skill_overrides: req.skill_overrides,
memory_overrides: req.memory_overrides.filter(|m| !m.is_empty()).map(Box::new),
stats: Box::default(),
interrupted: None,
unread: false,
@@ -2032,13 +2048,20 @@ impl AgentManager {
let mcp_servers = source.shared.mcp_servers_for_session(&provider_id, &live.init, &mcp_overrides);
let roots = source.shared.additional_directories(&live.init, &cwd, project_root.as_deref());
let skills_delivery = source.stage_skills(stage_key(live.driver), &cwd).await;
let memory_delivery = source.stage_memory(&provider_id, &cwd).await;
let cwd_s = dunce::canonicalize(&cwd).unwrap_or(cwd).to_string_lossy().into_owned();
let reply: Value = live
.peer
.request(
"session/fork",
{
let mut params = session_params(&cwd_s, &mcp_servers, skills_delivery.as_ref(), &roots);
let mut params = session_params(
&cwd_s,
&mcp_servers,
skills_delivery.as_ref(),
memory_delivery.as_ref(),
&roots,
);
params["sessionId"] = json!(live.session);
params
},
@@ -2765,6 +2788,7 @@ impl AgentManager {
let _ = std::fs::remove_file(self.shared.paths.store_dir.join(format!("{id}.json")));
let _ = std::fs::remove_dir_all(task.turn_dir());
skills::remove_farm(&self.shared.paths.store_dir, id);
memory::remove_farm(&self.shared.paths.store_dir, id);
let saved = task.state.lock().saved.clone();
if let Some(saved) = saved
&& !self.tasks.read().values().any(|t| t.state.lock().saved.as_ref() == Some(&saved))
@@ -3150,6 +3174,42 @@ impl AgentManager {
Ok(out)
}
/// Sets the session's memory overrides (auto-memory mode and per-entry modes); like MCP
/// and skill overrides, an idle resumable session recycles so the next turn starts with
/// the updated delivery.
pub fn set_memory_overrides(&self, id: &str, overrides: AgentMemoryOverrides) -> IdeResult<AgentTask> {
let task = self.task(id)?;
let cleaned_entries: BTreeMap<String, AgentMemoryMode> = overrides
.entries
.into_iter()
.filter_map(|(k, v)| (!k.trim().is_empty()).then(|| (k.trim().to_owned(), v)))
.collect();
let cleaned = AgentMemoryOverrides { auto_memory: overrides.auto_memory, entries: cleaned_entries };
let next_boxed = (!cleaned.is_empty()).then(|| Box::new(cleaned));
let (changed, busy, has_bg, out) = {
let mut s = task.state.lock();
if s.task.status == AgentStatus::Archived {
return Err(IdeError::invalid("the task is archived"));
}
let changed = s.task.memory_overrides != next_boxed;
if changed {
s.task.memory_overrides = next_boxed;
s.task.updated_ms = now_ms();
}
(changed, s.busy, !s.background_tasks.is_empty(), s.task.clone())
};
if changed {
task.persist();
task.emit_task();
if busy || has_bg || !task.permissions.lock().is_empty() {
task.memory_reload_pending.store(true, Ordering::Release);
} else {
task.recycle_resumable_session();
}
}
Ok(out)
}
/// Recycles idle resumable live sessions (or schedules reload after the running turn) when
/// global, workspace, or built-in IDE MCP server settings change.
pub fn notify_mcp_servers_changed(&self) {
@@ -3254,6 +3314,44 @@ impl Task {
}
}
/// Resolves and stages the session's memory delivery (`_meta.openidea.memory`).
async fn stage_memory(&self, provider: &str, cwd: &Path) -> Option<memory::Delivery> {
let (policy, overrides, home, roots) = {
let shared = &self.shared;
let mut policy = shared.memory_policy_hook.read().as_ref().map(|hook| hook()).unwrap_or_default();
let (overrides, task_root) = {
let s = self.state.lock();
(s.task.memory_overrides.as_deref().cloned(), s.task.project_root.as_ref().map(|p| p.0.clone()))
};
let mut roots = Vec::new();
if let Some(tr) = task_root {
roots.push(tr);
}
roots.extend(policy.workspace_roots.iter().cloned());
roots.push(shared.paths.project_root.clone());
policy.workspace_roots = roots.clone();
(policy, overrides, shared.paths.home_dir.clone(), roots)
};
let farm = memory::farm_dir(&self.shared.paths.store_dir, &self.id);
let out_cwd = cwd.to_path_buf();
let provider = provider.to_owned();
match blocking(move || {
let entries = memory::discover_memories(&roots, home.as_deref());
let states = memory::resolve_entries(entries, overrides.as_ref(), &policy);
let (auto_mode, _) = memory::resolve_provider_auto_memory(&provider, overrides.as_ref(), &policy);
memory::stage(&farm, &provider, &states, auto_mode, &out_cwd, home.as_deref())
.map_err(|e| IdeError::internal(e.to_string()))
})
.await
{
Ok(delivery) => Some(delivery),
Err(e) => {
tracing::warn!("agent task {}: staging its memory failed: {e}", self.id);
None
}
}
}
/// A task whose conversation is at hand (a new task, a copy).
fn restore(mut file: TaskFile, shared: Arc<Shared>) -> Arc<Self> {
let adopt = file.entries.is_empty() && file.session_id.is_some();
@@ -3345,6 +3443,7 @@ impl Task {
idle_epoch: AtomicU64::new(0),
mcp_reload_pending: AtomicBool::new(false),
skills_reload_pending: AtomicBool::new(false),
memory_reload_pending: AtomicBool::new(false),
config_sent: Mutex::new(HashSet::new()),
dirty: Mutex::new(BTreeSet::new()),
streamed: Mutex::new(Streamed::default()),
@@ -3980,7 +4079,8 @@ impl Task {
self.emit_attention(AgentAttentionReason::Finished);
}
if (self.mcp_reload_pending.swap(false, Ordering::AcqRel)
|| self.skills_reload_pending.swap(false, Ordering::AcqRel))
|| self.skills_reload_pending.swap(false, Ordering::AcqRel)
|| self.memory_reload_pending.swap(false, Ordering::AcqRel))
&& self.state.lock().background_tasks.is_empty()
{
self.recycle_resumable_session();
@@ -4669,12 +4769,25 @@ impl Task {
if self.shared.shut_down_since(epoch) {
return Err(SessionOpenError { message: "The agent manager shut down.".into(), allow_acp_fallback: false });
}
let memory_delivery = self.stage_memory(provider_id, cwd).await;
if spec.driver == provider::Driver::Acp && provider::is_copilot_provider(provider_id) {
let mcp_overrides = self.state.lock().task.mcp_overrides.clone();
for name in self.shared.mcp_servers_off_for_session(provider_id, &mcp_overrides) {
spec.args.push("--disable-mcp-server".into());
spec.args.push(name);
}
if let Some(mem) = memory_delivery.as_ref() {
if mem.copilot_enable_memory == Some(true) {
spec.args.push("--enable-memory".into());
}
if mem.copilot_exclude_store_memory {
spec.args.push("--excluded-tools".into());
spec.args.push("store_memory".into());
}
if mem.copilot_disable_custom_instructions {
spec.args.push("--no-custom-instructions".into());
}
}
}
self.stderr.lock().clear();
self.config_sent.lock().clear();
@@ -4730,7 +4843,8 @@ impl Task {
let cwd_s = dunce::canonicalize(cwd).unwrap_or_else(|_| cwd.to_path_buf()).to_string_lossy().into_owned();
let pending_native_fork = self.state.lock().pending_native_fork.clone();
let mut opening_params = session_params(&cwd_s, &mcp_servers, skills_delivery.as_ref(), &roots);
let mut opening_params =
session_params(&cwd_s, &mcp_servers, skills_delivery.as_ref(), memory_delivery.as_ref(), &roots);
if spec.driver == provider::Driver::Codex {
let s = self.state.lock();
let mut wanted = s.wanted.clone();
@@ -6132,7 +6246,13 @@ fn stage_key(driver: provider::Driver) -> &'static str {
/// servers, and the ones off for this session, so an agent that also loads its own
/// configuration (Claude Code) can keep a same-named server of it off too — plus the
/// session's staged skills for the drivers that take them, and the workspace's other roots.
fn session_params(cwd: &str, mcp: &McpForSession, skills: Option<&skills::Delivery>, roots: &[String]) -> Value {
fn session_params(
cwd: &str,
mcp: &McpForSession,
skills: Option<&skills::Delivery>,
memory: Option<&memory::Delivery>,
roots: &[String],
) -> Value {
let mut params = json!({ "cwd": cwd, "mcpServers": mcp.servers });
if !roots.is_empty() {
params["additionalDirectories"] = json!(roots);
@@ -6146,6 +6266,12 @@ fn session_params(cwd: &str, mcp: &McpForSession, skills: Option<&skills::Delive
{
meta["skills"] = v;
}
if let Some(memory) = memory
&& let Ok(v) = serde_json::to_value(memory)
&& v.as_object().is_some_and(|m| !m.is_empty())
{
meta["memory"] = v;
}
if !meta.is_null() && meta.as_object().is_some_and(|m| !m.is_empty()) {
params["_meta"] = json!({ "openidea": meta });
}
File diff suppressed because it is too large. Load diff
+226 -2
Переглянути файл
@@ -181,6 +181,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)]
@@ -834,6 +838,10 @@ 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)]
@@ -975,7 +983,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, Serialize, Deserialize, Type)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum McpScope {
User,
@@ -1042,7 +1050,223 @@ fn default_true() -> bool {
true
}
pub use ide_core::settings::{AgentSkillMode, AgentSkillPolicy};
pub use ide_core::settings::{
AgentMemoryEntryPolicy, AgentMemoryMode, AgentMemorySettings, 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>,
}
/// 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,
}
/// 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)]
+62 -6
Переглянути файл
@@ -174,10 +174,14 @@ 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>,
/// The staged skills' `--settings` JSON (`skillOverrides` for the native ones too).
skills_settings: Option<String>,
/// Combined `--settings` JSON (`skillOverrides`, `autoMemoryEnabled`, `claudeMdExcludes`, `instructionFiles`).
cli_settings: Option<String>,
/// `_meta.openidea.ephemeral`: `--no-session-persistence`, nothing saved under `~/.claude`.
ephemeral: bool,
shim: Weak<Shim>,
@@ -371,13 +375,20 @@ 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),
skills_settings: skills.and_then(|s| s.get("claudeSettings")).and_then(Value::as_str).map(str::to_owned),
cli_settings,
ephemeral: params.pointer("/_meta/openidea/ephemeral").and_then(Value::as_bool).unwrap_or(false),
shim: Arc::downgrade(self),
st: Mutex::new(State {
@@ -728,18 +739,28 @@ 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.skills_settings {
if let Some(settings) = &self.cli_settings {
args.extend(["--settings".to_owned(), settings.clone()]);
}
if self.ephemeral {
args.push("--no-session-persistence".to_owned());
}
args.extend(start.args());
let launch =
Launch { program: shim.config.program.clone(), args, cwd: self.cwd.clone(), env: shim.config.env.clone() };
let mut env = shim.config.env.clone();
if self.additional_dirs_claude_md
&& !env.iter().any(|(k, _)| k == "CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD")
{
env.push(("CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD".to_owned(), "1".to_owned()));
}
let launch = Launch { program: shim.config.program.clone(), args, cwd: self.cwd.clone(), env };
let io = shim
.cli
.launch(&launch, shim.on_stderr.clone())
@@ -1601,6 +1622,41 @@ 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);
+42
Переглянути файл
@@ -1442,3 +1442,45 @@ 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"
);
}
+14
Переглянути файл
@@ -20,6 +20,17 @@ pub(crate) const BUILTIN_COMMANDS: &[BuiltinCommandSpec] = &[
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.",
@@ -79,6 +90,7 @@ pub(super) enum BuiltinCommand {
Plan,
Mcp,
Skills,
Memories,
Status,
Review,
ReviewBranch,
@@ -95,6 +107,7 @@ impl BuiltinCommand {
"plan" => Self::Plan,
"mcp" => Self::Mcp,
"skills" => Self::Skills,
"memories" => Self::Memories,
"status" => Self::Status,
"review" => Self::Review,
"review-branch" => Self::ReviewBranch,
@@ -150,6 +163,7 @@ mod tests {
"plan",
"mcp",
"skills",
"memories",
"status",
"review",
"review-branch",
+49
Переглянути файл
@@ -362,6 +362,23 @@ 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;
}
@@ -708,6 +725,7 @@ 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") => {
@@ -747,6 +765,36 @@ 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() {
@@ -1518,6 +1566,7 @@ 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(),
+75
Переглянути файл
@@ -1695,6 +1695,57 @@ 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"] {
@@ -2087,6 +2138,8 @@ fn skills_become_commands_with_their_invocation_names() {
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());
@@ -2102,6 +2155,28 @@ 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")]
+34
Переглянути файл
@@ -462,6 +462,38 @@ fn apply_skills(params: &Value, req: &mut Value) {
}
}
/// Applies `_meta.openidea.memory` to Copilot's `session.create` / `session.resume` payload:
/// gates `store_memory` when auto-memory is `ReadOnly` or `Off`, disables custom instructions
/// when all workspace/user instructions are muted, and appends shared OpenIDEA memories.
fn apply_memory(params: &Value, req: &mut Value) {
let Some(mem) = params.pointer("/_meta/openidea/memory") else {
return;
};
if mem.get("copilotExcludeStoreMemory").and_then(Value::as_bool) == Some(true) {
let mut excluded: Vec<String> = req
.get("excludedTools")
.and_then(Value::as_array)
.into_iter()
.flatten()
.filter_map(Value::as_str)
.map(str::to_owned)
.collect();
if !excluded.iter().any(|t| t == "store_memory") {
excluded.push("store_memory".into());
}
req["excludedTools"] = json!(excluded);
}
if mem.get("copilotDisableCustomInstructions").and_then(Value::as_bool) == Some(true) {
req["customInstructions"] = json!(false);
}
if let Some(sys) = mem.get("copilotSystemMessage").and_then(Value::as_str).filter(|s| !s.is_empty()) {
req["systemMessage"] = json!({
"mode": "append",
"content": sys,
});
}
}
fn invalid(message: impl Into<String>) -> ResponseError {
error(codes::INVALID_PARAMS, message)
}
@@ -588,6 +620,7 @@ impl CopilotShim {
req["disabledMcpServers"] = disabled;
}
apply_skills(params, &mut req);
apply_memory(params, &mut req);
let created = self.call("session.create", req).await?;
let session_id = created
@@ -639,6 +672,7 @@ impl CopilotShim {
req["disabledMcpServers"] = disabled;
}
apply_skills(params, &mut req);
apply_memory(params, &mut req);
let resumed = self.call("session.resume", req).await?;
if let Ok(current) = self.call("session.model.getCurrent", json!({ "sessionId": session_id })).await {
+50
Переглянути файл
@@ -833,6 +833,56 @@ async fn session_new_and_load_forward_staged_skill_directories_and_disabled_skil
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn session_new_and_load_apply_copilot_memory_gating_and_system_message() {
let server =
Arc::new(FakeCopilotServer { peer: OnceLock::new(), calls: Mutex::new(Vec::new()), background_shell: false });
let updates = Arc::new(CollectUpdates(Mutex::new(Vec::new())));
let server_clone = server.clone();
let client = attach(updates, move |events| {
let (a, b) = tokio::io::duplex(1 << 16);
let (ar, aw) = tokio::io::split(a);
let (br, bw) = tokio::io::split(b);
let srv_peer = Peer::connect_framed(br, bw, server_clone.clone(), Framing::ContentLength);
let _ = server_clone.peer.set(srv_peer);
Ok(Peer::connect_framed(ar, aw, events, Framing::ContentLength))
})
.unwrap();
let _: Value = client.request("initialize", json!({}), None).await.unwrap();
let meta = json!({
"openidea": {
"memory": {
"autoMemory": "readOnly",
"copilotExcludeStoreMemory": true,
"copilotDisableCustomInstructions": true,
"copilotSystemMessage": "## Memory (shared)\nRun targeted tests."
}
}
});
let _: Value =
client.request("session/new", json!({ "cwd": "/tmp", "mcpServers": [], "_meta": meta }), None).await.unwrap();
let _: Value = client
.request(
"session/load",
json!({ "sessionId": "cop-sess-1", "cwd": "/tmp", "mcpServers": [], "_meta": meta }),
None,
)
.await
.unwrap();
let calls = server.calls.lock();
for method in ["session.create", "session.resume"] {
let params = calls.iter().find_map(|(m, p)| (m == method).then_some(p)).expect(method);
assert_eq!(params["excludedTools"], json!(["store_memory"]), "{method}: {params}");
assert_eq!(params["customInstructions"], json!(false), "{method}: {params}");
assert_eq!(
params["systemMessage"],
json!({ "mode": "append", "content": "## Memory (shared)\nRun targeted tests." }),
"{method}: {params}"
);
}
}
#[test]
fn translates_context_attribution_without_double_counting_parent_rollups() {
let payload = json!({
+134 -4
Переглянути файл
@@ -69,6 +69,8 @@ struct FakeAgent {
prompts: Mutex<Vec<Value>>,
/// Queued errors returned on the next `session/prompt` calls before succeeding.
prompt_errors: Mutex<VecDeque<(i64, String)>>,
/// Recorded `(method, _meta.openidea.memory)` payloads across `session/new`, `session/load`, and `session/fork`.
memory_calls: Mutex<Vec<(String, Option<Value>)>>,
}
impl FakeAgent {
@@ -179,6 +181,7 @@ impl Handler for FakeAgent {
})
.unwrap_or_default();
self.mcp_calls.lock().push((method.to_owned(), names));
self.memory_calls.lock().push((method.to_owned(), params.pointer("/_meta/openidea/memory").cloned()));
if params.pointer("/_meta/openidea/ephemeral") == Some(&json!(true)) {
self.calls.lock().push("ephemeral".into());
}
@@ -1286,6 +1289,7 @@ async fn commands_are_remembered_per_project_and_merged_with_skills_on_disk() {
"plan",
"mcp",
"skills",
"memories",
"status",
"review",
"review-branch",
@@ -1325,6 +1329,7 @@ async fn builtin_commands_only_fill_verified_gaps_and_preserve_advertised_metada
"plan",
"mcp",
"skills",
"memories",
"status",
"review",
"review-branch",
@@ -5971,6 +5976,7 @@ async fn per_session_mcp_overrides_filter_session_and_reload_when_idle() {
mcp_overrides: BTreeMap::from([("slack".into(), false)]),
idle: false,
skill_overrides: BTreeMap::new(),
memory_overrides: None,
ephemeral: false,
})
.await
@@ -5999,6 +6005,127 @@ async fn per_session_mcp_overrides_filter_session_and_reload_when_idle() {
mgr.shutdown();
}
#[tokio::test(flavor = "multi_thread")]
async fn per_session_memory_overrides_deliver_across_claude_codex_copilot_acp_cursor_and_hermes() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
std::fs::write(root.join("AGENTS.md"), "# Workspace Rules\nRun vitest first.\n").unwrap();
std::fs::write(root.join("CLAUDE.local.md"), "Noisy local draft\n").unwrap();
let agent = Arc::new(FakeAgent::default());
let mgr = manager(root, agent.clone());
mgr.set_memory_policy_hook(Box::new({
let root = root.to_path_buf();
move || memory::MemoryPolicy {
user: AgentMemorySettings { auto_memory: AutoMemoryMode::ReadWrite, ..Default::default() },
workspace: AgentMemorySettings::default(),
workspace_trusted: true,
workspace_roots: vec![root.clone()],
}
}));
// 1. Claude task with initial `ReadOnly` + muted `CLAUDE.local.md`, then updated while idle, forked, and deleted.
let claude_task = mgr
.create(NewAgentTask {
project_root: None,
prompt: text("again"),
provider: "claude".into(),
config: Vec::new(),
isolation: Isolation::Local,
base: None,
mcp_overrides: BTreeMap::new(),
skill_overrides: BTreeMap::new(),
memory_overrides: Some(AgentMemoryOverrides {
auto_memory: Some(AutoMemoryMode::ReadOnly),
entries: BTreeMap::from([("claudeWorkspace::CLAUDE.local.md".into(), AgentMemoryMode::Off)]),
}),
idle: false,
ephemeral: false,
})
.await
.unwrap();
wait_for(&mgr, &claude_task.id, AgentStatus::Ready).await;
{
let (method, payload) = agent.memory_calls.lock().last().cloned().unwrap();
assert_eq!(method, "session/new");
let mem = payload.unwrap();
assert_eq!(mem["autoMemory"], "readOnly");
assert_eq!(mem["claudeAutoMemory"], false);
assert!(
mem["claudeMdExcludes"]
.as_array()
.unwrap()
.iter()
.any(|v| v.as_str().is_some_and(|s| s.ends_with("CLAUDE.local.md")))
);
}
// Updating `set_memory_overrides` while idle recycles the session so the next turn reloads (`session/load`) with `Off`.
let updated = mgr
.set_memory_overrides(
&claude_task.id,
AgentMemoryOverrides { auto_memory: Some(AutoMemoryMode::Off), entries: BTreeMap::new() },
)
.unwrap();
assert_eq!(updated.memory_overrides.as_ref().unwrap().auto_memory, Some(AutoMemoryMode::Off));
mgr.prompt(&claude_task.id, text("again"), false).await.unwrap();
wait_for(&mgr, &claude_task.id, AgentStatus::Ready).await;
{
let (method, payload) = agent.memory_calls.lock().last().cloned().unwrap();
assert_eq!(method, "session/load");
assert_eq!(payload.unwrap()["autoMemory"], "off");
}
// Forking carries `memory_overrides` onto the forked task and sends `_meta.openidea.memory` on `session/fork`.
let forked = mgr.fork(&claude_task.id, None).await.unwrap();
assert_eq!(forked.memory_overrides.as_ref().unwrap().auto_memory, Some(AutoMemoryMode::Off));
{
let (method, payload) = agent.memory_calls.lock().last().cloned().unwrap();
assert_eq!(method, "session/fork");
assert_eq!(payload.unwrap()["autoMemory"], "off");
}
mgr.delete(&claude_task.id, false).await.unwrap();
assert!(!memory::farm_dir(&mgr.shared.paths.store_dir, &claude_task.id).exists());
// 2. Codex, Copilot, Cursor (ACP), and Hermes (ACP) each receive their normalized `_meta.openidea.memory`.
for (provider, expected_field) in [
("codex", Some("codexUseMemories")),
("copilot", Some("copilotEnableMemory")),
("cursor", None),
("hermes", None),
] {
let t = mgr
.create(NewAgentTask {
project_root: None,
prompt: text("again"),
provider: provider.into(),
config: Vec::new(),
isolation: Isolation::Local,
base: None,
mcp_overrides: BTreeMap::new(),
skill_overrides: BTreeMap::new(),
memory_overrides: Some(AgentMemoryOverrides {
auto_memory: Some(AutoMemoryMode::ReadOnly),
entries: BTreeMap::new(),
}),
idle: false,
ephemeral: false,
})
.await
.unwrap();
wait_for(&mgr, &t.id, AgentStatus::Ready).await;
let (method, payload) = agent.memory_calls.lock().last().cloned().unwrap();
assert_eq!(method, "session/new", "provider {provider}");
let mem = payload.expect("memory delivery present");
assert_eq!(mem["autoMemory"], "readOnly", "provider {provider}");
if let Some(field) = expected_field {
assert!(mem.get(field).is_some(), "provider {provider} missing {field}: {mem}");
}
}
mgr.shutdown();
}
#[tokio::test(flavor = "multi_thread")]
async fn per_session_skill_overrides_filter_commands_persist_and_reload_when_idle() {
let tmp = tempfile::tempdir().unwrap();
@@ -6034,6 +6161,7 @@ async fn per_session_skill_overrides_filter_commands_persist_and_reload_when_idl
("tdd".into(), AgentSkillMode::Auto),
("noisy".into(), AgentSkillMode::Off),
]),
memory_overrides: None,
ephemeral: false,
})
.await
@@ -6178,6 +6306,7 @@ async fn copilot_falls_back_to_acp_when_headless_probe_session_or_prompt_fails()
mcp_overrides: BTreeMap::new(),
idle: false,
skill_overrides: BTreeMap::new(),
memory_overrides: None,
ephemeral: false,
})
.await
@@ -6205,6 +6334,7 @@ async fn copilot_falls_back_to_acp_when_headless_probe_session_or_prompt_fails()
mcp_overrides: BTreeMap::new(),
idle: false,
skill_overrides: BTreeMap::new(),
memory_overrides: None,
ephemeral: false,
})
.await
@@ -6284,20 +6414,20 @@ done
#[test]
fn session_params_name_the_servers_off() {
let mcp = McpForSession { servers: vec![json!({ "name": "docs" })], off: vec!["github".into()] };
let params = session_params("/p", &mcp, None, &[]);
let params = session_params("/p", &mcp, None, None, &[]);
assert_eq!(params["cwd"], "/p");
assert_eq!(params["mcpServers"][0]["name"], "docs");
assert_eq!(params["_meta"]["openidea"]["mcpServersOff"], json!(["github"]));
let none = McpForSession { servers: Vec::new(), off: Vec::new() };
assert!(session_params("/p", &none, None, &[]).get("_meta").is_none());
assert!(session_params("/p", &none, None, None, &[]).get("_meta").is_none());
}
#[test]
fn session_params_offer_the_workspace_roots() {
let none = McpForSession { servers: Vec::new(), off: Vec::new() };
let params = session_params("/w/api", &none, None, &["/w/web".to_owned()]);
let params = session_params("/w/api", &none, None, None, &["/w/web".to_owned()]);
assert_eq!(params["additionalDirectories"], json!(["/w/web"]));
assert!(session_params("/w/api", &none, None, &[]).get("additionalDirectories").is_none());
assert!(session_params("/w/api", &none, None, None, &[]).get("additionalDirectories").is_none());
}
#[tokio::test]
+135
Переглянути файл
@@ -815,6 +815,74 @@ 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)
@@ -1336,6 +1404,73 @@ 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]
+158
Переглянути файл
@@ -27,6 +27,10 @@ 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.
@@ -331,6 +335,59 @@ 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" {
@@ -412,6 +469,9 @@ 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()
@@ -447,6 +507,7 @@ 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 {
@@ -678,6 +739,103 @@ 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(
+42 -1
Переглянути файл
@@ -15,7 +15,9 @@ use std::sync::Arc;
/// 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.
/// 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.
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(tag = "type", rename_all = "camelCase", rename_all_fields = "camelCase")]
pub enum McpUiRequest {
@@ -41,6 +43,36 @@ pub enum McpUiRequest {
#[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>,
}
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
@@ -204,6 +236,15 @@ 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,
+79
Переглянути файл
@@ -165,6 +165,11 @@ 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,
}
impl Default for AgentSettings {
@@ -196,6 +201,7 @@ impl Default for AgentSettings {
defaults: BTreeMap::new(),
mcp_servers: BTreeMap::new(),
skills: BTreeMap::new(),
memory: AgentMemorySettings::default(),
}
}
}
@@ -279,6 +285,79 @@ 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>,
}
/// 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>
+55 -1
Переглянути файл
@@ -391,9 +391,10 @@ pub const DEBUGPY_MISSING: &str = "debugpy is not installed";
/// `PYTHONPATH`. Neither: an `unavailable` error naming the interpreter.
pub async fn prepare_debugpy(spec: &mut AdapterSpec) -> IdeResult<()> {
let (command, cwd) = (spec.command.clone(), spec.cwd.clone());
let Some(python) = tokio::task::spawn_blocking(move || resolve_binary(&command, &cwd)).await.ok().flatten() else {
let Some(python) = tokio::task::spawn_blocking(move || debugpy_python(&command, &cwd)).await.ok().flatten() else {
return Ok(()); // Reported as a missing adapter when it is started.
};
spec.command = python.to_string_lossy().into_owned();
let mut probe = Command::new(&python);
probe.current_dir(&spec.cwd);
ide_core::process::prepare(probe.as_std_mut());
@@ -426,6 +427,46 @@ pub async fn prepare_debugpy(spec: &mut AdapterSpec) -> IdeResult<()> {
)))
}
/// The interpreter `<python> -m debugpy.adapter` runs with. On Windows a bare `python3` (the
/// built-in `python.toml`'s) or `python` may name an App Execution Alias in `WindowsApps`,
/// which only opens the Store unless the Store's Python is installed: every match on `PATH`
/// of the command, then `python`, then the `py` launcher, the first that is no alias or runs.
fn debugpy_python(command: &str, cwd: &Path) -> Option<PathBuf> {
let found = resolve_binary(command, cwd);
if !cfg!(windows) || !matches!(command, "python3" | "python") {
return found;
}
let pathext = std::env::var("PATHEXT").ok();
let dirs = search_dirs(cwd);
let mut candidates: Vec<PathBuf> = Vec::new();
for name in [command, "python", "py"] {
for dir in &dirs {
if let Some(p) = find_binary_in(name, cwd, std::slice::from_ref(dir), true, pathext.as_deref())
&& !candidates.contains(&p)
{
candidates.push(p);
}
}
}
let runs = |p: &Path| {
let mut c = std::process::Command::new(p);
ide_core::process::prepare(&mut c);
c.arg("--version").stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null());
c.status().is_ok_and(|s| s.success())
};
pick_python(candidates, runs).or(found)
}
/// The first candidate that is no App Execution Alias, or is one that `runs`.
fn pick_python(candidates: Vec<PathBuf>, runs: impl Fn(&Path) -> bool) -> Option<PathBuf> {
candidates.into_iter().find(|p| !is_app_execution_alias(p) || runs(p))
}
/// A Windows App Execution Alias (`%LOCALAPPDATA%\Microsoft\WindowsApps\python3.exe`).
fn is_app_execution_alias(path: &Path) -> bool {
path.parent().and_then(Path::file_name).is_some_and(|d| d.eq_ignore_ascii_case("WindowsApps"))
}
/// GDB's DAP interpreter (`-i dap`) shipped in GDB 14; older ones exit with
/// "Interpreter `dap' unrecognized".
const GDB_MIN_MAJOR: u32 = 14;
@@ -859,6 +900,19 @@ async fn connect_with_retries(
mod tests {
use super::*;
/// Windows: a Store alias on `PATH` before the real interpreter is skipped unless it runs
/// (the Store's Python is installed), so the Python Debug Server starts the real one.
#[test]
fn debugpy_skips_store_aliases_that_do_not_run() {
let alias = PathBuf::from("C:/Users/me/AppData/Local/Microsoft/WindowsApps/python3.exe");
let real = PathBuf::from("C:/Program Files/Python313/python.exe");
assert!(is_app_execution_alias(&alias) && !is_app_execution_alias(&real));
let both = vec![alias.clone(), real.clone()];
assert_eq!(pick_python(both.clone(), |_| false), Some(real.clone()));
assert_eq!(pick_python(both, |_| true), Some(alias.clone()));
assert_eq!(pick_python(vec![alias], |_| false), None);
}
/// A user's `languages/python.toml` `[debugger]` is the one debugpy runs with: no other
/// language (a template one) declares debugpy before Python.
#[test]
+24
Переглянути файл
@@ -912,6 +912,30 @@ impl DebugManager {
.collect()
}
/// Whether `s` is live and currently suspended (a breakpoint, step or manual pause).
/// `None` when the session has ended.
pub fn session_suspended(&self, s: DebugSessionId) -> Option<bool> {
self.sessions.lock().get(&s).map(|session| session.suspended.get())
}
/// The thread of `s`'s most recent stop, when the adapter named one.
pub fn stopped_thread(&self, s: DebugSessionId) -> Option<i64> {
self.sessions.lock().get(&s).and_then(|session| session.suspended.stopped_thread())
}
/// All stored breakpoints of `owner`, for tools that list or edit them. Line breakpoints
/// are keyed by file; function and data breakpoints have no file.
pub fn breakpoints(
&self,
owner: &str,
) -> (BTreeMap<PathBuf, Vec<Breakpoint>>, Vec<FunctionBreakpoint>, Vec<DataBreakpoint>) {
let store = self.breakpoints.lock();
match store.get(owner) {
Some(owner) => (owner.lines.clone(), owner.functions.clone(), owner.data.clone()),
None => Default::default(),
}
}
/// Starts a session: spawns the adapter, `initialize`, `launch`/`attach`,
/// waits for `initialized`, sends breakpoints, then `configurationDone`.
/// Events of the session (including cargo build output) go to `owner` only.
+8
Переглянути файл
@@ -207,6 +207,14 @@ impl Suspension {
stops.all.is_some() || !stops.threads.is_empty()
}
/// The most recently stopped individual thread, when the stop named one. A stop of every
/// thread (`allThreadsStopped`) names none, so callers fall back to the adapter's first thread.
pub fn stopped_thread(&self) -> Option<i64> {
let stops = self.0.lock();
let latest = stops.latest()?;
stops.threads.iter().find(|&&(_, ticket)| ticket == latest).map(|&(id, _)| id)
}
/// A `stopped` event; `all`: its `allThreadsStopped`.
pub fn stopped(&self, thread: Option<i64>, all: bool) {
let mut stops = self.0.lock();
+7
Переглянути файл
@@ -108,6 +108,7 @@ pub struct Host {
pub data_dir: PathBuf,
/// Machine-local tools and rebuildable caches.
pub local_data_dir: PathBuf,
home_dir: Option<PathBuf>,
pub languages: Arc<LanguageRegistry>,
syntax: Arc<OnceLock<Arc<Syntax>>>,
pub global_settings: SettingsStore,
@@ -206,6 +207,11 @@ impl Host {
self
}
/// User home directory used by agent memory discovery.
pub fn home_dir(&self) -> Option<PathBuf> {
self.home_dir.clone()
}
pub fn new(config: HostConfig) -> Self {
let HostConfig {
config_dir,
@@ -268,6 +274,7 @@ impl Host {
config_dir,
data_dir,
local_data_dir,
home_dir: dirs::home_dir(),
sink_for,
owner,
runtime,
File diff suppressed because it is too large. Load diff
+2
Переглянути файл
@@ -1,6 +1,7 @@
//! Built-in IDE tools. Transport and discovery live in `ide-mcp`.
mod background;
mod check;
mod debug;
mod edit;
mod editors;
mod requests;
@@ -43,6 +44,7 @@ fn tools() -> Vec<tool::Tool> {
tools.extend(search::tools());
tools.extend(editors::tools());
tools.push(check::check_files());
tools.extend(debug::tools());
tools.push(symbols::get_symbol_info());
tools.push(symbols::find_references());
tools.push(symbols::get_call_hierarchy());
+24 -2
Переглянути файл
@@ -15,6 +15,7 @@ struct State {
struct Pending {
window: String,
answer: oneshot::Sender<Result<bool, String>>,
value: oneshot::Sender<Option<String>>,
}
impl Requests {
pub fn set_ready(&self, window: &str, ready: bool) {
@@ -30,11 +31,23 @@ impl Requests {
state.pending.retain(|_, p| p.window != window);
}
pub fn answer(&self, window: &str, id: u32, allow: bool, error: Option<String>) -> IdeResult<()> {
self.answer_with(window, id, allow, error, None)
}
/// A request can also answer with a value, e.g. the id of the debug session it started.
pub fn answer_with(
&self,
window: &str,
id: u32,
allow: bool,
error: Option<String>,
value: Option<String>,
) -> IdeResult<()> {
let mut state = self.0.lock();
if !state.pending.get(&id).is_some_and(|p| p.window == window) {
return Err(IdeError::invalid("MCP request expired or belongs to another window"));
}
let pending = state.pending.remove(&id).unwrap();
let _ = pending.value.send(value);
let _ = pending.answer.send(error.map_or(Ok(allow), Err));
Ok(())
}
@@ -44,14 +57,23 @@ impl Requests {
}
pub(super) async fn ask(&self, call: &Call, request: McpUiRequest) -> IdeResult<()> {
self.ask_inner(call, request).await.map(|_| ())
}
pub(super) async fn ask_value(&self, call: &Call, request: McpUiRequest) -> IdeResult<Option<String>> {
self.ask_inner(call, request).await
}
async fn ask_inner(&self, call: &Call, request: McpUiRequest) -> IdeResult<Option<String>> {
let id = super::tool::request_id().0;
let (tx, rx) = oneshot::channel();
let (value_tx, value_rx) = oneshot::channel();
{
let mut state = self.0.lock();
if !state.ready.contains(call.window()) {
return Err(IdeError::unavailable("MCP request denied: no project window is available"));
}
state.pending.insert(id, Pending { window: call.window.clone(), answer: tx });
state.pending.insert(id, Pending { window: call.window.clone(), answer: tx, value: value_tx });
}
struct Close<'a>(&'a Requests, &'a Call, u32);
impl Drop for Close<'_> {
@@ -68,7 +90,7 @@ impl Requests {
_ = call.cancel.cancelled() => return Err(IdeError::cancelled()),
};
match result {
Ok(true) => Ok(()),
Ok(true) => Ok(value_rx.await.unwrap_or(None)),
Ok(false) => Err(IdeError::invalid("MCP request denied by the user")),
Err(message) => Err(IdeError::unavailable(message)),
}
+19 -15
Переглянути файл
@@ -29,14 +29,14 @@ const MAX_PROCESS_OUTPUT_LENGTH: usize = 20_000;
/// A before-launch build gets this long.
const BEFORE_LAUNCH_BUILD_TIMEOUT: Duration = Duration::from_secs(3600);
async fn load_configs(call: &Call) -> IdeResult<Vec<RunConfig>> {
pub(crate) async fn load_configs(call: &Call) -> IdeResult<Vec<RunConfig>> {
let host = call.host();
let window = call.window().to_owned();
let h = host.clone();
host.blocking(move || crate::ops::run::configs(&h, &window)).await
}
fn supports_overrides(config: &RunConfig) -> bool {
pub(crate) fn supports_overrides(config: &RunConfig) -> bool {
config.extras.compound.is_empty() && !config.command.trim().is_empty()
}
@@ -178,13 +178,17 @@ in the file instead of project-wide run configurations.",
.param(Param::optional("offset", ParamType::Integer, OFFSET))
}
/// What `execute_run_configuration` runs.
enum ExecutionTarget {
/// What `execute_run_configuration` and `xdebug_start_debugger_session` run.
pub(crate) enum ExecutionTarget {
ByName(String),
ByContext(String, i64),
}
fn execution_target(name: Option<String>, file: Option<String>, line: Option<i64>) -> IdeResult<ExecutionTarget> {
pub(crate) fn execution_target(
name: Option<String>,
file: Option<String>,
line: Option<i64>,
) -> IdeResult<ExecutionTarget> {
let name = name.filter(|n| !n.trim().is_empty());
let file = file.filter(|f| !f.trim().is_empty());
match (name, file, line) {
@@ -203,7 +207,7 @@ fn execution_target(name: Option<String>, file: Option<String>, line: Option<i64
/// The temporary configuration of the run point at `file:line` (1-based): the innermost target
/// enclosing that line (as JetBrains walks up to the enclosing test), else the whole file's
/// (its tests, its main function).
async fn config_from_code_location(
pub(crate) async fn config_from_code_location(
call: &Call,
configs: Vec<RunConfig>,
file: &str,
@@ -234,7 +238,7 @@ filePath to find valid run locations."
/// Applies the one-off overrides (JetBrains' `prepareRunConfigurationForExecution`): a missing or
/// empty string keeps the value, a whitespace-only one clears it; `envs` merge over the configuration's.
fn apply_overrides(
pub(crate) fn apply_overrides(
config: &mut RunConfig,
root: &Path,
args: Option<String>,
@@ -413,13 +417,13 @@ fn process_output(mut f: impl FnMut(&str) + Send + 'static) -> crate::ops::Chann
/// What failed before launch (JetBrains' `RunConfigurationBuildErrors`): build errors as
/// `path:line: message`, else the output of before-launch processes that failed.
#[derive(Default)]
struct BuildErrors {
errors: Vec<String>,
process_outputs: Vec<String>,
pub(crate) struct BuildErrors {
pub(crate) errors: Vec<String>,
pub(crate) process_outputs: Vec<String>,
}
impl BuildErrors {
fn text(&self) -> Option<String> {
pub(crate) fn text(&self) -> Option<String> {
let mut seen = std::collections::HashSet::new();
let errors: Vec<&String> = self.errors.iter().filter(|e| seen.insert(*e)).collect();
if !errors.is_empty() {
@@ -573,7 +577,7 @@ async fn find_java_module(call: &Call, main: &str) -> IdeResult<Option<String>>
/// built per its before-launch build policy, with `${classpath}` / `${testClasspath}`, the
/// module path and the module's `java` resolved through jdtls. `Err` says why it cannot start
/// (compile errors are added to `errors`). Other configurations are returned as they are.
async fn resolve_jvm_application(
pub(crate) async fn resolve_jvm_application(
call: &Call,
mut config: RunConfig,
errors: &mut BuildErrors,
@@ -639,7 +643,7 @@ async fn resolve_jvm_application(
/// The configuration's before-launch tasks, as the Run tool window runs them; returns why
/// the launch is aborted, if it is. Tool windows are not activated.
async fn before_launch(
pub(crate) async fn before_launch(
call: &Call,
config: &RunConfig,
configs: &[RunConfig],
@@ -754,7 +758,7 @@ fn describe_before_launch(
/// or applies — before-launch tasks, the stored environment (for a configuration made from
/// code, the one of the configuration it derives from), `.env` files, the `envs` overrides
/// (`NODE_OPTIONS`, `PATH`, ...), the stop command and a remote run target.
fn confirmation_detail(
pub(crate) fn confirmation_detail(
config: &RunConfig,
cwd: &str,
stored_env: &std::collections::BTreeMap<String, String>,
@@ -797,7 +801,7 @@ fn confirmation_detail(
detail
}
fn execution_failed(details: &[Option<String>]) -> IdeError {
pub(crate) fn execution_failed(details: &[Option<String>]) -> IdeError {
let details: Vec<&str> = details.iter().flatten().map(String::as_str).collect();
IdeError::invalid(format!("Execution failed: {}", details.join("\n")))
}
+14
Переглянути файл
@@ -299,6 +299,19 @@ pub fn mcp_respond(host: &Host, window: &str, id: u32, allow: bool, error: Optio
host.mcp_requests.answer(host.owner_window(window), id, allow, error)
}
/// Like `mcp_respond`, with a value for requests that ask for one (the started debug session id).
#[command(trust = trusted)]
pub fn mcp_respond_with(
host: &Host,
window: &str,
id: u32,
allow: bool,
error: Option<String>,
value: Option<String>,
) -> IdeResult<()> {
host.mcp_requests.answer_with(host.owner_window(window), id, allow, error, value)
}
#[cfg(test)]
mod tests {
use super::*;
@@ -323,6 +336,7 @@ ide_command::domain!(
mcp_background_projects,
mcp_regenerate_token,
mcp_respond,
mcp_respond_with,
mcp_server_status,
mcp_ui_ready,
mcp_unload_background_project,
+4
Переглянути файл
@@ -70,6 +70,10 @@ impl Call {
pub async fn ask(&self, request: ide_core::event::McpUiRequest) -> IdeResult<()> {
self.host.mcp_requests.ask(self, request).await
}
/// A window request that answers with a value, e.g. the debug session it started.
pub async fn ask_value(&self, request: ide_core::event::McpUiRequest) -> IdeResult<Option<String>> {
self.host.mcp_requests.ask_value(self, request).await
}
/// Whether the project has a window to show what the tool starts (not one loaded for MCP alone).
pub fn has_window(&self) -> bool {
self.host.mcp_requests.window_ready(&self.window)
+292 -5
Переглянути файл
@@ -6,11 +6,13 @@ use crate::agent_secrets::{AgentSecrets, Kept};
use ide_agent::registry::{AgentRegistry, RegistryPaths};
use ide_agent::{
AcpImportOutcome, AgentAcceptOutcome, AgentChange, AgentChanges, AgentChangesView, AgentCliOffer,
AgentCliUpdateResult, AgentCommand, AgentContextUsage, AgentEntry, AgentEvent, AgentLoginEvent, AgentModelCatalog,
AgentProbe, AgentPrompt, AgentProvider, AgentQueued, AgentRecoveryReport, AgentSkillMode, AgentSkillPolicy,
AgentSkillState, AgentTask, CopilotAuthStatus, CustomAgentInput, ExternalSession, InstallRemoteSkillRequest,
LoginLaunch, McpExternalSource, McpImportSelection, McpProbeResult, McpScope, McpServer, McpServerInput,
McpTransport, NewAgentTask, RemoteSkillBrowseResult, RemoteSkillPreview, SkillsPolicy,
AgentCliUpdateResult, AgentCommand, AgentContextUsage, AgentEntry, AgentEvent, AgentLoginEvent, AgentMemoryCatalog,
AgentMemoryEntryPolicy, AgentMemoryMode, AgentMemoryOverrides, AgentMemorySettings, AgentModelCatalog, AgentProbe,
AgentPrompt, AgentProvider, AgentProviderMemoryPolicy, AgentQueued, AgentRecoveryReport, AgentSkillMode,
AgentSkillPolicy, AgentSkillState, AgentTask, AutoMemoryMode, CopilotAuthStatus, CreateAgentMemoryInput,
CustomAgentInput, ExternalSession, InstallRemoteSkillRequest, LoginLaunch, McpExternalSource, McpImportSelection,
McpProbeResult, McpScope, McpServer, McpServerInput, McpTransport, NewAgentTask, PromoteAgentMemoryInput,
RemoteSkillBrowseResult, RemoteSkillPreview, SkillsPolicy,
};
use ide_command::command;
use ide_core::error::ErrorKind;
@@ -1295,6 +1297,17 @@ pub fn agent_set_skill_overrides(
host.project(window)?.agents.set_skill_overrides(&task, overrides)
}
/// Updates per-session memory overrides (auto-memory mode and per-entry modes) on `task`.
#[command(trust = always)]
pub fn agent_set_memory_overrides(
host: &Host,
window: &str,
task: String,
overrides: AgentMemoryOverrides,
) -> IdeResult<AgentTask> {
host.project(window)?.agents.set_memory_overrides(&task, overrides)
}
/// Every skill discovered in the project, the user's folders and enabled plugins, with
/// the mode a session runs it with (without any session's own overrides).
#[command(trust = always)]
@@ -1566,6 +1579,272 @@ fn host_skills_policy(host: &Host, project: Option<&crate::Project>) -> SkillsPo
}
}
fn host_memory_policy(host: &Host, project: Option<&crate::Project>) -> ide_agent::memory::MemoryPolicy {
match project {
Some(project) => ide_agent::memory::MemoryPolicy {
user: project.settings.layer(ide_workspace::settings::SettingsScope::Global).agents.memory.clone(),
workspace: project.settings.layer(ide_workspace::settings::SettingsScope::Project).agents.memory.clone(),
workspace_trusted: project.trusted.load(std::sync::atomic::Ordering::Acquire),
workspace_roots: workspace_skill_roots(&project.root),
},
None => ide_agent::memory::MemoryPolicy {
user: host.global_settings.effective().agents.memory.clone(),
workspace: Default::default(),
workspace_trusted: true,
workspace_roots: Vec::new(),
},
}
}
fn memory_settings_layers(
host: &Host,
project: Option<&std::sync::Arc<crate::Project>>,
) -> (AgentMemorySettings, Option<AgentMemorySettings>) {
let user = host.global_settings.effective().agents.memory.clone();
let workspace =
project.map(|p| p.settings.layer(ide_workspace::settings::SettingsScope::Project).agents.memory.clone());
(user, workspace)
}
fn is_default_memory_settings(s: &AgentMemorySettings) -> bool {
s.auto_memory == AutoMemoryMode::Inherit && s.providers.is_empty() && s.entries.is_empty()
}
fn persist_memory_settings(
host: &Host,
project: Option<&std::sync::Arc<crate::Project>>,
scope: McpScope,
settings: &AgentMemorySettings,
) -> IdeResult<()> {
let value = if is_default_memory_settings(settings) {
serde_json::Value::Null
} else {
serde_json::to_value(settings).map_err(|e| IdeError::invalid(e.to_string()))?
};
let event = IdeEvent::SettingsChanged { key: "agents.memory".into() };
match scope {
McpScope::User => {
host.global_settings.set(ide_workspace::settings::SettingsScope::Global, "agents.memory", value)?;
for p in host.projects() {
p.settings.reload();
p.agents.notify_mcp_servers_changed();
p.sink.emit(event.clone());
}
}
McpScope::Workspace => {
let p = project.ok_or_else(|| IdeError::invalid("Open a project to configure workspace memory"))?;
p.settings.set(ide_workspace::settings::SettingsScope::Project, "agents.memory", value)?;
p.agents.notify_mcp_servers_changed();
p.sink.emit(event);
}
}
Ok(())
}
async fn current_memory_catalog(host: &Host, project: Option<&crate::Project>) -> IdeResult<AgentMemoryCatalog> {
let policy = host_memory_policy(host, project);
let home = host.home_dir();
blocking(move || {
let entries = ide_agent::memory::discover_memories(&policy.workspace_roots, home.as_deref());
Ok(ide_agent::memory::resolve_catalog(entries, None, &policy, home.as_deref()))
})
.await
}
/// Discovers every agent instruction file, path-scoped rule, and learned auto-memory note
/// with resolved modes and per-provider auto-memory statuses.
#[command(trust = always)]
pub async fn agent_memory_list(host: &Host, window: &str) -> IdeResult<AgentMemoryCatalog> {
let project = host.project(window).ok().filter(|p| !p.light);
current_memory_catalog(host, project.as_deref()).await
}
/// Sets how memory entry `id` runs in `scope` (`settings.toml` vs `.openidea/settings.toml`),
/// never modifying the file on disk.
#[command(trust = always)]
pub async fn agent_memory_set_mode(
host: &Host,
window: &str,
id: String,
scope: McpScope,
mode: AgentMemoryMode,
agents: Vec<String>,
) -> IdeResult<AgentMemoryCatalog> {
let id = id.trim().to_owned();
if id.is_empty() {
return Err(IdeError::invalid("a memory entry needs an id"));
}
let clean_agents: Vec<String> = agents.into_iter().map(|a| a.trim().to_owned()).filter(|a| !a.is_empty()).collect();
let project = host.project(window).ok().filter(|p| !p.light);
let (mut user, mut workspace) = memory_settings_layers(host, project.as_ref());
let apply = |layer: &mut AgentMemorySettings| -> bool {
if mode == AgentMemoryMode::Auto && clean_agents.is_empty() {
layer.entries.remove(&id).is_some()
} else {
let next = AgentMemoryEntryPolicy { mode, agents: clean_agents.clone() };
layer.entries.insert(id.clone(), next.clone()).as_ref() != Some(&next)
}
};
match scope {
McpScope::User => {
if apply(&mut user) {
persist_memory_settings(host, None, scope, &user)?;
}
}
McpScope::Workspace => {
let ws =
workspace.as_mut().ok_or_else(|| IdeError::invalid("Open a project to configure workspace memory"))?;
if apply(ws) {
let updated = ws.clone();
persist_memory_settings(host, project.as_ref(), scope, &updated)?;
}
}
}
current_memory_catalog(host, project.as_deref()).await
}
/// Sets the cross-session auto-memory policy (`Inherit`, `ReadWrite`, `ReadOnly`, `Off`)
/// globally or for one `provider` in `scope`.
#[command(trust = always)]
pub async fn agent_memory_set_auto(
host: &Host,
window: &str,
scope: McpScope,
provider: Option<String>,
mode: AutoMemoryMode,
) -> IdeResult<AgentMemoryCatalog> {
let project = host.project(window).ok().filter(|p| !p.light);
let (mut user, mut workspace) = memory_settings_layers(host, project.as_ref());
let prov_key = provider
.as_deref()
.map(str::trim)
.filter(|s| !s.is_empty())
.map(|s| ide_agent::memory::normalize_provider_id(s).to_owned());
let apply = |layer: &mut AgentMemorySettings| -> bool {
match &prov_key {
None => {
let changed = layer.auto_memory != mode;
layer.auto_memory = mode;
changed
}
Some(key) => {
if mode == AutoMemoryMode::Inherit {
layer.providers.remove(key).is_some()
} else {
let next = AgentProviderMemoryPolicy { auto_memory: mode };
layer.providers.insert(key.clone(), next.clone()).as_ref() != Some(&next)
}
}
}
};
match scope {
McpScope::User => {
if apply(&mut user) {
persist_memory_settings(host, None, scope, &user)?;
}
}
McpScope::Workspace => {
let ws =
workspace.as_mut().ok_or_else(|| IdeError::invalid("Open a project to configure workspace memory"))?;
if apply(ws) {
let updated = ws.clone();
persist_memory_settings(host, project.as_ref(), scope, &updated)?;
}
}
}
current_memory_catalog(host, project.as_deref()).await
}
/// Creates a new instruction or path-scoped rule file on disk.
#[command(trust = always)]
pub async fn agent_memory_create(
host: &Host,
window: &str,
input: CreateAgentMemoryInput,
) -> IdeResult<AgentMemoryCatalog> {
let project = host.project(window).ok().filter(|p| !p.light);
if input.scope == McpScope::Workspace {
host.require_trust(window)?;
}
let ws_root = project.as_ref().map(|p| p.root.clone());
let home = host.home_dir();
blocking(move || {
ide_agent::memory::create_memory(&input, ws_root.as_deref(), home.as_deref()).map_err(IdeError::invalid)
})
.await?;
let event = IdeEvent::SettingsChanged { key: "agents.memory".into() };
for p in host.projects() {
p.agents.notify_mcp_servers_changed();
p.sink.emit(event.clone());
}
current_memory_catalog(host, project.as_deref()).await
}
/// Promotes a learned auto-memory note into `<workspace>/AGENTS.md`.
#[command(trust = trusted)]
pub async fn agent_memory_promote(
host: &Host,
window: &str,
input: PromoteAgentMemoryInput,
) -> IdeResult<AgentMemoryCatalog> {
host.require_trust(window)?;
let project = host.project(window)?;
let ws_root = project.root.clone();
let roots = workspace_skill_roots(&ws_root);
let home = host.home_dir();
blocking(move || {
let entries = ide_agent::memory::discover_memories(&roots, home.as_deref());
ide_agent::memory::promote_memory(&input, &entries, &ws_root).map_err(IdeError::invalid)
})
.await?;
let event = IdeEvent::SettingsChanged { key: "agents.memory".into() };
for p in host.projects() {
p.agents.notify_mcp_servers_changed();
p.sink.emit(event.clone());
}
current_memory_catalog(host, Some(&project)).await
}
/// Deletes a writable memory entry (learned auto-memory note or OpenIDEA shared memory file).
#[command(trust = always)]
pub async fn agent_memory_delete(host: &Host, window: &str, id: String) -> IdeResult<AgentMemoryCatalog> {
let project = host.project(window).ok().filter(|p| !p.light);
if id.starts_with("workspace::") {
host.require_trust(window)?;
}
let roots = project.as_ref().map(|p| workspace_skill_roots(&p.root)).unwrap_or_default();
let home = host.home_dir();
blocking(move || {
let entries = ide_agent::memory::discover_memories(&roots, home.as_deref());
ide_agent::memory::delete_memory(&id, &entries).map_err(IdeError::invalid)
})
.await?;
let event = IdeEvent::SettingsChanged { key: "agents.memory".into() };
for p in host.projects() {
p.agents.notify_mcp_servers_changed();
p.sink.emit(event.clone());
}
current_memory_catalog(host, project.as_deref()).await
}
/// Clears local auto-memory files for `provider` (`claude`, `codex`, or `hermes`).
#[command(trust = always)]
pub async fn agent_memory_reset_provider(host: &Host, window: &str, provider: String) -> IdeResult<AgentMemoryCatalog> {
let project = host.project(window).ok().filter(|p| !p.light);
let roots = project.as_ref().map(|p| workspace_skill_roots(&p.root)).unwrap_or_default();
let home = host.home_dir();
blocking(move || {
ide_agent::memory::reset_provider_memory(&provider, &roots, home.as_deref()).map_err(IdeError::invalid)
})
.await?;
let event = IdeEvent::SettingsChanged { key: "agents.memory".into() };
for p in host.projects() {
p.agents.notify_mcp_servers_changed();
p.sink.emit(event.clone());
}
current_memory_catalog(host, project.as_deref()).await
}
fn validate_project_root(root: &std::path::Path, requested: Option<&std::path::Path>) -> IdeResult<std::path::PathBuf> {
let Some(requested) = requested else {
return Ok(root.to_path_buf());
@@ -1744,6 +2023,13 @@ ide_command::domain!(
agent_mcp_save_json,
agent_mcp_set_enabled,
agent_mcp_test,
agent_memory_create,
agent_memory_delete,
agent_memory_list,
agent_memory_promote,
agent_memory_reset_provider,
agent_memory_set_auto,
agent_memory_set_mode,
agent_poke_network,
agent_preview_copilot_models,
agent_probe,
@@ -1768,6 +2054,7 @@ ide_command::domain!(
agent_set_config,
agent_set_env,
agent_set_mcp_overrides,
agent_set_memory_overrides,
agent_set_recovery_window,
agent_set_skill_overrides,
agent_skills_browse,
+20
Переглянути файл
@@ -600,6 +600,26 @@ pub fn debug_breakpoint_states(host: &Host, path: PathBuf) -> IdeResult<Vec<Brea
Ok(host.debugger.breakpoint_states(&path))
}
/// This window's stored breakpoints, with their full attributes (not just verification states).
/// Kept as a plain function: the MCP tools list and edit them under the window's owner, so they
/// are sent to this window's sessions just like breakpoints set in the editor.
pub fn debug_breakpoints(
host: &Host,
window: &str,
) -> (std::collections::BTreeMap<PathBuf, Vec<Breakpoint>>, Vec<FunctionBreakpoint>, Vec<DataBreakpoint>) {
host.debugger.breakpoints(host.owner_window(window))
}
/// Whether a live session is suspended; `None` once it has ended. Used by tools that wait for a pause.
pub fn debug_session_suspended(host: &Host, session: DebugSessionId) -> Option<bool> {
host.debugger.session_suspended(session)
}
/// The thread the session last stopped in, when the adapter named one. Frame tools default to it.
pub fn debug_stopped_thread(host: &Host, session: DebugSessionId) -> Option<i64> {
host.debugger.stopped_thread(session)
}
/// This window's live sessions, including adapter-started child sessions.
#[command(trust = always)]
pub fn debug_sessions(host: &Host, window: &str) -> IdeResult<Vec<SessionInfo>> {
+7
Переглянути файл
@@ -2097,6 +2097,12 @@ pub async fn lsp_restart(host: &Host, window: &str, server: ServerId) -> IdeResu
Ok(())
}
/// Stops a language server; it starts again when a file it serves is opened.
#[command(trust = trusted)]
pub async fn lsp_stop(host: &Host, window: &str, server: ServerId) -> IdeResult<()> {
host.project(window)?.lsp.stop(server).await
}
/// Restarts the language servers named `name` in every open project, so a tool installed or
/// updated from one window is what all of them run (not only that window's project).
pub async fn lsp_restart_named(host: &Host, name: &str) -> IdeResult<()> {
@@ -3306,6 +3312,7 @@ ide_command::domain!(
lsp_resolve_command,
lsp_resolve_completion,
lsp_restart,
lsp_stop,
lsp_semantic_tokens,
lsp_servers,
lsp_signature_help,
+7 -2
Переглянути файл
@@ -483,8 +483,13 @@ pub fn set_settings(
project.agents.notify_mcp_servers_changed();
}
}
// A skill policy change re-resolves the modes; an idle session restarts to pick them up.
if key == "agents" || key == "agents.skills" || key.starts_with("agents.skills.") {
// A skill or memory policy change re-resolves the modes; an idle session restarts to pick them up.
if key == "agents"
|| key == "agents.skills"
|| key.starts_with("agents.skills.")
|| key == "agents.memory"
|| key.starts_with("agents.memory.")
{
for project in affected() {
project.agents.notify_mcp_servers_changed();
}
+124
Переглянути файл
@@ -540,6 +540,9 @@ async fn start_inner(
.await
.map_err(|e| IdeError::internal(e.to_string()))??;
}
let xcode_container = matches!(config.kind.as_str(), "xcode" | "xcode-test")
.then(|| xcode_container(&config).map(|c| run_dir.join(c)))
.flatten();
if config.kind == "xcode" {
let (dir, cache) = (run_dir.clone(), project.cache_dir.clone());
config = host
@@ -600,9 +603,130 @@ async fn start_inner(
previous.emit(event);
});
}
let on_output = match xcode_container {
Some(container) => {
let (output, problems) = xcodebuild_problems(&project, &config.id, &run_dir, container, on_output, sink);
sink = problems;
output
}
None => on_output,
};
host.processes.start(&project.root, &config, &options, sink, Box::new(move |c| on_output(c)))
}
/// The `-project` / `-workspace` an Xcode configuration builds, relative to its folder.
fn xcode_container(config: &RunConfig) -> Option<String> {
config.extras.params.get("container").cloned().or_else(|| {
let at = config.args.iter().position(|a| a == "-project" || a == "-workspace")?;
config.args.get(at + 1).cloned()
})
}
const XCODEBUILD_SOURCE: &str = "xcodebuild";
/// Sends the compiler messages in an Xcode configuration's `xcodebuild` output to Problems as they
/// arrive, after clearing the ones its previous run reported. Messages without a location (linker
/// errors) are listed on the project file (`project.pbxproj` / `contents.xcworkspacedata`).
fn xcodebuild_problems(
project: &crate::project::Project,
config_id: &str,
cwd: &Path,
container: PathBuf,
on_output: Emit<OutputChunk>,
sink: ide_core::SharedSink,
) -> (Emit<OutputChunk>, ide_core::SharedSink) {
use ide_build::compile::{BuildMessage, XcodebuildMessages, diagnostics_from};
use ide_core::IdeEvent;
use std::collections::BTreeMap;
let project_file = container.join(if container.extension().is_some_and(|e| e == "xcworkspace") {
"contents.xcworkspacedata"
} else {
"project.pbxproj"
});
let reported = project.xcodebuild_problems.clone();
let previous = reported.lock().insert(config_id.to_owned(), Vec::new()).unwrap_or_default();
for path in previous {
sink.emit(IdeEvent::Diagnostics { path: path.into(), source: XCODEBUILD_SOURCE.into(), items: Vec::new() });
}
struct State {
parser: XcodebuildMessages,
/// Unfinished lines of stdout and stderr.
partial: [String; 2],
files: BTreeMap<PathBuf, Vec<BuildMessage>>,
}
let state = Arc::new(parking_lot::Mutex::new(State {
parser: XcodebuildMessages::new(&project.root, cwd),
partial: Default::default(),
files: BTreeMap::new(),
}));
let config_id = config_id.to_owned();
let publish = {
let sink = sink.clone();
move |state: &mut State, messages: Vec<BuildMessage>| {
let mut changed = Vec::new();
for mut m in messages {
if m.path.is_none() {
m.path = Some(project_file.clone().into());
m.range = Some(ide_core::Range::default());
}
let Some(path) = m.path.clone().map(PathBuf::from) else { continue };
if !state.files.contains_key(&path) {
reported.lock().entry(config_id.clone()).or_default().push(path.clone());
}
state.files.entry(path.clone()).or_default().push(m);
if !changed.contains(&path) {
changed.push(path);
}
}
for path in changed {
let items = diagnostics_from(&state.files[&path], XCODEBUILD_SOURCE).remove(&path).unwrap_or_default();
sink.emit(IdeEvent::Diagnostics { path: path.into(), source: XCODEBUILD_SOURCE.into(), items });
}
}
};
let publish = Arc::new(publish);
let output: Emit<OutputChunk> = {
let (state, publish) = (state.clone(), publish.clone());
Arc::new(move |chunk: OutputChunk| {
let stream = match &chunk {
OutputChunk::Stdout { text } => Some((0, text)),
OutputChunk::Stderr { text } => Some((1, text)),
OutputChunk::System { .. } => None,
};
if let Some((i, text)) = stream {
let mut guard = state.lock();
let s = &mut *guard;
s.partial[i].push_str(text);
let mut messages = Vec::new();
while let Some(end) = s.partial[i].find('\n') {
let line: String = s.partial[i].drain(..=end).collect();
messages.extend(s.parser.feed(line.trim_end_matches(['\n', '\r'])));
}
publish(s, messages);
}
on_output(chunk);
})
};
let problems: ide_core::SharedSink = Arc::new(move |event: IdeEvent| {
if matches!(event, IdeEvent::RunExited { .. }) {
let mut guard = state.lock();
let s = &mut *guard;
let mut messages = Vec::new();
for i in 0..2 {
let rest = std::mem::take(&mut s.partial[i]);
if !rest.is_empty() {
messages.extend(s.parser.feed(rest.trim_end_matches('\r')));
}
}
messages.extend(s.parser.finish());
publish(s, messages);
}
sink.emit(event);
});
(output, problems)
}
/// Plugins' Java agents (`[[contributes.javaAgents]]`, granted `java.agent`) for the JVM of an
/// Application, Spring Boot or JAR Application configuration started on this machine. A JVM on a
/// run target gets none; the console says so, and why an approved agent was left out. A launch
+92 -43
Переглянути файл
@@ -9,8 +9,9 @@ use ide_extension::Package;
use ide_extension::ledger::{Ledger, Subject};
use ide_language::ProgramPin;
use ide_plugin::{
CommitChange, CommitDraft, EventKind, HostApi, HostError, HttpRequest, HttpResponse, NotificationLevel,
ProcessChunk, ProcessCommand, ProcessOptions, ProcessOutput, Prompt, RepositoryStatus, SettingsTarget, StatusItem,
CommitChange, CommitDraft, EventKind, HostApi, HostError, HttpRequest, HttpResponse, HttpStreamHead,
NotificationLevel, ProcessChunk, ProcessCommand, ProcessOptions, ProcessOutput, Prompt, RepositoryStatus,
SettingsTarget, StatusItem,
};
use parking_lot::{Mutex, RwLock};
use std::collections::{BTreeMap, BTreeSet, HashMap};
@@ -327,6 +328,14 @@ fn network_error(error: reqwest::Error) -> HostError {
HostError::Failed(ide_http::client::describe(&error))
}
fn response_headers(response: &reqwest::Response) -> Vec<(String, String)> {
response
.headers()
.iter()
.map(|(k, v)| (k.as_str().to_owned(), String::from_utf8_lossy(v.as_bytes()).into_owned()))
.collect()
}
fn redirect_capability(from: &reqwest::Url, to: &reqwest::Url) -> Result<Capability, String> {
if from.scheme() == "https" && to.scheme() == "http" {
ide_plugin::net_host(to.as_str()).map(Capability::NetHttp)
@@ -737,6 +746,7 @@ pub(super) struct Shared {
processes: Mutex<HashMap<(String, u64), Arc<Proc>>>,
next_process: AtomicU64,
connections: super::ipc::Connections,
http_streams: super::http_stream::HttpStreams,
pub loopbacks: RwLock<Arc<dyn super::auth::Service>>,
process_shutdowns: Mutex<Vec<std::thread::JoinHandle<()>>>,
pub(super) prompts: Mutex<HashMap<u64, PromptEntry>>,
@@ -850,6 +860,7 @@ impl Shared {
processes: Mutex::default(),
next_process: AtomicU64::new(1),
connections: super::ipc::Connections::default(),
http_streams: super::http_stream::HttpStreams::default(),
loopbacks: RwLock::new(Arc::new(super::auth::Loopbacks::default())),
process_shutdowns: Mutex::default(),
prompts: Mutex::default(),
@@ -1078,6 +1089,7 @@ impl Shared {
self.kill_processes(plugin);
self.connections.clear(plugin);
self.http_streams.clear(plugin);
self.websockets.disconnect_plugin(plugin);
self.setting_snapshots.lock().retain(|(_, p), _| p != plugin);
let channels: Vec<_> = {
@@ -1365,6 +1377,47 @@ impl PluginApi {
self.approved_program_in_project(program, None)
}
/// `request` with its secrets filled in and a redirect policy that checks
/// every hop against its grants; the caller sets the timeout.
fn http_request(&self, request: HttpRequest) -> Result<reqwest::RequestBuilder, HostError> {
let secrets = self.shared.secrets.read().clone();
let id = self.id().to_owned();
let mut headers = reqwest::header::HeaderMap::new();
for (name, value) in &request.headers {
let value = fill_secrets(value, |n| secrets.get(&id, n))?;
let name = reqwest::header::HeaderName::from_bytes(name.as_bytes())
.map_err(|e| HostError::Invalid(format!("header {name:?}: {e}")))?;
let mut value = reqwest::header::HeaderValue::from_str(&value)
.map_err(|e| HostError::Invalid(format!("header {name}: {e}")))?;
value.set_sensitive(true);
headers.append(name, value);
}
let method = reqwest::Method::from_bytes(request.method.to_ascii_uppercase().as_bytes())
.map_err(|_| HostError::Invalid(format!("method {:?}", request.method)))?;
let grants = request.grants.clone();
let policy = reqwest::redirect::Policy::custom(move |attempt| {
if attempt.previous().len() >= 10 {
return attempt.error("too many redirects");
}
let wanted = attempt.previous().last().map_or_else(
|| ide_plugin::net_capability(attempt.url().as_str()),
|from| redirect_capability(from, attempt.url()),
);
match wanted {
Ok(wanted) if grants.iter().any(|g| g.covers(&wanted)) => attempt.follow(),
Ok(wanted) => attempt.error(RedirectDenied(wanted.to_string())),
Err(error) => attempt.error(error),
}
});
let client = ide_http::client::build_with_redirect(&ide_core::proxy_settings::proxy(), policy)
.map_err(|e| HostError::Failed(e.message))?;
let builder = client.request(method, &request.url).headers(headers);
Ok(match request.body {
Some(body) => builder.body(body),
None => builder,
})
}
pub(super) fn approved_program_in_project(&self, program: &str, root: Option<&Path>) -> Result<PathBuf, HostError> {
if let Some(pin) = root.and_then(|root| {
self.shared.project_pins.read().get(&(self.id().into(), format!("process:{program}"), root.into())).cloned()
@@ -2838,52 +2891,14 @@ impl HostApi for PluginApi {
}
fn fetch(&self, request: HttpRequest, cancel: &CancellationToken) -> Result<HttpResponse, HostError> {
let secrets = self.shared.secrets.read().clone();
let id = self.id().to_owned();
let mut headers = reqwest::header::HeaderMap::new();
for (name, value) in &request.headers {
let value = fill_secrets(value, |n| secrets.get(&id, n))?;
let name = reqwest::header::HeaderName::from_bytes(name.as_bytes())
.map_err(|e| HostError::Invalid(format!("header {name:?}: {e}")))?;
let mut value = reqwest::header::HeaderValue::from_str(&value)
.map_err(|e| HostError::Invalid(format!("header {name}: {e}")))?;
value.set_sensitive(true);
headers.append(name, value);
}
let method = reqwest::Method::from_bytes(request.method.to_ascii_uppercase().as_bytes())
.map_err(|_| HostError::Invalid(format!("method {:?}", request.method)))?;
let grants = request.grants.clone();
let policy = reqwest::redirect::Policy::custom(move |attempt| {
if attempt.previous().len() >= 10 {
return attempt.error("too many redirects");
}
let wanted = attempt.previous().last().map_or_else(
|| ide_plugin::net_capability(attempt.url().as_str()),
|from| redirect_capability(from, attempt.url()),
);
match wanted {
Ok(wanted) if grants.iter().any(|g| g.covers(&wanted)) => attempt.follow(),
Ok(wanted) => attempt.error(RedirectDenied(wanted.to_string())),
Err(error) => attempt.error(error),
}
});
let client = ide_http::client::build_with_redirect(&ide_core::proxy_settings::proxy(), policy)
.map_err(|e| HostError::Failed(e.message))?;
let builder = client.request(method, &request.url).headers(headers).timeout(request.timeout);
let builder = match request.body {
Some(body) => builder.body(body),
None => builder,
};
let timeout = request.timeout;
let builder = self.http_request(request)?.timeout(timeout);
let cancel = cancel.clone();
net_runtime().block_on(async move {
let send = async {
let response = builder.send().await.map_err(network_error)?;
let status = response.status().as_u16();
let headers = response
.headers()
.iter()
.map(|(k, v)| (k.as_str().to_owned(), String::from_utf8_lossy(v.as_bytes()).into_owned()))
.collect();
let headers = response_headers(&response);
let mut body = Vec::new();
let mut response = response;
while let Some(chunk) = response.chunk().await.map_err(|e| HostError::Failed(e.to_string()))? {
@@ -2901,6 +2916,40 @@ impl HostApi for PluginApi {
})
}
fn fetch_stream(&self, request: HttpRequest, cancel: &CancellationToken) -> Result<HttpStreamHead, HostError> {
self.shared.http_streams.check(self.id())?;
// Only the wait for the headers is bounded: the body may keep coming.
let timeout = request.timeout;
let builder = self.http_request(request)?;
let cancel = cancel.clone();
let response = net_runtime().block_on(async move {
tokio::select! {
r = tokio::time::timeout(timeout, builder.send()) => r
.map_err(|_| HostError::Failed("timed out waiting for the response headers".into()))?
.map_err(network_error),
() = cancel.cancelled() => Err(HostError::Cancelled),
}
})?;
let status = response.status().as_u16();
let headers = response_headers(&response);
let id = self.shared.http_streams.insert(self.id(), response)?;
Ok(HttpStreamHead { id, status, headers })
}
fn http_stream_read(
&self,
id: u64,
max: usize,
timeout: Duration,
cancel: &CancellationToken,
) -> Result<(Vec<u8>, bool), HostError> {
self.shared.http_streams.read(self.id(), id, max, timeout, cancel)
}
fn http_stream_close(&self, id: u64) {
self.shared.http_streams.close(self.id(), id);
}
fn websocket_connect(
&self,
root: &Path,
+112
Переглянути файл
@@ -0,0 +1,112 @@
//! Plugin-owned HTTP response bodies read as they arrive (`net.fetch-stream`),
//! closed on resource drop and plugin shutdown.
use super::api::net_runtime;
use ide_core::CancellationToken;
use ide_plugin::HostError;
use parking_lot::Mutex;
use std::collections::HashMap;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::Duration;
/// Most response streams one plugin keeps open at once.
const MAX_STREAMS: usize = 8;
struct Body {
response: reqwest::Response,
/// The part of the last chunk the plugin hasn't read yet.
pending: Vec<u8>,
done: bool,
}
struct Stream {
body: tokio::sync::Mutex<Body>,
closed: CancellationToken,
}
#[derive(Default)]
pub(super) struct HttpStreams {
next: AtomicU64,
entries: Mutex<HashMap<(String, u64), Arc<Stream>>>,
}
impl HttpStreams {
/// Fails when `plugin` already has the most streams open.
pub fn check(&self, plugin: &str) -> Result<(), HostError> {
if self.entries.lock().keys().filter(|(p, _)| p == plugin).count() >= MAX_STREAMS {
Err(HostError::Invalid("at most eight response streams per plugin".into()))
} else {
Ok(())
}
}
pub fn insert(&self, plugin: &str, response: reqwest::Response) -> Result<u64, HostError> {
let mut entries = self.entries.lock();
if entries.keys().filter(|(p, _)| p == plugin).count() >= MAX_STREAMS {
return Err(HostError::Invalid("at most eight response streams per plugin".into()));
}
let id = self.next.fetch_add(1, Ordering::Relaxed);
let body = Body { response, pending: Vec::new(), done: false };
entries.insert(
(plugin.into(), id),
Arc::new(Stream { body: tokio::sync::Mutex::new(body), closed: CancellationToken::new() }),
);
Ok(id)
}
pub fn read(
&self,
plugin: &str,
id: u64,
max: usize,
timeout: Duration,
cancel: &CancellationToken,
) -> Result<(Vec<u8>, bool), HostError> {
let entry = self
.entries
.lock()
.get(&(plugin.into(), id))
.cloned()
.ok_or_else(|| HostError::NotFound("response stream".into()))?;
net_runtime().block_on(async {
let read = async {
let mut body = entry.body.lock().await;
// `chunk` takes nothing until it is ready, so a timeout that drops
// this future in the middle loses no bytes.
if body.pending.is_empty() && !body.done {
match body.response.chunk().await {
Ok(Some(chunk)) => body.pending = chunk.to_vec(),
Ok(None) => body.done = true,
Err(e) => return Err(HostError::Failed(ide_http::client::describe(&e))),
}
}
let count = body.pending.len().min(max);
let bytes: Vec<u8> = body.pending.drain(..count).collect();
Ok((bytes, body.done && body.pending.is_empty()))
};
tokio::select! {
biased;
() = cancel.cancelled() => Err(HostError::Cancelled),
() = entry.closed.cancelled() => Err(HostError::Cancelled),
r = read => r,
() = tokio::time::sleep(timeout) => Ok((Vec::new(), false)),
}
})
}
pub fn close(&self, plugin: &str, id: u64) {
if let Some(entry) = self.entries.lock().remove(&(plugin.into(), id)) {
entry.closed.cancel();
}
}
pub fn clear(&self, plugin: &str) {
self.entries.lock().retain(|(p, _), entry| {
if p != plugin {
return true;
}
entry.closed.cancel();
false
});
}
}
+1
Переглянути файл
@@ -31,6 +31,7 @@ mod execution;
mod external_watch;
mod files_changed;
mod hover;
mod http_stream;
mod icon_extensions;
mod icon_patterns;
mod icon_settings;
+17
Переглянути файл
@@ -57,6 +57,8 @@ pub struct Project {
pub(crate) java_launches: crate::ops::java::cache::Sessions,
/// Reasons this window was already told why Kotlin is debugged with kotlin-debug-adapter.
pub(crate) kotlin_debug_notices: Mutex<HashSet<&'static str>>,
/// Files each Xcode configuration's last `xcodebuild` reported problems in, by configuration id.
pub(crate) xcodebuild_problems: Arc<Mutex<HashMap<String, Vec<PathBuf>>>>,
/// The completion only some plugins asked to complete again ([`crate::ops::lsp::lsp_completion`]).
pub(crate) completion_session: Mutex<Option<crate::ops::lsp::CompletionSession>>,
/// Database tool window: data sources and their connections.
@@ -708,6 +710,7 @@ impl Host {
cache_dir: self.local_data_dir.join("cache").join(&project_key),
java_launches: Default::default(),
kotlin_debug_notices: Mutex::default(),
xcodebuild_problems: Arc::default(),
completion_session: Mutex::default(),
db,
http_history,
@@ -874,6 +877,19 @@ impl Host {
plugin_dirs,
}
}));
let mem_settings = settings.clone();
let mem_root = root.clone();
let mem_trust = self.trust.clone();
agents.set_memory_policy_hook(Box::new(move || {
let layer = |scope| mem_settings.layer(scope).agents.memory.clone();
let workspace_trusted = mem_trust.window_trusted(&mem_root).unwrap_or(false);
ide_agent::memory::MemoryPolicy {
user: layer(ide_workspace::settings::SettingsScope::Global),
workspace: layer(ide_workspace::settings::SettingsScope::Project),
workspace_trusted,
workspace_roots: crate::ops::agent::workspace_skill_roots(&mem_root),
}
}));
agents.set_mcp_servers_hook(Box::new(move || {
crate::ops::agent::session_mcp_servers(&settings, &approvals, &secrets, &root)
}));
@@ -989,6 +1005,7 @@ impl Host {
cache_dir: self.local_data_dir.join("cache").join(&project_key),
java_launches: Default::default(),
kotlin_debug_notices: Mutex::default(),
xcodebuild_problems: Arc::default(),
completion_session: Mutex::default(),
db,
http_history,
+1
Переглянути файл
@@ -385,6 +385,7 @@ pub fn client_accepts(event: &IdeEvent, trusted: bool) -> bool {
| IdeEvent::LspRefresh { .. }
| IdeEvent::LspMessageRequest { .. }
| IdeEvent::LspMessageRequestDone { .. }
| IdeEvent::LspShowDocument { .. }
| IdeEvent::TerminalExited { .. }
| IdeEvent::RunExited { .. }
| IdeEvent::Debug { .. }
+166
Переглянути файл
@@ -1744,3 +1744,169 @@ async fn a_run_started_without_confirmation_works_in_a_background_project_and_ho
let loaded = h.host.mcp_background.snapshot(&h.host, std::time::Instant::now()).remove(0);
assert_eq!(loaded.kept_open_by, None, "the call is over and the run has exited");
}
#[tokio::test(flavor = "multi_thread")]
async fn debugger_tools_are_registered_with_their_expected_metadata() {
let h = Harness::new();
h.trust().await;
let tools = Registry::new(h.host.clone()).tools(&h.root).unwrap();
let names: Vec<&str> = tools.iter().map(|t| t.name.as_str()).collect();
for name in [
"xdebug_get_debugger_status",
"xdebug_start_debugger_session",
"xdebug_control_session",
"xdebug_list_breakpoints",
"xdebug_set_breakpoint",
"xdebug_remove_breakpoint",
"xdebug_run_to_line",
"xdebug_get_threads",
"xdebug_get_stack",
"xdebug_get_frame_values",
"xdebug_get_value_by_path",
"xdebug_evaluate_expression",
"xdebug_set_variable",
] {
assert!(names.contains(&name), "{name} is not registered");
}
let status = tools.iter().find(|t| t.name == "xdebug_get_debugger_status").unwrap();
assert!(status.read_only && !status.destructive);
let start = tools.iter().find(|t| t.name == "xdebug_start_debugger_session").unwrap();
assert!(!start.read_only && !start.destructive);
let control = tools.iter().find(|t| t.name == "xdebug_control_session").unwrap();
assert_eq!(control.input_schema["required"], json!(["action"]));
let set = tools.iter().find(|t| t.name == "xdebug_set_breakpoint").unwrap();
assert_eq!(set.input_schema["required"], json!([]));
}
/// Answers the debugger's breakpoint requests the way the editor does: it applies the edit to
/// its current list and mirrors it to the backend.
fn debugger_window(h: &Harness) {
use ide_core::event::McpUiRequest;
h.host.mcp_requests.set_ready("main", true);
let (host, events) = (h.host.clone(), h.events.clone());
tokio::spawn(async move {
let mut handled = std::collections::HashSet::new();
loop {
let request = events.lock().unwrap().iter().find_map(|e| match e {
IdeEvent::McpRequest { id, request }
if !handled.contains(id)
&& matches!(
request,
McpUiRequest::SetBreakpoint { .. }
| McpUiRequest::RemoveBreakpoints { .. }
| McpUiRequest::FlushBreakpoints
) =>
{
Some((*id, request.clone()))
}
_ => None,
});
let Some((id, request)) = request else {
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
continue;
};
handled.insert(id);
let owner = host.owner_window("main").to_owned();
let (mut files, _, _) = host.debugger.breakpoints(&owner);
match request {
McpUiRequest::SetBreakpoint { path, breakpoint } => {
let path = PathBuf::from(path);
let line = breakpoint.line - 1;
let bps = files.entry(path).or_default();
bps.retain(|b| b.line != line);
bps.push(ide_dap::Breakpoint {
line,
condition: breakpoint.condition,
hit_condition: breakpoint.hit_condition,
log_message: breakpoint.log_message,
enabled: breakpoint.enabled,
});
bps.sort_by_key(|b| b.line);
}
McpUiRequest::RemoveBreakpoints { path, line } => match path {
Some(path) => {
if let Some(bps) = files.get_mut(&PathBuf::from(path)) {
match line {
Some(line) => bps.retain(|b| b.line != line - 1),
None => bps.clear(),
}
}
}
None => files.clear(),
},
McpUiRequest::FlushBreakpoints => {}
_ => unreachable!(),
}
host.debugger.replace_breakpoints(&owner, files).await.unwrap();
let _ = host.mcp_requests.answer("main", id, true, None);
}
});
}
#[tokio::test(flavor = "multi_thread")]
async fn debugger_status_and_session_calls_without_a_session() {
let h = Harness::new();
h.trust().await;
assert_eq!(h.json("xdebug_get_debugger_status", json!({})).await, json!({"sessions": [], "activeSessionId": null}));
let err = h.error("xdebug_control_session", json!({"action": "RESUME"})).await;
assert!(err.contains("no active debug session"), "{err}");
let err = h.error("xdebug_start_debugger_session", json!({})).await;
assert!(err.contains("Pass either configurationName or filePath + line"), "{err}");
}
#[tokio::test(flavor = "multi_thread")]
async fn debugger_breakpoints_can_be_set_listed_and_removed() {
let h = Harness::new();
h.trust().await;
debugger_window(&h);
std::fs::write(h.root.join("src/main.py"), "first\nsecond\nthird\n").unwrap();
let set =
h.json("xdebug_set_breakpoint", json!({"filePath": "src/main.py", "line": 2, "condition": "x > 1"})).await;
assert_eq!(set["id"], "line:src/main.py:2");
assert_eq!(set["line"], 2);
assert_eq!(set["lineText"], "second");
assert_eq!(set["verified"], false);
let listed = h.json("xdebug_list_breakpoints", json!({"filePath": "src/main.py"})).await;
let breakpoints = listed["breakpoints"].as_array().unwrap();
assert_eq!(breakpoints.len(), 1);
assert_eq!(breakpoints[0]["condition"], "x > 1");
assert_eq!(breakpoints[0]["enabled"], true);
// Updating one field leaves the others alone.
h.json("xdebug_set_breakpoint", json!({"breakpointId": "line:src/main.py:2", "enabled": false})).await;
let listed = h.json("xdebug_list_breakpoints", json!({"filePath": "src/main.py"})).await;
let breakpoints = listed["breakpoints"].as_array().unwrap();
assert_eq!(breakpoints[0]["condition"], "x > 1");
assert_eq!(breakpoints[0]["enabled"], false);
let removed = h.json("xdebug_remove_breakpoint", json!({"breakpointId": "line:src/main.py:2"})).await;
assert_eq!(removed["removed"], true);
assert_eq!(removed["count"], 1);
let listed = h.json("xdebug_list_breakpoints", json!({})).await;
assert_eq!(listed["breakpoints"].as_array().unwrap().len(), 0);
// Removing a missing breakpoint is idempotent.
let removed = h.json("xdebug_remove_breakpoint", json!({"breakpointId": "line:src/main.py:2"})).await;
assert_eq!(removed["removed"], false);
}
#[tokio::test(flavor = "multi_thread")]
async fn debugger_breakpoints_update_by_id_and_clear_by_file() {
let h = Harness::new();
h.trust().await;
debugger_window(&h);
std::fs::write(h.root.join("src/main.py"), "first\nsecond\nthird\n").unwrap();
h.json("xdebug_set_breakpoint", json!({"filePath": "src/main.py", "line": 1})).await;
h.json("xdebug_set_breakpoint", json!({"filePath": "src/main.py", "line": 3})).await;
let updated = h
.json(
"xdebug_set_breakpoint",
json!({"breakpointId": "line:src/main.py:3", "enabled": false, "condition": null}),
)
.await;
assert_eq!(updated["line"], 3);
let listed = h.json("xdebug_list_breakpoints", json!({"filePath": "src/main.py"})).await;
let breakpoints = listed["breakpoints"].as_array().unwrap();
assert_eq!(breakpoints.len(), 2);
assert_eq!(breakpoints[1]["enabled"], false);
assert_eq!(breakpoints[1]["condition"], Value::Null);
let removed = h.json("xdebug_remove_breakpoint", json!({"owner": "agent"})).await;
assert_eq!(removed["count"], 2);
}
+52
Переглянути файл
@@ -6545,6 +6545,58 @@ fn api14_denies_new_privileges_and_requires_an_invoking_window() {
assert_eq!(f.host.declared_secret("api14", "token"), None);
}
/// `net.fetch-stream`: the body is read as it arrives, so a plugin gets the
/// first server-sent event while the server is still sending (here it never
/// finishes), and a short body ends with `done`. The same grants as `fetch`.
#[test]
fn fetch_stream_reads_events_before_the_body_ends() {
use std::io::{BufRead, BufReader, Write};
let f = fixture(Limits::default());
f.host.install_from_dir(&sample("api14"), &Consent::default()).unwrap();
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let port = listener.local_addr().unwrap().port();
std::thread::spawn(move || {
for (n, stream) in listener.incoming().flatten().enumerate() {
std::thread::spawn(move || {
let mut reader = BufReader::new(stream.try_clone().unwrap());
let mut line = String::new();
while reader.read_line(&mut line).unwrap_or(0) > 0 && line != "\r\n" {
line.clear();
}
let mut stream = stream;
let chunk = |stream: &mut std::net::TcpStream, s: &str| {
write!(stream, "{:x}\r\n{s}\r\n", s.len()).and_then(|()| stream.flush())
};
let _ = write!(
stream,
"HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nTransfer-Encoding: chunked\r\n\r\n"
);
let _ = chunk(&mut stream, "data: one\n\nevent: delta\ndata: t");
if n == 0 {
// Never ends: only streaming lets the plugin see "one" in time.
std::thread::sleep(Duration::from_secs(30));
return;
}
let _ = chunk(&mut stream, "wo\n\n");
let _ = write!(stream, "0\r\n\r\n");
});
}
});
let url = format!("http://localhost:{port}/events");
let err = f.run("api14", "fetch-stream", Some(&format!("1 {url}"))).unwrap_err();
assert!(err.contains("net:localhost") && err.contains("not granted"), "{err}");
f.host.set_capability("api14", "net:localhost", true).unwrap();
let started = std::time::Instant::now();
let out = f.run("api14", "fetch-stream", Some(&format!("1 {url}"))).unwrap();
assert_eq!(out.as_deref(), Some("200|message:one"));
assert!(started.elapsed() < Duration::from_secs(10), "{:?}", started.elapsed());
let out = f.run("api14", "fetch-stream", Some(&format!("3 {url}"))).unwrap();
assert_eq!(out.as_deref(), Some("200|message:one|delta:two|done"));
}
/// `net:ask`: a first request to a host outside the manifest asks the user
/// from an invoking window ("once" allows this request, "always" remembers
/// the host, refusal and dismissal deny). Background calls are denied without
+1 -1
Переглянути файл
@@ -22,7 +22,7 @@ pub fn client_capabilities() -> Value {
"window": {
"workDoneProgress": true,
"showMessage": { "messageActionItem": { "additionalPropertiesSupport": false } },
"showDocument": { "support": false }
"showDocument": { "support": true }
},
"workspace": {
"applyEdit": true,
+59 -1
Переглянути файл
@@ -633,6 +633,32 @@ fn tsserver_ran_out_of_memory(text: &str) -> bool {
})
}
/// The UI event for a `window/showDocument` request, or `None` when it can't be shown: an
/// external target that isn't a web link, or a file that doesn't exist.
fn show_document_event(params: &Value) -> Option<IdeEvent> {
let uri = params.get("uri").and_then(Value::as_str)?.to_owned();
let take_focus = params.get("takeFocus").and_then(Value::as_bool).unwrap_or(false);
if params.get("external").and_then(Value::as_bool).unwrap_or(false) {
let scheme = uri.split_once(':')?.0.to_ascii_lowercase();
return matches!(scheme.as_str(), "http" | "https" | "mailto").then_some(IdeEvent::LspShowDocument {
uri,
path: None,
selection: None,
take_focus,
});
}
let path = uri_to_path(&uri).filter(|p| p.is_file())?;
// Columns are UTF-16, the only position encoding we advertise.
let selection =
params.get("selection").cloned().and_then(|r| serde_json::from_value::<lsp::Range>(r).ok()).map(|r| {
ide_core::Range::new(
ide_core::Pos::new(r.start.line, r.start.character),
ide_core::Pos::new(r.end.line, r.end.character),
)
});
Some(IdeEvent::LspShowDocument { uri, path: Some(path.into()), selection, take_focus })
}
impl Handler for ClientHandler {
fn normalize_incoming(&self, message: &mut Value) {
crate::uri::encode_loose_file_uris(message);
@@ -731,7 +757,14 @@ impl Handler for ClientHandler {
match method {
"window/workDoneProgress/create" => Ok(Value::Null),
"window/showMessageRequest" => self.message_request(&mgr, &params),
"window/showDocument" => Ok(json!({ "success": false })),
"window/showDocument" => {
let event = show_document_event(&params);
let success = event.is_some();
if let Some(event) = event {
mgr.sink().emit(event);
}
Ok(json!({ "success": success }))
}
"workspace/configuration" => Ok(self.configuration(&params)),
"workspace/workspaceFolders" => Ok(mgr.workspace_folders(&self.server)),
"client/registerCapability" => {
@@ -847,6 +880,31 @@ mod tests {
assert_eq!(left, [("rustc E0308", 1), ("rust-analyzer E0308", 5), ("rust-analyzer unused_variables", 1)]);
}
#[test]
fn show_document_opens_existing_files_and_web_links() {
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("Expansion.swift");
std::fs::write(&file, "struct S {}\n").unwrap();
let uri = crate::uri::path_to_uri_string(&file);
let range = json!({ "start": { "line": 1, "character": 2 }, "end": { "line": 3, "character": 4 } });
let Some(IdeEvent::LspShowDocument { path, selection, take_focus, .. }) =
show_document_event(&json!({ "uri": uri, "selection": range, "takeFocus": true }))
else {
panic!("expected a show-document event");
};
assert_eq!(&*path.unwrap(), file.as_path());
assert_eq!(selection, Some(ide_core::Range::new(ide_core::Pos::new(1, 2), ide_core::Pos::new(3, 4))));
assert!(take_focus);
let missing = crate::uri::path_to_uri_string(&dir.path().join("gone.swift"));
assert!(show_document_event(&json!({ "uri": missing })).is_none());
assert!(matches!(
show_document_event(&json!({ "uri": "https://example.com", "external": true })),
Some(IdeEvent::LspShowDocument { path: None, take_focus: false, .. })
));
assert!(show_document_event(&json!({ "uri": uri, "external": true })).is_none());
}
#[test]
fn tsserver_aborts_are_out_of_memory() {
assert!(tsserver_ran_out_of_memory("TSServer exited. Code: 134. Signal: null"));
+15
Переглянути файл
@@ -4523,6 +4523,21 @@ impl LspManager {
}
}
/// Stops `server` on request. It stays down until a document it serves is opened again,
/// which starts it like any first start.
pub async fn stop(&self, server: ide_core::ServerId) -> IdeResult<()> {
let _reconfigure = self.reconfigure_lock.lock().await;
let s = self
.servers
.lock()
.iter()
.find(|s| s.id == server)
.cloned()
.ok_or_else(|| IdeError::not_found(format!("unknown language server {server}")))?;
self.stop_instance(&s, true).await;
Ok(())
}
/// Gracefully stops the current instance (`shutdown` + `exit`, then kill).
async fn stop_instance(&self, server: &Arc<Server>, final_stop: bool) {
let Some(run) = server.begin_stop(&self.sink, final_stop) else {
+23
Переглянути файл
@@ -4990,6 +4990,29 @@ async fn features_limit_what_a_server_is_used_for() {
assert!(!h.events.lock().iter().any(|e| matches!(e, IdeEvent::Diagnostics { source, .. } if source == "rope")));
}
#[tokio::test(flavor = "multi_thread")]
async fn a_stopped_server_starts_again_when_a_file_it_serves_opens() {
let h = harness(&[("mock", incremental_caps())]);
let (_, a) = h.open("a.mk", "x");
h.wait_status("mock", ServerStatus::Ready).await;
let s = h.launcher.state("mock");
let id = h.mgr.servers()[0].id;
tokio::time::timeout(Duration::from_secs(5), h.mgr.stop(id)).await.unwrap().unwrap();
assert_eq!(s.requested("shutdown").len(), 1);
assert_eq!(s.notified("exit").len(), 1);
assert_eq!(h.statuses("mock").last(), Some(&ServerStatus::Stopped));
tokio::time::sleep(Duration::from_millis(100)).await;
assert_eq!(s.launches.load(Ordering::SeqCst), 1, "stays down until needed");
let (_, b) = h.open("b.mk", "y");
h.wait_status("mock", ServerStatus::Ready).await;
assert_eq!(s.launches.load(Ordering::SeqCst), 2);
let opened: Vec<Value> =
s.notified("textDocument/didOpen").iter().map(|p| p["textDocument"]["uri"].clone()).collect();
assert!(opened.contains(&json!(uri_of(&a))) && opened.contains(&json!(uri_of(&b))), "{opened:?}");
h.mgr.shutdown_all().await;
}
#[tokio::test(flavor = "multi_thread")]
async fn shutdown_all_stops_gracefully() {
let h = harness(&[("mock", incremental_caps())]);
+17 -3
Переглянути файл
@@ -8,9 +8,9 @@ use crate::types::{
PluginHover, PluginInlayHint, ProviderDocument, SemanticToken,
};
use crate::types::{
EventKind, HostError, HttpRequest, HttpResponse, Invocation, Limits, NotificationLevel, ProcessChunk,
ProcessCommand, ProcessOutput, Prompt, RepositoryStatus, StatusItem, SyntaxFold, SyntaxSymbol, SyntaxToken,
WorkbenchEvent,
EventKind, HostError, HttpRequest, HttpResponse, HttpStreamHead, Invocation, Limits, NotificationLevel,
ProcessChunk, ProcessCommand, ProcessOutput, Prompt, RepositoryStatus, StatusItem, SyntaxFold, SyntaxSymbol,
SyntaxToken, WorkbenchEvent,
};
use crate::types::{
FieldValue, ServiceLog, ServiceLogToggle, ServicePane, ServiceTab, TableSort, View, ViewBody, ViewButton,
@@ -365,6 +365,20 @@ pub trait HostApi: Send + Sync {
fn publish_diagnostics(&self, path: &Path, items: Vec<ide_core::Diagnostic>) -> Result<(), HostError>;
/// Performs `request` (its host is granted), filling in secret placeholders.
fn fetch(&self, request: HttpRequest, cancel: &CancellationToken) -> Result<HttpResponse, HostError>;
/// As [`HostApi::fetch`], returning once the headers arrive (`request.timeout`
/// bounds only that wait); the body is read with [`HostApi::http_stream_read`].
fn fetch_stream(&self, request: HttpRequest, cancel: &CancellationToken) -> Result<HttpStreamHead, HostError>;
/// The next body bytes of an owned stream, at most `max`: empty and not done
/// when nothing arrived within `timeout`; `true` once the body has ended.
fn http_stream_read(
&self,
id: u64,
max: usize,
timeout: Duration,
cancel: &CancellationToken,
) -> Result<(Vec<u8>, bool), HostError>;
/// Closes an owned stream, including when its resource is dropped.
fn http_stream_close(&self, id: u64);
fn websocket_connect(
&self,
+9
Переглянути файл
@@ -574,6 +574,15 @@ pub struct HttpResponse {
pub body: Vec<u8>,
}
/// A response whose body is still arriving (WIT `net.response-stream`).
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct HttpStreamHead {
/// Owned by this plugin instance; read with [`crate::HostApi::http_stream_read`].
pub id: u64,
pub status: u16,
pub headers: Vec<(String, String)>,
}
/// What a one-off process printed (WIT `process.output`).
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct ProcessOutput {
+96 -19
Переглянути файл
@@ -27,6 +27,7 @@ pub(crate) mod bindings {
"openidea:plugin/process.child": super::ChildRes,
"openidea:plugin/ipc.connection": super::ConnectionRes,
"openidea:plugin/net.websocket": super::WebSocketRes,
"openidea:plugin/net.response-stream": super::ResponseStreamRes,
"openidea:plugin/auth.loopback": super::LoopbackRes,
},
});
@@ -263,6 +264,21 @@ impl Drop for WebSocketRes {
}
}
/// A response body still arriving, owned by this plugin instance. Releasing
/// the component resource closes the connection.
pub struct ResponseStreamRes {
id: u64,
status: u16,
headers: Vec<(String, String)>,
host: std::sync::Arc<dyn crate::HostApi>,
}
impl Drop for ResponseStreamRes {
fn drop(&mut self) {
self.host.http_stream_close(self.id);
}
}
impl Drop for ChildRes {
fn drop(&mut self) {
self.host.release_process(self.id);
@@ -1866,12 +1882,11 @@ impl diagnostics::Host for StoreData {
}
}
impl net::Host for StoreData {
fn fetch(&mut self, req: net::Request) -> Fallible<net::Response> {
let capability = match net_capability(&req.url) {
Ok(h) => h,
Err(e) => return Ok(Err(wit::Error::Invalid(e))),
};
impl StoreData {
/// The host request for `req` once its grants (asking under `net:ask`),
/// secrets and body size are checked: shared by `fetch` and `fetch-stream`.
fn net_request(&mut self, req: net::Request) -> Result<HttpRequest, wit::Error> {
let capability = net_capability(&req.url).map_err(wit::Error::Invalid)?;
let mut grants = self.granted.clone();
if let Err(e) = self.require(capability.clone()) {
// `net:ask`: an HTTPS (or loopback) host the manifest does not list
@@ -1880,35 +1895,38 @@ impl net::Host for StoreData {
let askable =
matches!(&capability, Capability::Net(_)) && self.granted.iter().any(|g| g.covers(&Capability::NetAsk));
let allowed = match &capability {
Capability::Net(host) if askable => match self.ask_net(host) {
Ok(Some(_)) => true,
Ok(None) => false,
// A cancelled or failed question is not a refusal.
Err(e) => return Ok(Err(e)),
},
// A cancelled or failed question is not a refusal.
Capability::Net(host) if askable => self.ask_net(host)?.is_some(),
_ => false,
};
if !allowed {
return Ok(Err(e));
return Err(e);
}
grants.push(capability.clone());
}
if req.headers.iter().any(|h| h.value.contains("{{secret:"))
&& let Err(e) = self.require(Capability::Secrets)
{
return Ok(Err(e));
if req.headers.iter().any(|h| h.value.contains("{{secret:")) {
self.require(Capability::Secrets)?;
}
if req.body.as_ref().is_some_and(|b| b.len() > MAX_REQUEST_BODY) {
return Ok(Err(wit::Error::Invalid("request body larger than 8 MiB".into())));
return Err(wit::Error::Invalid("request body larger than 8 MiB".into()));
}
let wanted = Duration::from_millis(u64::from(req.timeout_ms.unwrap_or(30_000)));
let request = HttpRequest {
Ok(HttpRequest {
method: req.method,
url: req.url,
headers: req.headers.into_iter().map(|h| (h.name, h.value)).collect(),
body: req.body,
timeout: wanted.min(self.io_timeout()),
grants,
})
}
}
impl net::Host for StoreData {
fn fetch(&mut self, req: net::Request) -> Fallible<net::Response> {
let request = match self.net_request(req) {
Ok(request) => request,
Err(e) => return Ok(Err(e)),
};
let token = self.cancel.token();
let outcome = self.host.fetch(request, &token);
@@ -1924,6 +1942,28 @@ impl net::Host for StoreData {
.map_err(to_wit))
}
fn fetch_stream(&mut self, req: net::Request) -> Fallible<Resource<ResponseStreamRes>> {
let request = match self.net_request(req) {
Ok(request) => request,
Err(e) => return Ok(Err(e)),
};
let token = self.cancel.token();
match self.host.fetch_stream(request, &token) {
Ok(head) => self
.push(ResponseStreamRes {
id: head.id,
status: head.status,
headers: head.headers,
host: self.host.clone(),
})
.map(Ok),
Err(e) => {
self.grant_io_error_grace();
Ok(Err(to_wit(e)))
}
}
}
fn websocket_connect(
&mut self,
project: Resource<ProjectRes>,
@@ -1989,6 +2029,43 @@ impl net::HostWebsocket for StoreData {
}
}
impl net::HostResponseStream for StoreData {
fn status(&mut self, this: Resource<ResponseStreamRes>) -> wasmtime::Result<u16> {
Ok(self.table.get(&this)?.status)
}
fn headers(&mut self, this: Resource<ResponseStreamRes>) -> wasmtime::Result<Vec<net::Header>> {
let stream = self.table.get(&this)?;
Ok(stream
.headers
.iter()
.map(|(name, value)| net::Header { name: name.clone(), value: value.clone() })
.collect())
}
fn read(&mut self, this: Resource<ResponseStreamRes>, max_bytes: u32, timeout_ms: u32) -> Fallible<net::BodyChunk> {
let id = self.table.get(&this)?.id;
let timeout = Duration::from_millis(u64::from(timeout_ms)).min(self.io_timeout());
let max = (max_bytes as usize).min(1 << 20);
let outcome = self.host.http_stream_read(id, max, timeout, &self.cancel.token());
if outcome.is_err() {
self.grant_io_error_grace();
}
Ok(outcome.map(|(bytes, done)| net::BodyChunk { bytes, done }).map_err(to_wit))
}
fn close(&mut self, this: Resource<ResponseStreamRes>) -> wasmtime::Result<()> {
let id = self.table.get(&this)?.id;
self.host.http_stream_close(id);
Ok(())
}
fn drop(&mut self, this: Resource<ResponseStreamRes>) -> wasmtime::Result<()> {
self.table.delete(this)?;
Ok(())
}
}
impl secrets::Host for StoreData {
fn set(&mut self, name: String, value: String) -> Fallible<()> {
if let Err(e) = self.require(Capability::Secrets) {
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
1e6a4ba99409620e9bf3ceb51387704018737f186a89037b05bcbcee1e38a967
8a08e92c30faaa683e531fd91c8a69392d75165cff62153e216008f7abbcb1ea
+4
Переглянути файл
@@ -24,6 +24,10 @@ title = "ipc"
id = "fetch"
title = "fetch"
[[contributes.commands]]
id = "fetch-stream"
title = "fetch-stream"
[[contributes.commands]]
id = "window-status"
title = "window-status"
+15
Переглянути файл
@@ -73,6 +73,21 @@ impl Plugin for Api14 {
let response = host::fetch(&openidea_plugin::HttpRequest::get(arg))?;
Ok(Some(String::from_utf8_lossy(&response.body).into()))
}
"fetch-stream" => {
// `<count> <url>`: the first `count` events, then the stream is dropped.
let (count, url) = arg.split_once(' ').unwrap_or(("1", arg));
let stream = host::fetch_stream(&openidea_plugin::HttpRequest::get(url))?;
let mut out = vec![stream.status().to_string()];
let mut events = stream.events();
for _ in 0..count.parse::<usize>().unwrap_or(1) {
out.push(match events.next(5_000)? {
Some(event) => format!("{}:{}", event.event, event.data),
None if events.is_done() => "done".into(),
None => "timeout".into(),
});
}
Ok(Some(out.join("|")))
}
"global-status" | "window-status" => {
let item = StatusItem { text: arg.into(), tooltip: None, command: Some("events".into()) };
if id == "global-status" {
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
667622767aa8c75a44c1348f6d07979ecb7a2db7ede9613999b61658a58557f5
de08e41d78da65ee3de2c709112e8d8905b50432bd59af1701dd633f674fa121
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
689a9f36b9d13e0b57bd1540321a06da65837510fd9a37225776abd8baccfd7c
455c833fc7d02c083a1ae67d1df507f29581f77d7f8624ff562f1ce982efc730
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
0316df8c6f5fd4523f077c1a12d2d8af9592729a66a5a99a155dde42bb331e96
a891db4b18f175648ec47a6c1e20edde0ff266d38b37a1fd2acc8f95ddf0d5b4
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
6732e125bfefcfad1c5712516e05bdaff7ceea4e71994de45109086e252e5f72
30f99018d1c6e518fbc179b2090a7f65856e10b9bed4bb76e605d88acec86393
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
bb6c942f198534adf96354dd670c175f73954782f516762c564d157f5004b744
39e361f892aa0944bc3eac5a2a9f5a7133deced54ca28193f8d789eaccc1a326
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
fa0957c9041bc31f7dc5b58aa912fa83851e6f0058d055e9582950195a1015b4
f36cf494eb56ebb9d6459a0b84b854ce413eed79e563074bc850de3ee4a4bb2d
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
00ac40b08a5a39d4e011e9391732f19c20eb439a6f980b8d96334a5547c28666
ea314de1d7cdf468b69603bda1766c7361497c9a50fc3e43ab508592d1861fe7
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
82473da5332e96dc9ef3a82947cde59b0a5d6acd49f8baad7c4fcc46ed4284dc
218dbcd47abeb8ef4b06e13cbbfdd7e24790c11f27c352ce95cfbb6cba61a062
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
8532a968b8522e9b1b6f0df3aed073191e2a441ab960f96af79d7132fda4090a
78bad0a6062a0131527a700e0b75ca24fd96162e8fe326b45b5a96c8da8723b4
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
ee0f3be61a8684275dc15acfdfe374b6d1751078d15c92608ba39ccbc6e10c67
f90db44c3df10b60fca9e337eba1d3269d8299ca06f5e60cbd9ab7dd65d32fba
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
4a3602e6024dcbeccb59ef9b324bab3e3254c908a7513c4f08bcbd212e368f9f
72aac6f440205694028e52df9932340131f6f30d89fbe3e9363a97110c912336
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
bd6aa162f07d96a580a8891433fd042e08a976f0f3ce4aee7694957ad394057c
366172ef7c2d4d2d218d3a653763852983b0af21e7e79ee644c4c216b64b2665
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
edac72326d401c873394ff0de9a659d5f3642259df136b87fb9b6cfe632e60c5
3eac3cab007df8f12e89b044f02348f564a5ec53376743ffccaacc6df383fd37
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
7454788469a0c0662987a4a774d8fc59b20b0dfec9bbac754e8e4aa0a46a1b43
3dab8c8f0177ab0de22a6daccc374c7aaa7e37f6959815edee5641d45bffa3ab
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
268b18f9303602b00f5c0d7254967aeb95c377b5a85011ead539b4ccab5811e2
834b90f241c89b7f24217f4ea579810de703da23806b7e21113df5a43ea20dbb
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
9e8809f276ef27561fe337f8268b3cf4f06be7ac1707a61e6e41407ec932bbb1
dbff03557f56e4483e8770c1dcca455c78f4331265613a93475ee28a8c581d79
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
c4594d365423395722e7f8e14f6d9c32ad4ff579b2eb42f5e2c5650e7cfa6bdc
e674c90857e859a6a7684f9d7899dbdf05f9fe5d310ed809def6bf5403877bda
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
91b267d3845bbd199662c0857ee23634a1d1b287204ce81fa148f1ce43eace3b
0e856198f5839dc675afcc883b43aa9c950c4f73807fe0b1145d976e00bbf2f4
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
8e5c91ab272fa1678fbef9607f12513f7a589ef3fd293cfd7a52497cf637de3d
b693136d64688418665ef010b5cb83b86fc4b0adc052b7783530cc53d863085e
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
a2e19194ba5f42e9d02d996c77444e8a5267fecc99bb02933f35aabb22fddadd
cb07913a6a7a1f61521818ffada5b59b8b30e08bc5ef3ed21a9d3a1924ac4445
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
78a9be879f2a07417c26a0818d2896ba6d93ea60bed69f3ebaf963ea1842147b
47642c0e293829c19528d85d6058b0ea08d68d3380032c4e04937322c88178a2
Бінарний файл не відображається.
Loaded 100 of 271 files, more files were not shown because too many files have changed in this diff. Show more