дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-27 21:12:34 +02:00
Порівняти коміти
200
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
ed46636417 | ||
|
|
83b14b4329 | ||
|
|
74eefd6116 | ||
|
|
a96c70f2a7 | ||
|
|
304503b9f1 | ||
|
|
06cf8fb16a | ||
|
|
521e00d075 | ||
|
|
b4cad6ec1b | ||
|
|
62e26fa7e3 | ||
|
|
1119467ab4 | ||
|
|
e1ce850a29 | ||
|
|
3e39368d43 | ||
|
|
b2a5ea1594 | ||
|
|
902d8ca257 | ||
|
|
92b5b5306f | ||
|
|
707cee9b0b | ||
|
|
d64be035c6 | ||
|
|
cb60c742fc | ||
|
|
b245335cc6 | ||
|
|
e13ed093ec | ||
|
|
aa0f8105af | ||
|
|
0adc816a56 | ||
|
|
ea29339b6b | ||
|
|
84854bed0e | ||
|
|
81b6cb7af6 | ||
|
|
ffe96c2ca2 | ||
|
|
33bd5372b6 | ||
|
|
44aeb95993 | ||
|
|
fa6b4be6f5 | ||
|
|
144cd90175 | ||
|
|
da3b621345 | ||
|
|
b301e2bbe1 | ||
|
|
feac919a1b | ||
|
|
0155d74084 | ||
|
|
130f75e7e8 | ||
|
|
2abd65aedd | ||
|
|
1b3e4fac6a | ||
|
|
72b0c7c48c | ||
|
|
25d1046af0 | ||
|
|
1cdb998532 | ||
|
|
b1ab5afa67 | ||
|
|
0101d11ac9 | ||
|
|
07d26722b1 | ||
|
|
df48d9271b | ||
|
|
cb6b7ccd3f | ||
|
|
13c0e8aa8d | ||
|
|
9f643af069 | ||
|
|
0c02a9e467 | ||
|
|
8c7bdc9bf2 | ||
|
|
a3f6d82391 | ||
|
|
bfde0ffc34 | ||
|
|
9067abf0cf | ||
|
|
4939b63c88 | ||
|
|
78d34af971 | ||
|
|
d47c9eb347 | ||
|
|
5348e42c59 | ||
|
|
a42eee29f4 | ||
|
|
a3e7142e4c | ||
|
|
d21fd65341 | ||
|
|
422f424b60 | ||
|
|
c10862b1a6 | ||
|
|
d4db49689e | ||
|
|
36ab40797c | ||
|
|
de7d62dce8 | ||
|
|
e3f9049e26 | ||
|
|
3e9f018cf4 | ||
|
|
e44d7fd396 | ||
|
|
dc490f1017 | ||
|
|
5289f44620 | ||
|
|
81aac31cc7 | ||
|
|
026163af9e | ||
|
|
ce03ae7c0f | ||
|
|
1cd8e8def5 | ||
|
|
a0b9fba2f2 | ||
|
|
1f6a3bbf0d | ||
|
|
5265455313 | ||
|
|
64cc72ba2e | ||
|
|
b79dbae83f | ||
|
|
e909c50fe4 | ||
|
|
da7125a944 | ||
|
|
e54e309d61 | ||
|
|
8c3371212c | ||
|
|
e08531c458 | ||
|
|
9c9e0e59cb | ||
|
|
1d5d33cf76 | ||
|
|
2bbba9b945 | ||
|
|
14f143b703 | ||
|
|
f2a372428c | ||
|
|
89524bd583 | ||
|
|
f90d94538d | ||
|
|
a4ad387085 | ||
|
|
f8a148c06d | ||
|
|
aa1a027162 | ||
|
|
b30716e22c | ||
|
|
7fb21003f3 | ||
|
|
ad8d32d9c7 | ||
|
|
08aef06844 | ||
|
|
3d5ec8a147 | ||
|
|
0f14314156 | ||
|
|
2413cc4b43 | ||
|
|
30291971e1 | ||
|
|
9f3d75976f | ||
|
|
72d9aad715 | ||
|
|
7264e7d66d | ||
|
|
10379a54f7 | ||
|
|
6564b9e6cb | ||
|
|
d437cd46f5 | ||
|
|
925d474274 | ||
|
|
89463afc18 | ||
|
|
c884aa4cc6 | ||
|
|
09108e02e3 | ||
|
|
2b6ca90457 | ||
|
|
3c3681ef2b | ||
|
|
b0d7bfef24 | ||
|
|
527add030a | ||
|
|
81c2fc9ace | ||
|
|
ef1b159544 | ||
|
|
7bfba926c2 | ||
|
|
1042f5fa56 | ||
|
|
fdad01034c | ||
|
|
6dddfde3bc | ||
|
|
0324bc368d | ||
|
|
96c6e65aad | ||
|
|
6eebd895ea | ||
|
|
cfad729dbd | ||
|
|
bd905c6689 | ||
|
|
7138becb3a | ||
|
|
6f7d2ce34d | ||
|
|
719961e34e | ||
|
|
11c432fc23 | ||
|
|
0b8698e47c | ||
|
|
f595a7abf0 | ||
|
|
fe7fa7d505 | ||
|
|
e998e2ca8e | ||
|
|
18424b322f | ||
|
|
daee26e680 | ||
|
|
5886e055b4 | ||
|
|
8d4b360933 | ||
|
|
f6704b53f6 | ||
|
|
91da88d09d | ||
|
|
5ab91245dd | ||
|
|
fb063c1f84 | ||
|
|
f926390d2e | ||
|
|
9b66744e72 | ||
|
|
071f768635 | ||
|
|
bbe9cf7a86 | ||
|
|
c10d2f0732 | ||
|
|
ec02a121e9 | ||
|
|
12eb2db641 | ||
|
|
2735d45d7e | ||
|
|
60262c92ba | ||
|
|
ca472742bf | ||
|
|
023408eb26 | ||
|
|
92c0e304cd | ||
|
|
3d534b447d | ||
|
|
89a3359aaf | ||
|
|
d88c4c87b6 | ||
|
|
197c7d6141 | ||
|
|
c61bb2b56d | ||
|
|
b9429858a6 | ||
|
|
c1e9707c7e | ||
|
|
a483ea77f4 | ||
|
|
de36b46660 | ||
|
|
5918605b2b | ||
|
|
f69d394480 | ||
|
|
eb078a0a19 | ||
|
|
5a884d7cba | ||
|
|
2ba2f33232 | ||
|
|
c9bb5a3169 | ||
|
|
bfbc70a438 | ||
|
|
e74edbcedc | ||
|
|
ebeb6476eb | ||
|
|
b8b245da5f | ||
|
|
5aeadcc888 | ||
|
|
edc750174b | ||
|
|
cdff357fdd | ||
|
|
de971848ab | ||
|
|
90cb56e9f8 | ||
|
|
baa0171d8a | ||
|
|
0d493fb515 | ||
|
|
a56add66ea | ||
|
|
2d568980c5 | ||
|
|
7920a4985e | ||
|
|
d6c7e7edc4 | ||
|
|
b1c69d1991 | ||
|
|
a869acdca2 | ||
|
|
fb3a037b7e | ||
|
|
dfaa784513 | ||
|
|
67e58f61b6 | ||
|
|
e75deb11c0 | ||
|
|
94b67515a5 | ||
|
|
a0b2678466 | ||
|
|
e3dc7e950b | ||
|
|
0a53c7b864 | ||
|
|
d4447c7aba | ||
|
|
9740edbfd4 | ||
|
|
b49b0e5c98 | ||
|
|
c88e379c8b | ||
|
|
db63c6c93b | ||
|
|
54a7962043 |
No files matched your search
@@ -156,6 +156,44 @@ jobs:
|
||||
- run: cargo clippy --workspace --all-targets -- -D warnings
|
||||
# Test fixtures write LF files; keep Git from converting them on checkout.
|
||||
- run: git config --global core.autocrlf false
|
||||
- name: Restore Maven artifacts for Java build tests
|
||||
id: jbuild-maven-cache
|
||||
if: runner.environment == 'github-hosted'
|
||||
uses: actions/cache/restore@v5
|
||||
with:
|
||||
path: ${{ runner.temp }}/jbuild-maven-repository
|
||||
key: jbuild-maven-${{ runner.os }}-${{ hashFiles('crates/ide-build/tests/fixtures/jbuild-maven/**/pom.xml') }}
|
||||
- name: Prepare Maven artifacts for Java build tests
|
||||
id: jbuild-maven
|
||||
if: runner.environment == 'github-hosted'
|
||||
timeout-minutes: 5
|
||||
shell: bash
|
||||
env:
|
||||
CACHE_HIT: ${{ steps.jbuild-maven-cache.outputs.cache-hit }}
|
||||
run: |
|
||||
if [[ -z "${JAVA_HOME:-}" || ! -d "$JAVA_HOME/bin" ]] || ! command -v mvn >/dev/null; then
|
||||
exit 0
|
||||
fi
|
||||
export MAVEN_OPTS="${MAVEN_OPTS:+$MAVEN_OPTS }-Dmaven.repo.local=$RUNNER_TEMP/jbuild-maven-repository"
|
||||
echo "MAVEN_OPTS=$MAVEN_OPTS" >> "$GITHUB_ENV"
|
||||
if [[ "$CACHE_HIT" == true ]]; then
|
||||
exit 0
|
||||
fi
|
||||
# The IDE also reads the compiler plugin descriptor when it builds the Maven model.
|
||||
for delay in 0 10 30; do
|
||||
sleep "$delay"
|
||||
if mvn -B -ntp -U -N -f crates/ide-build/tests/fixtures/jbuild-maven/pom.xml resources:resources compiler:compile; then
|
||||
echo "prepared=true" >> "$GITHUB_OUTPUT"
|
||||
exit 0
|
||||
fi
|
||||
done
|
||||
exit 1
|
||||
- name: Save Maven artifacts for Java build tests
|
||||
if: steps.jbuild-maven.outputs.prepared == 'true'
|
||||
uses: actions/cache/save@v5
|
||||
with:
|
||||
path: ${{ runner.temp }}/jbuild-maven-repository
|
||||
key: ${{ steps.jbuild-maven-cache.outputs.cache-primary-key }}
|
||||
- run: cargo nextest run --workspace --no-fail-fast
|
||||
- name: Remote backend with Docker Compose
|
||||
# Self-hosted runner containers do not mount /var/run/docker.sock (scripts/selfhost-runner/README.md).
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
name: Homebrew
|
||||
|
||||
# Updates the cask in the project tap, l0ng-ai/homebrew-tap (scripts/homebrew-cask.ts), so
|
||||
# `brew install --cask l0ng-ai/tap/openidea` installs the new release. Release runs it after
|
||||
# publishing; run it by hand to write the cask of an existing tag again. Skipped for prereleases
|
||||
# and without the HOMEBREW_TAP_TOKEN secret (contents: write on l0ng-ai/homebrew-tap).
|
||||
on:
|
||||
workflow_call:
|
||||
inputs:
|
||||
tag: { type: string, required: true }
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
tag:
|
||||
description: "Published stable release to write the cask for (e.g. v0.1.51)"
|
||||
required: true
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: homebrew-tap
|
||||
|
||||
jobs:
|
||||
cask:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
env:
|
||||
TAG: ${{ inputs.tag }}
|
||||
TAP: l0ng-ai/homebrew-tap
|
||||
HOMEBREW_TAP_TOKEN: ${{ secrets.HOMEBREW_TAP_TOKEN }}
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
steps:
|
||||
- name: Check tag and token
|
||||
id: check
|
||||
run: |
|
||||
if [[ ! "$TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
|
||||
echo "::notice::$TAG is not a stable release: the cask stays as is"
|
||||
echo "skip=true" >> "$GITHUB_OUTPUT"
|
||||
elif [ -z "$HOMEBREW_TAP_TOKEN" ]; then
|
||||
echo "::notice::HOMEBREW_TAP_TOKEN unset: not updating the cask for $TAG"
|
||||
echo "skip=true" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
- uses: actions/checkout@v5
|
||||
if: steps.check.outputs.skip != 'true'
|
||||
with: { sparse-checkout: scripts }
|
||||
- uses: actions/checkout@v5
|
||||
if: steps.check.outputs.skip != 'true'
|
||||
with:
|
||||
repository: ${{ env.TAP }}
|
||||
token: ${{ secrets.HOMEBREW_TAP_TOKEN }}
|
||||
path: tap
|
||||
- uses: actions/setup-node@v5
|
||||
if: steps.check.outputs.skip != 'true'
|
||||
with: { node-version: 22 }
|
||||
- name: Download DMGs
|
||||
if: steps.check.outputs.skip != 'true'
|
||||
run: gh release download "$TAG" -R "$GITHUB_REPOSITORY" -p '*.dmg' -D assets
|
||||
- name: Write the cask
|
||||
if: steps.check.outputs.skip != 'true'
|
||||
run: node scripts/homebrew-cask.ts "$TAG" assets tap/Casks/openidea.rb
|
||||
- name: Push to the tap
|
||||
if: steps.check.outputs.skip != 'true'
|
||||
working-directory: tap
|
||||
run: |
|
||||
git add Casks/openidea.rb
|
||||
if git diff --cached --quiet; then
|
||||
echo "the cask is already at ${TAG#v}"
|
||||
exit 0
|
||||
fi
|
||||
git config user.name "github-actions[bot]"
|
||||
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
|
||||
git commit -m "openidea ${TAG#v}"
|
||||
git push
|
||||
@@ -178,3 +178,10 @@ jobs:
|
||||
uses: ./.github/workflows/cnb-mirror.yml
|
||||
with: { tag: "${{ github.event.inputs.tag || github.ref_name }}" }
|
||||
secrets: inherit
|
||||
|
||||
# The cask in l0ng-ai/homebrew-tap; skipped for prereleases and without HOMEBREW_TAP_TOKEN.
|
||||
homebrew:
|
||||
needs: publish
|
||||
uses: ./.github/workflows/homebrew.yml
|
||||
with: { tag: "${{ github.event.inputs.tag || github.ref_name }}" }
|
||||
secrets: inherit
|
||||
+2
-21
@@ -149,27 +149,8 @@
|
||||
}
|
||||
},
|
||||
{
|
||||
"files": [
|
||||
"evals/**/*.ts",
|
||||
"perf/**/*.ts",
|
||||
"smoke/**/*.ts",
|
||||
"src/features/vcs/**/*.ts",
|
||||
"src/features/vcs/**/*.tsx",
|
||||
"src/features/run/**/*.ts",
|
||||
"src/features/run/**/*.tsx",
|
||||
"src/features/database/**/*.ts",
|
||||
"src/features/database/**/*.tsx",
|
||||
"src/features/analysis/**/*.ts",
|
||||
"src/features/analysis/**/*.tsx",
|
||||
"src/features/project-tree/**/*.ts",
|
||||
"src/features/project-tree/**/*.tsx",
|
||||
"src/features/http-client/**/*.ts",
|
||||
"src/features/http-client/**/*.tsx",
|
||||
"src/platform/**/*.ts",
|
||||
"src/platform/**/*.tsx",
|
||||
"src/features/debugger/**/*.ts",
|
||||
"src/features/debugger/**/*.tsx"
|
||||
],
|
||||
"files": ["**/*.ts", "**/*.tsx", "**/*.mts", "**/*.cts"],
|
||||
"excludeFiles": ["e2e/**"],
|
||||
"rules": {
|
||||
"no-await-in-loop": "error"
|
||||
}
|
||||
|
||||
Створено
+256
-196
File diff suppressed because it is too large.
Load diff
+2
-2
@@ -5,7 +5,7 @@ members = ["crates/*", "src-tauri"]
|
||||
exclude = ["sdk", "plugins"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.1.52"
|
||||
version = "0.1.53"
|
||||
edition = "2024"
|
||||
rust-version = "1.96"
|
||||
license = "Apache-2.0"
|
||||
@@ -108,7 +108,7 @@ jupyter-zmq-client = { version = "=2.0.0", default-features = false, features =
|
||||
jupyter-protocol = "=2.0.3"
|
||||
zeromq = { version = "0.6", default-features = false, features = ["tokio-runtime", "tcp-transport"] }
|
||||
lsp-types = "0.97"
|
||||
gix = { version = "0.89", default-features = false }
|
||||
gix = { version = "0.90", default-features = false }
|
||||
portable-pty = "0.9"
|
||||
reqwest = { version = "0.13", default-features = false, features = ["rustls-no-provider", "http2", "charset", "socks", "gzip", "deflate", "brotli"] }
|
||||
rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12", "logging"] }
|
||||
|
||||
@@ -33,6 +33,12 @@ its search-everything habits — to a native app with a Rust core.
|
||||
Editor, code insight, debugger, Git, terminal, database and HTTP clients,
|
||||
for 60+ languages. Builds for macOS, Windows and Linux.
|
||||
|
||||
On macOS you can also install it with Homebrew:
|
||||
|
||||
```bash
|
||||
brew install --cask l0ng-ai/tap/openidea
|
||||
```
|
||||
|
||||
## Benchmark
|
||||
|
||||
Opening [freqtrade](https://github.com/freqtrade/freqtrade) (Python, ~770 files)
|
||||
|
||||
@@ -33,6 +33,12 @@ her şeyi arama alışkanlığını) çekirdeği Rust ile yazılmış yerel bir
|
||||
Editör, kod analizi, hata ayıklayıcı (debugger), Git, terminal, veritabanı ve HTTP istemcileri;
|
||||
60'tan fazla dil için. macOS, Windows ve Linux sürümleri var.
|
||||
|
||||
macOS'ta Homebrew ile de kurabilirsiniz:
|
||||
|
||||
```bash
|
||||
brew install --cask l0ng-ai/tap/openidea
|
||||
```
|
||||
|
||||
## Performans karşılaştırması
|
||||
|
||||
[freqtrade](https://github.com/freqtrade/freqtrade) projesini (Python, ~770 dosya)
|
||||
|
||||
@@ -35,6 +35,12 @@ OpenIDEA 把 IntelliJ IDEA 的使用方式(快捷键、工具窗口、随处
|
||||
编辑器、代码洞察、调试器、Git、终端、数据库客户端和 HTTP 客户端,支持 60 多种语言。
|
||||
提供 macOS、Windows 和 Linux 版本。
|
||||
|
||||
在 macOS 上也可以用 Homebrew 安装:
|
||||
|
||||
```bash
|
||||
brew install --cask l0ng-ai/tap/openidea
|
||||
```
|
||||
|
||||
## 性能对比
|
||||
|
||||
在缓存已预热的情况下打开 [freqtrade](https://github.com/freqtrade/freqtrade)(Python,约 770 个文件),
|
||||
|
||||
@@ -6,6 +6,12 @@
|
||||
[Simple Icons](https://github.com/simple-icons/simple-icons), retrieved through
|
||||
Iconify (`simple-icons:angular`, `simple-icons:astro`, `simple-icons:cplusplus`, `simple-icons:dart`, `simple-icons:deepseek`, `simple-icons:django`, `simple-icons:dotnet`, `simple-icons:elixir`, `simple-icons:express`, `simple-icons:fastapi`, `simple-icons:flask`, `simple-icons:flutter`, `simple-icons:go`, `simple-icons:haskell`, `simple-icons:html5`, `simple-icons:kotlin`, `simple-icons:ktor`, `simple-icons:laravel`, `simple-icons:nestjs`, `simple-icons:nextdotjs`, `simple-icons:nodedotjs`, `simple-icons:nuxt`, `simple-icons:openjdk`, `simple-icons:phoenixframework`, `simple-icons:php`, `simple-icons:python`, `simple-icons:quarkus`, `simple-icons:ruby`, `simple-icons:rubyonrails`, `simple-icons:rust`, `simple-icons:scala`, `simple-icons:springboot`, `simple-icons:svelte`, `simple-icons:swift`, `simple-icons:symfony`, `simple-icons:vite`, `simple-icons:zig`) and filled with the brand colors (the standard icon grey for black logos). Licensed under [CC0 1.0 Universal](https://github.com/simple-icons/simple-icons/blob/develop/LICENSE.md).
|
||||
|
||||
## DuckDB symbol
|
||||
|
||||
DuckDB is a trademark of the DuckDB Foundation. The data source icon uses the
|
||||
light and dark symbols from the [DuckDB Design Manual](https://duckdb.org/design/manual/#logo-usage).
|
||||
The SVG paths and colors are preserved. See the [DuckDB trademark guidelines](https://duckdb.org/trademark_guidelines.html).
|
||||
|
||||
## Agent logos
|
||||
|
||||
The `src/ui/openidea/agents/` logos of agents listed in the
|
||||
@@ -149,6 +155,7 @@ languages whose JetBrains icons are not open source (Go, Ruby, Dart, Lua, Zig,
|
||||
Svelte, …). Those using the page-with-corner-badge layout (`goMod`, `goWork`,
|
||||
`dotenv`, `readme`, `lock`, `license`) reuse the page outline of the Apache-2.0
|
||||
expui `fileTypes/h.svg`; that outline is modified from the original by JetBrains.
|
||||
`goTest` adds a scaled copy of the Apache-2.0 expui `nodes/test.svg` as its badge.
|
||||
`src/ui/openidea/runConfigurations/springBoot*.svg` (the Spring Boot run configuration
|
||||
leaf) is OpenIDEA's own drawing.
|
||||
|
||||
|
||||
@@ -155,13 +155,14 @@ pub(crate) fn is_fast_option(id: &str) -> bool {
|
||||
}
|
||||
|
||||
/// Whether an option's available values and default belong to the selected model
|
||||
/// (`thought_level`, `context_tier`, and `model_config` options like `context` and `fast`)
|
||||
/// (`thought_level`, `context_tier`, and `model_config` options like `context`, `fast` and `service_tier`)
|
||||
/// rather than the provider as a whole.
|
||||
pub(crate) fn is_per_model_option(o: &AgentConfigOption) -> bool {
|
||||
matches!(o.category.as_deref(), Some("thought_level" | "context_tier" | "model_config"))
|
||||
|| matches!(o.id.as_str(), "effort" | "reasoning_effort" | "thinking" | "reasoning")
|
||||
|| is_fast_option(&o.id)
|
||||
|| is_context_option(&o.id)
|
||||
|| o.id == "service_tier"
|
||||
}
|
||||
|
||||
/// A `configOptions` array; only select options are kept (the UI shows them as dropdowns).
|
||||
@@ -531,6 +532,15 @@ mod tests {
|
||||
assert_eq!(ids(&c), [("allow_all", Some("off")), ("approval", Some("ask"))]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn service_tier_is_per_model() {
|
||||
let options = options_of(&json!({ "configOptions": [
|
||||
{ "id": "service_tier", "type": "select", "currentValue": "false",
|
||||
"options": [{ "value": "false" }, { "value": "true" }] }
|
||||
] }));
|
||||
assert!(is_per_model_option(&options[0]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn effort_context_and_fast_are_per_model_options() {
|
||||
let mut c = options_of(&json!({
|
||||
|
||||
@@ -450,10 +450,42 @@ struct TaskFile {
|
||||
/// The user named the task: its agent's own title updates no longer replace it.
|
||||
#[serde(default, skip_serializing_if = "is_false")]
|
||||
title_renamed: bool,
|
||||
/// [`NewAgentTask::ephemeral`]: the task file is never written, and new sessions ask the
|
||||
/// agent not to save their history.
|
||||
#[serde(default, skip_serializing_if = "is_false")]
|
||||
ephemeral: bool,
|
||||
/// Start the first session as a fork of a recorded native one (once).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pending_native_fork: Option<ForkStart>,
|
||||
}
|
||||
|
||||
/// A session to start as a fork of the recorded one: its source, and the id the host
|
||||
/// chooses for the fork (claude); codex assigns its own.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct ForkStart {
|
||||
source: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
target: Option<String>,
|
||||
}
|
||||
|
||||
/// A canonical lowercase UUID, the only session id shape either native agent writes.
|
||||
fn canonical_uuid(value: &str) -> bool {
|
||||
value.len() == 36
|
||||
&& value.bytes().enumerate().all(|(index, byte)| {
|
||||
if matches!(index, 8 | 13 | 18 | 23) {
|
||||
byte == b'-'
|
||||
} else {
|
||||
byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
struct PendingModel {
|
||||
/// Native Codex intent, including when this model cannot expose a Fast control.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
retained_service_tier: Option<AgentConfigChoice>,
|
||||
model: AgentConfigChoice,
|
||||
candidate: Option<AgentConfigValue>,
|
||||
options: Vec<AgentConfigOption>,
|
||||
@@ -469,6 +501,11 @@ impl PendingModel {
|
||||
});
|
||||
wanted.push(self.model.clone());
|
||||
wanted.extend(self.choices.iter().cloned());
|
||||
if let Some(choice) = &self.retained_service_tier
|
||||
&& !wanted.iter().any(|c| c.id == choice.id)
|
||||
{
|
||||
wanted.push(choice.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -502,6 +539,10 @@ struct TaskState {
|
||||
pending_rollback: u32,
|
||||
/// The user named the task; see `TaskFile::title_renamed`.
|
||||
title_renamed: bool,
|
||||
/// [`NewAgentTask::ephemeral`].
|
||||
ephemeral: bool,
|
||||
/// See `TaskFile::pending_native_fork`: cleared once a session is established.
|
||||
pending_native_fork: Option<ForkStart>,
|
||||
/// A turn is running or about to (prompts arriving now are queued).
|
||||
busy: bool,
|
||||
/// Background tasks the agent reported as running (`run_in_background` commands and
|
||||
@@ -527,7 +568,12 @@ impl TaskState {
|
||||
}
|
||||
task.config.retain(|o| !config::is_per_model_option(o));
|
||||
task.config.extend(pending.options.iter().cloned().map(|mut option| {
|
||||
if let Some(choice) = pending.choices.iter().find(|choice| choice.id == option.id) {
|
||||
if let Some(choice) = pending
|
||||
.choices
|
||||
.iter()
|
||||
.chain(pending.retained_service_tier.iter())
|
||||
.find(|choice| choice.id == option.id)
|
||||
{
|
||||
option.current = Some(choice.value.clone());
|
||||
}
|
||||
option
|
||||
@@ -778,6 +824,14 @@ impl AgentManager {
|
||||
provider::set_builtin_command(&dir, self.shared.env_secrets(), id, command.as_deref())
|
||||
}
|
||||
|
||||
/// Sets the extra arguments of a directly launched built-in ACP agent; empty resets them.
|
||||
pub fn set_builtin_additional_args(&self, id: &str, args: Vec<String>) -> IdeResult<()> {
|
||||
let Some(dir) = self.shared.paths.custom_agents_dir.as_deref() else {
|
||||
return Err(IdeError::unavailable("there is no custom agents directory"));
|
||||
};
|
||||
provider::set_builtin_additional_args(dir, self.shared.env_secrets(), id, args)
|
||||
}
|
||||
|
||||
/// Sets the environment variables built-in `id` starts with; empty clears them.
|
||||
pub fn set_builtin_env(&self, id: &str, env: std::collections::BTreeMap<String, String>) -> IdeResult<()> {
|
||||
let Some(dir) = self.shared.paths.custom_agents_dir.clone() else {
|
||||
@@ -1023,6 +1077,94 @@ impl AgentManager {
|
||||
subagents: Vec::new(),
|
||||
pending_rollback: 0,
|
||||
title_renamed: true,
|
||||
ephemeral: false,
|
||||
pending_native_fork: None,
|
||||
};
|
||||
let handle = Task::restore(file, self.shared.clone());
|
||||
self.tasks.write().insert(task.id.clone(), handle.clone());
|
||||
handle.emit_task();
|
||||
handle.persist();
|
||||
Ok(task)
|
||||
}
|
||||
|
||||
/// Forks a recorded external session into a new task: its first turn continues the
|
||||
/// recording as the agent's own fork, under an id the host chooses. The session must
|
||||
/// belong to this project and have been recorded in `cwd`.
|
||||
pub fn fork_session(&self, provider: &str, session_id: &str, cwd: &Path) -> IdeResult<AgentTask> {
|
||||
if !matches!(provider, "claude" | "codex") {
|
||||
return Err(IdeError::invalid(format!("cannot fork {provider} sessions")));
|
||||
}
|
||||
if !canonical_uuid(session_id) {
|
||||
return Err(IdeError::invalid("the recorded session has no canonical id"));
|
||||
}
|
||||
let spec = self.shared.spec(provider).ok_or_else(|| IdeError::invalid(format!("unknown agent {provider}")))?;
|
||||
if self.imported_session_ids().contains(session_id) {
|
||||
return Err(IdeError::invalid("that session is already a task"));
|
||||
}
|
||||
let found = self
|
||||
.external_sessions()
|
||||
.into_iter()
|
||||
.find(|s| s.provider == provider && s.session_id == session_id)
|
||||
.ok_or_else(|| IdeError::not_found(format!("unknown {provider} session {session_id}")))?;
|
||||
let recorded = found
|
||||
.cwd
|
||||
.map(PathBuf::from)
|
||||
.filter(|p| p.is_absolute())
|
||||
.ok_or_else(|| IdeError::invalid("the recorded session has no working directory"))?;
|
||||
let canonical = |p: &Path| dunce::canonicalize(p).unwrap_or_else(|_| p.to_path_buf());
|
||||
if canonical(cwd) != canonical(&recorded) {
|
||||
return Err(IdeError::invalid("the session was recorded in another directory"));
|
||||
}
|
||||
let root = self.shared.paths.project_root.clone();
|
||||
let config = self.shared.known_config(&spec.id);
|
||||
let now = now_ms();
|
||||
let id = uuid::Uuid::new_v4().simple().to_string();
|
||||
// The host names the fork's session id for claude; codex assigns its own.
|
||||
let target = (provider == "claude").then(|| uuid::Uuid::new_v4().to_string());
|
||||
let task = AgentTask {
|
||||
project_root: Some(IpcPath(root)),
|
||||
id,
|
||||
title: found.title,
|
||||
provider: spec.id.clone(),
|
||||
model: model_of(&config),
|
||||
status: AgentStatus::Ready,
|
||||
isolation: Isolation::Local,
|
||||
cwd: IpcPath(recorded),
|
||||
branch: None,
|
||||
base: None,
|
||||
base_commit: None,
|
||||
error: None,
|
||||
created_ms: now,
|
||||
updated_ms: now,
|
||||
config,
|
||||
commands: self.shared.known_commands(&spec.id),
|
||||
usage: None,
|
||||
queue: Vec::new(),
|
||||
capabilities: self.shared.probes.lock().get(&spec.id).map(|p| p.capabilities).unwrap_or_default(),
|
||||
resets_ms: None,
|
||||
retry: None,
|
||||
background: Box::default(),
|
||||
mcp_overrides: BTreeMap::new(),
|
||||
skill_overrides: BTreeMap::new(),
|
||||
stats: Box::default(),
|
||||
};
|
||||
let file = TaskFile {
|
||||
task: task.clone(),
|
||||
session_id: target.clone(),
|
||||
entries: Vec::new(),
|
||||
wanted: Vec::new(),
|
||||
pending_model: None,
|
||||
pending_switch: None,
|
||||
before: BTreeMap::new(),
|
||||
saved: None,
|
||||
touched: Some(BTreeSet::new()),
|
||||
turn: None,
|
||||
turns: Vec::new(),
|
||||
subagents: Vec::new(),
|
||||
pending_rollback: 0,
|
||||
title_renamed: true,
|
||||
ephemeral: false,
|
||||
pending_native_fork: Some(ForkStart { source: session_id.to_owned(), target }),
|
||||
};
|
||||
let handle = Task::restore(file, self.shared.clone());
|
||||
self.tasks.write().insert(task.id.clone(), handle.clone());
|
||||
@@ -1151,6 +1293,8 @@ impl AgentManager {
|
||||
subagents: Vec::new(),
|
||||
pending_rollback: 0,
|
||||
title_renamed: false,
|
||||
ephemeral: req.ephemeral,
|
||||
pending_native_fork: None,
|
||||
};
|
||||
let handle = Task::restore(file, self.shared.clone());
|
||||
handle.state.lock().busy = !req.idle;
|
||||
@@ -1516,6 +1660,8 @@ impl AgentManager {
|
||||
subagents: s.conversation.saved_subagents(),
|
||||
pending_rollback: total - keep,
|
||||
title_renamed: s.title_renamed,
|
||||
ephemeral: s.ephemeral,
|
||||
pending_native_fork: None,
|
||||
}
|
||||
};
|
||||
// Copying may have started the source's agent: it stops again once idle.
|
||||
@@ -2386,7 +2532,7 @@ impl Task {
|
||||
turns.push(Some(Arc::new(last)));
|
||||
}
|
||||
let mut wanted = file.wanted;
|
||||
let pending_model = file.pending_switch.or_else(|| {
|
||||
let mut pending_model = file.pending_switch.or_else(|| {
|
||||
let id = file.pending_model?;
|
||||
let index = wanted.iter().position(|choice| choice.id == id)?;
|
||||
let model = wanted.remove(index);
|
||||
@@ -2401,8 +2547,14 @@ impl Task {
|
||||
.and_then(|o| o.values.iter().find(|v| v.value == model.value))
|
||||
.cloned();
|
||||
let options = catalog.thought_levels.get(&model.value).cloned().unwrap_or_default();
|
||||
Some(PendingModel { model, candidate, options, choices: Vec::new() })
|
||||
Some(PendingModel { model, candidate, options, choices: Vec::new(), retained_service_tier: None })
|
||||
});
|
||||
if let Some(pending) = &mut pending_model
|
||||
&& pending.retained_service_tier.is_none()
|
||||
&& shared.spec(&task.provider).is_some_and(|spec| spec.driver == provider::Driver::Codex)
|
||||
{
|
||||
pending.retained_service_tier = wanted.iter().find(|c| c.id == "service_tier").cloned();
|
||||
}
|
||||
Arc::new(Self {
|
||||
id: task.id.clone(),
|
||||
shared,
|
||||
@@ -2420,6 +2572,8 @@ impl Task {
|
||||
turns,
|
||||
pending_rollback: file.pending_rollback,
|
||||
title_renamed: file.title_renamed,
|
||||
ephemeral: file.ephemeral,
|
||||
pending_native_fork: file.pending_native_fork,
|
||||
busy: false,
|
||||
background_tasks: Vec::new(),
|
||||
shell_context: Vec::new(),
|
||||
@@ -2675,7 +2829,9 @@ impl Task {
|
||||
let mut file = self.file.lock();
|
||||
// Read before the copy: whatever was asked for up to now is in it.
|
||||
let asked = self.saves_asked.load(Ordering::Acquire);
|
||||
if file.deleted || file.saved >= asked {
|
||||
// A throwaway task is never written: one its caller couldn't delete (a window closed
|
||||
// while it ran) is gone after a restart.
|
||||
if file.deleted || file.saved >= asked || self.state.lock().ephemeral {
|
||||
return;
|
||||
}
|
||||
let copy = {
|
||||
@@ -2695,6 +2851,8 @@ impl Task {
|
||||
subagents: s.conversation.saved_subagents(),
|
||||
pending_rollback: s.pending_rollback,
|
||||
title_renamed: s.title_renamed,
|
||||
ephemeral: s.ephemeral,
|
||||
pending_native_fork: s.pending_native_fork.clone(),
|
||||
}
|
||||
};
|
||||
let bytes = serde_json::to_vec(©);
|
||||
@@ -2975,7 +3133,13 @@ impl Task {
|
||||
.filter(|pending| pending.model.value == value)
|
||||
.map(|pending| pending.choices)
|
||||
.unwrap_or_default();
|
||||
let retained_service_tier = self
|
||||
.shared
|
||||
.spec(&provider)
|
||||
.filter(|spec| spec.driver == provider::Driver::Codex)
|
||||
.and_then(|_| s.wanted.iter().find(|c| c.id == "service_tier").cloned());
|
||||
s.pending_model = Some(PendingModel {
|
||||
retained_service_tier,
|
||||
model: AgentConfigChoice { id: target.id, value },
|
||||
candidate: Some(candidate),
|
||||
options,
|
||||
@@ -3357,66 +3521,116 @@ impl Task {
|
||||
let skills_delivery = self.stage_skills(stage_key(spec.driver), cwd).await;
|
||||
// Agents that compare canonical paths fail in a symlinked directory (macOS `/tmp`).
|
||||
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);
|
||||
if spec.driver == provider::Driver::Codex {
|
||||
let s = self.state.lock();
|
||||
let mut wanted = s.wanted.clone();
|
||||
if let Some(pending) = pending_model {
|
||||
pending.apply(&mut wanted, &s.task.config);
|
||||
}
|
||||
// Restore intent even when the resumed model cannot expose the Fast control.
|
||||
if let Some(fast) =
|
||||
wanted.iter().find(|c| c.id == "service_tier").and_then(|c| c.value.parse::<bool>().ok())
|
||||
{
|
||||
opening_params["_meta"]["openidea"]["codexFast"] = json!(fast);
|
||||
}
|
||||
}
|
||||
|
||||
let mut tried_auth = false;
|
||||
let mut session = None;
|
||||
let start_fresh = self.start_fresh.load(Ordering::Acquire);
|
||||
if pending_model.is_some() && (saved.is_none() || !can_load || start_fresh) {
|
||||
return Err(SessionOpenError {
|
||||
message: "The agent does not support resuming this session.".into(),
|
||||
allow_acp_fallback: false,
|
||||
});
|
||||
}
|
||||
if let (Some(id), true, false) = (saved, can_load, start_fresh) {
|
||||
// The replay goes before what this turn already showed (the user's message).
|
||||
let shown = self.adopts_replay().then(|| self.take_entries());
|
||||
self.replaying.store(true, Ordering::Release);
|
||||
let mut params = session_params(&cwd_s, &mcp_servers, skills_delivery.as_ref(), &roots);
|
||||
params["sessionId"] = json!(&id);
|
||||
let loaded = self.request_with_auth(&peer, &init, &mut tried_auth, "session/load", params).await;
|
||||
tokio::time::sleep(REPLAY_GRACE).await;
|
||||
self.replaying.store(false, Ordering::Release);
|
||||
if let Some(shown) = shown {
|
||||
if loaded.is_ok() {
|
||||
self.adopting_replay.store(false, Ordering::Release);
|
||||
let changed = self.state.lock().conversation.end_turn(None);
|
||||
self.mark_dirty(changed);
|
||||
} else {
|
||||
// A failed load may still have replayed part of it.
|
||||
self.take_entries();
|
||||
}
|
||||
for entry in shown {
|
||||
self.push_entry(entry);
|
||||
if let Some(fork) = pending_native_fork {
|
||||
if !capabilities.fork {
|
||||
return Err(SessionOpenError {
|
||||
message: "the agent can't continue a recorded session".into(),
|
||||
allow_acp_fallback: false,
|
||||
});
|
||||
}
|
||||
let mut params = opening_params.clone();
|
||||
params["sessionId"] = json!(&fork.source);
|
||||
if let Some(target) = &fork.target {
|
||||
match params["_meta"].as_object_mut() {
|
||||
Some(meta) => {
|
||||
if let Some(openidea) = meta.entry("openidea").or_insert_with(|| json!({})).as_object_mut() {
|
||||
openidea.insert("forkSessionId".into(), json!(target));
|
||||
}
|
||||
}
|
||||
None => params["_meta"] = json!({ "openidea": { "forkSessionId": target } }),
|
||||
}
|
||||
}
|
||||
match loaded {
|
||||
Ok(v) => session = Some((id, v)),
|
||||
// Not silently: a new session would lose the conversation and replace the saved id.
|
||||
Err(e) => {
|
||||
tracing::info!("agent task {}: session/load failed: {e}", self.id);
|
||||
if let Some(message) = self.sign_in_error(&e, Some(&sign_in_message)) {
|
||||
return Err(SessionOpenError { message, allow_acp_fallback: false });
|
||||
let reply = self
|
||||
.request_with_auth(&peer, &init, &mut tried_auth, "session/fork", params)
|
||||
.await
|
||||
.map_err(|e| SessionOpenError { message: self.describe(e), allow_acp_fallback: false })?;
|
||||
let id = reply
|
||||
.get("sessionId")
|
||||
.and_then(Value::as_str)
|
||||
.ok_or_else(|| SessionOpenError {
|
||||
message: "the agent returned no session".into(),
|
||||
allow_acp_fallback: false,
|
||||
})?
|
||||
.to_owned();
|
||||
session = Some((id, reply));
|
||||
} else {
|
||||
let start_fresh = self.start_fresh.load(Ordering::Acquire);
|
||||
if pending_model.is_some() && (saved.is_none() || !can_load || start_fresh) {
|
||||
return Err(SessionOpenError {
|
||||
message: "The agent does not support resuming this session.".into(),
|
||||
allow_acp_fallback: false,
|
||||
});
|
||||
}
|
||||
if let (Some(id), true, false) = (saved, can_load, start_fresh) {
|
||||
// The replay goes before what this turn already showed (the user's message).
|
||||
let shown = self.adopts_replay().then(|| self.take_entries());
|
||||
self.replaying.store(true, Ordering::Release);
|
||||
let mut params = opening_params.clone();
|
||||
params["sessionId"] = json!(&id);
|
||||
let loaded = self.request_with_auth(&peer, &init, &mut tried_auth, "session/load", params).await;
|
||||
tokio::time::sleep(REPLAY_GRACE).await;
|
||||
self.replaying.store(false, Ordering::Release);
|
||||
if let Some(shown) = shown {
|
||||
if loaded.is_ok() {
|
||||
self.adopting_replay.store(false, Ordering::Release);
|
||||
let changed = self.state.lock().conversation.end_turn(None);
|
||||
self.mark_dirty(changed);
|
||||
} else {
|
||||
// A failed load may still have replayed part of it.
|
||||
self.take_entries();
|
||||
}
|
||||
if pending_model.is_some() {
|
||||
for entry in shown {
|
||||
self.push_entry(entry);
|
||||
}
|
||||
}
|
||||
match loaded {
|
||||
Ok(v) => session = Some((id, v)),
|
||||
// Not silently: a new session would lose the conversation and replace the saved id.
|
||||
Err(e) => {
|
||||
tracing::info!("agent task {}: session/load failed: {e}", self.id);
|
||||
if let Some(message) = self.sign_in_error(&e, Some(&sign_in_message)) {
|
||||
return Err(SessionOpenError { message, allow_acp_fallback: false });
|
||||
}
|
||||
if pending_model.is_some() {
|
||||
return Err(SessionOpenError {
|
||||
message: format!(
|
||||
"Couldn't reopen this conversation's {} session: {}",
|
||||
spec.name,
|
||||
self.describe(e)
|
||||
),
|
||||
allow_acp_fallback: false,
|
||||
});
|
||||
}
|
||||
self.start_fresh.store(true, Ordering::Release);
|
||||
return Err(SessionOpenError {
|
||||
message: format!(
|
||||
"Couldn't reopen this conversation's {} session: {}",
|
||||
"Couldn't reopen this conversation's {} session: {}\n\nSend the message again to \
|
||||
continue in a new session. The agent won't see the earlier conversation.",
|
||||
spec.name,
|
||||
self.describe(e)
|
||||
),
|
||||
allow_acp_fallback: false,
|
||||
});
|
||||
}
|
||||
self.start_fresh.store(true, Ordering::Release);
|
||||
return Err(SessionOpenError {
|
||||
message: format!(
|
||||
"Couldn't reopen this conversation's {} session: {}\n\nSend the message again to \
|
||||
continue in a new session. The agent won't see the earlier conversation.",
|
||||
spec.name,
|
||||
self.describe(e)
|
||||
),
|
||||
allow_acp_fallback: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3424,7 +3638,10 @@ impl Task {
|
||||
let (session_id, result) = match session {
|
||||
Some(s) => s,
|
||||
None => {
|
||||
let params = session_params(&cwd_s, &mcp_servers, skills_delivery.as_ref(), &roots);
|
||||
let mut params = opening_params;
|
||||
if self.state.lock().ephemeral {
|
||||
mark_ephemeral(&mut params);
|
||||
}
|
||||
let v = self.request_with_auth(&peer, &init, &mut tried_auth, "session/new", params).await.map_err(
|
||||
|e| match self.sign_in_error(&e, Some(&sign_in_message)) {
|
||||
Some(msg) => SessionOpenError { message: msg, allow_acp_fallback: false },
|
||||
@@ -3535,7 +3752,10 @@ impl Task {
|
||||
if config::is_per_model_option(&o) && !model_options {
|
||||
continue;
|
||||
}
|
||||
let already = (known || explicit) && o.current.as_deref() == Some(choice.value.as_str());
|
||||
// A displayed tier can be inherited. Preserve an explicit Fast/Standard choice
|
||||
// even when it currently looks the same, so subsequent turns receive the override.
|
||||
let already =
|
||||
o.id != "service_tier" && (known || explicit) && o.current.as_deref() == Some(choice.value.as_str());
|
||||
if already || !o.values.iter().any(|v| v.value == choice.value) {
|
||||
continue;
|
||||
}
|
||||
@@ -3604,6 +3824,8 @@ impl Task {
|
||||
s.pending_model = None;
|
||||
s.task.capabilities = capabilities;
|
||||
s.session_id = Some(session_id.clone());
|
||||
// The recorded session is forked (or the fork resumed): the one-shot intent is spent.
|
||||
s.pending_native_fork = None;
|
||||
self.start_fresh.store(false, Ordering::Release);
|
||||
// The (re)started process runs nothing yet: whatever it reports next is all of it.
|
||||
s.background_tasks = Vec::new();
|
||||
@@ -4482,6 +4704,15 @@ fn session_params(cwd: &str, mcp: &McpForSession, skills: Option<&skills::Delive
|
||||
params
|
||||
}
|
||||
|
||||
/// `_meta.openidea.ephemeral` of `session/new`: the native drivers start the session without
|
||||
/// saving it (Claude Code `--no-session-persistence`, Codex `ephemeral` threads).
|
||||
fn mark_ephemeral(params: &mut Value) {
|
||||
if !params["_meta"]["openidea"].is_object() {
|
||||
params["_meta"]["openidea"] = json!({});
|
||||
}
|
||||
params["_meta"]["openidea"]["ephemeral"] = json!(true);
|
||||
}
|
||||
|
||||
fn is_false(b: &bool) -> bool {
|
||||
!*b
|
||||
}
|
||||
|
||||
@@ -612,6 +612,9 @@ pub struct AgentProvider {
|
||||
/// Executable and arguments actually launched, without flattening paths containing spaces.
|
||||
pub program: String,
|
||||
pub args: Vec<String>,
|
||||
/// Settings-managed suffix of `args`; absent for launches that cannot be edited.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub additional_args: Option<Vec<String>>,
|
||||
pub default_program: Option<String>,
|
||||
pub default_args: Vec<String>,
|
||||
pub login_hint: Option<String>,
|
||||
@@ -700,6 +703,10 @@ pub struct NewAgentTask {
|
||||
/// `!` command runs in it first.
|
||||
#[serde(default)]
|
||||
pub idle: bool,
|
||||
/// A throwaway task (Generate Commit Message): it isn't saved, so it doesn't outlive a
|
||||
/// restart, and the agent keeps no session history of its own for it.
|
||||
#[serde(default)]
|
||||
pub ephemeral: bool,
|
||||
}
|
||||
|
||||
/// A file the task changed: against [`AgentTask::base_commit`], or against `HEAD` in the
|
||||
|
||||
@@ -30,6 +30,67 @@ pub(super) fn transcript(config_dir: &Path, cwd: &Path, id: &str) -> PathBuf {
|
||||
.unwrap_or(direct)
|
||||
}
|
||||
|
||||
/// Brings session `id` into `config_dir` when it is missing there but another Claude Code
|
||||
/// configuration directory beside it (`~/.claude`, `~/.claude-work`...) has it: switching
|
||||
/// `CLAUDE_CONFIG_DIR` (another account) would otherwise lose every earlier conversation.
|
||||
/// Copies the transcript and its folder (subagents, tool results) under the same project
|
||||
/// directory name. Returns whether the session is in `config_dir` now.
|
||||
pub(super) fn adopt(config_dir: &Path, cwd: &Path, id: &str) -> bool {
|
||||
if transcript(config_dir, cwd, id).exists() {
|
||||
return true;
|
||||
}
|
||||
let file = format!("{id}.jsonl");
|
||||
let home = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE")).map(PathBuf::from);
|
||||
let mut homes: Vec<PathBuf> = config_dir
|
||||
.parent()
|
||||
.into_iter()
|
||||
.chain(home.as_deref())
|
||||
.flat_map(|dir| std::fs::read_dir(dir).into_iter().flatten().flatten())
|
||||
.filter(|d| d.file_name().to_string_lossy().starts_with(".claude"))
|
||||
.map(|d| d.path())
|
||||
.filter(|p| p != config_dir && p.join("projects").is_dir())
|
||||
.collect();
|
||||
homes.sort();
|
||||
homes.dedup();
|
||||
let found = homes.iter().find_map(|other| {
|
||||
let projects = other.join("projects");
|
||||
let direct = projects.join(escape(cwd));
|
||||
std::iter::once(direct.clone())
|
||||
.chain(std::fs::read_dir(&projects).into_iter().flatten().flatten().map(|d| d.path()))
|
||||
.find(|dir| dir.join(&file).is_file())
|
||||
});
|
||||
let Some(source) = found else { return false };
|
||||
let Some(name) = source.file_name() else { return false };
|
||||
let target = config_dir.join("projects").join(name);
|
||||
let copied = std::fs::create_dir_all(&target)
|
||||
.and_then(|()| copy_tree(&source.join(id), &target.join(id)))
|
||||
.and_then(|()| std::fs::copy(source.join(&file), target.join(&file)).map(drop));
|
||||
match copied {
|
||||
Ok(()) => true,
|
||||
Err(e) => {
|
||||
tracing::warn!("claude session {id}: copying it from {}: {e}", source.display());
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn copy_tree(from: &Path, to: &Path) -> std::io::Result<()> {
|
||||
if !from.is_dir() {
|
||||
return Ok(());
|
||||
}
|
||||
std::fs::create_dir_all(to)?;
|
||||
for entry in std::fs::read_dir(from)? {
|
||||
let entry = entry?;
|
||||
let dest = to.join(entry.file_name());
|
||||
if entry.file_type()?.is_dir() {
|
||||
copy_tree(&entry.path(), &dest)?;
|
||||
} else if !dest.exists() {
|
||||
std::fs::copy(entry.path(), dest)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The project directory name Claude Code uses for `cwd`.
|
||||
pub(crate) fn escape(cwd: &Path) -> String {
|
||||
cwd.to_string_lossy().chars().map(|c| if c.is_ascii_alphanumeric() { c } else { '-' }).collect()
|
||||
@@ -207,6 +268,26 @@ mod tests {
|
||||
json!({"type": "assistant", "uuid": id, "parentUuid": parent, "message": {"role": "assistant", "content": content}})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_session_from_another_config_dir_is_copied_in() {
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let (old, new) = (root.path().join(".claude-2"), root.path().join(".claude-3"));
|
||||
let cwd = Path::new("/work/app");
|
||||
let project = old.join("projects").join(escape(cwd));
|
||||
std::fs::create_dir_all(project.join("s1/subagents")).unwrap();
|
||||
std::fs::write(project.join("s1.jsonl"), "{}\n").unwrap();
|
||||
std::fs::write(project.join("s1/subagents/a.jsonl"), "{}\n").unwrap();
|
||||
std::fs::create_dir_all(new.join("projects")).unwrap();
|
||||
|
||||
assert!(!adopt(&new, cwd, "missing"));
|
||||
assert!(adopt(&new, cwd, "s1"));
|
||||
let copied = new.join("projects").join(escape(cwd));
|
||||
assert_eq!(transcript(&new, cwd, "s1"), copied.join("s1.jsonl"));
|
||||
assert!(copied.join("s1/subagents/a.jsonl").is_file());
|
||||
assert!(project.join("s1.jsonl").is_file(), "the original stays");
|
||||
assert!(adopt(&new, cwd, "s1"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_newest_branch_is_the_conversation() {
|
||||
let entries = vec![
|
||||
|
||||
@@ -178,6 +178,8 @@ struct Session {
|
||||
additional_dirs: Vec<String>,
|
||||
/// The staged skills' `--settings` JSON (`skillOverrides` for the native ones too).
|
||||
skills_settings: Option<String>,
|
||||
/// `_meta.openidea.ephemeral`: `--no-session-persistence`, nothing saved under `~/.claude`.
|
||||
ephemeral: bool,
|
||||
shim: Weak<Shim>,
|
||||
st: Mutex<State>,
|
||||
/// Serializes (re)starting the process.
|
||||
@@ -334,6 +336,12 @@ impl Shim {
|
||||
Some(history::transcript(self.config.config_dir.as_deref()?, cwd, id))
|
||||
}
|
||||
|
||||
/// Whether session `id` is in the configuration directory, copied there from another one
|
||||
/// if need be (see [`history::adopt`]).
|
||||
fn adopt(&self, cwd: &Path, id: &str) -> bool {
|
||||
self.config.config_dir.as_deref().is_some_and(|dir| history::adopt(dir, cwd, id))
|
||||
}
|
||||
|
||||
/// The conversation a session started with `start` begins with.
|
||||
fn base_chain(&self, cwd: &Path, start: &Start) -> Result<Vec<Value>, String> {
|
||||
let (id, at) = match start {
|
||||
@@ -370,6 +378,7 @@ impl Shim {
|
||||
skills_add_dir: skills.and_then(|s| s.get("claudeAddDir")).and_then(Value::as_str).map(PathBuf::from),
|
||||
additional_dirs: additional_dirs(params),
|
||||
skills_settings: skills.and_then(|s| s.get("claudeSettings")).and_then(Value::as_str).map(str::to_owned),
|
||||
ephemeral: params.pointer("/_meta/openidea/ephemeral").and_then(Value::as_bool).unwrap_or(false),
|
||||
shim: Arc::downgrade(self),
|
||||
st: Mutex::new(State {
|
||||
proc: None,
|
||||
@@ -435,10 +444,13 @@ impl Shim {
|
||||
let id = params.get("sessionId").and_then(Value::as_str).ok_or_else(|| invalid("no sessionId"))?;
|
||||
let cwd = self.cwd_of(¶ms);
|
||||
let (start, pending) = match self.load_pending(id) {
|
||||
Some(s) => (s, true),
|
||||
None if self.transcript(&cwd, id).is_some_and(|p| p.exists()) => {
|
||||
(Start::Resume { id: id.to_owned(), at: None }, false)
|
||||
Some(s) => {
|
||||
if let Start::Resume { id: from, .. } | Start::Fork { from, .. } = &s {
|
||||
self.adopt(&cwd, from);
|
||||
}
|
||||
(s, true)
|
||||
}
|
||||
None if self.adopt(&cwd, id) => (Start::Resume { id: id.to_owned(), at: None }, false),
|
||||
None => return Err(invalid(format!("no Claude Code session {id} in {}", cwd.display()))),
|
||||
};
|
||||
let chain = self.base_chain(&cwd, &start).map_err(internal)?;
|
||||
@@ -451,24 +463,43 @@ impl Shim {
|
||||
Ok(json!({ "configOptions": session.st.lock().settings.options() }))
|
||||
}
|
||||
"session/fork" => {
|
||||
let source = self.session(¶ms)?;
|
||||
let id = new_uuid(false);
|
||||
let (start, settings) = {
|
||||
let st = source.st.lock();
|
||||
let start = match &st.start {
|
||||
Start::New { .. } if !st.pending && st.titled_or_prompted() => {
|
||||
Start::Fork { from: source.id.clone(), id: id.clone(), at: None }
|
||||
}
|
||||
Start::New { .. } => Start::New { id: id.clone() },
|
||||
Start::Resume { id: from, at } | Start::Fork { from, at, .. } if st.pending => {
|
||||
Start::Fork { from: from.clone(), id: id.clone(), at: at.clone() }
|
||||
}
|
||||
_ => Start::Fork { from: source.id.clone(), id: id.clone(), at: None },
|
||||
};
|
||||
(start, st.settings.clone())
|
||||
let source_id =
|
||||
params.get("sessionId").and_then(Value::as_str).ok_or_else(|| invalid("no sessionId"))?;
|
||||
let source = self.sessions.lock().get(source_id).cloned();
|
||||
// The host names the fork's session id so the task knows it before the CLI
|
||||
// starts; only a canonical UUID is accepted.
|
||||
let requested = params.pointer("/_meta/openidea/forkSessionId").and_then(Value::as_str);
|
||||
if let Some(target) = requested
|
||||
&& !crate::canonical_uuid(target)
|
||||
{
|
||||
return Err(invalid("A fork session id must be a canonical UUID"));
|
||||
}
|
||||
let id = requested.map_or_else(|| new_uuid(false), str::to_owned);
|
||||
if self.sessions.lock().contains_key(&id) {
|
||||
return Err(invalid(format!("session {id} is already open")));
|
||||
}
|
||||
let cwd = source.as_ref().map_or_else(|| self.cwd_of(¶ms), |session| session.cwd.clone());
|
||||
let (start, settings) = match &source {
|
||||
Some(source) => {
|
||||
let st = source.st.lock();
|
||||
let start = match &st.start {
|
||||
Start::New { .. } if !st.pending && st.titled_or_prompted() => {
|
||||
Start::Fork { from: source.id.clone(), id: id.clone(), at: None }
|
||||
}
|
||||
Start::New { .. } => Start::New { id: id.clone() },
|
||||
Start::Resume { id: from, at } | Start::Fork { from, at, .. } if st.pending => {
|
||||
Start::Fork { from: from.clone(), id: id.clone(), at: at.clone() }
|
||||
}
|
||||
_ => Start::Fork { from: source.id.clone(), id: id.clone(), at: None },
|
||||
};
|
||||
(start, st.settings.clone())
|
||||
}
|
||||
// A recorded session is not open in this connection: the CLI forks it
|
||||
// from its transcript on disk when the task's first prompt starts it.
|
||||
None => (Start::Fork { from: source_id.to_owned(), id: id.clone(), at: None }, Settings::default()),
|
||||
};
|
||||
self.save_pending(&id, Some(&start));
|
||||
let session = self.add_session(&id, source.cwd.clone(), start, true, ¶ms);
|
||||
let session = self.add_session(&id, cwd, start, true, ¶ms);
|
||||
session.st.lock().settings = settings;
|
||||
let options = session.st.lock().settings.options();
|
||||
Ok(json!({ "sessionId": id, "configOptions": options }))
|
||||
@@ -703,6 +734,9 @@ impl Session {
|
||||
if let Some(settings) = &self.skills_settings {
|
||||
args.extend(["--settings".to_owned(), settings.clone()]);
|
||||
}
|
||||
if self.ephemeral {
|
||||
args.push("--no-session-persistence".to_owned());
|
||||
}
|
||||
args.extend(start.args());
|
||||
let launch =
|
||||
Launch { program: shim.config.program.clone(), args, cwd: self.cwd.clone(), env: shim.config.env.clone() };
|
||||
|
||||
@@ -464,6 +464,7 @@ async fn replay_simple() {
|
||||
let args = r.cli.launched.lock()[0].clone();
|
||||
assert!(args.windows(2).any(|w| w == ["--session-id", r.session.as_str()]), "{args:?}");
|
||||
assert!(args.contains(&"--permission-prompt-tool".to_owned()));
|
||||
assert!(!args.contains(&"--no-session-persistence".to_owned()));
|
||||
let user = r.sent(0).into_iter().find(|m| m["type"] == "user").unwrap();
|
||||
assert_eq!(user["message"]["content"][0]["text"], "Reply with exactly: hello there");
|
||||
}
|
||||
@@ -652,6 +653,84 @@ async fn replay_resume() {
|
||||
assert!(args.windows(2).any(|w| w == ["--resume", r.session.as_str()]), "{args:?}");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn fork_session_can_start_a_recorded_session_under_the_hosts_id() {
|
||||
/// Registering a fork must not start a process: its first prompt does.
|
||||
struct NoLaunch;
|
||||
impl Cli for NoLaunch {
|
||||
fn launch(&self, _: &Launch, _: OnStderr) -> std::io::Result<cli::CliIo> {
|
||||
panic!("session/fork must not launch the CLI")
|
||||
}
|
||||
}
|
||||
|
||||
let config = tempfile::tempdir().unwrap();
|
||||
let pending = tempfile::tempdir().unwrap();
|
||||
let h = Harness::connect(
|
||||
Arc::new(NoLaunch),
|
||||
config.path().to_path_buf(),
|
||||
pending.path().to_path_buf(),
|
||||
std::env::temp_dir(),
|
||||
Vec::new(),
|
||||
)
|
||||
.await;
|
||||
let source = "11111111-1111-4111-8111-111111111111";
|
||||
let target = "22222222-2222-4222-8222-222222222222";
|
||||
let reply = h
|
||||
.request(
|
||||
"session/fork",
|
||||
json!({
|
||||
"sessionId": source,
|
||||
"cwd": h.cwd,
|
||||
"mcpServers": [],
|
||||
"_meta": { "openidea": { "forkSessionId": target } }
|
||||
}),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(reply["sessionId"], target);
|
||||
// The host chose this id for the fork: the next process must fork the recorded
|
||||
// session under exactly it.
|
||||
let saved: Value =
|
||||
serde_json::from_slice(&std::fs::read(pending.path().join(format!("{target}.json"))).unwrap()).unwrap();
|
||||
assert_eq!(saved, json!({ "fork": source, "id": target, "at": null }));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn fork_session_rejects_a_requested_id_that_is_not_canonical() {
|
||||
struct NoLaunch;
|
||||
impl Cli for NoLaunch {
|
||||
fn launch(&self, _: &Launch, _: OnStderr) -> std::io::Result<cli::CliIo> {
|
||||
panic!("no process")
|
||||
}
|
||||
}
|
||||
|
||||
let config = tempfile::tempdir().unwrap();
|
||||
let pending = tempfile::tempdir().unwrap();
|
||||
let h = Harness::connect(
|
||||
Arc::new(NoLaunch),
|
||||
config.path().to_path_buf(),
|
||||
pending.path().to_path_buf(),
|
||||
std::env::temp_dir(),
|
||||
Vec::new(),
|
||||
)
|
||||
.await;
|
||||
for rejected in ["../../x", "AAAAAAAA-AAAA-4AAA-8AAA-AAAAAAAAAAAA", ""] {
|
||||
let error = h
|
||||
.request(
|
||||
"session/fork",
|
||||
json!({
|
||||
"sessionId": "11111111-1111-4111-8111-111111111111",
|
||||
"cwd": h.cwd,
|
||||
"mcpServers": [],
|
||||
"_meta": { "openidea": { "forkSessionId": rejected } }
|
||||
}),
|
||||
)
|
||||
.await
|
||||
.expect_err("only a canonical id may name the fork");
|
||||
assert!(error.to_string().contains("canonical"), "{rejected}: {error}");
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- recording ----------
|
||||
|
||||
/// Passes the real CLI's stdio through, keeping what went over it.
|
||||
@@ -1350,3 +1429,16 @@ fn additional_directories_are_read_from_the_session_params() {
|
||||
assert_eq!(additional_dirs(¶ms), ["/w/web", "/w/docs"]);
|
||||
assert!(additional_dirs(&json!({ "cwd": "/w/api" })).is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn an_ephemeral_session_is_not_saved() {
|
||||
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": { "ephemeral": true } } });
|
||||
h.request("session/new", params).await.unwrap();
|
||||
let args = cli.launched.lock()[0].clone();
|
||||
assert!(args.contains(&"--no-session-persistence".to_owned()), "{args:?}");
|
||||
}
|
||||
@@ -108,7 +108,7 @@ pub(crate) async fn discover(
|
||||
let options = translate::config_options(&models, &settings);
|
||||
let levels = crate::config::options_of(&json!({ "configOptions": options }))
|
||||
.into_iter()
|
||||
.filter(|o| o.category.as_deref() == Some("thought_level"))
|
||||
.filter(|o| matches!(o.category.as_deref(), Some("thought_level" | "model_config")))
|
||||
.collect();
|
||||
(model.id.clone(), levels)
|
||||
})
|
||||
@@ -492,8 +492,14 @@ impl CodexShim {
|
||||
self.prepare_project_trust(params).await;
|
||||
let mut request = json!({ "cwd": params.get("cwd") });
|
||||
apply_thread_config(params, &mut request);
|
||||
// Not written to `~/.codex/sessions`, so it isn't listed among the past threads.
|
||||
if params.pointer("/_meta/openidea/ephemeral").and_then(Value::as_bool) == Some(true) {
|
||||
request["ephemeral"] = json!(true);
|
||||
}
|
||||
let result = self.call("thread/start", request).await?;
|
||||
let (id, options) = self.open_thread(&result, &models, None);
|
||||
let mut settings = Settings::of(&result, &models);
|
||||
settings.fast_override = params.pointer("/_meta/openidea/codexFast").and_then(Value::as_bool);
|
||||
let (id, options) = self.open_thread(&result, &models, Some(settings));
|
||||
if id.is_empty() {
|
||||
return Err(error(codes::INTERNAL_ERROR, "codex started no thread"));
|
||||
}
|
||||
@@ -510,7 +516,9 @@ impl CodexShim {
|
||||
let mut request = json!({ "threadId": id, "cwd": params.get("cwd") });
|
||||
apply_thread_config(params, &mut request);
|
||||
let result = self.call("thread/resume", request).await?;
|
||||
let (_, options) = self.open_thread(&result, &models, None);
|
||||
let mut settings = Settings::of(&result, &models);
|
||||
settings.fast_override = params.pointer("/_meta/openidea/codexFast").and_then(Value::as_bool);
|
||||
let (_, options) = self.open_thread(&result, &models, Some(settings));
|
||||
let cwd = self.state.lock().threads.get(id).and_then(|t| t.cwd.clone());
|
||||
let thread = result.get("thread").unwrap_or(&Value::Null);
|
||||
for update in translate::history(thread, cwd.as_deref()) {
|
||||
@@ -613,6 +621,9 @@ impl CodexShim {
|
||||
if let Some(effort) = &s.effort {
|
||||
request["effort"] = json!(effort);
|
||||
}
|
||||
if let Some(tier) = s.service_tier_override(&models) {
|
||||
request["serviceTier"] = json!(tier);
|
||||
}
|
||||
}
|
||||
self.call("turn/start", request).await
|
||||
}
|
||||
@@ -1595,3 +1606,6 @@ fn mcp_text(response: &Value) -> String {
|
||||
.collect::<Vec<_>>();
|
||||
format!("MCP servers:\n{}", lines.join("\n"))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod reconnect_tests;
|
||||
@@ -0,0 +1,217 @@
|
||||
//! User-facing task operations through the native shim, with a local app-server stand-in.
|
||||
use super::*;
|
||||
use crate::{AgentManager, AgentPrompt, AgentStatus, Isolation, NewAgentTask};
|
||||
|
||||
#[derive(Default)]
|
||||
struct Runtime {
|
||||
models: Mutex<HashMap<String, String>>,
|
||||
hide_a: std::sync::atomic::AtomicBool,
|
||||
turns: Mutex<Vec<Value>>,
|
||||
tiers: Mutex<HashMap<String, Value>>,
|
||||
servers: Mutex<Vec<Peer>>,
|
||||
}
|
||||
struct Connection {
|
||||
runtime: Arc<Runtime>,
|
||||
peer: OnceLock<Peer>,
|
||||
}
|
||||
impl Handler for Connection {
|
||||
fn on_notification(&self, _: &str, _: Value) {}
|
||||
fn on_request(&self, method: &str, p: Value) -> Result<Value, (i64, String)> {
|
||||
match method {
|
||||
"initialize" => Ok(json!({})),
|
||||
"model/list" => {
|
||||
let mut data = vec![json!({"id":"b", "model":"b", "serviceTiers":[]})];
|
||||
if !self.runtime.hide_a.swap(false, std::sync::atomic::Ordering::SeqCst) {
|
||||
data.insert(0, json!({"id":"a", "model":"a", "isDefault":true, "serviceTiers":[{"id":"fast"}]}));
|
||||
}
|
||||
Ok(json!({"data":data}))
|
||||
}
|
||||
"config/read" => Ok(json!({"layers":[]})),
|
||||
"skills/list" => Ok(json!({"data":[]})),
|
||||
"thread/start" | "thread/resume" => {
|
||||
let mut models = self.runtime.models.lock();
|
||||
let id = p["threadId"].as_str().map(str::to_owned).unwrap_or_else(|| format!("s{}", models.len()));
|
||||
let model = models.entry(id.clone()).or_insert_with(|| "a".into()).clone();
|
||||
Ok(json!({"thread":{"id":id,"name":"fixture","turns":[]}, "model":model,
|
||||
"serviceTier":self.runtime.tiers.lock().get(&id).cloned().unwrap_or(json!("fast"))}))
|
||||
}
|
||||
"turn/start" => {
|
||||
let id = p["threadId"].as_str().unwrap();
|
||||
self.runtime.models.lock().insert(id.into(), p["model"].as_str().unwrap().into());
|
||||
if let Some(tier) = p.get("serviceTier") {
|
||||
self.runtime.tiers.lock().insert(id.into(), tier.clone());
|
||||
}
|
||||
self.runtime.turns.lock().push(p.clone());
|
||||
self.peer
|
||||
.get()
|
||||
.unwrap()
|
||||
.notify(
|
||||
"turn/completed",
|
||||
json!({"threadId":id,
|
||||
"turn":{"id":"t","status":"completed"}}),
|
||||
)
|
||||
.unwrap();
|
||||
Ok(json!({"turn":{"id":"t"}}))
|
||||
}
|
||||
_ => Err((codes::METHOD_NOT_FOUND, method.into())),
|
||||
}
|
||||
}
|
||||
}
|
||||
fn manager(dir: &Path, runtime: Arc<Runtime>) -> AgentManager {
|
||||
let agents = dir.join("agents");
|
||||
crate::provider::set_builtin_command(&agents, None, "codex", Some("/missing/fixture-codex")).unwrap();
|
||||
AgentManager::with_connector(
|
||||
crate::AgentPaths {
|
||||
project_root: dir.into(),
|
||||
store_dir: dir.join("store"),
|
||||
worktrees_dir: dir.join("worktrees"),
|
||||
models_file: dir.join("models.json"),
|
||||
custom_agents_dir: Some(agents),
|
||||
home_dir: Some(dir.into()),
|
||||
env_secrets: None,
|
||||
catalogs: Arc::default(),
|
||||
},
|
||||
tokio::runtime::Handle::current(),
|
||||
Arc::new(move |spec, _, client, _| {
|
||||
assert_eq!(spec.driver, crate::provider::Driver::Codex);
|
||||
let handler = Arc::new(Connection { runtime: runtime.clone(), peer: OnceLock::new() });
|
||||
let (a, b) = tokio::io::duplex(1 << 20);
|
||||
let (r, w) = tokio::io::split(b);
|
||||
let server = Peer::connect_framed(r, w, handler.clone(), Framing::Lines);
|
||||
handler.peer.set(server.clone()).ok().unwrap();
|
||||
runtime.servers.lock().push(server);
|
||||
attach(client, |events| {
|
||||
let (r, w) = tokio::io::split(a);
|
||||
Ok(Peer::connect_framed(r, w, events, Framing::Lines))
|
||||
})
|
||||
}),
|
||||
)
|
||||
}
|
||||
fn prompt() -> AgentPrompt {
|
||||
AgentPrompt { text: "fixture".into(), ..Default::default() }
|
||||
}
|
||||
async fn ready(mgr: &AgentManager, id: &str) {
|
||||
tokio::time::timeout(Duration::from_secs(10), async {
|
||||
loop {
|
||||
let task = mgr.task(id).unwrap();
|
||||
let (status, busy) = {
|
||||
let s = task.state.lock();
|
||||
(s.task.status, s.busy)
|
||||
};
|
||||
assert_ne!(status, AgentStatus::Failed);
|
||||
if status == AgentStatus::Ready && !busy {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(5)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
async fn send(mgr: &AgentManager, id: &str) {
|
||||
mgr.prompt(id, prompt(), false).await.unwrap();
|
||||
ready(mgr, id).await;
|
||||
}
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn explicit_tier_survives_standard_only_reconnect_before_immediate_prompt() {
|
||||
for late_model in [0, 1, 2, 3] {
|
||||
for choice in [Some("true"), Some("false"), None] {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let runtime = Arc::new(Runtime::default());
|
||||
let mgr = manager(tmp.path(), runtime.clone());
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
provider: "codex".into(),
|
||||
prompt: prompt(),
|
||||
isolation: Isolation::Local,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
ready(&mgr, &task.id).await;
|
||||
let catalog_config = mgr.task(&task.id).unwrap().state.lock().task.config.clone();
|
||||
if let Some(value) = choice {
|
||||
mgr.set_config(&task.id, "service_tier", value.into()).await.unwrap();
|
||||
}
|
||||
send(&mgr, &task.id).await;
|
||||
assert_eq!(
|
||||
runtime.turns.lock().last().unwrap().get("serviceTier"),
|
||||
choice.map(|v| json!(if v == "true" { "fast" } else { "default" })).as_ref()
|
||||
);
|
||||
mgr.set_config(&task.id, "model", "b".into()).await.unwrap();
|
||||
assert!(!mgr.task(&task.id).unwrap().state.lock().task.config.iter().any(|o| o.id == "service_tier"));
|
||||
send(&mgr, &task.id).await;
|
||||
assert_eq!(
|
||||
runtime.turns.lock().last().unwrap().get("serviceTier"),
|
||||
choice.map(|_| json!("default")).as_ref()
|
||||
);
|
||||
mgr.shutdown();
|
||||
drop(mgr);
|
||||
runtime.hide_a.store(late_model >= 2, std::sync::atomic::Ordering::SeqCst);
|
||||
let mut mgr = manager(tmp.path(), runtime.clone());
|
||||
send(&mgr, &task.id).await; // Reconnect while still on Standard-only B.
|
||||
assert!(!mgr.task(&task.id).unwrap().state.lock().task.config.iter().any(|o| o.id == "service_tier"));
|
||||
assert_eq!(
|
||||
runtime.turns.lock().last().unwrap().get("serviceTier"),
|
||||
choice.map(|_| json!("default")).as_ref()
|
||||
);
|
||||
if late_model != 0 {
|
||||
// Catalog knows A, but the session's picker has not received it yet.
|
||||
let current = mgr.task(&task.id).unwrap();
|
||||
let mut s = current.state.lock();
|
||||
let catalog = serde_json::from_value(
|
||||
json!({"fingerprint":"fixture", "schema":2, "config":catalog_config, "thoughtLevels":{"a":catalog_config.iter().filter(|o|crate::config::is_per_model_option(o)).collect::<Vec<_>>() }}),
|
||||
)
|
||||
.unwrap();
|
||||
mgr.shared
|
||||
.known
|
||||
.lock()
|
||||
.entry("codex".into())
|
||||
.or_default()
|
||||
.catalogs
|
||||
.insert(mgr.shared.root_key(), catalog);
|
||||
s.task.config.iter_mut().find(|o| o.id == "model").unwrap().values.retain(|v| v.value != "a");
|
||||
}
|
||||
mgr.set_config(&task.id, "model", "a".into()).await.unwrap();
|
||||
if late_model == 3 {
|
||||
// An older saved pending switch has no retained intent field.
|
||||
mgr.task(&task.id).unwrap().state.lock().pending_model.as_mut().unwrap().retained_service_tier = None;
|
||||
mgr.shutdown();
|
||||
mgr = manager(tmp.path(), runtime.clone());
|
||||
}
|
||||
let displayed = mgr
|
||||
.task(&task.id)
|
||||
.unwrap()
|
||||
.state
|
||||
.lock()
|
||||
.snapshot()
|
||||
.config
|
||||
.iter()
|
||||
.find(|o| o.id == "service_tier")
|
||||
.unwrap()
|
||||
.current
|
||||
.clone();
|
||||
assert_eq!(displayed.as_deref(), Some(choice.unwrap_or("true")));
|
||||
send(&mgr, &task.id).await; // No sleeps/retries between selecting A and submitting.
|
||||
assert_eq!(
|
||||
runtime.turns.lock().last().unwrap().get("serviceTier"),
|
||||
choice.map(|v| json!(if v == "true" { "fast" } else { "default" })).as_ref()
|
||||
);
|
||||
let other = mgr
|
||||
.create(NewAgentTask {
|
||||
provider: "codex".into(),
|
||||
prompt: prompt(),
|
||||
isolation: Isolation::Local,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
ready(&mgr, &other.id).await;
|
||||
assert!(
|
||||
runtime.turns.lock().last().unwrap().get("serviceTier").is_none(),
|
||||
"choices must not leak to another task"
|
||||
);
|
||||
mgr.shutdown();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -110,7 +110,8 @@ for line in sys.stdin:
|
||||
cursor = request['params']['cursor']
|
||||
model = 'one' if cursor is None else 'two'
|
||||
result = {'data': [{'id': model, 'isDefault': cursor is None,
|
||||
'defaultReasoningEffort': 'low', 'supportedReasoningEfforts': [{'reasoningEffort': 'low'}]}],
|
||||
'defaultReasoningEffort': 'low', 'supportedReasoningEfforts': [{'reasoningEffort': 'low'}],
|
||||
'serviceTiers': [{'id': 'fast', 'name': 'Fast', 'description': ''}] if cursor is None else []}],
|
||||
'nextCursor': 'second-page' if cursor is None else None}
|
||||
else:
|
||||
raise RuntimeError('must not create a thread or prompt: ' + method)
|
||||
@@ -125,6 +126,7 @@ for line in sys.stdin:
|
||||
driver: crate::provider::Driver::Codex,
|
||||
command: script.to_string_lossy().into_owned(),
|
||||
args: Vec::new(),
|
||||
additional_args_len: 0,
|
||||
env: Vec::new(),
|
||||
login_hint: String::new(),
|
||||
source: crate::AgentSource::Builtin,
|
||||
@@ -138,6 +140,9 @@ for line in sys.stdin:
|
||||
.collect();
|
||||
assert_eq!(models, ["one", "two"]);
|
||||
assert_eq!(found.levels.keys().map(String::as_str).collect::<Vec<_>>(), ["one", "two"]);
|
||||
assert!(found.config.iter().any(|o| o.id == SERVICE_TIER));
|
||||
assert!(found.levels["one"].iter().any(|o| o.id == SERVICE_TIER));
|
||||
assert!(found.levels["two"].iter().all(|o| o.id != SERVICE_TIER));
|
||||
let requests = std::fs::read_to_string(tmp.path().join("requests")).unwrap();
|
||||
let requests: Vec<Value> = requests.lines().map(|line| serde_json::from_str(line).unwrap()).collect();
|
||||
assert_eq!(
|
||||
@@ -162,6 +167,72 @@ for line in sys.stdin:
|
||||
|
||||
// ---- Pure translations -------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn fast_is_offered_only_when_the_model_advertises_it() {
|
||||
for capability in [
|
||||
json!({ "additionalSpeedTiers": ["fast"] }),
|
||||
json!({ "serviceTiers": [{ "id": "fast", "name": "Fast", "description": "" }] }),
|
||||
json!({ "serviceTiers": [{ "id": "priority", "name": "Fast", "description": "" }] }),
|
||||
] {
|
||||
let mut model = json!({ "id": "supported", "isDefault": true });
|
||||
model.as_object_mut().unwrap().extend(capability.as_object().unwrap().clone());
|
||||
let models = models_of(&json!({ "data": [model, { "id": "unsupported" }] }));
|
||||
let mut settings = Settings::of(&json!({}), &models);
|
||||
let options = config_options(&models, &settings);
|
||||
let fast = options.as_array().unwrap().iter().find(|o| o["id"] == "service_tier").expect("Fast option");
|
||||
assert_eq!(fast["category"], "model_config");
|
||||
assert_eq!(fast["currentValue"], "false");
|
||||
assert!(settings.set(&models, "service_tier", "true").is_ok());
|
||||
assert!(settings.set(&models, "service_tier", "invalid").is_err());
|
||||
let selected = settings.service_tier_override(&models).map(str::to_owned);
|
||||
settings.set(&models, "model", "unsupported").unwrap();
|
||||
assert!(config_options(&models, &settings).as_array().unwrap().iter().all(|o| o["id"] != "service_tier"));
|
||||
assert!(settings.set(&models, "service_tier", "true").is_err());
|
||||
assert_eq!(settings.service_tier_override(&models), Some("default"));
|
||||
settings.set(&models, "model", "supported").unwrap();
|
||||
assert_eq!(settings.service_tier_override(&models), selected.as_deref());
|
||||
let options = config_options(&models, &settings);
|
||||
assert_eq!(
|
||||
options.as_array().unwrap().iter().find(|o| o["id"] == SERVICE_TIER).unwrap()["currentValue"],
|
||||
"true"
|
||||
);
|
||||
}
|
||||
for capability in [json!({}), json!({ "additionalSpeedTiers": [] }), json!({ "serviceTiers": [] })] {
|
||||
let mut model = json!({ "id": "old", "isDefault": true });
|
||||
model.as_object_mut().unwrap().extend(capability.as_object().unwrap().clone());
|
||||
let models = models_of(&json!({ "data": [model] }));
|
||||
let settings = Settings::of(&json!({}), &models);
|
||||
assert!(config_options(&models, &settings).as_array().unwrap().iter().all(|o| o["id"] != "service_tier"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fast_defaults_do_not_become_user_overrides() {
|
||||
let models = models_of(&json!({ "data": [{
|
||||
"id": "m", "isDefault": true, "defaultServiceTier": "fast",
|
||||
"serviceTiers": [{ "id": "fast", "name": "Fast", "description": "" }]
|
||||
}] }));
|
||||
for (reported, current) in [
|
||||
(json!({}), "true"),
|
||||
(json!({ "serviceTier": null }), "false"),
|
||||
(json!({ "serviceTier": "fast" }), "true"),
|
||||
(json!({ "serviceTier": "priority" }), "true"),
|
||||
(json!({ "serviceTier": "default" }), "false"),
|
||||
] {
|
||||
let mut settings = Settings::of(&reported, &models);
|
||||
let options = config_options(&models, &settings);
|
||||
assert_eq!(
|
||||
options.as_array().unwrap().iter().find(|o| o["id"] == SERVICE_TIER).unwrap()["currentValue"],
|
||||
current
|
||||
);
|
||||
assert_eq!(settings.service_tier_override(&models), None);
|
||||
settings.set(&models, SERVICE_TIER, "true").unwrap();
|
||||
assert_eq!(settings.service_tier_override(&models), Some("fast"));
|
||||
settings.set(&models, SERVICE_TIER, "false").unwrap();
|
||||
assert_eq!(settings.service_tier_override(&models), Some("default"));
|
||||
}
|
||||
}
|
||||
|
||||
fn models() -> Vec<ModelInfo> {
|
||||
models_of(&json!({"data": [
|
||||
{"id": "big", "model": "big", "displayName": "Big", "description": "d", "hidden": false, "isDefault": true,
|
||||
@@ -185,6 +256,8 @@ fn settings_follow_the_thread_and_the_models() {
|
||||
Settings {
|
||||
model: "big".into(),
|
||||
effort: Some("low".into()),
|
||||
service_tier: None,
|
||||
fast_override: None,
|
||||
mode: Mode::Ask,
|
||||
collaboration_mode: DEFAULT_COLLABORATION_MODE.into(),
|
||||
collaboration_mode_override: None,
|
||||
@@ -648,6 +721,7 @@ enum Scenario {
|
||||
Steer,
|
||||
Simple,
|
||||
MultiTurn,
|
||||
ServiceTier { first: Option<bool>, second: Option<bool> },
|
||||
Approvals,
|
||||
UsageLimit,
|
||||
Subagent,
|
||||
@@ -666,6 +740,7 @@ impl Scenario {
|
||||
Scenario::Steer => "steer",
|
||||
Scenario::Simple => "simple",
|
||||
Scenario::MultiTurn => "multi_turn",
|
||||
Scenario::ServiceTier { .. } => "multi_turn",
|
||||
Scenario::Approvals => "approvals",
|
||||
Scenario::UsageLimit => "usage_limit",
|
||||
Scenario::Subagent => "subagent",
|
||||
@@ -772,6 +847,16 @@ async fn drive(scenario: Scenario, acp: &Peer, client: &Client, cwd: &str, threa
|
||||
out.push(("effort", request(acp, "session/set_config_option", set(EFFORT, "high")).await));
|
||||
out.push(("second", request(acp, "session/prompt", prompt("Reply with: two")).await));
|
||||
}
|
||||
Scenario::ServiceTier { first, second } => {
|
||||
for (label, choice) in [("first", first), ("second", second)] {
|
||||
if let Some(fast) = choice {
|
||||
request(acp, "session/set_config_option", set(SERVICE_TIER, if fast { "true" } else { "false" }))
|
||||
.await
|
||||
.expect("the model advertises Fast");
|
||||
}
|
||||
out.push((label, request(acp, "session/prompt", prompt("Reply with: hi")).await));
|
||||
}
|
||||
}
|
||||
Scenario::Approvals => {
|
||||
client.answers.lock().extend([Some("accept"), None]);
|
||||
out.push(("prompt", request(acp, "session/prompt", prompt("Run `touch b.txt`, then write a.txt.")).await));
|
||||
@@ -1304,6 +1389,44 @@ fn thread_names_are_the_first_line_of_the_reply() {
|
||||
assert_eq!(thread_name(&"x".repeat(100)).map(|n| n.chars().count()), Some(80));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn fast_selection_reaches_the_first_and_next_turn_and_standard_clears_it() {
|
||||
for (first, second, expected) in [
|
||||
(Some(true), Some(false), [Some("fast"), Some("default")]),
|
||||
(Some(false), Some(true), [Some("default"), Some("fast")]),
|
||||
(Some(true), None, [Some("fast"), Some("fast")]),
|
||||
(None, None, [None, None]),
|
||||
] {
|
||||
let scenario = Scenario::ServiceTier { first, second };
|
||||
let mut transcript = load(scenario.file());
|
||||
for (out, frame) in &mut transcript.frames {
|
||||
if *out {
|
||||
continue;
|
||||
}
|
||||
if let Some(models) = frame.pointer_mut("/result/data").and_then(Value::as_array_mut) {
|
||||
for model in models {
|
||||
model["serviceTiers"] = json!([{ "id": "fast", "name": "Fast", "description": "" }]);
|
||||
model["defaultServiceTier"] = json!("fast");
|
||||
}
|
||||
}
|
||||
if frame.pointer("/result/thread").is_some() {
|
||||
frame["result"]["serviceTier"] = json!("fast");
|
||||
}
|
||||
}
|
||||
let (results, _client, frames, _meta, _codex) = replay_transcript(scenario, transcript).await;
|
||||
assert!(result(&results, "first").is_ok());
|
||||
assert!(result(&results, "second").is_ok());
|
||||
let starts = sent(&frames, "turn/start");
|
||||
assert_eq!(starts.len(), 2);
|
||||
for (start, expected) in starts.iter().zip(expected) {
|
||||
assert_eq!(start["params"].get("serviceTier"), expected.map(|value| json!(value)).as_ref());
|
||||
assert!(start["params"].get("serviceTierForTurn").is_none());
|
||||
}
|
||||
assert!(sent(&frames, "turn/settings/update").is_empty());
|
||||
assert!(sent(&frames, "config/value/write").is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn settings_apply_to_the_next_turn() {
|
||||
let (results, client, frames, _) = replay(Scenario::MultiTurn).await;
|
||||
@@ -1891,3 +2014,40 @@ fn workspace_roots_join_the_thread_roots() {
|
||||
apply_thread_config(&json!({ "cwd": "/w/api", "mcpServers": [] }), &mut request);
|
||||
assert!(request.get("runtimeWorkspaceRoots").is_none());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn an_ephemeral_session_starts_an_ephemeral_thread() {
|
||||
for ephemeral in [true, false] {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let cwd = tmp.path().to_string_lossy().into_owned();
|
||||
let server = Arc::new(TrustServer {
|
||||
cwd: cwd.clone(),
|
||||
disabled: false,
|
||||
other_project: false,
|
||||
write_error: false,
|
||||
overridden: false,
|
||||
calls: Mutex::default(),
|
||||
});
|
||||
let client = Arc::new(Client::default());
|
||||
let (ours, theirs) = tokio::io::duplex(1 << 16);
|
||||
let (read, write) = tokio::io::split(theirs);
|
||||
let native = Peer::connect_framed(read, write, server.clone(), Framing::Lines);
|
||||
let acp = attach(client.clone(), |events| {
|
||||
let (read, write) = tokio::io::split(ours);
|
||||
Ok(Peer::connect_framed(read, write, events, Framing::Lines))
|
||||
})
|
||||
.unwrap();
|
||||
request(&acp, "initialize", json!({})).await.unwrap();
|
||||
let mut params = json!({"cwd": cwd, "mcpServers": []});
|
||||
if ephemeral {
|
||||
params["_meta"] = json!({"openidea": {"ephemeral": true}});
|
||||
}
|
||||
request(&acp, "session/new", params).await.unwrap();
|
||||
let calls = server.calls.lock();
|
||||
let (_, start) = calls.iter().find(|(m, _)| m == "thread/start").unwrap();
|
||||
assert_eq!(start.get("ephemeral"), ephemeral.then_some(&Value::Bool(true)), "{start}");
|
||||
drop(calls);
|
||||
acp.kill();
|
||||
native.kill();
|
||||
}
|
||||
}
|
||||
@@ -97,6 +97,8 @@ pub(super) struct ModelInfo {
|
||||
/// `(effort, description)`.
|
||||
pub efforts: Vec<(String, String)>,
|
||||
pub default_effort: Option<String>,
|
||||
pub fast_tier: Option<String>,
|
||||
pub default_service_tier: Option<String>,
|
||||
pub is_default: bool,
|
||||
pub hidden: bool,
|
||||
}
|
||||
@@ -123,6 +125,22 @@ pub(super) fn models_of(list: &Value) -> Vec<ModelInfo> {
|
||||
})
|
||||
.collect(),
|
||||
default_effort: str_of(m, "defaultReasoningEffort"),
|
||||
fast_tier: m
|
||||
.get("serviceTiers")
|
||||
.and_then(Value::as_array)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|tier| tier.get("id").and_then(Value::as_str))
|
||||
.chain(
|
||||
m.get("additionalSpeedTiers")
|
||||
.and_then(Value::as_array)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(Value::as_str),
|
||||
)
|
||||
.find(|tier| is_fast_tier(tier))
|
||||
.map(str::to_owned),
|
||||
default_service_tier: str_of(m, "defaultServiceTier"),
|
||||
is_default: m.get("isDefault").and_then(Value::as_bool) == Some(true),
|
||||
hidden: m.get("hidden").and_then(Value::as_bool) == Some(true),
|
||||
id,
|
||||
@@ -137,6 +155,9 @@ pub(super) struct Settings {
|
||||
/// A model id from `model/list`, or the one the thread reported.
|
||||
pub model: String,
|
||||
pub effort: Option<String>,
|
||||
pub service_tier: Option<String>,
|
||||
/// No choice preserves the runtime's default; false explicitly selects Standard.
|
||||
pub fast_override: Option<bool>,
|
||||
pub mode: Mode,
|
||||
/// Codex's Default/Plan collaboration mode. It is sent with each turn because it is
|
||||
/// part of the turn contract rather than the sandbox permission mode above.
|
||||
@@ -158,6 +179,12 @@ impl Settings {
|
||||
let mut s = Settings {
|
||||
model,
|
||||
effort: str_of(result, "reasoningEffort"),
|
||||
service_tier: match result.get("serviceTier") {
|
||||
// A live thread can explicitly report Standard even when the catalog defaults to Fast.
|
||||
Some(Value::Null) => Some("default".into()),
|
||||
_ => str_of(result, "serviceTier"),
|
||||
},
|
||||
fast_override: None,
|
||||
mode: Mode::of(
|
||||
result.get("approvalPolicy").unwrap_or(&Value::Null),
|
||||
result.get("sandbox").unwrap_or(&Value::Null),
|
||||
@@ -205,6 +232,16 @@ impl Settings {
|
||||
}
|
||||
self.effort = Some(value.to_owned());
|
||||
}
|
||||
SERVICE_TIER => {
|
||||
if !models.iter().any(|m| m.id == self.model && m.fast_tier.is_some()) {
|
||||
return Err(format!("{} has no Fast mode", self.model));
|
||||
}
|
||||
self.fast_override = Some(match value {
|
||||
"true" => true,
|
||||
"false" => false,
|
||||
_ => return Err(format!("unknown Fast mode {value}")),
|
||||
});
|
||||
}
|
||||
MODE => self.mode = Mode::parse(value).ok_or_else(|| format!("unknown mode {value}"))?,
|
||||
COLLABORATION_MODE => {
|
||||
if !matches!(value, DEFAULT_COLLABORATION_MODE | PLAN_COLLABORATION_MODE) {
|
||||
@@ -217,16 +254,32 @@ impl Settings {
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `turn/start.serviceTier`: omission inherits; "default" explicitly resets Fast.
|
||||
pub fn service_tier_override<'a>(&self, models: &'a [ModelInfo]) -> Option<&'a str> {
|
||||
match self.fast_override {
|
||||
Some(true) => Some(
|
||||
models.iter().find(|m| m.id == self.model).and_then(|m| m.fast_tier.as_deref()).unwrap_or("default"),
|
||||
),
|
||||
Some(false) => Some("default"),
|
||||
None => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) const MODEL: &str = "model";
|
||||
pub(super) const EFFORT: &str = "reasoning_effort";
|
||||
pub(super) const SERVICE_TIER: &str = "service_tier";
|
||||
pub(super) const MODE: &str = "mode";
|
||||
pub(super) const COLLABORATION_MODE: &str = "collaboration_mode";
|
||||
pub(super) const DEFAULT_COLLABORATION_MODE: &str = "default";
|
||||
pub(super) const PLAN_COLLABORATION_MODE: &str = "plan";
|
||||
|
||||
/// ACP `configOptions`: model, reasoning effort (for models that have it) and mode.
|
||||
fn is_fast_tier(tier: &str) -> bool {
|
||||
matches!(tier, "fast" | "priority")
|
||||
}
|
||||
|
||||
/// ACP `configOptions`: model, its supported settings and session modes.
|
||||
pub(super) fn config_options(models: &[ModelInfo], s: &Settings) -> Value {
|
||||
let mut model_values: Vec<Value> = models
|
||||
.iter()
|
||||
@@ -253,6 +306,16 @@ pub(super) fn config_options(models: &[ModelInfo], s: &Settings) -> Value {
|
||||
"currentValue": effort, "options": values,
|
||||
}));
|
||||
}
|
||||
if let Some(model) = models.iter().find(|m| m.id == s.model && m.fast_tier.is_some()) {
|
||||
let fast = s.fast_override.unwrap_or_else(|| {
|
||||
s.service_tier.as_deref().or(model.default_service_tier.as_deref()).is_some_and(is_fast_tier)
|
||||
});
|
||||
out.push(json!({
|
||||
"id": SERVICE_TIER, "name": "Fast", "category": "model_config", "type": "select",
|
||||
"currentValue": if fast { "true" } else { "false" },
|
||||
"options": [select_value("false", "Standard", None), select_value("true", "Fast", None)],
|
||||
}));
|
||||
}
|
||||
out.push(json!({
|
||||
"id": MODE, "name": "Mode", "category": "mode", "type": "select", "currentValue": s.mode.id(),
|
||||
"options": Mode::ALL.iter().map(|m| select_value(m.id(), m.name(), Some(m.description()))).collect::<Vec<_>>(),
|
||||
|
||||
@@ -751,3 +751,47 @@ async fn stop_ends_a_turn_left_running_only_by_background_shells() {
|
||||
assert_eq!(res["stopReason"], "cancelled");
|
||||
assert!(!server.calls.lock().iter().any(|(m, _)| m == "session.abort"));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn session_new_and_load_forward_staged_skill_directories_and_disabled_skills() {
|
||||
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": {
|
||||
"skills": {
|
||||
"copilotSkillDirectories": ["/farm/task-1/copilot"],
|
||||
"copilotDisabledSkills": ["muted", "off"],
|
||||
}
|
||||
}
|
||||
});
|
||||
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["skillDirectories"], json!(["/farm/task-1/copilot"]), "{method}: {params}");
|
||||
assert_eq!(params["disabledSkills"], json!(["muted", "off"]), "{method}: {params}");
|
||||
assert!(params.get("enableConfigDiscovery").is_none(), "{method} must not auto-enable workspace MCP discovery");
|
||||
}
|
||||
}
|
||||
@@ -33,6 +33,8 @@ pub(crate) struct ProviderSpec {
|
||||
pub driver: Driver,
|
||||
pub command: String,
|
||||
pub args: Vec<String>,
|
||||
/// Number of trailing arguments added by the built-in agent's settings.
|
||||
pub additional_args_len: usize,
|
||||
pub env: Vec<(String, String)>,
|
||||
/// How to sign in when the agent reports it needs authentication.
|
||||
pub login_hint: String,
|
||||
@@ -96,6 +98,7 @@ fn builtins() -> Vec<ProviderSpec> {
|
||||
driver: *driver,
|
||||
command: cmd[0].into(),
|
||||
args: cmd[1..].iter().map(|a| (*a).to_owned()).collect(),
|
||||
additional_args_len: 0,
|
||||
env: Vec::new(),
|
||||
login_hint: (*hint).into(),
|
||||
source: AgentSource::Builtin,
|
||||
@@ -347,16 +350,28 @@ pub(crate) fn is_unlisted(spec: &ProviderSpec) -> bool {
|
||||
UNLISTED.contains(&spec.id.as_str()) && builtin_spec(&spec.id).as_ref() == Some(spec)
|
||||
}
|
||||
|
||||
fn uses_package_runner(command: &str) -> bool {
|
||||
matches!(command, "npx" | "bunx" | "uvx")
|
||||
}
|
||||
|
||||
fn allows_additional_args(builtin: &ProviderSpec, driver: Driver) -> bool {
|
||||
builtin.driver == Driver::Acp && driver == Driver::Acp && !uses_package_runner(&builtin.command)
|
||||
}
|
||||
|
||||
/// Public launch metadata, keeping the built-in defaults separate from agent-file overrides.
|
||||
pub(crate) fn describe(spec: &ProviderSpec) -> AgentProvider {
|
||||
let builtin = builtin_spec(&spec.id);
|
||||
let reason = if matches!(spec.source, AgentSource::Registry { .. }) {
|
||||
Some(AgentCommandReadOnlyReason::Registry)
|
||||
} else if let Some(default) = &builtin {
|
||||
matches!(default.command.as_str(), "npx" | "bunx" | "uvx").then_some(AgentCommandReadOnlyReason::PackageRunner)
|
||||
uses_package_runner(&default.command).then_some(AgentCommandReadOnlyReason::PackageRunner)
|
||||
} else {
|
||||
Some(AgentCommandReadOnlyReason::CustomAgent)
|
||||
};
|
||||
let additional_args = builtin
|
||||
.as_ref()
|
||||
.filter(|b| reason.is_none() && allows_additional_args(b, spec.driver))
|
||||
.map(|_| spec.args[spec.args.len() - spec.additional_args_len..].to_vec());
|
||||
AgentProvider {
|
||||
id: spec.id.clone(),
|
||||
name: spec.name.clone(),
|
||||
@@ -366,6 +381,7 @@ pub(crate) fn describe(spec: &ProviderSpec) -> AgentProvider {
|
||||
.join(" "),
|
||||
program: spec.command.clone(),
|
||||
args: spec.args.clone(),
|
||||
additional_args,
|
||||
default_program: builtin.as_ref().map(|b| b.command.clone()),
|
||||
default_args: builtin.as_ref().map(|b| b.args.clone()).unwrap_or_default(),
|
||||
login_hint: Some(spec.login_hint(&ide_jsonrpc::resolve_spawn_program(&spec.command, &spec.env))),
|
||||
@@ -391,7 +407,24 @@ pub(crate) fn set_builtin_command(
|
||||
command: Option<&str>,
|
||||
) -> IdeResult<()> {
|
||||
update_builtin(custom_dir, secrets, id, |agent, builtin| {
|
||||
agent.command = command.unwrap_or(&builtin.command).to_owned()
|
||||
agent.command = command.unwrap_or(&builtin.command).to_owned();
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
/// Appends arguments to a directly launched built-in ACP agent; an empty list resets them.
|
||||
pub(crate) fn set_builtin_additional_args(
|
||||
custom_dir: &Path,
|
||||
secrets: Option<&dyn EnvSecrets>,
|
||||
id: &str,
|
||||
args: Vec<String>,
|
||||
) -> IdeResult<()> {
|
||||
update_builtin(custom_dir, secrets, id, |agent, builtin| {
|
||||
if !allows_additional_args(builtin, agent.driver) {
|
||||
return Err(IdeError::invalid(format!("{id} does not support additional arguments")));
|
||||
}
|
||||
agent.additional_args = args;
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
@@ -427,7 +460,10 @@ pub(crate) fn set_builtin_env(
|
||||
return agent.write(&file).map_err(Into::into);
|
||||
}
|
||||
}
|
||||
update_builtin(custom_dir, secrets, id, |agent, _| agent.env = env)
|
||||
update_builtin(custom_dir, secrets, id, |agent, _| {
|
||||
agent.env = env;
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
/// Changes built-in `id`'s agent file; a file left with only the built-in's values is removed.
|
||||
@@ -435,7 +471,7 @@ fn update_builtin(
|
||||
custom_dir: &Path,
|
||||
secrets: Option<&dyn EnvSecrets>,
|
||||
id: &str,
|
||||
change: impl FnOnce(&mut CustomAgent, &ProviderSpec),
|
||||
change: impl FnOnce(&mut CustomAgent, &ProviderSpec) -> IdeResult<()>,
|
||||
) -> IdeResult<()> {
|
||||
let Some(builtin) = builtin_spec(id) else {
|
||||
return Err(IdeError::invalid(format!("{id} is not a built-in agent")));
|
||||
@@ -449,6 +485,7 @@ fn update_builtin(
|
||||
driver: builtin.driver,
|
||||
command: builtin.command.clone(),
|
||||
args: builtin.args.clone(),
|
||||
additional_args: Vec::new(),
|
||||
env: BTreeMap::new(),
|
||||
registry: None,
|
||||
}
|
||||
@@ -456,11 +493,12 @@ fn update_builtin(
|
||||
if agent.registry.is_some() {
|
||||
return Err(IdeError::invalid(format!("{id} is installed from the ACP Registry")));
|
||||
}
|
||||
change(&mut agent, &builtin);
|
||||
change(&mut agent, &builtin)?;
|
||||
if agent.command == builtin.command
|
||||
&& agent.name.as_deref() == Some(builtin.name.as_str())
|
||||
&& agent.driver == builtin.driver
|
||||
&& agent.args == builtin.args
|
||||
&& agent.additional_args.is_empty()
|
||||
&& agent.env.is_empty()
|
||||
{
|
||||
match std::fs::remove_file(&file) {
|
||||
@@ -502,6 +540,7 @@ pub(crate) fn save_custom(
|
||||
driver: Driver::Acp,
|
||||
command: input.command.clone(),
|
||||
args: input.args.clone(),
|
||||
additional_args: Vec::new(),
|
||||
env: input.env.clone(),
|
||||
registry: None,
|
||||
}
|
||||
@@ -572,6 +611,7 @@ pub(crate) fn import_acp(
|
||||
driver: Driver::Acp,
|
||||
command: server.command,
|
||||
args: server.args,
|
||||
additional_args: Vec::new(),
|
||||
env: server.env,
|
||||
registry: None,
|
||||
}
|
||||
@@ -615,6 +655,9 @@ pub(crate) struct CustomAgent {
|
||||
pub command: String,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub args: Vec<String>,
|
||||
/// Kept separate from `args` so Settings reset does not erase a hand-written launch line.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub additional_args: Vec<String>,
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub env: BTreeMap<String, String>,
|
||||
/// Set when the agent was installed from the ACP Registry.
|
||||
@@ -746,6 +789,7 @@ pub(crate) fn load(custom_dir: Option<&Path>, secrets: Option<&dyn EnvSecrets>)
|
||||
driver: agent.driver,
|
||||
command: agent.command,
|
||||
args: agent.args,
|
||||
additional_args_len: 0,
|
||||
env,
|
||||
login_hint: "Sign in with the agent's own command line first.".into(),
|
||||
source,
|
||||
@@ -763,6 +807,10 @@ pub(crate) fn load(custom_dir: Option<&Path>, secrets: Option<&dyn EnvSecrets>)
|
||||
spec.args = crate::native::copilot::headless_args(&spec.args);
|
||||
}
|
||||
if spec.source == AgentSource::Custom {
|
||||
if allows_additional_args(existing, spec.driver) {
|
||||
spec.additional_args_len = agent.additional_args.len();
|
||||
spec.args.extend(agent.additional_args);
|
||||
}
|
||||
spec.source = AgentSource::Builtin;
|
||||
}
|
||||
*existing = spec;
|
||||
@@ -1043,6 +1091,53 @@ mod tests {
|
||||
set_builtin_env(dir.path(), None, "not-a-builtin", env).unwrap_err();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn additional_args_append_and_reset_without_replacing_agent_file_overrides() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
let omp = || load(Some(root), None).into_iter().find(|spec| spec.id == "omp").unwrap();
|
||||
assert_eq!(describe(&omp()).additional_args, Some(vec![]));
|
||||
set_builtin_additional_args(root, None, "omp", vec!["--extra".into()]).unwrap();
|
||||
assert_eq!(omp().args, ["acp", "--extra"]);
|
||||
set_builtin_additional_args(root, None, "omp", vec![]).unwrap();
|
||||
assert!(!root.join("omp.toml").exists());
|
||||
|
||||
let file = root.join("omp.toml");
|
||||
std::fs::write(
|
||||
&file,
|
||||
"name = \"My OMP\"\ncommand = \"/opt/my tools/omp\"\nargs = [\"acp\", \"--manual\"]\n[env]\nKEEP = \"value\"\n",
|
||||
)
|
||||
.unwrap();
|
||||
let original = omp();
|
||||
let extra = vec!["--label".into(), "two words".into(), String::new()];
|
||||
set_builtin_additional_args(root, None, "omp", extra.clone()).unwrap();
|
||||
let configured = omp();
|
||||
assert_eq!(configured.args, ["acp", "--manual", "--label", "two words", ""]);
|
||||
assert_eq!(describe(&configured).additional_args, Some(extra));
|
||||
set_builtin_additional_args(root, None, "omp", vec![]).unwrap();
|
||||
assert_eq!(omp(), original);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn additional_args_cannot_modify_managed_or_non_acp_launches() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
std::fs::write(
|
||||
root.join("gemini.toml"),
|
||||
"command = \"gemini\"\nargs = [\"--experimental-acp\"]\n[registry]\nid = \"gemini\"\nversion = \"1\"\n",
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::write(root.join("mine.toml"), "command = \"mine\"\n").unwrap();
|
||||
std::fs::write(root.join("omp.toml"), "command = \"omp\"\ndriver = \"codex\"\n").unwrap();
|
||||
let before = load(Some(root), None);
|
||||
for id in ["gemini", "mine", "omp", "codex", "claude-acp"] {
|
||||
let spec = before.iter().find(|spec| spec.id == id).unwrap();
|
||||
assert!(describe(spec).additional_args.is_none());
|
||||
assert!(set_builtin_additional_args(root, None, id, vec!["--extra".into()]).is_err());
|
||||
}
|
||||
assert_eq!(load(Some(root), None), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn registry_copilot_allows_only_the_github_account_override() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
@@ -1052,6 +1147,7 @@ mod tests {
|
||||
driver: Driver::Acp,
|
||||
command: "/tools/copilot".into(),
|
||||
args: vec!["--acp".into()],
|
||||
additional_args: Vec::new(),
|
||||
env: BTreeMap::from([("REGISTRY_SETTING".into(), "kept".into())]),
|
||||
registry: Some(RegistryRef { id: "copilot".into(), version: "1.0.0".into() }),
|
||||
}
|
||||
@@ -1108,6 +1204,7 @@ mod tests {
|
||||
driver: Driver::Acp,
|
||||
command: "amp".into(),
|
||||
args: vec![],
|
||||
additional_args: Vec::new(),
|
||||
env: BTreeMap::new(),
|
||||
registry: Some(RegistryRef { id: "amp-acp".into(), version: "1.0.0".into() }),
|
||||
}
|
||||
@@ -1133,6 +1230,7 @@ mod tests {
|
||||
driver: Driver::Claude,
|
||||
command: "/old/claude".into(),
|
||||
args: vec![],
|
||||
additional_args: Vec::new(),
|
||||
env: BTreeMap::new(),
|
||||
registry: None,
|
||||
};
|
||||
@@ -1186,6 +1284,7 @@ mod tests {
|
||||
driver: Driver::Acp,
|
||||
command: "/data/agents/tools/amp-acp/0.10.0/amp-acp".into(),
|
||||
args: vec!["acp".into()],
|
||||
additional_args: Vec::new(),
|
||||
env: BTreeMap::from([("K".to_owned(), "v".to_owned())]),
|
||||
registry: Some(RegistryRef { id: "amp-acp".into(), version: "0.10.0".into() }),
|
||||
};
|
||||
|
||||
@@ -550,6 +550,7 @@ fn install_entry_with(
|
||||
driver: Driver::Acp,
|
||||
command: exe.to_string_lossy().into_owned(),
|
||||
args,
|
||||
additional_args: Vec::new(),
|
||||
env,
|
||||
registry: Some(RegistryRef { id: entry.id.clone(), version: entry.version.clone() }),
|
||||
};
|
||||
@@ -941,6 +942,7 @@ mod tests {
|
||||
driver: Driver::Acp,
|
||||
command: "/x".into(),
|
||||
args: vec![],
|
||||
additional_args: Vec::new(),
|
||||
env: BTreeMap::new(),
|
||||
registry: Some(RegistryRef { id: id.into(), version: version.into() }),
|
||||
};
|
||||
@@ -1168,6 +1170,7 @@ esac
|
||||
driver: Driver::Acp,
|
||||
command: "/data/tools/copilot/1.0.104/node_modules/.bin/copilot".into(),
|
||||
args: vec!["--acp".into()],
|
||||
additional_args: Vec::new(),
|
||||
env: BTreeMap::new(),
|
||||
registry: Some(RegistryRef { id: "copilot".into(), version: "1.0.104".into() }),
|
||||
}
|
||||
|
||||
@@ -649,11 +649,14 @@ pub struct Delivery {
|
||||
|
||||
/// Stages the skills a session of `provider` runs with into `farm` — linking (copying on
|
||||
/// Windows, where directory symlinks need Developer Mode) every active skill folder into
|
||||
/// the CLI's tree — and reports what to hand the CLI. Skills the CLI discovers natively
|
||||
/// (its own folders of the working directory and the home) are not staged again: it already
|
||||
/// sees them, and seeing both would list one skill twice. Skills `off` are never staged;
|
||||
/// the CLI's native disable (where it has one) receives their names or paths. An ACP
|
||||
/// agent gets nothing here: its `/` menu is filtered instead.
|
||||
/// the CLI's tree — and reports what to hand the CLI. For Claude Code and Codex, skills
|
||||
/// the CLI discovers natively (its own folders of the working directory and the home) are
|
||||
/// not staged again so the CLI does not see duplicates. For Copilot (`copilot --headless`),
|
||||
/// config discovery is off by default (enabling it would also auto-load workspace `.mcp.json`
|
||||
/// outside OpenIDEA's MCP approvals), so every active `Auto` skill is staged into
|
||||
/// `skillDirectories`. Skills `off` are never staged; the CLI's native disable (where it has
|
||||
/// one) receives their names or paths. An ACP agent gets nothing here: its `/` menu is
|
||||
/// filtered instead.
|
||||
pub fn stage(
|
||||
farm: &Path,
|
||||
provider: &str,
|
||||
@@ -705,7 +708,7 @@ pub fn stage(
|
||||
if let Some(tree) = claude_tree.as_ref().filter(|_| !native_claude(&state.skill, &cwd, home)) {
|
||||
link_skill(&tree.join(name), path)?;
|
||||
}
|
||||
if let Some(tree) = copilot_tree.as_ref().filter(|_| !native_copilot(&state.skill, &cwd, home)) {
|
||||
if let Some(tree) = copilot_tree.as_ref() {
|
||||
link_skill(&tree.join(name), path)?;
|
||||
}
|
||||
if let Some(tree) = codex_tree.as_ref().filter(|_| !native_codex(&state.skill, &cwd, home)) {
|
||||
@@ -794,29 +797,6 @@ fn native_claude(skill: &AgentSkill, cwd: &Path, home: Option<&Path>) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
/// Copilot natively scans `.github/skills`, `.agents/skills` and `.claude/skills` in `cwd`,
|
||||
/// plus `~/.copilot` and `~/.agents/skills` in `home`. `.openidea/skills` is NOT native.
|
||||
fn native_copilot(skill: &AgentSkill, cwd: &Path, home: Option<&Path>) -> bool {
|
||||
let target = skill.path.0.as_path();
|
||||
for rel in [".github/skills", ".agents/skills", ".claude/skills"] {
|
||||
let root = cwd.join(rel);
|
||||
if is_under(target, &root) || direct_link_matches(&root, &skill.name, target) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
if let Some(h) = home {
|
||||
let h = dunce::canonicalize(h).unwrap_or_else(|_| h.to_path_buf());
|
||||
if is_under(target, &h.join(".copilot"))
|
||||
|| is_under(target, &h.join(".agents/skills"))
|
||||
|| direct_link_matches(&h.join(".copilot/skills"), &skill.name, target)
|
||||
|| direct_link_matches(&h.join(".agents/skills"), &skill.name, target)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Codex natively scans `.codex/skills` and `.agents/skills` in `cwd` and `home`.
|
||||
fn native_codex(skill: &AgentSkill, cwd: &Path, home: Option<&Path>) -> bool {
|
||||
let target = skill.path.0.as_path();
|
||||
@@ -1232,8 +1212,9 @@ mod tests {
|
||||
true,
|
||||
);
|
||||
|
||||
//For a local session, `.github/skills`, `.agents/skills` and `~/.agents/skills` are
|
||||
// already scanned natively by Copilot; `.openidea/skills` and `~/.codex/skills` are staged.
|
||||
// Copilot headless does not run disk config discovery unless explicitly opted in, so
|
||||
// every active `Auto` skill — including `.github/skills`, `.agents/skills`, `~/.agents/skills`,
|
||||
// `~/.copilot/installed-plugins`, `.openidea/skills`, and `~/.codex/skills` — must be staged.
|
||||
let mut states = states;
|
||||
std::fs::create_dir_all(repo.join(".openidea/skills/ideonly")).unwrap();
|
||||
states.push(AgentSkillState {
|
||||
@@ -1241,6 +1222,13 @@ mod tests {
|
||||
mode: AgentSkillMode::Auto,
|
||||
origin: AgentSkillOrigin::None,
|
||||
});
|
||||
let copilot_plugin_skills = home.join(".copilot/installed-plugins/_direct/azure/skills");
|
||||
std::fs::create_dir_all(copilot_plugin_skills.join("azure-ai")).unwrap();
|
||||
states.push(AgentSkillState {
|
||||
skill: skill("azure-ai", AgentSkillSource::CopilotUser, &copilot_plugin_skills),
|
||||
mode: AgentSkillMode::Auto,
|
||||
origin: AgentSkillOrigin::None,
|
||||
});
|
||||
|
||||
let farm = farm_dir(&root.join("store"), "task-1");
|
||||
let delivery = stage(&farm, "claude", &states, &repo, Some(&home)).unwrap();
|
||||
@@ -1249,7 +1237,7 @@ mod tests {
|
||||
let staged = listed(&claude_tree);
|
||||
assert_eq!(
|
||||
staged,
|
||||
["codexy", "gh", "ideonly", "lint", "muted", "tdd"],
|
||||
["azure-ai", "codexy", "gh", "ideonly", "lint", "muted", "tdd"],
|
||||
"everything but the off one: none is native to Claude here, and slash-only needs the folder"
|
||||
);
|
||||
|
||||
@@ -1259,8 +1247,8 @@ mod tests {
|
||||
let copilot_staged = listed(&farm.join("copilot"));
|
||||
assert_eq!(
|
||||
copilot_staged,
|
||||
["codexy", "ideonly"],
|
||||
"`gh` (.github), `tdd` (.agents) and `lint` (~/.agents) are native to Copilot; `.openidea` & `~/.codex` are staged"
|
||||
["azure-ai", "codexy", "gh", "ideonly", "lint", "tdd"],
|
||||
"all active Auto skills (including .github, .agents, ~/.agents, and ~/.copilot/installed-plugins) are staged for Copilot headless"
|
||||
);
|
||||
assert_eq!(
|
||||
delivery.codex_off,
|
||||
@@ -1276,12 +1264,12 @@ mod tests {
|
||||
]
|
||||
);
|
||||
|
||||
// A worktree task: the repo's skills are untracked, so workspace skills are staged now.
|
||||
// A worktree task also stages all active workspace, user, and plugin skills.
|
||||
let worktree = root.join("wt");
|
||||
std::fs::create_dir_all(&worktree).unwrap();
|
||||
let _ = stage(&farm, "copilot", &states, &worktree, Some(&home)).unwrap();
|
||||
let copilot_staged = listed(&farm.join("copilot"));
|
||||
assert!(copilot_staged.contains(&"gh".to_string()) && copilot_staged.contains(&"tdd".to_string()));
|
||||
assert_eq!(copilot_staged, ["azure-ai", "codexy", "gh", "ideonly", "lint", "tdd"]);
|
||||
|
||||
// Slash-only reaches Claude as `user-invocable-only`, off as `off`.
|
||||
let delivery = stage(&farm, "claude", &states, &repo, Some(&home)).unwrap();
|
||||
@@ -1289,7 +1277,7 @@ mod tests {
|
||||
assert_eq!(settings["skillOverrides"]["muted"], "user-invocable-only");
|
||||
assert_eq!(settings["skillOverrides"]["off"], "off");
|
||||
|
||||
// Restaging after a session turned `lint` off drops its link and leaves the skill.
|
||||
// Restaging after a session turned `lint` off drops its link and leaves the skill on disk.
|
||||
let session = BTreeMap::from([("lint".to_owned(), AgentSkillMode::Off)]);
|
||||
let restated = resolve(
|
||||
states.iter().map(|s| s.skill.clone()).collect(),
|
||||
@@ -1299,10 +1287,14 @@ mod tests {
|
||||
true,
|
||||
);
|
||||
stage(&farm, "claude", &restated, &repo, Some(&home)).unwrap();
|
||||
assert_eq!(listed(&claude_tree), ["codexy", "gh", "ideonly", "muted", "tdd"]);
|
||||
assert_eq!(listed(&claude_tree), ["azure-ai", "codexy", "gh", "ideonly", "muted", "tdd"]);
|
||||
assert!(home.join(".agents/skills/lint").is_dir());
|
||||
assert!(farm.join("copilot").is_dir(), "restaging Claude's tree leaves Copilot's alone");
|
||||
|
||||
let delivery = stage(&farm, "copilot", &restated, &repo, Some(&home)).unwrap();
|
||||
assert_eq!(listed(&farm.join("copilot")), ["azure-ai", "codexy", "gh", "ideonly", "tdd"]);
|
||||
assert_eq!(delivery.copilot_disabled_skills, ["lint", "muted", "off"]);
|
||||
|
||||
// An ACP agent gets no farm.
|
||||
let delivery = stage(&farm, "cursor-acp", &states, &repo, Some(&home)).unwrap();
|
||||
assert_eq!(delivery, Delivery::default());
|
||||
|
||||
@@ -63,6 +63,8 @@ struct FakeAgent {
|
||||
session_steering: bool,
|
||||
/// Records the `mcpServers` array passed to `session/new`, `session/load`, and `session/fork`.
|
||||
mcp_calls: Mutex<Vec<(String, Vec<String>)>>,
|
||||
/// The params of every `session/fork`, in order.
|
||||
forks: Mutex<Vec<Value>>,
|
||||
/// The content blocks of each `session/prompt`.
|
||||
prompts: Mutex<Vec<Value>>,
|
||||
}
|
||||
@@ -175,6 +177,9 @@ impl Handler for FakeAgent {
|
||||
})
|
||||
.unwrap_or_default();
|
||||
self.mcp_calls.lock().push((method.to_owned(), names));
|
||||
if params.pointer("/_meta/openidea/ephemeral") == Some(&json!(true)) {
|
||||
self.calls.lock().push("ephemeral".into());
|
||||
}
|
||||
}
|
||||
let session = params.get("sessionId").and_then(Value::as_str).unwrap_or("s1").to_owned();
|
||||
match method {
|
||||
@@ -203,7 +208,11 @@ impl Handler for FakeAgent {
|
||||
"modes": {"currentModeId": "ask", "availableModes": [{"id": "ask", "name": "Ask"}, {"id": "code", "name": "Code"}]},
|
||||
"configOptions": options}))
|
||||
}
|
||||
"session/fork" => Ok(json!({"sessionId": "s2"})),
|
||||
"session/fork" => {
|
||||
self.forks.lock().push(params.clone());
|
||||
let requested = params.pointer("/_meta/openidea/forkSessionId").and_then(Value::as_str);
|
||||
Ok(json!({ "sessionId": requested.unwrap_or("s2") }))
|
||||
}
|
||||
"_openidea/stop_task" => {
|
||||
self.calls.lock().push(format!("{method} {}", params["taskId"]));
|
||||
Ok(json!({}))
|
||||
@@ -642,6 +651,32 @@ async fn saved_conversation_reads_do_not_start_or_load_the_agent() {
|
||||
restored.shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn an_ephemeral_task_is_not_saved_and_asks_for_an_unsaved_session() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
for ephemeral in [true, false] {
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
prompt: text("Write a commit message"),
|
||||
provider: "claude".into(),
|
||||
isolation: Isolation::Local,
|
||||
ephemeral,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
|
||||
assert_eq!(agent.calls.lock().iter().any(|c| c == "ephemeral"), ephemeral);
|
||||
mgr.shutdown();
|
||||
// The caller never deleted it (its window closed): only a saved task comes back.
|
||||
let restored = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
assert_eq!(restored.task(&task.id).is_ok(), !ephemeral);
|
||||
restored.shutdown();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn claude_commands_share_catalog_discovery_and_persist_results() {
|
||||
@@ -2773,6 +2808,128 @@ async fn forks_rollbacks_and_steering() {
|
||||
restored.shutdown();
|
||||
}
|
||||
|
||||
const NATIVE_SOURCE: &str = "11111111-1111-4111-8111-111111111111";
|
||||
const NATIVE_TARGET: &str = "22222222-2222-4222-8222-222222222222";
|
||||
|
||||
/// Plants a recorded claude transcript for `session_id` under the project's escaped folder.
|
||||
fn plant_claude_session(mgr: &AgentManager, root: &Path, session_id: &str) {
|
||||
let config = root.join("claude-config");
|
||||
mgr.set_builtin_env(
|
||||
"claude",
|
||||
[("CLAUDE_CONFIG_DIR".to_string(), config.to_string_lossy().into_owned())].into_iter().collect(),
|
||||
)
|
||||
.unwrap();
|
||||
mgr.reload_providers();
|
||||
let escaped: String =
|
||||
root.to_string_lossy().chars().map(|c| if c.is_ascii_alphanumeric() { c } else { '-' }).collect();
|
||||
let transcript = config.join("projects").join(escaped).join(format!("{session_id}.jsonl"));
|
||||
std::fs::create_dir_all(transcript.parent().unwrap()).unwrap();
|
||||
std::fs::write(
|
||||
&transcript,
|
||||
format!(
|
||||
"{}\n",
|
||||
json!({
|
||||
"type": "user",
|
||||
"uuid": "u1",
|
||||
"parentUuid": null,
|
||||
"message": {"role": "user", "content": "fix the login bug"},
|
||||
"cwd": root.to_string_lossy(),
|
||||
})
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn fork_session_starts_a_ready_task_as_the_recorded_session_s_fork() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
plant_claude_session(&mgr, tmp.path(), NATIVE_SOURCE);
|
||||
|
||||
let task = mgr.fork_session("claude", NATIVE_SOURCE, tmp.path()).unwrap();
|
||||
assert_eq!(task.provider, "claude");
|
||||
assert_eq!(task.status, AgentStatus::Ready);
|
||||
assert_eq!(task.isolation, Isolation::Local);
|
||||
|
||||
mgr.prompt(&task.id, text("again"), true).await.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
|
||||
let forks = agent.forks.lock().clone();
|
||||
assert_eq!(forks.len(), 1, "one fork start");
|
||||
assert_eq!(forks[0]["sessionId"], NATIVE_SOURCE);
|
||||
let target = forks[0]["_meta"]["openidea"]["forkSessionId"].as_str().unwrap();
|
||||
assert!(canonical_uuid(target), "the host chooses a canonical fork id: {target}");
|
||||
assert_ne!(target, NATIVE_SOURCE);
|
||||
assert!(
|
||||
!agent.calls.lock().iter().any(|call| call == "session/new" || call == "session/load"),
|
||||
"the task forks the recorded session instead of starting or loading another"
|
||||
);
|
||||
assert_eq!(mgr.task(&task.id).unwrap().state.lock().session_id.as_deref(), Some(target));
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
/// Plants a recorded codex rollout for `session_id` under the home `.codex/sessions` tree.
|
||||
fn plant_codex_session(root: &Path, session_id: &str) {
|
||||
let dir = root.join(".codex").join("sessions").join("2026").join("11").join("23");
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::write(
|
||||
dir.join(format!("rollout-{session_id}.jsonl")),
|
||||
format!(
|
||||
"{}\n{}\n",
|
||||
json!({"type": "session_meta", "payload": {"id": session_id, "cwd": root.to_string_lossy()}}),
|
||||
json!({"type": "event_msg", "payload": {"type": "user_message", "message": "fix the login bug"}})
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn fork_session_uses_the_id_codex_assigns() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
plant_codex_session(tmp.path(), NATIVE_SOURCE);
|
||||
|
||||
let task = mgr.fork_session("codex", NATIVE_SOURCE, tmp.path()).unwrap();
|
||||
assert_eq!(task.status, AgentStatus::Ready);
|
||||
mgr.prompt(&task.id, text("again"), true).await.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
|
||||
let forks = agent.forks.lock().clone();
|
||||
assert_eq!(forks.len(), 1);
|
||||
assert_eq!(forks[0]["sessionId"], NATIVE_SOURCE);
|
||||
assert!(forks[0].pointer("/_meta/openidea/forkSessionId").is_none(), "codex names its own fork");
|
||||
assert_eq!(mgr.task(&task.id).unwrap().state.lock().session_id.as_deref(), Some("s2"));
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn fork_session_rejects_invalid_input_before_starting() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
plant_claude_session(&mgr, tmp.path(), NATIVE_SOURCE);
|
||||
|
||||
// Non-native provider, malformed id, unknown session, wrong directory.
|
||||
let cases: [(&str, &str, &Path, ide_core::error::ErrorKind); 4] = [
|
||||
("gemini", NATIVE_SOURCE, tmp.path(), ide_core::error::ErrorKind::InvalidInput),
|
||||
("claude", "not-a-uuid", tmp.path(), ide_core::error::ErrorKind::InvalidInput),
|
||||
("claude", NATIVE_TARGET, tmp.path(), ide_core::error::ErrorKind::NotFound),
|
||||
("claude", NATIVE_SOURCE, Path::new("/elsewhere"), ide_core::error::ErrorKind::InvalidInput),
|
||||
];
|
||||
for (index, (provider, id, cwd, kind)) in cases.into_iter().enumerate() {
|
||||
let error = mgr.fork_session(provider, id, cwd).unwrap_err();
|
||||
assert_eq!(error.kind, kind, "case {index}: {error}");
|
||||
}
|
||||
// A session already held by a task cannot be forked again.
|
||||
mgr.import_session("claude", NATIVE_SOURCE).unwrap();
|
||||
let error = mgr.fork_session("claude", NATIVE_SOURCE, tmp.path()).unwrap_err();
|
||||
assert_eq!(error.kind, ide_core::error::ErrorKind::InvalidInput, "{error}");
|
||||
assert!(agent.calls.lock().is_empty(), "no process may start");
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn usage_limits_and_late_settings() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
@@ -3045,6 +3202,46 @@ async fn rapid_idle_model_switches_share_discovery_and_never_apply_a_stale_compl
|
||||
restored.shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn explicit_service_tier_reaches_the_session_even_when_it_matches_the_reported_default() {
|
||||
for value in [None, Some("false"), Some("true")] {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
*agent.extra_options.lock() = vec![json!({
|
||||
"id": "service_tier", "name": "Fast", "category": "model_config", "type": "select",
|
||||
"currentValue": value.unwrap_or("true"),
|
||||
"options": [{"value": "false"}, {"value": "true"}]
|
||||
})];
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
prompt: text("again"),
|
||||
provider: "codex".into(),
|
||||
config: value
|
||||
.map(|value| vec![AgentConfigChoice { id: "service_tier".into(), value: value.into() }])
|
||||
.unwrap_or_default(),
|
||||
isolation: Isolation::Local,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
let calls = agent.calls.lock();
|
||||
let prompt = calls.iter().position(|call| call == "session/prompt").unwrap();
|
||||
if let Some(value) = value {
|
||||
let setting = calls
|
||||
.iter()
|
||||
.position(|call| call == &format!("session/set_config_option \"{value}\""))
|
||||
.expect("an explicit tier must not be mistaken for an inherited default");
|
||||
assert!(setting < prompt);
|
||||
} else {
|
||||
assert!(!calls.iter().any(|call| call == "session/set_config_option"));
|
||||
}
|
||||
drop(calls);
|
||||
mgr.shutdown();
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn upfront_effort_is_validated_after_changing_model_before_the_prompt() {
|
||||
for (effort, applied) in [("medium", true), ("high", false)] {
|
||||
@@ -5421,6 +5618,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(),
|
||||
ephemeral: false,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -5483,6 +5681,7 @@ async fn per_session_skill_overrides_filter_commands_persist_and_reload_when_idl
|
||||
("tdd".into(), AgentSkillMode::Auto),
|
||||
("noisy".into(), AgentSkillMode::Off),
|
||||
]),
|
||||
ephemeral: false,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -5626,6 +5825,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(),
|
||||
ephemeral: false,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -5652,6 +5852,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(),
|
||||
ephemeral: false,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
@@ -9,6 +9,7 @@ mod modules;
|
||||
mod parse;
|
||||
mod single;
|
||||
mod structure;
|
||||
mod tsc_watch;
|
||||
mod up_to_date;
|
||||
|
||||
pub use fingerprint::{LaunchFingerprint, launch_fingerprint, menu_fingerprint};
|
||||
@@ -16,12 +17,14 @@ pub use launch_resources::process_launch_resources;
|
||||
pub use modules::record_module_build;
|
||||
pub use single::{
|
||||
SingleFileTarget, compile_file_plan, compile_file_plan_cancellable, find_javac, gradle_compile_file_plan,
|
||||
has_gradle_file_target, javac_step, module_classpath, module_classpaths, single_file_classpath, single_file_target,
|
||||
has_gradle_file_target, javac_step, module_classpath, module_classpath_without_build, module_classpaths,
|
||||
single_file_classpath, single_file_target,
|
||||
};
|
||||
pub use structure::{
|
||||
StructureJdk, StructureRoots, artifact_file, artifact_output, language_release, structure_compile_file_plan,
|
||||
structure_outputs, structure_plan, structure_war_plan, structure_web_artifacts,
|
||||
};
|
||||
pub use tsc_watch::{tsc_watch, tsc_watch_roots};
|
||||
pub use up_to_date::{menu_up_to_date, record_menu_build};
|
||||
|
||||
use crate::process::{self, Stream};
|
||||
@@ -236,10 +239,13 @@ pub fn plan(
|
||||
let project_name = root.file_name().map_or_else(|| "project".to_owned(), |n| n.to_string_lossy().into_owned());
|
||||
let module_dir = match file {
|
||||
Some(f) => {
|
||||
let scope = model
|
||||
.gradle
|
||||
.iter()
|
||||
.flat_map(|g| std::iter::once(root.join(&g.dir)).chain(g.projects.iter().map(|p| root.join(&p.dir))))
|
||||
let maven_dirs = model.maven.iter().flat_map(|m| m.projects.iter().map(|p| normalize(&root.join(&p.dir))));
|
||||
let gradle_dirs = model.gradle.iter().flat_map(|g| {
|
||||
std::iter::once(normalize(&root.join(&g.dir)))
|
||||
.chain(g.projects.iter().map(|p| normalize(&root.join(&p.dir))))
|
||||
});
|
||||
let scope = maven_dirs
|
||||
.chain(gradle_dirs)
|
||||
.filter(|dir| f.starts_with(dir))
|
||||
.max_by_key(|dir| dir.components().count())
|
||||
.unwrap_or_else(|| root.to_path_buf());
|
||||
@@ -251,10 +257,13 @@ pub fn plan(
|
||||
None => None,
|
||||
};
|
||||
let dir = module_dir.clone().unwrap_or_else(|| root.to_path_buf());
|
||||
// A folder of sibling projects has no build file itself; its Maven projects are built one by one.
|
||||
let system = detect_dir(&dir, model, root)
|
||||
.or((!model.gradle.is_empty()).then_some(BuildSystem::Gradle))
|
||||
.or_else(|| model.maven.as_ref().filter(|m| !m.projects.is_empty()).map(|_| BuildSystem::Maven))
|
||||
let direct_system = detect_dir(&dir, model, root);
|
||||
let has_gradle = !model.gradle.is_empty();
|
||||
let has_maven = model.maven.as_ref().is_some_and(|m| !m.projects.is_empty());
|
||||
// A folder of sibling projects has no build file itself; build every linked Gradle and Maven project in it.
|
||||
let system = direct_system
|
||||
.or(has_gradle.then_some(BuildSystem::Gradle))
|
||||
.or(has_maven.then_some(BuildSystem::Maven))
|
||||
.ok_or_else(|| {
|
||||
IdeError::not_found("no supported build system (Maven, Gradle, .NET, Cargo, Go, TypeScript, CMake) found")
|
||||
})?;
|
||||
@@ -267,17 +276,26 @@ pub fn plan(
|
||||
),
|
||||
None => project_name,
|
||||
};
|
||||
let steps = match system {
|
||||
BuildSystem::Maven => maven_steps(root, model, kind, module_dir.as_deref(), cache, cancel)?,
|
||||
BuildSystem::Gradle => gradle_steps(root, model, kind, module_dir.as_deref())?,
|
||||
BuildSystem::Cargo => cargo_steps(&dir, kind),
|
||||
// Go builds the file's package (a module holds many).
|
||||
BuildSystem::Go => go_steps(file.and_then(Path::parent).unwrap_or(&dir), kind)?,
|
||||
BuildSystem::TypeScript => ts_steps(&dir, kind),
|
||||
BuildSystem::CMake => cmake_steps(&dir, kind, cmake.and_then(<[_]>::first)),
|
||||
BuildSystem::Dotnet => dotnet_steps(&dir, kind)?,
|
||||
// Never detected from a folder: it comes from the Project Structure (`structure_plan`).
|
||||
BuildSystem::Javac => return Err(IdeError::invalid("no build tool to run")),
|
||||
let steps = if module_dir.is_none() && direct_system.is_none() && has_gradle && has_maven {
|
||||
let mut combined = gradle_steps(root, model, kind, None)?;
|
||||
combined.extend(maven_steps(root, model, kind, None, cache, cancel)?);
|
||||
combined
|
||||
} else {
|
||||
match system {
|
||||
BuildSystem::Maven => maven_steps(root, model, kind, module_dir.as_deref(), cache, cancel)?,
|
||||
BuildSystem::Gradle => gradle_steps(root, model, kind, module_dir.as_deref())?,
|
||||
BuildSystem::Cargo => cargo_steps(&dir, kind),
|
||||
// Go builds the file's package (a module holds many); a directory target builds itself.
|
||||
BuildSystem::Go => {
|
||||
let pkg = file.map(|f| if f.is_dir() { f } else { f.parent().unwrap_or(f) }).unwrap_or(&dir);
|
||||
go_steps(pkg, kind)?
|
||||
}
|
||||
BuildSystem::TypeScript => ts_steps(&dir, kind),
|
||||
BuildSystem::CMake => cmake_steps(&dir, kind, cmake.and_then(<[_]>::first)),
|
||||
BuildSystem::Dotnet => dotnet_steps(&dir, kind)?,
|
||||
// Never detected from a folder: it comes from the Project Structure (`structure_plan`).
|
||||
BuildSystem::Javac => return Err(IdeError::invalid("no build tool to run")),
|
||||
}
|
||||
};
|
||||
Ok(BuildPlan { system, title, steps })
|
||||
}
|
||||
@@ -796,6 +814,11 @@ pub fn run(
|
||||
|
||||
/// 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)
|
||||
}
|
||||
|
||||
/// [`diagnostics`] reported by `source`.
|
||||
pub fn diagnostics_from(messages: &[BuildMessage], source: &str) -> BTreeMap<PathBuf, Vec<Diagnostic>> {
|
||||
let mut out: BTreeMap<PathBuf, Vec<Diagnostic>> = BTreeMap::new();
|
||||
for m in messages {
|
||||
let (Some(path), Some(range)) = (&m.path, m.range) else { continue };
|
||||
@@ -803,11 +826,11 @@ pub fn diagnostics(messages: &[BuildMessage]) -> BTreeMap<PathBuf, Vec<Diagnosti
|
||||
range,
|
||||
severity: m.severity,
|
||||
message: m.text.clone(),
|
||||
source: Some(DIAGNOSTICS_SOURCE.to_owned()),
|
||||
source: Some(source.to_owned()),
|
||||
code: m.code.clone(),
|
||||
unnecessary: false,
|
||||
deprecated: false,
|
||||
server: Some(DIAGNOSTICS_SOURCE.to_owned()),
|
||||
server: Some(source.to_owned()),
|
||||
});
|
||||
}
|
||||
out
|
||||
@@ -1912,4 +1935,92 @@ mod tests {
|
||||
assert_eq!(launch_class_dirs(BuildSystem::Gradle, m, true)[0], m.join("build/classes/kotlin/test"));
|
||||
assert_eq!(launch_class_dirs(BuildSystem::Maven, m, true), [m.join("target/classes")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn polyglot_root_targets_selected_subproject_or_combines_sibling_builds() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path().join("polyglot");
|
||||
write(&root, "Cargo.toml", "[package]\nname = \"root\"\nversion = \"0.1.0\"\n");
|
||||
write(
|
||||
&root,
|
||||
"fixtures/java-app/pom.xml",
|
||||
"<project><modelVersion>4.0.0</modelVersion><groupId>t</groupId><artifactId>app</artifactId><version>1</version></project>",
|
||||
);
|
||||
write(&root, "fixtures/kotlin-gradle/build.gradle.kts", "plugins { kotlin(\"jvm\") }\n");
|
||||
let model = crate::load(&root, &tmp.path().join("cache"), None);
|
||||
|
||||
let maven = plan(
|
||||
&root,
|
||||
&model,
|
||||
BuildKind::Build,
|
||||
Some(&root.join("fixtures/java-app")),
|
||||
None,
|
||||
None,
|
||||
&CancellationToken::new(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(maven.system, BuildSystem::Maven);
|
||||
assert_eq!(maven.steps.len(), 1);
|
||||
assert_eq!(maven.steps[0].cwd, root.join("fixtures/java-app"));
|
||||
|
||||
let gradle = plan(
|
||||
&root,
|
||||
&model,
|
||||
BuildKind::Build,
|
||||
Some(&root.join("fixtures/kotlin-gradle")),
|
||||
None,
|
||||
None,
|
||||
&CancellationToken::new(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(gradle.system, BuildSystem::Gradle);
|
||||
assert_eq!(gradle.steps.len(), 1);
|
||||
assert_eq!(gradle.steps[0].cwd, root.join("fixtures/kotlin-gradle"));
|
||||
|
||||
let cargo = plan(&root, &model, BuildKind::Build, Some(&root), None, None, &CancellationToken::new()).unwrap();
|
||||
assert_eq!(cargo.system, BuildSystem::Cargo);
|
||||
assert_eq!(cargo.steps[0].cwd, root);
|
||||
|
||||
// Folder without a root build file builds both linked Gradle and Maven subprojects on Build Project.
|
||||
let mixed = tmp.path().join("mixed");
|
||||
write(&mixed, "gradle-app/build.gradle.kts", "plugins { java }\n");
|
||||
write(
|
||||
&mixed,
|
||||
"maven-app/pom.xml",
|
||||
"<project><modelVersion>4.0.0</modelVersion><groupId>t</groupId><artifactId>m</artifactId><version>1</version></project>",
|
||||
);
|
||||
let mixed_model = crate::load(&mixed, &tmp.path().join("cache2"), None);
|
||||
let all = plan(&mixed, &mixed_model, BuildKind::Build, None, None, None, &CancellationToken::new()).unwrap();
|
||||
assert_eq!(all.steps.len(), 2);
|
||||
assert_eq!(all.steps[0].cwd, mixed.join("gradle-app"));
|
||||
assert_eq!(all.steps[1].cwd, mixed.join("maven-app"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn go_directory_target_builds_that_package_without_stepping_to_parent() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path().join("go-app");
|
||||
write(&root, "go.mod", "module example.com/app\n\ngo 1.22\n");
|
||||
write(&root, "cmd/server/main.go", "package main\nfunc main() {}\n");
|
||||
|
||||
let pkg = plan(
|
||||
&root,
|
||||
&BuildModel::default(),
|
||||
BuildKind::Build,
|
||||
Some(&root.join("cmd/server")),
|
||||
None,
|
||||
None,
|
||||
&CancellationToken::new(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(pkg.system, BuildSystem::Go);
|
||||
assert_eq!(pkg.steps[0].cwd, root);
|
||||
assert_eq!(pkg.steps[0].args, ["build", "./cmd/server/..."]);
|
||||
|
||||
let whole =
|
||||
plan(&root, &BuildModel::default(), BuildKind::Build, Some(&root), None, None, &CancellationToken::new())
|
||||
.unwrap();
|
||||
assert_eq!(whole.steps[0].cwd, root);
|
||||
assert_eq!(whole.steps[0].args, ["build", "./..."]);
|
||||
}
|
||||
}
|
||||
@@ -94,12 +94,12 @@ pub(super) fn build_javac_step(
|
||||
Ok(step)
|
||||
}
|
||||
|
||||
/// The resolved dependency classpath for one module and scope, tied to the same
|
||||
/// inputs as its launch build so POM, JDK, settings and profile changes invalidate it.
|
||||
/// The last resolved dependency classpath for one module and scope. A fingerprint
|
||||
/// permits reuse during a build; NoBuild also uses records without one.
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
struct CachedClasspath {
|
||||
version: u32,
|
||||
fingerprint: LaunchFingerprint,
|
||||
fingerprint: Option<LaunchFingerprint>,
|
||||
classpath: String,
|
||||
}
|
||||
|
||||
@@ -162,9 +162,6 @@ fn module_target(root: &Path, model: &BuildModel, module: &Path, test: bool) ->
|
||||
.iter()
|
||||
.find(|p| root.join(&p.dir) == module)
|
||||
.ok_or_else(|| IdeError::not_found("no linked Maven project found for module"))?;
|
||||
if project.packaging == "pom" {
|
||||
return Err(IdeError::not_found("the launch module is a Maven aggregator without sources"));
|
||||
}
|
||||
let top = maven_reactor(m, &project.dir)
|
||||
.ok_or_else(|| IdeError::not_found("no linked Maven reactor found for module"))?;
|
||||
let top_dir = subdir(root, &top.dir);
|
||||
@@ -217,6 +214,30 @@ pub fn module_classpath(
|
||||
module_classpaths(root, model, &[module.to_path_buf()], test, local_repo, cache, cancel)
|
||||
}
|
||||
|
||||
/// Uses the last launch classpath, or probes dependencies without invoking the compile lifecycle.
|
||||
pub fn module_classpath_without_build(
|
||||
root: &Path,
|
||||
model: &BuildModel,
|
||||
module: &Path,
|
||||
test: bool,
|
||||
cache: &Path,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<String> {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
let target = module_target(root, model, module, test)?;
|
||||
if let Some(path) = classpath_cache_path(root, cache, module, test)
|
||||
&& let Ok(bytes) = fs::read(path)
|
||||
&& let Ok(cached) = serde_json::from_slice::<CachedClasspath>(&bytes)
|
||||
&& cached.version == CLASSPATH_CACHE_VERSION
|
||||
&& classpath_entries_exist(root, &cached.classpath)
|
||||
{
|
||||
return Ok(cached.classpath);
|
||||
}
|
||||
classpath(root, model, &target, if test { "test" } else { "runtime" }, false, cancel)
|
||||
}
|
||||
|
||||
/// [`module_classpath`] of `modules[0]`. The other modules, launched together with it
|
||||
/// (#3971), share its Maven probe when they have no cached classpath, which leaves
|
||||
/// theirs cached for their own launches.
|
||||
@@ -245,7 +266,7 @@ pub fn module_classpaths(
|
||||
&& let Ok(bytes) = fs::read(path)
|
||||
&& let Ok(cached) = serde_json::from_slice::<CachedClasspath>(&bytes)
|
||||
&& cached.version == CLASSPATH_CACHE_VERSION
|
||||
&& cached.fingerprint == *fingerprint
|
||||
&& cached.fingerprint.as_ref() == Some(fingerprint)
|
||||
&& classpath_entries_exist(root, &cached.classpath)
|
||||
{
|
||||
if i == 0 {
|
||||
@@ -269,7 +290,7 @@ pub fn module_classpaths(
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
for (Probe(_, fingerprint, cache_path), classpath) in probes.into_iter().zip(&classpaths) {
|
||||
if let (Some(fingerprint), Some(path)) = (fingerprint, cache_path) {
|
||||
if let Some(path) = cache_path {
|
||||
let cached =
|
||||
CachedClasspath { version: CLASSPATH_CACHE_VERSION, fingerprint, classpath: classpath.clone() };
|
||||
if let Err(error) = cache_classpath(&path, &cached) {
|
||||
@@ -675,6 +696,81 @@ mod tests {
|
||||
assert!(single_file_target(root, &model, &root.join("other/Main.java")).is_err());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn pom_launch_resolves_dependencies_without_compiling_for_no_build() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(dir.path()).unwrap();
|
||||
fixture(&root);
|
||||
let pom = fs::read_to_string(root.join("app/pom.xml")).unwrap();
|
||||
write(
|
||||
&root,
|
||||
"app/pom.xml",
|
||||
&pom.replace("<artifactId>app</artifactId>", "<artifactId>app</artifactId><packaging>pom</packaging>"),
|
||||
);
|
||||
let script = root.join("mvnw");
|
||||
write(
|
||||
&root,
|
||||
"mvnw",
|
||||
"#!/bin/sh\nprintf '%s\\n' \"$@\" > args.txt\nmkdir -p app/target\nprintf '/repo/runtime.jar' > app/target/ide-compile-cp.txt\n",
|
||||
);
|
||||
fs::set_permissions(&script, fs::Permissions::from_mode(0o755)).unwrap();
|
||||
let model = crate::load(&root, &root.join("cache"), None);
|
||||
let cancel = CancellationToken::new();
|
||||
let cp = module_classpath_without_build(&root, &model, &root.join("app"), false, &root.join("cache"), &cancel)
|
||||
.unwrap();
|
||||
let paths: Vec<_> = std::env::split_paths(&cp).collect();
|
||||
assert!(paths.contains(&root.join("lib/target/classes")), "{cp}");
|
||||
assert!(paths.contains(&root.join("shared/target/classes")), "{cp}");
|
||||
assert!(paths.contains(&PathBuf::from("/repo/runtime.jar")), "{cp}");
|
||||
assert!(!paths.contains(&root.join("app/target/classes")), "{cp}");
|
||||
let args = fs::read_to_string(root.join("args.txt")).unwrap();
|
||||
assert!(!args.lines().any(|a| matches!(a, "compile" | "package" | "test-compile")), "{args}");
|
||||
assert!(args.lines().any(|a| a == "-Dmdep.includeScope=runtime"), "{args}");
|
||||
|
||||
module_classpath(&root, &model, &root.join("app"), false, None, &root.join("cache"), &cancel).unwrap();
|
||||
let args = fs::read_to_string(root.join("args.txt")).unwrap();
|
||||
assert!(args.lines().any(|a| a == "compile"), "{args}");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn no_build_keeps_the_last_launch_classpath_after_a_pom_change() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(dir.path()).unwrap();
|
||||
fixture(&root);
|
||||
let pom = fs::read_to_string(root.join("app/pom.xml")).unwrap();
|
||||
write(
|
||||
&root,
|
||||
"app/pom.xml",
|
||||
&pom.replace("<artifactId>app</artifactId>", "<artifactId>app</artifactId><packaging>pom</packaging>"),
|
||||
);
|
||||
write(
|
||||
&root,
|
||||
"mvnw",
|
||||
"#!/bin/sh\necho called >> calls.txt\nprintf '%s\\n' \"$@\" > args.txt\nmkdir -p app/target repo\ntouch repo/runtime.jar repo/runtime-v2.jar\nif grep -q changed app/pom.xml; then printf \"$PWD/repo/runtime-v2.jar\" > app/target/ide-compile-cp.txt; else printf \"$PWD/repo/runtime.jar\" > app/target/ide-compile-cp.txt; fi\n",
|
||||
);
|
||||
fs::set_permissions(root.join("mvnw"), fs::Permissions::from_mode(0o755)).unwrap();
|
||||
let model = crate::load(&root, &root.join("cache"), None);
|
||||
let cancel = CancellationToken::new();
|
||||
let previous =
|
||||
module_classpath(&root, &model, &root.join("app"), false, None, &root.join("cache"), &cancel).unwrap();
|
||||
assert!(previous.contains("repo/runtime.jar"), "{previous}");
|
||||
|
||||
let pom = fs::read_to_string(root.join("app/pom.xml")).unwrap();
|
||||
write(&root, "app/pom.xml", &pom.replace("</project>", "<description>changed</description></project>"));
|
||||
let launch =
|
||||
module_classpath_without_build(&root, &model, &root.join("app"), false, &root.join("cache"), &cancel)
|
||||
.unwrap();
|
||||
assert!(launch.contains("repo/runtime.jar"), "{launch}");
|
||||
assert!(!launch.contains("runtime-v2.jar"), "{launch}");
|
||||
assert_eq!(fs::read_to_string(root.join("calls.txt")).unwrap().lines().count(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn javac_prefers_the_module_jdk_and_scopes_test_sources() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -0,0 +1,450 @@
|
||||
//! Problems › TypeScript project errors: the project's own `tsc --watch` on each root
|
||||
//! `tsconfig.json`, its output parsed like Build's tsc step, one compilation at a time.
|
||||
//!
|
||||
//! A background check never writes into the project. A plain project runs `tsc --noEmit -p`
|
||||
//! with its `.tsbuildinfo` (written by `composite` / `incremental` even without emit) moved to a
|
||||
//! scratch folder. `tsc -b` cannot check without emitting (`--noEmit` fails with TS6310 on
|
||||
//! composite references), and plain `tsc -p` on a project with references needs their built
|
||||
//! `.d.ts` (TS6305). So a solution runs `tsc -b` on scratch copies of its configurations: each
|
||||
//! `extends` the real one and only sends the outputs and `.tsbuildinfo` to the scratch folder,
|
||||
//! keeping every option, file list and source position of the project.
|
||||
|
||||
use super::parse::{Format, OutputParser, RawMessage};
|
||||
use super::{BuildMessage, Lines, PathMap, resolve};
|
||||
use crate::process;
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult};
|
||||
use serde_json::{Value, json};
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
// ponytail: one `tsc` per root; past this the shallowest roots win. Raise it, or watch
|
||||
// on demand, if monorepos without a solution tsconfig need more.
|
||||
const MAX_ROOTS: usize = 8;
|
||||
|
||||
/// The configurations among `found` (the `tsconfig.json` files of the project) that no other
|
||||
/// one references: the ones a watcher runs on. Referenced projects are checked by their solution.
|
||||
pub fn tsc_watch_roots(found: Vec<PathBuf>) -> Vec<PathBuf> {
|
||||
let referenced: BTreeSet<PathBuf> = found.iter().flat_map(|c| references(c)).collect();
|
||||
let mut roots: Vec<PathBuf> = found.into_iter().filter(|c| !referenced.contains(c)).collect();
|
||||
roots.sort_by_key(|c| (c.components().count(), c.clone()));
|
||||
roots.truncate(MAX_ROOTS);
|
||||
roots
|
||||
}
|
||||
|
||||
fn read_json(path: &Path) -> Option<Value> {
|
||||
let text = std::fs::read_to_string(path).ok()?;
|
||||
serde_json::from_str(&ide_core::jsonc::strip(&text)).ok()
|
||||
}
|
||||
|
||||
/// The configurations `config` lists in `references` (a folder means its `tsconfig.json`).
|
||||
fn references(config: &Path) -> Vec<PathBuf> {
|
||||
let Some(json) = read_json(config) else { return Vec::new() };
|
||||
let dir = config.parent().unwrap_or(Path::new(""));
|
||||
let refs = json.get("references").and_then(|r| r.as_array()).into_iter().flatten();
|
||||
refs.filter_map(|r| r.get("path")?.as_str())
|
||||
.map(|p| {
|
||||
let p = super::normalize(&dir.join(p));
|
||||
if p.extension().is_some_and(|e| e == "json") { p } else { p.join("tsconfig.json") }
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A configuration and the ones it `extends`, most derived first, each with its folder (the
|
||||
/// base of its relative paths). A package base (`@tsconfig/node20/tsconfig.json`) is looked up
|
||||
/// in `node_modules` above the configuration.
|
||||
fn chain(config: &Path) -> Vec<(PathBuf, Value)> {
|
||||
let mut out = Vec::new();
|
||||
let mut next = vec![config.to_path_buf()];
|
||||
// A cycle or a deep chain ends here.
|
||||
while let Some(path) = next.pop().filter(|_| out.len() < 16) {
|
||||
let Some(json) = read_json(&path) else { continue };
|
||||
let dir = path.parent().unwrap_or(Path::new("")).to_path_buf();
|
||||
let bases: Vec<String> = match json.get("extends") {
|
||||
Some(Value::String(s)) => vec![s.clone()],
|
||||
Some(Value::Array(a)) => a.iter().filter_map(|v| v.as_str().map(str::to_owned)).collect(),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
// Later bases override earlier ones: visit them first.
|
||||
next.extend(bases.iter().filter_map(|b| resolve_base(&dir, b)));
|
||||
out.push((dir, json));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn resolve_base(dir: &Path, base: &str) -> Option<PathBuf> {
|
||||
let with_json = |p: PathBuf| {
|
||||
if p.is_dir() {
|
||||
p.join("tsconfig.json")
|
||||
} else if p.extension().is_some_and(|e| e == "json") {
|
||||
p
|
||||
} else {
|
||||
let mut s = p.into_os_string();
|
||||
s.push(".json");
|
||||
PathBuf::from(s)
|
||||
}
|
||||
};
|
||||
if base.starts_with('.') || Path::new(base).is_absolute() {
|
||||
return Some(with_json(super::normalize(&dir.join(base))));
|
||||
}
|
||||
dir.ancestors().map(|a| with_json(a.join("node_modules").join(base))).find(|p| p.is_file())
|
||||
}
|
||||
|
||||
/// The first value of `key` (a top-level key, or `compilerOptions.<key>`) along `chain`, with the
|
||||
/// folder it is relative to.
|
||||
fn lookup<'a>(chain: &'a [(PathBuf, Value)], key: &str) -> Option<(&'a Path, &'a Value)> {
|
||||
chain.iter().find_map(|(dir, json)| {
|
||||
let value = match key.strip_prefix("compilerOptions.") {
|
||||
Some(option) => json.get("compilerOptions")?.get(option)?,
|
||||
None => json.get(key)?,
|
||||
};
|
||||
Some((dir.as_path(), value))
|
||||
})
|
||||
}
|
||||
|
||||
/// The scratch copy of `config` for `tsc -b`: the real configuration with its outputs and
|
||||
/// `.tsbuildinfo` in `scratch` (file `<n>`), referencing the scratch copies `refs`. Settings that
|
||||
/// default relative to the configuration's own folder are spelled out, since the copy lives
|
||||
/// elsewhere: the files (`**/*`), their exclusions (`node_modules`, the output folder) and the
|
||||
/// `rootDir` of a composite project.
|
||||
fn scratch_config(config: &Path, scratch: &Path, n: usize, refs: &[PathBuf]) -> Value {
|
||||
let chain = chain(config);
|
||||
let dir = config.parent().unwrap_or(Path::new(""));
|
||||
let out = scratch.join(n.to_string());
|
||||
let mut options = json!({ "outDir": out, "tsBuildInfoFile": scratch.join(format!("{n}.tsbuildinfo")) });
|
||||
if lookup(&chain, "compilerOptions.declarationDir").is_some() {
|
||||
options["declarationDir"] = json!(out);
|
||||
}
|
||||
if lookup(&chain, "compilerOptions.outFile").is_some() {
|
||||
options["outFile"] = json!(out.join("out.js"));
|
||||
}
|
||||
if lookup(&chain, "compilerOptions.composite").is_some_and(|(_, v)| v == &json!(true))
|
||||
&& lookup(&chain, "compilerOptions.rootDir").is_none()
|
||||
{
|
||||
options["rootDir"] = json!(dir);
|
||||
}
|
||||
let mut copy = json!({
|
||||
"extends": config,
|
||||
"compilerOptions": options,
|
||||
"references": refs.iter().map(|r| json!({ "path": r })).collect::<Vec<_>>(),
|
||||
});
|
||||
if lookup(&chain, "include").is_none() && lookup(&chain, "files").is_none() {
|
||||
copy["include"] = json!([dir.join("**/*")]);
|
||||
}
|
||||
if lookup(&chain, "exclude").is_none() {
|
||||
let mut exclude = vec![dir.join("node_modules")];
|
||||
if let Some((base, Value::String(out_dir))) = lookup(&chain, "compilerOptions.outDir") {
|
||||
exclude.push(super::normalize(&base.join(out_dir)));
|
||||
}
|
||||
copy["exclude"] = json!(exclude);
|
||||
}
|
||||
copy
|
||||
}
|
||||
|
||||
/// The `tsc` arguments that watch `config` without writing into the project, writing the
|
||||
/// scratch configurations a solution needs into `scratch`.
|
||||
fn watch_args(config: &Path, scratch: &Path) -> std::io::Result<Vec<String>> {
|
||||
let path = |p: &Path| p.to_string_lossy().into_owned();
|
||||
let mut args: Vec<String> = if references(config).is_empty() {
|
||||
let name = config.file_name().map_or_else(|| "tsconfig.json".into(), |n| n.to_string_lossy().into_owned());
|
||||
let info = path(&scratch.join("tsconfig.tsbuildinfo"));
|
||||
["--noEmit", "-p", &name, "--incremental", "--tsBuildInfoFile", &info].map(String::from).to_vec()
|
||||
} else {
|
||||
// Every configuration the solution reaches gets a number: the solution 0, then in order.
|
||||
let mut numbers: BTreeMap<PathBuf, usize> = BTreeMap::from([(config.to_path_buf(), 0)]);
|
||||
let mut queue = vec![config.to_path_buf()];
|
||||
let mut i = 0;
|
||||
while i < queue.len() {
|
||||
let current = queue[i].clone();
|
||||
let refs: Vec<PathBuf> = references(¤t)
|
||||
.into_iter()
|
||||
.map(|r| {
|
||||
let next = numbers.len();
|
||||
let n = *numbers.entry(r.clone()).or_insert_with(|| {
|
||||
queue.push(r);
|
||||
next
|
||||
});
|
||||
scratch.join(format!("{n}.json"))
|
||||
})
|
||||
.collect();
|
||||
let copy = scratch_config(¤t, scratch, numbers[¤t], &refs);
|
||||
std::fs::write(scratch.join(format!("{}.json", numbers[¤t])), copy.to_string())?;
|
||||
i += 1;
|
||||
}
|
||||
vec!["-b".into(), path(&scratch.join("0.json"))]
|
||||
};
|
||||
args.extend(["--watch", "--pretty", "false", "--preserveWatchOutput"].map(String::from));
|
||||
Ok(args)
|
||||
}
|
||||
|
||||
/// The project's own `tsc` (`node_modules/.bin` from the configuration's folder up to `root`).
|
||||
fn local_tsc(root: &Path, dir: &Path) -> Option<PathBuf> {
|
||||
dir.ancestors()
|
||||
.take_while(|d| d.starts_with(root))
|
||||
.find_map(|d| ide_core::tool_path::find_command("tsc", d.join("node_modules/.bin").as_os_str(), dir))
|
||||
}
|
||||
|
||||
/// The messages of one compilation at a time: tsc ends each with
|
||||
/// `… - Found 2 errors. Watching for file changes.` `tsc -b` reports the errors of every
|
||||
/// project of the solution that has some, rebuilt this time or not ("out of date because it had
|
||||
/// errors"), so each compilation's list replaces the last.
|
||||
#[derive(Default)]
|
||||
struct Compilations {
|
||||
parser: Option<OutputParser>,
|
||||
raws: Vec<RawMessage>,
|
||||
}
|
||||
|
||||
impl Compilations {
|
||||
fn feed(&mut self, line: &str) -> Option<Vec<RawMessage>> {
|
||||
let parser = self.parser.get_or_insert_with(|| OutputParser::new(Format::Tsc));
|
||||
if line.contains("Watching for file changes.") {
|
||||
self.raws.extend(parser.finish());
|
||||
return Some(std::mem::take(&mut self.raws));
|
||||
}
|
||||
self.raws.extend(parser.feed(line).messages);
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// A scratch folder of this process for `config`, removed when dropped.
|
||||
struct Scratch(PathBuf);
|
||||
|
||||
impl Scratch {
|
||||
fn new(config: &Path) -> std::io::Result<Self> {
|
||||
use std::hash::{Hash, Hasher};
|
||||
let mut hash = std::collections::hash_map::DefaultHasher::new();
|
||||
config.hash(&mut hash);
|
||||
let dir = std::env::temp_dir().join("openidea-tsc-watch").join(format!(
|
||||
"{}-{:016x}",
|
||||
std::process::id(),
|
||||
hash.finish()
|
||||
));
|
||||
// Fresh: a `.tsbuildinfo` left by an earlier run would make tsc skip unchanged projects.
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir)?;
|
||||
Ok(Scratch(dir))
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Scratch {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs the project's `tsc --watch` on `config` until `cancel` fires or tsc exits, handing the
|
||||
/// messages of every finished compilation (all of them, an empty list when it passes) to
|
||||
/// `on_compilation`. Not found when the project has no TypeScript of its own.
|
||||
pub fn tsc_watch(
|
||||
root: &Path,
|
||||
config: &Path,
|
||||
cancel: &CancellationToken,
|
||||
mut on_compilation: impl FnMut(Vec<BuildMessage>),
|
||||
) -> IdeResult<()> {
|
||||
let dir = config.parent().ok_or_else(|| IdeError::invalid("no tsconfig folder"))?;
|
||||
let tsc = local_tsc(root, dir).ok_or_else(|| IdeError::not_found("no local typescript"))?;
|
||||
let scratch = Scratch::new(config)?;
|
||||
let args = watch_args(config, &scratch.0)?;
|
||||
let paths = PathMap::new(root);
|
||||
let mut compilations = Compilations::default();
|
||||
let program = tsc.to_string_lossy();
|
||||
process::run_bounded(&program, &args, dir, &BTreeMap::new(), cancel, |_, line| {
|
||||
if let Some(raws) = compilations.feed(line) {
|
||||
// Fresh file texts each time: the files changed since the last compilation.
|
||||
let mut lines = Lines::default();
|
||||
on_compilation(raws.into_iter().map(|r| resolve(r, dir, &paths, &mut lines)).collect());
|
||||
}
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn write(dir: &Path, rel: &str, text: &str) {
|
||||
let p = dir.join(rel);
|
||||
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
|
||||
std::fs::write(p, text).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn roots_are_the_configurations_no_other_one_references() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
// A solution with references (one by folder, one by file), plus an unrelated package.
|
||||
write(
|
||||
root,
|
||||
"tsconfig.json",
|
||||
r#"{ "files": [], // solution
|
||||
"references": [{ "path": "./packages/a" }, { "path": "packages/b/tsconfig.json" },] }"#,
|
||||
);
|
||||
write(root, "packages/a/tsconfig.json", r#"{"compilerOptions": {"composite": true}}"#);
|
||||
write(root, "packages/b/tsconfig.json", r#"{"compilerOptions": {"composite": true}}"#);
|
||||
write(root, "tools/cli/tsconfig.json", "{}");
|
||||
let found = ["tools/cli", "packages/b", "", "packages/a"].map(|d| root.join(d).join("tsconfig.json"));
|
||||
assert_eq!(tsc_watch_roots(found.to_vec()), [root.join("tsconfig.json"), root.join("tools/cli/tsconfig.json")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_solution_is_checked_through_scratch_copies_of_its_configurations() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let (root, scratch) = (tmp.path().join("p"), tmp.path().join("scratch"));
|
||||
std::fs::create_dir_all(&scratch).unwrap();
|
||||
write(
|
||||
&root,
|
||||
"tsconfig.json",
|
||||
r#"{"files": [], "references": [{"path": "./packages/a"}, {"path": "./packages/b"}]}"#,
|
||||
);
|
||||
// a: composite, every setting by default.
|
||||
write(&root, "packages/a/tsconfig.json", r#"{"compilerOptions": {"composite": true}}"#);
|
||||
// b: references a, settles its files, outputs and root in a shared base.
|
||||
write(
|
||||
&root,
|
||||
"packages/b/tsconfig.json",
|
||||
r#"{"extends": "../../tsconfig.base", "references": [{"path": "../a"}], "compilerOptions": {"outFile": "b.js"}}"#,
|
||||
);
|
||||
write(
|
||||
&root,
|
||||
"tsconfig.base.json",
|
||||
r#"{"compilerOptions": {"composite": true, "rootDir": ".", "outDir": "dist", "declarationDir": "types"},
|
||||
"include": ["packages/*/src"]}"#,
|
||||
);
|
||||
let args = watch_args(&root.join("tsconfig.json"), &scratch).unwrap();
|
||||
let s = |p: &str| scratch.join(p).to_string_lossy().into_owned();
|
||||
assert_eq!(args, ["-b", &s("0.json"), "--watch", "--pretty", "false", "--preserveWatchOutput"]);
|
||||
let copy = |n: usize| read_json(&scratch.join(format!("{n}.json"))).unwrap();
|
||||
let path = |p: &Path| json!(p);
|
||||
assert_eq!(
|
||||
copy(0),
|
||||
json!({
|
||||
"extends": path(&root.join("tsconfig.json")),
|
||||
"compilerOptions": {"outDir": path(&scratch.join("0")), "tsBuildInfoFile": s("0.tsbuildinfo")},
|
||||
"references": [{"path": s("1.json")}, {"path": s("2.json")}],
|
||||
"exclude": [path(&root.join("node_modules"))],
|
||||
})
|
||||
);
|
||||
let a = root.join("packages/a");
|
||||
assert_eq!(
|
||||
copy(1),
|
||||
json!({
|
||||
"extends": path(&a.join("tsconfig.json")),
|
||||
"compilerOptions": {
|
||||
"outDir": path(&scratch.join("1")), "tsBuildInfoFile": s("1.tsbuildinfo"), "rootDir": path(&a),
|
||||
},
|
||||
"references": [],
|
||||
"include": [path(&a.join("**/*"))],
|
||||
"exclude": [path(&a.join("node_modules"))],
|
||||
})
|
||||
);
|
||||
let b = root.join("packages/b");
|
||||
assert_eq!(
|
||||
copy(2),
|
||||
json!({
|
||||
"extends": path(&b.join("tsconfig.json")),
|
||||
"compilerOptions": {
|
||||
"outDir": path(&scratch.join("2")), "tsBuildInfoFile": s("2.tsbuildinfo"),
|
||||
"declarationDir": path(&scratch.join("2")), "outFile": path(&scratch.join("2/out.js")),
|
||||
},
|
||||
"references": [{"path": s("1.json")}],
|
||||
"exclude": [path(&b.join("node_modules")), path(&root.join("dist"))],
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_composite_package_base_gets_its_root_folder() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let (root, scratch) = (tmp.path().join("p"), tmp.path().join("scratch"));
|
||||
write(&root, "node_modules/@acme/tsconfig/base.json", r#"{"compilerOptions": {"composite": true}}"#);
|
||||
write(&root, "app/tsconfig.json", r#"{"extends": "@acme/tsconfig/base", "include": ["src"]}"#);
|
||||
let copy = scratch_config(&root.join("app/tsconfig.json"), &scratch, 3, &[]);
|
||||
assert_eq!(copy["compilerOptions"]["rootDir"], json!(root.join("app")));
|
||||
assert_eq!(copy.get("include"), None, "the files come from the real configuration");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_compilation_reports_its_own_messages() {
|
||||
// `tsc --noEmit --watch --pretty false --preserveWatchOutput`, as printed.
|
||||
let output = "\
|
||||
2:14:08 PM - Starting compilation in watch mode...
|
||||
|
||||
2:14:09 PM - Found 0 errors. Watching for file changes.
|
||||
2:14:12 PM - File change detected. Starting incremental compilation...
|
||||
|
||||
src/b.ts(1,37): error TS2322: Type 'string' is not assignable to type 'number'.
|
||||
src/c.ts(2,1): error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.
|
||||
Type 'string' is not assignable to type 'number'.
|
||||
|
||||
2:14:12 PM - Found 2 errors. Watching for file changes.
|
||||
2:14:15 PM - File change detected. Starting incremental compilation...
|
||||
|
||||
2:14:15 PM - Found 0 errors. Watching for file changes.";
|
||||
let mut compilations = Compilations::default();
|
||||
let found: Vec<Vec<(String, Option<String>)>> = output
|
||||
.lines()
|
||||
.filter_map(|l| compilations.feed(l))
|
||||
.map(|raws| raws.into_iter().map(|r| (r.path.unwrap_or_default(), r.code)).collect())
|
||||
.collect();
|
||||
assert_eq!(
|
||||
found,
|
||||
[
|
||||
vec![],
|
||||
vec![("src/b.ts".into(), Some("TS2322".into())), ("src/c.ts".into(), Some("TS2345".into()))],
|
||||
vec![]
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn the_projects_tsc_reports_until_cancelled() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
write(root, "app/tsconfig.json", "{}");
|
||||
write(root, "app/src/b.ts", "export const b: number = a;\n");
|
||||
// A watcher that prints one compilation and keeps running, like `tsc --watch`.
|
||||
write(
|
||||
root,
|
||||
"node_modules/.bin/tsc",
|
||||
"#!/bin/sh\necho \"$@\" > args.txt\n\
|
||||
echo 'src/b.ts(1,26): error TS2322: Type string is not assignable to type number.'\n\
|
||||
echo '1:00:00 PM - Found 1 error. Watching for file changes.'\nexec sleep 30\n",
|
||||
);
|
||||
let bin = root.join("node_modules/.bin/tsc");
|
||||
std::fs::set_permissions(&bin, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
let cancel = CancellationToken::new();
|
||||
let mut compilations = Vec::new();
|
||||
let started = std::time::Instant::now();
|
||||
let result = tsc_watch(root, &root.join("app/tsconfig.json"), &cancel, |messages| {
|
||||
compilations.push(messages);
|
||||
cancel.cancel();
|
||||
});
|
||||
assert_eq!(result.unwrap_err().kind, ide_core::error::ErrorKind::Cancelled);
|
||||
assert!(started.elapsed().as_secs() < 10, "cancelling stops the watcher");
|
||||
let [messages] = &compilations[..] else { panic!("{compilations:?}") };
|
||||
let paths: Vec<_> = messages.iter().map(|m| (m.path.clone().map(PathBuf::from), m.range)).collect();
|
||||
let at = |l, c| ide_core::Pos::new(l, c);
|
||||
assert_eq!(paths, [(Some(root.join("app/src/b.ts")), Some(ide_core::Range::new(at(0, 25), at(0, 26))))]);
|
||||
let args = std::fs::read_to_string(root.join("app/args.txt")).unwrap();
|
||||
let (check, rest) = args.trim().split_once(" --tsBuildInfoFile ").unwrap();
|
||||
assert_eq!(check, "--noEmit -p tsconfig.json --incremental");
|
||||
let (info, watch) = rest.split_once(' ').unwrap();
|
||||
assert_eq!(watch, "--watch --pretty false --preserveWatchOutput");
|
||||
// The `.tsbuildinfo` goes to a scratch folder outside the project, gone with the watcher.
|
||||
let scratch = Path::new(info).parent().unwrap();
|
||||
assert!(scratch.starts_with(std::env::temp_dir()) && !scratch.starts_with(root), "{info}");
|
||||
assert!(!scratch.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_local_typescript_runs_nothing() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
write(tmp.path(), "tsconfig.json", "{}");
|
||||
let err = tsc_watch(tmp.path(), &tmp.path().join("tsconfig.json"), &CancellationToken::new(), |_| {
|
||||
panic!("no compilation without typescript")
|
||||
})
|
||||
.unwrap_err();
|
||||
assert_eq!(err.kind, ide_core::error::ErrorKind::NotFound);
|
||||
}
|
||||
}
|
||||
@@ -364,9 +364,9 @@ pub fn parse_reported_projects(output: &str) -> Vec<ReportedProject> {
|
||||
output.lines().filter_map(|l| serde_json::from_str(l.trim_end().strip_prefix(MODEL_LINE)?).ok()).collect()
|
||||
}
|
||||
|
||||
/// Source roots of the reported source sets: `(absolute folder, is test, is resources)`.
|
||||
pub fn reported_source_roots(reported: &[ReportedProject]) -> Vec<(PathBuf, ReportedRoot)> {
|
||||
let mut out: Vec<(PathBuf, ReportedRoot)> = Vec::new();
|
||||
/// Source roots of the reported source sets: `(absolute folder, role, absolute folder of its project)`.
|
||||
pub fn reported_source_roots(reported: &[ReportedProject]) -> Vec<(PathBuf, ReportedRoot, PathBuf)> {
|
||||
let mut out: Vec<(PathBuf, ReportedRoot, PathBuf)> = Vec::new();
|
||||
for p in reported {
|
||||
for set in &p.source_sets {
|
||||
let (src, res) = if set.test {
|
||||
@@ -377,14 +377,14 @@ pub fn reported_source_roots(reported: &[ReportedProject]) -> Vec<(PathBuf, Repo
|
||||
for (dir, kind) in set.src.iter().map(|d| (d, src)).chain(set.res.iter().map(|d| (d, res))) {
|
||||
let dir = PathBuf::from(dir);
|
||||
// A folder shared by `main` and another set is `main`'s, as in IDEA.
|
||||
if !out.iter().any(|(d, _)| *d == dir) {
|
||||
out.push((dir, kind));
|
||||
if !out.iter().any(|(d, _, _)| *d == dir) {
|
||||
out.push((dir, kind, PathBuf::from(&p.dir)));
|
||||
}
|
||||
}
|
||||
}
|
||||
// IDEA excludes the build folder of every module.
|
||||
if let Some(b) = &p.build_dir {
|
||||
out.push((PathBuf::from(b), ReportedRoot::Excluded));
|
||||
out.push((PathBuf::from(b), ReportedRoot::Excluded, PathBuf::from(&p.dir)));
|
||||
}
|
||||
}
|
||||
out
|
||||
|
||||
@@ -441,7 +441,7 @@ impl JavaBuild<'_> {
|
||||
let record = model::load_record(&model::reactor_dir(self.cache, &top.key()))?;
|
||||
let project = record.model.projects.iter().find(|p| p.dir == module)?;
|
||||
let paths = class_paths(project, test);
|
||||
paths.first().is_some_and(|p| p.is_dir()).then_some(paths)
|
||||
paths.first().is_some_and(|p| p.exists()).then_some(paths)
|
||||
}
|
||||
|
||||
/// Builds `target`. A launch gets the classpath to run with; the others an empty one.
|
||||
@@ -517,7 +517,15 @@ impl JavaBuild<'_> {
|
||||
let Some(project) = project_at(path) else {
|
||||
return Ok(Built::Unsupported(format!("no Java project holds {}", path.display())));
|
||||
};
|
||||
launch_projects(&reactor_model, project, true)
|
||||
let mut all: Vec<(&ProjectModel, bool)> = Vec::new();
|
||||
for member in reactor_model.projects.iter().filter(|p| p.dir.starts_with(&project.dir)) {
|
||||
for set in launch_projects(&reactor_model, member, true) {
|
||||
if !all.iter().any(|(p, t)| p.dir == set.0.dir && *t == set.1) {
|
||||
all.push(set);
|
||||
}
|
||||
}
|
||||
}
|
||||
all
|
||||
}
|
||||
Target::File(file) => {
|
||||
let Some(project) = project_at(file) else {
|
||||
@@ -1031,7 +1039,7 @@ fn launch_projects<'a>(model: &'a ReactorModel, target: &'a ProjectModel, test:
|
||||
if test {
|
||||
visit(project, false, by_output, by_test_output, seen, out);
|
||||
}
|
||||
for entry in &project.set(test).classpath {
|
||||
for entry in project.set(test).classpath.iter().chain(&project.set(test).runtime_classpath) {
|
||||
if let Some(upstream) = by_output.get(entry.as_path()).filter(|p| p.dir != project.dir) {
|
||||
visit(upstream, false, by_output, by_test_output, seen, out);
|
||||
} else if let Some(upstream) = by_test_output.get(entry.as_path()).filter(|p| p.dir != project.dir) {
|
||||
@@ -1053,10 +1061,12 @@ fn class_paths(target: &ProjectModel, test: bool) -> Vec<PathBuf> {
|
||||
out.push(p.clone());
|
||||
}
|
||||
};
|
||||
if test {
|
||||
push(&target.test.output);
|
||||
if target.packaging != "pom" {
|
||||
if test {
|
||||
push(&target.test.output);
|
||||
}
|
||||
push(&target.main.output);
|
||||
}
|
||||
push(&target.main.output);
|
||||
for entry in &target.set(test).runtime_classpath {
|
||||
push(entry);
|
||||
}
|
||||
|
||||
@@ -18,15 +18,9 @@ fn tools() -> Option<(PathBuf, PathBuf)> {
|
||||
Some((home, mvn))
|
||||
}
|
||||
|
||||
const ROOT_POM: &str = r#"<project><modelVersion>4.0.0</modelVersion><groupId>t</groupId><artifactId>root</artifactId><version>1</version><packaging>pom</packaging>
|
||||
<modules><module>lib</module><module>app</module></modules>
|
||||
<properties><maven.compiler.release>11</maven.compiler.release><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties>
|
||||
<build><pluginManagement><plugins><plugin><artifactId>maven-compiler-plugin</artifactId><version>3.13.0</version>
|
||||
<configuration><parameters>true</parameters></configuration></plugin></plugins></pluginManagement></build></project>"#;
|
||||
const LIB_POM: &str = r#"<project><modelVersion>4.0.0</modelVersion><parent><groupId>t</groupId><artifactId>root</artifactId><version>1</version></parent><artifactId>lib</artifactId></project>"#;
|
||||
const APP_POM: &str = r#"<project><modelVersion>4.0.0</modelVersion><parent><groupId>t</groupId><artifactId>root</artifactId><version>1</version></parent><artifactId>app</artifactId>
|
||||
<dependencies><dependency><groupId>t</groupId><artifactId>lib</artifactId><version>1</version></dependency></dependencies>
|
||||
<build><resources><resource><directory>src/main/resources</directory><filtering>true</filtering></resource></resources></build></project>"#;
|
||||
const ROOT_POM: &str = include_str!("../../tests/fixtures/jbuild-maven/pom.xml");
|
||||
const LIB_POM: &str = include_str!("../../tests/fixtures/jbuild-maven/lib/pom.xml");
|
||||
const APP_POM: &str = include_str!("../../tests/fixtures/jbuild-maven/app/pom.xml");
|
||||
|
||||
/// A `lib` ← `app` reactor built by the IDE's Java build with a real Maven and JDK.
|
||||
struct Fixture {
|
||||
@@ -84,6 +78,8 @@ impl Fixture {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let build = [
|
||||
// A persistent Gradle daemon can keep the fixture's output pipes open on Windows.
|
||||
("gradle.properties", "org.gradle.daemon=false\n"),
|
||||
("settings.gradle", "rootProject.name = 'root'\ninclude 'lib', 'app'\n"),
|
||||
(
|
||||
"build.gradle",
|
||||
@@ -258,6 +254,12 @@ fn builds_maven_modules_with_javac_and_only_what_changed() {
|
||||
assert_eq!(f.build(Target::Project).failure, None);
|
||||
assert_eq!(f.steps(), ["javac lib (tests, 1 file)"]);
|
||||
assert!(f.out("t.lib/test-classes/l/LTest.class").is_file());
|
||||
|
||||
// Build Module on the root aggregator compiles every submodule under it.
|
||||
f.write("app/src/test/java/a/AggTest.java", "package a;\nclass AggTest { String s = l.L.name(); }\n");
|
||||
assert_eq!(f.build(Target::Module(&f.root)).failure, None);
|
||||
assert_eq!(f.steps(), ["javac app (tests, 1 of 2 files)"]);
|
||||
assert!(f.out("t.app/test-classes/a/AggTest.class").is_file());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -164,12 +164,13 @@ pub fn maven_external_roots(
|
||||
gradle::external_roots(root, owned.iter().map(String::as_str))
|
||||
}
|
||||
|
||||
/// Source, resource and build folders of the last Gradle sync, absolute.
|
||||
/// Source, resource and build folders of the last Gradle sync, with the folder of the
|
||||
/// project reporting each; all absolute.
|
||||
pub fn gradle_source_roots(
|
||||
root: &Path,
|
||||
cache_dir: &Path,
|
||||
settings: &ide_core::settings::GradleSettings,
|
||||
) -> Vec<(PathBuf, gradle::ReportedRoot)> {
|
||||
) -> Vec<(PathBuf, gradle::ReportedRoot, PathBuf)> {
|
||||
let reported = gradle::linked_dirs(root, settings)
|
||||
.iter()
|
||||
.flat_map(|dir| sync::reported_gradle_projects(&gradle::cache_dir(cache_dir, dir)).as_ref().clone())
|
||||
|
||||
@@ -9,7 +9,7 @@ use std::io::{BufRead, BufReader, Read};
|
||||
use std::path::Path;
|
||||
use std::process::{Command, Stdio};
|
||||
use std::sync::mpsc;
|
||||
use std::time::Duration;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum Stream {
|
||||
@@ -28,6 +28,8 @@ pub(crate) const MAX_TEXT_BYTES: usize = 32 * 1024 * 1024;
|
||||
/// `on_line` takes its lines waits on its full pipe, as it would on a terminal, instead of
|
||||
/// the lines piling up in memory (a line is at most [`MAX_LINE_BYTES`] in [`run_bounded`]).
|
||||
const LINE_QUEUE: usize = 64;
|
||||
/// How long output may keep arriving after the child exits before the run stops reading it.
|
||||
const OUTPUT_AFTER_EXIT: Duration = Duration::from_secs(1);
|
||||
/// What [`pump_bounded`] reads from a pipe at a time.
|
||||
const PUMP_CHUNK: usize = 64 * 1024;
|
||||
|
||||
@@ -236,6 +238,10 @@ fn run_with_env_capture(
|
||||
let mut tail_bytes = 0usize;
|
||||
let mut total = 0usize;
|
||||
let mut truncated = false;
|
||||
// When the child exited. A process it left running (a Gradle daemon on Windows) can inherit
|
||||
// the pipes and keep them open long after; the run ends once they have been quiet this long.
|
||||
let mut exited: Option<Instant> = None;
|
||||
let mut pipes_held = false;
|
||||
loop {
|
||||
if cancel.is_cancelled() {
|
||||
kill_tree(&mut child);
|
||||
@@ -244,6 +250,9 @@ fn run_with_env_capture(
|
||||
match rx.recv_timeout(Duration::from_millis(100)) {
|
||||
Ok((_, line)) if encoding.notice.as_ref() == Some(&line) => {}
|
||||
Ok((stream, line)) => {
|
||||
if exited.is_some() {
|
||||
exited = Some(Instant::now());
|
||||
}
|
||||
on_line(stream, &line);
|
||||
if !bounded {
|
||||
// The caller parses a complete model from `text`, so keep every line.
|
||||
@@ -274,12 +283,26 @@ fn run_with_env_capture(
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(mpsc::RecvTimeoutError::Timeout) => {}
|
||||
Err(mpsc::RecvTimeoutError::Timeout) => match exited {
|
||||
Some(at) if at.elapsed() >= OUTPUT_AFTER_EXIT => {
|
||||
pipes_held = true;
|
||||
break;
|
||||
}
|
||||
Some(_) => {}
|
||||
None => {
|
||||
if child.try_wait()?.is_some() {
|
||||
exited = Some(Instant::now());
|
||||
}
|
||||
}
|
||||
},
|
||||
Err(mpsc::RecvTimeoutError::Disconnected) => break,
|
||||
}
|
||||
}
|
||||
for r in readers.into_iter().flatten() {
|
||||
let _ = r.join();
|
||||
// Readers still blocked on a pipe that a leftover process holds end with it, on their own.
|
||||
if !pipes_held {
|
||||
for r in readers.into_iter().flatten() {
|
||||
let _ = r.join();
|
||||
}
|
||||
}
|
||||
let status = child.wait()?;
|
||||
let mut text = head;
|
||||
@@ -392,6 +415,31 @@ mod tests {
|
||||
assert_eq!(err.kind, ide_core::error::ErrorKind::Cancelled);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_process_left_holding_the_pipes_does_not_hold_the_run() {
|
||||
if cfg!(windows) {
|
||||
return;
|
||||
}
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
// The background child inherits stdout and stderr, as a Gradle daemon can on Windows.
|
||||
let script = "echo built; (sleep 30) & echo done >&2";
|
||||
let started = Instant::now();
|
||||
let mut lines = Vec::new();
|
||||
let out = run(
|
||||
"sh",
|
||||
&["-c".into(), script.into()],
|
||||
tmp.path(),
|
||||
&BTreeMap::new(),
|
||||
&CancellationToken::new(),
|
||||
|_, l| lines.push(l.to_owned()),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(started.elapsed() < Duration::from_secs(10), "took {:?}", started.elapsed());
|
||||
assert!(out.success);
|
||||
lines.sort();
|
||||
assert_eq!(lines, ["built", "done"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancel_kills_grandchildren() {
|
||||
if cfg!(windows) {
|
||||
|
||||
@@ -807,12 +807,13 @@ mod tests {
|
||||
Some(gradle::ProcessedResources { task: "processResources".into(), dir: "/p/build/resources/main".into() })
|
||||
);
|
||||
let src = |p: &str| PathBuf::from(core_src(p));
|
||||
let core = PathBuf::from(format!("{b}/modules/core"));
|
||||
assert_eq!(
|
||||
gradle::reported_source_roots(&projects),
|
||||
[
|
||||
(src("main/java"), gradle::ReportedRoot::Source),
|
||||
(src("main/resources"), gradle::ReportedRoot::Resources),
|
||||
(src("test/java"), gradle::ReportedRoot::Test),
|
||||
(src("main/java"), gradle::ReportedRoot::Source, core.clone()),
|
||||
(src("main/resources"), gradle::ReportedRoot::Resources, core.clone()),
|
||||
(src("test/java"), gradle::ReportedRoot::Test, core),
|
||||
]
|
||||
);
|
||||
let mut model = gradle::load(&root).unwrap();
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
<project>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<parent>
|
||||
<groupId>t</groupId>
|
||||
<artifactId>root</artifactId>
|
||||
<version>1</version>
|
||||
</parent>
|
||||
<artifactId>app</artifactId>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>t</groupId>
|
||||
<artifactId>lib</artifactId>
|
||||
<version>1</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<build>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
</build>
|
||||
</project>
|
||||
@@ -0,0 +1,9 @@
|
||||
<project>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<parent>
|
||||
<groupId>t</groupId>
|
||||
<artifactId>root</artifactId>
|
||||
<version>1</version>
|
||||
</parent>
|
||||
<artifactId>lib</artifactId>
|
||||
</project>
|
||||
@@ -0,0 +1,35 @@
|
||||
<project>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>t</groupId>
|
||||
<artifactId>root</artifactId>
|
||||
<version>1</version>
|
||||
<packaging>pom</packaging>
|
||||
<modules>
|
||||
<module>lib</module>
|
||||
<module>app</module>
|
||||
</modules>
|
||||
<properties>
|
||||
<maven.compiler.release>11</maven.compiler.release>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
</properties>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-resources-plugin</artifactId>
|
||||
<version>3.4.0</version>
|
||||
</plugin>
|
||||
</plugins>
|
||||
<pluginManagement>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.13.0</version>
|
||||
<configuration>
|
||||
<parameters>true</parameters>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</pluginManagement>
|
||||
</build>
|
||||
</project>
|
||||
@@ -58,9 +58,10 @@ pub fn set_text(text: &str, owner: usize) -> std::io::Result<()> {
|
||||
imp::set_text(text, owner)
|
||||
}
|
||||
|
||||
/// The clipboard's plain text, None when it holds none. macOS only (main thread);
|
||||
/// Linux reads it asynchronously through GTK in the app, Windows through the WebView.
|
||||
#[cfg(target_os = "macos")]
|
||||
/// The clipboard's plain text. None when macOS holds none, or when Windows cannot
|
||||
/// open the clipboard; empty when Windows holds none. Call on the main thread on
|
||||
/// macOS; Linux reads it asynchronously through GTK in the app.
|
||||
#[cfg(any(windows, target_os = "macos"))]
|
||||
pub fn text() -> Option<String> {
|
||||
imp::text()
|
||||
}
|
||||
@@ -255,6 +256,15 @@ pub fn decode(bytes: &[u8]) -> Vec<PathBuf> {
|
||||
out
|
||||
}
|
||||
|
||||
/// A `CF_UNICODETEXT` block as a string: UTF-16LE up to the first NUL. The block
|
||||
/// may be larger than the text, and a malformed one may lack the NUL.
|
||||
#[cfg(any(windows, test))]
|
||||
fn unicode_text(bytes: &[u8]) -> String {
|
||||
let (pairs, _) = bytes.as_chunks::<2>();
|
||||
let units: Vec<u16> = pairs.iter().map(|&pair| u16::from_le_bytes(pair)).take_while(|&unit| unit != 0).collect();
|
||||
String::from_utf16_lossy(&units)
|
||||
}
|
||||
|
||||
/// `BI_RGB` and `BI_BITFIELDS`: uncompressed pixels, the forms screenshots take.
|
||||
#[cfg(any(windows, test))]
|
||||
const BI_RGB: u32 = 0;
|
||||
@@ -310,7 +320,7 @@ fn dib_to_png(dib: &[u8]) -> Option<Vec<u8>> {
|
||||
|
||||
#[cfg(windows)]
|
||||
mod imp {
|
||||
use super::{HEADER, decode, dib_to_png, encode, names_text};
|
||||
use super::{HEADER, decode, dib_to_png, encode, names_text, unicode_text};
|
||||
use std::ffi::c_void;
|
||||
use std::path::PathBuf;
|
||||
use std::ptr;
|
||||
@@ -394,6 +404,19 @@ mod imp {
|
||||
image
|
||||
}
|
||||
|
||||
pub fn text() -> Option<String> {
|
||||
// Empty rather than None: a None falls back to the WebView, which prompts the user.
|
||||
if unsafe { IsClipboardFormatAvailable(CF_UNICODETEXT) } == 0 {
|
||||
return Some(String::new());
|
||||
}
|
||||
if !open() {
|
||||
return None;
|
||||
}
|
||||
let text = read_block(CF_UNICODETEXT).map(|bytes| unicode_text(&bytes));
|
||||
unsafe { CloseClipboard() };
|
||||
text
|
||||
}
|
||||
|
||||
#[link(name = "kernel32")]
|
||||
unsafe extern "system" {
|
||||
fn GlobalAlloc(flags: u32, bytes: usize) -> Handle;
|
||||
@@ -890,6 +913,16 @@ mod tests {
|
||||
assert!(set_png(&header, 0).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unicode_text_stops_at_the_nul() {
|
||||
let mut bytes: Vec<u8> = "héllo\r\n世界".encode_utf16().chain([0, 0x41]).flat_map(u16::to_le_bytes).collect();
|
||||
assert_eq!(unicode_text(&bytes), "héllo\r\n世界");
|
||||
// No terminator, and a stray odd byte, still read the whole text.
|
||||
bytes.truncate(bytes.len() - 4);
|
||||
bytes.push(7);
|
||||
assert_eq!(unicode_text(&bytes), "héllo\r\n世界");
|
||||
}
|
||||
|
||||
fn paths(list: &[&str]) -> Vec<PathBuf> {
|
||||
list.iter().map(PathBuf::from).collect()
|
||||
}
|
||||
|
||||
@@ -486,6 +486,15 @@ pub struct LanguageCodeStyle {
|
||||
/// SQL › Case › Identifiers (unquoted names): `upper` | `lower` | `keep`.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub identifier_case: Option<String>,
|
||||
/// JavaScript / TypeScript › Punctuation › Semicolons: `ignore` | `insert` | `remove`.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub semicolons: Option<String>,
|
||||
/// JavaScript / TypeScript › Punctuation › Quotes: `auto` | `single` | `double`.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub quotes: Option<String>,
|
||||
/// JavaScript / TypeScript › Spaces, by tsserver format option (`insertSpaceAfterCommaDelimiter`).
|
||||
#[serde(skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub spaces: BTreeMap<String, bool>,
|
||||
}
|
||||
|
||||
/// Editor › Code Style (General tab + per-language overrides).
|
||||
|
||||
@@ -46,6 +46,8 @@ pub enum ErrorData {
|
||||
JavaBuildProblems {
|
||||
problems: Vec<String>,
|
||||
},
|
||||
/// A remote backend of another OpenIDEA build still serves the project and refused to retire.
|
||||
RemoteBackendBusy,
|
||||
}
|
||||
|
||||
/// Git's reported result for each destination ref. A remote with several push URLs can
|
||||
|
||||
@@ -19,6 +19,7 @@ pub mod java_runtime;
|
||||
pub mod jsonc;
|
||||
pub mod memory;
|
||||
pub mod output_encoding;
|
||||
pub mod output_rate;
|
||||
pub mod platform;
|
||||
pub mod process;
|
||||
pub mod project_dir;
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
//! How often the terminal and Run console pumps hand output to the UI, from
|
||||
//! Settings › Tools › Terminal › Max FPS (#5897). The frontend paints at most that
|
||||
//! often anyway; batching at half its frame interval keeps a fresh batch ready for
|
||||
//! every frame while cutting the IPC events (and their handling on the UI thread)
|
||||
//! that would only be buffered there.
|
||||
|
||||
use std::sync::atomic::{AtomicU32, Ordering};
|
||||
use std::time::Duration;
|
||||
|
||||
/// Frames per second; 0 is Unlimited.
|
||||
static MAX_FPS: AtomicU32 = AtomicU32::new(0);
|
||||
|
||||
/// Applies the `terminal.maxFps` setting: `"unlimited"` or a number of frames per second.
|
||||
/// Running sessions pick it up at their next batch.
|
||||
pub fn set_max_fps(setting: &str) {
|
||||
MAX_FPS.store(setting.trim().parse::<u32>().unwrap_or(0), Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// The batch interval for a pump whose Unlimited interval is `unlimited`.
|
||||
pub fn batch_interval(unlimited: Duration) -> Duration {
|
||||
interval_for(MAX_FPS.load(Ordering::Relaxed), unlimited)
|
||||
}
|
||||
|
||||
/// Half the paint interval, within 4–200 ms, and never faster than the Unlimited rate.
|
||||
fn interval_for(fps: u32, unlimited: Duration) -> Duration {
|
||||
if fps == 0 {
|
||||
return unlimited;
|
||||
}
|
||||
Duration::from_millis((500 / u64::from(fps)).clamp(4, 200)).max(unlimited)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn interval_is_half_the_frame_and_clamped() {
|
||||
let terminal = Duration::from_millis(4);
|
||||
let run = Duration::from_millis(8);
|
||||
let ms = |fps, unlimited| interval_for(fps, unlimited).as_millis();
|
||||
assert_eq!(ms(0, terminal), 4, "Unlimited keeps the pump's own rate");
|
||||
assert_eq!(ms(0, run), 8);
|
||||
assert_eq!([60, 30, 15, 10, 5].map(|fps| ms(fps, terminal)), [8, 16, 33, 50, 100]);
|
||||
assert_eq!(ms(1, terminal), 200, "upper bound");
|
||||
assert_eq!(ms(1000, terminal), 4, "lower bound");
|
||||
assert_eq!(ms(1000, run), 8, "never faster than Unlimited");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn setting_values_parse_and_unknown_means_unlimited() {
|
||||
set_max_fps("30");
|
||||
assert_eq!(batch_interval(Duration::from_millis(4)).as_millis(), 16);
|
||||
set_max_fps("unlimited");
|
||||
assert_eq!(batch_interval(Duration::from_millis(4)).as_millis(), 4);
|
||||
set_max_fps("fast");
|
||||
assert_eq!(batch_interval(Duration::from_millis(8)).as_millis(), 8);
|
||||
}
|
||||
}
|
||||
@@ -417,10 +417,10 @@ impl Default for McpServerSettings {
|
||||
}
|
||||
}
|
||||
|
||||
/// Tools › Download sources: a mirror the installer tries when `github.com` is slow or
|
||||
/// unreachable.
|
||||
/// Tools › Download sources: mirrors the installer tries, in order, when `github.com` is slow
|
||||
/// or unreachable.
|
||||
///
|
||||
/// The mirror is a proxy prefix: the official URL is appended to it unchanged
|
||||
/// A mirror is a proxy prefix: the official URL is appended to it unchanged
|
||||
/// (`https://mirror.example/https://github.com/o/r/releases/download/…`), which is what the
|
||||
/// public GitHub proxies speak. Only `github.com` downloads are affected — those proxies
|
||||
/// hard-code that host, so Eclipse JDT LS and Open VSX keep their official addresses. Empty by
|
||||
@@ -428,8 +428,9 @@ impl Default for McpServerSettings {
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct ToolDownloadSettings {
|
||||
/// Proxy prefix prepended to `https://github.com/…` archive addresses only; empty keeps
|
||||
/// every download on its official host.
|
||||
/// Proxy prefixes prepended to `https://github.com/…` archive addresses only, separated by
|
||||
/// commas or whitespace and tried in order before the official host; empty keeps every
|
||||
/// download on its official host.
|
||||
pub github_mirror: String,
|
||||
}
|
||||
|
||||
@@ -823,6 +824,8 @@ pub struct AppearanceSettings {
|
||||
pub contrast_scrollbars: bool,
|
||||
/// Adjust colours for red-green vision deficiency.
|
||||
pub red_green_vision: bool,
|
||||
/// Turn off animations and transitions (also on when the OS asks for reduced motion).
|
||||
pub reduce_motion: bool,
|
||||
pub different_tool_window_background: bool,
|
||||
pub compact_mode: bool,
|
||||
/// IDEA "Use smaller indents in trees": tool window trees indent less per level.
|
||||
@@ -963,6 +966,7 @@ impl Default for AppearanceSettings {
|
||||
ui_font_fallback: String::new(),
|
||||
contrast_scrollbars: false,
|
||||
red_green_vision: false,
|
||||
reduce_motion: false,
|
||||
different_tool_window_background: false,
|
||||
compact_mode: false,
|
||||
small_tree_indents: false,
|
||||
@@ -1208,6 +1212,8 @@ pub struct LanguagesSettings {
|
||||
pub prettier: ExternalFormatterSettings,
|
||||
pub oxfmt: ExternalFormatterSettings,
|
||||
pub biome: ExternalFormatterSettings,
|
||||
/// dprint formats every file its configuration covers: `languages` is unused.
|
||||
pub dprint: ExternalFormatterSettings,
|
||||
pub ruff: ExternalFormatterSettings,
|
||||
pub black: ExternalFormatterSettings,
|
||||
pub java: JavaSettings,
|
||||
@@ -1234,6 +1240,7 @@ impl Default for LanguagesSettings {
|
||||
languages: BIOME_LANGUAGES.iter().map(|&l| l.into()).collect(),
|
||||
..ExternalFormatterSettings::default()
|
||||
},
|
||||
dprint: ExternalFormatterSettings { languages: Vec::new(), ..ExternalFormatterSettings::default() },
|
||||
ruff: ExternalFormatterSettings {
|
||||
languages: vec!["python".into()],
|
||||
..ExternalFormatterSettings::default()
|
||||
@@ -1311,6 +1318,7 @@ impl LanguagesSettings {
|
||||
ExternalFormatter::Prettier => &self.prettier,
|
||||
ExternalFormatter::Oxfmt => &self.oxfmt,
|
||||
ExternalFormatter::Biome => &self.biome,
|
||||
ExternalFormatter::Dprint => &self.dprint,
|
||||
ExternalFormatter::Ruff => &self.ruff,
|
||||
ExternalFormatter::Black => &self.black,
|
||||
}
|
||||
@@ -1324,6 +1332,7 @@ pub enum ExternalFormatter {
|
||||
Prettier,
|
||||
Oxfmt,
|
||||
Biome,
|
||||
Dprint,
|
||||
Ruff,
|
||||
Black,
|
||||
}
|
||||
@@ -1335,6 +1344,7 @@ impl ExternalFormatter {
|
||||
Self::Prettier => "prettier",
|
||||
Self::Oxfmt => "oxfmt",
|
||||
Self::Biome => "biome",
|
||||
Self::Dprint => "dprint",
|
||||
Self::Ruff => "ruff",
|
||||
Self::Black => "black",
|
||||
}
|
||||
@@ -1345,11 +1355,11 @@ impl ExternalFormatter {
|
||||
pub const BIOME_LANGUAGES: [&str; 8] =
|
||||
["css", "graphql", "javascript", "javascriptreact", "typescript", "typescriptreact", "json", "jsonc"];
|
||||
|
||||
/// An external formatter (Prettier, oxfmt, Biome, Ruff, Black) and the languages it formats.
|
||||
/// An external formatter (Prettier, oxfmt, Biome, dprint, Ruff, Black) and the languages it formats.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct ExternalFormatterSettings {
|
||||
/// Empty path: project node_modules (Prettier/oxfmt/Biome), managed installation, then PATH.
|
||||
/// Empty path: project node_modules (Prettier/oxfmt/Biome/dprint), managed installation, then PATH.
|
||||
pub path: String,
|
||||
/// Ruff only: directory containing its configuration, or a configuration file.
|
||||
pub configuration_directory: String,
|
||||
@@ -1720,11 +1730,14 @@ pub struct TypeScriptSettings {
|
||||
/// plugin (hybrid mode; a Vue project's program alone needs ~3 GiB, and the
|
||||
/// vtsls default 3072 dies in a GC death spiral), else unset (vtsls default).
|
||||
pub tsserver_max_memory: u32,
|
||||
/// Problems › TypeScript project errors: the project's own `tsc --watch` per root
|
||||
/// `tsconfig.json` reports the errors of files that are not open.
|
||||
pub watch_problems: bool,
|
||||
}
|
||||
|
||||
impl Default for TypeScriptSettings {
|
||||
fn default() -> Self {
|
||||
Self { version: "bundled".into(), tsserver_max_memory: 0 }
|
||||
Self { version: "bundled".into(), tsserver_max_memory: 0, watch_problems: false }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -308,6 +308,14 @@ pub struct SessionInfo {
|
||||
pub parent: Option<DebugSessionId>,
|
||||
}
|
||||
|
||||
/// One owner's breakpoints, kept without a session and sent when one of its sessions starts.
|
||||
#[derive(Default)]
|
||||
struct OwnerBreakpoints {
|
||||
lines: BTreeMap<PathBuf, Vec<Breakpoint>>,
|
||||
functions: Vec<FunctionBreakpoint>,
|
||||
data: Vec<DataBreakpoint>,
|
||||
}
|
||||
|
||||
/// Who started a session. Every event of the session, and of the child sessions
|
||||
/// its adapter starts, goes to `sink` only; `key` (e.g. a window label) scopes
|
||||
/// listings such as [`DebugManager::sessions`].
|
||||
@@ -336,13 +344,12 @@ pub struct DebugManager {
|
||||
sessions: Mutex<HashMap<DebugSessionId, Arc<Session>>>,
|
||||
/// Session start order, for "the first session" semantics.
|
||||
order: Mutex<Vec<DebugSessionId>>,
|
||||
breakpoints: Mutex<BTreeMap<PathBuf, Vec<Breakpoint>>>,
|
||||
/// Breakpoints by owner (window): each window's sessions get only its own.
|
||||
breakpoints: Mutex<HashMap<String, OwnerBreakpoints>>,
|
||||
states: Mutex<HashMap<PathBuf, Vec<BreakpointState>>>,
|
||||
/// Explicit exception filter choices (filter id → enabled); unset filters use the adapter default.
|
||||
exception_choices: Mutex<BTreeMap<String, bool>>,
|
||||
exception_classes: Mutex<Vec<ExceptionClassBreakpoint>>,
|
||||
function_breakpoints: Mutex<Vec<FunctionBreakpoint>>,
|
||||
data_breakpoints: Mutex<Vec<DataBreakpoint>>,
|
||||
/// In-flight stops, by session: a second Stop sets `stop_force`, the waiting one kills.
|
||||
stopping: Mutex<HashMap<DebugSessionId, Arc<Session>>>,
|
||||
jvm_finder: Mutex<jvm_memory::JvmFinder>,
|
||||
@@ -450,6 +457,21 @@ fn no_session(s: DebugSessionId) -> IdeError {
|
||||
IdeError::not_found(format!("no debug session {}", s.0))
|
||||
}
|
||||
|
||||
/// debugpy hands a subprocess (`subProcess: true`, forked or spawned) over as an `attach` whose
|
||||
/// `connect` is its own client listener: the child session is another connection to the running
|
||||
/// adapter, as VS Code makes it, not a new adapter that would take that port for a debug server.
|
||||
fn subprocess_connection(configuration: &Value, spec: &AdapterSpec) -> Option<(AdapterSpec, u16)> {
|
||||
configuration.get("subProcessId")?;
|
||||
let connect = configuration.get("connect")?;
|
||||
let port = u16::try_from(connect.get("port")?.as_u64()?).ok()?;
|
||||
let mut spec = spec.clone();
|
||||
if let Some(host) = connect.get("host").and_then(Value::as_str) {
|
||||
let loopback = host == "localhost" || host.parse::<std::net::IpAddr>().is_ok_and(|ip| ip.is_loopback());
|
||||
spec.server_host = (!loopback).then(|| host.to_owned());
|
||||
}
|
||||
Some((spec, port))
|
||||
}
|
||||
|
||||
/// The name of a child session: the adapter's, or the parent's when it gives none. js-debug
|
||||
/// names a browser page's session after the page the browser starts on, before the URL
|
||||
/// loads (`about:blank`, or nothing in a new profile), which says nothing about what is debugged.
|
||||
@@ -803,8 +825,6 @@ impl DebugManager {
|
||||
states: Mutex::default(),
|
||||
exception_choices: Mutex::default(),
|
||||
exception_classes: Mutex::default(),
|
||||
function_breakpoints: Mutex::default(),
|
||||
data_breakpoints: Mutex::default(),
|
||||
stopping: Mutex::default(),
|
||||
jvm_finder: Mutex::new(Arc::new(jvm_memory::find_local_jvm)),
|
||||
})
|
||||
@@ -824,8 +844,24 @@ impl DebugManager {
|
||||
self.order.lock().iter().filter_map(|id| sessions.get(id).cloned()).collect()
|
||||
}
|
||||
|
||||
pub(crate) fn stored_breakpoints(&self, path: &Path) -> Vec<Breakpoint> {
|
||||
self.breakpoints.lock().get(path).cloned().unwrap_or_default()
|
||||
pub(crate) fn stored_breakpoints(&self, owner: &str, path: &Path) -> Vec<Breakpoint> {
|
||||
self.breakpoints.lock().get(owner).and_then(|b| b.lines.get(path).cloned()).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn function_breakpoints(&self, owner: &str) -> Vec<FunctionBreakpoint> {
|
||||
self.breakpoints.lock().get(owner).map(|b| b.functions.clone()).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn data_breakpoints(&self, owner: &str) -> Vec<DataBreakpoint> {
|
||||
self.breakpoints.lock().get(owner).map(|b| b.data.clone()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// `owner`'s sessions that take breakpoint requests.
|
||||
fn configured_sessions(&self, owner: &str) -> Vec<Arc<Session>> {
|
||||
self.live_sessions()
|
||||
.into_iter()
|
||||
.filter(|s| s.owner.key == owner && s.configured.load(Ordering::Acquire) && !s.conn.is_closed())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Live sessions of `owner` (all owners when `None`).
|
||||
@@ -1032,6 +1068,13 @@ impl DebugManager {
|
||||
if let Some(obj) = configuration.as_object_mut() {
|
||||
obj.entry("request").or_insert_with(|| request.clone().into());
|
||||
}
|
||||
let (spec, port) = match parent.port {
|
||||
Some(port) => (parent.spec.clone(), Some(port)),
|
||||
None => match subprocess_connection(&configuration, &parent.spec) {
|
||||
Some((spec, port)) => (spec, Some(port)),
|
||||
None => (parent.spec.clone(), None),
|
||||
},
|
||||
};
|
||||
self.start_session(
|
||||
DebugSessionId::next(),
|
||||
parent.owner.clone(),
|
||||
@@ -1040,8 +1083,8 @@ impl DebugManager {
|
||||
Some(parent.id),
|
||||
request,
|
||||
configuration,
|
||||
parent.spec.clone(),
|
||||
parent.port,
|
||||
spec,
|
||||
port,
|
||||
None,
|
||||
)
|
||||
.await
|
||||
@@ -1269,8 +1312,10 @@ impl DebugManager {
|
||||
let (files, idle): (Vec<_>, Vec<_>) = self
|
||||
.breakpoints
|
||||
.lock()
|
||||
.iter()
|
||||
.map(|(p, b)| (p.clone(), b.clone()))
|
||||
.get(&s.owner.key)
|
||||
.map(|b| b.lines.iter().map(|(p, b)| (p.clone(), b.clone())).collect::<Vec<_>>())
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.partition(|(_, b)| b.iter().any(|b| b.enabled));
|
||||
let sent = join_all(files.iter().map(|(path, bps)| s.send_breakpoints(path, bps, None))).await;
|
||||
// Breakpoint states follow the owner's first session.
|
||||
@@ -1288,14 +1333,14 @@ impl DebugManager {
|
||||
Err(e) => tracing::debug!("setBreakpoints for {} failed: {e}", path.display()),
|
||||
}
|
||||
}
|
||||
let functions = self.function_breakpoints.lock().clone();
|
||||
let functions = self.function_breakpoints(&s.owner.key);
|
||||
if !functions.is_empty()
|
||||
&& s.supports("supportsFunctionBreakpoints")
|
||||
&& let Err(e) = s.send_function_breakpoints(&functions).await
|
||||
{
|
||||
tracing::debug!("setFunctionBreakpoints failed: {e}");
|
||||
}
|
||||
let data = self.data_breakpoints.lock().clone();
|
||||
let data = self.data_breakpoints(&s.owner.key);
|
||||
if !data.is_empty()
|
||||
&& s.supports("supportsDataBreakpoints")
|
||||
&& let Err(e) = s.send_data_breakpoints(&data).await
|
||||
@@ -1448,26 +1493,59 @@ impl DebugManager {
|
||||
}
|
||||
}
|
||||
|
||||
/// Breakpoints are kept per file even without a session and sent on start.
|
||||
/// Returns states from the first live session, or unverified states when none.
|
||||
/// `owner`'s breakpoints are kept per file even without a session and sent when one of
|
||||
/// its sessions starts. Returns states from its first live session, or unverified states.
|
||||
pub async fn set_breakpoints(
|
||||
&self,
|
||||
owner: &str,
|
||||
path: PathBuf,
|
||||
breakpoints: Vec<Breakpoint>,
|
||||
) -> IdeResult<Vec<BreakpointState>> {
|
||||
{
|
||||
let mut store = self.breakpoints.lock();
|
||||
let lines = &mut store.entry(owner.to_owned()).or_default().lines;
|
||||
if breakpoints.is_empty() {
|
||||
store.remove(&path);
|
||||
lines.remove(&path);
|
||||
} else {
|
||||
store.insert(path.clone(), breakpoints.clone());
|
||||
lines.insert(path.clone(), breakpoints.clone());
|
||||
}
|
||||
}
|
||||
self.send_file_breakpoints(owner, path, breakpoints).await
|
||||
}
|
||||
|
||||
/// Replaces all of `owner`'s line breakpoints with `files` (the window's whole list), sending
|
||||
/// the files that changed to its sessions. A file the window no longer lists can't stay
|
||||
/// behind and be sent to every later session, whatever made the two lists diverge (#6116).
|
||||
pub async fn replace_breakpoints(&self, owner: &str, files: BTreeMap<PathBuf, Vec<Breakpoint>>) -> IdeResult<()> {
|
||||
let changed: Vec<(PathBuf, Vec<Breakpoint>)> = {
|
||||
let mut store = self.breakpoints.lock();
|
||||
let lines = &mut store.entry(owner.to_owned()).or_default().lines;
|
||||
let files: BTreeMap<_, _> = files.into_iter().filter(|(_, b)| !b.is_empty()).collect();
|
||||
let removed = lines.keys().filter(|p| !files.contains_key(*p)).map(|p| (p.clone(), Vec::new()));
|
||||
let changed = files.iter().filter(|(p, b)| lines.get(*p) != Some(b)).map(|(p, b)| (p.clone(), b.clone()));
|
||||
let changed = removed.chain(changed).collect();
|
||||
*lines = files;
|
||||
changed
|
||||
};
|
||||
for (path, breakpoints) in changed {
|
||||
self.send_file_breakpoints(owner, path, breakpoints).await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Drops `owner`'s breakpoints (its window closed).
|
||||
pub fn forget_breakpoints(&self, owner: &str) {
|
||||
self.breakpoints.lock().remove(owner);
|
||||
}
|
||||
|
||||
async fn send_file_breakpoints(
|
||||
&self,
|
||||
owner: &str,
|
||||
path: PathBuf,
|
||||
breakpoints: Vec<Breakpoint>,
|
||||
) -> IdeResult<Vec<BreakpointState>> {
|
||||
let mut result: Option<Vec<BreakpointState>> = None;
|
||||
for s in self.live_sessions() {
|
||||
if !s.configured.load(Ordering::Acquire) || s.conn.is_closed() {
|
||||
continue;
|
||||
}
|
||||
for s in self.configured_sessions(owner) {
|
||||
match s.send_breakpoints(&path, &breakpoints, None).await {
|
||||
Ok(states) => {
|
||||
result.get_or_insert(states);
|
||||
@@ -1618,16 +1696,39 @@ impl DebugManager {
|
||||
}
|
||||
|
||||
pub async fn stack_trace(&self, s: DebugSessionId, thread_id: i64) -> IdeResult<Vec<StackFrame>> {
|
||||
const MAX_FRAMES: u64 = 400;
|
||||
let session = self.session(s)?;
|
||||
session.check_thread(thread_id)?;
|
||||
let body = session
|
||||
.conn
|
||||
.request_timeout(
|
||||
let request = |start: u64, levels: u64| {
|
||||
session.conn.request_timeout(
|
||||
"stackTrace",
|
||||
json!({ "threadId": thread_id, "startFrame": 0, "levels": 400 }),
|
||||
json!({ "threadId": thread_id, "startFrame": start, "levels": levels }),
|
||||
REQUEST_TIMEOUT,
|
||||
)
|
||||
.await?;
|
||||
};
|
||||
let frames_of = |mut body: Value| match body.get_mut("stackFrames").map(Value::take) {
|
||||
Some(Value::Array(frames)) => frames,
|
||||
_ => Vec::new(),
|
||||
};
|
||||
let raw = match request(0, MAX_FRAMES).await {
|
||||
Ok(body) => frames_of(body),
|
||||
// java-debug fails the whole request when one frame's source lookup throws (on Windows,
|
||||
// a CGLIB proxy's `<generated>` source against `sourcePaths`): the frames come one at a
|
||||
// time instead, without the ones it cannot describe.
|
||||
// ponytail: one request per frame; page around the failing ones if deep stacks get slow.
|
||||
Err(first @ DapError::Failed { .. }) => {
|
||||
let Ok(top) = request(0, 1).await else { return Err(first.into()) };
|
||||
let total = top.get("totalFrames").and_then(Value::as_u64).unwrap_or(MAX_FRAMES).min(MAX_FRAMES);
|
||||
let mut raw = frames_of(top);
|
||||
for start in 1..total {
|
||||
if let Ok(body) = request(start, 1).await {
|
||||
raw.extend(frames_of(body));
|
||||
}
|
||||
}
|
||||
raw
|
||||
}
|
||||
Err(e) => return Err(e.into()),
|
||||
};
|
||||
let kotlin_lsp = session.kotlin_lsp_quirks().is_some();
|
||||
let frame = |f: &Value| {
|
||||
let mut frame = frame_from(f);
|
||||
@@ -1639,7 +1740,7 @@ impl DebugManager {
|
||||
}
|
||||
frame
|
||||
};
|
||||
Ok(body.get("stackFrames").and_then(Value::as_array).map(|f| f.iter().map(frame).collect()).unwrap_or_default())
|
||||
Ok(raw.iter().map(frame).collect())
|
||||
}
|
||||
|
||||
pub async fn scopes(&self, s: DebugSessionId, frame_id: i64) -> IdeResult<Vec<Scope>> {
|
||||
@@ -1831,7 +1932,7 @@ impl DebugManager {
|
||||
if force {
|
||||
self.suspend_breakpoints(&session, Some(&path)).await?;
|
||||
}
|
||||
let stored = self.stored_breakpoints(&path);
|
||||
let stored = self.stored_breakpoints(&session.owner.key, &path);
|
||||
let sent: Vec<Breakpoint> =
|
||||
if force { stored.iter().map(|b| Breakpoint { enabled: false, ..b.clone() }).collect() } else { stored };
|
||||
session.send_breakpoints(&path, &sent, Some(line)).await?;
|
||||
@@ -1846,10 +1947,15 @@ impl DebugManager {
|
||||
let files: Vec<PathBuf> = self
|
||||
.breakpoints
|
||||
.lock()
|
||||
.iter()
|
||||
.filter(|(path, bps)| Some(path.as_path()) != except && bps.iter().any(|b| b.enabled))
|
||||
.map(|(path, _)| path.clone())
|
||||
.collect();
|
||||
.get(&session.owner.key)
|
||||
.map(|b| {
|
||||
b.lines
|
||||
.iter()
|
||||
.filter(|(path, bps)| Some(path.as_path()) != except && bps.iter().any(|b| b.enabled))
|
||||
.map(|(path, _)| path.clone())
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let sent = join_all(files.iter().map(|path| session.send_breakpoints(path, &[], None))).await;
|
||||
let mut failed = None;
|
||||
for (path, result) in files.into_iter().zip(sent) {
|
||||
@@ -1863,11 +1969,12 @@ impl DebugManager {
|
||||
if let Some(e) = failed {
|
||||
return Err(e.into());
|
||||
}
|
||||
if !self.function_breakpoints.lock().is_empty() && session.supports("supportsFunctionBreakpoints") {
|
||||
if !self.function_breakpoints(&session.owner.key).is_empty() && session.supports("supportsFunctionBreakpoints")
|
||||
{
|
||||
session.send_function_breakpoints(&[]).await?;
|
||||
session.pending_restore.lock().functions = true;
|
||||
}
|
||||
if !self.data_breakpoints.lock().is_empty() && session.supports("supportsDataBreakpoints") {
|
||||
if !self.data_breakpoints(&session.owner.key).is_empty() && session.supports("supportsDataBreakpoints") {
|
||||
session.send_data_breakpoints(&[]).await?;
|
||||
session.pending_restore.lock().data = true;
|
||||
}
|
||||
@@ -1877,8 +1984,11 @@ impl DebugManager {
|
||||
/// Re-sends what [`suspend_breakpoints`](Self::suspend_breakpoints) / run to cursor replaced.
|
||||
pub(crate) async fn restore_breakpoints(&self, session: &Arc<Session>) {
|
||||
let pending = std::mem::take(&mut *session.pending_restore.lock());
|
||||
let files: Vec<(PathBuf, Vec<Breakpoint>)> =
|
||||
pending.files.into_iter().map(|path| (path.clone(), self.stored_breakpoints(&path))).collect();
|
||||
let files: Vec<(PathBuf, Vec<Breakpoint>)> = pending
|
||||
.files
|
||||
.into_iter()
|
||||
.map(|path| (path.clone(), self.stored_breakpoints(&session.owner.key, &path)))
|
||||
.collect();
|
||||
let sent = join_all(files.iter().map(|(path, bps)| session.send_breakpoints(path, bps, None))).await;
|
||||
for ((path, _), result) in files.iter().zip(sent) {
|
||||
if let Err(e) = result {
|
||||
@@ -1886,13 +1996,13 @@ impl DebugManager {
|
||||
}
|
||||
}
|
||||
if pending.functions {
|
||||
let functions = self.function_breakpoints.lock().clone();
|
||||
let functions = self.function_breakpoints(&session.owner.key);
|
||||
if let Err(e) = session.send_function_breakpoints(&functions).await {
|
||||
tracing::debug!("restoring function breakpoints failed: {e}");
|
||||
}
|
||||
}
|
||||
if pending.data {
|
||||
let data = self.data_breakpoints.lock().clone();
|
||||
let data = self.data_breakpoints(&session.owner.key);
|
||||
if let Err(e) = session.send_data_breakpoints(&data).await {
|
||||
tracing::debug!("restoring data breakpoints failed: {e}");
|
||||
}
|
||||
@@ -2102,14 +2212,17 @@ impl DebugManager {
|
||||
Ok(hot_swap_result(&body))
|
||||
}
|
||||
|
||||
/// Stores method breakpoints (kept without a session, sent on start) and sends them to
|
||||
/// every configured session whose adapter supports them. States from the first one.
|
||||
pub async fn set_function_breakpoints(&self, list: Vec<FunctionBreakpoint>) -> IdeResult<Vec<BreakpointState>> {
|
||||
*self.function_breakpoints.lock() = list.clone();
|
||||
/// Stores `owner`'s method breakpoints (kept without a session, sent on start) and sends them
|
||||
/// to each of its configured sessions whose adapter supports them. States from the first one.
|
||||
pub async fn set_function_breakpoints(
|
||||
&self,
|
||||
owner: &str,
|
||||
list: Vec<FunctionBreakpoint>,
|
||||
) -> IdeResult<Vec<BreakpointState>> {
|
||||
self.breakpoints.lock().entry(owner.to_owned()).or_default().functions = list.clone();
|
||||
let mut result = None;
|
||||
for s in self.live_sessions() {
|
||||
if !s.configured.load(Ordering::Acquire) || s.conn.is_closed() || !s.supports("supportsFunctionBreakpoints")
|
||||
{
|
||||
for s in self.configured_sessions(owner) {
|
||||
if !s.supports("supportsFunctionBreakpoints") {
|
||||
continue;
|
||||
}
|
||||
match s.send_function_breakpoints(&list).await {
|
||||
@@ -2122,12 +2235,17 @@ impl DebugManager {
|
||||
Ok(result.unwrap_or_else(|| unverified(list.iter().map(|b| b.enabled))))
|
||||
}
|
||||
|
||||
/// Stores field watchpoints and sends them to every configured session that supports them.
|
||||
pub async fn set_data_breakpoints(&self, list: Vec<DataBreakpoint>) -> IdeResult<Vec<BreakpointState>> {
|
||||
*self.data_breakpoints.lock() = list.clone();
|
||||
/// Stores `owner`'s field watchpoints and sends them to each of its configured sessions that
|
||||
/// supports them.
|
||||
pub async fn set_data_breakpoints(
|
||||
&self,
|
||||
owner: &str,
|
||||
list: Vec<DataBreakpoint>,
|
||||
) -> IdeResult<Vec<BreakpointState>> {
|
||||
self.breakpoints.lock().entry(owner.to_owned()).or_default().data = list.clone();
|
||||
let mut result = None;
|
||||
for s in self.live_sessions() {
|
||||
if !s.configured.load(Ordering::Acquire) || s.conn.is_closed() || !s.supports("supportsDataBreakpoints") {
|
||||
for s in self.configured_sessions(owner) {
|
||||
if !s.supports("supportsDataBreakpoints") {
|
||||
continue;
|
||||
}
|
||||
match s.send_data_breakpoints(&list).await {
|
||||
|
||||
@@ -1017,6 +1017,13 @@ fn on_reverse_request(mgr: &Arc<DebugManager>, s: &Arc<Session>, seq: i64, comma
|
||||
}
|
||||
}
|
||||
|
||||
/// `text` as a terminal sends it when typed: Enter is CR. A Unix terminal turns CR into the
|
||||
/// newline a line read waits for, but Windows' ConPTY reads LF as Ctrl+J, so a program blocked
|
||||
/// in `input()` never sees its line end (#6041).
|
||||
fn as_typed(text: &str) -> std::borrow::Cow<'_, str> {
|
||||
if text.contains('\n') { text.replace("\r\n", "\r").replace('\n', "\r").into() } else { text.into() }
|
||||
}
|
||||
|
||||
/// A `runInTerminal` program and the pseudo-terminal it runs in.
|
||||
pub(crate) struct ProgramTerminal {
|
||||
writer: Arc<ide_core::input::InputWriter>,
|
||||
@@ -1030,7 +1037,7 @@ pub(crate) struct ProgramTerminal {
|
||||
|
||||
impl ProgramTerminal {
|
||||
pub(crate) fn write(&mut self, text: &str) -> std::io::Result<()> {
|
||||
self.writer.write(text.as_bytes())
|
||||
self.writer.write(as_typed(text).as_bytes())
|
||||
}
|
||||
|
||||
/// The program's process id while it runs.
|
||||
@@ -1386,6 +1393,13 @@ fn parse_jdwp_port(line: &str) -> Option<u16> {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn typed_input_ends_lines_with_enter() {
|
||||
assert_eq!(super::as_typed("42\n"), "42\r");
|
||||
assert_eq!(super::as_typed("a\r\nb\n"), "a\rb\r");
|
||||
assert_eq!(super::as_typed("no newline"), "no newline");
|
||||
}
|
||||
|
||||
use super::{Suspension, kotlin_jvm_args, parse_jdwp_port};
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -122,8 +122,12 @@ struct Script {
|
||||
run_in_terminal: Option<Vec<String>>,
|
||||
/// Send a `startDebugging` reverse request (child session) when a non-child `launch` arrives.
|
||||
start_debugging: bool,
|
||||
/// The child's `startDebugging` arguments instead of a js-debug style `launch`.
|
||||
child_request: Option<Value>,
|
||||
ignore_configuration_done: bool,
|
||||
source_path: Option<String>,
|
||||
/// Fail each `stackTrace` request whose frames include this one (java-debug, one frame's source lookup throwing).
|
||||
failing_frame: Option<u64>,
|
||||
/// Report this process id in the adapter's `process` event (the program being debugged).
|
||||
debuggee_pid: Option<u32>,
|
||||
/// java-debug's spelling of the same event.
|
||||
@@ -201,8 +205,10 @@ impl Default for Script {
|
||||
Self {
|
||||
run_in_terminal: None,
|
||||
start_debugging: false,
|
||||
child_request: None,
|
||||
ignore_configuration_done: false,
|
||||
source_path: None,
|
||||
failing_frame: None,
|
||||
debuggee_pid: None,
|
||||
java_process_id: false,
|
||||
output_after_terminate: false,
|
||||
@@ -365,10 +371,11 @@ async fn fake_adapter<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(stream
|
||||
);
|
||||
}
|
||||
if script.start_debugging && msg["arguments"]["isChild"] != true {
|
||||
send!(
|
||||
let arguments = script.child_request.clone().unwrap_or_else(
|
||||
// Like js-debug, the child's configuration repeats the launch's `type`.
|
||||
json!({"type": "request", "command": "startDebugging", "arguments": {"request": "launch", "configuration": {"name": "child", "isChild": true, "type": msg["arguments"]["type"]}}})
|
||||
|| json!({"request": "launch", "configuration": {"name": "child", "isChild": true, "type": msg["arguments"]["type"]}}),
|
||||
);
|
||||
send!(json!({"type": "request", "command": "startDebugging", "arguments": arguments}));
|
||||
}
|
||||
if script.pending_startup != Some(false) {
|
||||
tokio::time::sleep(script.initialized_delay).await;
|
||||
@@ -516,6 +523,20 @@ async fn fake_adapter<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(stream
|
||||
ok!(msg, json!({"threads": [{"id": 1, "name": "MainThread"}]}));
|
||||
}
|
||||
}
|
||||
"stackTrace" if let Some(bad) = script.failing_frame => {
|
||||
let start = msg["arguments"]["startFrame"].as_u64().unwrap();
|
||||
let end = (start + msg["arguments"]["levels"].as_u64().unwrap()).min(3);
|
||||
if (start..end).contains(&bad) {
|
||||
send!(
|
||||
json!({"type": "response", "request_seq": msg["seq"], "command": "stackTrace", "success": false, "message": "Illegal char <<> at index 21: C:\\p\\com\\x\\<generated>"})
|
||||
);
|
||||
} else {
|
||||
let frames: Vec<Value> = (start..end)
|
||||
.map(|i| json!({"id": 10 + i, "name": format!("f{i}"), "line": 1, "column": 1}))
|
||||
.collect();
|
||||
ok!(msg, json!({"stackFrames": frames, "totalFrames": 3}));
|
||||
}
|
||||
}
|
||||
"stackTrace" => ok!(
|
||||
msg,
|
||||
json!({"stackFrames": [
|
||||
@@ -895,7 +916,7 @@ async fn full_protocol_flow() {
|
||||
let path = PathBuf::from("/p/a.py");
|
||||
let disabled = Breakpoint { enabled: false, ..bp(2) };
|
||||
let cond = Breakpoint { condition: Some("x > 1".into()), ..bp(7) };
|
||||
let states = h.manager.set_breakpoints(path.clone(), vec![bp(4), disabled, cond]).await.unwrap();
|
||||
let states = h.manager.set_breakpoints(&h.owner.key, path.clone(), vec![bp(4), disabled, cond]).await.unwrap();
|
||||
assert!(states.iter().all(|s| !s.verified), "no session yet");
|
||||
|
||||
let id = h.start(config()).await.unwrap();
|
||||
@@ -977,7 +998,7 @@ async fn full_protocol_flow() {
|
||||
assert_eq!(asked["arguments"]["frameId"], 10);
|
||||
|
||||
// Live breakpoint updates reach the session.
|
||||
let states = h.manager.set_breakpoints(path.clone(), vec![bp(0)]).await.unwrap();
|
||||
let states = h.manager.set_breakpoints(&h.owner.key, path.clone(), vec![bp(0)]).await.unwrap();
|
||||
assert!(states[0].verified);
|
||||
|
||||
h.manager.resume(id, 1).await.unwrap();
|
||||
@@ -1001,7 +1022,7 @@ async fn full_protocol_flow() {
|
||||
async fn run_to_cursor_uses_temporary_breakpoint() {
|
||||
let h = harness(Script::default());
|
||||
let path = PathBuf::from("/p/a.py");
|
||||
h.manager.set_breakpoints(path.clone(), vec![bp(1)]).await.unwrap();
|
||||
h.manager.set_breakpoints(&h.owner.key, path.clone(), vec![bp(1)]).await.unwrap();
|
||||
let id = h.start(config()).await.unwrap();
|
||||
h.wait_event(|e| matches!(e, DebugEvent::Stopped { .. })).await;
|
||||
h.manager.run_to(id, 1, path.clone(), 9, false).await.unwrap();
|
||||
@@ -1033,7 +1054,7 @@ async fn stop_terminates_and_disconnects() {
|
||||
#[tokio::test]
|
||||
async fn unity_attach_waits_for_mono_and_disconnects_without_terminating_editor() {
|
||||
let h = harness(Script { empty_thread_responses: 2, ..Script::default() });
|
||||
h.manager.set_breakpoints(PathBuf::from("/p/a.cs"), vec![bp(4)]).await.unwrap();
|
||||
h.manager.set_breakpoints(&h.owner.key, PathBuf::from("/p/a.cs"), vec![bp(4)]).await.unwrap();
|
||||
let start = h.start(LaunchConfig {
|
||||
adapter: "unity".into(),
|
||||
request: "attach".into(),
|
||||
@@ -1193,6 +1214,46 @@ async fn child_of(h: &Harness, parent: DebugSessionId) -> DebugSessionId {
|
||||
panic!("no child session of {parent:?}");
|
||||
}
|
||||
|
||||
/// debugpy's subprocess (`subProcess: true`): an `attach` whose `connect` is the running adapter's
|
||||
/// client listener, so the child session connects there instead of starting another adapter.
|
||||
#[tokio::test]
|
||||
async fn a_debugpy_subprocess_connects_to_the_running_adapter() {
|
||||
/// Each launch's reused port and remote host.
|
||||
type Launches = Arc<Mutex<Vec<(Option<u16>, Option<String>)>>>;
|
||||
struct CaptureLauncher {
|
||||
inner: FakeLauncher,
|
||||
launches: Launches,
|
||||
}
|
||||
impl AdapterLauncher for CaptureLauncher {
|
||||
fn launch(&self, spec: AdapterSpec, reuse: Option<u16>) -> LaunchFuture {
|
||||
self.launches.lock().push((reuse, spec.server_host.clone()));
|
||||
self.inner.launch(spec, reuse)
|
||||
}
|
||||
}
|
||||
let child = |host: &str| {
|
||||
json!({"request": "attach", "configuration": {"name": "Subprocess 42", "isChild": true, "subProcessId": 42,
|
||||
"connect": {"host": host, "port": 51234}}})
|
||||
};
|
||||
for (host, server_host) in [("127.0.0.1", None), ("10.0.0.5", Some("10.0.0.5".to_owned()))] {
|
||||
let launches: Launches = Arc::default();
|
||||
let script = Script { start_debugging: true, child_request: Some(child(host)), ..Script::default() };
|
||||
let launcher =
|
||||
CaptureLauncher { inner: FakeLauncher { log: Arc::default(), script }, launches: launches.clone() };
|
||||
let manager =
|
||||
DebugManager::with_launcher(Arc::new(LanguageRegistry::from_configs(Vec::new())), Arc::new(launcher));
|
||||
let (owner, _) = recording_owner("main");
|
||||
let parent = manager.start(config(), owner).await.unwrap();
|
||||
for _ in 0..200 {
|
||||
if launches.lock().len() == 2 {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
assert_eq!(*launches.lock(), [(None, None), (Some(51234), server_host)], "{host}");
|
||||
manager.stop(parent).await.unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_browser_page_session_has_the_page_capability() {
|
||||
let h = harness(Script { start_debugging: true, ..Script::default() });
|
||||
@@ -1845,7 +1906,7 @@ fn function_bp(name: &str, enabled: bool) -> FunctionBreakpoint {
|
||||
async fn function_and_data_breakpoints_are_stored_and_sent() {
|
||||
let h = harness(Script::default());
|
||||
let cond = FunctionBreakpoint { condition: Some("n > 1".into()), ..function_bp("com.a.B#run", true) };
|
||||
let states = h.manager.set_function_breakpoints(vec![cond, function_bp("off", false)]).await.unwrap();
|
||||
let states = h.manager.set_function_breakpoints(&h.owner.key, vec![cond, function_bp("off", false)]).await.unwrap();
|
||||
assert!(!states[0].verified && states[1].message.as_deref() == Some("Disabled"), "no session yet");
|
||||
let watch = DataBreakpoint {
|
||||
data_id: "Req#count".into(),
|
||||
@@ -1854,7 +1915,7 @@ async fn function_and_data_breakpoints_are_stored_and_sent() {
|
||||
hit_condition: Some("2".into()),
|
||||
enabled: true,
|
||||
};
|
||||
h.manager.set_data_breakpoints(vec![watch]).await.unwrap();
|
||||
h.manager.set_data_breakpoints(&h.owner.key, vec![watch]).await.unwrap();
|
||||
|
||||
let id = h.start(config()).await.unwrap();
|
||||
assert_eq!(
|
||||
@@ -1870,8 +1931,11 @@ async fn function_and_data_breakpoints_are_stored_and_sent() {
|
||||
let pos = |c: &str| order.iter().position(|x| x == c).unwrap();
|
||||
assert!(pos("setFunctionBreakpoints") < pos("configurationDone"));
|
||||
|
||||
let states =
|
||||
h.manager.set_function_breakpoints(vec![function_bp("missing", true), function_bp("ok", true)]).await.unwrap();
|
||||
let states = h
|
||||
.manager
|
||||
.set_function_breakpoints(&h.owner.key, vec![function_bp("missing", true), function_bp("ok", true)])
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!((states[0].verified, states[1].verified), (false, true), "live states from the session");
|
||||
|
||||
let info = h.manager.data_breakpoint_info(id, 101, "count".into(), Some(10)).await.unwrap();
|
||||
@@ -1914,10 +1978,13 @@ async fn force_stepping_suspends_breakpoints_until_the_next_stop() {
|
||||
let h = harness(Script::default());
|
||||
let a = PathBuf::from("/p/a.py");
|
||||
let b = PathBuf::from("/p/b.py");
|
||||
h.manager.set_breakpoints(a.clone(), vec![bp(1)]).await.unwrap();
|
||||
h.manager.set_breakpoints(b.clone(), vec![bp(3)]).await.unwrap();
|
||||
h.manager.set_breakpoints(PathBuf::from("/p/off.py"), vec![Breakpoint { enabled: false, ..bp(5) }]).await.unwrap();
|
||||
h.manager.set_function_breakpoints(vec![function_bp("run", true)]).await.unwrap();
|
||||
h.manager.set_breakpoints(&h.owner.key, a.clone(), vec![bp(1)]).await.unwrap();
|
||||
h.manager.set_breakpoints(&h.owner.key, b.clone(), vec![bp(3)]).await.unwrap();
|
||||
h.manager
|
||||
.set_breakpoints(&h.owner.key, PathBuf::from("/p/off.py"), vec![Breakpoint { enabled: false, ..bp(5) }])
|
||||
.await
|
||||
.unwrap();
|
||||
h.manager.set_function_breakpoints(&h.owner.key, vec![function_bp("run", true)]).await.unwrap();
|
||||
let id = h.start(config()).await.unwrap();
|
||||
h.wait_event(|e| matches!(e, DebugEvent::Stopped { .. })).await;
|
||||
let sent_for = |path: &str| -> Vec<Value> {
|
||||
@@ -1951,10 +2018,10 @@ async fn force_stepping_suspends_breakpoints_until_the_next_stop() {
|
||||
#[tokio::test]
|
||||
async fn startup_sends_every_file_at_once_and_skips_files_with_nothing_enabled() {
|
||||
let h = harness(Script { hold_set_breakpoints: 2, ..Script::default() });
|
||||
h.manager.set_breakpoints(PathBuf::from("/p/a.py"), vec![bp(1)]).await.unwrap();
|
||||
h.manager.set_breakpoints(PathBuf::from("/p/b.py"), vec![bp(3)]).await.unwrap();
|
||||
h.manager.set_breakpoints(&h.owner.key, PathBuf::from("/p/a.py"), vec![bp(1)]).await.unwrap();
|
||||
h.manager.set_breakpoints(&h.owner.key, PathBuf::from("/p/b.py"), vec![bp(3)]).await.unwrap();
|
||||
let off = PathBuf::from("/p/off.py");
|
||||
h.manager.set_breakpoints(off.clone(), vec![Breakpoint { enabled: false, ..bp(5) }]).await.unwrap();
|
||||
h.manager.set_breakpoints(&h.owner.key, off.clone(), vec![Breakpoint { enabled: false, ..bp(5) }]).await.unwrap();
|
||||
// Waiting for each answer before the next request would stall until the request timeout.
|
||||
tokio::time::timeout(Duration::from_secs(5), h.start(config())).await.expect("requests pipelined").unwrap();
|
||||
let paths: Vec<Value> = requests(&h, "setBreakpoints").into_iter().map(|r| r["source"]["path"].clone()).collect();
|
||||
@@ -1965,6 +2032,40 @@ async fn startup_sends_every_file_at_once_and_skips_files_with_nothing_enabled()
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn sessions_get_only_their_windows_breakpoints_and_a_replaced_list_drops_stale_files() {
|
||||
let h = harness(Script::default());
|
||||
let other = "project-2";
|
||||
h.manager.set_breakpoints(other, PathBuf::from("/p/other.py"), vec![bp(1)]).await.unwrap();
|
||||
h.manager.set_function_breakpoints(other, vec![function_bp("elsewhere", true)]).await.unwrap();
|
||||
let stale = PathBuf::from("/p/stale.py");
|
||||
h.manager.set_breakpoints(&h.owner.key, stale.clone(), vec![bp(2)]).await.unwrap();
|
||||
let id = h.start(config()).await.unwrap();
|
||||
let paths = || -> Vec<(Value, Value)> {
|
||||
requests(&h, "setBreakpoints")
|
||||
.into_iter()
|
||||
.map(|r| (r["source"]["path"].clone(), r["breakpoints"].clone()))
|
||||
.collect()
|
||||
};
|
||||
assert_eq!(paths(), [(json!("/p/stale.py"), json!([{"line": 3}]))], "another window's file is not sent");
|
||||
assert!(requests(&h, "setFunctionBreakpoints").is_empty(), "nor its method breakpoints");
|
||||
|
||||
// The window's list no longer has the stale file (#6116): replacing clears it in the session...
|
||||
let kept = PathBuf::from("/p/kept.py");
|
||||
h.manager.replace_breakpoints(&h.owner.key, BTreeMap::from([(kept.clone(), vec![bp(4)])])).await.unwrap();
|
||||
assert_eq!(paths()[1..], [(json!("/p/stale.py"), json!([])), (json!("/p/kept.py"), json!([{"line": 5}]))]);
|
||||
// ...unchanged files are not sent again...
|
||||
h.manager.replace_breakpoints(&h.owner.key, BTreeMap::from([(kept.clone(), vec![bp(4)])])).await.unwrap();
|
||||
assert_eq!(paths().len(), 3);
|
||||
h.manager.stop(id).await.unwrap();
|
||||
// ...and the next session gets only what the window lists.
|
||||
let h2 = harness(Script::default());
|
||||
h2.manager.set_breakpoints(&h2.owner.key, stale.clone(), vec![bp(2)]).await.unwrap();
|
||||
h2.manager.replace_breakpoints(&h2.owner.key, BTreeMap::new()).await.unwrap();
|
||||
h2.start(config()).await.unwrap();
|
||||
assert!(requests(&h2, "setBreakpoints").is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn hot_reload_sends_its_reason_and_reports_the_flutter_app() {
|
||||
let h = harness(Script::default());
|
||||
@@ -2165,7 +2266,7 @@ async fn godot_gets_resolved_paths() {
|
||||
Arc::new(FakeLauncher { log: log.clone(), script: Script::default() }),
|
||||
);
|
||||
let bp = Breakpoint { line: 0, condition: None, hit_condition: None, log_message: None, enabled: true };
|
||||
manager.set_breakpoints(link.join("player.gd"), vec![bp]).await.unwrap();
|
||||
manager.set_breakpoints("main", link.join("player.gd"), vec![bp]).await.unwrap();
|
||||
let id = manager.start(godot_launch(&link), owner).await.unwrap();
|
||||
let sent = log.lock().iter().find(|m| m["command"] == "setBreakpoints").cloned().unwrap();
|
||||
assert_eq!(sent["arguments"]["source"]["path"], json!(real.join("player.gd")));
|
||||
@@ -2192,7 +2293,7 @@ async fn kotlin_configures_without_configuration_done_response() {
|
||||
let project = tempfile::tempdir().unwrap();
|
||||
let path = project.path().join("Main.kt");
|
||||
std::fs::write(&path, "package org.example\nfun main() {}\n").unwrap();
|
||||
h.manager.set_breakpoints(path.clone(), vec![bp(1)]).await.unwrap();
|
||||
h.manager.set_breakpoints(&h.owner.key, path.clone(), vec![bp(1)]).await.unwrap();
|
||||
let mut config = config();
|
||||
config.adapter = kotlin::ADAPTER.into();
|
||||
config.request = "attach".into();
|
||||
@@ -2226,7 +2327,7 @@ async fn kotlin_official_release_ten_no_delay_runs() {
|
||||
let (owner, events) = recording_owner("kotlin-probe");
|
||||
let manager = DebugManager::new(Arc::new(LanguageRegistry::from_configs(Vec::new())));
|
||||
let h = Harness { manager, owner, events, log: Arc::default() };
|
||||
h.manager.set_breakpoints(source.clone(), vec![bp(5)]).await.unwrap();
|
||||
h.manager.set_breakpoints(&h.owner.key, source.clone(), vec![bp(5)]).await.unwrap();
|
||||
let id = h.manager.start_with(config.clone(), h.owner.clone(), |_| Some(adapter.clone())).await.unwrap();
|
||||
let stopped = h.wait_event(|e| matches!(e, DebugEvent::Stopped { reason, .. } if reason == "breakpoint")).await;
|
||||
let DebugEvent::Stopped { thread_id, .. } = stopped else { unreachable!() };
|
||||
@@ -2248,6 +2349,21 @@ async fn kotlin_official_release_ten_no_delay_runs() {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn stack_trace_leaves_out_a_frame_the_adapter_cannot_describe() {
|
||||
let h = harness(Script { failing_frame: Some(1), ..Script::default() });
|
||||
let id = h.start(config()).await.unwrap();
|
||||
let frames = h.manager.stack_trace(id, 1).await.unwrap();
|
||||
assert_eq!(frames.iter().map(|f| f.name.as_str()).collect::<Vec<_>>(), ["f0", "f2"]);
|
||||
h.manager.stop(id).await.unwrap();
|
||||
|
||||
let h = harness(Script { failing_frame: Some(0), ..Script::default() });
|
||||
let id = h.start(config()).await.unwrap();
|
||||
let error = h.manager.stack_trace(id, 1).await.unwrap_err();
|
||||
assert!(error.message.contains("<generated>"), "{error:?}");
|
||||
h.manager.stop(id).await.unwrap();
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[tokio::test]
|
||||
async fn netcoredbg_windows_source_paths_round_trip() {
|
||||
@@ -2255,7 +2371,7 @@ async fn netcoredbg_windows_source_paths_round_trip() {
|
||||
let native = r"D:\work\LoginController.cs";
|
||||
let h = harness(Script { source_path: Some(native.into()), ..Script::default() });
|
||||
let path = PathBuf::from(client);
|
||||
h.manager.set_breakpoints(path.clone(), vec![bp(25)]).await.unwrap();
|
||||
h.manager.set_breakpoints(&h.owner.key, path.clone(), vec![bp(25)]).await.unwrap();
|
||||
let mut cfg = config();
|
||||
cfg.adapter = "netcoredbg".into();
|
||||
let id = h.start(cfg).await.unwrap();
|
||||
@@ -2279,7 +2395,7 @@ async fn java_windows_source_paths_for_launch_and_attach() {
|
||||
] {
|
||||
let h = harness(Script { source_path: Some(returned.into()), ..Script::default() });
|
||||
let path = PathBuf::from(client);
|
||||
h.manager.set_breakpoints(path.clone(), vec![bp(4)]).await.unwrap();
|
||||
h.manager.set_breakpoints(&h.owner.key, path.clone(), vec![bp(4)]).await.unwrap();
|
||||
let mut cfg = config();
|
||||
cfg.adapter = "java-debug".into();
|
||||
cfg.request = request.into();
|
||||
@@ -3374,7 +3490,7 @@ async fn kotlin_lsp_gets_real_paths_and_its_link_holds_nothing() {
|
||||
let project = tempfile::tempdir().unwrap();
|
||||
let path = project.path().join("Main.kt");
|
||||
std::fs::write(&path, "package org.example\nfun main() {}\n").unwrap();
|
||||
h.manager.set_breakpoints(path.clone(), vec![bp(1)]).await.unwrap();
|
||||
h.manager.set_breakpoints(&h.owner.key, path.clone(), vec![bp(1)]).await.unwrap();
|
||||
let id = h.start(kotlin_lsp_attach(project.path())).await.unwrap();
|
||||
assert_eq!(h.request("setBreakpoints")["arguments"]["source"]["path"], json!(path));
|
||||
let sent = &h.request("attach")["arguments"];
|
||||
|
||||
@@ -47,7 +47,7 @@ async fn debugpy_end_to_end() {
|
||||
let sink: SharedSink = Arc::new(move |e: IdeEvent| sink_events.lock().push(e));
|
||||
let manager = DebugManager::new(Arc::new(LanguageRegistry::from_configs(Vec::new())));
|
||||
let bp = Breakpoint { line: 3, condition: None, hit_condition: None, log_message: None, enabled: true };
|
||||
manager.set_breakpoints(script.clone(), vec![bp]).await.unwrap();
|
||||
manager.set_breakpoints("main", script.clone(), vec![bp]).await.unwrap();
|
||||
let id = manager
|
||||
.start(
|
||||
LaunchConfig {
|
||||
@@ -74,7 +74,7 @@ async fn debugpy_end_to_end() {
|
||||
assert!(vars.iter().any(|v| v.name == "total"), "{vars:?}");
|
||||
let v = manager.evaluate(id, Some(frames[0].id), "total + 100".into()).await.unwrap();
|
||||
assert_eq!(v.value, "100");
|
||||
manager.set_breakpoints(script.clone(), vec![]).await.unwrap();
|
||||
manager.set_breakpoints("main", script.clone(), vec![]).await.unwrap();
|
||||
manager.resume(id, thread_id).await.unwrap();
|
||||
wait(&events, |e| matches!(e, DebugEvent::Output { output, .. } if output.contains("total 3"))).await;
|
||||
wait(&events, |e| matches!(e, DebugEvent::Terminated)).await;
|
||||
|
||||
@@ -96,6 +96,7 @@ async fn breakpoints_stepping_and_variables_in_a_real_godot() {
|
||||
let script_as_opened = dir.join("player.gd");
|
||||
manager
|
||||
.set_breakpoints(
|
||||
"main",
|
||||
script_as_opened.clone(),
|
||||
vec![Breakpoint {
|
||||
line: BREAK_LINE,
|
||||
|
||||
@@ -81,6 +81,7 @@ async fn listens_for_xdebug_until_stopped_with_path_mappings() {
|
||||
let local_script = local.join("index.php");
|
||||
manager
|
||||
.set_breakpoints(
|
||||
"main",
|
||||
local_script.clone(),
|
||||
vec![Breakpoint {
|
||||
line: BREAK_LINE,
|
||||
|
||||
@@ -261,7 +261,7 @@ async fn scenario(case: &Case) -> Result<Vec<String>, String> {
|
||||
let m = &run.manager;
|
||||
let line_bp =
|
||||
Breakpoint { line: case.loop_line, condition: None, hit_condition: None, log_message: None, enabled: true };
|
||||
m.set_breakpoints(case.source.clone(), vec![line_bp]).await.map_err(|e| e.message)?;
|
||||
m.set_breakpoints("test", case.source.clone(), vec![line_bp]).await.map_err(|e| e.message)?;
|
||||
|
||||
let seen = run.seen();
|
||||
let id = m.start(case.config.clone(), run.owner.clone()).await.map_err(|e| format!("start: {}", e.message))?;
|
||||
@@ -356,9 +356,9 @@ async fn scenario(case: &Case) -> Result<Vec<String>, String> {
|
||||
// Method breakpoint: continue → stops in `parse`.
|
||||
if caps.function_breakpoints {
|
||||
let fb = FunctionBreakpoint { name: case.function.into(), condition: None, hit_condition: None, enabled: true };
|
||||
let states = m.set_function_breakpoints(vec![fb]).await.map_err(|e| e.message)?;
|
||||
let states = m.set_function_breakpoints("test", vec![fb]).await.map_err(|e| e.message)?;
|
||||
report.push(format!("method breakpoint `{}`: verified={}", case.function, states[0].verified));
|
||||
m.set_breakpoints(case.source.clone(), vec![]).await.map_err(|e| e.message)?;
|
||||
m.set_breakpoints("test", case.source.clone(), vec![]).await.map_err(|e| e.message)?;
|
||||
let seen = run.seen();
|
||||
m.resume(s, thread).await.map_err(|e| e.message)?;
|
||||
match run.stopped_after(seen).await {
|
||||
@@ -368,8 +368,10 @@ async fn scenario(case: &Case) -> Result<Vec<String>, String> {
|
||||
}
|
||||
None => report.push("method breakpoint: NOT HIT".into()),
|
||||
}
|
||||
m.set_function_breakpoints(vec![]).await.map_err(|e| e.message)?;
|
||||
m.set_breakpoints(case.source.clone(), vec![line_bp_at(case.loop_line)]).await.map_err(|e| e.message)?;
|
||||
m.set_function_breakpoints("test", vec![]).await.map_err(|e| e.message)?;
|
||||
m.set_breakpoints("test", case.source.clone(), vec![line_bp_at(case.loop_line)])
|
||||
.await
|
||||
.map_err(|e| e.message)?;
|
||||
let seen = run.seen();
|
||||
m.step(s, thread, StepKind::Out).await.map_err(|e| e.message)?;
|
||||
run.stopped_after(seen).await.ok_or("no stop after step out of parse")?;
|
||||
@@ -378,7 +380,7 @@ async fn scenario(case: &Case) -> Result<Vec<String>, String> {
|
||||
}
|
||||
|
||||
// Force Step Over ignores the breakpoint inside parse.
|
||||
m.set_breakpoints(case.source.clone(), vec![line_bp_at(case.loop_line)]).await.map_err(|e| e.message)?;
|
||||
m.set_breakpoints("test", case.source.clone(), vec![line_bp_at(case.loop_line)]).await.map_err(|e| e.message)?;
|
||||
let seen = run.seen();
|
||||
m.force_step_over(s, thread).await.map_err(|e| e.message)?;
|
||||
let (_, t, reason) = run.stopped_after(seen).await.ok_or("no stop after force step over")?;
|
||||
@@ -409,8 +411,8 @@ async fn scenario(case: &Case) -> Result<Vec<String>, String> {
|
||||
hit_condition: None,
|
||||
enabled: true,
|
||||
};
|
||||
let states = m.set_data_breakpoints(vec![wp]).await.map_err(|e| e.message)?;
|
||||
m.set_breakpoints(case.source.clone(), vec![]).await.map_err(|e| e.message)?;
|
||||
let states = m.set_data_breakpoints("test", vec![wp]).await.map_err(|e| e.message)?;
|
||||
m.set_breakpoints("test", case.source.clone(), vec![]).await.map_err(|e| e.message)?;
|
||||
let seen = run.seen();
|
||||
m.resume(s, thread).await.map_err(|e| e.message)?;
|
||||
match run.stopped_after(seen).await {
|
||||
@@ -425,8 +427,8 @@ async fn scenario(case: &Case) -> Result<Vec<String>, String> {
|
||||
}
|
||||
None => report.push(format!("watchpoint `{data_id}`: NOT HIT")),
|
||||
}
|
||||
m.set_data_breakpoints(vec![]).await.map_err(|e| e.message)?;
|
||||
m.set_breakpoints(case.source.clone(), vec![line_bp_at(case.loop_line)])
|
||||
m.set_data_breakpoints("test", vec![]).await.map_err(|e| e.message)?;
|
||||
m.set_breakpoints("test", case.source.clone(), vec![line_bp_at(case.loop_line)])
|
||||
.await
|
||||
.map_err(|e| e.message)?;
|
||||
}
|
||||
@@ -623,7 +625,7 @@ async fn attach_to_processes() {
|
||||
};
|
||||
let run = Run::new();
|
||||
run.manager
|
||||
.set_breakpoints(case.source.clone(), vec![line_bp_at(case.line)])
|
||||
.set_breakpoints("test", case.source.clone(), vec![line_bp_at(case.line)])
|
||||
.await
|
||||
.map_err(|e| e.message)?;
|
||||
let id =
|
||||
|
||||
@@ -253,7 +253,7 @@ async fn scenario(case: &Case) -> Result<Vec<String>, String> {
|
||||
let mut report = Vec::new();
|
||||
let run = Run::new();
|
||||
let m = &run.manager;
|
||||
m.set_breakpoints(case.source.clone(), vec![bp(LOOP_LINE)]).await.map_err(|e| e.message)?;
|
||||
m.set_breakpoints("test", case.source.clone(), vec![bp(LOOP_LINE)]).await.map_err(|e| e.message)?;
|
||||
let id = m.start(case.config.clone(), run.owner.clone()).await.map_err(|e| format!("start: {}", e.message))?;
|
||||
|
||||
let (s, thread) = run.stopped(0, "the loop breakpoint").await?;
|
||||
@@ -312,7 +312,7 @@ async fn scenario(case: &Case) -> Result<Vec<String>, String> {
|
||||
expect_line(&run.top(s2, t2).await?, LOOP_LINE, "continue")?;
|
||||
|
||||
// Without breakpoints, the program runs to its end.
|
||||
m.set_breakpoints(case.source.clone(), vec![]).await.map_err(|e| e.message)?;
|
||||
m.set_breakpoints("test", case.source.clone(), vec![]).await.map_err(|e| e.message)?;
|
||||
let seen = run.seen();
|
||||
m.resume(s2, t2).await.map_err(|e| e.message)?;
|
||||
run.wait(seen, "terminated", |s, e| (s == id && matches!(e, DebugEvent::Terminated)).then_some(())).await?;
|
||||
@@ -333,7 +333,7 @@ async fn scenario(case: &Case) -> Result<Vec<String>, String> {
|
||||
report.push("continue to exit: output and terminated".into());
|
||||
|
||||
// Restart (the UI starts the same configuration again), then Stop while paused.
|
||||
m.set_breakpoints(case.source.clone(), vec![bp(LOOP_LINE)]).await.map_err(|e| e.message)?;
|
||||
m.set_breakpoints("test", case.source.clone(), vec![bp(LOOP_LINE)]).await.map_err(|e| e.message)?;
|
||||
let seen = run.seen();
|
||||
let again = m.start(case.config.clone(), run.owner.clone()).await.map_err(|e| format!("restart: {}", e.message))?;
|
||||
let (s, thread) = run.stopped(seen, "the breakpoint after restart").await?;
|
||||
|
||||
@@ -110,6 +110,7 @@ async fn real_editor_attach_breakpoint_step_variables_and_detach() {
|
||||
let line = SCRIPT.lines().position(|l| l.contains("int answer =")).unwrap() as u32;
|
||||
manager
|
||||
.set_breakpoints(
|
||||
"smoke",
|
||||
source.clone(),
|
||||
vec![Breakpoint { line, condition: None, hit_condition: None, log_message: None, enabled: true }],
|
||||
)
|
||||
|
||||
@@ -135,7 +135,7 @@ impl Context {
|
||||
}
|
||||
|
||||
macro_rules! sqlx_pool {
|
||||
($manager:ident, $handle:ident, $options:ty, $connection:ty, $driver:expr, $query:expr $(, $after_init:ident)?) => {
|
||||
($manager:ident, $handle:ident, $options:ty, $connection:ty, $initialize:ident, $unfinished:expr) => {
|
||||
pub struct $manager {
|
||||
options: $options,
|
||||
init: Arc<Vec<String>>,
|
||||
@@ -164,41 +164,28 @@ macro_rules! sqlx_pool {
|
||||
}
|
||||
}
|
||||
|
||||
impl $manager {
|
||||
async fn initialize(&self, mut conn: $connection) -> Result<$handle, sqlx::Error> {
|
||||
let context = Context::new($initialize(&self.options, &mut conn, &self.init).await?);
|
||||
Ok($handle {
|
||||
conn: Some(conn),
|
||||
context,
|
||||
options: self.options.clone(),
|
||||
init: self.init.clone(),
|
||||
timeout: self.timeout,
|
||||
in_transaction: false,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl ManageConnection for $manager {
|
||||
type Connection = $handle;
|
||||
type Error = sqlx::Error;
|
||||
|
||||
async fn connect(&self) -> Result<Self::Connection, Self::Error> {
|
||||
tokio::time::timeout(self.timeout, async {
|
||||
let mut conn = self.options.connect().await?;
|
||||
let context_sql = |value: Option<String>| {
|
||||
value.map(|v| {
|
||||
if $driver == DbDriver::Postgres {
|
||||
format!("SET search_path TO {v}")
|
||||
} else {
|
||||
crate::sql::use_schema($driver, &v).expect("switchable driver")
|
||||
}
|
||||
})
|
||||
};
|
||||
for sql in self.init.iter() {
|
||||
sqlx::raw_sql(sqlx::AssertSqlSafe(sql.clone())).execute(&mut conn).await?;
|
||||
}
|
||||
$(if !self.init.is_empty() {
|
||||
self.options.$after_init(&mut conn).await?;
|
||||
})?
|
||||
let row = sqlx::raw_sql(sqlx::AssertSqlSafe($query.to_owned())).fetch_one(&mut conn).await?;
|
||||
let context = Context::new(context_sql(row.try_get(0)?));
|
||||
Ok($handle {
|
||||
conn: Some(conn),
|
||||
context,
|
||||
options: self.options.clone(),
|
||||
init: self.init.clone(),
|
||||
timeout: self.timeout,
|
||||
in_transaction: false,
|
||||
})
|
||||
})
|
||||
.await
|
||||
.map_err(|_| sqlx::Error::PoolTimedOut)?
|
||||
tokio::time::timeout(self.timeout, async { self.initialize(self.options.connect().await?).await })
|
||||
.await
|
||||
.map_err(|_| sqlx::Error::PoolTimedOut)?
|
||||
}
|
||||
|
||||
async fn is_valid(&self, conn: &mut Self::Connection) -> Result<(), Self::Error> {
|
||||
@@ -206,16 +193,24 @@ macro_rules! sqlx_pool {
|
||||
}
|
||||
|
||||
fn has_broken(&self, conn: &mut Self::Connection) -> bool {
|
||||
conn.conn.is_none()
|
||||
conn.conn.is_none() || ($unfinished)(conn)
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum PgReadOnly {
|
||||
Off,
|
||||
Session,
|
||||
Transaction,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct PostgresOptions {
|
||||
connection: PgConnectOptions,
|
||||
read_only: bool,
|
||||
read_only: PgReadOnly,
|
||||
local_settings: Arc<[String]>,
|
||||
}
|
||||
|
||||
const PG_READ_ONLY_HINT: &str = "Read-only requires the pooler to track default_transaction_read_only for each client. \
|
||||
@@ -230,7 +225,7 @@ impl PostgresOptions {
|
||||
}
|
||||
|
||||
async fn verify_read_only(&self, conn: &mut PgConnection) -> Result<(), sqlx::Error> {
|
||||
if self.read_only && !pg_setting_on(conn, "SHOW default_transaction_read_only").await? {
|
||||
if self.read_only == PgReadOnly::Session && !pg_setting_on(conn, "SHOW default_transaction_read_only").await? {
|
||||
return Err(sqlx::Error::Configuration(
|
||||
format!(
|
||||
"PostgreSQL did not enable the requested default_transaction_read_only setting. \
|
||||
@@ -244,7 +239,7 @@ impl PostgresOptions {
|
||||
|
||||
async fn verify_startup_script(&self, conn: &mut PgConnection) -> Result<(), sqlx::Error> {
|
||||
self.verify_read_only(conn).await?;
|
||||
if self.read_only && !pg_setting_on(conn, "SHOW transaction_read_only").await? {
|
||||
if self.read_only == PgReadOnly::Session && !pg_setting_on(conn, "SHOW transaction_read_only").await? {
|
||||
return Err(sqlx::Error::Configuration(
|
||||
"The startup script left a writable transaction open on a read-only PostgreSQL source.".into(),
|
||||
));
|
||||
@@ -285,19 +280,53 @@ fn postgres_connect_error(error: sqlx::Error, read_only: bool) -> IdeError {
|
||||
error
|
||||
}
|
||||
|
||||
sqlx_pool!(
|
||||
PgManager,
|
||||
PgHandle,
|
||||
PostgresOptions,
|
||||
PgConnection,
|
||||
DbDriver::Postgres,
|
||||
"SHOW search_path",
|
||||
verify_startup_script
|
||||
);
|
||||
sqlx_pool!(MysqlManager, MysqlHandle, MySqlConnectOptions, MySqlConnection, DbDriver::Mysql, "SELECT DATABASE()");
|
||||
async fn initialize_postgres(
|
||||
options: &PostgresOptions,
|
||||
conn: &mut PgConnection,
|
||||
init: &[String],
|
||||
) -> Result<Option<String>, sqlx::Error> {
|
||||
let guarded = options.read_only == PgReadOnly::Transaction;
|
||||
if guarded {
|
||||
sqlx::raw_sql(pg_read_only::BEGIN).execute(&mut *conn).await?;
|
||||
}
|
||||
for sql in init {
|
||||
if guarded {
|
||||
pg_read_only::check_single(conn, sql).await?;
|
||||
}
|
||||
sqlx::raw_sql(sqlx::AssertSqlSafe(sql.clone())).execute(&mut *conn).await?;
|
||||
}
|
||||
if !guarded && !init.is_empty() {
|
||||
options.verify_startup_script(conn).await?;
|
||||
}
|
||||
let row = sqlx::raw_sql("SHOW search_path").fetch_one(&mut *conn).await?;
|
||||
let path: Option<String> = row.try_get(0)?;
|
||||
if guarded {
|
||||
sqlx::raw_sql("COMMIT").execute(conn).await?;
|
||||
return Ok(path);
|
||||
}
|
||||
Ok(path.map(|v| format!("SET search_path TO {v}")))
|
||||
}
|
||||
|
||||
async fn initialize_mysql(
|
||||
_: &MySqlConnectOptions,
|
||||
conn: &mut MySqlConnection,
|
||||
init: &[String],
|
||||
) -> Result<Option<String>, sqlx::Error> {
|
||||
for sql in init {
|
||||
sqlx::raw_sql(sqlx::AssertSqlSafe(sql.clone())).execute(&mut *conn).await?;
|
||||
}
|
||||
let row = sqlx::raw_sql("SELECT DATABASE()").fetch_one(conn).await?;
|
||||
Ok(row.try_get::<Option<String>, _>(0)?.and_then(|v| crate::sql::use_schema(DbDriver::Mysql, &v)))
|
||||
}
|
||||
|
||||
sqlx_pool!(PgManager, PgHandle, PostgresOptions, PgConnection, initialize_postgres, |c: &PgHandle| c.options.read_only
|
||||
== PgReadOnly::Transaction
|
||||
&& c.in_transaction);
|
||||
sqlx_pool!(MysqlManager, MysqlHandle, MySqlConnectOptions, MySqlConnection, initialize_mysql, |_: &MysqlHandle| false);
|
||||
|
||||
pub struct ServerPool<M: ManageConnection> {
|
||||
inner: Bb8Pool<M>,
|
||||
transaction_read_only: bool,
|
||||
closed: AtomicBool,
|
||||
}
|
||||
|
||||
@@ -774,7 +803,9 @@ macro_rules! backend_id {
|
||||
}
|
||||
|
||||
mod cursor;
|
||||
mod pg_read_only;
|
||||
pub(crate) use cursor::{Cursors, Key as CursorKey};
|
||||
pub(crate) use pg_read_only::validate as validate_pg_read_only;
|
||||
|
||||
/// Whether the pages of `sql`'s result can be read by a cursor (see [`cursor`]): a query that
|
||||
/// leaves the session as it was.
|
||||
@@ -947,6 +978,10 @@ impl Setup {
|
||||
}
|
||||
|
||||
impl Pool {
|
||||
pub(crate) fn transaction_read_only(&self) -> bool {
|
||||
matches!(self, Pool::Postgres(p) if p.transaction_read_only)
|
||||
}
|
||||
|
||||
pub fn driver(&self) -> DbDriver {
|
||||
match self {
|
||||
Pool::Sqlite(_) => DbDriver::Sqlite,
|
||||
@@ -1058,27 +1093,68 @@ impl Pool {
|
||||
if let Some(p) = password {
|
||||
opts = opts.password(p);
|
||||
}
|
||||
if !setup.params.is_empty() {
|
||||
opts = opts.options(setup.params);
|
||||
}
|
||||
if let Some(n) = setup.statement_cache {
|
||||
opts = opts.statement_cache_capacity(n);
|
||||
}
|
||||
let options = PostgresOptions { connection: opts, read_only: source.read_only };
|
||||
let mut manager = PgManager { options, init: init.clone(), timeout };
|
||||
// Open once directly so authentication failures retain their database error.
|
||||
let first = match manager.connect().await {
|
||||
Err(e) if source.ssl == DbSslMode::Prefer && tls_failed(&e) => {
|
||||
tracing::info!("TLS handshake failed, connecting without TLS (SSL mode Prefer): {e}");
|
||||
manager.options.connection = manager.options.connection.clone().ssl_mode(PgSslMode::Disable);
|
||||
manager.connect().await
|
||||
}
|
||||
first => first,
|
||||
// Remove only the option supplied by the Read-only checkbox on a retry.
|
||||
let fallback = source.read_only.then(|| {
|
||||
let opts = opts.clone().statement_cache_capacity(0);
|
||||
if setup.params.len() == 1 { opts } else { opts.options(setup.params.iter().skip(1).cloned()) }
|
||||
});
|
||||
if !setup.params.is_empty() {
|
||||
opts = opts.options(setup.params);
|
||||
}
|
||||
.map_err(|e| postgres_connect_error(e, source.read_only))?;
|
||||
let mode = if source.read_only { PgReadOnly::Session } else { PgReadOnly::Off };
|
||||
let mut manager = PgManager {
|
||||
options: PostgresOptions { connection: opts, read_only: mode, local_settings: Arc::default() },
|
||||
init: init.clone(),
|
||||
timeout,
|
||||
};
|
||||
let mut fallback = fallback;
|
||||
let mut try_plain = source.ssl == DbSslMode::Prefer;
|
||||
let first = loop {
|
||||
let mut login_failed = false;
|
||||
let result = tokio::time::timeout(timeout, async {
|
||||
let mut conn =
|
||||
manager.options.connection.connect().await.inspect_err(|_| login_failed = true)?;
|
||||
manager.options.verify_read_only(&mut conn).await?;
|
||||
manager.initialize(conn).await
|
||||
})
|
||||
.await
|
||||
.unwrap_or(Err(sqlx::Error::PoolTimedOut));
|
||||
match result {
|
||||
Err(e) if login_failed && try_plain && tls_failed(&e) => {
|
||||
tracing::info!("TLS handshake failed, connecting without TLS (SSL mode Prefer): {e}");
|
||||
try_plain = false;
|
||||
manager.options.connection =
|
||||
manager.options.connection.clone().ssl_mode(PgSslMode::Disable);
|
||||
fallback = fallback.map(|opts| opts.ssl_mode(PgSslMode::Disable));
|
||||
}
|
||||
Err(e)
|
||||
if login_failed
|
||||
&& fallback.is_some()
|
||||
&& e.as_database_error().is_some_and(|db| {
|
||||
postgres_read_only_hint(true, db.code().as_deref(), db.message()).is_some()
|
||||
}) =>
|
||||
{
|
||||
manager.options.connection =
|
||||
fallback.take().expect("read-only startup option was supplied");
|
||||
manager.options.read_only = PgReadOnly::Transaction;
|
||||
try_plain = false;
|
||||
let (startup, settings) = pg_read_only::startup(&init).map_err(IdeError::invalid)?;
|
||||
manager.init = Arc::new(startup);
|
||||
manager.options.local_settings = settings.into();
|
||||
tracing::info!(
|
||||
"PostgreSQL endpoint rejected read-only startup; using read-only transactions"
|
||||
);
|
||||
}
|
||||
result => break result.map_err(|e| postgres_connect_error(e, source.read_only))?,
|
||||
}
|
||||
};
|
||||
let transaction_read_only = manager.options.read_only == PgReadOnly::Transaction;
|
||||
let pool = Bb8Pool::builder().max_size(MAX).connection_timeout(timeout).build_unchecked(manager);
|
||||
let _ = pool.add(first);
|
||||
Ok(Pool::Postgres(ServerPool { inner: pool, closed: AtomicBool::new(false) }))
|
||||
Ok(Pool::Postgres(ServerPool { inner: pool, transaction_read_only, closed: AtomicBool::new(false) }))
|
||||
}
|
||||
DbDriver::Mysql => {
|
||||
let mut opts = MySqlConnectOptions::new()
|
||||
@@ -1139,7 +1215,11 @@ impl Pool {
|
||||
let first = first.map_err(db_err)?;
|
||||
let pool = Bb8Pool::builder().max_size(MAX).connection_timeout(timeout).build_unchecked(manager);
|
||||
let _ = pool.add(first);
|
||||
Ok(Pool::Mysql(ServerPool { inner: pool, closed: AtomicBool::new(false) }))
|
||||
Ok(Pool::Mysql(ServerPool {
|
||||
inner: pool,
|
||||
transaction_read_only: false,
|
||||
closed: AtomicBool::new(false),
|
||||
}))
|
||||
}
|
||||
DbDriver::SqlServer => {
|
||||
use tiberius::Config;
|
||||
@@ -1204,6 +1284,29 @@ impl Pool {
|
||||
matches!(self, Pool::Sqlite(_) | Pool::Postgres(_) | Pool::Mysql(_))
|
||||
}
|
||||
|
||||
async fn cancel_query(&self, sql: String) {
|
||||
if let Pool::Postgres(p) = self
|
||||
&& p.transaction_read_only
|
||||
{
|
||||
// The target owns its backend until cancellation finishes; all regular pool slots may be busy.
|
||||
let control = async {
|
||||
let mut c = p.inner.dedicated_connection().await.map_err(db_err)?;
|
||||
c.start_read_only().await?;
|
||||
Ok::<_, IdeError>(c)
|
||||
};
|
||||
// Never queue a late cancel after giving up the backend whose PID it names.
|
||||
if let Ok(Ok(mut conn)) = tokio::time::timeout(Duration::from_secs(2), control).await {
|
||||
let _ = sqlx::raw_sql(sqlx::AssertSqlSafe(format!("{sql}; ROLLBACK"))).execute(&mut *conn).await;
|
||||
} else {
|
||||
tracing::debug!(
|
||||
"No PostgreSQL backend available to signal cancellation; discarding the client connection"
|
||||
);
|
||||
}
|
||||
} else {
|
||||
let _ = self.rows(&sql, 1).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs `sql` (no row limit beyond `max`), for introspection: cells are text (see [`Cells::Text`]).
|
||||
pub async fn rows(&self, sql: &str, max: usize) -> IdeResult<Vec<Vec<Option<String>>>> {
|
||||
if let Pool::Jdbc(p) = self {
|
||||
@@ -1217,8 +1320,13 @@ impl Pool {
|
||||
}
|
||||
let mut conn = Held::acquire(self).await?;
|
||||
conn.apply_context(None).await?;
|
||||
let fetched = conn.fetch_rows(sql, max).await;
|
||||
Ok(fetched?.1)
|
||||
let owned = conn.begin_read_only().await?;
|
||||
let result = async {
|
||||
conn.check_protected_statement(sql).await?;
|
||||
conn.fetch_rows(sql, max).await
|
||||
}
|
||||
.await;
|
||||
Ok(conn.finish_read_only(owned, result).await?.1)
|
||||
}
|
||||
|
||||
/// Runs one statement and keeps at most `max_rows` rows. Cancelling stops
|
||||
@@ -1260,6 +1368,9 @@ impl Pool {
|
||||
/// Runs `statements` in one transaction; each must change `expect_one`
|
||||
/// row when flagged (table editor submits).
|
||||
pub async fn transaction(&self, statements: &[(String, bool)]) -> IdeResult<u64> {
|
||||
if self.transaction_read_only() {
|
||||
return Err(IdeError::invalid("Cannot submit table changes on a read-only PostgreSQL source"));
|
||||
}
|
||||
match self {
|
||||
Pool::Jdbc(_) => Err(IdeError::invalid("Custom JDBC table editing is unsupported")),
|
||||
Pool::Clickhouse(_) => Err(crate::clickhouse::transaction_error()),
|
||||
@@ -1426,6 +1537,15 @@ impl Held {
|
||||
Held::Oracle(_) => DbDriver::Oracle,
|
||||
_ => return Ok(()),
|
||||
};
|
||||
if let Held::Postgres(c) = self
|
||||
&& c.options.read_only == PgReadOnly::Transaction
|
||||
{
|
||||
let wanted = schema
|
||||
.filter(|s| !s.is_empty())
|
||||
.map(|s| crate::sql::quote_ident(driver, s))
|
||||
.or_else(|| c.context.default.clone());
|
||||
return c.select_path(wanted).await;
|
||||
}
|
||||
let context = self.context().expect("switchable connection");
|
||||
let wanted = context.wanted(driver, schema);
|
||||
if context.known && context.current == wanted {
|
||||
@@ -1467,6 +1587,7 @@ impl Held {
|
||||
}
|
||||
|
||||
async fn fetch_rows(&mut self, sql: &str, max: usize) -> IdeResult<Fetched> {
|
||||
self.require_read_only_transaction()?;
|
||||
self.before_statement(sql);
|
||||
let result = match self {
|
||||
Held::Sqlite(c) => fetch!(&mut **c, sql, max, Cells::Text),
|
||||
@@ -1484,6 +1605,31 @@ impl Held {
|
||||
|
||||
/// Runs a statement without results (`BEGIN`, `COMMIT`, `ROLLBACK`).
|
||||
pub async fn command(&mut self, sql: &str) -> IdeResult<()> {
|
||||
let owned = self.begin_read_only().await?;
|
||||
let result = async {
|
||||
self.check_protected_statement(sql).await?;
|
||||
self.run_command(sql).await
|
||||
}
|
||||
.await;
|
||||
self.finish_read_only(owned, result).await
|
||||
}
|
||||
|
||||
pub(crate) async fn begin_manual(&mut self, driver: DbDriver) -> IdeResult<()> {
|
||||
if matches!(self, Self::Postgres(c) if c.options.read_only == PgReadOnly::Transaction) {
|
||||
self.begin_read_only().await?;
|
||||
return Ok(());
|
||||
}
|
||||
self.run_command(begin_statement(driver)).await
|
||||
}
|
||||
|
||||
pub(crate) async fn finish_manual(&mut self, commit: bool) -> IdeResult<()> {
|
||||
if matches!(self, Self::Postgres(c) if c.options.read_only == PgReadOnly::Transaction) {
|
||||
return self.end_read_only(commit).await;
|
||||
}
|
||||
self.run_command(if commit { "COMMIT" } else { "ROLLBACK" }).await
|
||||
}
|
||||
|
||||
async fn run_command(&mut self, sql: &str) -> IdeResult<()> {
|
||||
self.before_statement(sql);
|
||||
let result = self.raw_command(sql).await;
|
||||
if result.is_ok() {
|
||||
@@ -1493,6 +1639,7 @@ impl Held {
|
||||
}
|
||||
|
||||
async fn raw_command(&mut self, sql: &str) -> IdeResult<()> {
|
||||
self.require_read_only_transaction()?;
|
||||
match self {
|
||||
Held::SqlServer(c) => mssql_command(c, sql).await,
|
||||
Held::Clickhouse(_) => Err(crate::clickhouse::transaction_error()),
|
||||
@@ -1575,6 +1722,31 @@ impl Held {
|
||||
if let Held::Snowflake(c, schema) = self {
|
||||
return c.execute_in(schema.as_deref(), sql, skip, max_rows, cancel).await;
|
||||
}
|
||||
let owned = self.begin_read_only().await?;
|
||||
let result = async {
|
||||
self.check_protected_statement(sql).await?;
|
||||
self.run_statement(pool, sql, skip, max_rows, cancel).await
|
||||
}
|
||||
.await;
|
||||
if cancel.is_cancelled()
|
||||
&& let Held::Postgres(c) = self
|
||||
&& c.options.read_only == PgReadOnly::Transaction
|
||||
{
|
||||
c.conn.take();
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
self.finish_read_only(owned, result).await
|
||||
}
|
||||
|
||||
async fn run_statement(
|
||||
&mut self,
|
||||
pool: &Pool,
|
||||
sql: &str,
|
||||
skip: usize,
|
||||
max_rows: usize,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<QueryResult> {
|
||||
self.require_read_only_transaction()?;
|
||||
self.before_statement(sql);
|
||||
let started = Instant::now();
|
||||
// `$id`: the query naming the server process, `$kill`: how another connection stops it.
|
||||
@@ -1590,7 +1762,7 @@ impl Held {
|
||||
};
|
||||
if cancel.is_cancelled() {
|
||||
if let Some(b) = backend {
|
||||
let _ = pool.rows(&$kill(b), 1).await;
|
||||
pool.cancel_query($kill(b)).await;
|
||||
}
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
|
||||
@@ -95,6 +95,7 @@ impl Cursors {
|
||||
skip: usize,
|
||||
max: usize,
|
||||
cancel: &CancellationToken,
|
||||
protected: bool,
|
||||
) -> Option<IdeResult<Fetched>> {
|
||||
let (id, reads) = {
|
||||
let mut registry = self.registry.lock();
|
||||
@@ -110,7 +111,7 @@ impl Cursors {
|
||||
self.finish(id, &fetched);
|
||||
Some(Ok(fetched))
|
||||
}
|
||||
Some(Err(e)) if e.kind == ErrorKind::Cancelled => {
|
||||
Some(Err(e)) if protected || e.kind == ErrorKind::Cancelled => {
|
||||
self.close(id);
|
||||
Some(Err(e))
|
||||
}
|
||||
@@ -196,6 +197,19 @@ impl Cursors {
|
||||
/// nobody asks for [`IDLE`], or it is released (its channel closes).
|
||||
async fn serve(mut held: Held, pool: Arc<Pool>, sql: String, mut reads: mpsc::Receiver<Read>) {
|
||||
let Some(first) = reads.recv().await else { return held.discard().await };
|
||||
let prepare = async {
|
||||
let owned = held.begin_read_only().await?;
|
||||
held.check_protected_statement(&sql).await?;
|
||||
Ok(owned)
|
||||
}
|
||||
.await;
|
||||
let owned = match prepare {
|
||||
Ok(owned) => owned,
|
||||
Err(error) => {
|
||||
let _ = first.reply.send(Err(error));
|
||||
return;
|
||||
}
|
||||
};
|
||||
// `$id`: the query naming the server process, `$kill`: how another connection stops it.
|
||||
// Evaluates to whether the connection can go back to its pool (the stream was read to
|
||||
// its end); otherwise it is closed rather than left to be drained.
|
||||
@@ -217,7 +231,7 @@ async fn serve(mut held: Held, pool: Arc<Pool>, sql: String, mut reads: mpsc::Re
|
||||
};
|
||||
if cancel.is_cancelled() {
|
||||
if let Some(b) = backend {
|
||||
let _ = pool.rows(&$kill(b), 1).await;
|
||||
pool.cancel_query($kill(b)).await;
|
||||
}
|
||||
let _ = reply.send(Err(IdeError::cancelled()));
|
||||
break;
|
||||
@@ -236,13 +250,13 @@ async fn serve(mut held: Held, pool: Arc<Pool>, sql: String, mut reads: mpsc::Re
|
||||
}
|
||||
Err(e) => {
|
||||
let _ = reply.send(Err(e));
|
||||
reusable = true;
|
||||
reusable = !owned;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
drop(stream);
|
||||
if let Some((reply, mut fetched)) = last {
|
||||
if let Some((_, fetched)) = &mut last {
|
||||
if fetched.0.is_empty() && looks_like_query(&sql) {
|
||||
fetched.0 = (&mut **$conn)
|
||||
.prepare(sqlx::AssertSqlSafe(sql.clone()).into_sql_str())
|
||||
@@ -250,12 +264,11 @@ async fn serve(mut held: Held, pool: Arc<Pool>, sql: String, mut reads: mpsc::Re
|
||||
.map(|s| statement_columns(&s))
|
||||
.unwrap_or_default();
|
||||
}
|
||||
let _ = reply.send(Ok(fetched));
|
||||
}
|
||||
reusable
|
||||
(reusable, last)
|
||||
}};
|
||||
}
|
||||
let reusable = match &mut held {
|
||||
let (reusable, last) = match &mut held {
|
||||
Held::Sqlite(c) => serve!(c, None::<&str>, |_: String| String::new()),
|
||||
Held::Postgres(c) => {
|
||||
serve!(&mut ***c, Some("SELECT pg_backend_pid()"), |b: String| format!("SELECT pg_cancel_backend({b})"))
|
||||
@@ -263,7 +276,9 @@ async fn serve(mut held: Held, pool: Arc<Pool>, sql: String, mut reads: mpsc::Re
|
||||
Held::Mysql(c) => serve!(&mut ***c, Some("SELECT CONNECTION_ID()"), |b: String| format!("KILL QUERY {b}")),
|
||||
_ => unreachable!("only the sqlx drivers keep cursors"),
|
||||
};
|
||||
if !reusable {
|
||||
if let Some((reply, fetched)) = last {
|
||||
let _ = reply.send(held.finish_read_only(owned, Ok(fetched)).await);
|
||||
} else if !reusable {
|
||||
held.discard().await;
|
||||
}
|
||||
}
|
||||
@@ -452,7 +467,7 @@ mod tests {
|
||||
});
|
||||
let resumed = tokio::spawn({
|
||||
let (cursors, key) = (cursors.clone(), key.clone());
|
||||
async move { cursors.resume(&key, 1, 1, &CancellationToken::new()).await.is_some() }
|
||||
async move { cursors.resume(&key, 1, 1, &CancellationToken::new(), false).await.is_some() }
|
||||
});
|
||||
in_read.notified().await;
|
||||
cursors.release(&key);
|
||||
|
||||
@@ -0,0 +1,248 @@
|
||||
//! PostgreSQL transaction-pool connections whose endpoint rejects the read-only startup option.
|
||||
|
||||
use super::{Context, Held, PgConnection, PgHandle, PgReadOnly, db_err};
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use sqlx::{Executor, SqlSafeStr};
|
||||
|
||||
// Take the first snapshot before user SQL, fixing the transaction characteristics on this backend.
|
||||
pub(super) const BEGIN: &str = "BEGIN READ ONLY; SELECT 1";
|
||||
|
||||
fn leading_word<'a>(input: &mut &'a str) -> &'a str {
|
||||
loop {
|
||||
*input = input.trim_start_matches([' ', '\t', '\r', '\n', '\x0c', '\x0b', ';']);
|
||||
if let Some(comment) = input.strip_prefix("--") {
|
||||
*input = &comment[comment.find(['\r', '\n']).unwrap_or(comment.len())..];
|
||||
} else if let Some(mut comment) = input.strip_prefix("/*") {
|
||||
let mut depth = 1usize;
|
||||
while depth > 0 {
|
||||
let Some(at) = comment.find(['/', '*']) else { return "" };
|
||||
comment = &comment[at..];
|
||||
if let Some(rest) = comment.strip_prefix("/*") {
|
||||
depth += 1;
|
||||
comment = rest;
|
||||
} else if let Some(rest) = comment.strip_prefix("*/") {
|
||||
depth -= 1;
|
||||
comment = rest;
|
||||
} else {
|
||||
comment = &comment[1..];
|
||||
}
|
||||
}
|
||||
*input = comment;
|
||||
} else {
|
||||
let end = input.find(|c: char| !(c.is_alphanumeric() || c == '_' || c == '$')).unwrap_or(input.len());
|
||||
let (word, rest) = input.split_at(end);
|
||||
*input = rest;
|
||||
return word;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn control(mut sql: &str) -> Option<&'static str> {
|
||||
let first = leading_word(&mut sql);
|
||||
for name in ["BEGIN", "COMMIT", "END", "ROLLBACK", "ABORT"] {
|
||||
if first.eq_ignore_ascii_case(name) {
|
||||
return Some(name);
|
||||
}
|
||||
}
|
||||
let second = leading_word(&mut sql);
|
||||
if second.eq_ignore_ascii_case("TRANSACTION") {
|
||||
return [("START", "START TRANSACTION"), ("PREPARE", "PREPARE TRANSACTION"), ("SET", "SET TRANSACTION")]
|
||||
.into_iter()
|
||||
.find_map(|(verb, name)| first.eq_ignore_ascii_case(verb).then_some(name));
|
||||
}
|
||||
(first.eq_ignore_ascii_case("SET")
|
||||
&& second.eq_ignore_ascii_case("SESSION")
|
||||
&& leading_word(&mut sql).eq_ignore_ascii_case("CHARACTERISTICS"))
|
||||
.then_some("SET SESSION CHARACTERISTICS")
|
||||
}
|
||||
|
||||
pub(crate) fn validate(sql: &str) -> Result<(), String> {
|
||||
if sql.contains('\0') {
|
||||
return Err("PostgreSQL statements cannot contain a null byte".into());
|
||||
}
|
||||
let blocked = control(sql).or_else(|| {
|
||||
sql.contains(';')
|
||||
.then(|| crate::split::split(sql, crate::DbDriver::Postgres))
|
||||
.and_then(|statements| statements.iter().find_map(|s| control(&s.text)))
|
||||
});
|
||||
if let Some(name) = blocked {
|
||||
return Err(format!("{name} is unavailable while OpenIDEA manages the read-only transaction"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A startup SET must follow the client to its next backend without changing the next client's session.
|
||||
pub(super) fn startup(statements: &[String]) -> Result<(Vec<String>, Vec<String>), String> {
|
||||
let mut init = Vec::with_capacity(statements.len());
|
||||
let mut settings = Vec::new();
|
||||
for sql in statements {
|
||||
validate(sql)?;
|
||||
let mut rest = sql.as_str();
|
||||
let verb = leading_word(&mut rest);
|
||||
if verb.eq_ignore_ascii_case("RESET") || verb.eq_ignore_ascii_case("DISCARD") {
|
||||
return Err(format!("{verb} in a startup script cannot be preserved across pooled read-only transactions"));
|
||||
}
|
||||
if verb.eq_ignore_ascii_case("SET") {
|
||||
let after_set = rest;
|
||||
let kind = leading_word(&mut rest);
|
||||
if !kind.eq_ignore_ascii_case("LOCAL") && !kind.eq_ignore_ascii_case("CONSTRAINTS") {
|
||||
let mut after_session = rest;
|
||||
let local = if kind.eq_ignore_ascii_case("SESSION")
|
||||
&& !leading_word(&mut after_session).eq_ignore_ascii_case("AUTHORIZATION")
|
||||
{
|
||||
rest
|
||||
} else {
|
||||
after_set
|
||||
};
|
||||
let sql = format!("SET LOCAL {local}");
|
||||
settings.push(sql.clone());
|
||||
init.push(sql);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
init.push(sql.clone());
|
||||
}
|
||||
Ok((init, settings))
|
||||
}
|
||||
|
||||
// Keep the text result format of raw_sql. For SQL containing a delimiter, PostgreSQL's Parse
|
||||
// validates that the text denotes a single command, including under the server's quoting rules.
|
||||
pub(super) async fn check_single(conn: &mut PgConnection, sql: &str) -> Result<(), sqlx::Error> {
|
||||
if sql.contains(';') {
|
||||
conn.prepare(sqlx::AssertSqlSafe(sql.to_owned()).into_sql_str()).await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
impl PgHandle {
|
||||
pub(super) async fn start_read_only(&mut self) -> IdeResult<()> {
|
||||
self.in_transaction = true;
|
||||
let result = async {
|
||||
sqlx::raw_sql(BEGIN).execute(&mut **self).await.map_err(db_err)?;
|
||||
let settings = self.options.local_settings.clone();
|
||||
for sql in settings.iter() {
|
||||
check_single(self, sql).await.map_err(db_err)?;
|
||||
sqlx::raw_sql(sqlx::AssertSqlSafe(sql.clone())).execute(&mut **self).await.map_err(db_err)?;
|
||||
}
|
||||
self.apply_local_path().await
|
||||
}
|
||||
.await;
|
||||
if result.is_err() {
|
||||
self.conn.take();
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
async fn apply_local_path(&mut self) -> IdeResult<()> {
|
||||
if let Some(path) = &self.context.current {
|
||||
let path = path.clone();
|
||||
sqlx::query("SELECT pg_catalog.set_config('search_path', $1, true)")
|
||||
.bind(path)
|
||||
.execute(&mut **self)
|
||||
.await
|
||||
.map_err(db_err)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) async fn select_path(&mut self, wanted: Option<String>) -> IdeResult<()> {
|
||||
if !self.context.known || self.context.current != wanted {
|
||||
self.context.current = wanted;
|
||||
if self.in_transaction {
|
||||
self.apply_local_path().await?;
|
||||
}
|
||||
self.context.known = true;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Held {
|
||||
pub(super) fn require_read_only_transaction(&self) -> IdeResult<()> {
|
||||
if matches!(self, Self::Postgres(c) if c.options.read_only == PgReadOnly::Transaction && (!c.in_transaction || c.conn.is_none()))
|
||||
{
|
||||
return Err(IdeError::internal("PostgreSQL read-only transaction has not started"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn guarded_postgres(&mut self) -> Option<&mut PgHandle> {
|
||||
match self {
|
||||
Self::Postgres(c) if c.options.read_only == PgReadOnly::Transaction => Some(c),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns true when this operation owns the transaction and must finish it.
|
||||
pub(super) async fn begin_read_only(&mut self) -> IdeResult<bool> {
|
||||
if let Some(c) = self.guarded_postgres()
|
||||
&& !c.in_transaction
|
||||
{
|
||||
c.start_read_only().await?;
|
||||
return Ok(true);
|
||||
}
|
||||
Ok(false)
|
||||
}
|
||||
|
||||
pub(super) async fn check_protected_statement(&mut self, sql: &str) -> IdeResult<()> {
|
||||
self.require_read_only_transaction()?;
|
||||
if let Some(c) = self.guarded_postgres() {
|
||||
validate(sql).map_err(IdeError::invalid)?;
|
||||
check_single(c, sql).await.map_err(db_err)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) async fn end_read_only(&mut self, commit: bool) -> IdeResult<()> {
|
||||
if let Some(c) = self.guarded_postgres() {
|
||||
if c.conn.is_none() {
|
||||
return Err(IdeError::invalid("The read-only PostgreSQL transaction lost its connection"));
|
||||
}
|
||||
let end = if commit { "COMMIT" } else { "ROLLBACK" };
|
||||
if let Err(error) = sqlx::raw_sql(end).execute(&mut **c).await {
|
||||
c.conn.take();
|
||||
return Err(db_err(error));
|
||||
}
|
||||
c.in_transaction = false;
|
||||
c.context = Context::new(c.context.default.clone());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) async fn finish_read_only<T>(&mut self, owned: bool, result: IdeResult<T>) -> IdeResult<T> {
|
||||
if owned && let Err(error) = self.end_read_only(result.is_ok()).await {
|
||||
return Err(result.err().unwrap_or(error));
|
||||
}
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::validate;
|
||||
|
||||
#[test]
|
||||
fn names_transaction_control_and_accepts_quoted_text() {
|
||||
for name in [
|
||||
"BEGIN",
|
||||
"COMMIT",
|
||||
"END",
|
||||
"ROLLBACK",
|
||||
"ABORT",
|
||||
"START TRANSACTION",
|
||||
"PREPARE TRANSACTION",
|
||||
"SET TRANSACTION",
|
||||
"SET SESSION CHARACTERISTICS",
|
||||
] {
|
||||
let statement = name.to_lowercase().replace(' ', " /* note */ ");
|
||||
let sql = format!(" -- preceding comment\n /* outer /* nested */ block */ {statement}");
|
||||
assert!(validate(&sql).unwrap_err().contains(name), "{sql}");
|
||||
}
|
||||
assert!(validate("SELECT 1; COMMIT").unwrap_err().contains("COMMIT"));
|
||||
for sql in
|
||||
["SELECT 'a; COMMIT'", "SELECT $$;ROLLBACK$$", "SELECT 1 /* END */", "SET LOCAL search_path TO public"]
|
||||
{
|
||||
assert!(validate(sql).is_ok(), "{sql}");
|
||||
}
|
||||
}
|
||||
}
|
||||
+120
-21
@@ -178,6 +178,18 @@ pub struct TableDetails {
|
||||
pub triggers: Vec<TriggerInfo>,
|
||||
}
|
||||
|
||||
/// One object privilege on a table: `grantee` may run `privilege` (`SELECT`, …), granted
|
||||
/// by `grantor` (unknown on MySQL), and may grant it on when `grantable`.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[serde(rename = "DbTableGrant")]
|
||||
pub struct TableGrant {
|
||||
pub grantee: String,
|
||||
pub grantor: Option<String>,
|
||||
pub privilege: String,
|
||||
pub grantable: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[serde(rename = "DbCompletionColumn")]
|
||||
@@ -285,6 +297,8 @@ pub struct DbManager {
|
||||
type Session = Arc<tokio::sync::Mutex<Option<Held>>>;
|
||||
|
||||
const MAX_META_ROWS: usize = 100_000;
|
||||
/// Completion columns of the default schema, which are read without the shared cap.
|
||||
const MAX_SCHEMA_COMPLETION_ROWS: usize = 1_000_000;
|
||||
|
||||
/// Rows of catalog query `q`, run again as [`sql::postgres_legacy`] when a PostgreSQL server's
|
||||
/// catalog lacks a column it reads (openGauss, PostgreSQL 9).
|
||||
@@ -394,7 +408,7 @@ pub(crate) fn keep_alive(pool: &Arc<Pool>, every: Duration) {
|
||||
async fn end_session(session: &Session) {
|
||||
let held = session.lock().await.take();
|
||||
if let Some(mut conn) = held
|
||||
&& (conn.command("ROLLBACK").await.is_err() || conn.restore_default().await.is_err())
|
||||
&& (conn.finish_manual(false).await.is_err() || conn.restore_default().await.is_err())
|
||||
{
|
||||
conn.discard().await;
|
||||
}
|
||||
@@ -837,11 +851,18 @@ impl DbManager {
|
||||
_ => pool.rows(version, 1).await,
|
||||
};
|
||||
pool.close().await;
|
||||
let strict =
|
||||
source.external_tunnel.is_some() || matches!(source.driver, DbDriver::Clickhouse | DbDriver::Snowflake);
|
||||
let strict = pool.transaction_read_only()
|
||||
|| source.external_tunnel.is_some()
|
||||
|| matches!(source.driver, DbDriver::Clickhouse | DbDriver::Snowflake);
|
||||
let rows = if strict { result? } else { result.unwrap_or_default() };
|
||||
let v = rows.into_iter().next().and_then(|r| r.into_iter().next().flatten());
|
||||
Ok(v.unwrap_or_else(|| "Connected".into()))
|
||||
let mut message = v.unwrap_or_else(|| "Connected".into());
|
||||
if pool.transaction_read_only() {
|
||||
message.push_str(
|
||||
"\nRead-only queries use BEGIN READ ONLY because this endpoint rejected the startup setting.",
|
||||
);
|
||||
}
|
||||
Ok(message)
|
||||
}
|
||||
|
||||
/// Runs `job` with the client tool at `executable` against target `id`, connected like the
|
||||
@@ -1157,6 +1178,28 @@ impl DbManager {
|
||||
Ok(TableDetails { columns, indexes, foreign_keys, triggers })
|
||||
}
|
||||
|
||||
/// The object privileges granted on `table`; empty, without a query, on the engines
|
||||
/// [`sql::table_grants`] doesn't cover.
|
||||
pub async fn table_grants(&self, id: &str, schema: &str, table: &str) -> IdeResult<Vec<TableGrant>> {
|
||||
let pool = self.pool(id).await?;
|
||||
let Some(q) = sql::table_grants(pool.driver(), schema, table) else {
|
||||
return Ok(Vec::new());
|
||||
};
|
||||
Ok(pool
|
||||
.rows(&q, MAX_META_ROWS)
|
||||
.await?
|
||||
.into_iter()
|
||||
.filter_map(|r| {
|
||||
let mut it = r.into_iter();
|
||||
let grantee = it.next().flatten()?;
|
||||
let grantor = it.next().flatten().filter(|g| !g.is_empty());
|
||||
let privilege = it.next().flatten()?.to_ascii_uppercase();
|
||||
let grantable = flag(&it.next().flatten());
|
||||
Some(TableGrant { grantee, grantor, privilege, grantable })
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// The routines and sequences of `schema`.
|
||||
pub async fn schema_objects(&self, id: &str, schema: &str) -> IdeResult<SchemaObjects> {
|
||||
let pool = self.pool(id).await?;
|
||||
@@ -1388,13 +1431,34 @@ impl DbManager {
|
||||
let pool = self.pool(id).await?;
|
||||
let driver = pool.driver();
|
||||
let mut tables: Vec<CompletionTable> = Vec::new();
|
||||
if let Pool::Jdbc(p) = &*pool {
|
||||
return self.jdbc_completion(id, p).await;
|
||||
}
|
||||
let default_schema = match sql::current_schema(driver) {
|
||||
None => "main".to_owned(),
|
||||
Some(q) => pool
|
||||
.rows(q, 1)
|
||||
.await?
|
||||
.into_iter()
|
||||
.next()
|
||||
.and_then(|r| r.into_iter().next().flatten())
|
||||
.unwrap_or_default(),
|
||||
};
|
||||
let rows = match &*pool {
|
||||
Pool::Jdbc(p) => return self.jdbc_completion(id, p).await,
|
||||
Pool::Snowflake(p) => {
|
||||
tables = snowflake::meta::completion(p).await?;
|
||||
Vec::new()
|
||||
}
|
||||
_ => pool.rows(sql::completion_columns(driver), MAX_META_ROWS).await?,
|
||||
// The default schema is read in full: under a shared row cap, a schema with many
|
||||
// tables lost the columns of the tables sorting last (#6118). Other schemas share the cap.
|
||||
_ if !default_schema.is_empty() => {
|
||||
let only = sql::completion_columns(driver, sql::CompletionScope::Only(&default_schema));
|
||||
let mut rows = pool.rows(&only, MAX_SCHEMA_COMPLETION_ROWS).await?;
|
||||
let rest = sql::completion_columns(driver, sql::CompletionScope::Except(&default_schema));
|
||||
rows.extend(pool.rows(&rest, MAX_META_ROWS).await?);
|
||||
rows
|
||||
}
|
||||
_ => pool.rows(&sql::completion_columns(driver, sql::CompletionScope::All), MAX_META_ROWS).await?,
|
||||
};
|
||||
for r in rows {
|
||||
let mut it = r.into_iter().map(Option::unwrap_or_default);
|
||||
@@ -1430,16 +1494,6 @@ impl DbManager {
|
||||
})
|
||||
};
|
||||
let foreign_keys = group_foreign_keys(fk_rows, &tables);
|
||||
let default_schema = match sql::current_schema(driver) {
|
||||
None => "main".to_owned(),
|
||||
Some(q) => pool
|
||||
.rows(q, 1)
|
||||
.await?
|
||||
.into_iter()
|
||||
.next()
|
||||
.and_then(|r| r.into_iter().next().flatten())
|
||||
.unwrap_or_default(),
|
||||
};
|
||||
Ok(CompletionModel { default_schema, tables, foreign_keys })
|
||||
}
|
||||
|
||||
@@ -1455,6 +1509,22 @@ impl DbManager {
|
||||
self.execute_from(id, statement, 0, max_rows, cancel, None).await
|
||||
}
|
||||
|
||||
/// Refuses transaction control anywhere in a guarded console script before running its first statement.
|
||||
pub async fn validate_script(&self, id: &str, statements: &[split::SqlStatement]) -> IdeResult<()> {
|
||||
if statements.len() > 1
|
||||
&& self.source(id).is_ok_and(|s| s.driver == DbDriver::Postgres && s.read_only)
|
||||
&& self.pool(id).await?.transaction_read_only()
|
||||
{
|
||||
for statement in statements {
|
||||
if let Err(error) = conn::validate_pg_read_only(&statement.text) {
|
||||
self.finish_transaction(id, false).await?;
|
||||
return Err(IdeError::invalid(error));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// [`execute`](Self::execute), reading past the first `skip` rows without keeping
|
||||
/// them: a later page of a result, where only that page is decoded and returned.
|
||||
/// `schema` is a query console's active context: the connection that runs the
|
||||
@@ -1590,16 +1660,23 @@ impl DbManager {
|
||||
return p.query_in_schema(statement, skip, max_rows, cancel, schema).await;
|
||||
}
|
||||
let session = self.sessions.lock().get(id).cloned();
|
||||
if !conn::cursor_statement(statement) {
|
||||
let protected = pool.transaction_read_only();
|
||||
let cursor = protected || conn::cursor_statement(statement);
|
||||
if !cursor || (protected && skip == 0 && paging) {
|
||||
// A cursor's open statement could keep this one waiting (a lock), and would show data from before it.
|
||||
self.cursors.release_target(id);
|
||||
}
|
||||
if paging && session.is_none() && skip > 0 && pool.keeps_cursors() && conn::cursor_statement(statement) {
|
||||
if paging && session.is_none() && (skip > 0 || protected) && pool.keeps_cursors() && cursor {
|
||||
let key = conn::CursorKey::new(id, statement, schema);
|
||||
let started = std::time::Instant::now();
|
||||
let page = match self.cursors.resume(&key, skip, max_rows, cancel).await {
|
||||
let page = match self.cursors.resume(&key, skip, max_rows, cancel, protected).await {
|
||||
Some(page) => page,
|
||||
None => {
|
||||
if protected && skip > 0 {
|
||||
return Err(IdeError::invalid(
|
||||
"This read-only result is no longer open at this page. Run the query again.",
|
||||
));
|
||||
}
|
||||
let mut held = Held::acquire(&pool).await?;
|
||||
held.apply_context(schema).await?;
|
||||
self.cursors.start(held, pool.clone(), key, skip, max_rows, cancel).await
|
||||
@@ -1627,10 +1704,32 @@ impl DbManager {
|
||||
return Err(IdeError::invalid("ClickHouse manual transactions are unsupported"));
|
||||
}
|
||||
let mut held = session.lock().await;
|
||||
if pool.transaction_read_only() {
|
||||
// Own the session during awaits so a dropped request cannot return an unfinished transaction.
|
||||
let mut conn = match held.take() {
|
||||
Some(conn) => conn,
|
||||
None => {
|
||||
let mut conn = Held::acquire(&pool).await?;
|
||||
conn.begin_manual(pool.driver()).await?;
|
||||
conn
|
||||
}
|
||||
};
|
||||
let result = async {
|
||||
conn.apply_context(schema).await?;
|
||||
conn.execute_from(&pool, statement, skip, max_rows, cancel).await
|
||||
}
|
||||
.await;
|
||||
if result.is_ok() {
|
||||
*held = Some(conn);
|
||||
} else if cancel.is_cancelled() || conn.finish_manual(false).await.is_err() {
|
||||
conn.discard().await;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
if held.is_none() {
|
||||
let mut conn = Held::acquire(&pool).await?;
|
||||
conn.apply_context(schema).await?;
|
||||
conn.command(conn::begin_statement(pool.driver())).await?;
|
||||
conn.begin_manual(pool.driver()).await?;
|
||||
*held = Some(conn);
|
||||
}
|
||||
let conn = held.as_mut().expect("opened above");
|
||||
@@ -1676,7 +1775,7 @@ impl DbManager {
|
||||
let Some(session) = session else { return Ok(()) };
|
||||
let mut held = session.lock().await;
|
||||
let Some(mut conn) = held.take() else { return Ok(()) };
|
||||
if let Err(e) = conn.command(if commit { "COMMIT" } else { "ROLLBACK" }).await {
|
||||
if let Err(e) = conn.finish_manual(commit).await {
|
||||
// Discarding a Snowflake connection doesn't end its session, which the data source's
|
||||
// other targets share: the transaction stays open, so it stays held to be ended again.
|
||||
if matches!(conn, conn::Held::Snowflake(..)) {
|
||||
|
||||
+121
-38
@@ -252,31 +252,47 @@ pub fn indexes(driver: DbDriver, schema: &str, table: &str) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// Which schemas a [`completion_columns`] query reads.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum CompletionScope<'a> {
|
||||
/// Every non-system schema, capped at [`COMPLETION_ROW_CAP`] rows.
|
||||
All,
|
||||
/// One schema, in full.
|
||||
Only(&'a str),
|
||||
/// Every non-system schema but this one, capped at [`COMPLETION_ROW_CAP`] rows.
|
||||
Except(&'a str),
|
||||
}
|
||||
|
||||
/// Rows a [`CompletionScope::All`] or [`CompletionScope::Except`] query returns at most.
|
||||
pub const COMPLETION_ROW_CAP: usize = 50_000;
|
||||
|
||||
/// Rows: `schema, table, kind (table/view), column, type, nullable (YES/NO), is_pk (0/1), has_default (0/1)`
|
||||
/// for SQL completion, grouped by table in column order.
|
||||
pub fn completion_columns(driver: DbDriver) -> &'static str {
|
||||
match driver {
|
||||
pub fn completion_columns(driver: DbDriver, scope: CompletionScope) -> String {
|
||||
let (query, schema, order) = match driver {
|
||||
DbDriver::Jdbc => unreachable!("JDBC introspection uses DatabaseMetaData"),
|
||||
DbDriver::Clickhouse => {
|
||||
DbDriver::Clickhouse => (
|
||||
"SELECT c.database, c.table, CASE t.engine WHEN 'View' THEN 'view' \
|
||||
WHEN 'MaterializedView' THEN 'materialized view' WHEN 'WindowView' THEN 'view' ELSE 'table' END, \
|
||||
c.name, c.type, CASE WHEN startsWith(c.type, 'Nullable(') \
|
||||
OR startsWith(c.type, 'LowCardinality(Nullable(') THEN 'YES' ELSE 'NO' END, c.is_in_primary_key, 1 \
|
||||
FROM system.columns c JOIN system.tables t ON t.database = c.database AND t.name = c.table \
|
||||
WHERE lower(c.database) NOT IN ('system', 'information_schema') AND t.is_temporary = 0 \
|
||||
ORDER BY c.database, c.table, c.position LIMIT 50000"
|
||||
}
|
||||
DbDriver::Sqlite => {
|
||||
WHERE lower(c.database) NOT IN ('system', 'information_schema') AND t.is_temporary = 0",
|
||||
"c.database",
|
||||
"c.database, c.table, c.position",
|
||||
),
|
||||
DbDriver::Sqlite => (
|
||||
"SELECT 'main', m.name, m.type, p.name, p.type, CASE WHEN p.\"notnull\" = 0 THEN 'YES' ELSE 'NO' END, \
|
||||
CASE WHEN p.pk > 0 THEN 1 ELSE 0 END, \
|
||||
CASE WHEN p.dflt_value IS NOT NULL THEN 1 \
|
||||
WHEN p.pk = 1 AND upper(p.type) = 'INTEGER' \
|
||||
AND (SELECT count(*) FROM pragma_table_info(m.name) k WHERE k.pk > 0) = 1 THEN 1 ELSE 0 END \
|
||||
FROM sqlite_master m JOIN pragma_table_info(m.name) p \
|
||||
WHERE m.type IN ('table', 'view') AND m.name NOT LIKE 'sqlite\\_%' ESCAPE '\\' ORDER BY m.name, p.cid"
|
||||
}
|
||||
// Identity columns own their sequence through an internal dependency (`attidentity` is PostgreSQL 10+).
|
||||
DbDriver::Postgres => {
|
||||
WHERE m.type IN ('table', 'view') AND m.name NOT LIKE 'sqlite\\_%' ESCAPE '\\'",
|
||||
"'main'",
|
||||
"m.name, p.cid",
|
||||
),
|
||||
DbDriver::Postgres => (
|
||||
"SELECT n.nspname, c.relname, CASE c.relkind WHEN 'v' THEN 'view' WHEN 'm' THEN 'materialized view' ELSE 'table' END, a.attname, \
|
||||
format_type(a.atttypid, a.atttypmod), CASE WHEN a.attnotnull THEN 'NO' ELSE 'YES' END, \
|
||||
CASE WHEN EXISTS (SELECT 1 FROM pg_index i WHERE i.indrelid = c.oid AND i.indisprimary \
|
||||
@@ -287,19 +303,21 @@ pub fn completion_columns(driver: DbDriver) -> &'static str {
|
||||
FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace JOIN pg_attribute a ON a.attrelid = c.oid \
|
||||
WHERE c.relkind IN ('r', 'v', 'm', 'p', 'f') AND a.attnum > 0 AND NOT a.attisdropped \
|
||||
AND n.nspname NOT IN ('pg_catalog', 'information_schema') \
|
||||
AND n.nspname NOT LIKE 'pg\\_toast%' AND n.nspname NOT LIKE 'pg\\_temp%' \
|
||||
ORDER BY n.nspname, c.relname, a.attnum LIMIT 50000"
|
||||
}
|
||||
DbDriver::Mysql => {
|
||||
AND n.nspname NOT LIKE 'pg\\_toast%' AND n.nspname NOT LIKE 'pg\\_temp%'",
|
||||
"n.nspname",
|
||||
"n.nspname, c.relname, a.attnum",
|
||||
),
|
||||
DbDriver::Mysql => (
|
||||
"SELECT c.table_schema, c.table_name, CASE WHEN t.table_type LIKE '%VIEW%' THEN 'view' ELSE 'table' END, \
|
||||
c.column_name, c.column_type, c.is_nullable, CASE WHEN c.column_key = 'PRI' THEN 1 ELSE 0 END, \
|
||||
CASE WHEN c.column_default IS NOT NULL OR c.extra LIKE '%auto_increment%' THEN 1 ELSE 0 END \
|
||||
FROM information_schema.columns c JOIN information_schema.tables t \
|
||||
ON t.table_schema = c.table_schema AND t.table_name = c.table_name \
|
||||
WHERE c.table_schema NOT IN ('information_schema', 'mysql', 'performance_schema', 'sys') \
|
||||
ORDER BY c.table_schema, c.table_name, c.ordinal_position LIMIT 50000"
|
||||
}
|
||||
DbDriver::SqlServer => {
|
||||
WHERE c.table_schema NOT IN ('information_schema', 'mysql', 'performance_schema', 'sys')",
|
||||
"c.table_schema",
|
||||
"c.table_schema, c.table_name, c.ordinal_position",
|
||||
),
|
||||
DbDriver::SqlServer => (
|
||||
"SELECT c.TABLE_SCHEMA, c.TABLE_NAME, CASE WHEN t.TABLE_TYPE LIKE '%VIEW%' THEN 'view' ELSE 'table' END, \
|
||||
c.COLUMN_NAME, c.DATA_TYPE, c.IS_NULLABLE, \
|
||||
CASE WHEN EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc \
|
||||
@@ -310,19 +328,21 @@ pub fn completion_columns(driver: DbDriver) -> &'static str {
|
||||
CASE WHEN c.COLUMN_DEFAULT IS NOT NULL THEN 1 ELSE 0 END \
|
||||
FROM INFORMATION_SCHEMA.COLUMNS c JOIN INFORMATION_SCHEMA.TABLES t \
|
||||
ON t.TABLE_SCHEMA = c.TABLE_SCHEMA AND t.TABLE_NAME = c.TABLE_NAME \
|
||||
WHERE c.TABLE_SCHEMA NOT IN ('sys', 'INFORMATION_SCHEMA') \
|
||||
ORDER BY c.TABLE_SCHEMA, c.TABLE_NAME, c.ORDINAL_POSITION"
|
||||
}
|
||||
DbDriver::Snowflake => {
|
||||
WHERE c.TABLE_SCHEMA NOT IN ('sys', 'INFORMATION_SCHEMA')",
|
||||
"c.TABLE_SCHEMA",
|
||||
"c.TABLE_SCHEMA, c.TABLE_NAME, c.ORDINAL_POSITION",
|
||||
),
|
||||
DbDriver::Snowflake => (
|
||||
"SELECT c.table_schema, c.table_name, CASE t.table_type WHEN 'VIEW' THEN 'view' \
|
||||
WHEN 'MATERIALIZED VIEW' THEN 'materialized view' ELSE 'table' END, c.column_name, c.data_type, \
|
||||
c.is_nullable, 0, CASE WHEN c.column_default IS NOT NULL THEN 1 ELSE 0 END \
|
||||
FROM information_schema.columns c JOIN information_schema.tables t \
|
||||
ON t.table_schema = c.table_schema AND t.table_name = c.table_name \
|
||||
WHERE c.table_schema <> 'INFORMATION_SCHEMA' \
|
||||
ORDER BY c.table_schema, c.table_name, c.ordinal_position LIMIT 50000"
|
||||
}
|
||||
DbDriver::Oracle => {
|
||||
WHERE c.table_schema <> 'INFORMATION_SCHEMA'",
|
||||
"c.table_schema",
|
||||
"c.table_schema, c.table_name, c.ordinal_position",
|
||||
),
|
||||
DbDriver::Oracle => (
|
||||
"SELECT c.owner, c.table_name, CASE WHEN v.view_name IS NOT NULL THEN 'view' ELSE 'table' END, \
|
||||
c.column_name, c.data_type, DECODE(c.nullable, 'Y', 'YES', 'NO'), \
|
||||
CASE WHEN k.column_name IS NOT NULL THEN 1 ELSE 0 END, \
|
||||
@@ -334,10 +354,22 @@ pub fn completion_columns(driver: DbDriver) -> &'static str {
|
||||
AND kc.constraint_name = con.constraint_name WHERE con.constraint_type = 'P') k \
|
||||
ON k.owner = c.owner AND k.table_name = c.table_name AND k.column_name = c.column_name \
|
||||
WHERE c.owner NOT IN ('CTXSYS', 'DBSFWUSER', 'DVSYS', 'GSMADMIN_INTERNAL', 'LBACSYS', 'MDDATA', \
|
||||
'MDSYS', 'OLAPSYS', 'OUTLN', 'SYS', 'SYSTEM', 'XDB', 'XS$NULL') \
|
||||
ORDER BY c.owner, c.table_name, c.column_id FETCH FIRST 50000 ROWS ONLY"
|
||||
}
|
||||
}
|
||||
'MDSYS', 'OLAPSYS', 'OUTLN', 'SYS', 'SYSTEM', 'XDB', 'XS$NULL')",
|
||||
"c.owner",
|
||||
"c.owner, c.table_name, c.column_id",
|
||||
),
|
||||
};
|
||||
let filter = match scope {
|
||||
CompletionScope::All => String::new(),
|
||||
CompletionScope::Only(s) => format!(" AND {schema} = {}", quote_literal(driver, s)),
|
||||
CompletionScope::Except(s) => format!(" AND {schema} <> {}", quote_literal(driver, s)),
|
||||
};
|
||||
let cap = match (scope, driver) {
|
||||
(CompletionScope::Only(_), _) | (_, DbDriver::Sqlite | DbDriver::SqlServer) => String::new(),
|
||||
(_, DbDriver::Oracle) => format!(" FETCH FIRST {COMPLETION_ROW_CAP} ROWS ONLY"),
|
||||
_ => format!(" LIMIT {COMPLETION_ROW_CAP}"),
|
||||
};
|
||||
format!("{query}{filter} ORDER BY {order}{cap}")
|
||||
}
|
||||
|
||||
/// Rows: `schema, table, constraint, column, ref schema, ref table, ref column`
|
||||
@@ -673,6 +705,28 @@ pub fn triggers(driver: DbDriver, schema: &str, table: &str) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// `grantee, grantor, privilege, grantable` rows of `table`'s object privileges, for the
|
||||
/// engines whose catalog keeps them per table: PostgreSQL's ACL (its implicit owner
|
||||
/// privileges when `relacl` is null) and MySQL's `TABLE_PRIVILEGES` (no grantor). `None`
|
||||
/// for the other engines, which then run no query.
|
||||
pub fn table_grants(driver: DbDriver, schema: &str, table: &str) -> Option<String> {
|
||||
let (s, t) = (quote_literal(driver, schema), quote_literal(driver, table));
|
||||
match driver {
|
||||
DbDriver::Postgres => Some(format!(
|
||||
"SELECT CASE WHEN a.grantee = 0 THEN 'PUBLIC' ELSE pg_get_userbyid(a.grantee) END, \
|
||||
pg_get_userbyid(a.grantor), a.privilege_type, CASE WHEN a.is_grantable THEN 'YES' ELSE 'NO' END \
|
||||
FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace \
|
||||
CROSS JOIN LATERAL aclexplode(coalesce(c.relacl, acldefault('r', c.relowner))) a \
|
||||
WHERE n.nspname = {s} AND c.relname = {t} ORDER BY 1, 2"
|
||||
)),
|
||||
DbDriver::Mysql => Some(format!(
|
||||
"SELECT grantee, NULL, privilege_type, is_grantable FROM information_schema.table_privileges \
|
||||
WHERE table_schema = {s} AND table_name = {t} ORDER BY 1"
|
||||
)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// `before`, `insert` of SQLite's `CREATE TRIGGER name BEFORE INSERT ON …` (its catalog keeps only the text).
|
||||
pub fn sqlite_trigger_event(sql: &str) -> (String, String) {
|
||||
let upper = sql.to_ascii_uppercase();
|
||||
@@ -928,7 +982,7 @@ mod tests {
|
||||
let keys = indexes(driver, "default", "events");
|
||||
assert!(keys.contains("'PRIMARY KEY' AS index_name, 0 AS is_unique, primary_key AS expression"));
|
||||
assert!(keys.contains("SELECT name, 0, expr FROM system.data_skipping_indices"));
|
||||
let completion = completion_columns(driver);
|
||||
let completion = completion_columns(driver, CompletionScope::All);
|
||||
assert!(completion.contains("c.is_in_primary_key, 1"));
|
||||
assert!(completion.contains("ORDER BY c.database, c.table, c.position LIMIT 50000"));
|
||||
}
|
||||
@@ -1038,7 +1092,7 @@ mod tests {
|
||||
assert!(indexes(DbDriver::SqlServer, "dbo", "t").contains("sys.indexes"));
|
||||
assert!(foreign_keys(DbDriver::SqlServer).contains("sys.foreign_key_columns"));
|
||||
assert!(table_foreign_keys(DbDriver::SqlServer, "dbo", "t").contains("OBJECT_ID(N'[dbo].[t]')"));
|
||||
assert!(completion_columns(DbDriver::SqlServer).contains("INFORMATION_SCHEMA.COLUMNS"));
|
||||
assert!(completion_columns(DbDriver::SqlServer, CompletionScope::All).contains("INFORMATION_SCHEMA.COLUMNS"));
|
||||
}
|
||||
|
||||
/// Under a case-sensitive or binary collation, catalog names only resolve as declared:
|
||||
@@ -1052,7 +1106,7 @@ mod tests {
|
||||
tables(d, "dbo"),
|
||||
columns(d, "dbo", "t"),
|
||||
indexes(d, "dbo", "t"),
|
||||
completion_columns(d).to_owned(),
|
||||
completion_columns(d, CompletionScope::All),
|
||||
foreign_keys(d).to_owned(),
|
||||
table_foreign_keys(d, "dbo", "t"),
|
||||
routines(d, "dbo").unwrap(),
|
||||
@@ -1119,7 +1173,7 @@ mod tests {
|
||||
assert!(indexes(DbDriver::Oracle, "hr", "t").contains("all_indexes"));
|
||||
assert!(foreign_keys(DbDriver::Oracle).contains("constraint_type = 'R'"));
|
||||
assert!(table_foreign_keys(DbDriver::Oracle, "hr", "t").contains("all_cons_columns"));
|
||||
assert!(completion_columns(DbDriver::Oracle).contains("all_tab_columns"));
|
||||
assert!(completion_columns(DbDriver::Oracle, CompletionScope::All).contains("all_tab_columns"));
|
||||
assert!(triggers(DbDriver::Oracle, "hr", "t").contains("all_triggers"));
|
||||
assert!(routines(DbDriver::Oracle, "hr").unwrap().contains("all_objects"));
|
||||
assert!(packages(DbDriver::Oracle, "hr").unwrap().contains("object_type = 'PACKAGE'"));
|
||||
@@ -1234,7 +1288,7 @@ mod tests {
|
||||
let columns = columns(driver, "PUBLIC", "ORDERS");
|
||||
assert!(columns.contains("'NUMBER(' || numeric_precision"), "{columns}");
|
||||
assert!(columns.contains("table_name = 'ORDERS' ORDER BY ordinal_position"), "{columns}");
|
||||
assert!(completion_columns(driver).contains("LIMIT 50000"));
|
||||
assert!(completion_columns(driver, CompletionScope::All).contains("LIMIT 50000"));
|
||||
assert!(routines(driver, "PUBLIC").unwrap().contains("information_schema.procedures"));
|
||||
assert!(sequences(driver, "PUBLIC").unwrap().contains("information_schema.sequences"));
|
||||
assert_eq!(
|
||||
@@ -1246,6 +1300,35 @@ mod tests {
|
||||
assert_eq!(crate::plan::explain_statement(driver, "select 1;"), "EXPLAIN USING TABULAR select 1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn completion_reads_the_default_schema_without_the_shared_cap() {
|
||||
// #6118: 5,000+ tables in one Oracle schema overflowed the shared cap, so tables
|
||||
// sorting last had no columns.
|
||||
let only = completion_columns(DbDriver::Oracle, CompletionScope::Only("APP's"));
|
||||
assert!(only.ends_with("AND c.owner = 'APP''s' ORDER BY c.owner, c.table_name, c.column_id"), "{only}");
|
||||
let rest = completion_columns(DbDriver::Oracle, CompletionScope::Except("APP"));
|
||||
assert!(rest.contains("AND c.owner <> 'APP' ORDER BY"), "{rest}");
|
||||
assert!(rest.ends_with(" FETCH FIRST 50000 ROWS ONLY"), "{rest}");
|
||||
let all = completion_columns(DbDriver::Oracle, CompletionScope::All);
|
||||
assert!(all.ends_with("'XS$NULL') ORDER BY c.owner, c.table_name, c.column_id FETCH FIRST 50000 ROWS ONLY"));
|
||||
for (driver, column) in [
|
||||
(DbDriver::Postgres, "n.nspname"),
|
||||
(DbDriver::Mysql, "c.table_schema"),
|
||||
(DbDriver::Clickhouse, "c.database"),
|
||||
(DbDriver::Snowflake, "c.table_schema"),
|
||||
(DbDriver::SqlServer, "c.TABLE_SCHEMA"),
|
||||
(DbDriver::Sqlite, "'main'"),
|
||||
] {
|
||||
let only = completion_columns(driver, CompletionScope::Only("app"));
|
||||
assert!(only.contains(&format!(" AND {column} = 'app' ORDER BY ")), "{only}");
|
||||
assert!(!only.contains("LIMIT") && !only.contains("FETCH FIRST"), "{only}");
|
||||
let rest = completion_columns(driver, CompletionScope::Except("app"));
|
||||
assert!(rest.contains(&format!(" AND {column} <> 'app' ORDER BY ")), "{rest}");
|
||||
let capped = !matches!(driver, DbDriver::Sqlite | DbDriver::SqlServer);
|
||||
assert_eq!(rest.ends_with(" LIMIT 50000"), capped, "{rest}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn postgres_catalog_queries_run_on_older_servers() {
|
||||
let pg = DbDriver::Postgres;
|
||||
@@ -1257,7 +1340,7 @@ mod tests {
|
||||
tables(pg, "s"),
|
||||
columns(pg, "s", "t"),
|
||||
indexes(pg, "s", "t"),
|
||||
completion_columns(pg).to_owned(),
|
||||
completion_columns(pg, CompletionScope::All),
|
||||
foreign_keys(pg).to_owned(),
|
||||
table_foreign_keys(pg, "s", "t"),
|
||||
triggers(pg, "s", "t"),
|
||||
@@ -1268,7 +1351,7 @@ mod tests {
|
||||
let upper = q.to_uppercase();
|
||||
assert!(!["LATERAL", "ORDINALITY", "ATTIDENTITY"].iter().any(|w| upper.contains(w)), "{q}");
|
||||
}
|
||||
assert_eq!(postgres_legacy(completion_columns(pg)), None);
|
||||
assert_eq!(postgres_legacy(&completion_columns(pg, CompletionScope::All)), None);
|
||||
let routines = postgres_legacy(&routines(pg, "s").unwrap()).unwrap();
|
||||
assert!(!routines.contains("prokind") && routines.contains("NOT p.proisagg"));
|
||||
assert_eq!(postgres_legacy(&indexes(pg, "s", "t")), None);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use ide_core::{CancellationToken, IdeResult};
|
||||
use ide_db::{DataSource, DbDriver, DbJdbcDriver, DbManager, SortKey};
|
||||
use ide_db::{DataSource, DbDriver, DbJdbcDriver, DbManager, DbProperty, SortKey};
|
||||
use std::{path::Path, sync::Arc};
|
||||
|
||||
fn manager(dir: &Path) -> DbManager {
|
||||
@@ -89,21 +89,25 @@ async fn named_jdbc_sources_persist_the_type_and_reject_a_profile_for_another_ty
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "requires DUCKDB_JDBC_JAR and a local Java 17+ runtime"]
|
||||
async fn duckdb_custom_driver_through_database_manager() -> IdeResult<()> {
|
||||
let tmp = tempfile::tempdir()?;
|
||||
let db = manager(tmp.path());
|
||||
fn register_duckdb(db: &DbManager, vendor: Option<&str>) -> IdeResult<()> {
|
||||
let jar = std::env::var("DUCKDB_JDBC_JAR").expect("DUCKDB_JDBC_JAR");
|
||||
assert_eq!(ide_db::jdbc_driver_classes(std::slice::from_ref(&jar))?, ["org.duckdb.DuckDBDriver"]);
|
||||
db.save_jdbc_driver(DbJdbcDriver {
|
||||
id: "duck".into(),
|
||||
name: "DuckDB".into(),
|
||||
vendor: None,
|
||||
vendor: vendor.map(str::to_owned),
|
||||
jars: vec![jar],
|
||||
class_name: "org.duckdb.DuckDBDriver".into(),
|
||||
url_template: "jdbc:duckdb:".into(),
|
||||
})?;
|
||||
})
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "requires DUCKDB_JDBC_JAR and a local Java 17+ runtime"]
|
||||
async fn duckdb_custom_driver_through_database_manager() -> IdeResult<()> {
|
||||
let tmp = tempfile::tempdir()?;
|
||||
let db = manager(tmp.path());
|
||||
register_duckdb(&db, None)?;
|
||||
let source = DataSource {
|
||||
id: "test".into(),
|
||||
name: "DuckDB".into(),
|
||||
@@ -157,6 +161,104 @@ async fn duckdb_custom_driver_through_database_manager() -> IdeResult<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "requires DUCKDB_JDBC_JAR and a local Java 17+ runtime"]
|
||||
async fn duckdb_named_file_enforces_read_only_at_open() -> IdeResult<()> {
|
||||
let tmp = tempfile::tempdir()?;
|
||||
let db = manager(tmp.path());
|
||||
register_duckdb(&db, Some("duckdb"))?;
|
||||
let file = tmp.path().join("example.duckdb");
|
||||
let mut source = DataSource {
|
||||
id: "test".into(),
|
||||
name: "DuckDB".into(),
|
||||
driver: DbDriver::Jdbc,
|
||||
vendor: "duckdb".into(),
|
||||
global: true,
|
||||
jdbc_driver: "duck".into(),
|
||||
url: format!("jdbc:duckdb:{}", file.display()),
|
||||
file: Some(file.clone().into()),
|
||||
read_only: true,
|
||||
..Default::default()
|
||||
};
|
||||
let cancel = CancellationToken::new();
|
||||
let err = db.test(&source, None, None).await.unwrap_err();
|
||||
assert!(err.message.contains("existing database file"), "{}", err.message);
|
||||
assert!(!file.exists());
|
||||
|
||||
source.read_only = false;
|
||||
db.save_sources(vec![source.clone()]).await?;
|
||||
db.execute("test", "create table items (id int)", 1, &cancel).await?;
|
||||
db.execute("test", "insert into items values (1)", 1, &cancel).await?;
|
||||
db.disconnect("test").await;
|
||||
|
||||
source.read_only = true;
|
||||
let reopened = manager(tmp.path());
|
||||
assert!(reopened.test(&source, None, None).await?.to_lowercase().contains("duckdb"));
|
||||
let mut conflicting = source.clone();
|
||||
for options in ["; access_mode = READ_WRITE", "; duckdb.read_only = false"] {
|
||||
conflicting.url = format!("{}{options}", source.url);
|
||||
let err = reopened.test(&conflicting, None, None).await.unwrap_err();
|
||||
assert!(err.message.contains("conflicts with Read-only"), "{}", err.message);
|
||||
}
|
||||
conflicting.url = source.url.clone();
|
||||
conflicting.properties.push(DbProperty { name: "ACCESS_MODE".into(), value: "READ_WRITE".into() });
|
||||
let err = reopened.test(&conflicting, None, None).await.unwrap_err();
|
||||
assert!(err.message.contains("conflicts with Read-only"), "{}", err.message);
|
||||
|
||||
reopened.save_sources(vec![source.clone()]).await?;
|
||||
assert_eq!(reopened.source("test")?.vendor, "duckdb");
|
||||
assert_eq!(reopened.execute("test", "select id from items", 1, &cancel).await?.rows, [vec![Some("1".into())]]);
|
||||
for query in ["insert into items values (2)", "create table added (id int)"] {
|
||||
let err = reopened.execute("test", query, 1, &cancel).await.unwrap_err();
|
||||
assert!(err.message.to_lowercase().contains("read-only"), "{}", err.message);
|
||||
}
|
||||
assert!(!reopened.tables("test", "main").await?.iter().any(|table| table.name == "added"));
|
||||
reopened.disconnect("test").await;
|
||||
|
||||
source.read_only = false;
|
||||
reopened.save_sources(vec![source]).await?;
|
||||
reopened.execute("test", "insert into items values (2)", 1, &cancel).await?;
|
||||
assert_eq!(
|
||||
reopened.execute("test", "select count(*) from items", 1, &cancel).await?.rows,
|
||||
[vec![Some("2".into())]]
|
||||
);
|
||||
reopened.disconnect("test").await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "requires DUCKDB_JDBC_JAR and a local Java 17+ runtime"]
|
||||
async fn duckdb_named_memory_lives_until_disconnect() -> IdeResult<()> {
|
||||
let tmp = tempfile::tempdir()?;
|
||||
let db = manager(tmp.path());
|
||||
register_duckdb(&db, Some("duckdb"))?;
|
||||
let mut source = DataSource {
|
||||
id: "test".into(),
|
||||
name: "DuckDB (memory)".into(),
|
||||
driver: DbDriver::Jdbc,
|
||||
vendor: "duckdb".into(),
|
||||
global: true,
|
||||
jdbc_driver: "duck".into(),
|
||||
url: "jdbc:duckdb:".into(),
|
||||
..Default::default()
|
||||
};
|
||||
let cancel = CancellationToken::new();
|
||||
db.save_sources(vec![source.clone()]).await?;
|
||||
db.execute("test", "create table session_items as select 42 as id", 1, &cancel).await?;
|
||||
assert_eq!(db.execute("test", "select id from session_items", 1, &cancel).await?.rows, [vec![Some("42".into())]]);
|
||||
db.disconnect("test").await;
|
||||
assert!(!db.tables("test", "main").await?.iter().any(|table| table.name == "session_items"));
|
||||
db.disconnect("test").await;
|
||||
|
||||
source.read_only = true;
|
||||
for url in ["jdbc:duckdb:", "jdbc:duckdb::memory:"] {
|
||||
source.url = url.into();
|
||||
let err = db.test(&source, None, None).await.unwrap_err();
|
||||
assert!(err.message.contains("existing database file"), "{}", err.message);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "requires CLICKHOUSE_JDBC_CLASSPATH and a loopback ClickHouse fixture on CLICKHOUSE_JDBC_TEST_PORT"]
|
||||
async fn clickhouse_vendor_driver_reads_catalog_and_results() -> IdeResult<()> {
|
||||
|
||||
@@ -322,3 +322,39 @@ async fn later_pages_continue_the_result_where_the_previous_page_stopped() -> Id
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn table_grants_list_table_privileges() -> IdeResult<()> {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let Some(db) = manager(&tmp, "").await else { return Ok(()) };
|
||||
let c = CancellationToken::new();
|
||||
for stmt in [
|
||||
"DROP DATABASE IF EXISTS oi_grants",
|
||||
"DROP USER IF EXISTS 'oi_grant_reader'@'%', 'oi_grant_writer'@'%'",
|
||||
"CREATE USER 'oi_grant_reader'@'%', 'oi_grant_writer'@'%'",
|
||||
"CREATE DATABASE oi_grants",
|
||||
"CREATE TABLE oi_grants.shared (id INT)",
|
||||
"CREATE TABLE oi_grants.private (id INT)",
|
||||
"GRANT SELECT ON oi_grants.shared TO 'oi_grant_reader'@'%'",
|
||||
"GRANT INSERT, UPDATE ON oi_grants.shared TO 'oi_grant_writer'@'%' WITH GRANT OPTION",
|
||||
] {
|
||||
db.execute("m", stmt, 10, &c).await?;
|
||||
}
|
||||
let grants = db.table_grants("m", "oi_grants", "shared").await?;
|
||||
let mut rows: Vec<_> =
|
||||
grants.iter().map(|g| (g.grantee.as_str(), g.privilege.as_str(), g.grantable, g.grantor.clone())).collect();
|
||||
rows.sort();
|
||||
assert_eq!(
|
||||
rows,
|
||||
[
|
||||
("'oi_grant_reader'@'%'", "SELECT", false, None),
|
||||
("'oi_grant_writer'@'%'", "INSERT", true, None),
|
||||
("'oi_grant_writer'@'%'", "UPDATE", true, None),
|
||||
]
|
||||
);
|
||||
assert!(db.table_grants("m", "oi_grants", "private").await?.is_empty());
|
||||
for stmt in ["DROP DATABASE oi_grants", "DROP USER 'oi_grant_reader'@'%', 'oi_grant_writer'@'%'"] {
|
||||
db.execute("m", stmt, 10, &c).await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -5,11 +5,174 @@ use ide_core::{CancellationToken, IdeResult};
|
||||
use ide_db::{DataSource, DbDriver, DbManager};
|
||||
|
||||
fn server() -> Option<(String, u16, String, String)> {
|
||||
let v = std::env::var("OPENIDEA_TEST_POSTGRES").ok()?;
|
||||
endpoint("OPENIDEA_TEST_POSTGRES")
|
||||
}
|
||||
|
||||
fn endpoint(variable: &str) -> Option<(String, u16, String, String)> {
|
||||
let v = std::env::var(variable).ok()?;
|
||||
let mut it = v.splitn(4, ':');
|
||||
Some((it.next()?.into(), it.next()?.parse().ok()?, it.next()?.into(), it.next().unwrap_or("").into()))
|
||||
}
|
||||
|
||||
/// A disposable PgBouncer transaction pool which rejects default_transaction_read_only at startup
|
||||
/// (`OPENIDEA_TEST_PGBOUNCER`, same format). PgBouncer 1.24 rejects it; 1.26 tracks it per client,
|
||||
/// which keeps the startup option in use and fails the fallback assertion below.
|
||||
#[tokio::test]
|
||||
async fn transaction_pooler_runs_read_only_work_on_the_assigned_backend() -> IdeResult<()> {
|
||||
let Some((host, port, user, password)) = endpoint("OPENIDEA_TEST_PGBOUNCER") else { return Ok(()) };
|
||||
let dir = tempfile::tempdir()?;
|
||||
let root = dir.path();
|
||||
let ssh = std::sync::Arc::new(ide_ssh::SshManager::new(root.join("ssh-passwords.json")));
|
||||
let db = DbManager::new(root.into(), root.join("passwords.json"), root.join("history.json"), ssh);
|
||||
let mut source = DataSource {
|
||||
id: "ro".into(),
|
||||
name: "Pooler".into(),
|
||||
driver: DbDriver::Postgres,
|
||||
host,
|
||||
port: Some(port),
|
||||
user,
|
||||
read_only: true,
|
||||
..Default::default()
|
||||
};
|
||||
let normal = DataSource { id: "rw".into(), read_only: false, ..source.clone() };
|
||||
source.options.startup_script =
|
||||
"SET search_path = pg_catalog, public; SET statement_timeout = '17s'; SELECT 1".into();
|
||||
db.save_sources(vec![source.clone(), normal]).await?;
|
||||
for id in ["rw", "ro"] {
|
||||
db.set_password(id, Some(password.clone()), false).await?;
|
||||
}
|
||||
let message = db.test(&source, Some(password.clone()), None).await?;
|
||||
assert!(message.contains("PostgreSQL") && message.contains("BEGIN READ ONLY"), "{message}");
|
||||
let c = CancellationToken::new();
|
||||
let table = format!("public.oi_pooler_{}", uuid::Uuid::new_v4().simple());
|
||||
let write = format!("INSERT INTO {table} VALUES (1)");
|
||||
pooler_modes(&db, &table, &write, &c).await?;
|
||||
pooler_rotation(&db, &c).await?;
|
||||
pooler_manual(&db, &write, &c).await?;
|
||||
pooler_paging(&db, &c).await?;
|
||||
pooler_cancellation(&db, &c).await?;
|
||||
source.options.time_zone = "Europe/Paris".into();
|
||||
source.options.startup_script = "SELECT 'read;only'".into();
|
||||
let configured = ide_db::Pool::connect(&source, Some(&password), None).await?;
|
||||
assert_eq!(configured.rows("SHOW TimeZone", 1).await?, [[Some("Europe/Paris".into())]]);
|
||||
configured.close().await;
|
||||
source.options.startup_script = "SELECT 1/0; COMMIT".into();
|
||||
let error = db.test(&source, Some(password), None).await.unwrap_err();
|
||||
assert!(error.message.contains("COMMIT"), "{}", error.message);
|
||||
db.execute("rw", &format!("DROP TABLE {table}"), 1, &c).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn pooler_modes(db: &DbManager, table: &str, write: &str, c: &CancellationToken) -> IdeResult<()> {
|
||||
let mode = "SHOW transaction_read_only";
|
||||
assert_eq!(db.execute("ro", mode, 1, c).await?.rows, [[Some("on".into())]]);
|
||||
assert_eq!(db.execute("rw", mode, 1, c).await?.rows, [[Some("off".into())]]);
|
||||
db.execute("rw", &format!("CREATE TABLE {table} (n int)"), 1, c).await?;
|
||||
assert!(db.execute("ro", write, 1, c).await.unwrap_err().message.contains("25006"));
|
||||
assert_eq!(db.pool("ro").await?.rows(mode, 1).await?, [[Some("on".into())]]);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn pooler_rotation(db: &DbManager, c: &CancellationToken) -> IdeResult<()> {
|
||||
let status = "SELECT pg_backend_pid(), current_setting('transaction_read_only'), current_setting('search_path'), current_setting('statement_timeout')";
|
||||
let pool = db.pool("ro").await?;
|
||||
let mut client = ide_db::Held::acquire(&pool).await?;
|
||||
let first_pid = client.execute(&pool, status, 1, c).await?.rows[0][0].clone();
|
||||
let writable = db.pool("rw").await?;
|
||||
let mut blockers = Vec::new();
|
||||
let mut previous_backend = loop {
|
||||
let mut other = ide_db::Held::acquire(&writable).await?;
|
||||
other.command("BEGIN").await?;
|
||||
let pid = other.execute(&writable, status, 1, c).await?.rows[0][0].clone();
|
||||
if pid == first_pid {
|
||||
break other;
|
||||
}
|
||||
blockers.push(other);
|
||||
assert!(blockers.len() < 4, "the fixture must offer the original backend");
|
||||
};
|
||||
for mut other in blockers {
|
||||
other.command("ROLLBACK").await?;
|
||||
}
|
||||
let rerouted = client.execute(&pool, status, 1, c).await?;
|
||||
assert_ne!(rerouted.rows[0][0], first_pid);
|
||||
assert_eq!(rerouted.rows[0][1..], [Some("on".into()), Some("pg_catalog, public".into()), Some("17s".into())]);
|
||||
let ordinary = previous_backend.execute(&writable, status, 1, c).await?;
|
||||
assert_ne!(ordinary.rows[0][2].as_deref(), Some("pg_catalog, public"));
|
||||
assert_ne!(ordinary.rows[0][3].as_deref(), Some("17s"));
|
||||
previous_backend.command("ROLLBACK").await?;
|
||||
drop(client);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn pooler_manual(db: &DbManager, write: &str, c: &CancellationToken) -> IdeResult<()> {
|
||||
let mode = "SHOW transaction_read_only";
|
||||
db.set_manual_commit("ro", true).await?;
|
||||
for commit in [true, false] {
|
||||
assert_eq!(db.execute("ro", mode, 1, c).await?.rows, [[Some("on".into())]]);
|
||||
db.finish_transaction("ro", commit).await?;
|
||||
}
|
||||
db.execute("ro", write, 1, c).await.unwrap_err();
|
||||
assert_eq!(db.execute("ro", mode, 1, c).await?.rows, [[Some("on".into())]]);
|
||||
let timestamp = "SELECT transaction_timestamp()";
|
||||
for batch in [false, true] {
|
||||
let before = db.execute("ro", timestamp, 1, c).await?.rows;
|
||||
let error = if batch {
|
||||
let script = ide_db::split::split("SELECT 1/0; COMMIT", DbDriver::Postgres);
|
||||
db.validate_script("ro", &script).await.unwrap_err()
|
||||
} else {
|
||||
db.execute("ro", "COMMIT", 1, c).await.unwrap_err()
|
||||
};
|
||||
assert!(error.message.contains("COMMIT"), "{}", error.message);
|
||||
assert_ne!(db.execute("ro", timestamp, 1, c).await?.rows, before);
|
||||
}
|
||||
db.set_manual_commit("ro", false).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn pooler_paging(db: &DbManager, c: &CancellationToken) -> IdeResult<()> {
|
||||
let query = "SELECT current_setting('transaction_read_only'), pg_backend_pid(), transaction_timestamp(), n FROM generate_series(1, 12) n";
|
||||
let first = db.execute_from("ro", query, 0, 2, c, None).await?;
|
||||
let page = db.execute_from("ro", query, 2, 2, c, None).await?;
|
||||
let next = db.execute_from("ro", query, 4, 2, c, None).await?;
|
||||
assert_eq!(page.rows[0][0].as_deref(), Some("on"));
|
||||
assert_eq!(page.rows[0][..3], first.rows[0][..3]);
|
||||
assert_eq!(next.rows[0][..3], page.rows[0][..3]);
|
||||
assert_eq!(next.rows[0][3].as_deref(), Some("5"));
|
||||
db.release_result("ro", query, None);
|
||||
let expired = db.execute_from("ro", query, 6, 2, c, None).await.unwrap_err();
|
||||
assert!(expired.message.contains("Run the query again"), "{}", expired.message);
|
||||
let chosen = db.execute_from("ro", "SELECT current_schema()", 0, 1, c, Some("public")).await?;
|
||||
assert_eq!(chosen.rows, [[Some("public".into())]]);
|
||||
assert_eq!(db.execute("ro", "SELECT current_schema()", 1, c).await?.rows, [[Some("pg_catalog".into())]]);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn pooler_cancellation(db: &DbManager, c: &CancellationToken) -> IdeResult<()> {
|
||||
let writable = db.pool("rw").await?;
|
||||
let mode = "SHOW transaction_read_only";
|
||||
let stop = CancellationToken::new();
|
||||
let slow = "SELECT pg_sleep(10) AS oi_pooler_cancel";
|
||||
let (outcome, observed) = tokio::join!(db.execute("ro", slow, 1, &stop), async {
|
||||
for _ in 0..40 {
|
||||
let live = writable.rows("SELECT count(*) FROM pg_stat_activity WHERE state = 'active' AND query = 'SELECT pg_sleep(10) AS oi_pooler_cancel'", 1).await.unwrap();
|
||||
if live[0][0].as_deref() == Some("1") {
|
||||
stop.cancel();
|
||||
return true;
|
||||
}
|
||||
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
|
||||
}
|
||||
stop.cancel();
|
||||
false
|
||||
});
|
||||
assert!(observed, "the slow statement reached PostgreSQL before cancellation");
|
||||
assert_eq!(outcome.unwrap_err().kind, ide_core::error::ErrorKind::Cancelled);
|
||||
assert_eq!(db.execute("ro", mode, 1, c).await?.rows, [[Some("on".into())]]);
|
||||
let active = writable.rows("SELECT count(*) FROM pg_stat_activity WHERE state <> 'idle' AND query = 'SELECT pg_sleep(10) AS oi_pooler_cancel'", 1).await?;
|
||||
assert_eq!(active, [[Some("0".into())]]);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn manager(tmp: &tempfile::TempDir) -> Option<DbManager> {
|
||||
let (host, port, user, password) = server()?;
|
||||
let root = tmp.path().to_path_buf();
|
||||
@@ -572,3 +735,84 @@ async fn external_startup_does_not_block_another_source_and_disconnect_cancels_i
|
||||
assert!(matches!(result, Err(error) if error.kind == ide_core::error::ErrorKind::Cancelled));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn table_grants_expand_the_acl_per_grantee() -> IdeResult<()> {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let Some(db) = manager(&tmp).await else { return Ok(()) };
|
||||
let c = CancellationToken::new();
|
||||
for stmt in [
|
||||
"DROP SCHEMA IF EXISTS oi_grants CASCADE",
|
||||
"DROP ROLE IF EXISTS oi_grant_reader",
|
||||
"DROP ROLE IF EXISTS oi_grant_writer",
|
||||
"CREATE ROLE oi_grant_reader",
|
||||
"CREATE ROLE oi_grant_writer",
|
||||
"CREATE SCHEMA oi_grants",
|
||||
"CREATE TABLE oi_grants.shared (id INT)",
|
||||
"CREATE TABLE oi_grants.private (id INT)",
|
||||
"GRANT SELECT ON oi_grants.shared TO oi_grant_reader, PUBLIC",
|
||||
"GRANT INSERT, UPDATE ON oi_grants.shared TO oi_grant_writer WITH GRANT OPTION",
|
||||
] {
|
||||
db.execute("p", stmt, 10, &c).await?;
|
||||
}
|
||||
let owner = db.execute("p", "SELECT current_user", 1, &c).await?.rows[0][0].clone().unwrap();
|
||||
let grants = db.table_grants("p", "oi_grants", "shared").await?;
|
||||
let of = |grantee: &str| {
|
||||
let mut v: Vec<_> = grants
|
||||
.iter()
|
||||
.filter(|g| g.grantee == grantee)
|
||||
.map(|g| (g.privilege.as_str(), g.grantable, g.grantor.as_deref() == Some(owner.as_str())))
|
||||
.collect();
|
||||
v.sort();
|
||||
v
|
||||
};
|
||||
assert_eq!(of("oi_grant_reader"), [("SELECT", false, true)], "{grants:?}");
|
||||
assert_eq!(of("PUBLIC"), [("SELECT", false, true)], "{grants:?}");
|
||||
assert_eq!(of("oi_grant_writer"), [("INSERT", true, true), ("UPDATE", true, true)], "{grants:?}");
|
||||
assert!(of(&owner).contains(&("TRUNCATE", false, true)), "{grants:?}");
|
||||
// No ACL yet: the owner's implicit privileges.
|
||||
let private = db.table_grants("p", "oi_grants", "private").await?;
|
||||
assert!(private.iter().all(|g| g.grantee == owner), "{private:?}");
|
||||
assert!(private.iter().any(|g| g.privilege == "SELECT"), "{private:?}");
|
||||
for stmt in ["DROP SCHEMA oi_grants CASCADE", "DROP ROLE oi_grant_reader", "DROP ROLE oi_grant_writer"] {
|
||||
db.execute("p", stmt, 10, &c).await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Completion reads the default schema in full: 52,000 columns there passed the cap shared with
|
||||
/// the other schemas, and the tables sorting last lost theirs (#6118).
|
||||
#[tokio::test]
|
||||
async fn completion_reads_every_column_of_a_wide_default_schema() -> IdeResult<()> {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let Some(db) = manager(&tmp).await else { return Ok(()) };
|
||||
let c = CancellationToken::new();
|
||||
let schema = format!("oi_wide_{}", uuid::Uuid::new_v4().simple());
|
||||
let mut sources = db.sources()?;
|
||||
let mut source = sources[0].clone();
|
||||
source.id = "wide".into();
|
||||
source.options.startup_script = format!("SET search_path = {schema}");
|
||||
sources.push(source);
|
||||
let password = server().map(|(.., password)| password);
|
||||
db.save_sources(sources).await?;
|
||||
db.set_password("wide", password, false).await?;
|
||||
db.execute("p", &format!("CREATE SCHEMA {schema}"), 1, &c).await?;
|
||||
let fill = format!(
|
||||
"DO $$ DECLARE cols text; BEGIN \
|
||||
SELECT string_agg('c' || g || ' int', ', ') INTO cols FROM generate_series(1, 200) g; \
|
||||
FOR i IN 1..260 LOOP EXECUTE format('CREATE TABLE {schema}.t%s (%s)', lpad(i::text, 3, '0'), cols); \
|
||||
END LOOP; END $$"
|
||||
);
|
||||
let result = async {
|
||||
db.execute("p", &fill, 1, &c).await?;
|
||||
let completion = db.completion("wide").await?;
|
||||
assert_eq!(completion.default_schema, schema);
|
||||
let wide: Vec<_> = completion.tables.iter().filter(|t| t.schema == schema).collect();
|
||||
assert_eq!(wide.len(), 260);
|
||||
assert!(wide.iter().all(|t| t.columns.len() == 200), "a table lost columns");
|
||||
Ok(())
|
||||
}
|
||||
.await;
|
||||
db.execute("p", &format!("DROP SCHEMA {schema} CASCADE"), 1, &c).await?;
|
||||
result
|
||||
}
|
||||
@@ -187,7 +187,7 @@ async fn sqlserver_introspection_works_under_a_case_sensitive_collation() {
|
||||
let fk = ["dbo", "Child", "FK_Child_Parent", "ParentId", "dbo", "Parent", "Id"];
|
||||
assert_eq!(cells(pool.rows(&sql::table_foreign_keys(d, "dbo", "Child"), 100).await.unwrap()), [fk]);
|
||||
assert_eq!(cells(pool.rows(sql::foreign_keys(d), 100).await.unwrap()), [fk]);
|
||||
assert_eq!(cells(pool.rows(sql::completion_columns(d), 100).await.unwrap()).len(), 4);
|
||||
assert_eq!(cells(pool.rows(&sql::completion_columns(d, sql::CompletionScope::All), 100).await.unwrap()).len(), 4);
|
||||
assert_eq!(cells(pool.rows(&sql::routines(d, "dbo").unwrap(), 100).await.unwrap())[0][..2], ["Touch", "procedure"]);
|
||||
drop(pool);
|
||||
master
|
||||
|
||||
@@ -46,6 +46,13 @@ pub enum Capability {
|
||||
/// the manifest does not list; each answer applies to one host. Plain
|
||||
/// HTTP elsewhere always needs `net.http:<host>`.
|
||||
NetAsk,
|
||||
/// The host of the `string` setting `key`, approved when the user applies
|
||||
/// its value in Settings (`net:setting:server`, `net.http:setting:server`).
|
||||
/// HTTPS (and loopback HTTP) unless `http`.
|
||||
NetSetting {
|
||||
http: bool,
|
||||
key: String,
|
||||
},
|
||||
/// Unencrypted HTTP to one host.
|
||||
NetHttp(String),
|
||||
/// A local socket or named pipe on the project machine.
|
||||
@@ -62,6 +69,8 @@ pub enum Capability {
|
||||
/// Load the plugin's Java agent into the JVMs of Java run configurations. Never
|
||||
/// declared: it comes from `[[contributes.javaAgents]]`.
|
||||
JavaAgent,
|
||||
/// Fork a recorded native agent session into a new task in the open project (API 1.18).
|
||||
Agents,
|
||||
}
|
||||
|
||||
/// How a grant is presented (plan 4.2).
|
||||
@@ -87,11 +96,13 @@ impl Capability {
|
||||
| Self::VcsWrite
|
||||
| Self::Net(_)
|
||||
| Self::NetAsk
|
||||
| Self::NetSetting { .. }
|
||||
| Self::NetHttp(_)
|
||||
| Self::Secrets
|
||||
| Self::InputEvents
|
||||
| Self::Clipboard
|
||||
| Self::ClipboardRead => Risk::Medium,
|
||||
| Self::ClipboardRead
|
||||
| Self::Agents => Risk::Medium,
|
||||
// A trusted project's own files name the programs the IDE starts (its settings, its
|
||||
// build scripts), so writing them is running code.
|
||||
Self::ProjectWrite
|
||||
@@ -136,6 +147,12 @@ impl Capability {
|
||||
"Ask to connect to a host that is not on the list the first time it tries; you allow or refuse each host, and can revoke the allowed ones"
|
||||
.into()
|
||||
}
|
||||
Self::NetSetting { http, key } if *http => {
|
||||
format!("Connect to the host set in the `{key}` setting over unencrypted HTTP (from the machine the project is on)")
|
||||
}
|
||||
Self::NetSetting { http: _, key } => {
|
||||
format!("Connect to the host set in the `{key}` setting (from the machine the project is on)")
|
||||
}
|
||||
Self::NetHttp(host) => {
|
||||
format!("Connect to {host} over unencrypted HTTP (from the machine the project is on)")
|
||||
}
|
||||
@@ -149,6 +166,7 @@ impl Capability {
|
||||
Self::FsRead(path) => format!("Read files under {path}, outside the project"),
|
||||
Self::FsWrite(path) => format!("Change files under {path}, outside the project"),
|
||||
Self::JavaAgent => "Run code inside the Java applications you start".into(),
|
||||
Self::Agents => "Fork a recorded agent session into a new task in the open project".into(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -180,6 +198,19 @@ pub fn host_matches(pattern: &str, host: &str) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
/// Validates a manifest-style host (letters, digits and `-` labels, at most 253
|
||||
/// bytes) and returns it lowercased. A `*` is never valid here — only a
|
||||
/// `net:`/`net.http:` grant itself may carry the `*.` subdomain pattern, and a
|
||||
/// host taken from a setting value never does.
|
||||
pub fn manifest_host(host: &str) -> Result<String, String> {
|
||||
let valid = !host.is_empty()
|
||||
&& host.len() <= 253
|
||||
&& host.split('.').all(|label| {
|
||||
!label.is_empty() && label.len() <= 63 && label.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-')
|
||||
});
|
||||
valid.then(|| host.to_ascii_lowercase()).ok_or_else(|| "invalid host".into())
|
||||
}
|
||||
|
||||
/// Validates a socket path; a grant may use `*` in its last segment only.
|
||||
pub fn validate_ipc_name(name: &str, pattern: bool) -> Result<(), String> {
|
||||
let pipe = name.starts_with(r"\\.\pipe\");
|
||||
@@ -269,6 +300,8 @@ impl fmt::Display for Capability {
|
||||
Self::ClipboardRead => f.write_str("clipboard.read"),
|
||||
Self::Net(h) => write!(f, "net:{h}"),
|
||||
Self::NetAsk => f.write_str("net:ask"),
|
||||
Self::NetSetting { http, key } if *http => write!(f, "net.http:setting:{key}"),
|
||||
Self::NetSetting { http: _, key } => write!(f, "net:setting:{key}"),
|
||||
Self::NetHttp(h) => write!(f, "net.http:{h}"),
|
||||
Self::Ipc(p) => write!(f, "ipc:{p}"),
|
||||
Self::Process(b) => write!(f, "process:{b}"),
|
||||
@@ -276,6 +309,7 @@ impl fmt::Display for Capability {
|
||||
Self::FsRead(p) => write!(f, "fs.read:{p}"),
|
||||
Self::FsWrite(p) => write!(f, "fs.write:{p}"),
|
||||
Self::JavaAgent => f.write_str("java.agent"),
|
||||
Self::Agents => f.write_str("agents"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -295,23 +329,27 @@ impl FromStr for Capability {
|
||||
if kind == "net" && arg == "ask" {
|
||||
return Ok(Self::NetAsk);
|
||||
}
|
||||
let host = arg.strip_prefix("*.").unwrap_or(arg);
|
||||
let valid = !host.is_empty()
|
||||
&& host.len() <= 253
|
||||
&& host.split('.').all(|label| {
|
||||
!label.is_empty()
|
||||
&& label.len() <= 63
|
||||
&& label.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-')
|
||||
});
|
||||
if valid {
|
||||
Ok(if kind == "net" {
|
||||
Self::Net(arg.to_ascii_lowercase())
|
||||
// `net:setting:<key>` names the plugin's `string` setting the
|
||||
// host comes from; the same key rule as a settings schema.
|
||||
if let Some(key) = arg.strip_prefix("setting:") {
|
||||
let valid_key = !key.is_empty()
|
||||
&& key.len() <= 64
|
||||
&& key.chars().all(|c| c.is_ascii_alphanumeric() || "-_.".contains(c));
|
||||
return if valid_key {
|
||||
Ok(Self::NetSetting { http: kind == "net.http", key: key.to_owned() })
|
||||
} else {
|
||||
Self::NetHttp(arg.to_ascii_lowercase())
|
||||
})
|
||||
} else {
|
||||
Err(format!("invalid host in {s:?}"))
|
||||
Err(format!("invalid setting key in {s:?}"))
|
||||
};
|
||||
}
|
||||
manifest_host(arg.strip_prefix("*.").unwrap_or(arg))
|
||||
.map(|_| {
|
||||
if kind == "net" {
|
||||
Self::Net(arg.to_ascii_lowercase())
|
||||
} else {
|
||||
Self::NetHttp(arg.to_ascii_lowercase())
|
||||
}
|
||||
})
|
||||
.map_err(|_| format!("invalid host in {s:?}"))
|
||||
}
|
||||
"ipc" => {
|
||||
validate_ipc_name(arg, true)?;
|
||||
@@ -355,6 +393,7 @@ impl FromStr for Capability {
|
||||
"clipboard" => Self::Clipboard,
|
||||
"clipboard.read" => Self::ClipboardRead,
|
||||
"java.agent" => Self::JavaAgent,
|
||||
"agents" => Self::Agents,
|
||||
_ => return Err(format!("unknown capability {s:?}")),
|
||||
})
|
||||
}
|
||||
@@ -549,6 +588,77 @@ mod net_ask_tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod net_setting_tests {
|
||||
use super::*;
|
||||
|
||||
/// `net:setting:<key>` names a settings key instead of a host: the host
|
||||
/// comes from the setting's value and is approved when the user sets it
|
||||
/// (#3809).
|
||||
#[test]
|
||||
fn setting_derived_grants_parse_and_print() {
|
||||
for s in ["net:setting:server", "net.http:setting:server"] {
|
||||
let cap: Capability = s.parse().unwrap();
|
||||
assert_eq!(cap.to_string(), s, "{s}");
|
||||
assert_eq!(cap.risk(), Risk::Medium, "{s}");
|
||||
}
|
||||
assert_eq!(
|
||||
"net:setting:server".parse::<Capability>().unwrap(),
|
||||
Capability::NetSetting { http: false, key: "server".into() }
|
||||
);
|
||||
assert_eq!(
|
||||
"net.http:setting:server".parse::<Capability>().unwrap(),
|
||||
Capability::NetSetting { http: true, key: "server".into() }
|
||||
);
|
||||
assert!(!"net:setting:server".parse::<Capability>().unwrap().auto_migrates());
|
||||
let derived = "net:setting:server".parse::<Capability>().unwrap();
|
||||
assert!(derived.describe().contains("`server`"));
|
||||
assert!("net.http:setting:server".parse::<Capability>().unwrap().describe().contains("unencrypted"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn setting_derived_grants_stay_strict() {
|
||||
for s in ["net:setting:", "net:setting:a b", "net:setting:a:b", "net.http:setting:"] {
|
||||
assert!(s.parse::<Capability>().is_err(), "{s}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The derivation covers nothing by itself: a literal-host grant and a
|
||||
/// setting-derived grant are different grants, and the host materializes
|
||||
/// only after the user approves the setting's value.
|
||||
#[test]
|
||||
fn derived_grants_do_not_cover_literal_hosts() {
|
||||
let derived: Capability = "net:setting:server".parse().unwrap();
|
||||
let literal: Capability = "net:gitlab.intranet.example".parse().unwrap();
|
||||
assert!(!derived.covers(&literal));
|
||||
assert!(!literal.covers(&derived));
|
||||
assert!(!derived.covers(&"net.http:gitlab.intranet.example".parse().unwrap()));
|
||||
assert!(!derived.covers(&"net:setting:other".parse().unwrap()));
|
||||
}
|
||||
|
||||
/// The host of a setting value passes the same rules as a manifest host,
|
||||
/// and a `*` is refused (`net:*` stays impossible).
|
||||
#[test]
|
||||
fn value_hosts_follow_the_manifest_host_rules() {
|
||||
assert_eq!(manifest_host("GitLab.Intranet.Example").unwrap(), "gitlab.intranet.example");
|
||||
for bad in
|
||||
["", "*", "*.example.com", "a b", "under_score.example", "gitlab.intranet.example.", &"a".repeat(254)]
|
||||
{
|
||||
assert!(manifest_host(bad).is_err(), "{bad}");
|
||||
}
|
||||
let long = ["a".repeat(61), "b".repeat(61), "c".repeat(61), "d".repeat(61)].join(".");
|
||||
assert_eq!(long.len(), 247);
|
||||
assert!(manifest_host(&long).is_ok());
|
||||
assert!(
|
||||
manifest_host(&["a".repeat(63), "b".repeat(63), "c".repeat(63), "d".repeat(63)].join(".")).is_err(),
|
||||
"over 253 bytes"
|
||||
);
|
||||
assert!(manifest_host(&"a".repeat(64)).is_err(), "over 63 bytes per label");
|
||||
// Pattern grants keep working: only a value (and a bare host) refuses `*`.
|
||||
assert!("net:*.github.com".parse::<Capability>().is_ok());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod database_tests {
|
||||
use super::*;
|
||||
|
||||
@@ -58,6 +58,10 @@ pub struct Grant {
|
||||
/// Exact hosts approved through `net:ask`, separate from manifest grants.
|
||||
#[serde(default)]
|
||||
pub net_hosts: BTreeSet<String>,
|
||||
/// Hosts approved for `net:setting:<key>` / `net.http:setting:<key>`
|
||||
/// grants, keyed by the grant: the user approved the value in Settings.
|
||||
#[serde(default)]
|
||||
pub setting_hosts: BTreeMap<String, String>,
|
||||
/// Optional capabilities the user declined (not asked again until re-confirmed).
|
||||
#[serde(default)]
|
||||
pub declined: BTreeSet<String>,
|
||||
@@ -209,6 +213,7 @@ impl Ledger {
|
||||
if !req.required.iter().chain(&req.optional).any(|c| c == &Capability::NetAsk) {
|
||||
grant.net_hosts.clear();
|
||||
}
|
||||
retain_setting_hosts(grant, req);
|
||||
if !grant.confirmed {
|
||||
return Decision::NeedsConfirmation { new: req.required.clone(), first_time: true };
|
||||
}
|
||||
@@ -236,6 +241,7 @@ impl Ledger {
|
||||
if !req.required.iter().chain(&req.optional).any(|c| c == &Capability::NetAsk) {
|
||||
grant.net_hosts.clear();
|
||||
}
|
||||
retain_setting_hosts(grant, req);
|
||||
grant.plugin_id = req.plugin_id.to_owned();
|
||||
grant.version = req.version.to_owned();
|
||||
grant.package_hash = req.package_hash.to_owned();
|
||||
@@ -269,6 +275,9 @@ impl Ledger {
|
||||
if cap == &Capability::NetAsk {
|
||||
grant.net_hosts.clear();
|
||||
}
|
||||
if matches!(cap, Capability::NetSetting { .. }) {
|
||||
grant.setting_hosts.remove(&s);
|
||||
}
|
||||
if let Capability::Process(_) | Capability::JavaAgent = cap {
|
||||
grant.binaries.remove(&s);
|
||||
for binaries in grant.project_binaries.values_mut() {
|
||||
@@ -292,6 +301,21 @@ impl Ledger {
|
||||
self.grants.get_mut(subject).is_some_and(|g| g.net_hosts.remove(host))
|
||||
}
|
||||
|
||||
/// Remembers the host the user approved for a `net:setting:` grant: it
|
||||
/// covers requests only while the setting still holds it.
|
||||
pub fn remember_setting_host(&mut self, subject: &Subject, cap: &Capability, host: &str) -> bool {
|
||||
let Some(grant) = self.grants.get_mut(subject) else { return false };
|
||||
if !grant.confirmed || !grant.has(cap) || host.contains('*') {
|
||||
return false;
|
||||
}
|
||||
grant.setting_hosts.insert(cap.to_string(), host.to_owned());
|
||||
true
|
||||
}
|
||||
|
||||
pub fn forget_setting_host(&mut self, subject: &Subject, cap: &Capability) -> bool {
|
||||
self.grants.get_mut(subject).is_some_and(|g| g.setting_hosts.remove(&cap.to_string()).is_some())
|
||||
}
|
||||
|
||||
/// Records the program approved for a `process:` grant (or the jar of a `java.agent` one).
|
||||
pub fn set_binary(&mut self, subject: &Subject, cap: &Capability, binary: BinaryGrant) {
|
||||
if let Some(grant) = self.grants.get_mut(subject) {
|
||||
@@ -393,6 +417,19 @@ pub fn by_risk(caps: &[Capability]) -> Vec<(Risk, Vec<Capability>)> {
|
||||
groups.into_iter().map(|(r, v)| (r.0, v)).collect()
|
||||
}
|
||||
|
||||
/// Drops setting-derived hosts the manifest no longer asks for, like
|
||||
/// `net_hosts` are dropped when `net:ask` is removed.
|
||||
fn retain_setting_hosts(grant: &mut Grant, req: &Request<'_>) {
|
||||
let declared: Vec<String> = req
|
||||
.required
|
||||
.iter()
|
||||
.chain(&req.optional)
|
||||
.filter(|c| matches!(c, Capability::NetSetting { .. }))
|
||||
.map(|c| c.to_string())
|
||||
.collect();
|
||||
grant.setting_hosts.retain(|cap, _| declared.contains(cap));
|
||||
}
|
||||
|
||||
/// Pins an explicitly selected executable, retaining a multicall shim's filename.
|
||||
pub fn approve_program(path: &Path) -> Result<BinaryGrant, String> {
|
||||
if !path.is_absolute() || !is_executable(path) {
|
||||
@@ -589,6 +626,58 @@ mod tests {
|
||||
assert!(l.get(&r.subject).unwrap().net_hosts.is_empty());
|
||||
}
|
||||
|
||||
/// A setting-derived host is approved per grant, survives re-confirmation,
|
||||
/// is replaced by the next approval, and goes when the grant or the
|
||||
/// manifest declaration goes (#3809).
|
||||
#[test]
|
||||
fn setting_hosts_are_approved_per_grant_and_drop_with_it() {
|
||||
let mut l = Ledger::in_memory();
|
||||
let r = req("1.0.0", "h", &["project.read"], &["net:setting:server", "net.http:setting:server"]);
|
||||
l.confirm(
|
||||
&r,
|
||||
&["net:setting:server".parse().unwrap(), "net.http:setting:server".parse().unwrap()],
|
||||
BTreeMap::new(),
|
||||
);
|
||||
let cap: Capability = "net:setting:server".parse().unwrap();
|
||||
let other: Capability = "net.http:setting:server".parse().unwrap();
|
||||
|
||||
// Not granted (declined optional, or not confirmed): refused.
|
||||
let declined = req("1.0.0", "h", &["project.read"], &["net:setting:server"]);
|
||||
let mut l2 = Ledger::in_memory();
|
||||
l2.confirm(&declined, &[], BTreeMap::new());
|
||||
assert!(!l2.remember_setting_host(&declined.subject, &cap, "jira.corp.example"), "declined optional");
|
||||
let never = req("1.0.0", "h", &["project.read"], &[]);
|
||||
let mut l3 = Ledger::in_memory();
|
||||
assert!(!l3.remember_setting_host(&never.subject, &cap, "jira.corp.example"), "never confirmed");
|
||||
|
||||
assert!(l.remember_setting_host(&r.subject, &cap, "gitlab.intranet.example"));
|
||||
assert!(!l.remember_setting_host(&r.subject, &cap, "*"), "a wildcard value is refused");
|
||||
assert_eq!(
|
||||
l.get(&r.subject).unwrap().setting_hosts.get("net:setting:server").map(String::as_str),
|
||||
Some("gitlab.intranet.example")
|
||||
);
|
||||
// The other transport is its own record; the derived grant itself covers no host.
|
||||
assert!(l.remember_setting_host(&r.subject, &other, "jira.corp.example"));
|
||||
assert!(!l.get(&r.subject).unwrap().has(&Capability::Net("gitlab.intranet.example".into())));
|
||||
// Re-confirmation keeps the approval; a manifest that drops the grant drops the record.
|
||||
l.confirm(&r, &["net:setting:server".parse().unwrap()], BTreeMap::new());
|
||||
assert_eq!(
|
||||
l.get(&r.subject).unwrap().setting_hosts.get("net:setting:server").map(String::as_str),
|
||||
Some("gitlab.intranet.example")
|
||||
);
|
||||
let without = req("2.0.0", "h2", &["project.read"], &[]);
|
||||
assert!(matches!(l.decide(&without), Decision::Allowed { .. }), "same or fewer needs: silent");
|
||||
assert!(l.get(&r.subject).unwrap().setting_hosts.is_empty(), "records follow the manifest");
|
||||
|
||||
// Revoking the capability clears its record.
|
||||
l.confirm(&r, &["net:setting:server".parse().unwrap()], BTreeMap::new());
|
||||
l.remember_setting_host(&r.subject, &cap, "gitlab.intranet.example");
|
||||
assert!(l.set(&r.subject, &cap, false));
|
||||
assert!(l.get(&r.subject).unwrap().setting_hosts.is_empty());
|
||||
// Forgetting without a record is an error.
|
||||
assert!(!l.forget_setting_host(&r.subject, &cap));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn migration_grants_low_risk_only() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -26,7 +26,9 @@ mod resolve;
|
||||
mod ui;
|
||||
mod when;
|
||||
|
||||
pub use capability::{Capability, CapabilityInfo, Risk, expand_ipc_name, host_matches, validate_ipc_name};
|
||||
pub use capability::{
|
||||
Capability, CapabilityInfo, Risk, expand_ipc_name, host_matches, manifest_host, validate_ipc_name,
|
||||
};
|
||||
pub use index::ContributionIndex;
|
||||
pub use manifest::{
|
||||
ActivationEvent, CATEGORIES, Capabilities, ENGINE_VERSION, EVENT_KINDS, LEGACY_API, MANIFEST_FILE, MAX_CATEGORIES,
|
||||
|
||||
@@ -34,7 +34,7 @@ use std::path::{Component, Path, PathBuf};
|
||||
|
||||
pub const MANIFEST_FILE: &str = "plugin.toml";
|
||||
/// The plugin API (engine) version this host implements.
|
||||
pub const ENGINE_VERSION: &str = "1.16.0";
|
||||
pub const ENGINE_VERSION: &str = "1.18.0";
|
||||
/// The 0.1 API, still accepted for contribution-only packages and 0.1 components.
|
||||
pub const LEGACY_API: &str = "0.1";
|
||||
/// Marketplace categories, in the order they are shown.
|
||||
@@ -168,6 +168,8 @@ pub const EVENT_KINDS: &[&str] = &[
|
||||
"action-performed",
|
||||
"vcs-changed",
|
||||
"problems-changed",
|
||||
"project-closed",
|
||||
"watched-files-changed",
|
||||
];
|
||||
|
||||
impl std::fmt::Display for ActivationEvent {
|
||||
@@ -367,6 +369,12 @@ impl Manifest {
|
||||
if matches!(cap, Capability::ClipboardRead) {
|
||||
self.needs_api(&format!("capability `{cap}`"), 11)?;
|
||||
}
|
||||
if matches!(cap, Capability::Agents) {
|
||||
self.needs_api(&format!("capability `{cap}`"), 18)?;
|
||||
}
|
||||
if matches!(cap, Capability::NetSetting { .. }) {
|
||||
self.needs_api(&format!("capability `{cap}`"), 18)?;
|
||||
}
|
||||
if matches!(cap, Capability::JavaAgent) {
|
||||
return Err(
|
||||
"`java.agent` comes from `[[contributes.javaAgents]]`: remove it from [capabilities]".into()
|
||||
@@ -403,6 +411,10 @@ impl Manifest {
|
||||
if matches!(event, ActivationEvent::Event(kind) if kind == "files-changed") {
|
||||
self.needs_api("`on-event:files-changed`", 3)?;
|
||||
}
|
||||
if matches!(event, ActivationEvent::Event(kind) if kind == "project-closed" || kind == "watched-files-changed")
|
||||
{
|
||||
self.needs_api(&format!("`{event}`"), 18)?;
|
||||
}
|
||||
if !seen.insert(event) {
|
||||
return Err(format!("duplicate activation event {event}"));
|
||||
}
|
||||
@@ -758,6 +770,20 @@ required = [\"lsp:phoxite\"]
|
||||
assert_eq!(m.capabilities.optional, [Capability::ClipboardRead]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn setting_derived_net_capabilities_need_the_current_api_minor() {
|
||||
for cap in ["net:setting:server", "net.http:setting:server"] {
|
||||
let caps = format!("[capabilities]\noptional = [\"{cap}\"]\n");
|
||||
assert!(
|
||||
err(&format!("{}{caps}", BASE.replace("^1.2", "^1.17"))).contains("new in plugin API 1.18"),
|
||||
"{cap}"
|
||||
);
|
||||
let m = Manifest::parse(&format!("{}{caps}", BASE.replace("^1.2", "^1.18"))).unwrap();
|
||||
assert_eq!(m.capabilities.optional.len(), 1, "{cap}");
|
||||
assert_eq!(m.capabilities.optional[0].to_string(), cap);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn java_agent_capability_is_not_declared() {
|
||||
for list in ["required", "optional"] {
|
||||
@@ -962,4 +988,21 @@ mod net_ask_api_tests {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn project_closed_and_watched_files_events_require_api_1_18() {
|
||||
for kind in ["project-closed", "watched-files-changed"] {
|
||||
for engine in ["^1.17", "^1.18"] {
|
||||
let manifest = format!(
|
||||
"id = 'test'\nname = 'Test'\nversion = '0.1.0'\nwasm = 'plugin.wasm'\nengines.openidea = '{engine}'\nactivation = [\"on-event:{kind}\"]\n"
|
||||
);
|
||||
let parsed = Manifest::parse(&manifest);
|
||||
if engine == "^1.18" {
|
||||
parsed.unwrap();
|
||||
} else {
|
||||
assert!(parsed.unwrap_err().contains("new in plugin API 1.18"), "{kind} {engine}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -66,7 +66,12 @@ serde_json = { workspace = true, features = ["raw_value"] }
|
||||
toml.workspace = true
|
||||
specta.workspace = true
|
||||
specta-typescript.workspace = true
|
||||
tokio = { workspace = true, features = ["io-std"] }
|
||||
bytes = "1"
|
||||
flate2.workspace = true
|
||||
http-body-util = "0.1"
|
||||
hyper = { version = "1", features = ["http1", "server"] }
|
||||
hyper-util = { version = "0.1", default-features = false, features = ["tokio"] }
|
||||
tokio = { workspace = true, features = ["io-std", "net", "signal"] }
|
||||
tracing.workspace = true
|
||||
url = "2"
|
||||
tracing-subscriber.workspace = true
|
||||
|
||||
@@ -1,11 +1,16 @@
|
||||
//! `openidea-server`: the IDE backend for remote development, either serving one
|
||||
//! desktop client over stdin / stdout (`--stdio`) or running as a persistent
|
||||
//! per-project daemon (`--attach <project>`).
|
||||
//! `openidea-server`: the headless IDE backend.
|
||||
//!
|
||||
//! * `--stdio`: JSON-RPC over stdin/stdout for SSH / remote development clients.
|
||||
//! * `--attach <project>`: persistent per-project remote development daemon.
|
||||
//! * `--web`: HTTP + WebSocket server exposing the full OpenIDEA web interface on a configurable port.
|
||||
//! * `--mcp-stdio`: MCP stdio bridge.
|
||||
//! * `--connect <host> <port>`: TCP relay over stdin/stdout.
|
||||
|
||||
use ide_host::catalogue::TrustClass;
|
||||
use ide_host::plugins::remote::{RemotePluginLanguages, SYNC_COMMAND};
|
||||
use ide_host::plugins::remote_host::RemotePlugins;
|
||||
use ide_host::rpc::{self, Dispatcher};
|
||||
use ide_host::web_server::{self, WebServerConfig};
|
||||
use ide_host::{Host, HostConfig};
|
||||
use ide_language::LanguageRegistry;
|
||||
use std::path::PathBuf;
|
||||
@@ -17,6 +22,126 @@ enum Mode {
|
||||
Daemon(PathBuf, ide_host::daemon::BuildId),
|
||||
}
|
||||
|
||||
fn print_usage() {
|
||||
eprintln!(
|
||||
"\
|
||||
usage:
|
||||
openidea-server --web [options] [<project>]
|
||||
openidea-server --stdio
|
||||
openidea-server --attach <project-path>
|
||||
openidea-server --mcp-stdio [--project <path>]
|
||||
openidea-server --connect <host> <port>
|
||||
openidea-server --version
|
||||
|
||||
web mode options:
|
||||
--host <addr> Bind address (default: $OPENIDEA_HOST or 127.0.0.1)
|
||||
--port <port> Listen port (default: $OPENIDEA_PORT or 8080)
|
||||
--base-path <prefix> Optional reverse-proxy URL prefix (default: $OPENIDEA_BASE_PATH)
|
||||
--web-dir <dir> Built frontend directory (default: $OPENIDEA_WEB_DIR or auto-detected dist/)
|
||||
--project <path> Workspace directory to open on startup (default: $OPENIDEA_WORKSPACE_DIR)
|
||||
--home <dir> Persistent config/data directory (default: $OPENIDEA_SERVER_HOME or ~/.openidea)
|
||||
--token <secret|auto> Access token ($OPENIDEA_WEB_TOKEN; default: auto-generated random token)
|
||||
--no-auth Disable token auth ($OPENIDEA_WEB_NO_AUTH=1; use only behind an authenticating proxy)
|
||||
--no-trust-project Prompt before trusting --project instead of trusting it automatically"
|
||||
);
|
||||
}
|
||||
|
||||
struct ParsedWebArgs {
|
||||
config: WebServerConfig,
|
||||
home_override: Option<PathBuf>,
|
||||
}
|
||||
|
||||
fn env_truthy(name: &str) -> bool {
|
||||
std::env::var(name).ok().is_some_and(|v| matches!(v.trim().to_ascii_lowercase().as_str(), "1" | "true" | "yes"))
|
||||
}
|
||||
|
||||
fn parse_web_args(args: &[String]) -> Result<ParsedWebArgs, String> {
|
||||
let mut host = std::env::var("OPENIDEA_HOST").unwrap_or_else(|_| "127.0.0.1".into());
|
||||
let mut port: u16 = match std::env::var("OPENIDEA_PORT") {
|
||||
Ok(raw) if !raw.trim().is_empty() => {
|
||||
raw.trim().parse::<u16>().map_err(|_| format!("invalid OPENIDEA_PORT value: {raw}"))?
|
||||
}
|
||||
_ => 8080,
|
||||
};
|
||||
let mut base_path = std::env::var("OPENIDEA_BASE_PATH").ok().filter(|s| !s.trim().is_empty());
|
||||
let mut web_dir = web_server::default_web_dir();
|
||||
let mut project = std::env::var_os("OPENIDEA_WORKSPACE_DIR")
|
||||
.or_else(|| std::env::var_os("OPENIDEA_PROJECT"))
|
||||
.filter(|s| !s.is_empty())
|
||||
.map(PathBuf::from);
|
||||
let mut trust_project = true;
|
||||
let mut no_auth = env_truthy("OPENIDEA_WEB_NO_AUTH");
|
||||
let mut auth_token = std::env::var("OPENIDEA_WEB_TOKEN").ok().filter(|s| !s.trim().is_empty());
|
||||
let mut home_override: Option<PathBuf> = None;
|
||||
|
||||
let mut i = 0;
|
||||
while i < args.len() {
|
||||
let arg = args[i].as_str();
|
||||
let next_val = |i: &mut usize, flag: &str| -> Result<String, String> {
|
||||
*i += 1;
|
||||
args.get(*i).cloned().ok_or_else(|| format!("missing value for {flag}"))
|
||||
};
|
||||
if arg == "--web" {
|
||||
i += 1;
|
||||
continue;
|
||||
} else if arg == "--host" {
|
||||
host = next_val(&mut i, "--host")?;
|
||||
} else if let Some(v) = arg.strip_prefix("--host=") {
|
||||
host = v.to_owned();
|
||||
} else if arg == "--port" || arg == "-p" {
|
||||
let v = next_val(&mut i, arg)?;
|
||||
port = v.parse::<u16>().map_err(|_| format!("invalid port: {v}"))?;
|
||||
} else if let Some(v) = arg.strip_prefix("--port=") {
|
||||
port = v.parse::<u16>().map_err(|_| format!("invalid port: {v}"))?;
|
||||
} else if arg == "--base-path" {
|
||||
base_path = Some(next_val(&mut i, "--base-path")?);
|
||||
} else if let Some(v) = arg.strip_prefix("--base-path=") {
|
||||
base_path = Some(v.to_owned());
|
||||
} else if arg == "--web-dir" {
|
||||
web_dir = PathBuf::from(next_val(&mut i, "--web-dir")?);
|
||||
} else if let Some(v) = arg.strip_prefix("--web-dir=") {
|
||||
web_dir = PathBuf::from(v);
|
||||
} else if arg == "--project" || arg == "--workspace" {
|
||||
project = Some(PathBuf::from(next_val(&mut i, arg)?));
|
||||
} else if let Some(v) = arg.strip_prefix("--project=").or_else(|| arg.strip_prefix("--workspace=")) {
|
||||
project = Some(PathBuf::from(v));
|
||||
} else if arg == "--home" {
|
||||
home_override = Some(PathBuf::from(next_val(&mut i, "--home")?));
|
||||
} else if let Some(v) = arg.strip_prefix("--home=") {
|
||||
home_override = Some(PathBuf::from(v));
|
||||
} else if arg == "--token" {
|
||||
auth_token = Some(next_val(&mut i, "--token")?);
|
||||
no_auth = false;
|
||||
} else if let Some(v) = arg.strip_prefix("--token=") {
|
||||
auth_token = Some(v.to_owned());
|
||||
no_auth = false;
|
||||
} else if arg == "--no-auth" {
|
||||
auth_token = None;
|
||||
no_auth = true;
|
||||
} else if arg == "--no-trust-project" {
|
||||
trust_project = false;
|
||||
} else if arg.starts_with('-') {
|
||||
return Err(format!("unknown option: {arg}"));
|
||||
} else if project.is_none() {
|
||||
project = Some(PathBuf::from(arg));
|
||||
} else {
|
||||
return Err(format!("unexpected positional argument: {arg}"));
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
|
||||
if no_auth {
|
||||
auth_token = None;
|
||||
} else if auth_token.is_none() || auth_token.as_deref() == Some("auto") {
|
||||
auth_token = Some(web_server::generate_token());
|
||||
}
|
||||
|
||||
Ok(ParsedWebArgs {
|
||||
config: WebServerConfig { host, port, base_path, web_dir, project, trust_project, auth_token },
|
||||
home_override,
|
||||
})
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let raw_args: Vec<String> = std::env::args().collect();
|
||||
if let Some(project) = ide_mcp::stdio_request(&raw_args) {
|
||||
@@ -28,6 +153,10 @@ fn main() {
|
||||
println!("openidea-server {} (protocol {})", env!("CARGO_PKG_VERSION"), rpc::PROTOCOL_VERSION);
|
||||
return;
|
||||
}
|
||||
if args.iter().any(|a| a == "--help" || a == "-h") {
|
||||
print_usage();
|
||||
return;
|
||||
}
|
||||
if args.first().is_some_and(|a| a == "--connect") {
|
||||
// One forwarded connection (see `ide_host::relay`): stdout carries its bytes.
|
||||
let code = match ide_host::relay::parse_args(&args[1..]).and_then(|(host, port)| {
|
||||
@@ -42,24 +171,57 @@ fn main() {
|
||||
};
|
||||
std::process::exit(code);
|
||||
}
|
||||
|
||||
let base = server_home();
|
||||
#[cfg(unix)]
|
||||
if args.first().is_some_and(|a| a == "--attach") {
|
||||
let Some(project_path) = args.get(1).filter(|p| !p.is_empty()) else {
|
||||
eprintln!("usage: openidea-server --attach <project-path>");
|
||||
eprintln!("usage: openidea-server --attach <project-path> [--replace]");
|
||||
std::process::exit(2);
|
||||
};
|
||||
// `--replace`: stop another build's backend that still holds the project.
|
||||
let replace = args.get(2).is_some_and(|a| a == "--replace");
|
||||
let home = dirs::home_dir().unwrap_or_default();
|
||||
let code =
|
||||
match ide_host::daemon::attach(&base, &home, project_path, std::io::stdin(), std::io::stdout().lock()) {
|
||||
Ok(()) => 0,
|
||||
Err(e) => {
|
||||
eprintln!("{e}");
|
||||
1
|
||||
}
|
||||
};
|
||||
let code = match ide_host::daemon::attach(
|
||||
&base,
|
||||
&home,
|
||||
project_path,
|
||||
replace,
|
||||
std::io::stdin(),
|
||||
std::io::stdout().lock(),
|
||||
) {
|
||||
Ok(()) => 0,
|
||||
Err(e) => {
|
||||
eprintln!("{e}");
|
||||
1
|
||||
}
|
||||
};
|
||||
std::process::exit(code);
|
||||
}
|
||||
|
||||
if args.iter().any(|a| a == "--web") {
|
||||
let parsed = match parse_web_args(&args) {
|
||||
Ok(p) => p,
|
||||
Err(e) => {
|
||||
eprintln!("error: {e}");
|
||||
print_usage();
|
||||
std::process::exit(2);
|
||||
}
|
||||
};
|
||||
init_tracing();
|
||||
let base = parsed.home_override.unwrap_or(base);
|
||||
init_process_env(&base);
|
||||
let worker_threads = std::thread::available_parallelism().map(|n| n.get()).unwrap_or(2).clamp(2, 8);
|
||||
let runtime = tokio::runtime::Builder::new_multi_thread()
|
||||
.worker_threads(worker_threads)
|
||||
.max_blocking_threads(32)
|
||||
.enable_all()
|
||||
.build()
|
||||
.expect("tokio runtime");
|
||||
let code = runtime.block_on(web_server::run(parsed.config, base));
|
||||
std::process::exit(code);
|
||||
}
|
||||
|
||||
let mode = match args.as_slice() {
|
||||
#[cfg(unix)]
|
||||
[flag, sock, build] if flag == "--daemon" => {
|
||||
@@ -73,27 +235,33 @@ fn main() {
|
||||
[flag, _] if flag == "--attach" => Mode::Stdio,
|
||||
_ if args.iter().any(|a| a == "--stdio") => Mode::Stdio,
|
||||
_ => {
|
||||
eprintln!(
|
||||
"usage: openidea-server --stdio | --attach <project-path> | --mcp-stdio [--project <path>] | --connect <host> <port> | --version"
|
||||
);
|
||||
print_usage();
|
||||
std::process::exit(2);
|
||||
}
|
||||
};
|
||||
// stdout carries the protocol: logs go to stderr.
|
||||
init_tracing();
|
||||
init_process_env(&base);
|
||||
let runtime = tokio::runtime::Builder::new_multi_thread().enable_all().build().expect("tokio runtime");
|
||||
let code = runtime.block_on(run(base, mode));
|
||||
std::process::exit(code);
|
||||
}
|
||||
|
||||
fn init_tracing() {
|
||||
// stdout carries the protocol in --stdio mode: logs always go to stderr.
|
||||
tracing_subscriber::fmt()
|
||||
.with_writer(std::io::stderr)
|
||||
.with_env_filter(tracing_subscriber::EnvFilter::try_from_env("OPENIDEA_LOG").unwrap_or_else(|_| "info".into()))
|
||||
.init();
|
||||
// An SSH exec channel gets a minimal environment: take the login shell's, read
|
||||
// afresh on every start, plus the IDE-managed tools. Before any other thread starts.
|
||||
}
|
||||
|
||||
fn init_process_env(base: &std::path::Path) {
|
||||
// An SSH exec channel or container entrypoint gets a minimal environment: inherit login shell
|
||||
// env plus IDE-managed tools before any other thread starts.
|
||||
ide_host::shell_env::inherit_login_shell_env("openidea-server");
|
||||
let data_dir = base.join("data");
|
||||
ide_tools::extend_process_path(&data_dir);
|
||||
ide_dap::adapter::set_tools_root(ide_tools::tools_dir(&data_dir));
|
||||
ide_sdk::java::add_jdk_root(&ide_tools::jdk::jdks_dir(&data_dir));
|
||||
let runtime = tokio::runtime::Builder::new_multi_thread().enable_all().build().expect("tokio runtime");
|
||||
let code = runtime.block_on(run(base, mode));
|
||||
std::process::exit(code);
|
||||
}
|
||||
|
||||
fn server_home() -> PathBuf {
|
||||
|
||||
@@ -121,11 +121,13 @@ fn ensure_private_dir(dir: &Path) -> io::Result<()> {
|
||||
}
|
||||
|
||||
/// Connects to the daemon for `project_path` (spawning it if needed) and bridges
|
||||
/// `input` / `output` to its Unix socket.
|
||||
/// `input` / `output` to its Unix socket. With `replace`, a daemon of another build that
|
||||
/// refuses to retire is stopped first.
|
||||
pub fn attach(
|
||||
base: &Path,
|
||||
home: &Path,
|
||||
project_path: &str,
|
||||
replace: bool,
|
||||
input: impl Read + Send + 'static,
|
||||
output: impl Write,
|
||||
) -> Result<(), String> {
|
||||
@@ -137,11 +139,11 @@ pub fn attach(
|
||||
.map_err(|e| format!("cannot identify openidea-server build: {e}"))?;
|
||||
let hex = hasher.finalize().to_hex();
|
||||
let build = &hex.as_str()[..16];
|
||||
let stream = connect_or_spawn(&exe, &paths, build)?;
|
||||
let stream = connect_or_spawn(&exe, &paths, build, replace)?;
|
||||
bridge(stream, input, output).map_err(|e| format!("daemon relay failed: {e}"))
|
||||
}
|
||||
|
||||
fn connect_or_spawn(exe: &Path, paths: &DaemonPaths, build: &str) -> Result<UnixStream, String> {
|
||||
fn connect_or_spawn(exe: &Path, paths: &DaemonPaths, build: &str, replace: bool) -> Result<UnixStream, String> {
|
||||
let lock_file = OpenOptions::new()
|
||||
.create(true)
|
||||
.truncate(false)
|
||||
@@ -153,8 +155,11 @@ fn connect_or_spawn(exe: &Path, paths: &DaemonPaths, build: &str) -> Result<Unix
|
||||
flock(&lock_file, FlockOperation::LockExclusive)
|
||||
.map_err(|e| format!("cannot lock {}: {e}", paths.lock.display()))?;
|
||||
|
||||
if let Some(stream) = existing_daemon(paths, build)? {
|
||||
return Ok(stream);
|
||||
match existing_daemon(paths, build) {
|
||||
Ok(Some(stream)) => return Ok(stream),
|
||||
Ok(None) => {}
|
||||
Err(e) if replace && e.contains(rpc::OTHER_BUILD_BUSY) => stop_daemon(&paths.socket)?,
|
||||
Err(e) => return Err(e),
|
||||
}
|
||||
|
||||
match std::fs::remove_file(&paths.socket) {
|
||||
@@ -232,10 +237,7 @@ fn existing_daemon(paths: &DaemonPaths, build: &str) -> Result<Option<UnixStream
|
||||
Err(io::Error::other("unexpected response from stopping daemon"))
|
||||
}
|
||||
}
|
||||
BUSY => Err(io::Error::other(
|
||||
"Another build of OpenIDEA still has this project open, is running tasks, or has unsaved changes. \
|
||||
Reconnect with that build, then stop the remote backend before upgrading.",
|
||||
)),
|
||||
BUSY => Err(io::Error::other(rpc::OTHER_BUILD_BUSY)),
|
||||
_ => Err(io::Error::other("unrecognized remote backend response")),
|
||||
}
|
||||
};
|
||||
@@ -247,6 +249,63 @@ fn existing_daemon(paths: &DaemonPaths, build: &str) -> Result<Option<UnixStream
|
||||
exchange(stream).map_err(|e| format!("cannot attach to {}: {e}", paths.socket.display()))
|
||||
}
|
||||
|
||||
/// Stops the daemon serving `socket` (another build's, which refused to retire): asks it to
|
||||
/// shut down like the remote Stop Backend action does, and kills it if it hasn't after a while.
|
||||
fn stop_daemon(socket: &Path) -> Result<(), String> {
|
||||
let pids = daemon_pids(socket)?;
|
||||
if pids.is_empty() {
|
||||
return Err(format!("cannot find the backend serving {}", socket.display()));
|
||||
}
|
||||
let signal = |sig| {
|
||||
for pid in &pids {
|
||||
if let Some(pid) = rustix::process::Pid::from_raw(*pid) {
|
||||
let _ = rustix::process::kill_process(pid, sig);
|
||||
}
|
||||
}
|
||||
};
|
||||
let alive = || pids.iter().any(|pid| process_exists(*pid));
|
||||
signal(rustix::process::Signal::TERM);
|
||||
let deadline = Instant::now() + rpc::SHUTDOWN_TIMEOUT;
|
||||
while alive() && Instant::now() < deadline {
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
}
|
||||
if alive() {
|
||||
signal(rustix::process::Signal::KILL);
|
||||
std::thread::sleep(Duration::from_millis(200));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Whether `pid` still runs: an exited process its parent hasn't reaped yet (a zombie) doesn't.
|
||||
fn process_exists(pid: i32) -> bool {
|
||||
if !rustix::process::Pid::from_raw(pid).is_some_and(|pid| rustix::process::test_kill_process(pid).is_ok()) {
|
||||
return false;
|
||||
}
|
||||
Command::new("ps")
|
||||
.args(["-o", "stat=", "-p", &pid.to_string()])
|
||||
.output()
|
||||
.map_or(true, |out| !String::from_utf8_lossy(&out.stdout).trim_start().starts_with('Z'))
|
||||
}
|
||||
|
||||
/// Processes started as `openidea-server --daemon <socket> <build>`.
|
||||
fn daemon_pids(socket: &Path) -> Result<Vec<i32>, String> {
|
||||
let out = Command::new("ps")
|
||||
.args(["-axww", "-o", "pid=", "-o", "args="])
|
||||
.output()
|
||||
.map_err(|e| format!("cannot list processes: {e}"))?;
|
||||
Ok(daemon_pids_in(&String::from_utf8_lossy(&out.stdout), &socket.to_string_lossy()))
|
||||
}
|
||||
|
||||
fn daemon_pids_in(ps: &str, socket: &str) -> Vec<i32> {
|
||||
ps.lines()
|
||||
.filter_map(|line| {
|
||||
let (pid, args) = line.trim_start().split_once(char::is_whitespace)?;
|
||||
let mut words = args.split_whitespace().skip_while(|w| *w != "--daemon").skip(1);
|
||||
(words.next() == Some(socket)).then(|| pid.parse().ok()).flatten()
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn read_log_tail(file: &mut File, offset: u64) -> String {
|
||||
if file.seek(SeekFrom::Start(offset)).is_err() {
|
||||
return String::new();
|
||||
@@ -480,3 +539,19 @@ fn has_live_work(host: &Host) -> bool {
|
||||
.iter()
|
||||
.any(|project| project.agents.has_live_work() || project.documents.has_unsaved_changes())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::daemon_pids_in;
|
||||
|
||||
#[test]
|
||||
fn finds_the_daemon_of_a_socket_in_the_process_list() {
|
||||
let ps = " 1 /sbin/init\n\
|
||||
581660 /root/.openidea/server/0.1.51/634a/openidea-server --daemon /root/.openidea/run/s-de2d.sock 634a\n\
|
||||
141712 /root/.openidea/server/0.1.53/e116/openidea-server --daemon /root/.openidea/run/s-a67f.sock e116\n\
|
||||
582484 /bin/bash --init-file /tmp/openidea-shell-integration-0.1.51/bash/openidea.bashrc -i\n\
|
||||
590000 grep --daemon /root/.openidea/run/s-de2d.sock.bak\n";
|
||||
assert_eq!(daemon_pids_in(ps, "/root/.openidea/run/s-de2d.sock"), [581660]);
|
||||
assert!(daemon_pids_in(ps, "/root/.openidea/run/s-none.sock").is_empty());
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,52 @@ const OXFMT_CONFIGS: [&str; 4] = [".oxfmtrc.json", ".oxfmtrc.jsonc", "oxfmt.conf
|
||||
/// A Biome configuration, or Biome installed as a project dependency (it then uses its defaults).
|
||||
const BIOME_MARKERS: [&str; 3] = ["biome.json", "biome.jsonc", "node_modules/@biomejs/biome/package.json"];
|
||||
|
||||
/// dprint's configuration files, and dprint installed as a project dependency.
|
||||
const DPRINT_MARKERS: [&str; 5] =
|
||||
["dprint.json", ".dprint.json", "dprint.jsonc", ".dprint.jsonc", "node_modules/dprint/package.json"];
|
||||
|
||||
/// The nearest of `names` in `file`'s folder or above, up to the project `root` (none outside it).
|
||||
fn find_in_project(file: &Path, root: &Path, names: &[&str]) -> Option<PathBuf> {
|
||||
file.parent()?
|
||||
.ancestors()
|
||||
.take_while(|dir| dir.starts_with(root))
|
||||
.find_map(|dir| names.iter().map(|name| dir.join(name)).find(|p| p.is_file()))
|
||||
}
|
||||
|
||||
fn dprint_project(file: &Path, root: &Path) -> bool {
|
||||
find_in_project(file, root, &DPRINT_MARKERS).is_some()
|
||||
}
|
||||
|
||||
/// `dprint editor-info` results by configuration file (the project root without one) and the
|
||||
/// configuration's modification time. Failures are kept too: an offline plugin download would
|
||||
/// otherwise time out again on every format.
|
||||
// ponytail: `extends` files and a configuration outside the project are not watched; editing one needs a change of the project's file (or a restart).
|
||||
type EditorInfo = (Option<std::time::SystemTime>, IdeResult<String>);
|
||||
static DPRINT_EDITOR_INFO: std::sync::LazyLock<std::sync::Mutex<std::collections::HashMap<PathBuf, EditorInfo>>> =
|
||||
std::sync::LazyLock::new(Default::default);
|
||||
|
||||
/// Whether the dprint configuration found for `file` (from its folder, as dprint finds it) has a
|
||||
/// plugin for it. `retry` runs `editor-info` again after a remembered failure.
|
||||
fn dprint_covers(tools: &Tools, custom: Option<&Path>, file: &Path, root: &Path, retry: bool) -> IdeResult<bool> {
|
||||
let dir = file.parent().ok_or_else(|| IdeError::invalid("dprint: file has no directory"))?;
|
||||
let config = find_in_project(file, root, &DPRINT_MARKERS[..4]);
|
||||
let modified = config.as_ref().and_then(|c| std::fs::metadata(c).and_then(|m| m.modified()).ok());
|
||||
let key = config.unwrap_or_else(|| root.to_path_buf());
|
||||
let cached = {
|
||||
let cache = DPRINT_EDITOR_INFO.lock().unwrap_or_else(|e| e.into_inner());
|
||||
cache.get(&key).filter(|(at, info)| *at == modified && !(retry && info.is_err())).map(|(_, info)| info.clone())
|
||||
};
|
||||
let info = cached.unwrap_or_else(|| {
|
||||
let info = tools.formatter_command("dprint", file, custom).and_then(|mut command| {
|
||||
command.current_dir(dir);
|
||||
formatter::dprint_editor_info(command)
|
||||
});
|
||||
DPRINT_EDITOR_INFO.lock().unwrap_or_else(|e| e.into_inner()).insert(key, (modified, info.clone()));
|
||||
info
|
||||
})?;
|
||||
formatter::dprint_covers(&info, file)
|
||||
}
|
||||
|
||||
/// Reformat Code uses Biome below a Biome configuration or installation, unless the nearest
|
||||
/// configuration turns its formatter off (Biome lints, another tool formats).
|
||||
fn biome_formats(file: &Path) -> bool {
|
||||
@@ -31,6 +77,69 @@ fn biome_formats(file: &Path) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
const PRETTIER_CONFIGS: [&str; 18] = [
|
||||
".prettierrc",
|
||||
".prettierrc.json",
|
||||
".prettierrc.json5",
|
||||
".prettierrc.yaml",
|
||||
".prettierrc.yml",
|
||||
".prettierrc.toml",
|
||||
".prettierrc.js",
|
||||
".prettierrc.cjs",
|
||||
".prettierrc.mjs",
|
||||
".prettierrc.ts",
|
||||
".prettierrc.cts",
|
||||
".prettierrc.mts",
|
||||
"prettier.config.js",
|
||||
"prettier.config.cjs",
|
||||
"prettier.config.mjs",
|
||||
"prettier.config.ts",
|
||||
"prettier.config.cts",
|
||||
"prettier.config.mts",
|
||||
];
|
||||
|
||||
/// A Prettier configuration applies to `file`: a configuration file or a `prettier` key in a
|
||||
/// `package.json` above it.
|
||||
fn prettier_configured(file: &Path) -> bool {
|
||||
PRETTIER_CONFIGS.iter().any(|name| formatter::find_up(file, Path::new(name)).is_some())
|
||||
|| file.ancestors().skip(1).any(|dir| {
|
||||
std::fs::read_to_string(dir.join("package.json"))
|
||||
.ok()
|
||||
.and_then(|text| serde_json::from_str::<serde_json::Value>(&text).ok())
|
||||
.is_some_and(|v| v.get("prettier").is_some())
|
||||
})
|
||||
}
|
||||
|
||||
/// The languages whose server formats in the IDE's code style (`ts_code_style`).
|
||||
const CODE_STYLE_LANGUAGES: [&str; 4] = ["javascript", "javascriptreact", "typescript", "typescriptreact"];
|
||||
|
||||
/// In Automatic mode, the project's own configuration of `tool` wins over the TypeScript server,
|
||||
/// whose output follows the IDE's code style. Not before the tool is installed (`resolves`): a fresh
|
||||
/// clone keeps formatting with the server until `npm install`.
|
||||
fn project_takes_over(tool: ExternalFormatter, language: &str, file: &Path, resolves: impl FnOnce() -> bool) -> bool {
|
||||
CODE_STYLE_LANGUAGES.contains(&language) && project_configured(tool, file) && resolves()
|
||||
}
|
||||
|
||||
/// Format on save runs the external tool: its own setting, or the editor's when the tool takes over
|
||||
/// from the language server (Black, dprint, or a project configuration), so saving keeps formatting.
|
||||
fn runs_on_save(tool: ExternalFormatter, run_on_save: bool, takes_over: bool, format_on_save: bool) -> bool {
|
||||
run_on_save
|
||||
|| ((matches!(tool, ExternalFormatter::Black | ExternalFormatter::Dprint) || takes_over) && format_on_save)
|
||||
}
|
||||
|
||||
/// The project configures `tool`. Every formatter needs an arm. dprint is chosen before this check
|
||||
/// (`dprint_project`), so it never reaches it.
|
||||
fn project_configured(tool: ExternalFormatter, file: &Path) -> bool {
|
||||
match tool {
|
||||
ExternalFormatter::Prettier => prettier_configured(file),
|
||||
ExternalFormatter::Oxfmt => {
|
||||
OXFMT_CONFIGS.iter().any(|name| formatter::find_up(file, Path::new(name)).is_some())
|
||||
}
|
||||
ExternalFormatter::Biome => biome_formats(file),
|
||||
ExternalFormatter::Ruff | ExternalFormatter::Black | ExternalFormatter::Dprint => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The `pyproject.toml` Black reads for `file`, in the project root Black finds: the nearest folder
|
||||
/// with `.git`, `.hg`, or a `pyproject.toml` that has `[tool.black]` (one without it is skipped).
|
||||
/// `None` when that root has no `pyproject.toml`: Black then reads the user's configuration.
|
||||
@@ -283,6 +392,47 @@ fn minimal_edits(text: &str, edits: Vec<TextEdit>) -> Vec<TextEdit> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The edits on the lines of `range`. Some servers (Intelephense, #6055) answer a range request
|
||||
/// with edits across the whole file; Reformat Code with a selection changes only the selected
|
||||
/// lines. An edit that reaches past them and keeps its line count is split into one per line.
|
||||
fn within_lines(text: &str, edits: Vec<TextEdit>, range: Range) -> Vec<TextEdit> {
|
||||
let from = Pos::new(range.start.line, 0);
|
||||
// A selection ending at a line start leaves that line out.
|
||||
let to = if range.end.col == 0 && range.end.line > range.start.line {
|
||||
range.end
|
||||
} else {
|
||||
Pos::new(range.end.line + 1, 0)
|
||||
};
|
||||
let doc = ide_text::Document::new(text);
|
||||
edits
|
||||
.into_iter()
|
||||
.flat_map(|e| if e.range.start >= from && e.range.end <= to { vec![e] } else { per_line(&doc, e) })
|
||||
.filter(|e| e.range.start >= from && e.range.end <= to)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// `edit` as one edit per line when it replaces as many lines as it inserts, else nothing.
|
||||
fn per_line(doc: &ide_text::Document, edit: TextEdit) -> Vec<TextEdit> {
|
||||
let Range { start, end } = edit.range;
|
||||
let lines: Vec<&str> = edit.new_text.split('\n').collect();
|
||||
if lines.len() as u32 != end.line - start.line + 1 {
|
||||
return Vec::new();
|
||||
}
|
||||
let width = |line: u32| doc.line(line).map_or(0, |l| l.encode_utf16().count() as u32);
|
||||
lines
|
||||
.into_iter()
|
||||
.zip(start.line..=end.line)
|
||||
.map(|(new_text, line)| TextEdit {
|
||||
range: Range::new(
|
||||
Pos::new(line, if line == start.line { start.col } else { 0 }),
|
||||
Pos::new(line, if line == end.line { end.col } else { width(line) }),
|
||||
),
|
||||
new_text: new_text.to_owned(),
|
||||
})
|
||||
.filter(|e| doc.slice(doc.pos_to_offset(e.range.start), doc.pos_to_offset(e.range.end)) != e.new_text)
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub async fn format(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
@@ -492,18 +642,58 @@ async fn provider_edits(
|
||||
}
|
||||
return Ok(Some(edits));
|
||||
}
|
||||
let mut selected = external_tool(options.tool, language.as_ref(), &snap.path, &settings.languages)?;
|
||||
// dprint formats what its configuration covers, before the language's own formatters.
|
||||
let dprint = &settings.languages.dprint;
|
||||
let forced_dprint = options.tool == Some(ExternalFormatter::Dprint);
|
||||
let auto_dprint = options.tool.is_none()
|
||||
&& (dprint.prefer || dprint_project(&snap.path, &project.root))
|
||||
&& project.require_trust().is_ok();
|
||||
let mut selected = None;
|
||||
if forced_dprint || auto_dprint {
|
||||
host.require_trust(window)?;
|
||||
let tools = Tools::new(&host.local_data_dir);
|
||||
let custom = ide_sdk::apply::setting_path(&project.root, &dprint.path);
|
||||
let (path, root) = (snap.path.clone(), project.root.clone());
|
||||
let covers =
|
||||
tokio::task::spawn_blocking(move || dprint_covers(&tools, custom.as_deref(), &path, &root, forced_dprint))
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()))?;
|
||||
match covers {
|
||||
Ok(true) => selected = Some(ExternalFormatter::Dprint),
|
||||
Ok(false) if forced_dprint => {
|
||||
return Err(
|
||||
IdeError::invalid("The dprint configuration has no plugin for this file").with_tool("dprint")
|
||||
);
|
||||
}
|
||||
Ok(false) => {}
|
||||
Err(e) if forced_dprint => return Err(e.with_tool("dprint")),
|
||||
// Not installed, no configuration, plugins not downloadable: the usual formatter.
|
||||
Err(e) => tracing::warn!("dprint editor-info failed, using the usual formatter: {}", e.message),
|
||||
}
|
||||
}
|
||||
if selected.is_none() {
|
||||
selected = external_tool(options.tool, language.as_ref(), &snap.path, &settings.languages)?;
|
||||
}
|
||||
let mut takes_over = false;
|
||||
// Black is selected only when configured or preferred: the Ruff server's formatting doesn't replace it.
|
||||
if let Some(tool) = selected
|
||||
&& options.tool.is_none()
|
||||
&& tool != ExternalFormatter::Dprint
|
||||
&& tool != ExternalFormatter::Black
|
||||
&& !settings.languages.formatter(tool).prefer
|
||||
&& match doc {
|
||||
Some(doc) => project.lsp.can_format(doc).await?,
|
||||
None => project.lsp.can_format_text(&snap.path, &snap.language).await,
|
||||
}
|
||||
{
|
||||
selected = None;
|
||||
takes_over = project_takes_over(tool, snap.language.as_str(), &snap.path, || {
|
||||
let custom = ide_sdk::apply::setting_path(&project.root, &settings.languages.formatter(tool).path);
|
||||
Tools::new(&host.local_data_dir).formatter_command(tool.name(), &snap.path, custom.as_deref()).is_ok()
|
||||
});
|
||||
if !takes_over
|
||||
&& match doc {
|
||||
Some(doc) => project.lsp.can_format(doc).await?,
|
||||
None => project.lsp.can_format_text(&snap.path, &snap.language).await,
|
||||
}
|
||||
{
|
||||
selected = None;
|
||||
}
|
||||
}
|
||||
let Some(selected) = selected else {
|
||||
if options.on_save && !settings.editor.format_on_save {
|
||||
@@ -514,22 +704,35 @@ async fn provider_edits(
|
||||
None => project.lsp.format_text(&snap.path, &snap.language, &snap.text, options).await?,
|
||||
};
|
||||
let text = snap.text;
|
||||
return tokio::task::spawn_blocking(move || Some(minimal_edits(&text, edits)))
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()));
|
||||
return tokio::task::spawn_blocking(move || {
|
||||
let edits = minimal_edits(&text, edits);
|
||||
Some(match range {
|
||||
Some(range) => within_lines(&text, edits, range),
|
||||
None => edits,
|
||||
})
|
||||
})
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()));
|
||||
};
|
||||
let tool_settings = settings.languages.formatter(selected);
|
||||
// Black takes over from the language server in its projects, so Format on save runs it too.
|
||||
let runs_on_save =
|
||||
tool_settings.run_on_save || (selected == ExternalFormatter::Black && settings.editor.format_on_save);
|
||||
if options.on_save && !runs_on_save {
|
||||
if options.on_save && !runs_on_save(selected, tool_settings.run_on_save, takes_over, settings.editor.format_on_save)
|
||||
{
|
||||
return Ok(None);
|
||||
}
|
||||
host.require_trust(window)?;
|
||||
if snap.read_only {
|
||||
return Err(IdeError::invalid("The file is read-only"));
|
||||
}
|
||||
let config = language.and_then(|l| l.formatter).expect("external_tool selects languages with a formatter");
|
||||
let config = language
|
||||
.and_then(|l| l.formatter)
|
||||
.or_else(|| {
|
||||
(selected == ExternalFormatter::Dprint).then(|| ide_language::FormatterConfig {
|
||||
tool: "dprint".into(),
|
||||
parser: String::new(),
|
||||
range: false,
|
||||
})
|
||||
})
|
||||
.expect("external_tool selects languages with a formatter");
|
||||
let tool = selected.name();
|
||||
let name = formatter::display_name(tool);
|
||||
let mut custom = ide_sdk::apply::setting_path(&project.root, &tool_settings.path);
|
||||
@@ -680,7 +883,7 @@ pub async fn python_import_edits(
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use ExternalFormatter::{Biome, Black, Oxfmt, Prettier, Ruff};
|
||||
use ExternalFormatter::{Biome, Black, Dprint, Oxfmt, Prettier, Ruff};
|
||||
use ide_core::LanguageId;
|
||||
use ide_language::LanguageRegistry;
|
||||
|
||||
@@ -898,6 +1101,90 @@ mod tests {
|
||||
assert_eq!(black_pyproject(&file), Some(repo.join("pkg/pyproject.toml")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dprint_configuration_or_dependency_in_the_project_marks_a_dprint_project() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path().join("home/project");
|
||||
let file = root.join("web/src/app.ts");
|
||||
assert!(!dprint_project(&file, &root));
|
||||
for marker in DPRINT_MARKERS {
|
||||
let path = root.join("web").join(marker);
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
std::fs::write(&path, "{}").unwrap();
|
||||
assert!(dprint_project(&file, &root), "{marker}");
|
||||
assert!(!dprint_project(&root.join("api/main.ts"), &root), "{marker}");
|
||||
// A file outside the project is not below the project's dprint.
|
||||
assert!(!dprint_project(&dir.path().join("elsewhere/web/src/app.ts"), &root), "{marker}");
|
||||
std::fs::remove_file(&path).unwrap();
|
||||
}
|
||||
// dprint installed above the project (a stray `~/node_modules/dprint`) doesn't count.
|
||||
let stray = dir.path().join("home/node_modules/dprint/package.json");
|
||||
std::fs::create_dir_all(stray.parent().unwrap()).unwrap();
|
||||
std::fs::write(&stray, "{}").unwrap();
|
||||
std::fs::write(dir.path().join("home/dprint.json"), "{}").unwrap();
|
||||
assert!(!dprint_project(&file, &root));
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn dprint_coverage_comes_from_editor_info_cached_per_configuration() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
std::fs::create_dir_all(root.join("src")).unwrap();
|
||||
let config = root.join("dprint.json");
|
||||
std::fs::write(&config, "{}").unwrap();
|
||||
// Shell builtins only: the command runs with the tools' empty PATH.
|
||||
let info = r#"{"plugins":[{"fileExtensions":["ts"],"fileNames":["Dockerfile"]}]}"#;
|
||||
let fake = root.join("fake-dprint");
|
||||
let script = format!(
|
||||
"#!/bin/sh\necho run >> \"$0.runs\"\n[ -f fail ] && {{ echo 'bad config' >&2; exit 1; }}\nprintf '%s' '{info}'\n"
|
||||
);
|
||||
std::fs::write(&fake, script).unwrap();
|
||||
std::fs::set_permissions(&fake, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
let tools = Tools::with_paths(root.join("tools"), Default::default(), ide_tools::platform::Platform::current());
|
||||
let runs = || std::fs::read_to_string(root.join("fake-dprint.runs")).unwrap_or_default().lines().count();
|
||||
let covers = |file: &str, retry| dprint_covers(&tools, Some(&fake), &root.join(file), root, retry);
|
||||
|
||||
assert!(covers("src/app.ts", false).unwrap());
|
||||
assert!(covers("src/Dockerfile", false).unwrap());
|
||||
// Not covered: the usual formatter takes the file.
|
||||
assert!(!covers("src/main.py", false).unwrap());
|
||||
assert_eq!(runs(), 1);
|
||||
|
||||
// A changed configuration is read again, and its error is dprint's.
|
||||
std::fs::write(root.join("src/fail"), "").unwrap();
|
||||
let later = std::fs::metadata(&config).unwrap().modified().unwrap() + std::time::Duration::from_secs(5);
|
||||
std::fs::File::options().write(true).open(&config).unwrap().set_modified(later).unwrap();
|
||||
let error = covers("src/app.ts", false).unwrap_err();
|
||||
assert!(error.message.contains("bad config"), "{}", error.message);
|
||||
assert_eq!(error.data, Some(ide_core::error::ErrorData::Tool { tool: "dprint".into(), missing: false }));
|
||||
assert_eq!(runs(), 2);
|
||||
// The failure is remembered (an offline download would time out again), unless retried.
|
||||
assert!(covers("src/app.ts", false).is_err());
|
||||
assert_eq!(runs(), 2);
|
||||
std::fs::remove_file(root.join("src/fail")).unwrap();
|
||||
assert!(covers("src/app.ts", true).unwrap());
|
||||
assert_eq!(runs(), 3);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn dprint_without_a_project_configuration_runs_once_per_project() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
std::fs::create_dir_all(root.join("a/b")).unwrap();
|
||||
let fake = root.join("fake-dprint");
|
||||
std::fs::write(&fake, "#!/bin/sh\necho run >> \"$0.runs\"\nprintf '%s' '{\"plugins\":[]}'\n").unwrap();
|
||||
std::fs::set_permissions(&fake, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
let tools = Tools::with_paths(root.join("tools"), Default::default(), ide_tools::platform::Platform::current());
|
||||
for file in ["a/x.ts", "a/b/y.ts", "z.ts"] {
|
||||
assert!(!dprint_covers(&tools, Some(&fake), &root.join(file), root, false).unwrap());
|
||||
}
|
||||
assert_eq!(std::fs::read_to_string(root.join("fake-dprint.runs")).unwrap().lines().count(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn biome_config_or_dependency_selects_biome_for_its_languages() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
@@ -964,6 +1251,55 @@ mod tests {
|
||||
assert_eq!(tool(None, "typescript", file, &settings).unwrap(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_project_configuration_of_the_formatter_wins_over_the_language_server() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
std::fs::create_dir_all(root.join("a/src")).unwrap();
|
||||
std::fs::create_dir_all(root.join("b/src")).unwrap();
|
||||
std::fs::create_dir_all(root.join("c/src")).unwrap();
|
||||
std::fs::write(root.join("a/.prettierrc.json"), "{}").unwrap();
|
||||
std::fs::write(root.join("b/package.json"), r#"{ "prettier": { "semi": false } }"#).unwrap();
|
||||
std::fs::write(root.join("c/package.json"), r#"{ "name": "c" }"#).unwrap();
|
||||
std::fs::write(root.join("c/biome.json"), "{}").unwrap();
|
||||
assert!(project_configured(Prettier, &root.join("a/src/app.ts")));
|
||||
assert!(project_configured(Prettier, &root.join("b/src/app.ts")));
|
||||
assert!(!project_configured(Prettier, &root.join("c/src/app.ts")));
|
||||
assert!(project_configured(Biome, &root.join("c/src/app.ts")));
|
||||
assert!(!project_configured(Oxfmt, &root.join("c/src/app.ts")));
|
||||
std::fs::write(root.join("c/.oxfmtrc.json"), "{}").unwrap();
|
||||
assert!(project_configured(Oxfmt, &root.join("c/src/app.ts")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_the_typescript_server_languages_give_way_to_an_installed_project_formatter() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
std::fs::write(dir.path().join(".prettierrc"), "{}").unwrap();
|
||||
let file = |name: &str| dir.path().join(name);
|
||||
for language in ["typescript", "typescriptreact", "javascript", "javascriptreact"] {
|
||||
assert!(project_takes_over(Prettier, language, &file("a.ts"), || true), "{language}");
|
||||
}
|
||||
for language in ["json", "css", "html", "yaml", "markdown", "vue"] {
|
||||
assert!(!project_takes_over(Prettier, language, &file("a.json"), || true), "{language}");
|
||||
}
|
||||
// Configured but not installed yet (before `npm install`): the language server formats.
|
||||
assert!(!project_takes_over(Prettier, "typescript", &file("a.ts"), || false));
|
||||
// No configuration: the tool isn't even looked up.
|
||||
assert!(!project_takes_over(Biome, "typescript", &file("a.ts"), || panic!("resolved")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn format_on_save_keeps_running_when_the_project_formatter_takes_over() {
|
||||
// Format on save formatted with the language server before; the tool that replaces it does too.
|
||||
assert!(runs_on_save(Prettier, false, true, true));
|
||||
assert!(!runs_on_save(Prettier, false, true, false));
|
||||
assert!(runs_on_save(Black, false, false, true));
|
||||
assert!(runs_on_save(Dprint, false, false, true));
|
||||
// Selected by the settings, not taking over: only its own Run on save.
|
||||
assert!(!runs_on_save(Prettier, false, false, true));
|
||||
assert!(runs_on_save(Prettier, true, false, false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn forced_tool_runs_that_formatter_or_reports_why_not() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
@@ -1050,6 +1386,26 @@ mod tests {
|
||||
|
||||
const ALIGN: PhpAlignment = PhpAlignment { key_value_pairs: true, assignments: true };
|
||||
|
||||
#[test]
|
||||
fn range_formatting_changes_only_the_selected_lines() {
|
||||
// Intelephense answers a range request for lines 2-3 with edits across the file (#6055).
|
||||
let text = "<?php\nf(\"a\");\n$x = 1;\n$y = 2;\nf(\"b\");\n";
|
||||
let formatted = "<?php\nf('a');\n$x = 1;\n$y = 2;\nf('b');\n";
|
||||
let whole = vec![TextEdit { range: Range::new(Pos::new(0, 0), Pos::new(5, 0)), new_text: formatted.into() }];
|
||||
let edits = minimal_edits(text, whole);
|
||||
let selected = Range::new(Pos::new(2, 0), Pos::new(3, 8));
|
||||
assert_eq!(
|
||||
after(text, &within_lines(text, edits.clone(), selected)),
|
||||
"<?php\nf(\"a\");\n$x = 1;\n$y = 2;\nf(\"b\");\n"
|
||||
);
|
||||
// Selected up to the start of line 4: line 4 stays as it is.
|
||||
let to_line_start = Range::new(Pos::new(2, 3), Pos::new(3, 0));
|
||||
assert_eq!(
|
||||
after(text, &within_lines(text, edits, to_line_start)),
|
||||
"<?php\nf(\"a\");\n$x = 1;\n$y = 2;\nf(\"b\");\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_whole_file_edit_becomes_one_edit_per_changed_region() {
|
||||
let text = "a\n b\nc\nd\n e\n";
|
||||
|
||||
@@ -15,6 +15,7 @@ mod formatter;
|
||||
mod java_runtime;
|
||||
mod kotlin_bridge;
|
||||
pub mod mcp;
|
||||
pub mod menu;
|
||||
pub mod notebook;
|
||||
pub mod ops;
|
||||
mod phpstan;
|
||||
@@ -26,6 +27,9 @@ mod requests;
|
||||
pub mod rpc;
|
||||
pub mod shell_env;
|
||||
pub mod trust;
|
||||
mod ts_code_style;
|
||||
mod tsc_watch;
|
||||
pub mod web_server;
|
||||
|
||||
pub use project::{Project, history_retention};
|
||||
|
||||
@@ -378,6 +382,7 @@ impl Host {
|
||||
self.mcp_reports.forget_window(window);
|
||||
self.mcp_requests.forget_window(window);
|
||||
self.mcp_agent_runs.forget_window(window);
|
||||
self.debugger.forget_breakpoints(self.owner_window(window));
|
||||
self.external_logs.write().remove(self.owner_window(window));
|
||||
for request in self.project_requests.write().remove(self.owner_window(window)).unwrap_or_default() {
|
||||
self.cancel_request(request);
|
||||
@@ -385,10 +390,12 @@ impl Host {
|
||||
// After the cancels: a capture or open still running then discards what it registers.
|
||||
ops::heap::close_window_snapshots(self, window);
|
||||
let project = self.projects.write().remove(window)?;
|
||||
if self.windows_for_root(&project.root).is_empty()
|
||||
&& let Some(plugins) = self.plugin_host()
|
||||
{
|
||||
plugins.withdraw_project_run_targets(&project.root);
|
||||
if let Some(plugins) = self.plugin_host() {
|
||||
if self.windows_for_root(&project.root).is_empty() {
|
||||
plugins.project_closed(&project.root, window);
|
||||
} else {
|
||||
plugins.forget_client(window);
|
||||
}
|
||||
}
|
||||
project.files_events_active.store(false, std::sync::atomic::Ordering::Release);
|
||||
project.plugin_diagnostics.close();
|
||||
@@ -420,6 +427,9 @@ impl Host {
|
||||
if let Some(phpstan) = &project.phpstan {
|
||||
phpstan.stop();
|
||||
}
|
||||
if let Some(watch) = &project.tsc_watch {
|
||||
watch.stop();
|
||||
}
|
||||
project.documents.clear_workspace_edit_history();
|
||||
project.agents.detach_sinks();
|
||||
project.flutter.stop();
|
||||
@@ -649,6 +659,9 @@ impl Host {
|
||||
if let Some(phpstan) = &project.phpstan {
|
||||
phpstan.stop();
|
||||
}
|
||||
if let Some(watch) = &project.tsc_watch {
|
||||
watch.stop();
|
||||
}
|
||||
project.documents.clear_workspace_edit_history();
|
||||
project.notebooks.stop_admission();
|
||||
project.agents.shutdown();
|
||||
|
||||
@@ -446,9 +446,15 @@ pub fn stop_run() -> Tool {
|
||||
"Stops the running command of an agent tab, the way the Run tool window's Stop does: it asks the \
|
||||
process tree to exit and, with `force`, kills it. Waits up to `timeout` milliseconds (default {STOP_TIMEOUT_MS}) \
|
||||
for it to end and returns the tab's status (`stoppedByAgent` once it ended). A process that ignores the request \
|
||||
keeps `stopping`: call again with `force`. The tab stays open with its output."
|
||||
keeps `stopping`: call again with `force`. The tab stays open with its output.
|
||||
|
||||
Pass `runId` instead of `name` to stop a run `execute_run_configuration` started and left running; the result is \
|
||||
its `state` (`stopped` or `stopping`) and `exitCode` when it has one."
|
||||
),
|
||||
|call| async move {
|
||||
if let Some(id) = call.opt_i64("runId")? {
|
||||
return stop_configuration_run(&call, id).await;
|
||||
}
|
||||
let run = find(&call)?;
|
||||
let id = run.live_process().ok_or_else(|| IdeError::invalid(format!("`{}` is not running", run.name)))?;
|
||||
let force = call.flag("force", false)?;
|
||||
@@ -467,11 +473,48 @@ keeps `stopping`: call again with `force`. The tab stays open with its output."
|
||||
},
|
||||
)
|
||||
.write()
|
||||
.param(Param::required("name", ParamType::String, NAME))
|
||||
.param(Param::optional("name", ParamType::String, NAME))
|
||||
.param(Param::optional("runId", ParamType::Integer, "`runId` from `execute_run_configuration`, instead of `name`"))
|
||||
.param(Param::optional("force", ParamType::Boolean, "Kill the process tree instead of asking it to exit"))
|
||||
.param(Param::optional("timeout", ParamType::Integer, "Milliseconds to wait for the command to end"))
|
||||
}
|
||||
|
||||
/// `stop_run` for a run `execute_run_configuration` started (#6127).
|
||||
async fn stop_configuration_run(call: &Call, raw: i64) -> IdeResult<Output> {
|
||||
use super::configs::{forget_started, run_exit, started_by_mcp, wait_exit};
|
||||
if call.opt_str("name")?.is_some() {
|
||||
return Err(IdeError::invalid("pass either `name` or `runId`, not both"));
|
||||
}
|
||||
let id = u32::try_from(raw)
|
||||
.ok()
|
||||
.map(ide_core::RunId)
|
||||
.filter(|id| started_by_mcp(*id))
|
||||
.ok_or_else(|| IdeError::not_found(format!("no run {raw} started by execute_run_configuration")))?;
|
||||
let host = call.host();
|
||||
let deadline = std::time::Instant::now() + timeout(call, STOP_TIMEOUT_MS)?;
|
||||
let exit = match run_exit(&host, id) {
|
||||
Some(exit) => Some(exit),
|
||||
None => {
|
||||
crate::ops::run::run_stop(&host, call.window(), id)?;
|
||||
if call.flag("force", false)? {
|
||||
// A second Stop kills the tree.
|
||||
crate::ops::run::run_stop(&host, call.window(), id)?;
|
||||
}
|
||||
wait_exit(call, id, Some(deadline)).await?
|
||||
}
|
||||
};
|
||||
if exit.is_some() {
|
||||
forget_started(id);
|
||||
}
|
||||
let mut out = Map::new();
|
||||
out.insert("runId".into(), id.0.into());
|
||||
out.insert("state".into(), if exit.is_some() { "stopped" } else { "stopping" }.into());
|
||||
if let Some(Some(code)) = exit {
|
||||
out.insert("exitCode".into(), code.into());
|
||||
}
|
||||
Output::json(Value::Object(out))
|
||||
}
|
||||
|
||||
pub fn tools() -> Vec<Tool> {
|
||||
vec![run_command(), wait_for_run(), read_run_output(), get_run_status(), send_run_input(), stop_run(), list_runs()]
|
||||
}
|
||||
|
||||
@@ -15,8 +15,9 @@ use ide_core::{IdeError, IdeResult, RunId, Severity};
|
||||
use ide_run::{OutputChunk, RunConfig};
|
||||
use parking_lot::Mutex;
|
||||
use serde_json::{Map, Value, json};
|
||||
use std::collections::HashSet;
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
use std::sync::{Arc, LazyLock};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
const DEFAULT_TIMEOUT_MS: usize = 10_000;
|
||||
@@ -281,7 +282,19 @@ workingDirectory, envs).",
|
||||
}
|
||||
|
||||
/// Polls how run `id` ended: `None` while running, else its exit code (if known).
|
||||
fn run_exit(host: &crate::Host, id: RunId) -> Option<Option<i32>> {
|
||||
/// The runs `execute_run_configuration` started: `stop_run` takes their `runId`, and only theirs,
|
||||
/// not the user's own runs.
|
||||
static STARTED: LazyLock<Mutex<HashSet<RunId>>> = LazyLock::new(Default::default);
|
||||
|
||||
pub(super) fn started_by_mcp(id: RunId) -> bool {
|
||||
STARTED.lock().contains(&id)
|
||||
}
|
||||
|
||||
pub(super) fn forget_started(id: RunId) {
|
||||
STARTED.lock().remove(&id);
|
||||
}
|
||||
|
||||
pub(super) fn run_exit(host: &crate::Host, id: RunId) -> Option<Option<i32>> {
|
||||
match host.processes.exit_code(id) {
|
||||
Ok(exit) => exit,
|
||||
// Remote (SSH) runs, or a finished run already forgotten: the run list knows whether it runs.
|
||||
@@ -294,7 +307,7 @@ fn run_exit(host: &crate::Host, id: RunId) -> Option<Option<i32>> {
|
||||
|
||||
/// Waits for run `id` to exit, until `deadline`: `None` when it is still running. Cancelling
|
||||
/// the call stops the run.
|
||||
async fn wait_exit(call: &Call, id: RunId, deadline: Option<Instant>) -> IdeResult<Option<Option<i32>>> {
|
||||
pub(super) async fn wait_exit(call: &Call, id: RunId, deadline: Option<Instant>) -> IdeResult<Option<Option<i32>>> {
|
||||
let host = call.host();
|
||||
loop {
|
||||
if let Some(exit) = run_exit(&host, id) {
|
||||
@@ -741,7 +754,8 @@ Behavior:
|
||||
Returns the execution result including current output snapshot, optional exit code, and optional `fullOutputPath`.
|
||||
In OpenIDEA the user is asked first for every call; `programArguments` replace the configuration's \
|
||||
arguments (appended to a command that is one shell line, such as `npm run dev`); the run does not appear in the Run \
|
||||
tool window; output files are private and deleted after a day.",
|
||||
tool window: while it is still running, the result carries `runId`, which `stop_run` stops; output files are private \
|
||||
and deleted after a day.",
|
||||
|call| async move {
|
||||
let target = execution_target(
|
||||
call.opt_str("configurationName")?,
|
||||
@@ -807,14 +821,24 @@ one by one",
|
||||
}
|
||||
};
|
||||
|
||||
STARTED.lock().insert(info.id);
|
||||
let exit = match limit {
|
||||
Some(limit) if !limit.is_zero() => wait_exit(&call, info.id, Some(Instant::now() + limit)).await?,
|
||||
_ => None,
|
||||
};
|
||||
if exit.is_some() {
|
||||
STARTED.lock().remove(&info.id);
|
||||
}
|
||||
let c = collector.lock();
|
||||
let mut result = Map::new();
|
||||
if let Some(Some(code)) = exit {
|
||||
result.insert("exitCode".into(), code.into());
|
||||
match exit {
|
||||
Some(Some(code)) => {
|
||||
result.insert("exitCode".into(), code.into());
|
||||
}
|
||||
Some(None) => {}
|
||||
None => {
|
||||
result.insert("runId".into(), info.id.0.into());
|
||||
}
|
||||
}
|
||||
result.insert("output".into(), c.preview().into());
|
||||
// An exited run whose whole output is in `output` needs no file.
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -88,6 +88,13 @@ pub fn agent_set_command(host: &Host, window: &str, id: String, command: Option<
|
||||
host.project(window)?.agents.set_builtin_command(&id, command)
|
||||
}
|
||||
|
||||
/// Sets additional launch arguments for a built-in ACP agent; an empty list resets them.
|
||||
#[command(trust = trusted)]
|
||||
pub fn agent_set_additional_args(host: &Host, window: &str, id: String, args: Vec<String>) -> IdeResult<()> {
|
||||
host.require_trust(window)?;
|
||||
host.project(window)?.agents.set_builtin_additional_args(&id, args)
|
||||
}
|
||||
|
||||
/// Environment variables built-in agent `id` starts with (saved in its agent file);
|
||||
/// an empty map clears them.
|
||||
#[command(trust = trusted)]
|
||||
@@ -281,6 +288,21 @@ pub async fn agent_import_session(
|
||||
blocking(move || agents.import_session(&provider, &session_id)).await
|
||||
}
|
||||
|
||||
/// Forks a recorded external session into a new task: its first turn continues the recording
|
||||
/// as the agent's own fork, under an id the host chooses. `cwd` must be where it was recorded.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn agent_fork_session(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
provider: String,
|
||||
session_id: String,
|
||||
cwd: String,
|
||||
) -> IdeResult<AgentTask> {
|
||||
host.require_trust(window)?;
|
||||
let agents = host.project(window)?.agents.clone();
|
||||
blocking(move || agents.fork_session(&provider, &session_id, std::path::Path::new(&cwd))).await
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn agent_create(host: &Host, window: &str, request: NewAgentTask) -> IdeResult<AgentTask> {
|
||||
host.require_trust(window)?;
|
||||
@@ -1445,6 +1467,7 @@ ide_command::domain!(
|
||||
agent_entries,
|
||||
agent_external_sessions,
|
||||
agent_fork,
|
||||
agent_fork_session,
|
||||
agent_grouped_changes,
|
||||
agent_hermes_profiles,
|
||||
agent_import_session,
|
||||
@@ -1469,6 +1492,7 @@ ide_command::domain!(
|
||||
agent_rollback,
|
||||
agent_rollback_changes,
|
||||
agent_send_queued_now,
|
||||
agent_set_additional_args,
|
||||
agent_set_command,
|
||||
agent_shell,
|
||||
agent_set_config,
|
||||
|
||||
@@ -971,6 +971,7 @@ pub async fn build_run(
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
let (root, cache, sink) = (project.root.clone(), project.build_cache_dir(), project.sink.clone());
|
||||
let file = file.map(|f| ide_core::project_roots::resolve(&root, &f));
|
||||
let settings = project.settings.effective();
|
||||
let detected = project.detected_roots.read().clone();
|
||||
let config_dir = host.config_dir.clone();
|
||||
|
||||
@@ -9,7 +9,7 @@ use ide_core::{IdeError, IdeResult, IpcPath, RequestId};
|
||||
use ide_db::split::SqlStatement;
|
||||
use ide_db::{
|
||||
CompletionModel, DataSource, Databases, DbObjectKind, DbRowEdit, DbVisibilityChange, HistoryEntry, PlanNode,
|
||||
QueryResult, SchemaObjects, SortKey, TableDetails, TableInfo, TablePage,
|
||||
QueryResult, SchemaObjects, SortKey, TableDetails, TableGrant, TableInfo, TablePage,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
@@ -293,6 +293,19 @@ pub async fn db_table_details(
|
||||
db.table_details(&id, &schema, &table).await
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn db_table_grants(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
id: String,
|
||||
schema: String,
|
||||
table: String,
|
||||
) -> IdeResult<Vec<TableGrant>> {
|
||||
// Who may read or change `table` (PostgreSQL and MySQL; empty elsewhere).
|
||||
let db = host.project(window)?.db.clone();
|
||||
db.table_grants(&id, &schema, &table).await
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn db_ddl(host: &Host, window: &str, id: String, schema: String, table: String) -> IdeResult<String> {
|
||||
// The DDL of table or view `table` (Go to DDL, Generate DDL).
|
||||
@@ -481,6 +494,7 @@ async fn execute_statements(
|
||||
let db = host.project(window)?.db.clone();
|
||||
let cancel = host.begin_request(request);
|
||||
let result = async {
|
||||
db.validate_script(id, &statements).await?;
|
||||
for (index, statement) in statements.into_iter().enumerate() {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
@@ -690,6 +704,7 @@ ide_command::domain!(
|
||||
db_sources,
|
||||
db_statements,
|
||||
db_table_details,
|
||||
db_table_grants,
|
||||
db_table_page,
|
||||
db_tables,
|
||||
db_test,
|
||||
|
||||
@@ -32,12 +32,20 @@ pub async fn debug_start(host: &Host, window: &str, config: LaunchConfig) -> Ide
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let mut config = config;
|
||||
let enhanced = take_enhanced_redefinition(&mut config);
|
||||
let executor = take_executor(&mut config);
|
||||
let java_exec = java_exec_path(&config);
|
||||
let agents = if is_jvm_launch(&config) {
|
||||
ide_run::java_agent::current_for(java_exec.as_deref())
|
||||
let mut agents = if is_jvm_launch(&config) {
|
||||
ide_run::java_agent::current_for_executor(java_exec.as_deref(), executor.as_deref())
|
||||
} else {
|
||||
Default::default()
|
||||
ide_run::java_agent::Agents::default()
|
||||
};
|
||||
match enhanced {
|
||||
Some(Ok(option)) => agents.options.insert(0, option.to_owned()),
|
||||
Some(Err(note)) => agents.notes.push(note),
|
||||
None => {}
|
||||
}
|
||||
let config = add_java_agents(config, &agents.options);
|
||||
let mut config = match_java_debug_encoding(start_java_attach_listener(config, cfg!(windows)), cfg!(windows));
|
||||
if config.adapter == "debugpy"
|
||||
@@ -249,6 +257,34 @@ fn java_exec_path(config: &LaunchConfig) -> Option<std::path::PathBuf> {
|
||||
extra.get("javaExec").and_then(|v| v.as_str()).filter(|s| !s.is_empty()).map(std::path::PathBuf::from)
|
||||
}
|
||||
|
||||
/// The configuration's Enhanced class redefinition (`enhancedClassRedefinition` in the launch
|
||||
/// extras, which this removes): for a JVM the debugger starts, JetBrains Runtime's flag, or the
|
||||
/// console line saying why the session runs without it.
|
||||
fn take_enhanced_redefinition(config: &mut LaunchConfig) -> Option<Result<&'static str, String>> {
|
||||
let Some(serde_json::Value::Object(mut extra)) =
|
||||
config.extra_json.as_deref().and_then(|e| serde_json::from_str(e).ok())
|
||||
else {
|
||||
return None;
|
||||
};
|
||||
let on = extra.remove("enhancedClassRedefinition")?.as_bool() == Some(true);
|
||||
config.extra_json = Some(serde_json::Value::Object(extra).to_string());
|
||||
(on && is_jvm_launch(config))
|
||||
.then(|| ide_run::java_hotswap::enhanced_redefinition(java_exec_path(config).as_deref()))
|
||||
}
|
||||
|
||||
/// The plugin executor the session launches through (`executor` in the launch extras, which
|
||||
/// this removes): its plugin's executor-bound Java agent loads only then.
|
||||
fn take_executor(config: &mut LaunchConfig) -> Option<String> {
|
||||
let Some(serde_json::Value::Object(mut extra)) =
|
||||
config.extra_json.as_deref().and_then(|e| serde_json::from_str(e).ok())
|
||||
else {
|
||||
return None;
|
||||
};
|
||||
let executor = extra.remove("executor")?;
|
||||
config.extra_json = Some(serde_json::Value::Object(extra).to_string());
|
||||
executor.as_str().filter(|s| !s.is_empty()).map(str::to_owned)
|
||||
}
|
||||
|
||||
/// Plugins' Java agents ([`ide_run::java_agent`]) after the configuration's VM options:
|
||||
/// java-debug's and java-analyzer's `vmArgs` (one line, or a list) or the Kotlin debugger's
|
||||
/// `vmArguments` (a list).
|
||||
@@ -380,13 +416,25 @@ fn match_java_debug_encoding(mut config: LaunchConfig, windows: bool) -> LaunchC
|
||||
config
|
||||
}
|
||||
|
||||
/// This window's breakpoints of `path`.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn debug_set_breakpoints(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
path: PathBuf,
|
||||
breakpoints: Vec<Breakpoint>,
|
||||
) -> IdeResult<Vec<BreakpointState>> {
|
||||
host.debugger.set_breakpoints(path, breakpoints).await
|
||||
host.debugger.set_breakpoints(host.owner_window(window), path, breakpoints).await
|
||||
}
|
||||
|
||||
/// Replaces all of this window's line breakpoints with `files`.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn debug_replace_breakpoints(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
files: std::collections::BTreeMap<PathBuf, Vec<Breakpoint>>,
|
||||
) -> IdeResult<()> {
|
||||
host.debugger.replace_breakpoints(host.owner_window(window), files).await
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
@@ -629,18 +677,20 @@ pub fn debug_capabilities(host: &Host, session: DebugSessionId) -> IdeResult<Deb
|
||||
#[command(trust = trusted)]
|
||||
pub async fn debug_set_function_breakpoints(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
breakpoints: Vec<FunctionBreakpoint>,
|
||||
) -> IdeResult<Vec<BreakpointState>> {
|
||||
host.debugger.set_function_breakpoints(breakpoints).await
|
||||
host.debugger.set_function_breakpoints(host.owner_window(window), breakpoints).await
|
||||
}
|
||||
|
||||
/// Field watchpoints; states aligned with `breakpoints`.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn debug_set_data_breakpoints(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
breakpoints: Vec<DataBreakpoint>,
|
||||
) -> IdeResult<Vec<BreakpointState>> {
|
||||
host.debugger.set_data_breakpoints(breakpoints).await
|
||||
host.debugger.set_data_breakpoints(host.owner_window(window), breakpoints).await
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
@@ -916,6 +966,64 @@ mod tests {
|
||||
assert_eq!(add_java_agents(config.clone(), &[]).extra_json, config.extra_json);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn enhanced_class_redefinition_is_taken_from_the_launch_extras() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let jdk = |name: &str, implementor: &str| {
|
||||
let home = tmp.path().join(name);
|
||||
std::fs::create_dir_all(home.join("bin")).unwrap();
|
||||
std::fs::write(home.join("release"), format!("IMPLEMENTOR=\"{implementor}\"\n")).unwrap();
|
||||
std::fs::write(home.join("bin/java"), "").unwrap();
|
||||
home.join("bin/java").to_string_lossy().into_owned()
|
||||
};
|
||||
let (jbr, temurin) = (jdk("jbr", "JetBrains s.r.o."), jdk("temurin", "Eclipse Adoptium"));
|
||||
let extras = |config: &LaunchConfig| {
|
||||
serde_json::from_str::<serde_json::Value>(config.extra_json.as_deref().unwrap()).unwrap()
|
||||
};
|
||||
|
||||
let mut config = launch(
|
||||
"java-debug",
|
||||
"launch",
|
||||
serde_json::json!({"javaExec": jbr, "vmArgs": "-Xmx1g", "enhancedClassRedefinition": true}),
|
||||
);
|
||||
assert_eq!(take_enhanced_redefinition(&mut config), Some(Ok(ide_run::java_hotswap::OPTION)));
|
||||
assert!(extras(&config).get("enhancedClassRedefinition").is_none(), "not passed on to the adapter");
|
||||
assert_eq!(extras(&config)["vmArgs"], "-Xmx1g");
|
||||
|
||||
let mut config =
|
||||
launch("java-debug", "launch", serde_json::json!({"javaExec": temurin, "enhancedClassRedefinition": true}));
|
||||
let note = take_enhanced_redefinition(&mut config).unwrap().unwrap_err();
|
||||
assert!(note.contains("is not a JetBrains Runtime"), "{note}");
|
||||
let mut config = launch("java-debug", "launch", serde_json::json!({"enhancedClassRedefinition": true}));
|
||||
assert!(take_enhanced_redefinition(&mut config).unwrap().unwrap_err().contains("is unknown"));
|
||||
|
||||
// Off, absent, or not a JVM the debugger starts: nothing to add, and no note.
|
||||
for (adapter, request, extra) in [
|
||||
("java-debug", "launch", serde_json::json!({"javaExec": jbr, "enhancedClassRedefinition": false})),
|
||||
("java-debug", "launch", serde_json::json!({"javaExec": jbr})),
|
||||
("java-debug", "attach", serde_json::json!({"javaExec": jbr, "enhancedClassRedefinition": true})),
|
||||
] {
|
||||
let mut config = launch(adapter, request, extra);
|
||||
assert_eq!(take_enhanced_redefinition(&mut config), None);
|
||||
assert!(extras(&config).get("enhancedClassRedefinition").is_none());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_executor_is_taken_out_of_the_launch_extras() {
|
||||
let extras = |config: &LaunchConfig| {
|
||||
serde_json::from_str::<serde_json::Value>(config.extra_json.as_deref().unwrap()).unwrap()
|
||||
};
|
||||
let mut config =
|
||||
launch("java-debug", "launch", serde_json::json!({"vmArgs": "-Xmx1g", "executor": "acme.reload"}));
|
||||
assert_eq!(take_executor(&mut config).as_deref(), Some("acme.reload"));
|
||||
assert!(extras(&config).get("executor").is_none(), "not passed on to the adapter");
|
||||
assert_eq!(extras(&config)["vmArgs"], "-Xmx1g");
|
||||
let mut plain = launch("java-debug", "launch", serde_json::json!({"vmArgs": "-Xmx1g"}));
|
||||
assert_eq!(take_executor(&mut plain), None);
|
||||
assert_eq!(extras(&plain)["vmArgs"], "-Xmx1g");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn debug_server_port_only_for_local_java_debug() {
|
||||
let port = |adapter: &str, request: &str, extra| debug_server_port(&launch(adapter, request, extra));
|
||||
@@ -962,6 +1070,7 @@ ide_command::domain!(
|
||||
debug_listen_for_jvm,
|
||||
debug_pause,
|
||||
debug_redefine_classes,
|
||||
debug_replace_breakpoints,
|
||||
debug_resolve_variable,
|
||||
debug_restart_frame,
|
||||
debug_resume,
|
||||
|
||||
@@ -81,8 +81,8 @@ pub async fn doc_set_line_ending(host: &Host, window: &str, doc: DocId, line_end
|
||||
|
||||
/// Structure view: LSP document symbols when available (with tree-sitter
|
||||
/// visibility and type-alias kinds), tree-sitter otherwise.
|
||||
/// Tree-sitter answers come from the per-document tree cache (incremental
|
||||
/// re-parse); large documents get no syntax structure.
|
||||
/// Normal files reuse the per-document tree cache. Large Markdown files use
|
||||
/// the syntax parser's size limit for heading outlines.
|
||||
#[command(trust = always)]
|
||||
pub async fn doc_outline(host: &Host, window: &str, doc: DocId) -> IdeResult<Vec<OutlineItem>> {
|
||||
let project = host.project(window)?;
|
||||
@@ -118,7 +118,7 @@ pub async fn doc_outline(host: &Host, window: &str, doc: DocId) -> IdeResult<Vec
|
||||
}
|
||||
items
|
||||
}
|
||||
None if snap.large => Vec::new(),
|
||||
None if snap.large && snap.language.as_str() != "markdown" => Vec::new(),
|
||||
None => syntax(),
|
||||
})
|
||||
})
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
//! HTTP Client commands shared by the desktop shell's IPC commands and the remote server: a remote
|
||||
//! window sends its requests from the project host and keeps their history there.
|
||||
use crate::Host;
|
||||
use ide_command::command;
|
||||
use ide_core::{IdeResult, IpcPath, Location, RequestId};
|
||||
use ide_http::{HistoryEntry, HttpExchange};
|
||||
use std::path::PathBuf;
|
||||
|
||||
use super::blocking;
|
||||
|
||||
/// The root of the window's project, when one is open.
|
||||
fn root(host: &Host, window: &str) -> Option<PathBuf> {
|
||||
host.project(window).ok().map(|p| p.root.clone())
|
||||
}
|
||||
|
||||
/// Environment names from the `http-client(.private).env.json` files that apply to `path`.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn http_environments(host: &Host, window: &str, path: Option<IpcPath>) -> IdeResult<Vec<String>> {
|
||||
let root = root(host, window);
|
||||
blocking(move || ide_http::environments(path.as_deref(), root.as_deref())).await
|
||||
}
|
||||
|
||||
/// Sends request `index` of `text` (the editor buffer of `path`) and records
|
||||
/// the exchange in the response history. Cancel with `cancel_request(request)`.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn http_execute(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
request: RequestId,
|
||||
path: Option<IpcPath>,
|
||||
text: String,
|
||||
index: u32,
|
||||
env: Option<String>,
|
||||
) -> IdeResult<HttpExchange> {
|
||||
let project = host.project(window)?;
|
||||
let cancel = host.begin_request(request);
|
||||
let input = ide_http::RunInput {
|
||||
text: &text,
|
||||
index,
|
||||
file: path.as_deref(),
|
||||
root: Some(&project.root),
|
||||
env: env.as_deref(),
|
||||
};
|
||||
let result = ide_http::run(input, &cancel).await;
|
||||
host.end_request(request);
|
||||
let exchange = result?;
|
||||
let history = project.http_history.clone();
|
||||
let saved = exchange.clone();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
if let Err(e) = history.add(&saved) {
|
||||
tracing::warn!("http history: {}", e.message);
|
||||
}
|
||||
});
|
||||
Ok(exchange)
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub fn http_history(host: &Host, window: &str) -> IdeResult<Vec<HistoryEntry>> {
|
||||
Ok(host.project(window)?.http_history.list())
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub fn http_history_get(host: &Host, window: &str, id: String) -> IdeResult<HttpExchange> {
|
||||
host.project(window)?.http_history.get(&id)
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub fn http_history_clear(host: &Host, window: &str) -> IdeResult<()> {
|
||||
host.project(window)?.http_history.clear()
|
||||
}
|
||||
|
||||
/// Convert to cURL and Copy: request `index` of `text` (the editor buffer of `path`), with
|
||||
/// the variables of `env` substituted, as a cURL command.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn http_curl(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
path: Option<IpcPath>,
|
||||
text: String,
|
||||
index: u32,
|
||||
env: Option<String>,
|
||||
) -> IdeResult<String> {
|
||||
let root = root(host, window);
|
||||
blocking(move || {
|
||||
ide_http::curl(&ide_http::RunInput {
|
||||
text: &text,
|
||||
index,
|
||||
file: path.as_deref(),
|
||||
root: root.as_deref(),
|
||||
env: env.as_deref(),
|
||||
})
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// The environment file for the request file `path` (`is_private`: the private one): the nearest
|
||||
/// existing one, else a new one next to it.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn http_environment_file(host: &Host, window: &str, path: IpcPath, is_private: bool) -> IdeResult<IpcPath> {
|
||||
let root = root(host, window);
|
||||
blocking(move || ide_http::env::environment_file(&path, root.as_deref(), is_private).map(IpcPath::from)).await
|
||||
}
|
||||
|
||||
/// Where `{{name}}` is defined in the environment files that apply to request file `path`
|
||||
/// (Navigate › Declaration on a variable), private file first.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn http_variable_definitions(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
path: IpcPath,
|
||||
name: String,
|
||||
) -> IdeResult<Vec<Location>> {
|
||||
let root = root(host, window);
|
||||
blocking(move || Ok(ide_http::env::variable_definitions(&path, root.as_deref(), &name))).await
|
||||
}
|
||||
|
||||
ide_command::domain!(
|
||||
http: http_curl,
|
||||
http_environment_file,
|
||||
http_environments,
|
||||
http_execute,
|
||||
http_history,
|
||||
http_history_clear,
|
||||
http_history_get,
|
||||
http_variable_definitions,
|
||||
);
|
||||
@@ -69,16 +69,15 @@ pub(crate) async fn resolve_launch(
|
||||
progress("Resolving the module");
|
||||
let project = host.project(window)?;
|
||||
let module = ide_core::project_roots::resolve(&project.root, &module);
|
||||
let scope = {
|
||||
let scope = std::sync::Arc::new({
|
||||
let (project, module) = (project.clone(), module.clone());
|
||||
tokio::task::spawn_blocking(move || workspace::scope_for(&project, &module))
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()))??
|
||||
};
|
||||
});
|
||||
if !project.lsp.java_served_by_jdtls(&module) {
|
||||
return resolve_launch_without_jdtls(host, &project, module, scope, test, policy, cancel, events).await;
|
||||
}
|
||||
let scope = std::sync::Arc::new(scope);
|
||||
let launches = project.java_launches.for_cache(&scope.cache);
|
||||
let prefer_maven = scope.settings.languages.java.maven.delegate_build;
|
||||
// A launch builds incrementally unless the configuration asks for Rebuild or NoBuild.
|
||||
@@ -110,6 +109,10 @@ pub(crate) async fn resolve_launch(
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()))?
|
||||
};
|
||||
// A dependency-only POM has no Java project in jdtls, but is a valid launch classpath.
|
||||
if is_maven_aggregator(&scope.root, &model, &module) {
|
||||
return resolve_launch_without_jdtls(host, &project, module, scope, test, policy, cancel, events).await;
|
||||
}
|
||||
// A Maven or Gradle module is built by the IDE's Java build ([`served_by_service`]), unless
|
||||
// the launch debugs with java-debug, whose HotSwap reloads what jdtls compiles (ecj's
|
||||
// classes differ from javac's: lambda names). jdtls keeps building for its diagnostics
|
||||
@@ -383,6 +386,10 @@ fn is_maven_module(root: &Path, model: &BuildModel, module: &Path) -> bool {
|
||||
model.maven.as_ref().is_some_and(|m| m.projects.iter().any(|p| root.join(&p.dir) == module))
|
||||
}
|
||||
|
||||
fn is_maven_aggregator(root: &Path, model: &BuildModel, module: &Path) -> bool {
|
||||
model.maven.as_ref().is_some_and(|m| m.projects.iter().any(|p| root.join(&p.dir) == module && p.packaging == "pom"))
|
||||
}
|
||||
|
||||
/// Whether the IDE's Java build builds the module holding `path` (#4078): a Maven module unless
|
||||
/// Settings › Maven › Delegate IDE build/run actions to Maven asks for Maven; a Gradle module
|
||||
/// when Settings › Gradle › Build and run using asks for the IDE.
|
||||
@@ -418,31 +425,32 @@ fn gradle_served(settings: &Settings) -> bool {
|
||||
|
||||
/// A launch of a module jdtls doesn't serve (another Java language server, or none): the
|
||||
/// build tool compiles it, and the classpath comes from that server, else from Maven.
|
||||
/// Dependency-only Maven POMs also use this path, without querying a Java language server.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
async fn resolve_launch_without_jdtls(
|
||||
host: &Host,
|
||||
project: &std::sync::Arc<crate::Project>,
|
||||
module: PathBuf,
|
||||
scope: workspace::Scope,
|
||||
scope: std::sync::Arc<workspace::Scope>,
|
||||
test: bool,
|
||||
policy: BuildPolicy,
|
||||
cancel: &CancellationToken,
|
||||
events: Option<LaunchEvents>,
|
||||
) -> IdeResult<JavaLaunchInfo> {
|
||||
let started = std::time::Instant::now();
|
||||
let scope = std::sync::Arc::new(scope);
|
||||
let kind = if policy == BuildPolicy::Rebuild { compile::BuildKind::Rebuild } else { compile::BuildKind::Build };
|
||||
let (model, built, by_service) = {
|
||||
let (scope, module, cancel, events) = (scope.clone(), module.clone(), cancel.clone(), events.clone());
|
||||
let (service, data_dir) = (host.java_build.clone(), host.local_data_dir.clone());
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let model = load_launch_model(&scope);
|
||||
let aggregator = is_maven_aggregator(&scope.root, &model, &module);
|
||||
let on_event = |event: BuildEvent| {
|
||||
if let Some(events) = &events {
|
||||
events(event);
|
||||
}
|
||||
};
|
||||
if policy == BuildPolicy::NoBuild {
|
||||
if policy == BuildPolicy::NoBuild && !aggregator {
|
||||
return (model, None, false);
|
||||
}
|
||||
if served_by_service(&scope.root, &model, &scope.settings, &module)
|
||||
@@ -455,7 +463,7 @@ async fn resolve_launch_without_jdtls(
|
||||
&model,
|
||||
&module,
|
||||
test,
|
||||
Some(kind),
|
||||
(policy != BuildPolicy::NoBuild).then_some(kind),
|
||||
&cancel,
|
||||
&on_event,
|
||||
) {
|
||||
@@ -467,6 +475,9 @@ async fn resolve_launch_without_jdtls(
|
||||
Err(e) => return (model, Some(Err(e)), false),
|
||||
}
|
||||
}
|
||||
if policy == BuildPolicy::NoBuild {
|
||||
return (model, None, false);
|
||||
}
|
||||
let built = compile::build_for_launch(&scope.root, &model, &module, test, kind, &cancel, &on_event);
|
||||
(model, Some(built), false)
|
||||
})
|
||||
@@ -486,14 +497,17 @@ async fn resolve_launch_without_jdtls(
|
||||
)));
|
||||
}
|
||||
Some(Ok(built)) => {
|
||||
info.build = Some(match built.failure {
|
||||
let status = match built.failure {
|
||||
None => JavaBuildStatus::Succeeded,
|
||||
Some(failure) if policy == BuildPolicy::MakeAndContinueOnErrors => {
|
||||
info.hints.push(failure);
|
||||
JavaBuildStatus::Failed
|
||||
}
|
||||
Some(failure) => return Err(IdeError::internal(failure)),
|
||||
});
|
||||
};
|
||||
if policy != BuildPolicy::NoBuild {
|
||||
info.build = Some(status);
|
||||
}
|
||||
class_paths.extend(built.class_dirs.iter().map(|p| p.to_string_lossy().into_owned()));
|
||||
}
|
||||
}
|
||||
@@ -501,7 +515,8 @@ async fn resolve_launch_without_jdtls(
|
||||
if let Some(events) = &events {
|
||||
events(BuildEvent::Progress { message: "Resolving the classpath".into(), fraction: None });
|
||||
}
|
||||
let from_server = project.lsp.java_server_classpath(&module, test, cancel).await?;
|
||||
let aggregator = is_maven_aggregator(&scope.root, &model, &module);
|
||||
let from_server = if aggregator { None } else { project.lsp.java_server_classpath(&module, test, cancel).await? };
|
||||
let data_dir = host.local_data_dir.clone();
|
||||
let cancel = cancel.clone();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
@@ -527,7 +542,11 @@ async fn resolve_launch_without_jdtls(
|
||||
));
|
||||
}
|
||||
let local_repo = ide_sdk::apply::maven_local_repository(root, settings);
|
||||
let classpath = compile::module_classpath(root, &model, &module, test, local_repo, cache, &cancel)?;
|
||||
let classpath = if aggregator && policy == BuildPolicy::NoBuild {
|
||||
compile::module_classpath_without_build(root, &model, &module, test, cache, &cancel)?
|
||||
} else {
|
||||
compile::module_classpath(root, &model, &module, test, local_repo, cache, &cancel)?
|
||||
};
|
||||
append_unique_class_paths(
|
||||
&mut class_paths,
|
||||
std::env::split_paths(&classpath).map(|p| p.to_string_lossy().into_owned()),
|
||||
@@ -902,7 +921,8 @@ pub async fn java_build_workspace(
|
||||
|
||||
/// The JVM of OpenIDEA's JUnit runner for the module at `module`, given its resolved test classpath:
|
||||
/// the classpath with the runner and `junit-platform-launcher` of the engine's version (unless the
|
||||
/// classpath has one; from the engine's repository, else downloaded once from Maven Central), and,
|
||||
/// classpath has one, or has JUnit 4 alone; from the engine's repository, else downloaded once from
|
||||
/// Maven Central), and,
|
||||
/// for a Maven module, what its Surefire configuration gives the forked test JVM.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn java_junit_runner(
|
||||
@@ -926,13 +946,13 @@ pub async fn java_junit_runner(
|
||||
let runner = ide_sdk::java::junit_runner_jar(&data_dir)
|
||||
.ok_or_else(|| IdeError::internal("Cannot install the JUnit runner"))?;
|
||||
let launcher = match ide_sdk::java::junit_launcher(&class_paths) {
|
||||
ide_sdk::java::JunitLauncher::OnClasspath => None,
|
||||
ide_sdk::java::JunitLauncher::OnClasspath | ide_sdk::java::JunitLauncher::Junit4 => None,
|
||||
ide_sdk::java::JunitLauncher::Found(path) => Some(path),
|
||||
ide_sdk::java::JunitLauncher::Missing(version) => Some(download_junit_launcher(&data_dir, &version)?),
|
||||
ide_sdk::java::JunitLauncher::NoPlatform => {
|
||||
return Err(IdeError::unavailable(
|
||||
"No JUnit Platform (junit-platform-engine) on the test classpath. To run these tests through \
|
||||
Maven, set Settings › Build Tools › Maven › Run tests using to Maven.",
|
||||
"Neither JUnit 5 (junit-platform-engine) nor JUnit 4 is on the test classpath. To run these tests \
|
||||
through Maven, set Settings › Build Tools › Maven › Run tests using to Maven.",
|
||||
));
|
||||
}
|
||||
};
|
||||
|
||||
@@ -2292,6 +2292,7 @@ pub async fn plugin_language_visuals(host: &Host, window: &str, doc: DocId) -> I
|
||||
let project = host.project(window)?;
|
||||
let snap = project.documents.snapshot(doc)?;
|
||||
let generation = project.lsp.injection_generation();
|
||||
let root = project.root.clone();
|
||||
blocking(move || {
|
||||
let d = ProviderDocument {
|
||||
path: snap.path.0,
|
||||
@@ -2311,8 +2312,8 @@ pub async fn plugin_language_visuals(host: &Host, window: &str, doc: DocId) -> I
|
||||
{
|
||||
out.injections = plugins.provide_injections(&d);
|
||||
out.colors = plugins.language_colors(&d);
|
||||
out.gutter_actions = plugins.language_gutter_actions(&d);
|
||||
out.hover_actions = plugins.language_hover_actions(&d);
|
||||
out.gutter_actions = plugins.language_gutter_actions(&d, Some(&root));
|
||||
out.hover_actions = plugins.language_hover_actions(&d, Some(&root));
|
||||
}
|
||||
project.lsp.set_injections_at(
|
||||
doc,
|
||||
|
||||
@@ -19,6 +19,7 @@ pub mod flutter;
|
||||
pub mod fs;
|
||||
pub mod heap;
|
||||
pub mod history;
|
||||
pub mod http;
|
||||
pub mod java;
|
||||
pub mod jvm_icons;
|
||||
pub mod lsp;
|
||||
@@ -92,6 +93,7 @@ ide_command::domains!(
|
||||
fs: crate::ops::fs,
|
||||
heap: crate::ops::heap,
|
||||
history: crate::ops::history,
|
||||
http: crate::ops::http,
|
||||
java: crate::ops::java,
|
||||
jvm_icons: crate::ops::jvm_icons,
|
||||
lsp: crate::ops::lsp,
|
||||
|
||||
@@ -7,7 +7,7 @@ use crate::Project;
|
||||
use ide_command::command;
|
||||
use ide_core::{DocId, IdeResult, IpcPath, LanguageId, Location, Pos};
|
||||
use ide_index::{ExtensionCount, FileMatch, IndexStatus, SymbolFilter, SymbolMatch};
|
||||
use ide_language::{FileReference, WebReference};
|
||||
use ide_language::{CSS_VARIABLE, FileReference, WebReference};
|
||||
use ide_workspace::file_refs::{self, PathCompletion};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
@@ -25,6 +25,18 @@ pub struct WebGoto {
|
||||
|
||||
const MAX_WEB_TARGETS: usize = 200;
|
||||
|
||||
/// A custom property declaration (`--accent: #3b82f6`), for `var(--…)` completion and hover.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct CssVariable {
|
||||
pub name: String,
|
||||
/// The declared value, whitespace collapsed.
|
||||
pub value: Option<String>,
|
||||
pub location: Location,
|
||||
}
|
||||
|
||||
const MAX_CSS_VARIABLES: usize = 5000;
|
||||
|
||||
/// A Python class definition and the base names written in its source. The UI builds a
|
||||
/// name → locations index from every class in the project (attached dependency roots
|
||||
/// included) to compute ↑ overrides / ↓ overridden gutter markers without a language
|
||||
@@ -185,6 +197,41 @@ pub async fn web_goto(host: &Host, window: &str, doc: DocId, pos: Pos) -> IdeRes
|
||||
.await
|
||||
}
|
||||
|
||||
/// Custom properties declared in `doc` (from its current text, first) and in the project's
|
||||
/// other stylesheets (from the index, so kept up to date as files change).
|
||||
#[command(trust = always)]
|
||||
pub async fn web_css_variables(host: &Host, window: &str, doc: DocId) -> IdeResult<Vec<CssVariable>> {
|
||||
let project = host.project(window)?;
|
||||
let syntax = host.syntax();
|
||||
blocking(move || {
|
||||
let snap = project.documents.snapshot(doc)?;
|
||||
let own = if snap.large { Vec::new() } else { syntax.web_definitions(&snap.language, &snap.text) };
|
||||
let mut out: Vec<CssVariable> = own
|
||||
.into_iter()
|
||||
.filter(|t| t.kind == CSS_VARIABLE)
|
||||
.map(|t| CssVariable {
|
||||
name: t.name,
|
||||
value: t.container,
|
||||
location: Location { path: snap.path.clone(), range: t.range, uri: None },
|
||||
})
|
||||
.collect();
|
||||
out.extend(
|
||||
project
|
||||
.index
|
||||
.symbols_prefixed("--", CSS_VARIABLE, MAX_CSS_VARIABLES)
|
||||
.into_iter()
|
||||
.filter(|m| *m.path != *snap.path)
|
||||
.map(|m| CssVariable {
|
||||
name: m.name,
|
||||
value: m.container,
|
||||
location: Location { path: m.path, range: m.range, uri: None },
|
||||
}),
|
||||
);
|
||||
Ok(out)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// The file a Python import path (`a.b.c`, or `.x` relative to `from`) names; `None` when
|
||||
/// no project or content root has it.
|
||||
#[command(trust = always)]
|
||||
@@ -450,6 +497,7 @@ ide_command::domain!(
|
||||
recent_files,
|
||||
remove_recent,
|
||||
scope_files,
|
||||
web_css_variables,
|
||||
web_goto,
|
||||
web_unresolved_references,
|
||||
);
|
||||
@@ -22,6 +22,8 @@ pub struct ProjectInfo {
|
||||
pub workspace: Option<ide_workspace::workspace::Workspace>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub unity: Option<ide_workspace::unity::UnityProjectInfo>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub unreal: Option<ide_workspace::unreal::UnrealProjectInfo>,
|
||||
}
|
||||
|
||||
pub fn info(project: &Project) -> ProjectInfo {
|
||||
@@ -45,6 +47,7 @@ pub fn info(project: &Project) -> ProjectInfo {
|
||||
root: project.root.clone().into(),
|
||||
workspace,
|
||||
unity: ide_workspace::unity::detect(&project.root),
|
||||
unreal: ide_workspace::unreal::detect(&project.root),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -122,6 +125,14 @@ pub fn settings_set(
|
||||
if key == "mcpServer" || key.starts_with("mcpServer.") {
|
||||
host.mcp.apply(host);
|
||||
}
|
||||
if key == "terminal" || key.starts_with("terminal.") {
|
||||
super::term::apply_output_rate(host, window);
|
||||
}
|
||||
if "languages.typescript.watchProblems".starts_with(&key)
|
||||
&& let Some(watch) = host.project(window).ok().and_then(|p| p.tsc_watch.clone())
|
||||
{
|
||||
watch.apply(&host.runtime);
|
||||
}
|
||||
let sink = host.window_sink(window);
|
||||
sink.emit(IdeEvent::SettingsChanged { key });
|
||||
if let Some(root) = applied.roots_changed {
|
||||
@@ -279,6 +290,36 @@ fn refresh_workspace(project: &Project) {
|
||||
project.sink.emit(ide_core::IdeEvent::ProjectRootsChanged { root: project.root.clone().into() });
|
||||
}
|
||||
|
||||
/// Records `project` in `recent` (its branch, unless attached to a workspace, and display name).
|
||||
pub fn record_recent(recent: &ide_workspace::RecentProjects, project: &Project) -> IdeResult<()> {
|
||||
let info = info(project);
|
||||
let attached = info.workspace.as_ref().is_some_and(|w| !w.is_container(&project.root));
|
||||
let branch = if attached {
|
||||
None
|
||||
} else {
|
||||
project.repos.read().primary().and_then(|r| r.branch_info().ok()).and_then(|b| b.head)
|
||||
};
|
||||
recent.touch(&project.root, branch)?;
|
||||
recent.rename(&project.root, Some(&info.display_name))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// File › Rename Project…: the display name of `window`'s project; an empty `name` restores the
|
||||
/// folder name. A workspace container renames the workspace, else it is stored in project settings.
|
||||
pub fn rename(host: &Host, window: &str, name: &str) -> IdeResult<Arc<Project>> {
|
||||
let project = host.project(window)?;
|
||||
let name = name.trim();
|
||||
if let Some(workspace) = ide_workspace::workspace::Workspace::load(&project.root)?
|
||||
&& workspace.is_container(&project.root)
|
||||
{
|
||||
save_workspace(host, window, name, workspace.projects)?;
|
||||
} else {
|
||||
let value = if name.is_empty() { serde_json::Value::Null } else { serde_json::Value::String(name.to_owned()) };
|
||||
project.settings.set(SettingsScope::Project, "general.projectName", value)?;
|
||||
}
|
||||
Ok(project)
|
||||
}
|
||||
|
||||
/// Attaches a trusted folder without replacing the current project.
|
||||
pub fn attach_workspace(host: &Host, window: &str, path: &Path) -> IdeResult<ide_core::IpcPath> {
|
||||
let project = host.project(window)?;
|
||||
|
||||
@@ -319,6 +319,7 @@ pub async fn run_start(
|
||||
on_output: Channel<OutputChunk>,
|
||||
request: Option<ide_core::RequestId>,
|
||||
) -> IdeResult<RunInfo> {
|
||||
super::term::apply_output_rate(host, window);
|
||||
let on_output: Emit<OutputChunk> = Arc::new(move |chunk| {
|
||||
let _ = on_output.send(chunk);
|
||||
});
|
||||
@@ -558,7 +559,8 @@ async fn start_inner(
|
||||
|
||||
/// 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.
|
||||
/// run target gets none; the console says so, and why an approved agent was left out. A launch
|
||||
/// through a plugin executor (`extras.executor`) also gets that plugin's executor-bound agent.
|
||||
fn add_java_agents(config: &mut RunConfig, on_output: &Emit<OutputChunk>, run_dir: Option<&Path>) {
|
||||
if !ide_run::java_agent::applies(&config.kind) {
|
||||
return;
|
||||
@@ -574,7 +576,7 @@ fn add_java_agents(config: &mut RunConfig, on_output: &Emit<OutputChunk>, run_di
|
||||
.or_else(|| std::env::var_os("JAVA_HOME").map(std::path::PathBuf::from));
|
||||
ide_run::java_agent::launched_java(&config.command, &search, home.as_deref())
|
||||
});
|
||||
let agents = ide_run::java_agent::current_for(java.as_deref());
|
||||
let agents = ide_run::java_agent::current_for_executor(java.as_deref(), config.extras.executor.as_deref());
|
||||
let say = |text: &str| on_output(OutputChunk::System { text: format!("{text}\n") });
|
||||
if run_dir.is_none() {
|
||||
if !agents.options.is_empty() {
|
||||
|
||||
@@ -30,8 +30,13 @@ impl ReplaceHost for DocumentsHost<'_> {
|
||||
continue;
|
||||
}
|
||||
docs.apply_edits(doc, &edits)?;
|
||||
if save {
|
||||
// An open tab's file may have changed on disk before the watcher reported it:
|
||||
// autosave keeps that change and leaves the replacement unsaved. A file opened
|
||||
// just for this was read now.
|
||||
if transient {
|
||||
docs.save(doc)?;
|
||||
} else if save {
|
||||
docs.autosave(doc)?;
|
||||
}
|
||||
return Ok(edits.len() as u32);
|
||||
}
|
||||
@@ -50,7 +55,9 @@ impl ReplaceHost for DocumentsHost<'_> {
|
||||
/// Edits go through the document layer as one patch per file, so open editors
|
||||
/// update live and undo the whole file's replacements in one step. Unsaved
|
||||
/// editor buffers are replaced in place and left unsaved; other open documents
|
||||
/// are saved, and files that were not open are opened transiently, saved and closed.
|
||||
/// are saved unless the file changed on disk meanwhile (then the replacement stays
|
||||
/// unsaved, as autosave does), and files that were not open are opened
|
||||
/// transiently, saved and closed.
|
||||
///
|
||||
/// With `all_in_scope` (Replace All after the search hit its match limit) the
|
||||
/// scope is searched again without the limit and every match in it is replaced,
|
||||
|
||||
@@ -29,6 +29,7 @@ pub async fn term_spawn(
|
||||
mut options: TerminalOptions,
|
||||
on_output: Channel<String>,
|
||||
) -> IdeResult<TerminalInfo> {
|
||||
apply_output_rate(host, window);
|
||||
if !host.project(window).is_ok_and(|p| p.is_trusted()) {
|
||||
// Project terminal settings can otherwise start a command as soon as a tab restores.
|
||||
let global = host.global_settings.effective().terminal;
|
||||
@@ -61,6 +62,17 @@ pub async fn term_spawn(
|
||||
Ok(info)
|
||||
}
|
||||
|
||||
/// Settings › Tools › Terminal › Max FPS also paces the terminal and Run console output
|
||||
/// pumps (#5897): applied from the window's effective settings when a session starts and
|
||||
/// when the setting changes. The rate is process-wide; the last window to apply it wins.
|
||||
pub(crate) fn apply_output_rate(host: &Host, window: &str) {
|
||||
let terminal = match host.project(window) {
|
||||
Ok(project) => project.settings.effective().terminal,
|
||||
Err(_) => host.global_settings.effective().terminal,
|
||||
};
|
||||
ide_core::output_rate::set_max_fps(&terminal.max_fps);
|
||||
}
|
||||
|
||||
/// Tools › Start SSH Session: a login shell on SSH configuration `id`, opened by the
|
||||
/// built-in client with the configuration's saved password, key or agent.
|
||||
pub async fn spawn_ssh(
|
||||
|
||||
@@ -24,6 +24,12 @@ struct LogAccess {
|
||||
cache: PathBuf,
|
||||
}
|
||||
|
||||
fn external_log_of(host: &Host, window: &str, path: &Path) -> Option<std::sync::Arc<Repo>> {
|
||||
host.external_logs.read().get(host.owner_window(window)).and_then(|repos| {
|
||||
repos.iter().filter(|r| path.starts_with(r.root())).max_by_key(|r| r.root().components().count()).cloned()
|
||||
})
|
||||
}
|
||||
|
||||
/// Immutable Git objects exposed through the editor's ordinary read-only VFS.
|
||||
/// `encoding` re-decodes the blob with it ("Reload with Encoding") instead of
|
||||
/// the project's detection.
|
||||
@@ -81,9 +87,7 @@ async fn revision_text(
|
||||
encoding: Option<&str>,
|
||||
) -> IdeResult<Option<(String, &'static encoding_rs::Encoding, bool)>> {
|
||||
let project = host.project(window).ok();
|
||||
let external = host.external_logs.read().get(host.owner_window(window)).and_then(|rs| {
|
||||
rs.iter().filter(|r| path.starts_with(r.root())).max_by_key(|r| r.root().components().count()).cloned()
|
||||
});
|
||||
let external = external_log_of(host, window, path);
|
||||
let (path, rev, encoding) = (path.to_path_buf(), rev.to_owned(), encoding.map(str::to_owned));
|
||||
blocking(move || {
|
||||
fn with_repo<T>(
|
||||
@@ -622,9 +626,7 @@ pub async fn vcs_staging_line_hunks(
|
||||
#[command(trust = always)]
|
||||
pub async fn vcs_file_at(host: &Host, window: &str, path: PathBuf, rev: Option<String>) -> IdeResult<Option<String>> {
|
||||
let project = host.project(window).ok();
|
||||
let external = host.external_logs.read().get(host.owner_window(window)).and_then(|rs| {
|
||||
rs.iter().filter(|r| path.starts_with(r.root())).max_by_key(|r| r.root().components().count()).cloned()
|
||||
});
|
||||
let external = external_log_of(host, window, &path);
|
||||
blocking(move || {
|
||||
if let Some(project) = project {
|
||||
return project.with_log_backend_of(&path, |r| {
|
||||
@@ -640,14 +642,37 @@ pub async fn vcs_file_at(host: &Host, window: &str, path: PathBuf, rev: Option<S
|
||||
.await
|
||||
}
|
||||
|
||||
/// An image at the selected Git revision or index stage as a data URL, absent if the path is missing.
|
||||
#[command(trust = always)]
|
||||
pub async fn vcs_image_at(host: &Host, window: &str, path: PathBuf, rev: String) -> IdeResult<Option<String>> {
|
||||
let project = host.project(window).ok();
|
||||
let external = external_log_of(host, window, &path);
|
||||
blocking(move || {
|
||||
let mime = ide_vfs::image_mime(&path)
|
||||
.ok_or_else(|| ide_core::IdeError::invalid(format!("{} is not a supported image", path.display())))?;
|
||||
let read = |repo: &Repo| repo.file_bytes_at_bounded(&path, &rev, ide_vfs::MAX_IMAGE_SIZE as usize);
|
||||
let bytes = if let Some(project) = project {
|
||||
if !ide_vfs::on_local_drive(&path)
|
||||
&& external.is_none()
|
||||
&& !project.repos().all().iter().any(|repo| ide_vfs::same_share(repo.root(), &path))
|
||||
{
|
||||
return Err(ide_core::IdeError::invalid("image is not on a local drive or an opened share"));
|
||||
}
|
||||
project.with_log_repo_of(&path, read)?
|
||||
} else {
|
||||
read(external.as_deref().ok_or_else(|| ide_core::IdeError::unavailable("external Git log is not open"))?)?
|
||||
};
|
||||
Ok(bytes.map(|bytes| format!("data:{mime};base64,{}", ide_vfs::base64(&bytes))))
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// The file's git mode at `rev` (`100644`, `100755`, `120000`…), `"WT"` for the
|
||||
/// worktree; `None` when absent there. Lets the diff viewer report a mode-only change.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn vcs_file_mode(host: &Host, window: &str, path: PathBuf, rev: Option<String>) -> IdeResult<Option<String>> {
|
||||
let project = host.project(window).ok();
|
||||
let external = host.external_logs.read().get(host.owner_window(window)).and_then(|rs| {
|
||||
rs.iter().filter(|r| path.starts_with(r.root())).max_by_key(|r| r.root().components().count()).cloned()
|
||||
});
|
||||
let external = external_log_of(host, window, &path);
|
||||
blocking(move || {
|
||||
if let Some(project) = project {
|
||||
return project.with_log_backend_of(&path, |r| r.file_mode_at(&path, rev.as_deref()));
|
||||
@@ -3200,6 +3225,7 @@ ide_command::domain!(
|
||||
vcs_discard,
|
||||
vcs_edit_remote,
|
||||
vcs_file_at,
|
||||
vcs_image_at,
|
||||
vcs_file_mode,
|
||||
vcs_diff_entries,
|
||||
vcs_git_version,
|
||||
|
||||
@@ -8,7 +8,7 @@ use ide_core::proxy_settings::{ProxyMode, ProxySettings};
|
||||
use std::time::Duration;
|
||||
|
||||
/// Whether `url` names this machine (`localhost` or a loopback address).
|
||||
pub fn is_loopback(url: &reqwest::Url) -> bool {
|
||||
fn is_loopback(url: &reqwest::Url) -> bool {
|
||||
let host = url.host_str().unwrap_or_default().trim_start_matches('[').trim_end_matches(']');
|
||||
host.eq_ignore_ascii_case("localhost") || host.parse::<std::net::IpAddr>().is_ok_and(|ip| ip.is_loopback())
|
||||
}
|
||||
|
||||
@@ -68,6 +68,17 @@ pub trait PluginWorkspace: Send + Sync {
|
||||
fn problems(&self, _client: &str, _path: Option<&Path>) -> Result<Vec<ide_plugin::FileProblems>, HostError> {
|
||||
Ok(Vec::new())
|
||||
}
|
||||
/// Fork a recorded native agent session into a new task in the invoking
|
||||
/// window's project, returning the new task id (API 1.18).
|
||||
fn fork_agent_session(
|
||||
&self,
|
||||
_client: &str,
|
||||
_agent: &str,
|
||||
_session_id: &str,
|
||||
_cwd: &Path,
|
||||
) -> Result<String, HostError> {
|
||||
Err(HostError::Failed("agent fork unavailable".into()))
|
||||
}
|
||||
|
||||
/// Roots of the open projects.
|
||||
fn projects(&self) -> Vec<PathBuf>;
|
||||
@@ -675,6 +686,9 @@ pub(super) struct Shared {
|
||||
net_prompts: Mutex<HashMap<String, Option<Instant>>>,
|
||||
pub net_hosts_session_only: AtomicBool,
|
||||
session_net_hosts: Mutex<HashMap<String, BTreeSet<String>>>,
|
||||
/// Setting-derived approvals kept for the session only (remote hosts),
|
||||
/// plugin → `net:setting:` grant → its approved host.
|
||||
pub(super) session_setting_hosts: Mutex<HashMap<String, BTreeMap<String, String>>>,
|
||||
pub(super) next_prompt: AtomicU64,
|
||||
pub(super) run_configurations: super::run_detectors::DynamicConfigurations,
|
||||
pub(super) run_targets: Mutex<super::run_targets::Targets>,
|
||||
@@ -695,8 +709,11 @@ pub(super) struct Shared {
|
||||
pub(super) closed_clients: Mutex<BTreeSet<String>>,
|
||||
/// plugin → kinds subscribed at run time (kept across idle reclaim).
|
||||
pub subscriptions: Mutex<super::event_paths::Subscriptions>,
|
||||
/// Paths outside their project that plugins watch (kept across idle reclaim).
|
||||
pub(super) external_watches: super::external_watch::ExternalWatches,
|
||||
/// plugin → files it shows problems for, withdrawn when it stops.
|
||||
diagnostics: Mutex<HashMap<String, BTreeSet<PathBuf>>>,
|
||||
project_generations: Mutex<HashMap<PathBuf, u64>>,
|
||||
pub secrets: RwLock<Arc<dyn SecretStore>>,
|
||||
/// (plugin, `process:` capability) → the approved program.
|
||||
pub pins: Arc<RwLock<HashMap<(String, String), ProgramPin>>>,
|
||||
@@ -719,6 +736,29 @@ pub(super) struct Shared {
|
||||
/// A window's log tabs of one plugin: key → what it runs, oldest first.
|
||||
type LogTabs = Vec<(String, ide_plugin::ServiceLog)>;
|
||||
|
||||
/// The settings key a `net:setting:` grant derives its host from.
|
||||
fn setting_key(cap: &Capability) -> String {
|
||||
match cap {
|
||||
Capability::NetSetting { key, .. } => key.clone(),
|
||||
_ => String::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The host a setting value names: a bare host, or a URL the user pasted
|
||||
/// (`https://jira.corp.example/`), checked with the manifest host rules — a `*`
|
||||
/// is refused. `Ok(None)` when the value is empty (the setting is cleared).
|
||||
pub(super) fn setting_host(value: &str) -> Result<Option<String>, String> {
|
||||
let value = value.trim();
|
||||
if value.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
let host =
|
||||
if value.contains("://") { ide_plugin::net_host(value)? } else { value.trim_end_matches('.').to_owned() };
|
||||
ide_extension::manifest_host(&host)
|
||||
.map(Some)
|
||||
.map_err(|_| format!("{value:?} is not a host (example.com) or a URL (https://example.com/)"))
|
||||
}
|
||||
|
||||
/// Log tabs a plugin's code may have open in one window; opening more forgets
|
||||
/// the oldest (that tab can no longer start its program).
|
||||
const MAX_LOG_TABS: usize = 32;
|
||||
@@ -757,6 +797,7 @@ impl Shared {
|
||||
net_prompts: Mutex::default(),
|
||||
net_hosts_session_only: AtomicBool::new(false),
|
||||
session_net_hosts: Mutex::default(),
|
||||
session_setting_hosts: Mutex::default(),
|
||||
next_prompt: AtomicU64::new(1),
|
||||
run_configurations: Arc::default(),
|
||||
run_targets: Mutex::default(),
|
||||
@@ -773,11 +814,35 @@ impl Shared {
|
||||
contexts: Mutex::default(),
|
||||
closed_clients: Mutex::default(),
|
||||
subscriptions: Mutex::default(),
|
||||
external_watches: Default::default(),
|
||||
diagnostics: Mutex::default(),
|
||||
project_generations: Mutex::default(),
|
||||
log_tabs: Mutex::default(),
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn project_generation(&self, root: &Path) -> Result<u64, HostError> {
|
||||
let workspace = self.workspace().ok_or(HostError::Cancelled)?;
|
||||
if !workspace.projects().iter().any(|r| r == root) {
|
||||
return Err(HostError::NotFound("project is not open".into()));
|
||||
}
|
||||
let mut gens = self.project_generations.lock();
|
||||
Ok(*gens.entry(root.to_path_buf()).or_insert(1))
|
||||
}
|
||||
|
||||
pub(super) fn bump_project_generation(&self, root: &Path) -> u64 {
|
||||
let mut gens = self.project_generations.lock();
|
||||
let cur = gens.entry(root.to_path_buf()).or_insert(1);
|
||||
*cur = cur.saturating_add(1);
|
||||
*cur
|
||||
}
|
||||
|
||||
/// Moves a closed project's generation on rather than forgetting it, so a handle
|
||||
/// taken before the close stays stale if the project is opened again.
|
||||
pub(super) fn close_project_generation(&self, root: &Path) {
|
||||
self.bump_project_generation(root);
|
||||
}
|
||||
|
||||
pub(super) fn workspace(&self) -> Option<Arc<dyn PluginWorkspace>> {
|
||||
self.workspace.read().clone()
|
||||
}
|
||||
@@ -1000,6 +1065,7 @@ impl Shared {
|
||||
self.withdraw_prompts(plugin);
|
||||
self.net_prompts.lock().remove(plugin);
|
||||
self.session_net_hosts.lock().remove(plugin);
|
||||
self.session_setting_hosts.lock().remove(plugin);
|
||||
let removed: Vec<(Option<String>, String)> = {
|
||||
let mut contexts = self.contexts.lock();
|
||||
let keys: Vec<_> = contexts.keys().filter(|(_, p, _)| p == plugin).cloned().collect();
|
||||
@@ -1023,6 +1089,9 @@ impl Shared {
|
||||
let _ = workspace.publish_diagnostics(plugin, &path, Vec::new());
|
||||
}
|
||||
}
|
||||
if subscriptions {
|
||||
self.external_watches.remove_plugin(plugin);
|
||||
}
|
||||
if subscriptions && self.subscriptions.lock().remove(plugin) {
|
||||
self.sink.emit(None, PluginEvent::SubscriptionsChanged);
|
||||
}
|
||||
@@ -1493,6 +1562,73 @@ fn failed(e: impl std::fmt::Display) -> HostError {
|
||||
HostError::Failed(e.to_string())
|
||||
}
|
||||
|
||||
/// `cwd` of `open-terminal-session-in`: a directory of the project, relative to `root`
|
||||
/// (`""` is the root), that exists and stays inside the project once symlinks are resolved.
|
||||
fn project_subdirectory(root: &Path, cwd: &str) -> Result<PathBuf, HostError> {
|
||||
let invalid = |why: &str| HostError::Invalid(format!("terminal directory {cwd:?}: {why}"));
|
||||
if cwd.len() > 4096 || cwd.contains('\0') {
|
||||
return Err(invalid("not a path"));
|
||||
}
|
||||
let relative = Path::new(cwd);
|
||||
if relative.is_absolute() || relative.has_root() {
|
||||
return Err(invalid("must be relative to the project root"));
|
||||
}
|
||||
let base = dunce::canonicalize(root).map_err(|_| invalid("the project root is gone"))?;
|
||||
let dir = dunce::canonicalize(base.join(relative)).map_err(|_| invalid("no such directory"))?;
|
||||
if !dir.starts_with(&base) {
|
||||
return Err(invalid("outside the project"));
|
||||
}
|
||||
if !dir.is_dir() {
|
||||
return Err(invalid("not a directory"));
|
||||
}
|
||||
Ok(dir)
|
||||
}
|
||||
|
||||
impl PluginApi {
|
||||
/// The value of `key` the user set for this plugin, as a plain string
|
||||
/// (`None` when unset or not a string).
|
||||
pub(super) fn setting_value(&self, key: &str) -> Option<String> {
|
||||
let raw = self.setting(None, key)?;
|
||||
serde_json::from_str::<String>(&raw).ok()
|
||||
}
|
||||
|
||||
/// The plugin's `net:setting:` grants with their hosts: the approved host
|
||||
/// while the setting still holds it, and the pending one to approve
|
||||
/// otherwise (`None` when the value is unset or not a host).
|
||||
pub(super) fn net_setting_hosts(&self, subject: &Subject) -> Vec<(Capability, Option<String>, Option<String>)> {
|
||||
let derived: Vec<Capability> = self
|
||||
.pkg
|
||||
.manifest
|
||||
.capabilities
|
||||
.all()
|
||||
.filter(|c| matches!(c, Capability::NetSetting { .. }))
|
||||
.cloned()
|
||||
.collect();
|
||||
if derived.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
let ledger = self.shared.ledger.lock();
|
||||
let grant = ledger.get(subject).filter(|g| g.confirmed);
|
||||
let session = self.shared.session_setting_hosts.lock().get(self.id()).cloned().unwrap_or_default();
|
||||
derived
|
||||
.into_iter()
|
||||
.map(|cap| {
|
||||
let current = self.setting_value(&setting_key(&cap)).and_then(|v| setting_host(&v).ok()).flatten();
|
||||
let record = grant.and_then(|g| g.setting_hosts.get(&cap.to_string())).map(String::as_str);
|
||||
let session_host = session.get(&cap.to_string()).map(String::as_str);
|
||||
// An approval covers requests only while the setting still holds it.
|
||||
let approved = [record, session_host]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.find(|host| current.as_deref() == Some(host))
|
||||
.map(str::to_owned);
|
||||
let pending = current.filter(|host| approved.as_deref() != Some(host));
|
||||
(cap, approved, pending)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
impl HostApi for PluginApi {
|
||||
fn database_upsert(&self, root: &Path, source: ide_plugin::PluginDataSource) -> Result<(), HostError> {
|
||||
let (host, db) = self.database_host(root)?;
|
||||
@@ -1561,8 +1697,13 @@ impl HostApi for PluginApi {
|
||||
}
|
||||
}
|
||||
|
||||
fn register_run_target(&self, root: &Path, target: ide_plugin::PluginRunTarget) -> Result<(), HostError> {
|
||||
self.register_target(root, target)
|
||||
fn register_run_target(
|
||||
&self,
|
||||
root: &Path,
|
||||
target: ide_plugin::PluginRunTarget,
|
||||
generation: Option<u64>,
|
||||
) -> Result<(), HostError> {
|
||||
self.register_target(root, target, generation)
|
||||
}
|
||||
fn unregister_run_target(&self, root: &Path, id: &str) {
|
||||
self.unregister_target(root, id);
|
||||
@@ -1573,7 +1714,7 @@ impl HostApi for PluginApi {
|
||||
client: &str,
|
||||
config: &str,
|
||||
args: Vec<String>,
|
||||
debug: bool,
|
||||
options: ide_plugin::PluginRunStartOptions,
|
||||
cancel: &CancellationToken,
|
||||
timeout: Duration,
|
||||
) -> Result<String, HostError> {
|
||||
@@ -1584,15 +1725,40 @@ impl HostApi for PluginApi {
|
||||
let mut run =
|
||||
self.shared.workspace().ok_or(HostError::Cancelled)?.run_configuration(client, self.id(), config)?;
|
||||
let binary = self.approved_program_in_project(&run.command, self.shared.project_of(client).as_deref())?;
|
||||
let user_override = !run.detected;
|
||||
let debug = options.debug;
|
||||
if debug && run.debug_adapter.is_none() {
|
||||
return Err(HostError::Invalid("this configuration has no debugger".into()));
|
||||
}
|
||||
let program = run.command.clone();
|
||||
if debug && run.extras.target.as_ref().is_some_and(|t| !t.is_empty()) {
|
||||
let has_target = run.extras.target.as_ref().is_some_and(|t| !t.is_empty());
|
||||
if debug && has_target {
|
||||
return Err(HostError::Invalid("debugging this target is not supported".into()));
|
||||
}
|
||||
if debug && options.output_mode == Some(ide_plugin::PluginOutputMode::Pty) {
|
||||
return Err(HostError::Invalid("terminal emulation cannot be used when debugging".into()));
|
||||
}
|
||||
if debug {
|
||||
run.extras.emulate_terminal = false;
|
||||
run.command = binary.to_string_lossy().into_owned();
|
||||
} else {
|
||||
// Precedence: user-saved override > per-invocation override > plugin default.
|
||||
if !user_override && let Some(mode) = options.output_mode {
|
||||
run.extras.emulate_terminal = mode == ide_plugin::PluginOutputMode::Pty;
|
||||
}
|
||||
if run.extras.emulate_terminal {
|
||||
if run.is_test {
|
||||
return Err(HostError::Invalid("terminal emulation cannot be used for test configurations".into()));
|
||||
}
|
||||
if run.extras.stdin_file.is_some() {
|
||||
return Err(HostError::Invalid(
|
||||
"input cannot be redirected from a file when emulating a terminal".into(),
|
||||
));
|
||||
}
|
||||
if has_target {
|
||||
return Err(HostError::Invalid("terminal emulation on this target is not supported".into()));
|
||||
}
|
||||
}
|
||||
}
|
||||
run.args.extend(args);
|
||||
let id = self.new_operation(
|
||||
@@ -1613,6 +1779,7 @@ impl HostApi for PluginApi {
|
||||
key: String,
|
||||
title: String,
|
||||
cmd: ProcessCommand,
|
||||
cwd: Option<String>,
|
||||
cancel: &CancellationToken,
|
||||
timeout: Duration,
|
||||
) -> Result<String, HostError> {
|
||||
@@ -1623,6 +1790,11 @@ impl HostApi for PluginApi {
|
||||
if !self.shared.workspace().is_some_and(|w| w.trusted(&root)) {
|
||||
return Err(HostError::Denied("project is not trusted".into()));
|
||||
}
|
||||
// Trust and the program pin stay the project's; the directory only moves the shell.
|
||||
let dir = match &cwd {
|
||||
Some(cwd) => project_subdirectory(&root, cwd)?,
|
||||
None => root.clone(),
|
||||
};
|
||||
let binary = self.approved_program_in_project(&cmd.program, Some(&root))?;
|
||||
let mut command = StdCommand::new(&binary);
|
||||
append_process_env(&mut command, &cmd.env)?;
|
||||
@@ -1654,7 +1826,7 @@ impl HostApi for PluginApi {
|
||||
program: binary.into(),
|
||||
args: cmd.args,
|
||||
env: cmd.env.into_iter().collect(),
|
||||
cwd: root.into(),
|
||||
cwd: dir.into(),
|
||||
};
|
||||
if let Err(error) = self.window_request(client, request, cancel, timeout) {
|
||||
self.shared.operations.lock().remove(&id);
|
||||
@@ -1830,6 +2002,12 @@ impl HostApi for PluginApi {
|
||||
fn file_icon_decorations(&self, set: &str, items: Vec<(PathBuf, String)>) -> Result<(), HostError> {
|
||||
self.set_file_icon_decorations(set, items)
|
||||
}
|
||||
fn fork_agent_session(&self, client: &str, agent: &str, session_id: &str, cwd: &Path) -> Result<String, HostError> {
|
||||
self.shared
|
||||
.workspace()
|
||||
.ok_or_else(|| HostError::NotFound("window project".into()))?
|
||||
.fork_agent_session(client, agent, session_id, cwd)
|
||||
}
|
||||
fn console_rules(&self, rules: Vec<ide_plugin::ConsoleRule>) -> Result<(), HostError> {
|
||||
let rules = super::console_rules::normalize(rules).map_err(HostError::Invalid)?;
|
||||
let mut all = self.shared.console_rules.lock();
|
||||
@@ -2196,7 +2374,10 @@ impl HostApi for PluginApi {
|
||||
|
||||
fn reveal_view(&self, client: Option<&str>, view: &str) -> Result<(), HostError> {
|
||||
let client = from_window(client, "reveal a view")?;
|
||||
let declared = self.shared.ui.items(super::ui_points::VIEWS, Some(self.id())).iter().any(|i| i.key == view);
|
||||
// A tool window comes to the front; a dialog (API 1.18) opens.
|
||||
let declared = [super::ui_points::VIEWS, super::ui_points::DIALOGS]
|
||||
.into_iter()
|
||||
.any(|point| self.shared.ui.items(point, Some(self.id())).iter().any(|i| i.key == view));
|
||||
if !declared {
|
||||
return Err(HostError::NotFound(format!("the plugin declares no view {view:?}")));
|
||||
}
|
||||
@@ -2690,6 +2871,16 @@ impl HostApi for PluginApi {
|
||||
return Ok(None);
|
||||
}
|
||||
let host = host.trim_end_matches('.').to_ascii_lowercase();
|
||||
// A host the plugin derives from a setting is approved in Settings,
|
||||
// not asked about here: pending or revoked, it stays denied without a
|
||||
// dialog (#3809).
|
||||
if self.pkg.manifest.capabilities.all().any(|cap| {
|
||||
matches!(cap, Capability::NetSetting { http: false, key: _ })
|
||||
&& self.setting_value(&setting_key(cap)).and_then(|v| setting_host(&v).ok()).flatten().as_deref()
|
||||
== Some(host.as_str())
|
||||
}) {
|
||||
return Ok(None);
|
||||
}
|
||||
{
|
||||
let ledger = self.shared.ledger.lock();
|
||||
if let Some(grant) = ledger.get(subject)
|
||||
@@ -2932,14 +3123,36 @@ impl HostApi for PluginApi {
|
||||
}
|
||||
}
|
||||
|
||||
fn subscribe_paths(&self, kind: &str, globs: Vec<String>) -> Result<(), HostError> {
|
||||
let filter = super::event_paths::PathFilter::new(kind, globs)?;
|
||||
fn subscribe_paths_with_options(
|
||||
&self,
|
||||
kind: &str,
|
||||
globs: Vec<String>,
|
||||
debounce_ms: Option<u32>,
|
||||
) -> Result<(), HostError> {
|
||||
let debounce = match debounce_ms {
|
||||
Some(ms) if ms > 60_000 => return Err(HostError::Invalid("debounce must not exceed 60000 ms".into())),
|
||||
Some(ms) => Some(Duration::from_millis(ms as u64)),
|
||||
None => None,
|
||||
};
|
||||
let filter = super::event_paths::PathFilter::with_debounce(kind, globs, debounce)?;
|
||||
if self.shared.subscriptions.lock().set_paths(self.id(), kind, filter) {
|
||||
self.shared.sink.emit(None, PluginEvent::SubscriptionsChanged);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn subscribe_paths(&self, kind: &str, globs: Vec<String>) -> Result<(), HostError> {
|
||||
self.subscribe_paths_with_options(kind, globs, None)
|
||||
}
|
||||
|
||||
fn project_generation(&self, root: &Path) -> Result<u64, HostError> {
|
||||
self.shared.project_generation(root)
|
||||
}
|
||||
|
||||
fn watch_paths(&self, client: &str, project: &Path, paths: Vec<PathBuf>) -> Result<(), HostError> {
|
||||
self.shared.external_watches.set(self.id(), client, project, paths)
|
||||
}
|
||||
|
||||
fn unsubscribe(&self, kind: &str) {
|
||||
if self.shared.subscriptions.lock().unsubscribe(self.id(), kind) {
|
||||
self.shared.sink.emit(None, PluginEvent::SubscriptionsChanged);
|
||||
@@ -3489,6 +3702,14 @@ impl PluginWorkspace for HostWorkspace {
|
||||
Ok(config)
|
||||
}
|
||||
|
||||
fn fork_agent_session(&self, client: &str, agent: &str, session_id: &str, cwd: &Path) -> Result<String, HostError> {
|
||||
let host = self.0.upgrade().ok_or(HostError::Cancelled)?;
|
||||
let project = host.project(client).map_err(failed)?;
|
||||
project.require_trust().map_err(failed)?;
|
||||
// Scans the recorded transcripts on disk; plugin calls already run off the UI thread.
|
||||
Ok(project.agents.fork_session(agent, session_id, cwd).map_err(failed)?.id)
|
||||
}
|
||||
|
||||
fn buffer_text_in(&self, client: Option<&str>, path: &Path) -> Option<String> {
|
||||
client
|
||||
.and_then(|w| self.0.upgrade()?.project(w).ok()?.documents.text_of(path))
|
||||
@@ -3850,6 +4071,29 @@ impl PluginWorkspace for HostWorkspace {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn terminal_directories_stay_inside_the_project() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap().join("project");
|
||||
std::fs::create_dir_all(root.join("sub/deeper")).unwrap();
|
||||
std::fs::write(root.join("file.txt"), "").unwrap();
|
||||
let outside = tmp.path().join("outside");
|
||||
std::fs::create_dir_all(&outside).unwrap();
|
||||
assert_eq!(project_subdirectory(&root, "").unwrap(), root);
|
||||
assert_eq!(project_subdirectory(&root, "sub/deeper").unwrap(), root.join("sub/deeper"));
|
||||
assert_eq!(project_subdirectory(&root, "sub/../sub").unwrap(), root.join("sub"));
|
||||
for bad in ["/tmp", "../outside", "sub/../../outside", "missing", "file.txt", "a\0b"] {
|
||||
assert!(matches!(project_subdirectory(&root, bad), Err(HostError::Invalid(_))), "{bad:?}");
|
||||
}
|
||||
#[cfg(unix)]
|
||||
{
|
||||
std::os::unix::fs::symlink(&outside, root.join("escape")).unwrap();
|
||||
assert!(project_subdirectory(&root, "escape").is_err(), "a link out of the project");
|
||||
std::os::unix::fs::symlink(root.join("sub"), root.join("inside")).unwrap();
|
||||
assert_eq!(project_subdirectory(&root, "inside").unwrap(), root.join("sub"));
|
||||
}
|
||||
}
|
||||
|
||||
fn api(dir: &Path, pins: Arc<RwLock<HashMap<(String, String), ProgramPin>>>) -> PluginApi {
|
||||
let manifest = ide_extension::Manifest::parse(
|
||||
"id = \"acme.lint\"\nname = \"Lint\"\nversion = \"1.0.0\"\nengines.openidea = \"^1.0\"\n",
|
||||
@@ -4826,7 +5070,18 @@ impl PluginApi {
|
||||
if let Some(icon) = file.as_ref().and_then(|f| f.icon.as_ref()) {
|
||||
ide_extension::validate_item_id(icon, "file icon id").map_err(HostError::Invalid)?;
|
||||
}
|
||||
items.retain(|d| decoration_style(&d.style));
|
||||
for colors in items.iter_mut().filter_map(|d| d.colors.as_mut()) {
|
||||
for color in [&mut colors.foreground, &mut colors.background].into_iter().flatten() {
|
||||
*color = decoration_color(color).ok_or_else(|| {
|
||||
HostError::Invalid(format!("decoration color '{color}' is not #rrggbb or #rrggbbaa"))
|
||||
})?;
|
||||
}
|
||||
}
|
||||
items
|
||||
.iter_mut()
|
||||
.for_each(|d| d.colors = d.colors.take().filter(|c| c.foreground.is_some() || c.background.is_some()));
|
||||
// An item with its own colors (API 1.17) may leave the style empty.
|
||||
items.retain(|d| decoration_style(&d.style) || (d.style.is_empty() && d.colors.is_some()));
|
||||
if items.iter().any(|d| d.range.start > d.range.end) {
|
||||
return Err(HostError::Invalid("reversed decoration range".into()));
|
||||
}
|
||||
@@ -4924,6 +5179,13 @@ impl PluginApi {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
/// A `set-styled` color as the editor renders it: `#rrggbb` or `#rrggbbaa`, lower case.
|
||||
fn decoration_color(color: &str) -> Option<String> {
|
||||
let hex = color.strip_prefix('#')?;
|
||||
((hex.len() == 6 || hex.len() == 8) && hex.bytes().all(|b| b.is_ascii_hexdigit()))
|
||||
.then(|| format!("#{}", hex.to_ascii_lowercase()))
|
||||
}
|
||||
|
||||
fn decoration_style(style: &str) -> bool {
|
||||
matches!(
|
||||
style,
|
||||
@@ -5058,9 +5320,38 @@ mod workbench_tests {
|
||||
hover: None,
|
||||
after: Some("after".into()),
|
||||
markdown_hover: None,
|
||||
colors: None,
|
||||
};
|
||||
api.decorations(Some(&path), "set", vec![item("highlight"), item("unknown")]).unwrap();
|
||||
assert_eq!(api.shared.decoration_sets()["test"][0].items.len(), 1);
|
||||
// Styled items (API 1.17): colors are validated and normalized; an empty style needs colors.
|
||||
let colored = |style: &str, foreground: Option<&str>, background: Option<&str>| ide_plugin::Decoration {
|
||||
colors: Some(ide_plugin::DecorationColors {
|
||||
foreground: foreground.map(Into::into),
|
||||
background: background.map(Into::into),
|
||||
}),
|
||||
..item(style)
|
||||
};
|
||||
api.decorations(
|
||||
Some(&path),
|
||||
"styled",
|
||||
vec![
|
||||
colored("", Some("#1A1A1A"), Some("#FFEB3BFF")),
|
||||
colored("highlight", None, Some("#00e5ff")),
|
||||
colored("", None, None),
|
||||
item(""),
|
||||
],
|
||||
)
|
||||
.unwrap();
|
||||
let styled = api.shared.decoration_sets()["test"].iter().find(|s| s.set_id == "styled").unwrap().items.clone();
|
||||
assert_eq!(styled.len(), 2);
|
||||
let first = styled[0].colors.as_ref().unwrap();
|
||||
assert_eq!((first.foreground.as_deref(), first.background.as_deref()), (Some("#1a1a1a"), Some("#ffeb3bff")));
|
||||
for bad in ["red", "#fff", "#12345g", "rgb(0,0,0)", "#1234567", "#ffffff; x: y"] {
|
||||
let err = api.decorations(Some(&path), "styled", vec![colored("", Some(bad), None)]).unwrap_err();
|
||||
assert!(matches!(err, HostError::Invalid(ref m) if m.contains("#rrggbb")), "{bad}: {err}");
|
||||
}
|
||||
api.decorations(None, "styled", vec![]).unwrap();
|
||||
// Decorations follow the file: a path outside the open project is accepted too.
|
||||
api.decorations(Some(&root.join("../outside.txt")), "set", vec![]).unwrap();
|
||||
assert_eq!(api.shared.decoration_sets()["test"].len(), 2);
|
||||
|
||||
@@ -51,6 +51,53 @@ pub async fn plugin_run_command(
|
||||
result
|
||||
}
|
||||
|
||||
/// Run Anything entries of the plugin declaring `prefix` for the field's `text` (API 1.18).
|
||||
#[command(trust = trusted)]
|
||||
pub async fn plugin_run_anything_suggest(
|
||||
host: &Host,
|
||||
plugins: &Arc<PluginHost>,
|
||||
window: &str,
|
||||
plugin_id: String,
|
||||
prefix: String,
|
||||
text: String,
|
||||
) -> IdeResult<Vec<ide_plugin::RunAnythingItem>> {
|
||||
let (plugins, window_id) = (plugins.clone(), window.to_owned());
|
||||
let root = host.project(window).ok().map(|p| p.root.clone());
|
||||
host.blocking(move || plugins.run_anything_suggest(&plugin_id, &window_id, root, &prefix, &text)).await
|
||||
}
|
||||
|
||||
/// Runs a Run Anything line starting with the plugin's `prefix` (API 1.18): whether
|
||||
/// the plugin claimed it.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn plugin_run_anything_run(
|
||||
host: &Host,
|
||||
plugins: &Arc<PluginHost>,
|
||||
window: &str,
|
||||
plugin_id: String,
|
||||
prefix: String,
|
||||
line: String,
|
||||
) -> IdeResult<bool> {
|
||||
let (plugins, window_id) = (plugins.clone(), window.to_owned());
|
||||
let root = host.project(window).ok().map(|p| p.root.clone());
|
||||
host.blocking(move || plugins.run_anything_run(&plugin_id, &window_id, root, &prefix, &line)).await
|
||||
}
|
||||
|
||||
/// Completions for a field of a plugin's own run configuration (API 1.18).
|
||||
#[command(trust = trusted)]
|
||||
pub async fn plugin_run_configuration_complete(
|
||||
host: &Host,
|
||||
plugins: &Arc<PluginHost>,
|
||||
window: &str,
|
||||
config_id: String,
|
||||
field: String,
|
||||
text: String,
|
||||
caret: u32,
|
||||
) -> IdeResult<Vec<ide_plugin::RunConfigCompletion>> {
|
||||
let (plugins, window_id) = (plugins.clone(), window.to_owned());
|
||||
let root = host.project(window)?.root.clone();
|
||||
host.blocking(move || plugins.run_configuration_complete(&window_id, &root, &config_id, &field, &text, caret)).await
|
||||
}
|
||||
|
||||
/// The UI language (BCP 47) that plugin code reads with `ui.locale()`.
|
||||
#[command(trust = always)]
|
||||
pub async fn plugin_set_ui_locale(plugins: &Arc<PluginHost>, tag: String) -> IdeResult<()> {
|
||||
@@ -316,7 +363,10 @@ ide_command::domain!(
|
||||
plugin_post_events,
|
||||
plugin_prepare_debug_run,
|
||||
plugin_program,
|
||||
plugin_run_anything_run,
|
||||
plugin_run_anything_suggest,
|
||||
plugin_run_command,
|
||||
plugin_run_configuration_complete,
|
||||
plugin_select_tests,
|
||||
plugin_set_active_file,
|
||||
plugin_set_ui_locale,
|
||||
|
||||
@@ -17,11 +17,21 @@ pub(super) struct Subscriptions {
|
||||
#[derive(Clone)]
|
||||
pub(super) struct PathFilter {
|
||||
pub globs: Vec<String>,
|
||||
pub debounce: Option<std::time::Duration>,
|
||||
matchers: Vec<GlobMatcher>,
|
||||
}
|
||||
|
||||
impl PathFilter {
|
||||
#[allow(dead_code)]
|
||||
pub fn new(kind: &str, globs: Vec<String>) -> Result<Self, HostError> {
|
||||
Self::with_debounce(kind, globs, None)
|
||||
}
|
||||
|
||||
pub fn with_debounce(
|
||||
kind: &str,
|
||||
globs: Vec<String>,
|
||||
debounce: Option<std::time::Duration>,
|
||||
) -> Result<Self, HostError> {
|
||||
if !matches!(kind, "file-opened" | "file-saved" | "files-changed" | "document-changed") {
|
||||
return Err(HostError::Invalid(
|
||||
"subscribe-paths supports file-opened, file-saved, files-changed and document-changed".into(),
|
||||
@@ -53,7 +63,7 @@ impl PathFilter {
|
||||
.compile_matcher(),
|
||||
);
|
||||
}
|
||||
Ok(Self { globs, matchers })
|
||||
Ok(Self { globs, debounce, matchers })
|
||||
}
|
||||
|
||||
pub fn matches(&self, root: &Path, path: &Path) -> bool {
|
||||
@@ -78,7 +88,7 @@ impl Subscriptions {
|
||||
changed = self.kinds.entry(plugin.to_owned()).or_default().insert(kind);
|
||||
}
|
||||
let previous = self.paths.entry(plugin.to_owned()).or_default().insert(kind.to_owned(), filter.clone());
|
||||
previous.is_none_or(|old| old.globs != filter.globs) | changed
|
||||
previous.is_none_or(|old| old.globs != filter.globs || old.debounce != filter.debounce) | changed
|
||||
}
|
||||
pub fn unsubscribe(&mut self, plugin: &str, kind: &str) -> bool {
|
||||
let removed = self.paths.get_mut(plugin).is_some_and(|filters| filters.remove(kind).is_some());
|
||||
@@ -120,6 +130,8 @@ impl PluginHost {
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
let batch = ide_plugin::FilesChanged {
|
||||
project: batch.project.clone(),
|
||||
generation: batch.generation,
|
||||
created: paths(&batch.created),
|
||||
modified: paths(&batch.modified),
|
||||
removed: paths(&batch.removed),
|
||||
|
||||
@@ -244,12 +244,16 @@ impl PluginHost {
|
||||
if self.shared.client_closed(client) {
|
||||
return;
|
||||
}
|
||||
self.queues
|
||||
.lock()
|
||||
.entry((plugin.into(), Some(client.into())))
|
||||
.or_insert_with(|| EventQueue { since: Instant::now(), events: Vec::new(), files_source: None })
|
||||
.events
|
||||
.push(event);
|
||||
let now = Instant::now();
|
||||
let mut queues = self.queues.lock();
|
||||
let queue = queues.entry((plugin.into(), Some(client.into()))).or_insert_with(|| EventQueue {
|
||||
since: now,
|
||||
last_event: now,
|
||||
events: Vec::new(),
|
||||
files_source: None,
|
||||
});
|
||||
queue.last_event = now;
|
||||
queue.events.push(event);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -434,6 +438,9 @@ fn validate_configurations(
|
||||
if let Some(cwd) = &c.cwd {
|
||||
ide_plugin::resolve_new_in_root(root, cwd).map_err(HostError::Invalid)?;
|
||||
}
|
||||
if c.test && c.output_mode == ide_plugin::PluginOutputMode::Pty {
|
||||
return Err(HostError::Invalid("test configurations cannot emulate a terminal".into()));
|
||||
}
|
||||
validate_env(&c.env)?;
|
||||
validate_debugger(c.debugger.as_ref())?;
|
||||
}
|
||||
@@ -607,6 +614,7 @@ impl PluginHost {
|
||||
.to_string_lossy()
|
||||
.into_owned();
|
||||
config.debug_adapter = owned.debug_adapter;
|
||||
config.extras.emulate_terminal = false;
|
||||
Ok(config)
|
||||
}
|
||||
}
|
||||
@@ -801,4 +809,16 @@ mod tests {
|
||||
assert!(ok(AttachChild { kind: "dotnet".into(), command_contains: Some("Worker.dll".into()) }));
|
||||
assert!(!ok(AttachChild { kind: "dotnet".into(), command_contains: Some(String::new()) }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn configurations_reject_pty_on_test_configurations() {
|
||||
let root = std::env::temp_dir();
|
||||
let mut c = launch(vec![], None);
|
||||
c.output_mode = ide_plugin::PluginOutputMode::Pty;
|
||||
assert!(validate_configurations(&root, std::slice::from_ref(&c)).is_ok());
|
||||
c.test = true;
|
||||
assert!(validate_configurations(&root, std::slice::from_ref(&c)).is_err());
|
||||
c.output_mode = ide_plugin::PluginOutputMode::Pipes;
|
||||
assert!(validate_configurations(&root, &[c]).is_ok());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
//! Paths outside a project that a plugin watches (`events.watch-paths`, API 1.18).
|
||||
//!
|
||||
//! A watch set belongs to (plugin, project) and the window that asked for it. Every
|
||||
//! directory is watched flat (its own entries): a watched file through its parent, a
|
||||
//! watched directory through itself plus its parent (so its own removal is seen).
|
||||
//! Watcher threads only queue changes here; [`super::PluginHost::flush_events_at`]
|
||||
//! delivers them while the set, its window and its project are still current.
|
||||
use ide_core::{NullSink, ipc_path::to_ipc};
|
||||
use ide_plugin::{FilesChanged, HostError};
|
||||
use ide_vfs::{FsBatch, WatchMode, Watcher};
|
||||
use parking_lot::Mutex;
|
||||
use std::collections::{BTreeMap, BTreeSet, HashMap};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct ExternalWatches {
|
||||
sets: Mutex<HashMap<(String, PathBuf), WatchSet>>,
|
||||
pending: Arc<Mutex<Vec<Change>>>,
|
||||
next: AtomicU64,
|
||||
}
|
||||
|
||||
struct WatchSet {
|
||||
id: u64,
|
||||
client: String,
|
||||
_watchers: Vec<Watcher>,
|
||||
}
|
||||
|
||||
/// Changes seen by one watch set, waiting for delivery.
|
||||
pub(super) struct Change {
|
||||
pub plugin: String,
|
||||
pub client: String,
|
||||
pub project: PathBuf,
|
||||
set: u64,
|
||||
pub batch: FilesChanged,
|
||||
}
|
||||
|
||||
/// What one flat directory watch reports: entries named exactly, or all of them.
|
||||
#[derive(Default)]
|
||||
struct Wanted {
|
||||
exact: BTreeSet<PathBuf>,
|
||||
entries: bool,
|
||||
}
|
||||
|
||||
impl ExternalWatches {
|
||||
/// Replaces what `plugin` watches for `project` from window `client`.
|
||||
pub fn set(&self, plugin: &str, client: &str, project: &Path, paths: Vec<PathBuf>) -> Result<(), HostError> {
|
||||
let key = (plugin.to_owned(), project.to_path_buf());
|
||||
if paths.is_empty() {
|
||||
self.sets.lock().remove(&key);
|
||||
return Ok(());
|
||||
}
|
||||
let id = self.next.fetch_add(1, Ordering::Relaxed) + 1;
|
||||
let mut dirs: BTreeMap<PathBuf, Wanted> = BTreeMap::new();
|
||||
for path in &paths {
|
||||
if let Some(parent) = path.parent() {
|
||||
dirs.entry(parent.to_path_buf()).or_default().exact.insert(path.clone());
|
||||
}
|
||||
if path.is_dir() {
|
||||
dirs.entry(path.clone()).or_default().entries = true;
|
||||
}
|
||||
}
|
||||
let mut watchers = Vec::with_capacity(dirs.len());
|
||||
for (dir, wanted) in dirs {
|
||||
let pending = Arc::downgrade(&self.pending);
|
||||
let (plugin, client, project) = (plugin.to_owned(), client.to_owned(), project.to_path_buf());
|
||||
let watched = dir.clone();
|
||||
let on_change = Box::new(move |batch: &FsBatch| {
|
||||
let Some(pending) = pending.upgrade() else { return };
|
||||
let Some(batch) = select(&watched, &wanted, batch) else { return };
|
||||
// Drained on every event flush; bounded by the flat directories' entries.
|
||||
pending.lock().push(Change {
|
||||
plugin: plugin.clone(),
|
||||
client: client.clone(),
|
||||
project: project.clone(),
|
||||
set: id,
|
||||
batch,
|
||||
});
|
||||
});
|
||||
let watcher = Watcher::start_with(&dir, Vec::new(), Arc::new(NullSink), on_change, WatchMode::Flat)
|
||||
.map_err(|e| HostError::Failed(format!("cannot watch {}: {}", dir.display(), e.message)))?;
|
||||
watchers.push(watcher);
|
||||
}
|
||||
let set = WatchSet { id, client: client.to_owned(), _watchers: watchers };
|
||||
self.sets.lock().insert(key, set);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Changes of sets still in place, oldest first; others are dropped.
|
||||
pub fn take(&self) -> Vec<Change> {
|
||||
let changes = std::mem::take(&mut *self.pending.lock());
|
||||
if changes.is_empty() {
|
||||
return changes;
|
||||
}
|
||||
let sets = self.sets.lock();
|
||||
changes
|
||||
.into_iter()
|
||||
.filter(|c| {
|
||||
sets.get(&(c.plugin.clone(), c.project.clone())).is_some_and(|s| s.id == c.set && s.client == c.client)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn remove_plugin(&self, plugin: &str) {
|
||||
self.sets.lock().retain(|(p, _), _| p != plugin);
|
||||
}
|
||||
|
||||
pub fn remove_project(&self, root: &Path) {
|
||||
self.sets.lock().retain(|(_, project), _| project != root);
|
||||
}
|
||||
|
||||
pub fn remove_client(&self, client: &str) {
|
||||
self.sets.lock().retain(|_, set| set.client != client);
|
||||
}
|
||||
}
|
||||
|
||||
/// The part of `batch` (from the flat watch on `dir`) the set asked for. Ignored
|
||||
/// files are reported too: as modified while they exist, removed once they don't.
|
||||
fn select(dir: &Path, wanted: &Wanted, batch: &FsBatch) -> Option<FilesChanged> {
|
||||
let keep = |path: &&PathBuf| wanted.exact.contains(*path) || (wanted.entries && path.parent() == Some(dir));
|
||||
let ipc = |paths: Vec<&PathBuf>| paths.into_iter().map(|p| to_ipc(p)).collect::<Vec<_>>();
|
||||
let mut modified: Vec<&PathBuf> = batch.modified.iter().filter(keep).collect();
|
||||
let mut removed: Vec<&PathBuf> = batch.removed.iter().filter(keep).collect();
|
||||
for path in batch.ignored.iter().filter(keep) {
|
||||
if path.symlink_metadata().is_ok() { modified.push(path) } else { removed.push(path) }
|
||||
}
|
||||
let changes = FilesChanged {
|
||||
project: None,
|
||||
generation: None,
|
||||
created: ipc(batch.created.iter().filter(keep).collect()),
|
||||
modified: ipc(modified),
|
||||
removed: ipc(removed),
|
||||
};
|
||||
(!changes.created.is_empty() || !changes.modified.is_empty() || !changes.removed.is_empty()).then_some(changes)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn batch(created: &[&Path], modified: &[&Path], removed: &[&Path], ignored: &[&Path]) -> FsBatch {
|
||||
let v = |p: &[&Path]| p.iter().map(|p| p.to_path_buf()).collect();
|
||||
FsBatch {
|
||||
created: v(created),
|
||||
modified: v(modified),
|
||||
removed: v(removed),
|
||||
ignored: v(ignored),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_flat_watch_reports_only_what_the_set_names() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let dir = tmp.path();
|
||||
let (file, other, kept) = (dir.join("Taskfile.yml"), dir.join("other.yml"), dir.join("kept.yml"));
|
||||
std::fs::write(&kept, "").unwrap();
|
||||
let exact = Wanted { exact: [file.clone()].into(), entries: false };
|
||||
let got = select(dir, &exact, &batch(&[&file], &[&other], &[], &[&kept])).unwrap();
|
||||
assert_eq!(got.created, vec![to_ipc(&file)]);
|
||||
assert!(got.modified.is_empty() && got.removed.is_empty());
|
||||
assert!(select(dir, &exact, &batch(&[], &[&other], &[], &[])).is_none());
|
||||
|
||||
let nested = dir.join("sub").join("deep.yml");
|
||||
let entries = Wanted { exact: BTreeSet::new(), entries: true };
|
||||
let gone = dir.join("gone.yml");
|
||||
let got = select(dir, &entries, &batch(&[&nested], &[&other], &[], &[&kept, &gone])).unwrap();
|
||||
assert!(got.created.is_empty(), "entries below the directory are not watched");
|
||||
assert_eq!(got.modified, vec![to_ipc(&other), to_ipc(&kept)]);
|
||||
assert_eq!(got.removed, vec![to_ipc(&gone)]);
|
||||
}
|
||||
}
|
||||
@@ -28,11 +28,21 @@ pub(super) fn retain_live(events: &mut Vec<WorkbenchEvent>, source: Option<&Sour
|
||||
}
|
||||
}
|
||||
|
||||
/// Queues `incoming`, folding a filesystem batch into the queued one it continues:
|
||||
/// the project batch, or the watched-paths batch of the same project.
|
||||
pub(super) fn append(events: &mut Vec<WorkbenchEvent>, incoming: Vec<WorkbenchEvent>) {
|
||||
for event in incoming {
|
||||
if let WorkbenchEvent::FilesChanged(batch) = &event
|
||||
&& let Some(WorkbenchEvent::FilesChanged(previous)) =
|
||||
events.iter_mut().find(|e| matches!(e, WorkbenchEvent::FilesChanged(_)))
|
||||
let previous = events.iter_mut().find_map(|queued| match (queued, &event) {
|
||||
(WorkbenchEvent::FilesChanged(previous), WorkbenchEvent::FilesChanged(_)) => Some(previous),
|
||||
(WorkbenchEvent::WatchedFilesChanged(previous), WorkbenchEvent::WatchedFilesChanged(batch))
|
||||
if previous.project == batch.project =>
|
||||
{
|
||||
Some(previous)
|
||||
}
|
||||
_ => None,
|
||||
});
|
||||
if let (WorkbenchEvent::FilesChanged(batch) | WorkbenchEvent::WatchedFilesChanged(batch), Some(previous)) =
|
||||
(&event, previous)
|
||||
{
|
||||
use std::collections::BTreeMap;
|
||||
#[derive(Clone, Copy)]
|
||||
@@ -61,7 +71,9 @@ pub(super) fn append(events: &mut Vec<WorkbenchEvent>, incoming: Vec<WorkbenchEv
|
||||
paths.insert(path.clone(), kind);
|
||||
}
|
||||
}
|
||||
*previous = FilesChanged::default();
|
||||
let project = batch.project.clone().or_else(|| previous.project.clone());
|
||||
let generation = batch.generation.or(previous.generation);
|
||||
*previous = FilesChanged { project, generation, ..Default::default() };
|
||||
for (path, kind) in paths {
|
||||
match kind {
|
||||
Created => previous.created.push(path),
|
||||
@@ -88,14 +100,15 @@ impl PluginHost {
|
||||
}
|
||||
let paths =
|
||||
|paths: &[PathBuf]| paths.iter().filter(|p| p.starts_with(root)).map(|p| to_ipc(p)).collect::<Vec<_>>();
|
||||
let batch = FilesChanged {
|
||||
created: paths(&batch.created),
|
||||
modified: paths(&batch.modified),
|
||||
removed: paths(&batch.removed),
|
||||
};
|
||||
if batch.created.is_empty() && batch.modified.is_empty() && batch.removed.is_empty() {
|
||||
let created = paths(&batch.created);
|
||||
let modified = paths(&batch.modified);
|
||||
let removed = paths(&batch.removed);
|
||||
if created.is_empty() && modified.is_empty() && removed.is_empty() {
|
||||
return;
|
||||
}
|
||||
let generation = self.shared.bump_project_generation(root);
|
||||
let batch =
|
||||
FilesChanged { project: Some(to_ipc(root)), generation: Some(generation), created, modified, removed };
|
||||
self.post_events_from(
|
||||
Some(client),
|
||||
vec![WorkbenchEvent::FilesChanged(batch)],
|
||||
@@ -189,7 +202,15 @@ mod tests {
|
||||
let queues = host.queues.lock();
|
||||
let queue = queues.values().next().expect("new session queue");
|
||||
assert!(queue.files_source.as_ref().unwrap().same(&Source { active: Arc::downgrade(&new) }));
|
||||
assert_eq!(queue.events, [delta(0, &to_ipc(&root.join("new.rs")))]);
|
||||
assert_eq!(
|
||||
queue.events,
|
||||
[WorkbenchEvent::FilesChanged(FilesChanged {
|
||||
project: Some(to_ipc(&root)),
|
||||
generation: Some(2),
|
||||
created: vec![to_ipc(&root.join("new.rs"))],
|
||||
..Default::default()
|
||||
})]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -291,6 +312,7 @@ mod tests {
|
||||
created: vec![to_ipc(&root.join("config/a.yaml")), to_ipc(&root.join("src/a.rs"))],
|
||||
modified: vec![to_ipc(&root.join("config/b.yaml"))],
|
||||
removed: vec![to_ipc(&root.join("config/c.yaml"))],
|
||||
..Default::default()
|
||||
})],
|
||||
);
|
||||
host.flush_events();
|
||||
@@ -306,6 +328,7 @@ mod tests {
|
||||
created: vec![to_ipc(&root.join("config/a.yaml"))],
|
||||
modified: vec![to_ipc(&root.join("config/b.yaml"))],
|
||||
removed: vec![to_ipc(&root.join("config/c.yaml"))],
|
||||
..Default::default()
|
||||
}]
|
||||
);
|
||||
} else {
|
||||
@@ -437,6 +460,7 @@ mod tests {
|
||||
PendingFiles {
|
||||
queue: super::super::EventQueue {
|
||||
since: std::time::Instant::now(),
|
||||
last_event: std::time::Instant::now(),
|
||||
events: vec![delta(0, "/project/new")],
|
||||
files_source: None,
|
||||
},
|
||||
@@ -475,6 +499,7 @@ mod tests {
|
||||
created: vec![format!("/project/{i}")],
|
||||
modified: vec!["/project/shared".into()],
|
||||
removed: vec!["/project/gone".into()],
|
||||
..Default::default()
|
||||
})],
|
||||
);
|
||||
}
|
||||
@@ -616,7 +641,15 @@ mod tests {
|
||||
};
|
||||
let data = host.run_command("files-events", "events", None, inv).unwrap().unwrap();
|
||||
let received: Vec<FilesChanged> = serde_json::from_str(&data).unwrap();
|
||||
assert_eq!(received, [FilesChanged { created: vec![to_ipc(&root.join("new.rs"))], ..Default::default() }]);
|
||||
assert_eq!(
|
||||
received,
|
||||
[FilesChanged {
|
||||
project: Some(to_ipc(&root)),
|
||||
generation: Some(3),
|
||||
created: vec![to_ipc(&root.join("new.rs"))],
|
||||
..Default::default()
|
||||
}]
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn queued_filter_replacement_and_pause_do_not_activate() {
|
||||
@@ -656,4 +689,226 @@ mod tests {
|
||||
host.post_files_changed("main", &root, &active, &batch);
|
||||
assert!(host.queues.lock().is_empty(), "paused paths never queue work");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn files_changed_debounce_coalesces_bursts_of_edits_without_repeated_delivery() {
|
||||
use super::super::event_paths::PathFilter;
|
||||
use std::time::Duration;
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let host = files_changed_host(&root);
|
||||
host.shared.subscriptions.lock().set_paths(
|
||||
"files-events",
|
||||
"files-changed",
|
||||
PathFilter::with_debounce("files-changed", vec!["**/*".into()], Some(Duration::from_millis(80))).unwrap(),
|
||||
);
|
||||
|
||||
let active = Arc::new(AtomicBool::new(true));
|
||||
// Post 3 bursts of file changes quickly within debounce window
|
||||
host.post_files_changed(
|
||||
"main",
|
||||
&root,
|
||||
&active,
|
||||
&ide_vfs::FsBatch { created: vec![root.join("file1.rs")], ..Default::default() },
|
||||
);
|
||||
host.flush_events();
|
||||
assert_eq!(host.instances(), 0, "first change must be debounced, not delivered immediately");
|
||||
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
host.post_files_changed(
|
||||
"main",
|
||||
&root,
|
||||
&active,
|
||||
&ide_vfs::FsBatch { modified: vec![root.join("file2.rs")], ..Default::default() },
|
||||
);
|
||||
host.flush_events();
|
||||
assert_eq!(host.instances(), 0, "second change within debounce window resets debounce");
|
||||
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
host.post_files_changed(
|
||||
"main",
|
||||
&root,
|
||||
&active,
|
||||
&ide_vfs::FsBatch { removed: vec![root.join("file3.rs")], ..Default::default() },
|
||||
);
|
||||
host.flush_events();
|
||||
assert_eq!(host.instances(), 0, "third change still debouncing");
|
||||
|
||||
// Wait until debounce expires (> 80 ms since last event)
|
||||
std::thread::sleep(Duration::from_millis(100));
|
||||
host.flush_events();
|
||||
assert!(host.wait_events(Duration::from_secs(5)));
|
||||
|
||||
let inv = ide_plugin::Invocation {
|
||||
client: Some("main".into()),
|
||||
workspace_root: Some(root.clone()),
|
||||
..Default::default()
|
||||
};
|
||||
let data = host.run_command("files-events", "events", None, inv).unwrap().unwrap();
|
||||
let batches: Vec<FilesChanged> = serde_json::from_str(&data).unwrap();
|
||||
assert_eq!(batches.len(), 1, "rapid edit bursts must coalesce into exactly 1 batch");
|
||||
assert_eq!(batches[0].created, [to_ipc(&root.join("file1.rs"))]);
|
||||
assert_eq!(batches[0].modified, [to_ipc(&root.join("file2.rs"))]);
|
||||
assert_eq!(batches[0].removed, [to_ipc(&root.join("file3.rs"))]);
|
||||
assert_eq!(host.shared.project_generation(&root).unwrap(), 4);
|
||||
}
|
||||
|
||||
struct MultiWorkspace(std::sync::Mutex<Vec<PathBuf>>);
|
||||
impl super::super::PluginWorkspace for MultiWorkspace {
|
||||
fn projects(&self) -> Vec<PathBuf> {
|
||||
self.0.lock().unwrap().clone()
|
||||
}
|
||||
fn buffer_text(&self, _: &Path) -> Option<String> {
|
||||
None
|
||||
}
|
||||
fn document(&self, _: &Path) -> Option<(u64, String)> {
|
||||
None
|
||||
}
|
||||
fn apply_edits(
|
||||
&self,
|
||||
_: &Path,
|
||||
_: u64,
|
||||
_: &[ide_core::TextEdit],
|
||||
_: bool,
|
||||
) -> Result<u64, ide_plugin::HostError> {
|
||||
unreachable!()
|
||||
}
|
||||
fn trusted(&self, _: &Path) -> bool {
|
||||
true
|
||||
}
|
||||
fn project_of(&self, window: &str) -> Option<PathBuf> {
|
||||
let projects = self.0.lock().unwrap();
|
||||
match window {
|
||||
"main" => projects.first().cloned(),
|
||||
"other" => projects.get(1).cloned(),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
fn publish_diagnostics(
|
||||
&self,
|
||||
_: &str,
|
||||
_: &Path,
|
||||
_: Vec<ide_core::Diagnostic>,
|
||||
) -> Result<(), ide_plugin::HostError> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stale_run_target_registration_rejected_after_generation_bump() {
|
||||
use ide_plugin::HostError;
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let host = files_changed_host(&root);
|
||||
let dummy = root.join("dummy");
|
||||
std::fs::write(&dummy, b"dummy").unwrap();
|
||||
host.shared.pins.write().insert(
|
||||
("files-events".into(), "process:dummy".into()),
|
||||
ide_language::ProgramPin::approve(&dummy).unwrap(),
|
||||
);
|
||||
let plugin = host.get("files-events").unwrap();
|
||||
let api = super::super::api::PluginApi { pkg: plugin.pkg.clone(), shared: host.shared.clone() };
|
||||
|
||||
let target = ide_plugin::PluginRunTarget {
|
||||
id: "target-1".into(),
|
||||
name: "Target 1".into(),
|
||||
program: "dummy".into(),
|
||||
args: vec!["test".into()],
|
||||
workdir_args: vec![],
|
||||
container_root: None,
|
||||
commands: vec![],
|
||||
};
|
||||
|
||||
// Generation starts at 1
|
||||
let gen1 = host.shared.project_generation(&root).unwrap();
|
||||
assert_eq!(gen1, 1);
|
||||
|
||||
// Registering with matching generation succeeds
|
||||
assert!(api.register_target(&root, target.clone(), Some(gen1)).is_ok());
|
||||
|
||||
// Bump generation (simulating filesystem change or manual bump)
|
||||
let gen2 = host.shared.bump_project_generation(&root);
|
||||
assert_eq!(gen2, 2);
|
||||
|
||||
// Registering with old generation is rejected with Stale
|
||||
let err = api.register_target(&root, target.clone(), Some(gen1)).unwrap_err();
|
||||
assert!(matches!(err, HostError::Stale));
|
||||
|
||||
// Registering with new generation succeeds
|
||||
assert!(api.register_target(&root, target, Some(gen2)).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn project_isolation_and_project_closed_lifecycle() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root_a = dunce::canonicalize(tmp.path()).unwrap().join("project_a");
|
||||
let root_b = dunce::canonicalize(tmp.path()).unwrap().join("project_b");
|
||||
std::fs::create_dir_all(&root_a).unwrap();
|
||||
std::fs::create_dir_all(&root_b).unwrap();
|
||||
let host = files_changed_host(&root_a);
|
||||
let ws = Arc::new(MultiWorkspace(std::sync::Mutex::new(vec![root_a.clone(), root_b.clone()])));
|
||||
host.set_workspace(Some(ws.clone()));
|
||||
|
||||
let dummy = tmp.path().join("dummy");
|
||||
std::fs::write(&dummy, b"dummy").unwrap();
|
||||
host.shared.pins.write().insert(
|
||||
("files-events".into(), "process:dummy".into()),
|
||||
ide_language::ProgramPin::approve(&dummy).unwrap(),
|
||||
);
|
||||
let plugin = host.get("files-events").unwrap();
|
||||
let api = super::super::api::PluginApi { pkg: plugin.pkg.clone(), shared: host.shared.clone() };
|
||||
|
||||
let active_a = Arc::new(AtomicBool::new(true));
|
||||
let active_b = Arc::new(AtomicBool::new(true));
|
||||
|
||||
// Post changes to Project A and B
|
||||
host.post_files_changed(
|
||||
"main",
|
||||
&root_a,
|
||||
&active_a,
|
||||
&ide_vfs::FsBatch { created: vec![root_a.join("a.rs")], ..Default::default() },
|
||||
);
|
||||
host.post_files_changed(
|
||||
"other",
|
||||
&root_b,
|
||||
&active_b,
|
||||
&ide_vfs::FsBatch { created: vec![root_b.join("b.rs")], ..Default::default() },
|
||||
);
|
||||
|
||||
assert_eq!(host.shared.project_generation(&root_a).unwrap(), 2);
|
||||
assert_eq!(host.shared.project_generation(&root_b).unwrap(), 2);
|
||||
|
||||
// Bumping project A does not bump project B
|
||||
let bump_a = host.shared.bump_project_generation(&root_a);
|
||||
assert_eq!(bump_a, 3);
|
||||
assert_eq!(host.shared.project_generation(&root_b).unwrap(), 2);
|
||||
|
||||
// Register target for project A and B
|
||||
let target = ide_plugin::PluginRunTarget {
|
||||
id: "run".into(),
|
||||
name: "Run".into(),
|
||||
program: "dummy".into(),
|
||||
args: vec![],
|
||||
workdir_args: vec![],
|
||||
container_root: None,
|
||||
commands: vec![],
|
||||
};
|
||||
assert!(api.register_target(&root_a, target.clone(), None).is_ok());
|
||||
assert!(api.register_target(&root_b, target.clone(), None).is_ok());
|
||||
|
||||
assert_eq!(host.run_targets(&root_a).len(), 1);
|
||||
assert_eq!(host.run_targets(&root_b).len(), 1);
|
||||
|
||||
// Close project A
|
||||
ws.0.lock().unwrap().retain(|p| p != &root_a);
|
||||
host.project_closed(&root_a, "main");
|
||||
|
||||
// Project A targets withdrawn, Project B untouched
|
||||
assert!(host.run_targets(&root_a).is_empty());
|
||||
assert_eq!(host.run_targets(&root_b).len(), 1);
|
||||
|
||||
// Project A generation closed (NotFound on lookup), Project B intact
|
||||
assert!(host.shared.project_generation(&root_a).is_err());
|
||||
assert_eq!(host.shared.project_generation(&root_b).unwrap(), 2);
|
||||
}
|
||||
}
|
||||
@@ -8,8 +8,13 @@
|
||||
//! args = "optional-arguments" # optional
|
||||
//! vmOptions = ["-XX:+AllowEnhancedClassRedefinition"] # optional, API 1.14
|
||||
//! jdk = "jetbrains" # optional: only those VM options on JBR
|
||||
//! executor = "Hot Reload" # optional, API 1.18: see below
|
||||
//! ```
|
||||
//!
|
||||
//! With `executor`, the agent is not added to every launch: the plugin contributes an
|
||||
//! executor beside Run and Debug ("Run with Hot Reload", "Debug with Hot Reload"), and only
|
||||
//! launches through it get the agent and its `vmOptions`.
|
||||
//!
|
||||
//! One agent per plugin. The declaration derives the optional high-risk `java.agent`
|
||||
//! capability; granting it records the jar's hash, and a launch adds the agent only
|
||||
//! while the jar still has it ([`ide_run::java_agent`]).
|
||||
@@ -28,6 +33,7 @@ pub const POINT_ID: &str = "javaAgents";
|
||||
const MAX_ARGS: usize = 4096;
|
||||
const MAX_VM_OPTION: usize = 512;
|
||||
const MAX_VM_OPTIONS: usize = 32;
|
||||
const MAX_EXECUTOR: usize = 40;
|
||||
|
||||
#[derive(Clone, Debug, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
@@ -39,6 +45,8 @@ struct Decl {
|
||||
vm_options: Vec<String>,
|
||||
#[serde(default)]
|
||||
jdk: Option<String>,
|
||||
#[serde(default)]
|
||||
executor: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
@@ -48,6 +56,8 @@ pub(super) struct Agent {
|
||||
pub(super) args: Option<String>,
|
||||
pub(super) vm_options: Vec<String>,
|
||||
pub(super) jdk: Option<String>,
|
||||
/// The executor title: only launches through it get the agent.
|
||||
pub(super) executor: Option<String>,
|
||||
}
|
||||
|
||||
/// Agents of enabled plugins.
|
||||
@@ -111,9 +121,16 @@ impl ExtensionPoint for JavaAgentsPoint {
|
||||
if !vm_options.is_empty() || jdk.is_some() {
|
||||
pkg.manifest.needs_api("contributes.javaAgents.vmOptions", 14)?;
|
||||
}
|
||||
let label = label(&d.path, args.as_deref(), &vm_options);
|
||||
let executor = validate_executor(d.executor)?;
|
||||
if executor.is_some() {
|
||||
pkg.manifest.needs_api("contributes.javaAgents.executor", 18)?;
|
||||
}
|
||||
let mut label = label(&d.path, args.as_deref(), &vm_options);
|
||||
if let Some(title) = &executor {
|
||||
label = format!("{label} (Run with {title})");
|
||||
}
|
||||
let (store, plugin) = (self.store.clone(), pkg.id().to_owned());
|
||||
let agent = Agent { jar, args, vm_options, jdk };
|
||||
let agent = Agent { jar, args, vm_options, jdk, executor };
|
||||
Ok(Prepared::new(label, move || Ok(store.add(plugin, agent))).file(d.path).capability(Capability::JavaAgent))
|
||||
}
|
||||
}
|
||||
@@ -153,6 +170,17 @@ fn validate_jdk(jdk: Option<String>) -> Result<Option<String>, String> {
|
||||
Ok(Some(raw))
|
||||
}
|
||||
|
||||
/// The executor's title: one line, short enough for "Debug '<configuration>' with <title>".
|
||||
fn validate_executor(executor: Option<String>) -> Result<Option<String>, String> {
|
||||
let Some(title) = executor.map(|s| s.trim().to_owned()) else { return Ok(None) };
|
||||
if title.is_empty() || title.chars().count() > MAX_EXECUTOR || title.contains(|c: char| c.is_control()) {
|
||||
return Err(format!(
|
||||
"contributes.javaAgents: `executor` must be a title of 1–{MAX_EXECUTOR} characters on one line"
|
||||
));
|
||||
}
|
||||
Ok(Some(title))
|
||||
}
|
||||
|
||||
/// What Settings › Plugins shows: jar name, args, and any JVM options.
|
||||
fn label(path: &Path, args: Option<&str>, vm_options: &[String]) -> String {
|
||||
let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
@@ -224,6 +252,7 @@ impl JavaAgentSource for PluginJavaAgents {
|
||||
vm_options: agent.vm_options.clone(),
|
||||
jdk: agent.jdk.clone(),
|
||||
approved_hash: pins.get(&(plugin.clone(), cap.clone())).map(|pin| pin.hash.clone()),
|
||||
executor: agent.executor.clone(),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -306,6 +335,33 @@ mod tests {
|
||||
assert_eq!(agent.jdk.as_deref(), Some("jetbrains"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_an_executor_from_api_18() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let manifest = MANIFEST.replace("^1.10", "^1.18");
|
||||
let decl = "[[contributes.javaAgents]]\npath = \"agent/spring agent.jar\"\nexecutor = \" Hot Reload \"\n";
|
||||
let pkg = package(&tmp.path().join("ok"), &format!("{manifest}{decl}"));
|
||||
assert_eq!(prepare(&pkg).unwrap().label, "spring agent.jar (Run with Hot Reload)");
|
||||
let store: Arc<JavaAgents> = Arc::default();
|
||||
let point = JavaAgentsPoint::new(store.clone());
|
||||
let _keep = (point.prepare(&pkg, pkg.manifest.declarations(POINT_ID).remove(0)).unwrap().commit)().unwrap();
|
||||
assert_eq!(store.for_plugin("acme.spring").unwrap().executor.as_deref(), Some("Hot Reload"));
|
||||
let source = PluginJavaAgents { store, pins: Arc::default() };
|
||||
assert_eq!(source.agents()[0].executor.as_deref(), Some("Hot Reload"));
|
||||
|
||||
let old = package(&tmp.path().join("old"), &format!("{MANIFEST_14}{decl}"));
|
||||
assert!(prepare(&old).map(|_| ()).unwrap_err().contains("new in plugin API 1.18"));
|
||||
let long = format!(
|
||||
"[[contributes.javaAgents]]\npath = \"agent/spring agent.jar\"\nexecutor = \"{}\"\n",
|
||||
"x".repeat(41)
|
||||
);
|
||||
let long = package(&tmp.path().join("long"), &format!("{manifest}{long}"));
|
||||
assert!(prepare(&long).map(|_| ()).unwrap_err().contains("`executor`"));
|
||||
let empty = "[[contributes.javaAgents]]\npath = \"agent/spring agent.jar\"\nexecutor = \" \"\n";
|
||||
let empty = package(&tmp.path().join("empty"), &format!("{manifest}{empty}"));
|
||||
assert!(prepare(&empty).map(|_| ()).unwrap_err().contains("`executor`"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refuses_what_would_fail_at_launch() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
use super::{PluginHost, ProviderKind};
|
||||
use ide_core::{IdeResult, Pos, Range};
|
||||
use ide_plugin::{ProviderDocument, language_features::*};
|
||||
use std::sync::Arc;
|
||||
use std::{path::Path, sync::Arc};
|
||||
|
||||
pub(crate) fn valid_range(doc: &ProviderDocument, range: Range) -> bool {
|
||||
valid_range_in(&ide_text::Document::new(&doc.text), range)
|
||||
@@ -279,14 +279,18 @@ impl PluginHost {
|
||||
/// Optional API 1.14 hover actions. Only plugins declaring the
|
||||
/// `hover-actions` provider kind are asked; the released language-features
|
||||
/// export remains unchanged.
|
||||
pub fn language_hover_actions(&self, doc: &ProviderDocument) -> Vec<(String, HoverAction)> {
|
||||
/// `project`: the root of the project whose editor shows `doc`, the providers' invocation project.
|
||||
pub fn language_hover_actions(&self, doc: &ProviderDocument, project: Option<&Path>) -> Vec<(String, HoverAction)> {
|
||||
let project = project.map(Path::to_path_buf);
|
||||
let mut out = Vec::new();
|
||||
for (d, _bounds) in self.feature_documents(doc, None) {
|
||||
let snapshot = d.clone();
|
||||
let text = ide_text::Document::new(&snapshot.text);
|
||||
let d = Arc::new(d);
|
||||
let results = self
|
||||
.document_calls(ProviderKind::HoverActions, &snapshot, move |rt, t| rt.language_hover_actions(&d, t));
|
||||
let project = project.clone();
|
||||
let results = self.document_calls(ProviderKind::HoverActions, &snapshot, move |rt, t| {
|
||||
rt.language_hover_actions(&d, project.as_deref(), t)
|
||||
});
|
||||
for (p, items) in results {
|
||||
let commands: std::collections::HashSet<_> =
|
||||
self.ui.items(super::COMMANDS, Some(p.id())).into_iter().map(|c| c.key).collect();
|
||||
@@ -304,14 +308,22 @@ impl PluginHost {
|
||||
out
|
||||
}
|
||||
|
||||
pub fn language_gutter_actions(&self, doc: &ProviderDocument) -> Vec<(String, GutterAction)> {
|
||||
/// `project`: the root of the project whose editor shows `doc`, the providers' invocation project.
|
||||
pub fn language_gutter_actions(
|
||||
&self,
|
||||
doc: &ProviderDocument,
|
||||
project: Option<&Path>,
|
||||
) -> Vec<(String, GutterAction)> {
|
||||
let project = project.map(Path::to_path_buf);
|
||||
let mut out = Vec::new();
|
||||
for (d, bounds) in self.feature_documents(doc, None) {
|
||||
let lines = d.text.split('\n').count() as u32;
|
||||
let snapshot = d.clone();
|
||||
let d = Arc::new(d);
|
||||
let results = self
|
||||
.document_calls(ProviderKind::GutterActions, &snapshot, move |rt, t| rt.language_gutter_actions(&d, t));
|
||||
let project = project.clone();
|
||||
let results = self.document_calls(ProviderKind::GutterActions, &snapshot, move |rt, t| {
|
||||
rt.language_gutter_actions(&d, project.as_deref(), t)
|
||||
});
|
||||
for (p, items) in results {
|
||||
let commands: std::collections::HashSet<_> =
|
||||
self.ui.items(super::COMMANDS, Some(p.id())).into_iter().map(|c| c.key).collect();
|
||||
|
||||
@@ -385,6 +385,9 @@ impl PluginHost {
|
||||
}
|
||||
);
|
||||
let fetched = self.fetch_market_package(&candidate.url, &entry, &archive);
|
||||
if let Some(mirror) = &candidate.mirror {
|
||||
mirror::report(mirror, fetched.is_ok());
|
||||
}
|
||||
if let Err(e) = &fetched {
|
||||
tracing::warn!("plugins: {} from {} failed: {}", entry.id, candidate.url, e.message);
|
||||
}
|
||||
|
||||
@@ -27,6 +27,7 @@ pub(crate) mod diagnostics;
|
||||
pub mod endpoints;
|
||||
mod event_paths;
|
||||
mod execution;
|
||||
mod external_watch;
|
||||
mod files_changed;
|
||||
mod hover;
|
||||
mod icon_extensions;
|
||||
@@ -211,6 +212,7 @@ const LATENCY_WINDOW: usize = 128;
|
||||
/// Events waiting for one plugin (from one window).
|
||||
struct EventQueue {
|
||||
since: Instant,
|
||||
last_event: Instant,
|
||||
events: Vec<WorkbenchEvent>,
|
||||
files_source: Option<files_changed::Source>,
|
||||
}
|
||||
@@ -220,6 +222,8 @@ const MAX_QUEUED_EVENTS: usize = 500;
|
||||
/// How long events for a plugin that is not running are collected before it
|
||||
/// is activated to receive them.
|
||||
const IDLE_BATCH: Duration = Duration::from_secs(2);
|
||||
/// Maximum delay for debounced events before forcing delivery.
|
||||
const MAX_DEBOUNCE_WAIT: Duration = Duration::from_secs(5);
|
||||
|
||||
struct LoadedPlugin {
|
||||
pkg: Package,
|
||||
@@ -1170,6 +1174,92 @@ impl PluginHost {
|
||||
self.info_of(id)
|
||||
}
|
||||
|
||||
/// Approves the host the plugin's `net:setting:<key>` grant derives from
|
||||
/// the setting's value right now: the dialog when the user applies the
|
||||
/// value in Settings, or the pending row's Approve action. `expected` is
|
||||
/// the host the user was shown: when the setting changed since (the plugin
|
||||
/// can write its own settings), nothing is approved. On a remote host the
|
||||
/// approval is kept for the session only, like `net:ask` (#3809).
|
||||
pub fn approve_net_setting(&self, id: &str, setting: &str, http: bool, expected: &str) -> IdeResult<PluginInfo> {
|
||||
let _guard = self.lifecycle.lock();
|
||||
let plugin = self.get(id)?;
|
||||
self.check_not_uninstalling(&plugin)?;
|
||||
let cap = Capability::NetSetting { http, key: setting.to_owned() };
|
||||
if !plugin.manifest().declares(&cap) {
|
||||
return Err(IdeError::invalid(format!("plugin {id:?} does not declare {cap}")));
|
||||
}
|
||||
let api = api::PluginApi { pkg: plugin.pkg.clone(), shared: self.shared.clone() };
|
||||
let value = api
|
||||
.setting_value(setting)
|
||||
.ok_or_else(|| IdeError::invalid(format!("setting {setting:?} holds no value")))?;
|
||||
let host = api::setting_host(&value)
|
||||
.map_err(IdeError::invalid)?
|
||||
.ok_or_else(|| IdeError::invalid(format!("setting {setting:?} holds no host")))?;
|
||||
if host != expected {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"setting {setting:?} now holds {host}, not {expected}: approve the new value instead"
|
||||
)));
|
||||
}
|
||||
let session_only = self.shared.net_hosts_session_only.load(std::sync::atomic::Ordering::Relaxed);
|
||||
if !session_only {
|
||||
let mut ledger = self.ledger.lock();
|
||||
if !ledger.remember_setting_host(&plugin.subject(), &cap, &host) {
|
||||
return Err(IdeError::invalid(format!("plugin {id:?} does not have {cap} granted")));
|
||||
}
|
||||
self.save_ledger(&ledger);
|
||||
}
|
||||
self.stop(&plugin);
|
||||
if session_only {
|
||||
self.shared.session_setting_hosts.lock().entry(id.to_owned()).or_default().insert(cap.to_string(), host);
|
||||
}
|
||||
if !self.state.lock().disabled.contains(id) {
|
||||
self.start(&plugin);
|
||||
}
|
||||
// Plugins that need this one follow it: running again, or blocked while it can't run.
|
||||
self.settle_dependents(id);
|
||||
self.changed();
|
||||
self.info_of(id)
|
||||
}
|
||||
|
||||
/// The host a `net:setting:<key>` grant derives from `value` (a bare host
|
||||
/// or a URL), for the approval dialog; an error refuses the value.
|
||||
pub fn net_setting_host(&self, id: &str, setting: &str, value: &str) -> IdeResult<String> {
|
||||
let plugin = self.get(id)?;
|
||||
let cap = Capability::NetSetting { http: false, key: setting.to_owned() };
|
||||
if !plugin.manifest().declares(&cap)
|
||||
&& !plugin.manifest().declares(&Capability::NetSetting { http: true, key: setting.to_owned() })
|
||||
{
|
||||
return Err(IdeError::invalid(format!("plugin {id:?} does not declare a setting grant for {setting:?}")));
|
||||
}
|
||||
api::setting_host(value)
|
||||
.map_err(IdeError::invalid)?
|
||||
.ok_or_else(|| IdeError::invalid(format!("{value:?} holds no host")))
|
||||
}
|
||||
|
||||
/// Drops the approved host of a `net:setting:<key>` grant (its revoke
|
||||
/// action, or the setting's value being cleared). Nothing recorded: still
|
||||
/// fine, the state is already as asked.
|
||||
pub fn forget_net_setting(&self, id: &str, setting: &str, http: bool) -> IdeResult<PluginInfo> {
|
||||
let _guard = self.lifecycle.lock();
|
||||
let plugin = self.get(id)?;
|
||||
self.check_not_uninstalling(&plugin)?;
|
||||
let cap = Capability::NetSetting { http, key: setting.to_owned() };
|
||||
{
|
||||
let mut ledger = self.ledger.lock();
|
||||
ledger.forget_setting_host(&plugin.subject(), &cap);
|
||||
self.save_ledger(&ledger);
|
||||
}
|
||||
self.shared.session_setting_hosts.lock().get_mut(id).map(|hosts| hosts.remove(&cap.to_string()));
|
||||
self.stop(&plugin);
|
||||
if !self.state.lock().disabled.contains(id) {
|
||||
self.start(&plugin);
|
||||
}
|
||||
// Plugins that need this one follow it: running again, or blocked while it can't run.
|
||||
self.settle_dependents(id);
|
||||
self.changed();
|
||||
self.info_of(id)
|
||||
}
|
||||
|
||||
/// Grants or revokes one declared capability (Settings › Plugins › Permissions).
|
||||
/// Revoking a required one stops the plugin until consent is given again.
|
||||
pub fn set_capability(&self, id: &str, capability: &str, granted: bool) -> IdeResult<PluginInfo> {
|
||||
@@ -1187,6 +1277,10 @@ impl PluginHost {
|
||||
return Err(IdeError::invalid(format!("plugin {id:?} has not been confirmed yet")));
|
||||
}
|
||||
ledger.set(&subject, &cap, granted);
|
||||
if !granted {
|
||||
// A session-only approval of a setting-derived host goes with its grant.
|
||||
self.shared.session_setting_hosts.lock().get_mut(id).map(|hosts| hosts.remove(&cap.to_string()));
|
||||
}
|
||||
if granted
|
||||
&& cap == Capability::JavaAgent
|
||||
&& let Some(jar) = agent_jar_grant(plugin.manifest(), plugin.dir())
|
||||
@@ -1433,6 +1527,110 @@ impl PluginHost {
|
||||
})
|
||||
}
|
||||
|
||||
/// Run Anything entries (API 1.18) of the plugin that declares `prefix`, for the
|
||||
/// field's `text` in `window`'s project: from what it already knows, within 300 ms.
|
||||
pub fn run_anything_suggest(
|
||||
&self,
|
||||
id: &str,
|
||||
window: &str,
|
||||
root: Option<PathBuf>,
|
||||
prefix: &str,
|
||||
text: &str,
|
||||
) -> IdeResult<Vec<ide_plugin::RunAnythingItem>> {
|
||||
self.declared_run_anything(id, prefix)?;
|
||||
if text.len() > 4096 || !(prefix.starts_with(text) || text.starts_with(prefix)) {
|
||||
return Err(IdeError::invalid("the text doesn't start with the plugin's prefix"));
|
||||
}
|
||||
let invocation = Invocation { client: Some(window.to_owned()), workspace_root: root, ..Default::default() };
|
||||
let (prefix, text) = (prefix.to_owned(), text.to_owned());
|
||||
let budget = Duration::from_millis(300);
|
||||
self.code_call_with_budget(
|
||||
id,
|
||||
invocation,
|
||||
"suggesting Run Anything entries",
|
||||
None,
|
||||
Some(budget),
|
||||
move |rt, inv| rt.run_anything_suggest(&prefix, &text, inv, budget),
|
||||
)
|
||||
}
|
||||
|
||||
/// Runs a Run Anything line whose first word is `prefix` (API 1.18): whether the
|
||||
/// plugin claimed it. A failed call is an error, which the caller treats as claimed.
|
||||
pub fn run_anything_run(
|
||||
&self,
|
||||
id: &str,
|
||||
window: &str,
|
||||
root: Option<PathBuf>,
|
||||
prefix: &str,
|
||||
line: &str,
|
||||
) -> IdeResult<bool> {
|
||||
self.declared_run_anything(id, prefix)?;
|
||||
if line.len() > 4096 || line.split_whitespace().next() != Some(prefix) {
|
||||
return Err(IdeError::invalid("the line doesn't start with the plugin's prefix"));
|
||||
}
|
||||
let invocation = Invocation { client: Some(window.to_owned()), workspace_root: root, ..Default::default() };
|
||||
let (prefix, line) = (prefix.to_owned(), line.to_owned());
|
||||
let timeout = self.limits.timeout;
|
||||
self.code_call(id, invocation, "running a Run Anything line", move |rt, inv| {
|
||||
rt.run_anything_run(&prefix, &line, inv, timeout)
|
||||
})
|
||||
}
|
||||
|
||||
/// Completions (API 1.18) for `field` of the plugin run configuration `config_id`
|
||||
/// (`plugin:<plugin>:<id>`, also a user's override of one), as `window`'s project
|
||||
/// currently has it, for the field's `text` and UTF-16 `caret`: from what the owning
|
||||
/// plugin already knows, within 300 ms.
|
||||
pub fn run_configuration_complete(
|
||||
&self,
|
||||
window: &str,
|
||||
root: &Path,
|
||||
config_id: &str,
|
||||
field: &str,
|
||||
text: &str,
|
||||
caret: u32,
|
||||
) -> IdeResult<Vec<ide_plugin::RunConfigCompletion>> {
|
||||
if text.len() > 16 * 1024 || caret as usize > text.encode_utf16().count() || field.len() > 64 {
|
||||
return Err(IdeError::invalid("the field text or caret is out of range"));
|
||||
}
|
||||
if !self.run_detection().detect(root).iter().any(|c| c.id == config_id && c.kind == "plugin") {
|
||||
return Err(IdeError::not_found("this plugin configuration is no longer provided"));
|
||||
}
|
||||
let owner = self
|
||||
.plugins
|
||||
.read()
|
||||
.keys()
|
||||
.filter(|id| {
|
||||
config_id.strip_prefix(ide_run::EXTERNAL_PREFIX).is_some_and(|rest| rest.starts_with(&format!("{id}:")))
|
||||
})
|
||||
.max_by_key(|id| id.len())
|
||||
.cloned()
|
||||
.ok_or_else(|| IdeError::not_found("the plugin owning this configuration is not loaded"))?;
|
||||
let own = config_id[ide_run::EXTERNAL_PREFIX.len() + owner.len() + 1..].to_owned();
|
||||
let invocation = Invocation {
|
||||
client: Some(window.to_owned()),
|
||||
workspace_root: Some(root.to_path_buf()),
|
||||
..Default::default()
|
||||
};
|
||||
let (field, text) = (field.to_owned(), text.to_owned());
|
||||
let budget = Duration::from_millis(300);
|
||||
self.code_call_with_budget(
|
||||
&owner,
|
||||
invocation,
|
||||
"completing a run configuration field",
|
||||
None,
|
||||
Some(budget),
|
||||
move |rt, inv| rt.run_configuration_complete(&own, &field, &text, caret, inv, budget),
|
||||
)
|
||||
}
|
||||
|
||||
fn declared_run_anything(&self, id: &str, prefix: &str) -> IdeResult<()> {
|
||||
if self.ui.items(ui_points::RUN_ANYTHING, Some(id)).iter().any(|d| d.key == prefix) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(IdeError::invalid(format!("plugin {id:?} declares no Run Anything prefix {prefix:?}")))
|
||||
}
|
||||
}
|
||||
|
||||
/// Content of a declared view, or of a custom editor (`invocation.editor`
|
||||
/// is its document). Activates the plugin (`on-view`).
|
||||
pub fn render_view(
|
||||
@@ -1805,10 +2003,57 @@ impl PluginHost {
|
||||
/// events, and ignores context writes of commands still running for it.
|
||||
pub fn forget_client(&self, label: &str) {
|
||||
self.queues.lock().retain(|(_, client), _| client.as_deref() != Some(label));
|
||||
self.shared.external_watches.remove_client(label);
|
||||
self.shared.forget_client(label);
|
||||
self.forget_web_ptys(label);
|
||||
}
|
||||
|
||||
/// A project closed (or the last window for it detached). Closes the project
|
||||
/// generation, drops queued events for that window and project, withdraws run
|
||||
/// targets and run configurations, and delivers
|
||||
/// `project-closed` to subscribed plugins.
|
||||
pub fn project_closed(&self, root: &Path, window: &str) {
|
||||
self.shared.close_project_generation(root);
|
||||
self.shared.external_watches.remove_project(root);
|
||||
self.withdraw_project_run_targets(root);
|
||||
self.shared.run_configurations.write().retain(|(_, r), _| r != root);
|
||||
|
||||
let root_ipc = ide_core::ipc_path::to_ipc(root);
|
||||
{
|
||||
let mut queues = self.queues.lock();
|
||||
queues.retain(|(_, client), q| {
|
||||
if client.as_deref() == Some(window) {
|
||||
return false;
|
||||
}
|
||||
q.events.retain(|e| {
|
||||
if let WorkbenchEvent::FilesChanged(f) | WorkbenchEvent::WatchedFilesChanged(f) = e
|
||||
&& f.project.as_deref() == Some(&root_ipc)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
true
|
||||
});
|
||||
!q.events.is_empty()
|
||||
});
|
||||
}
|
||||
|
||||
let plugins = self.plugins.read();
|
||||
for p in plugins.values() {
|
||||
{
|
||||
let mut batches = p.batches.lock();
|
||||
batches.files_pending.retain(|(client, ws_root), _| {
|
||||
client.as_deref() != Some(window) && ws_root.as_deref() != Some(root)
|
||||
});
|
||||
}
|
||||
}
|
||||
drop(plugins);
|
||||
// In-flight work is not cancelled: an instance serves every project, and its
|
||||
// results for this one are refused now that the project's generation moved on.
|
||||
|
||||
self.post_events(None, vec![WorkbenchEvent::ProjectClosed(root_ipc)]);
|
||||
self.flush_events();
|
||||
}
|
||||
|
||||
/// The user cancelled a plugin task (`task_id` from `TaskStarted`).
|
||||
pub fn cancel_task(&self, task_id: &str) -> bool {
|
||||
task_id.parse().is_ok_and(|id| self.shared.cancel_task(id))
|
||||
@@ -1945,6 +2190,36 @@ impl PluginHost {
|
||||
);
|
||||
}
|
||||
|
||||
/// Queues what `events.watch-paths` watchers saw for their plugin and window,
|
||||
/// while that window still shows the project the watch belongs to.
|
||||
fn queue_watched_changes(&self, now: Instant) {
|
||||
let changes = self.shared.external_watches.take();
|
||||
if changes.is_empty() {
|
||||
return;
|
||||
}
|
||||
let subs = self.shared.subscriptions.lock().clone();
|
||||
let plugins = self.plugins.read();
|
||||
let mut queues = self.queues.lock();
|
||||
for change in changes {
|
||||
let Some(p) = plugins.get(&change.plugin) else { continue };
|
||||
if self.shared.project_of(&change.client).as_deref() != Some(change.project.as_path())
|
||||
|| !Self::wants(p, EventKind::WatchedFilesChanged, subs.kinds.get(p.id()))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let batch =
|
||||
ide_plugin::FilesChanged { project: Some(ide_core::ipc_path::to_ipc(&change.project)), ..change.batch };
|
||||
let queue = queues.entry((change.plugin, Some(change.client))).or_insert_with(|| EventQueue {
|
||||
since: now,
|
||||
last_event: now,
|
||||
events: Vec::new(),
|
||||
files_source: None,
|
||||
});
|
||||
queue.last_event = now;
|
||||
files_changed::append(&mut queue.events, vec![WorkbenchEvent::WatchedFilesChanged(batch)]);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn post_events(&self, client: Option<&str>, events: Vec<WorkbenchEvent>) {
|
||||
self.post_events_from(client, events, None);
|
||||
}
|
||||
@@ -1998,9 +2273,11 @@ impl PluginHost {
|
||||
}
|
||||
let queue = queues.entry((p.id().to_owned(), client.map(str::to_owned))).or_insert_with(|| EventQueue {
|
||||
since: now,
|
||||
last_event: now,
|
||||
events: Vec::new(),
|
||||
files_source: None,
|
||||
});
|
||||
queue.last_event = now;
|
||||
if let Some(source) = &source {
|
||||
if !queue.files_source.as_ref().is_some_and(|old| old.same(source)) {
|
||||
queue.events.retain(|e| !matches!(e, WorkbenchEvent::FilesChanged(_)));
|
||||
@@ -2015,6 +2292,7 @@ impl PluginHost {
|
||||
&& !matches!(
|
||||
event,
|
||||
WorkbenchEvent::FilesChanged(_)
|
||||
| WorkbenchEvent::WatchedFilesChanged(_)
|
||||
| WorkbenchEvent::RunExited(_)
|
||||
| WorkbenchEvent::TerminalExited(_)
|
||||
| WorkbenchEvent::ContentTabAction(_)
|
||||
@@ -2039,24 +2317,82 @@ impl PluginHost {
|
||||
|
||||
#[doc(hidden)]
|
||||
pub fn flush_events_at(&self, now: Instant) {
|
||||
self.queue_watched_changes(now);
|
||||
let due: Vec<(QueueKey, EventQueue)> = {
|
||||
let mut queues = self.queues.lock();
|
||||
let plugins = self.plugins.read();
|
||||
let keys: Vec<_> = queues
|
||||
.iter()
|
||||
.filter(|((id, _), q)| {
|
||||
let running =
|
||||
plugins.get(id).is_some_and(|p| p.runtime.lock().as_ref().is_some_and(|a| a.is_alive()));
|
||||
running
|
||||
let subs = self.shared.subscriptions.lock();
|
||||
let mut due = Vec::new();
|
||||
let mut keys_to_remove = Vec::new();
|
||||
|
||||
for (key, q) in queues.iter_mut() {
|
||||
let (id, _client) = key;
|
||||
let running = plugins.get(id).is_some_and(|p| p.runtime.lock().as_ref().is_some_and(|a| a.is_alive()));
|
||||
let has_files = q.events.iter().any(|e| matches!(e, WorkbenchEvent::FilesChanged(_)));
|
||||
let has_scheduled = q.events.iter().any(|e| matches!(e, WorkbenchEvent::Scheduled));
|
||||
// Already debounced by the watcher, like project file changes.
|
||||
let has_watched = q.events.iter().any(|e| matches!(e, WorkbenchEvent::WatchedFilesChanged(_)));
|
||||
let debounce = subs.paths.get(id).and_then(|p| p.get("files-changed")).and_then(|f| f.debounce);
|
||||
|
||||
let (files_due, files_debouncing) = if has_files {
|
||||
if let Some(debounce) = debounce {
|
||||
let elapsed = now.saturating_duration_since(q.last_event) >= debounce
|
||||
|| now.saturating_duration_since(q.since) >= MAX_DEBOUNCE_WAIT;
|
||||
(elapsed, !elapsed)
|
||||
} else {
|
||||
(true, false)
|
||||
}
|
||||
} else {
|
||||
(false, false)
|
||||
};
|
||||
|
||||
let other_events_due = (running
|
||||
|| has_watched
|
||||
|| now.saturating_duration_since(q.since) >= IDLE_BATCH
|
||||
|| q.events.len() >= MAX_QUEUED_EVENTS / 2
|
||||
|| has_scheduled)
|
||||
&& q.events.iter().any(|e| !matches!(e, WorkbenchEvent::FilesChanged(_)));
|
||||
|
||||
if files_debouncing {
|
||||
if other_events_due {
|
||||
let mut other_events = Vec::new();
|
||||
q.events.retain(|e| {
|
||||
if matches!(e, WorkbenchEvent::FilesChanged(_)) {
|
||||
true
|
||||
} else {
|
||||
other_events.push(e.clone());
|
||||
false
|
||||
}
|
||||
});
|
||||
due.push((
|
||||
key.clone(),
|
||||
EventQueue {
|
||||
since: q.since,
|
||||
last_event: q.last_event,
|
||||
events: other_events,
|
||||
files_source: None,
|
||||
},
|
||||
));
|
||||
}
|
||||
} else {
|
||||
let is_due = files_due
|
||||
|| has_watched
|
||||
|| running
|
||||
|| now.saturating_duration_since(q.since) >= IDLE_BATCH
|
||||
|| q.events.len() >= MAX_QUEUED_EVENTS / 2
|
||||
|| q.events
|
||||
.iter()
|
||||
.any(|e| matches!(e, WorkbenchEvent::FilesChanged(_) | WorkbenchEvent::Scheduled))
|
||||
})
|
||||
.map(|(k, _)| k.clone())
|
||||
.collect();
|
||||
keys.into_iter().filter_map(|k| queues.remove(&k).map(|q| (k, q))).collect()
|
||||
|| has_scheduled;
|
||||
if is_due {
|
||||
keys_to_remove.push(key.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for k in keys_to_remove {
|
||||
if let Some(q) = queues.remove(&k) {
|
||||
due.push((k, q));
|
||||
}
|
||||
}
|
||||
due
|
||||
};
|
||||
let mut changed = false;
|
||||
for ((id, client), queue) in due {
|
||||
@@ -2081,9 +2417,10 @@ impl PluginHost {
|
||||
pub fn wait_events(&self, timeout: Duration) -> bool {
|
||||
let deadline = Instant::now() + timeout;
|
||||
loop {
|
||||
let busy = self.plugins.read().values().any(|p| p.batches.lock().pending > 0);
|
||||
self.flush_events_at(Instant::now());
|
||||
let busy =
|
||||
self.plugins.read().values().any(|p| p.batches.lock().pending > 0) || !self.queues.lock().is_empty();
|
||||
if !busy {
|
||||
self.flush_events_at(Instant::now());
|
||||
return true;
|
||||
}
|
||||
if Instant::now() >= deadline {
|
||||
@@ -2125,12 +2462,20 @@ impl PluginHost {
|
||||
&& queue.events.iter().any(|e| !matches!(e, WorkbenchEvent::FilesChanged(_)))
|
||||
{
|
||||
let (files, other) = queue.events.into_iter().partition(|e| matches!(e, WorkbenchEvent::FilesChanged(_)));
|
||||
let changed =
|
||||
self.deliver(id, client.clone(), EventQueue { since: queue.since, events: other, files_source: None });
|
||||
let changed = self.deliver(
|
||||
id,
|
||||
client.clone(),
|
||||
EventQueue { since: queue.since, last_event: queue.last_event, events: other, files_source: None },
|
||||
);
|
||||
return self.deliver(
|
||||
id,
|
||||
client,
|
||||
EventQueue { since: queue.since, events: files, files_source: queue.files_source },
|
||||
EventQueue {
|
||||
since: queue.since,
|
||||
last_event: queue.last_event,
|
||||
events: files,
|
||||
files_source: queue.files_source,
|
||||
},
|
||||
) | changed;
|
||||
}
|
||||
let Ok(plugin) = self.get(id) else { return false };
|
||||
@@ -2451,12 +2796,15 @@ impl PluginHost {
|
||||
let restricted = p.dev_root.as_deref().is_some_and(|root| !(self.project_policy.read())(root));
|
||||
if due && !restricted && self.startup_finished.load(Ordering::Acquire) {
|
||||
// Activates it if needed and calls `handle([scheduled])`.
|
||||
self.queues
|
||||
.lock()
|
||||
.entry((p.id().to_owned(), None))
|
||||
.or_insert_with(|| EventQueue { since: now, events: Vec::new(), files_source: None })
|
||||
.events
|
||||
.push(WorkbenchEvent::Scheduled);
|
||||
let mut q = self.queues.lock();
|
||||
let queue = q.entry((p.id().to_owned(), None)).or_insert_with(|| EventQueue {
|
||||
since: now,
|
||||
last_event: now,
|
||||
events: Vec::new(),
|
||||
files_source: None,
|
||||
});
|
||||
queue.last_event = now;
|
||||
queue.events.push(WorkbenchEvent::Scheduled);
|
||||
}
|
||||
}
|
||||
if changed {
|
||||
@@ -2490,6 +2838,7 @@ impl PluginHost {
|
||||
fn prepare(&self, pkg: &Package) -> Result<ide_extension::PreparedSet, String> {
|
||||
plugin_icon(pkg)?;
|
||||
let mut set = self.registry.prepare(pkg)?;
|
||||
check_setting_grants(pkg)?;
|
||||
for icon in [&pkg.manifest.icon, &pkg.manifest.icon_dark].into_iter().flatten() {
|
||||
if !set.files.contains(icon) {
|
||||
set.files.push(icon.clone());
|
||||
@@ -2648,7 +2997,7 @@ impl PluginHost {
|
||||
meta.declared_extra = set.capabilities.clone();
|
||||
meta.error = None;
|
||||
}
|
||||
let (granted, pending) = match decision {
|
||||
let (mut granted, pending) = match decision {
|
||||
Decision::Allowed { granted, pending } => (granted, pending),
|
||||
Decision::NeedsConfirmation { new, .. } => {
|
||||
let mut meta = plugin.meta.lock();
|
||||
@@ -2661,6 +3010,19 @@ impl PluginHost {
|
||||
if let Err(e) = self.registry.commit(set) {
|
||||
return self.set_failed(plugin, e);
|
||||
}
|
||||
// Setting-derived network grants materialize their approved host while
|
||||
// the setting holds it: `net:setting:server` acts as `net:<host>`, so
|
||||
// the request path keeps its rules (`net_capability` / `covers`).
|
||||
let api = api::PluginApi { pkg: plugin.pkg.clone(), shared: self.shared.clone() };
|
||||
for (cap, approved, _pending) in api.net_setting_hosts(&plugin.subject()) {
|
||||
if let Some(host) = approved {
|
||||
match cap {
|
||||
Capability::NetSetting { http: false, key: _ } => granted.push(Capability::Net(host)),
|
||||
Capability::NetSetting { http: true, key: _ } => granted.push(Capability::NetHttp(host)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
{
|
||||
let mut meta = plugin.meta.lock();
|
||||
meta.granted = granted;
|
||||
@@ -3116,6 +3478,21 @@ impl PluginHost {
|
||||
.filter(|g| g.confirmed && g.has(&Capability::NetAsk) && m.declares(&Capability::NetAsk))
|
||||
.map(|g| g.net_hosts.iter().cloned().collect())
|
||||
.unwrap_or_default();
|
||||
// Setting-derived hosts, listed next to the `net:ask` ones: the
|
||||
// approved host, and a pending one the setting now holds.
|
||||
let net_settings = if m.capabilities.all().any(|c| matches!(c, Capability::NetSetting { .. })) {
|
||||
let api = api::PluginApi { pkg: p.pkg.clone(), shared: self.shared.clone() };
|
||||
api.net_setting_hosts(&p.subject())
|
||||
.into_iter()
|
||||
.filter(|(cap, ..)| grant.as_ref().is_some_and(|g| g.confirmed && g.has(cap)))
|
||||
.map(|(cap, approved, pending)| {
|
||||
let Capability::NetSetting { http, key } = cap else { unreachable!() };
|
||||
types::PluginNetSetting { setting: key, http, host: approved, pending }
|
||||
})
|
||||
.collect()
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
PluginInfo {
|
||||
id: m.id.clone(),
|
||||
name: m.name.clone(),
|
||||
@@ -3145,6 +3522,7 @@ impl PluginHost {
|
||||
vm_options: agent.vm_options,
|
||||
jdk: agent.jdk,
|
||||
approved,
|
||||
executor: agent.executor,
|
||||
}
|
||||
}),
|
||||
source: p.source,
|
||||
@@ -3155,6 +3533,7 @@ impl PluginHost {
|
||||
has_code: m.wasm.is_some(),
|
||||
capabilities,
|
||||
net_hosts,
|
||||
net_settings,
|
||||
contributions: self.registry.contributions(&m.id),
|
||||
activation: m.activation.iter().map(ToString::to_string).collect(),
|
||||
warnings: meta.warnings.clone(),
|
||||
@@ -3183,6 +3562,37 @@ fn agent_jar_grant(manifest: &Manifest, dir: &Path) -> Option<BinaryGrant> {
|
||||
Some(BinaryGrant { path, hash })
|
||||
}
|
||||
|
||||
/// `net:setting:<key>` grants name a `string` setting of the plugin's own
|
||||
/// settings schema; checked like the other manifest checks, at install and
|
||||
/// start (#3809).
|
||||
fn check_setting_grants(pkg: &Package) -> Result<(), String> {
|
||||
let derived: Vec<&Capability> =
|
||||
pkg.manifest.capabilities.all().filter(|c| matches!(c, Capability::NetSetting { .. })).collect();
|
||||
if derived.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let mut strings = BTreeSet::new();
|
||||
for decl in pkg.manifest.declarations(ui_points::SETTINGS) {
|
||||
let decl = ui_points::settings(pkg, decl)?;
|
||||
for property in decl.json.get("properties").and_then(|p| p.as_array()).into_iter().flatten() {
|
||||
if property.get("type").and_then(|t| t.as_str()) == Some("string")
|
||||
&& let Some(key) = property.get("key").and_then(|k| k.as_str())
|
||||
{
|
||||
strings.insert(key.to_owned());
|
||||
}
|
||||
}
|
||||
}
|
||||
for cap in derived {
|
||||
let Capability::NetSetting { http: _, key } = cap else { continue };
|
||||
if !strings.contains(key.as_str()) {
|
||||
return Err(format!(
|
||||
"capability `{cap}` needs a `string` setting {key:?} in the plugin's own settings schema"
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Consent / Settings: surface exact contributed JVM flags on the `java.agent` permission.
|
||||
fn annotate_java_agent_vm_options(capabilities: &mut [CapabilityInfo], manifest: &Manifest) {
|
||||
let opts = java_agents::declared_vm_options(manifest);
|
||||
|
||||
@@ -95,6 +95,9 @@ pub fn register_builtin_points(
|
||||
registry.register(Arc::new(UiPoint::new(p::VIEWS, ui.clone(), p::view)))?;
|
||||
registry.register(Arc::new(UiPoint::new(p::CUSTOM_EDITORS, ui.clone(), p::custom_editor)))?;
|
||||
registry.register(Arc::new(UiPoint::new(p::EDITOR_PANELS, ui.clone(), p::editor_panel)))?;
|
||||
registry.register(Arc::new(UiPoint::new(p::OVERLAYS, ui.clone(), p::overlay)))?;
|
||||
registry.register(Arc::new(UiPoint::new(p::DIALOGS, ui.clone(), p::dialog)))?;
|
||||
registry.register(Arc::new(UiPoint::new(p::RUN_ANYTHING, ui.clone(), p::run_anything)))?;
|
||||
registry.register(Arc::new(UiPoint::new(p::MARKER_ICONS, ui.clone(), p::marker_icon)))?;
|
||||
registry.register(Arc::new(UiPoint::new(p::FILE_ICONS, ui.clone(), p::file_icon)))?;
|
||||
registry.register(Arc::new(UiPoint::new(p::FILE_TEMPLATES, ui.clone(), p::file_template)))?;
|
||||
|
||||
Loaded 100 of 1298 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Заблокувати користувача