дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-28 13:32:29 +02:00
Порівняти коміти
255
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
c8757d9a5c | ||
|
|
a0c03447a0 | ||
|
|
c4e0900485 | ||
|
|
a42f13edc2 | ||
|
|
18d6041f2f | ||
|
|
15c5e921df | ||
|
|
bc64188c38 | ||
|
|
a3c819e064 | ||
|
|
1f2e92b433 | ||
|
|
8dfca955a5 | ||
|
|
91aba61c97 | ||
|
|
1fb4135b5b | ||
|
|
24598e0dae | ||
|
|
2436ad6fe9 | ||
|
|
c2c6931f0e | ||
|
|
2e0c8dd527 | ||
|
|
f4be752dda | ||
|
|
a52a639b8e | ||
|
|
1b0bf4d741 | ||
|
|
13597e40a1 | ||
|
|
aa1aa91b0d | ||
|
|
032a3b0453 | ||
|
|
07750ad984 | ||
|
|
ba38f070d9 | ||
|
|
c77f4db777 | ||
|
|
d3067c8d3a | ||
|
|
7bf2702565 | ||
|
|
65c45ffe05 | ||
|
|
84b528f0cd | ||
|
|
8621764813 | ||
|
|
22e1c4b927 | ||
|
|
e2817656e8 | ||
|
|
306c71290c | ||
|
|
51ccb68b72 | ||
|
|
2e965810e9 | ||
|
|
31b70cf0ac | ||
|
|
d0989e2a4b | ||
|
|
d96ed8d154 | ||
|
|
6b41870368 | ||
|
|
660becbaa4 | ||
|
|
a0afc478c1 | ||
|
|
07a88c6fa4 | ||
|
|
46bd6fad3c | ||
|
|
f64dbe65b4 | ||
|
|
e2a5a5db81 | ||
|
|
6eb7abff9f | ||
|
|
b46112fe0b | ||
|
|
4507dc172d | ||
|
|
8442c0c339 | ||
|
|
8ffe3bd230 | ||
|
|
1babff55fc | ||
|
|
2ad95150eb | ||
|
|
fe3e647abb | ||
|
|
62cc6768fe | ||
|
|
2e93422270 | ||
|
|
3a1353cc0e | ||
|
|
c5eab0a4a3 | ||
|
|
581c8cf025 | ||
|
|
807c447792 | ||
|
|
217693a56f | ||
|
|
557295b1df | ||
|
|
7c674e70e5 | ||
|
|
1602a5d010 | ||
|
|
a6d135d66f | ||
|
|
924bf6d3b9 | ||
|
|
318c227b0c | ||
|
|
2ce7621abb | ||
|
|
7ecccb3b75 | ||
|
|
7cbf17b10e | ||
|
|
cb0d02620d | ||
|
|
d6ca43cba4 | ||
|
|
165d4f7d76 | ||
|
|
5785ebadd8 | ||
|
|
0c67a4eea2 | ||
|
|
5e2deed81e | ||
|
|
cae7c05fb1 | ||
|
|
be83458161 | ||
|
|
661124d0d4 | ||
|
|
0dae111b2d | ||
|
|
61d269045b | ||
|
|
266d85fa1a | ||
|
|
f964d79e10 | ||
|
|
4a3eacff62 | ||
|
|
aebc2fe02d | ||
|
|
9b63aa9526 | ||
|
|
df07073886 | ||
|
|
3433ee951b | ||
|
|
8f5b281486 | ||
|
|
43aee8058c | ||
|
|
4016c3c905 | ||
|
|
e6cb7df653 | ||
|
|
2a26c82357 | ||
|
|
66f0bce92f | ||
|
|
dfbd13e2af | ||
|
|
944b57dead | ||
|
|
5bcb37492f | ||
|
|
d5bde9af67 | ||
|
|
5b3e2b7a3d | ||
|
|
dbb6fa51c3 | ||
|
|
3d1769ef00 | ||
|
|
c966429f92 | ||
|
|
dfcc05dd41 | ||
|
|
d41feefc07 | ||
|
|
f0fe910017 | ||
|
|
b932220b41 | ||
|
|
bcad8f61cb | ||
|
|
2cdcb888cf | ||
|
|
9ed0fd9fa7 | ||
|
|
fe76dc4573 | ||
|
|
45a75f782a | ||
|
|
bd1fd011e4 | ||
|
|
b44015b2ce | ||
|
|
0cce0a9840 | ||
|
|
db8224f74e | ||
|
|
b075f5de2a | ||
|
|
3240164840 | ||
|
|
f70f362a3d | ||
|
|
806bb4c78d | ||
|
|
57094bc285 | ||
|
|
a5e0c41663 | ||
|
|
77071238a0 | ||
|
|
64097d3c20 | ||
|
|
cf0e57e5df | ||
|
|
703cf23296 | ||
|
|
a88073d6fb | ||
|
|
4b5745c1b6 | ||
|
|
4667c81e6b | ||
|
|
cea9d863f9 | ||
|
|
5fa953eddd | ||
|
|
031f1acd07 | ||
|
|
add23fe97f | ||
|
|
3d2b0946de | ||
|
|
6c7282b442 | ||
|
|
1f79a7f805 | ||
|
|
3d1eaf71e4 | ||
|
|
138209c627 | ||
|
|
b283d352b7 | ||
|
|
f7f9dabe2b | ||
|
|
787d4fbcfa | ||
|
|
3fbd0e05a5 | ||
|
|
2d021a3414 | ||
|
|
cd7582c5e5 | ||
|
|
d16b852054 | ||
|
|
06223d9bd7 | ||
|
|
dcd81d601b | ||
|
|
762ebecd86 | ||
|
|
fd4efff6e3 | ||
|
|
8968974f42 | ||
|
|
5f083ae47c | ||
|
|
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 |
No files matched your search
@@ -3,7 +3,8 @@ 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).
|
||||
# and without the HOMEBREW_TAP_DEPLOY_KEY secret (the private half of a write deploy key on
|
||||
# l0ng-ai/homebrew-tap).
|
||||
on:
|
||||
workflow_call:
|
||||
inputs:
|
||||
@@ -27,17 +28,17 @@ jobs:
|
||||
env:
|
||||
TAG: ${{ inputs.tag }}
|
||||
TAP: l0ng-ai/homebrew-tap
|
||||
HOMEBREW_TAP_TOKEN: ${{ secrets.HOMEBREW_TAP_TOKEN }}
|
||||
HOMEBREW_TAP_DEPLOY_KEY: ${{ secrets.HOMEBREW_TAP_DEPLOY_KEY }}
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
steps:
|
||||
- name: Check tag and token
|
||||
- name: Check tag and deploy key
|
||||
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"
|
||||
elif [ -z "$HOMEBREW_TAP_DEPLOY_KEY" ]; then
|
||||
echo "::notice::HOMEBREW_TAP_DEPLOY_KEY unset: not updating the cask for $TAG"
|
||||
echo "skip=true" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
- uses: actions/checkout@v5
|
||||
@@ -47,7 +48,7 @@ jobs:
|
||||
if: steps.check.outputs.skip != 'true'
|
||||
with:
|
||||
repository: ${{ env.TAP }}
|
||||
token: ${{ secrets.HOMEBREW_TAP_TOKEN }}
|
||||
ssh-key: ${{ secrets.HOMEBREW_TAP_DEPLOY_KEY }}
|
||||
path: tap
|
||||
- uses: actions/setup-node@v5
|
||||
if: steps.check.outputs.skip != 'true'
|
||||
|
||||
@@ -39,6 +39,7 @@ on:
|
||||
- "src/editor/lsp/hint.ts"
|
||||
- "src/editor/lsp/lsp.ts"
|
||||
- "src/editor/lsp/positions.ts"
|
||||
- "src/editor/lsp/snippet.ts"
|
||||
- "src/bindings.ts"
|
||||
- "src/styles/tokens.css"
|
||||
- "src/test/setup.ts"
|
||||
@@ -106,7 +107,7 @@ jobs:
|
||||
# ide-lsp/dap/run/sdk/tools.
|
||||
unused='^crates/(ide-agent|ide-analysis|ide-android|ide-cli|ide-clipboard|ide-coverage|ide-db|ide-docker|ide-fonts|ide-github|ide-http|ide-mcp|ide-notebook|ide-profiler|ide-scaffold|ide-spell|ide-ssh|ide-vcs|ide-web)/'
|
||||
# The workflow's paths, less those handled per language below.
|
||||
smoke='^(crates/|Cargo\.(toml|lock)$|src/features/(run|debugger|build|build-tools)/|src/platform/|src/workbench/|src/ui/|src/editor/(api|navigationProviders|relatedProviders|core/cm/(cornerInset|iconArea)|lsp/(availability|diagnostics|files|hint|lsp|positions))\.ts$|src/bindings\.ts$|src/styles/tokens\.css$|src/test/setup\.ts$|src-tauri/icons/128x128\.png$|smoke/|vite\.config\.ts$|tsconfig\.json$|package\.json$|pnpm-(lock|workspace)\.yaml$|patches/|\.github/workflows/language-smoke\.yml$|\.github/tool-versions\.env$)'
|
||||
smoke='^(crates/|Cargo\.(toml|lock)$|src/features/(run|debugger|build|build-tools)/|src/platform/|src/workbench/|src/ui/|src/editor/(api|navigationProviders|relatedProviders|core/cm/(cornerInset|iconArea)|lsp/(availability|diagnostics|files|hint|lsp|positions|snippet))\.ts$|src/bindings\.ts$|src/styles/tokens\.css$|src/test/setup\.ts$|src-tauri/icons/128x128\.png$|smoke/|vite\.config\.ts$|tsconfig\.json$|package\.json$|pnpm-(lock|workspace)\.yaml$|patches/|\.github/workflows/language-smoke\.yml$|\.github/tool-versions\.env$)'
|
||||
langs=""
|
||||
while read -r f; do
|
||||
case "$f" in
|
||||
|
||||
@@ -179,7 +179,7 @@ jobs:
|
||||
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.
|
||||
# The cask in l0ng-ai/homebrew-tap; skipped for prereleases and without HOMEBREW_TAP_DEPLOY_KEY.
|
||||
homebrew:
|
||||
needs: publish
|
||||
uses: ./.github/workflows/homebrew.yml
|
||||
|
||||
Створено
+254
-197
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.53"
|
||||
version = "0.1.54"
|
||||
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"] }
|
||||
|
||||
@@ -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.
|
||||
|
||||
|
||||
@@ -25,7 +25,7 @@ pub(crate) async fn run(shared: &Arc<Shared>, spec: &ProviderSpec, model: Option
|
||||
Err(err)
|
||||
if !prefer_stored
|
||||
&& crate::provider::is_copilot_provider(&spec.id)
|
||||
&& crate::provider::has_unconfigured_copilot_ambient_token(&spec.env)
|
||||
&& crate::provider::has_unconfigured_copilot_ambient_token(&spec.env, &shared.paths.project_root)
|
||||
&& super::auth_required(0, &err) =>
|
||||
{
|
||||
let retry = run_once(shared, spec, true, model).await;
|
||||
|
||||
@@ -283,6 +283,20 @@ impl AgentCatalogs {
|
||||
}
|
||||
}
|
||||
|
||||
/// Clears a failed discovery cooldown so a fresh sign-in can immediately load models.
|
||||
pub(crate) fn clear_failed_cooldown(&self, shared: &Shared, provider: &str) {
|
||||
let key = Self::key(shared, provider);
|
||||
let mut state = self.state.lock();
|
||||
if let Some(entry) = state.entries.get_mut(&key)
|
||||
&& entry.flight.is_none()
|
||||
&& entry.error.is_some()
|
||||
{
|
||||
entry.completed = None;
|
||||
entry.retry_at_ms = None;
|
||||
entry.error = None;
|
||||
}
|
||||
}
|
||||
|
||||
fn snapshot(&self, shared: &Shared, provider: &str, entry: &Entry) -> AgentModelCatalog {
|
||||
let catalog = entry.catalog.clone().unwrap_or_default();
|
||||
let model_failure = entry.requested_model.as_ref().and_then(|model| entry.model_failures.get(model));
|
||||
@@ -613,6 +627,40 @@ impl crate::AgentManager {
|
||||
let spec = self.shared.spec(provider).ok_or_else(|| IdeError::invalid(format!("unknown agent {provider}")))?;
|
||||
Ok(self.shared.paths.catalogs.request(&self.shared, spec, force, model).0)
|
||||
}
|
||||
|
||||
/// Probes Copilot's model catalog for a staged `account` selection (`""` = Copilot CLI
|
||||
/// default) without mutating `models.json` or broadcasting to active sessions before Apply.
|
||||
pub async fn preview_copilot_models(&self, account: &str, model: Option<&str>) -> IdeResult<AgentModelCatalog> {
|
||||
let mut spec = provider::load(self.shared.paths.custom_agents_dir.as_deref(), self.shared.env_secrets())
|
||||
.into_iter()
|
||||
.find(|p| p.id == "copilot")
|
||||
.ok_or_else(|| IdeError::not_found("unknown agent 'copilot'"))?;
|
||||
spec.env.retain(|(name, _)| name != provider::COPILOT_GITHUB_ACCOUNT_ENV);
|
||||
let account = account.trim();
|
||||
if !account.is_empty() {
|
||||
spec.env.push((provider::COPILOT_GITHUB_ACCOUNT_ENV.into(), account.to_owned()));
|
||||
}
|
||||
match discover(&self.shared, spec, model).await {
|
||||
Ok(found) => Ok(AgentModelCatalog {
|
||||
provider: "copilot".into(),
|
||||
config: self.shared.config_for_new_task(found.config, "copilot"),
|
||||
thought_levels: self.shared.thought_levels_for_new_task(found.levels, "copilot"),
|
||||
refreshing: false,
|
||||
refreshed_at_ms: Some(self.shared.paths.catalogs.epoch_ms()),
|
||||
retry_at_ms: None,
|
||||
error: None,
|
||||
}),
|
||||
Err(error) => Ok(AgentModelCatalog {
|
||||
provider: "copilot".into(),
|
||||
config: Vec::new(),
|
||||
thought_levels: BTreeMap::new(),
|
||||
refreshing: false,
|
||||
refreshed_at_ms: None,
|
||||
retry_at_ms: None,
|
||||
error: Some(error),
|
||||
}),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn discover(
|
||||
|
||||
@@ -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!({
|
||||
|
||||
@@ -33,6 +33,7 @@ pub use catalogs::AgentCatalogs;
|
||||
pub use cli_update::{AgentCliOffer, AgentCliUpdateResult};
|
||||
pub use external::ExternalSession;
|
||||
pub use model::*;
|
||||
pub use provider::{LoginLaunch, gh_authenticated_accounts, gh_login_launch};
|
||||
pub use skill_installer::{
|
||||
InstallRemoteSkillRequest, RemoteSkillBrowseResult, RemoteSkillCandidate, RemoteSkillFile, RemoteSkillPreview,
|
||||
SkillScanWarning, SkillScanWarningKind,
|
||||
@@ -53,6 +54,49 @@ use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering};
|
||||
use std::sync::{Arc, Weak};
|
||||
use std::time::Duration;
|
||||
|
||||
/// Resolves agent `id`'s interactive sign-in command without an open project.
|
||||
pub fn login_launch_without_project(
|
||||
custom_agents_dir: Option<&Path>,
|
||||
secrets: Option<&dyn EnvSecrets>,
|
||||
cwd: &Path,
|
||||
id: &str,
|
||||
) -> IdeResult<LoginLaunch> {
|
||||
let spec = provider::load(custom_agents_dir, secrets)
|
||||
.into_iter()
|
||||
.find(|p| p.id == id)
|
||||
.ok_or_else(|| IdeError::not_found(format!("unknown agent '{id}'")))?;
|
||||
spec.login_launch(cwd, None)
|
||||
.ok_or_else(|| IdeError::unavailable(format!("{} cannot be signed in directly from OpenIDEA", spec.name)))
|
||||
}
|
||||
|
||||
/// Queries Copilot's default CLI sign-in status alongside authenticated `gh` accounts.
|
||||
pub async fn copilot_auth_status_with(
|
||||
custom_agents_dir: Option<&Path>,
|
||||
secrets: Option<&dyn EnvSecrets>,
|
||||
cwd: &Path,
|
||||
) -> CopilotAuthStatus {
|
||||
let copilot_spec = provider::load(custom_agents_dir, secrets).into_iter().find(|p| p.id == "copilot");
|
||||
let cwd_buf = cwd.to_path_buf();
|
||||
let cli_fut = async move {
|
||||
let spec = copilot_spec?;
|
||||
native::copilot::probe_auth_status(spec, cwd_buf).await
|
||||
};
|
||||
let gh_fut = tokio::task::spawn_blocking(provider::gh_authenticated_accounts);
|
||||
let (cli, gh) = tokio::join!(cli_fut, gh_fut);
|
||||
let (gh_installed, gh_accounts) = gh.unwrap_or((false, Vec::new()));
|
||||
match cli {
|
||||
Some(cli) => CopilotAuthStatus {
|
||||
authenticated: cli.authenticated,
|
||||
login: cli.login,
|
||||
auth_type: cli.auth_type,
|
||||
status_message: cli.status_message,
|
||||
gh_installed,
|
||||
gh_accounts,
|
||||
},
|
||||
None => CopilotAuthStatus { gh_installed, gh_accounts, ..CopilotAuthStatus::default() },
|
||||
}
|
||||
}
|
||||
|
||||
/// Receives the events of one project's tasks.
|
||||
pub type AgentSink = Arc<dyn Fn(AgentEvent) + Send + Sync>;
|
||||
|
||||
@@ -201,6 +245,8 @@ struct Shared {
|
||||
providers: RwLock<Vec<provider::ProviderSpec>>,
|
||||
/// Last probe of each provider.
|
||||
probes: Mutex<HashMap<String, AgentProbe>>,
|
||||
/// `type: "terminal"` login arguments reported during `initialize`, by provider id.
|
||||
terminal_auth_args: RwLock<HashMap<String, Vec<String>>>,
|
||||
/// Copilot CLI installs where `--headless` failed and fell back to `--acp`.
|
||||
copilot_acp_fallback: Mutex<HashSet<CopilotBinaryKey>>,
|
||||
/// [`IDLE_RELEASE`], in milliseconds (shorter in tests).
|
||||
@@ -450,10 +496,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 +547,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 +585,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 +614,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
|
||||
@@ -660,6 +752,7 @@ impl AgentManager {
|
||||
known,
|
||||
providers,
|
||||
probes: Mutex::new(HashMap::new()),
|
||||
terminal_auth_args: RwLock::new(HashMap::new()),
|
||||
copilot_acp_fallback: Mutex::new(HashSet::new()),
|
||||
idle_release_ms: AtomicU64::new(IDLE_RELEASE.as_millis() as u64),
|
||||
mcp_servers_hook: RwLock::new(None),
|
||||
@@ -739,16 +832,24 @@ impl AgentManager {
|
||||
*self.shared.git_executable.write() = Some(hook);
|
||||
}
|
||||
|
||||
/// Directory holding linked Git worktrees created for agent tasks of this project.
|
||||
pub fn worktrees_dir(&self) -> &Path {
|
||||
&self.shared.paths.worktrees_dir
|
||||
}
|
||||
|
||||
/// The agents (custom ones re-read), whether each is installed, and what they offered last time.
|
||||
pub fn providers(&self) -> Vec<AgentProvider> {
|
||||
let specs = provider::load(self.shared.paths.custom_agents_dir.as_deref(), self.shared.env_secrets());
|
||||
let in_use: std::collections::HashSet<String> =
|
||||
self.tasks.read().values().map(|t| t.state.lock().task.provider.clone()).collect();
|
||||
let terminal_auth = self.shared.terminal_auth_args.read();
|
||||
let list = specs
|
||||
.iter()
|
||||
.filter(|p| !provider::is_unlisted(p) || in_use.contains(&p.id))
|
||||
.map(|p| {
|
||||
let mut info = provider::describe(p);
|
||||
info.can_sign_in =
|
||||
p.can_sign_in(&self.shared.paths.project_root, terminal_auth.get(&p.id).map(Vec::as_slice));
|
||||
let catalog = self.shared.paths.catalogs.cached(&self.shared, &p.id);
|
||||
info.config = self.shared.config_for_new_task(catalog.config, &p.id);
|
||||
info.thought_levels = self.shared.thought_levels_for_new_task(catalog.thought_levels, &p.id);
|
||||
@@ -756,6 +857,7 @@ impl AgentManager {
|
||||
info
|
||||
})
|
||||
.collect();
|
||||
drop(terminal_auth);
|
||||
let mut prev = self.shared.providers.write();
|
||||
let mut probes = self.shared.probes.lock();
|
||||
probes.retain(|id, _| {
|
||||
@@ -769,6 +871,35 @@ impl AgentManager {
|
||||
list
|
||||
}
|
||||
|
||||
/// Resolves the interactive sign-in command for agent `id`.
|
||||
pub fn login_launch(&self, id: &str) -> IdeResult<LoginLaunch> {
|
||||
let specs = provider::load(self.shared.paths.custom_agents_dir.as_deref(), self.shared.env_secrets());
|
||||
let spec = specs
|
||||
.into_iter()
|
||||
.find(|p| p.id == id)
|
||||
.ok_or_else(|| IdeError::not_found(format!("unknown agent '{id}'")))?;
|
||||
let terminal_args = self.shared.terminal_auth_args.read().get(id).cloned();
|
||||
let launch = spec.login_launch(&self.shared.paths.project_root, terminal_args.as_deref()).ok_or_else(|| {
|
||||
IdeError::unavailable(format!("{} cannot be signed in directly from OpenIDEA", spec.name))
|
||||
})?;
|
||||
self.shared.paths.catalogs.clear_failed_cooldown(&self.shared, id);
|
||||
Ok(launch)
|
||||
}
|
||||
|
||||
/// Queries Copilot's default CLI sign-in status alongside authenticated `gh` accounts.
|
||||
pub async fn copilot_auth_status(&self) -> CopilotAuthStatus {
|
||||
let status = copilot_auth_status_with(
|
||||
self.shared.paths.custom_agents_dir.as_deref(),
|
||||
self.shared.env_secrets(),
|
||||
&self.shared.paths.project_root,
|
||||
)
|
||||
.await;
|
||||
if status.authenticated || !status.gh_accounts.is_empty() {
|
||||
self.shared.paths.catalogs.clear_failed_cooldown(&self.shared, "copilot");
|
||||
}
|
||||
status
|
||||
}
|
||||
|
||||
/// Overrides built-in `id`'s command with `command` (the driver and arguments stay
|
||||
/// the built-in's) through its agent file, or returns it to auto-detection with `None`.
|
||||
pub fn set_builtin_command(&self, id: &str, command: Option<String>) -> IdeResult<()> {
|
||||
@@ -778,12 +909,22 @@ 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 {
|
||||
return Err(IdeError::unavailable("there is no custom agents directory"));
|
||||
};
|
||||
provider::set_builtin_env(&dir, self.shared.env_secrets(), id, env)
|
||||
provider::set_builtin_env(&dir, self.shared.env_secrets(), id, env)?;
|
||||
self.shared.paths.catalogs.evict_if_idle(&self.shared, id);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Saves a new custom ACP agent through its agent file.
|
||||
@@ -1023,6 +1164,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 +1380,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 +1747,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 +2619,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 +2634,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 +2659,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 +2916,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 +2938,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 +3220,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,
|
||||
@@ -3345,6 +3596,14 @@ impl Task {
|
||||
let is_auth = matches!(&e, RpcError::Server { code, message, .. } if acp::auth_required(*code, message));
|
||||
SessionOpenError { message: self.describe(e), allow_acp_fallback: !is_auth }
|
||||
})?;
|
||||
if let Some(args) = init.auth_methods.iter().find_map(|method| {
|
||||
if method.get("type").and_then(Value::as_str) != Some("terminal") {
|
||||
return None;
|
||||
}
|
||||
method.get("args")?.as_array()?.iter().map(|v| v.as_str().map(str::to_owned)).collect::<Option<Vec<_>>>()
|
||||
}) {
|
||||
self.shared.terminal_auth_args.write().insert(provider_id.to_owned(), args);
|
||||
}
|
||||
let sign_in_message = spec.sign_in_message(&init.auth_methods);
|
||||
let can_load = init.load_session();
|
||||
let (capabilities, embedded) = capabilities_of(&init);
|
||||
@@ -3357,66 +3616,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 +3733,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 +3847,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 +3919,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 +4799,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
|
||||
}
|
||||
@@ -4779,7 +5105,8 @@ fn tool_event(
|
||||
i: usize,
|
||||
entry: &AgentEntry,
|
||||
) -> Option<AgentEvent> {
|
||||
let AgentEntry::Tool { id, title, kind, status, locations, images, output, diffs, started_ms, ended_ms } = entry
|
||||
let AgentEntry::Tool { id, title, kind, status, locations, images, output, diffs, started_ms, ended_ms, command } =
|
||||
entry
|
||||
else {
|
||||
return None;
|
||||
};
|
||||
@@ -4794,6 +5121,7 @@ fn tool_event(
|
||||
diffs: diffs.clone(),
|
||||
started_ms: *started_ms,
|
||||
ended_ms: *ended_ms,
|
||||
command: command.clone(),
|
||||
};
|
||||
let text = output.as_deref().unwrap_or_default();
|
||||
let key = (subagent, i);
|
||||
|
||||
@@ -547,6 +547,9 @@ pub enum AgentEntry {
|
||||
started_ms: Option<f64>,
|
||||
#[serde(default)]
|
||||
ended_ms: Option<f64>,
|
||||
/// The command an `execute` call runs, from its structured input; `None` when the agent gave none.
|
||||
#[serde(default)]
|
||||
command: Option<String>,
|
||||
},
|
||||
Plan {
|
||||
items: Vec<AgentPlanItem>,
|
||||
@@ -612,6 +615,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>,
|
||||
@@ -620,6 +626,9 @@ pub struct AgentProvider {
|
||||
pub command_read_only_reason: Option<AgentCommandReadOnlyReason>,
|
||||
/// Whether the command was found (on `PATH`).
|
||||
pub installed: bool,
|
||||
/// Whether OpenIDEA can run this agent's sign-in flow directly in an embedded terminal.
|
||||
#[serde(default)]
|
||||
pub can_sign_in: bool,
|
||||
/// The built-in command can be owned by a global npm package.
|
||||
#[serde(default)]
|
||||
pub can_check_cli_update: bool,
|
||||
@@ -644,6 +653,34 @@ pub enum AgentCommandReadOnlyReason {
|
||||
CustomAgent,
|
||||
}
|
||||
|
||||
/// An authenticated `github.com` account stored in GitHub CLI (`gh`).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct GhAuthAccount {
|
||||
pub login: String,
|
||||
pub active: bool,
|
||||
}
|
||||
|
||||
/// GitHub Copilot's default sign-in status alongside the accounts available through `gh`.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct CopilotAuthStatus {
|
||||
pub authenticated: bool,
|
||||
pub login: Option<String>,
|
||||
pub auth_type: Option<String>,
|
||||
pub status_message: Option<String>,
|
||||
pub gh_installed: bool,
|
||||
pub gh_accounts: Vec<GhAuthAccount>,
|
||||
}
|
||||
|
||||
/// Output and completion of an interactive sign-in PTY started by the IDE.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(tag = "type", rename_all = "camelCase")]
|
||||
pub enum AgentLoginEvent {
|
||||
Output { data: String },
|
||||
Exited { code: Option<i32> },
|
||||
}
|
||||
|
||||
/// Where an agent comes from.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(tag = "kind", rename_all = "camelCase")]
|
||||
@@ -700,6 +737,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
|
||||
}
|
||||
@@ -1470,14 +1481,13 @@ fn stop_reason(turn: &Value, last_error: Option<Value>, rate_limits: Option<&Val
|
||||
let e = turn.get("error").filter(|e| !e.is_null()).cloned().or(last_error).unwrap_or(json!({}));
|
||||
let message = translate::error_message(&e);
|
||||
return match translate::classify(&e, rate_limits) {
|
||||
Failure::Refusal => Ok(json!({ "stopReason": "refusal" })),
|
||||
Failure::UsageLimit(resets) => Err(ResponseError {
|
||||
code: codes::INTERNAL_ERROR,
|
||||
message,
|
||||
data: Some(json!({ "openidea": { "usageLimit": { "resetsAtMs": resets } } })),
|
||||
}),
|
||||
Failure::Auth => Err(error(AUTH_REQUIRED, format!("Codex authentication failed: {message}"))),
|
||||
Failure::Other => Err(error(codes::INTERNAL_ERROR, message)),
|
||||
Failure::Refusal | Failure::Other => Err(error(codes::INTERNAL_ERROR, message)),
|
||||
};
|
||||
}
|
||||
_ => "end_turn",
|
||||
@@ -1595,3 +1605,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,
|
||||
@@ -382,6 +455,90 @@ fn failures_are_classified() {
|
||||
assert_eq!(stop_reason(&json!({"status": "interrupted"}), None, None).unwrap(), json!({"stopReason": "cancelled"}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_turns_preserve_codex_error_diagnostics() {
|
||||
let policy = json!({
|
||||
"message": "This content was flagged for possible cybersecurity risk.",
|
||||
"additionalDetails": "Contact support if this is unexpected.",
|
||||
"codexErrorInfo": "cyberPolicy"
|
||||
});
|
||||
let expected = "This content was flagged for possible cybersecurity risk.\nContact support if this is unexpected.\nCodex error: cyberPolicy";
|
||||
for (turn_error, last_error) in [(policy.clone(), None), (Value::Null, Some(policy.clone()))] {
|
||||
let failure = stop_reason(&json!({ "status": "failed", "error": turn_error }), last_error, None).unwrap_err();
|
||||
assert_eq!(failure.code, codes::INTERNAL_ERROR);
|
||||
assert_eq!(failure.message, expected);
|
||||
}
|
||||
// A completed turn's own error wins over an older error notification.
|
||||
let failure = stop_reason(
|
||||
&json!({ "status": "failed", "error": policy }),
|
||||
Some(json!({ "message": "An earlier retry failed.", "codexErrorInfo": "other" })),
|
||||
None,
|
||||
)
|
||||
.unwrap_err();
|
||||
assert_eq!(failure.message, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_turn_diagnostics_include_string_and_structured_error_codes() {
|
||||
for (value, expected) in [
|
||||
(
|
||||
json!({ "message": "Context is full.", "codexErrorInfo": "contextWindowExceeded" }),
|
||||
"Context is full.\nCodex error: contextWindowExceeded",
|
||||
),
|
||||
(
|
||||
json!({ "message": "The stream disconnected.", "codexErrorInfo": { "responseStreamDisconnected": { "httpStatusCode": 502 } } }),
|
||||
"The stream disconnected.\nCodex error: responseStreamDisconnected (HTTP 502)",
|
||||
),
|
||||
(
|
||||
json!({ "message": "Failed\nbecause", "additionalDetails": "because", "codexErrorInfo": null }),
|
||||
"Failed\nbecause",
|
||||
),
|
||||
(
|
||||
json!({ "message": " ", "additionalDetails": " Details ", "codexErrorInfo": "cyberPolicy" }),
|
||||
"Codex failed\nDetails\nCodex error: cyberPolicy",
|
||||
),
|
||||
(json!({ "message": "Failed", "codexErrorInfo": "" }), "Failed"),
|
||||
(json!({}), "Codex failed"),
|
||||
] {
|
||||
assert_eq!(error_message(&value), expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn policy_failure_is_forwarded_over_acp_with_its_original_diagnostics() {
|
||||
for notification_only in [false, true] {
|
||||
let mut transcript = load(Scenario::UsageLimit.file());
|
||||
let policy = json!({
|
||||
"message": "This content was flagged for possible cybersecurity risk.",
|
||||
"additionalDetails": "Contact support if this is unexpected.",
|
||||
"codexErrorInfo": "cyberPolicy"
|
||||
});
|
||||
for (out, frame) in &mut transcript.frames {
|
||||
if *out {
|
||||
continue;
|
||||
}
|
||||
match frame["method"].as_str() {
|
||||
Some("error") => frame["params"]["error"] = policy.clone(),
|
||||
Some("turn/completed") => {
|
||||
frame["params"]["turn"]["error"] = if notification_only { Value::Null } else { policy.clone() }
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let (results, _client, _frames, _meta, _codex) = replay_transcript(Scenario::Simple, transcript).await;
|
||||
match result(&results, "prompt") {
|
||||
Err(RpcError::Server { code, message, .. }) => {
|
||||
assert_eq!(*code, codes::INTERNAL_ERROR);
|
||||
assert_eq!(
|
||||
message,
|
||||
"This content was flagged for possible cybersecurity risk.\nContact support if this is unexpected.\nCodex error: cyberPolicy"
|
||||
);
|
||||
}
|
||||
response => panic!("the failed turn must reach the task as an error, got {response:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn approvals_offer_what_codex_offers_and_always_a_decline() {
|
||||
let params = json!({"availableDecisions": ["accept",
|
||||
@@ -648,6 +805,7 @@ enum Scenario {
|
||||
Steer,
|
||||
Simple,
|
||||
MultiTurn,
|
||||
ServiceTier { first: Option<bool>, second: Option<bool> },
|
||||
Approvals,
|
||||
UsageLimit,
|
||||
Subagent,
|
||||
@@ -666,6 +824,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 +931,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 +1473,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 +2098,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<_>>(),
|
||||
@@ -677,7 +740,7 @@ pub(super) enum Failure {
|
||||
UsageLimit(Option<f64>),
|
||||
/// Signed out or refused.
|
||||
Auth,
|
||||
/// The model declined.
|
||||
/// The server blocked the turn under a safety policy.
|
||||
Refusal,
|
||||
Other,
|
||||
}
|
||||
@@ -717,13 +780,27 @@ fn resets_at(rate_limits: Option<&Value>) -> Option<f64> {
|
||||
exhausted.map(|s| s * 1000.0)
|
||||
}
|
||||
|
||||
/// The text a failed turn reports: codex's message, with its details.
|
||||
/// The text a failed turn reports: Codex's message, details and diagnostic code.
|
||||
pub(super) fn error_message(error: &Value) -> String {
|
||||
let message = error.get("message").and_then(Value::as_str).unwrap_or("Codex failed").trim();
|
||||
match error.get("additionalDetails").and_then(Value::as_str).map(str::trim).filter(|d| !d.is_empty()) {
|
||||
Some(details) if !message.contains(details) => format!("{message}\n{details}"),
|
||||
_ => message.to_owned(),
|
||||
let original =
|
||||
error.get("message").and_then(Value::as_str).map(str::trim).filter(|m| !m.is_empty()).unwrap_or("Codex failed");
|
||||
let mut message = original.to_owned();
|
||||
if let Some(details) =
|
||||
error.get("additionalDetails").and_then(Value::as_str).map(str::trim).filter(|d| !d.is_empty())
|
||||
&& !original.contains(details)
|
||||
{
|
||||
message.push('\n');
|
||||
message.push_str(details);
|
||||
}
|
||||
let info = error.get("codexErrorInfo").unwrap_or(&Value::Null);
|
||||
let code = info.as_str().or_else(|| info.as_object()?.keys().next().map(String::as_str));
|
||||
if let Some(code) = code.map(str::trim).filter(|c| !c.is_empty()) {
|
||||
message.push_str(&format!("\nCodex error: {code}"));
|
||||
if let Some(status) = info.get(code).and_then(|details| details.get("httpStatusCode")).and_then(Value::as_u64) {
|
||||
message.push_str(&format!(" (HTTP {status})"));
|
||||
}
|
||||
}
|
||||
message
|
||||
}
|
||||
|
||||
/// One choice of an approval: what ACP shows and what codex gets back.
|
||||
|
||||
@@ -114,7 +114,7 @@ pub(crate) fn is_missing_binary_error(err: &std::io::Error) -> bool {
|
||||
pub(crate) async fn discover(spec: ProviderSpec, cwd: PathBuf) -> Result<Discovered, DiscoverError> {
|
||||
tokio::time::timeout(DISCOVER_TIMEOUT, async move {
|
||||
let prefer_stored = crate::provider::prefer_stored_copilot_auth();
|
||||
let has_ambient = crate::provider::has_unconfigured_copilot_ambient_token(&spec.env);
|
||||
let has_ambient = crate::provider::has_unconfigured_copilot_ambient_token(&spec.env, &cwd);
|
||||
match discover_once(spec.clone(), cwd.clone(), prefer_stored).await {
|
||||
Err(err)
|
||||
if !prefer_stored
|
||||
@@ -185,6 +185,78 @@ async fn discover_once(spec: ProviderSpec, cwd: PathBuf, strip_ambient: bool) ->
|
||||
res
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub(crate) struct CliAuthStatus {
|
||||
pub authenticated: bool,
|
||||
pub login: Option<String>,
|
||||
pub auth_type: Option<String>,
|
||||
pub status_message: Option<String>,
|
||||
}
|
||||
|
||||
/// Queries `auth.getStatus` on Copilot's headless server (ignoring any IDE-selected `gh`
|
||||
/// account override so the UI can show what the "Default" account resolves to).
|
||||
pub(crate) async fn probe_auth_status(mut spec: ProviderSpec, cwd: PathBuf) -> Option<CliAuthStatus> {
|
||||
spec.env.retain(|(name, _)| name != crate::provider::COPILOT_GITHUB_ACCOUNT_ENV);
|
||||
tokio::time::timeout(Duration::from_secs(8), async move {
|
||||
let prefer_stored = crate::provider::prefer_stored_copilot_auth();
|
||||
let has_ambient = crate::provider::has_unconfigured_copilot_ambient_token(&spec.env, &cwd);
|
||||
let first = probe_auth_once(spec.clone(), cwd.clone(), prefer_stored).await;
|
||||
if !prefer_stored
|
||||
&& has_ambient
|
||||
&& first.as_ref().is_none_or(|s| !s.authenticated)
|
||||
&& let Some(retry) = probe_auth_once(spec, cwd, true).await
|
||||
{
|
||||
if retry.authenticated {
|
||||
crate::provider::mark_prefer_stored_copilot_auth();
|
||||
}
|
||||
return Some(retry);
|
||||
}
|
||||
first
|
||||
})
|
||||
.await
|
||||
.ok()
|
||||
.flatten()
|
||||
}
|
||||
|
||||
async fn probe_auth_once(spec: ProviderSpec, cwd: PathBuf, strip_ambient: bool) -> Option<CliAuthStatus> {
|
||||
let launch = tokio::task::spawn_blocking({
|
||||
let cwd = cwd.clone();
|
||||
move || spec.resolve_for_launch_with_copilot_env(&cwd, strip_ambient)
|
||||
})
|
||||
.await
|
||||
.ok()?
|
||||
.ok()?;
|
||||
let cwd = dunce::canonicalize(&cwd).unwrap_or(cwd);
|
||||
let args = headless_args(&launch.args);
|
||||
let peer = Peer::spawn_framed(
|
||||
&launch.command,
|
||||
&args,
|
||||
&cwd,
|
||||
&launch.env,
|
||||
Arc::new(ide_jsonrpc::NoopHandler),
|
||||
Box::new(|_| {}),
|
||||
Framing::ContentLength,
|
||||
)
|
||||
.ok()?;
|
||||
let res = async {
|
||||
handshake(&peer).await.ok()?;
|
||||
let auth: Value = peer.request("auth.getStatus", json!({}), None).await.ok()?;
|
||||
let authenticated = auth.get("isAuthenticated").and_then(Value::as_bool).unwrap_or(false);
|
||||
let str_field = |key: &str| {
|
||||
auth.get(key).and_then(Value::as_str).map(str::trim).filter(|s| !s.is_empty()).map(str::to_owned)
|
||||
};
|
||||
Some(CliAuthStatus {
|
||||
authenticated,
|
||||
login: str_field("login"),
|
||||
auth_type: str_field("authType"),
|
||||
status_message: str_field("statusMessage"),
|
||||
})
|
||||
}
|
||||
.await;
|
||||
peer.kill();
|
||||
res
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(super) fn attach(
|
||||
client: Arc<dyn Handler>,
|
||||
|
||||
@@ -2,7 +2,10 @@
|
||||
//! `<config>/agents/<id>.toml` (written by hand, or by installing one from the ACP
|
||||
//! Registry, see `registry`).
|
||||
|
||||
use crate::{AcpImportOutcome, AgentCommandReadOnlyReason, AgentProvider, AgentSource, CustomAgentInput, EnvSecrets};
|
||||
use crate::{
|
||||
AcpImportOutcome, AgentCommandReadOnlyReason, AgentProvider, AgentSource, CustomAgentInput, EnvSecrets,
|
||||
GhAuthAccount,
|
||||
};
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
@@ -33,6 +36,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,
|
||||
@@ -71,7 +76,7 @@ const BUILTIN: &[(&str, &str, Driver, &[&str], &str)] = &[
|
||||
"GitHub Copilot",
|
||||
Driver::Copilot,
|
||||
&["copilot", "--headless", "--no-auto-update", "--stdio"],
|
||||
"Run `copilot` in a terminal and sign in.",
|
||||
"Run `copilot login` in a terminal.",
|
||||
),
|
||||
("cursor", "Cursor", Driver::Acp, &["cursor-agent", "acp"], "Run `cursor-agent login` in a terminal."),
|
||||
("opencode", "OpenCode", Driver::Acp, &["opencode", "acp"], "Run `opencode auth login` in a terminal."),
|
||||
@@ -96,6 +101,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,
|
||||
@@ -148,12 +154,26 @@ impl ProviderSpec {
|
||||
cwd: &Path,
|
||||
strip_ambient_tokens: bool,
|
||||
) -> Result<Self, String> {
|
||||
let account = is_copilot_provider(&self.id).then(|| copilot_github_account(&self.env)).flatten();
|
||||
let is_copilot = is_copilot_provider(&self.id);
|
||||
let account = is_copilot.then(|| copilot_github_account(&self.env)).flatten();
|
||||
let explicit_copilot_token =
|
||||
self.env.iter().any(|(name, value)| name == "COPILOT_GITHUB_TOKEN" && !value.is_empty());
|
||||
let mut resolved = self.resolve_for_launch_base(cwd, strip_ambient_tokens || account.is_some());
|
||||
if let Some(account) = account {
|
||||
let token = github_token_for_account(&account)?;
|
||||
// Keep any project-scoped `GH_TOKEN` untouched so `gh` commands inside Copilot's
|
||||
// shell use the project's GitHub account while `COPILOT_GITHUB_TOKEN` bills `account`.
|
||||
resolved.env.retain(|(name, _)| !AMBIENT_COPILOT_AUTH_VARS.contains(&name.as_str()));
|
||||
resolved.env.push(("COPILOT_GITHUB_TOKEN".into(), token));
|
||||
} else if is_copilot
|
||||
&& !strip_ambient_tokens
|
||||
&& !explicit_copilot_token
|
||||
&& ide_core::project_env::github_token(cwd).is_some()
|
||||
&& let Some(default_token) = default_github_token()
|
||||
{
|
||||
// A project-scoped `GH_TOKEN` targets repository/PR commands, not Copilot model
|
||||
// billing: pin `COPILOT_GITHUB_TOKEN` to the user's global `gh` account when present.
|
||||
resolved.env.push(("COPILOT_GITHUB_TOKEN".into(), default_token));
|
||||
}
|
||||
Ok(resolved)
|
||||
}
|
||||
@@ -163,7 +183,7 @@ impl ProviderSpec {
|
||||
self.command = crate::native::newest_install(&self.command);
|
||||
}
|
||||
if is_copilot_provider(&self.id) {
|
||||
self.env = sanitized_copilot_env(&self.env, strip_ambient_tokens);
|
||||
self.env = sanitized_copilot_env(&self.env, cwd, strip_ambient_tokens);
|
||||
self.env.retain(|(name, _)| name != COPILOT_GITHUB_ACCOUNT_ENV);
|
||||
}
|
||||
let program = ide_jsonrpc::resolve_spawn_program(&self.command, &self.env);
|
||||
@@ -173,6 +193,80 @@ impl ProviderSpec {
|
||||
.into_owned();
|
||||
self
|
||||
}
|
||||
|
||||
/// Resolves the executable, arguments, and environment to run this agent's interactive
|
||||
/// sign-in flow directly in an IDE PTY without shell quoting.
|
||||
pub(crate) fn login_launch(&self, cwd: &Path, terminal_auth_args: Option<&[String]>) -> Option<LoginLaunch> {
|
||||
let search = ide_core::tool_path::search_path();
|
||||
let resolve_exe = |cmd: &str, env: &[(String, String)]| -> Option<PathBuf> {
|
||||
let spawned = ide_jsonrpc::resolve_spawn_program(cmd, env);
|
||||
let candidate =
|
||||
if spawned.components().count() > 1 && !spawned.is_absolute() { cwd.join(&spawned) } else { spawned };
|
||||
if candidate.is_absolute() && is_executable(&candidate) {
|
||||
return Some(candidate);
|
||||
}
|
||||
ide_core::tool_path::find_command(&candidate.to_string_lossy(), &search, cwd)
|
||||
};
|
||||
|
||||
if let Some((separate_cmd, separate_args)) = match self.id.as_str() {
|
||||
"claude-acp" => Some(("claude", &[][..])),
|
||||
"codex-acp" => Some(("codex", &["login"][..])),
|
||||
"vibe" => Some(("vibe", &[][..])),
|
||||
_ => None,
|
||||
} {
|
||||
let program = resolve_exe(separate_cmd, &self.env)?;
|
||||
return Some(LoginLaunch {
|
||||
program,
|
||||
args: separate_args.iter().map(|s| (*s).to_owned()).collect(),
|
||||
env: self.env.iter().cloned().collect(),
|
||||
});
|
||||
}
|
||||
|
||||
if let Some(builtin) = builtin_spec(&self.id) {
|
||||
let args = terminal_auth_args
|
||||
.filter(|_| matches!(self.source, AgentSource::Registry { .. }))
|
||||
.map(<[String]>::to_vec)
|
||||
.or_else(|| builtin_login_args(&builtin))?;
|
||||
let resolved = self.clone().resolve_for_launch_base(cwd, true);
|
||||
let program = resolve_exe(&resolved.command, &resolved.env)?;
|
||||
let mut env: BTreeMap<String, String> = resolved.env.into_iter().collect();
|
||||
if is_copilot_provider(&self.id) {
|
||||
for key in AMBIENT_COPILOT_AUTH_VARS {
|
||||
env.insert(key.to_owned(), String::new());
|
||||
}
|
||||
}
|
||||
return Some(LoginLaunch { program, args, env });
|
||||
}
|
||||
|
||||
let args = terminal_auth_args?.to_vec();
|
||||
let resolved = self.clone().resolve_for_launch_base(cwd, true);
|
||||
let program = resolve_exe(&resolved.command, &resolved.env)?;
|
||||
Some(LoginLaunch { program, args, env: resolved.env.into_iter().collect() })
|
||||
}
|
||||
|
||||
pub(crate) fn can_sign_in(&self, cwd: &Path, terminal_auth_args: Option<&[String]>) -> bool {
|
||||
self.login_launch(cwd, terminal_auth_args).is_some()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct LoginLaunch {
|
||||
pub program: PathBuf,
|
||||
pub args: Vec<String>,
|
||||
pub env: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
fn builtin_login_args(builtin: &ProviderSpec) -> Option<Vec<String>> {
|
||||
let prefix = format!("Run `{}", builtin.command);
|
||||
let rest = builtin.login_hint.strip_prefix(&prefix)?.strip_prefix([' ', '`']);
|
||||
match rest {
|
||||
Some(after_space) if builtin.login_hint[prefix.len()..].starts_with(' ') => {
|
||||
let (args, _) = after_space.split_once('`')?;
|
||||
Some(args.split_whitespace().map(str::to_owned).collect())
|
||||
}
|
||||
Some(_) => Some(Vec::new()),
|
||||
None => None,
|
||||
}
|
||||
}
|
||||
|
||||
const AMBIENT_COPILOT_AUTH_VARS: [&str; 3] = ["COPILOT_GITHUB_TOKEN", "GH_TOKEN", "GITHUB_TOKEN"];
|
||||
@@ -191,16 +285,26 @@ pub(crate) fn copilot_github_account(env: &[(String, String)]) -> Option<String>
|
||||
.map(str::to_owned)
|
||||
}
|
||||
|
||||
fn find_gh_executable() -> Option<PathBuf> {
|
||||
ide_core::tool_path::find_gh_executable()
|
||||
}
|
||||
|
||||
fn is_valid_github_login(account: &str) -> bool {
|
||||
let bytes = account.as_bytes();
|
||||
!bytes.is_empty()
|
||||
&& bytes.len() <= 39
|
||||
&& bytes[0].is_ascii_alphanumeric()
|
||||
&& bytes.iter().all(|b| b.is_ascii_alphanumeric() || *b == b'-' || *b == b'_')
|
||||
}
|
||||
|
||||
fn github_token_for_account(account: &str) -> Result<String, String> {
|
||||
let path = ide_core::process::shell_env()
|
||||
.find(|(name, _)| name == "PATH")
|
||||
.map(|(_, value)| value)
|
||||
.or_else(|| ide_core::process::host_var_os("PATH"));
|
||||
let program = path
|
||||
.as_deref()
|
||||
.and_then(|path| ide_core::process::find_executable("gh", path))
|
||||
if !is_valid_github_login(account) {
|
||||
return Err(format!("Invalid GitHub account login: {account}"));
|
||||
}
|
||||
let program = find_gh_executable()
|
||||
.ok_or_else(|| "GitHub CLI (`gh`) is required to select a Copilot GitHub account".to_owned())?;
|
||||
let mut command = std::process::Command::new(program);
|
||||
ide_core::process::prepare(&mut command);
|
||||
command.args(["auth", "token", "--hostname", "github.com", "--user", account]).envs(ide_core::process::shell_env());
|
||||
for name in AMBIENT_COPILOT_AUTH_VARS {
|
||||
command.env_remove(name);
|
||||
@@ -226,6 +330,140 @@ fn github_token_for_account(account: &str) -> Result<String, String> {
|
||||
Ok(token.to_owned())
|
||||
}
|
||||
|
||||
/// Interactive `gh auth login` launch for adding/switching GitHub CLI accounts in-IDE,
|
||||
/// with ambient `GITHUB_TOKEN` / `GH_TOKEN` cleared so `gh` does not refuse to run.
|
||||
pub fn gh_login_launch() -> IdeResult<LoginLaunch> {
|
||||
let program = find_gh_executable().ok_or_else(|| IdeError::unavailable("GitHub CLI (`gh`) is not installed"))?;
|
||||
let mut env = BTreeMap::new();
|
||||
for key in AMBIENT_COPILOT_AUTH_VARS {
|
||||
env.insert(key.to_owned(), String::new());
|
||||
}
|
||||
Ok(LoginLaunch {
|
||||
program,
|
||||
args: vec!["auth".into(), "login".into(), "--hostname".into(), "github.com".into()],
|
||||
env,
|
||||
})
|
||||
}
|
||||
|
||||
/// Returns `(gh_installed, authenticated_accounts)` for `github.com` from `gh auth status`,
|
||||
/// ignoring ambient token environment variables so keyring accounts remain visible.
|
||||
pub fn gh_authenticated_accounts() -> (bool, Vec<GhAuthAccount>) {
|
||||
let Some(program) = find_gh_executable() else {
|
||||
return (false, Vec::new());
|
||||
};
|
||||
let run_gh = |args: &[&str]| -> Option<std::process::Output> {
|
||||
let mut command = std::process::Command::new(&program);
|
||||
ide_core::process::prepare(&mut command);
|
||||
command
|
||||
.args(args)
|
||||
.envs(ide_core::process::shell_env())
|
||||
.env("GH_PROMPT_DISABLED", "1")
|
||||
.env("GH_NO_UPDATE_NOTIFIER", "1")
|
||||
.env("NO_COLOR", "1");
|
||||
for name in AMBIENT_COPILOT_AUTH_VARS {
|
||||
command.env_remove(name);
|
||||
}
|
||||
command.output().ok()
|
||||
};
|
||||
if let Some(output) = run_gh(&["auth", "status", "--json", "hosts"]) {
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
if let Some(accounts) = parse_gh_auth_status_json(&stdout) {
|
||||
return (true, accounts);
|
||||
}
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
if !stderr.contains("unknown flag: --json") {
|
||||
return (true, Vec::new());
|
||||
}
|
||||
}
|
||||
let fallback = run_gh(&["auth", "status", "--hostname", "github.com"])
|
||||
.map(|out| format!("{}\n{}", String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr)))
|
||||
.map(|text| parse_gh_auth_status_text(&text))
|
||||
.unwrap_or_default();
|
||||
(true, fallback)
|
||||
}
|
||||
|
||||
fn parse_gh_auth_status_json(text: &str) -> Option<Vec<GhAuthAccount>> {
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct Entry {
|
||||
#[serde(default)]
|
||||
state: Option<String>,
|
||||
#[serde(default)]
|
||||
active: bool,
|
||||
#[serde(default)]
|
||||
login: String,
|
||||
#[serde(default)]
|
||||
token_source: Option<String>,
|
||||
}
|
||||
#[derive(Deserialize)]
|
||||
struct Response {
|
||||
#[serde(default)]
|
||||
hosts: BTreeMap<String, Vec<Entry>>,
|
||||
}
|
||||
let parsed: Response = serde_json::from_str(text.trim()).ok()?;
|
||||
let mut accounts: Vec<GhAuthAccount> = Vec::new();
|
||||
if let Some(entries) = parsed.hosts.get("github.com") {
|
||||
for entry in entries {
|
||||
let login = entry.login.trim();
|
||||
if login.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if entry.state.as_deref().is_some_and(|s| s != "success") {
|
||||
continue;
|
||||
}
|
||||
// Tokens from the environment (`GH_TOKEN`, `GITHUB_TOKEN`, …) are not keyring accounts.
|
||||
if entry.token_source.as_deref().is_some_and(|source| source.ends_with("_TOKEN") || source == "env") {
|
||||
continue;
|
||||
}
|
||||
if let Some(existing) = accounts.iter_mut().find(|a| a.login == login) {
|
||||
existing.active |= entry.active;
|
||||
} else {
|
||||
accounts.push(GhAuthAccount { login: login.to_owned(), active: entry.active });
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(accounts)
|
||||
}
|
||||
|
||||
fn parse_gh_auth_status_text(text: &str) -> Vec<GhAuthAccount> {
|
||||
let mut accounts: Vec<GhAuthAccount> = Vec::new();
|
||||
let mut current: Option<usize> = None;
|
||||
for line in text.lines() {
|
||||
let trimmed = line.trim();
|
||||
if let Some((_, rest)) = trimmed.split_once("Logged in to github.com account ") {
|
||||
let login = rest.split_whitespace().next().unwrap_or("").trim();
|
||||
current = None;
|
||||
if !login.is_empty() && !rest.contains("_TOKEN") {
|
||||
if let Some(idx) = accounts.iter().position(|a| a.login == login) {
|
||||
current = Some(idx);
|
||||
} else {
|
||||
accounts.push(GhAuthAccount { login: login.to_owned(), active: false });
|
||||
current = Some(accounts.len() - 1);
|
||||
}
|
||||
}
|
||||
} else if trimmed.starts_with("- Active account: true")
|
||||
&& let Some(idx) = current
|
||||
{
|
||||
accounts[idx].active = true;
|
||||
}
|
||||
}
|
||||
accounts
|
||||
}
|
||||
|
||||
fn default_github_token() -> Option<String> {
|
||||
let program = find_gh_executable()?;
|
||||
let mut command = std::process::Command::new(program);
|
||||
ide_core::process::prepare(&mut command);
|
||||
command.args(["auth", "token", "--hostname", "github.com"]).envs(ide_core::process::shell_env());
|
||||
for name in AMBIENT_COPILOT_AUTH_VARS {
|
||||
command.env_remove(name);
|
||||
}
|
||||
let output = command.output().ok().filter(|out| out.status.success())?;
|
||||
let token = String::from_utf8(output.stdout).ok()?;
|
||||
let token = token.trim();
|
||||
(!token.is_empty()).then(|| token.to_owned())
|
||||
}
|
||||
|
||||
pub(crate) fn prefer_stored_copilot_auth() -> bool {
|
||||
PREFER_STORED_COPILOT_AUTH.load(std::sync::atomic::Ordering::Acquire)
|
||||
}
|
||||
@@ -234,18 +472,17 @@ pub(crate) fn mark_prefer_stored_copilot_auth() {
|
||||
PREFER_STORED_COPILOT_AUTH.store(true, std::sync::atomic::Ordering::Release);
|
||||
}
|
||||
|
||||
pub(crate) fn has_unconfigured_copilot_ambient_token(spec_env: &[(String, String)]) -> bool {
|
||||
pub(crate) fn has_unconfigured_copilot_ambient_token(spec_env: &[(String, String)], cwd: &Path) -> bool {
|
||||
AMBIENT_COPILOT_AUTH_VARS.iter().any(|&key| {
|
||||
!spec_env.iter().any(|(k, v)| k == key && !v.is_empty())
|
||||
&& ambient_copilot_env_value(key).is_some_and(|v| !v.is_empty())
|
||||
&& ambient_copilot_env_value(key, cwd).is_some_and(|v| !v.is_empty())
|
||||
})
|
||||
}
|
||||
|
||||
fn ambient_copilot_env_value(key: &str) -> Option<String> {
|
||||
ide_core::process::shell_env()
|
||||
.find(|(k, _)| *k == key)
|
||||
.map(|(_, v)| v.to_string_lossy().into_owned())
|
||||
.or_else(|| ide_core::process::host_var_os(key).map(|v| v.to_string_lossy().into_owned()))
|
||||
fn ambient_copilot_env_value(key: &str, cwd: &Path) -> Option<String> {
|
||||
ide_core::process::host_var_os_in(cwd, key).map(|v| v.to_string_lossy().into_owned()).or_else(|| {
|
||||
ide_core::process::shell_env().find(|(k, _)| *k == key).map(|(_, v)| v.to_string_lossy().into_owned())
|
||||
})
|
||||
}
|
||||
|
||||
/// Builds child environment overrides for `copilot`:
|
||||
@@ -256,9 +493,10 @@ fn ambient_copilot_env_value(key: &str) -> Option<String> {
|
||||
/// while preserving any token explicitly configured in OpenIDEA's agent `spec_env`.
|
||||
pub(crate) fn sanitized_copilot_env(
|
||||
spec_env: &[(String, String)],
|
||||
cwd: &Path,
|
||||
strip_ambient_tokens: bool,
|
||||
) -> Vec<(String, String)> {
|
||||
sanitize_copilot_env_with(spec_env, strip_ambient_tokens, ambient_copilot_env_value)
|
||||
sanitize_copilot_env_with(spec_env, strip_ambient_tokens, |key| ambient_copilot_env_value(key, cwd))
|
||||
}
|
||||
|
||||
pub(crate) fn sanitize_copilot_env_with(
|
||||
@@ -347,16 +585,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 +616,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))),
|
||||
@@ -373,6 +624,7 @@ pub(crate) fn describe(spec: &ProviderSpec) -> AgentProvider {
|
||||
command_editable: reason.is_none(),
|
||||
command_read_only_reason: reason,
|
||||
installed: installed(&spec.command),
|
||||
can_sign_in: spec.can_sign_in(Path::new("."), None),
|
||||
can_check_cli_update: spec.source == AgentSource::Builtin && crate::cli_update::package(&spec.id).is_some(),
|
||||
env: spec.env.iter().cloned().collect(),
|
||||
config: vec![],
|
||||
@@ -391,7 +643,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 +696,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 +707,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 +721,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 +729,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 +776,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 +847,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 +891,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 +1025,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 +1043,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;
|
||||
@@ -853,6 +1137,22 @@ mod tests {
|
||||
assert_eq!(reset.env, custom.env);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_builtin_login_hint_yields_the_arguments_sign_in_runs() {
|
||||
// Sign In runs the arguments in the hint's backticks: rewording a hint must keep that form.
|
||||
for spec in builtins() {
|
||||
if matches!(spec.id.as_str(), "claude-acp" | "codex-acp" | "vibe") {
|
||||
continue;
|
||||
}
|
||||
assert!(builtin_login_args(&spec).is_some(), "{}: {}", spec.id, spec.login_hint);
|
||||
}
|
||||
let args = |id: &str| builtin_login_args(&builtin_spec(id).unwrap()).unwrap();
|
||||
assert_eq!(args("copilot"), ["login"]);
|
||||
assert_eq!(args("goose"), ["configure"]);
|
||||
assert_eq!(args("hermes"), ["model"]);
|
||||
assert!(args("qwen").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn login_hints_cover_all_builtin_commands_and_preserve_separate_login_tools() {
|
||||
for spec in builtins() {
|
||||
@@ -1043,6 +1343,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 +1399,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() }),
|
||||
}
|
||||
@@ -1064,12 +1412,12 @@ mod tests {
|
||||
"copilot",
|
||||
BTreeMap::from([
|
||||
("REGISTRY_SETTING".into(), "kept".into()),
|
||||
(COPILOT_GITHUB_ACCOUNT_ENV.into(), "dengliu_microsoft".into()),
|
||||
(COPILOT_GITHUB_ACCOUNT_ENV.into(), "alice-work".into()),
|
||||
]),
|
||||
)
|
||||
.unwrap();
|
||||
let spec = load(Some(dir.path()), None).into_iter().find(|spec| spec.id == "copilot").unwrap();
|
||||
assert_eq!(copilot_github_account(&spec.env).as_deref(), Some("dengliu_microsoft"));
|
||||
assert_eq!(copilot_github_account(&spec.env).as_deref(), Some("alice-work"));
|
||||
|
||||
set_builtin_env(dir.path(), None, "copilot", BTreeMap::from([("REGISTRY_SETTING".into(), "changed".into())]))
|
||||
.unwrap_err();
|
||||
@@ -1078,7 +1426,7 @@ mod tests {
|
||||
#[test]
|
||||
fn launch_metadata_never_passes_the_github_account_control_to_copilot() {
|
||||
let mut spec = builtin_spec("copilot").unwrap();
|
||||
spec.env.push((COPILOT_GITHUB_ACCOUNT_ENV.into(), "dengliu_microsoft".into()));
|
||||
spec.env.push((COPILOT_GITHUB_ACCOUNT_ENV.into(), "alice-work".into()));
|
||||
let resolved = spec.resolve_for_launch(Path::new("."));
|
||||
assert!(resolved.env.iter().all(|(name, _)| name != COPILOT_GITHUB_ACCOUNT_ENV));
|
||||
}
|
||||
@@ -1108,6 +1456,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 +1482,7 @@ mod tests {
|
||||
driver: Driver::Claude,
|
||||
command: "/old/claude".into(),
|
||||
args: vec![],
|
||||
additional_args: Vec::new(),
|
||||
env: BTreeMap::new(),
|
||||
registry: None,
|
||||
};
|
||||
@@ -1186,6 +1536,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() }),
|
||||
};
|
||||
@@ -1359,4 +1710,68 @@ mod tests {
|
||||
vec![("GITHUB_TOKEN".into(), String::new()), ("GH_TOKEN".into(), "github_pat_custom".into())]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_gh_auth_status_json_and_text_without_ambient_token_entries() {
|
||||
let raw = r#"{
|
||||
"hosts": {
|
||||
"github.com": [
|
||||
{"state": "failed", "active": true, "login": "bad", "tokenSource": "GITHUB_TOKEN"},
|
||||
{"state": "success", "active": true, "login": "alice", "tokenSource": "keyring"},
|
||||
{"state": "success", "active": false, "login": "alice-work", "tokenSource": "keyring"},
|
||||
{"state": "success", "active": false, "login": "env_user", "tokenSource": "GH_TOKEN"}
|
||||
],
|
||||
"ghe.example.com": [
|
||||
{"state": "success", "active": true, "login": "corp", "tokenSource": "keyring"}
|
||||
]
|
||||
}
|
||||
}"#;
|
||||
assert_eq!(
|
||||
parse_gh_auth_status_json(raw),
|
||||
Some(vec![
|
||||
GhAuthAccount { login: "alice".into(), active: true },
|
||||
GhAuthAccount { login: "alice-work".into(), active: false },
|
||||
])
|
||||
);
|
||||
|
||||
let text = "\
|
||||
github.com
|
||||
✓ Logged in to github.com account env_user (GH_TOKEN)
|
||||
- Active account: true
|
||||
✓ Logged in to github.com account alice (keyring)
|
||||
- Active account: false
|
||||
✓ Logged in to github.com account alice-work (keyring)
|
||||
- Active account: true
|
||||
";
|
||||
assert_eq!(
|
||||
parse_gh_auth_status_text(text),
|
||||
vec![
|
||||
GhAuthAccount { login: "alice".into(), active: false },
|
||||
GhAuthAccount { login: "alice-work".into(), active: true },
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn login_launch_resolves_paths_with_spaces_and_clears_ambient_copilot_tokens() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let app_support = dir.path().join("Application Support/copilot");
|
||||
std::fs::create_dir_all(&app_support).unwrap();
|
||||
let bin = app_support.join(if cfg!(windows) { "copilot.cmd" } else { "copilot" });
|
||||
std::fs::write(&bin, "#!/bin/sh\n").unwrap();
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::set_permissions(&bin, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
}
|
||||
let mut spec = builtin_spec("copilot").unwrap();
|
||||
spec.command = bin.to_string_lossy().into_owned();
|
||||
spec.source = AgentSource::Registry { version: "1.0.115".into(), update: None };
|
||||
let launch = spec.login_launch(dir.path(), None).unwrap();
|
||||
assert_eq!(launch.program, bin);
|
||||
assert_eq!(launch.args, ["login"]);
|
||||
assert_eq!(launch.env.get("GITHUB_TOKEN").map(String::as_str), Some(""));
|
||||
assert_eq!(launch.env.get("GH_TOKEN").map(String::as_str), Some(""));
|
||||
assert_eq!(launch.env.get("COPILOT_GITHUB_TOKEN").map(String::as_str), Some(""));
|
||||
}
|
||||
}
|
||||
@@ -189,6 +189,11 @@ fn parse(text: &str) -> IdeResult<Vec<Entry>> {
|
||||
/// `github/copilot-cli` publishes standalone archives and `SHA256SUMS.txt` on every GitHub
|
||||
/// release. Supplying them installs Copilot without Node.js, npm, `~/.npmrc`, or mirror lag.
|
||||
fn add_copilot_release_binaries(entry: &mut Entry, release_base: &str) {
|
||||
let sys_root = if cfg!(target_os = "linux") { Some(Path::new("/")) } else { None };
|
||||
add_copilot_release_binaries_with_root(entry, release_base, sys_root);
|
||||
}
|
||||
|
||||
fn add_copilot_release_binaries_with_root(entry: &mut Entry, release_base: &str, sys_root: Option<&Path>) {
|
||||
let tag = format!("v{}", entry.version.trim_start_matches('v'));
|
||||
let base = format!("{}/{}", release_base.trim_end_matches('/'), tag);
|
||||
let sha256_url = format!("{base}/SHA256SUMS.txt");
|
||||
@@ -196,9 +201,12 @@ fn add_copilot_release_binaries(entry: &mut Entry, release_base: &str) {
|
||||
Some(p) => (p.args.clone(), p.env.clone()),
|
||||
None => (vec!["--acp".into()], BTreeMap::new()),
|
||||
};
|
||||
let linux = if cfg!(target_env = "musl") { "linuxmusl" } else { "linux" };
|
||||
let linux_arm = format!("copilot-{linux}-arm64.tar.gz");
|
||||
let linux_x64 = format!("copilot-{linux}-x64.tar.gz");
|
||||
let linux_arm = format!(
|
||||
"copilot-{}-arm64.tar.gz",
|
||||
sys_root.map_or("linux", |root| copilot_linux_variant_at(root, Arch::Arm64))
|
||||
);
|
||||
let linux_x64 =
|
||||
format!("copilot-{}-x64.tar.gz", sys_root.map_or("linux", |root| copilot_linux_variant_at(root, Arch::X64)));
|
||||
let targets = [
|
||||
("darwin-aarch64", "copilot-darwin-arm64.tar.gz", "./copilot"),
|
||||
("darwin-x86_64", "copilot-darwin-x64.tar.gz", "./copilot"),
|
||||
@@ -219,6 +227,22 @@ fn add_copilot_release_binaries(entry: &mut Entry, release_base: &str) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Picks `linux` (glibc) or `linuxmusl` from the host's runtime dynamic linker rather than
|
||||
/// `cfg!(target_env = "musl")`: `openidea-server` on Linux is built as static musl so it runs
|
||||
/// on every distro, while Copilot's Linux archives dynamically link glibc or musl.
|
||||
fn copilot_linux_variant_at(root: &Path, arch: Arch) -> &'static str {
|
||||
let (glibc_rel, musl_rel) = match arch {
|
||||
Arch::Arm64 => ("lib/ld-linux-aarch64.so.1", "lib/ld-musl-aarch64.so.1"),
|
||||
Arch::X64 => ("lib64/ld-linux-x86-64.so.2", "lib/ld-musl-x86_64.so.1"),
|
||||
};
|
||||
let glibc = root.join(glibc_rel);
|
||||
let has_musl_name = |p: PathBuf| p.file_name().is_some_and(|n| n.to_string_lossy().contains("musl"));
|
||||
let points_to_musl =
|
||||
fs::read_link(&glibc).is_ok_and(has_musl_name) || fs::canonicalize(&glibc).is_ok_and(has_musl_name);
|
||||
let has_glibc = glibc.exists() && !points_to_musl;
|
||||
if !has_glibc && root.join(musl_rel).exists() { "linuxmusl" } else { "linux" }
|
||||
}
|
||||
|
||||
fn safe_segment(s: &str) -> bool {
|
||||
!s.is_empty()
|
||||
&& !s.starts_with('.')
|
||||
@@ -443,7 +467,15 @@ fn write_atomic(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
|
||||
|
||||
/// Installs (or updates to) the registry's current version of `id`, streaming progress
|
||||
/// through `emit`, and points the agent file at it.
|
||||
pub fn install(paths: &RegistryPaths, id: &str, cancel: &CancellationToken, emit: Emit) -> IdeResult<()> {
|
||||
/// Installs agent `id`; an npm package retries against the public npm registry when the
|
||||
/// configured one misses it only with `public_npm_fallback`.
|
||||
pub fn install(
|
||||
paths: &RegistryPaths,
|
||||
id: &str,
|
||||
public_npm_fallback: bool,
|
||||
cancel: &CancellationToken,
|
||||
emit: Emit,
|
||||
) -> IdeResult<()> {
|
||||
let id = canonical_id(id);
|
||||
// The saved index is what the user picked from; fetch only when there is none.
|
||||
let text = match fs::read_to_string(&paths.cache_file) {
|
||||
@@ -455,9 +487,14 @@ pub fn install(paths: &RegistryPaths, id: &str, cancel: &CancellationToken, emit
|
||||
.iter()
|
||||
.find(|e| e.id == id)
|
||||
.ok_or_else(|| IdeError::not_found(format!("{id} is not in the ACP Registry")))?;
|
||||
install_entry(paths, entry, Platform::current(), &on_path, cancel, emit)
|
||||
let npm_installer =
|
||||
move |p: &Package, entry: &Entry, dir: &Path, platform, cancel: &CancellationToken, emit: Emit| {
|
||||
install_npm(p, entry, dir, platform, public_npm_fallback, cancel, emit)
|
||||
};
|
||||
install_entry_with(paths, entry, Platform::current(), &on_path, &npm_installer, cancel, emit)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn install_entry(
|
||||
paths: &RegistryPaths,
|
||||
entry: &Entry,
|
||||
@@ -466,7 +503,10 @@ fn install_entry(
|
||||
cancel: &CancellationToken,
|
||||
emit: Emit,
|
||||
) -> IdeResult<()> {
|
||||
install_entry_with(paths, entry, platform, on_path, &install_npm, cancel, emit)
|
||||
let npm_installer = |p: &Package, entry: &Entry, dir: &Path, platform, cancel: &CancellationToken, emit: Emit| {
|
||||
install_npm(p, entry, dir, platform, true, cancel, emit)
|
||||
};
|
||||
install_entry_with(paths, entry, platform, on_path, &npm_installer, cancel, emit)
|
||||
}
|
||||
|
||||
type NpmInstaller = dyn Fn(&Package, &Entry, &Path, Platform, &CancellationToken, Emit) -> IdeResult<PathBuf>;
|
||||
@@ -550,6 +590,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() }),
|
||||
};
|
||||
@@ -662,20 +703,23 @@ fn install_npm(
|
||||
entry: &Entry,
|
||||
dir: &Path,
|
||||
platform: Platform,
|
||||
public_fallback: bool,
|
||||
cancel: &CancellationToken,
|
||||
emit: Emit,
|
||||
) -> IdeResult<PathBuf> {
|
||||
let (name, _) = split_npm_spec(&p.package);
|
||||
let npm = which::which("npm").map_err(|_| IdeError::unavailable(format!("npm is required to install {name}")))?;
|
||||
install_npm_with(&npm, p, entry, dir, platform, cancel, emit)
|
||||
install_npm_with(&npm, p, entry, dir, platform, public_fallback, cancel, emit)
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn install_npm_with(
|
||||
npm: &Path,
|
||||
p: &Package,
|
||||
entry: &Entry,
|
||||
dir: &Path,
|
||||
platform: Platform,
|
||||
public_fallback: bool,
|
||||
cancel: &CancellationToken,
|
||||
emit: Emit,
|
||||
) -> IdeResult<PathBuf> {
|
||||
@@ -703,6 +747,7 @@ fn install_npm_with(
|
||||
},
|
||||
&specs,
|
||||
false,
|
||||
public_fallback,
|
||||
cancel,
|
||||
emit,
|
||||
)?;
|
||||
@@ -941,6 +986,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() }),
|
||||
};
|
||||
@@ -1002,7 +1048,7 @@ mod tests {
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn npm_registry_agent_retries_against_public_npmjs_on_mirror_miss() {
|
||||
fn npm_registry_agent_retries_against_public_npmjs_on_mirror_miss_unless_registries_are_configured_only() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let install_dir = dir.path().join("acme/1.2.0");
|
||||
fs::create_dir_all(&install_dir).unwrap();
|
||||
@@ -1041,8 +1087,8 @@ esac
|
||||
]}"#;
|
||||
let entry = parse(index).unwrap().remove(0);
|
||||
let pkg = entry.distribution.npx.as_ref().unwrap();
|
||||
let exe =
|
||||
install_npm_with(&npm, pkg, &entry, &install_dir, MAC_ARM, &CancellationToken::new(), &|_| {}).unwrap();
|
||||
let exe = install_npm_with(&npm, pkg, &entry, &install_dir, MAC_ARM, true, &CancellationToken::new(), &|_| {})
|
||||
.unwrap();
|
||||
let calls: Vec<String> = fs::read_to_string(&log).unwrap().lines().map(str::to_owned).collect();
|
||||
assert_eq!(calls.len(), 2, "{calls:?}");
|
||||
assert!(!calls[0].contains("--registry="), "{calls:?}");
|
||||
@@ -1050,6 +1096,15 @@ esac
|
||||
assert!(calls[1].contains("--@acme:registry=https://registry.npmjs.org/"), "{calls:?}");
|
||||
assert_eq!(exe, install_dir.join("node_modules/.bin/agent-acp"));
|
||||
assert!(exe.is_file());
|
||||
// Only the configured registries: the miss is the error, and npmjs is never asked.
|
||||
let only = dir.path().join("acme-only/1.2.0");
|
||||
fs::create_dir_all(&only).unwrap();
|
||||
let err =
|
||||
install_npm_with(&npm, pkg, &entry, &only, MAC_ARM, false, &CancellationToken::new(), &|_| {}).unwrap_err();
|
||||
let calls: Vec<String> = fs::read_to_string(&log).unwrap().lines().map(str::to_owned).collect();
|
||||
assert_eq!(calls.len(), 3, "{calls:?}");
|
||||
assert!(!calls[2].contains("--registry="), "{calls:?}");
|
||||
assert!(err.message.contains("notarget"), "{err:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1168,6 +1223,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() }),
|
||||
}
|
||||
@@ -1180,7 +1236,7 @@ esac
|
||||
write_atomic(&p.cache_file, index.as_bytes()).unwrap();
|
||||
let spec = provider::load(Some(&p.agents_dir), None).into_iter().find(|s| s.id == "copilot").unwrap();
|
||||
assert_eq!(spec.name, "GitHub Copilot");
|
||||
assert_eq!(spec.login_hint, "Run `copilot` in a terminal and sign in.");
|
||||
assert_eq!(spec.login_hint, "Run `copilot login` in a terminal.");
|
||||
assert_eq!(spec.source, AgentSource::Registry { version: "1.0.104".into(), update: None });
|
||||
|
||||
let mut providers = vec![provider::describe(&spec)];
|
||||
@@ -1272,4 +1328,96 @@ esac
|
||||
assert!(npm_bin.is_file());
|
||||
assert_eq!(CustomAgent::read(&p.agent_file("copilot")).unwrap().command, npm_bin.to_string_lossy());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selects_copilot_linux_archive_from_runtime_dynamic_linker() {
|
||||
let index = r#"{"agents":[
|
||||
{"id":"github-copilot-cli","name":"Copilot","version":"1.0.116",
|
||||
"distribution":{"npx":{"package":"@github/[email protected]","args":["--acp"]}}}
|
||||
]}"#;
|
||||
let archives_for = |root: &Path| -> (String, String) {
|
||||
let mut entry = parse(index).unwrap().remove(0);
|
||||
entry.distribution.binary.clear();
|
||||
add_copilot_release_binaries_with_root(&mut entry, "https://example.invalid/releases", Some(root));
|
||||
(
|
||||
entry.distribution.binary["linux-x86_64"].archive.clone(),
|
||||
entry.distribution.binary["linux-aarch64"].archive.clone(),
|
||||
)
|
||||
};
|
||||
let touch = |path: PathBuf| {
|
||||
fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
fs::write(path, b"").unwrap();
|
||||
};
|
||||
|
||||
// 1. Non-FHS root (neither loader present) defaults to glibc archives.
|
||||
let empty = tempfile::tempdir().unwrap();
|
||||
assert_eq!(
|
||||
archives_for(empty.path()),
|
||||
(
|
||||
"https://example.invalid/releases/v1.0.116/copilot-linux-x64.tar.gz".into(),
|
||||
"https://example.invalid/releases/v1.0.116/copilot-linux-arm64.tar.gz".into(),
|
||||
)
|
||||
);
|
||||
|
||||
// 2. Standard glibc host (and glibc host with musl-tools also installed) uses `copilot-linux-*`,
|
||||
// even when `openidea-server` itself is compiled for `*-unknown-linux-musl`.
|
||||
let glibc = tempfile::tempdir().unwrap();
|
||||
touch(glibc.path().join("lib64/ld-linux-x86-64.so.2"));
|
||||
touch(glibc.path().join("lib/ld-linux-aarch64.so.1"));
|
||||
assert_eq!(
|
||||
archives_for(glibc.path()),
|
||||
(
|
||||
"https://example.invalid/releases/v1.0.116/copilot-linux-x64.tar.gz".into(),
|
||||
"https://example.invalid/releases/v1.0.116/copilot-linux-arm64.tar.gz".into(),
|
||||
)
|
||||
);
|
||||
touch(glibc.path().join("lib/ld-musl-x86_64.so.1"));
|
||||
touch(glibc.path().join("lib/ld-musl-aarch64.so.1"));
|
||||
assert_eq!(
|
||||
archives_for(glibc.path()),
|
||||
(
|
||||
"https://example.invalid/releases/v1.0.116/copilot-linux-x64.tar.gz".into(),
|
||||
"https://example.invalid/releases/v1.0.116/copilot-linux-arm64.tar.gz".into(),
|
||||
)
|
||||
);
|
||||
|
||||
// 3. musl-only host (e.g. Alpine) uses `copilot-linuxmusl-*`.
|
||||
let musl = tempfile::tempdir().unwrap();
|
||||
touch(musl.path().join("lib/ld-musl-x86_64.so.1"));
|
||||
touch(musl.path().join("lib/ld-musl-aarch64.so.1"));
|
||||
assert_eq!(
|
||||
archives_for(musl.path()),
|
||||
(
|
||||
"https://example.invalid/releases/v1.0.116/copilot-linuxmusl-x64.tar.gz".into(),
|
||||
"https://example.invalid/releases/v1.0.116/copilot-linuxmusl-arm64.tar.gz".into(),
|
||||
)
|
||||
);
|
||||
|
||||
// 4. Alpine `libc6-compat` / `gcompat` symlinking `ld-linux` to `ld-musl` still picks `linuxmusl`.
|
||||
#[cfg(unix)]
|
||||
{
|
||||
fs::create_dir_all(musl.path().join("lib64")).unwrap();
|
||||
std::os::unix::fs::symlink("../lib/ld-musl-x86_64.so.1", musl.path().join("lib64/ld-linux-x86-64.so.2"))
|
||||
.unwrap();
|
||||
std::os::unix::fs::symlink("ld-musl-aarch64.so.1", musl.path().join("lib/ld-linux-aarch64.so.1")).unwrap();
|
||||
assert_eq!(
|
||||
archives_for(musl.path()),
|
||||
(
|
||||
"https://example.invalid/releases/v1.0.116/copilot-linuxmusl-x64.tar.gz".into(),
|
||||
"https://example.invalid/releases/v1.0.116/copilot-linuxmusl-arm64.tar.gz".into(),
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
let parsed = parse(index).unwrap().remove(0);
|
||||
let expected_x64 = format!("copilot-{}-x64.tar.gz", copilot_linux_variant_at(Path::new("/"), Arch::X64));
|
||||
assert!(
|
||||
parsed.distribution.binary["linux-x86_64"].archive.ends_with(&expected_x64),
|
||||
"unexpected linux-x86_64 archive: {}",
|
||||
parsed.distribution.binary["linux-x86_64"].archive
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -32,7 +32,7 @@ pub fn widens_access(params: &Value) -> bool {
|
||||
tool.and_then(|t| t.pointer("/rawInput/networkApprovalContext")).is_some_and(|c| !c.is_null())
|
||||
}
|
||||
|
||||
fn command_from_value(val: &Value) -> Option<String> {
|
||||
pub(crate) fn command_from_value(val: &Value) -> Option<String> {
|
||||
match val {
|
||||
Value::String(s) => {
|
||||
let trimmed = s.trim();
|
||||
|
||||
@@ -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)] {
|
||||
@@ -4172,6 +4369,7 @@ fn a_running_tools_output_is_sent_as_appends() {
|
||||
diffs: Vec::new(),
|
||||
started_ms: Some(1.0),
|
||||
ended_ms: None,
|
||||
command: None,
|
||||
};
|
||||
let running = |output| call(AgentToolStatus::Running, output);
|
||||
let event = |streamed: &mut Streamed, session: Session, i, entry: &AgentEntry| {
|
||||
@@ -5421,6 +5619,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 +5682,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 +5826,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 +5853,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();
|
||||
|
||||
@@ -91,6 +91,7 @@ impl Timeline {
|
||||
diffs: Vec::new(),
|
||||
started_ms: Some(crate::now_ms()),
|
||||
ended_ms: None,
|
||||
command: None,
|
||||
};
|
||||
let index = match self.tools.get(&id) {
|
||||
Some(&i) => {
|
||||
@@ -154,7 +155,7 @@ impl Timeline {
|
||||
}
|
||||
|
||||
fn merge_tool(&mut self, index: usize, update: &Value) {
|
||||
let AgentEntry::Tool { title, kind, status, locations: locs, output, images, diffs, ended_ms, .. } =
|
||||
let AgentEntry::Tool { title, kind, status, locations: locs, output, images, diffs, ended_ms, command, .. } =
|
||||
&mut self.entries[index]
|
||||
else {
|
||||
return;
|
||||
@@ -171,6 +172,11 @@ impl Timeline {
|
||||
*ended_ms = Some(crate::now_ms());
|
||||
}
|
||||
}
|
||||
if let Some(raw) = update.pointer("/rawInput/command").or_else(|| update.pointer("/rawInput/cmd"))
|
||||
&& let Some(cmd) = crate::security::command_from_value(raw)
|
||||
{
|
||||
*command = Some(crate::shell_script(&cmd).unwrap_or(cmd));
|
||||
}
|
||||
if update.get("locations").is_some_and(Value::is_array) {
|
||||
*locs = locations(update.get("locations"));
|
||||
}
|
||||
@@ -471,6 +477,34 @@ mod tests {
|
||||
assert!(matches!(&t.entries[0], AgentEntry::Question { chosen: Some(answer), .. } if answer == "One"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_execute_call_keeps_the_command_from_its_structured_input() {
|
||||
let mut t = Timeline::default();
|
||||
let command = |t: &Timeline, i: usize| match &t.entries[i] {
|
||||
AgentEntry::Tool { command, .. } => command.clone(),
|
||||
_ => panic!(),
|
||||
};
|
||||
t.apply(&json!({"sessionUpdate": "tool_call", "toolCallId": "a", "title": "Run command", "kind": "execute",
|
||||
"rawInput": {"command": "python hello_world.py"}}));
|
||||
assert_eq!(command(&t, 0).as_deref(), Some("python hello_world.py"));
|
||||
// An argv array whose shell wraps the script, sent with a later update.
|
||||
t.apply(&json!({"sessionUpdate": "tool_call", "toolCallId": "b", "title": "Run command", "kind": "execute"}));
|
||||
assert_eq!(command(&t, 1), None);
|
||||
t.apply(&json!({"sessionUpdate": "tool_call_update", "toolCallId": "b",
|
||||
"rawInput": {"cmd": ["bash", "-lc", "cargo test -p ide-agent"]}}));
|
||||
assert_eq!(command(&t, 1).as_deref(), Some("cargo test -p ide-agent"));
|
||||
// One shell line, unwrapped as the permission card does.
|
||||
t.apply(&json!({"sessionUpdate": "tool_call", "toolCallId": "c", "kind": "execute",
|
||||
"rawInput": {"command": "/bin/zsh -lc 'node hello.js'"}}));
|
||||
assert_eq!(command(&t, 2).as_deref(), Some("node hello.js"));
|
||||
// A later update without one keeps it; tasks saved before the field load without it.
|
||||
t.apply(&json!({"sessionUpdate": "tool_call_update", "toolCallId": "c", "status": "completed"}));
|
||||
assert_eq!(command(&t, 2).as_deref(), Some("node hello.js"));
|
||||
let mut old = serde_json::to_value(&t.entries[2]).unwrap();
|
||||
old.as_object_mut().unwrap().remove("command");
|
||||
assert!(matches!(serde_json::from_value(old).unwrap(), AgentEntry::Tool { command: None, .. }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tool_images_survive_updates_text_truncation_and_serialization() {
|
||||
use base64::Engine;
|
||||
|
||||
@@ -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};
|
||||
@@ -811,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 };
|
||||
@@ -818,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
|
||||
|
||||
@@ -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,451 @@
|
||||
//! 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"))],
|
||||
})
|
||||
);
|
||||
// Chained joins: the configurations name native paths, `packages/a` would mix separators on Windows.
|
||||
let a = root.join("packages").join("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").join("b");
|
||||
assert_eq!(
|
||||
copy(2),
|
||||
json!({
|
||||
"extends": path(&b.join("tsconfig.json")),
|
||||
"compilerOptions": {
|
||||
"outDir": path(&scratch.join("2")), "tsBuildInfoFile": s("2.tsbuildinfo"),
|
||||
"declarationDir": path(&scratch.join("2")), "outFile": path(&scratch.join("2").join("out.js")),
|
||||
},
|
||||
"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);
|
||||
}
|
||||
}
|
||||
@@ -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.
|
||||
@@ -1039,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) {
|
||||
@@ -1061,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);
|
||||
}
|
||||
|
||||
@@ -91,12 +91,14 @@ fn plan(root: &Path, model: &BuildModel, cancel: &CancellationToken) -> IdeResul
|
||||
|
||||
/// Run the project's configured wrapper/settings/JDK and lifecycle, with an output
|
||||
/// redirector loaded before Maven calculates its lifecycle execution plans.
|
||||
/// Builds the Kotlin libraries; `on_progress` gets Maven's progress (message, fraction 0..1).
|
||||
pub fn build(
|
||||
root: &Path,
|
||||
model: &BuildModel,
|
||||
bundle: &Path,
|
||||
generation: &Path,
|
||||
cancel: &CancellationToken,
|
||||
on_progress: &(dyn Fn(&str, Option<f32>) + Sync),
|
||||
) -> IdeResult<Outcome> {
|
||||
std::fs::create_dir_all(generation)?;
|
||||
let mut plan = plan(root, model, cancel)?;
|
||||
@@ -124,10 +126,10 @@ pub fn build(
|
||||
for step in &plan.steps {
|
||||
let mut reactor = plan.clone();
|
||||
reactor.steps = vec![step.clone()];
|
||||
let result = compile::run(root, &reactor, cancel, &|event| {
|
||||
if let BuildEvent::Output { text, .. } = event {
|
||||
tracing::debug!("kotlin bridge: {}", text.trim_end());
|
||||
}
|
||||
let result = compile::run(root, &reactor, cancel, &|event| match event {
|
||||
BuildEvent::Output { text, .. } => tracing::debug!("kotlin bridge: {}", text.trim_end()),
|
||||
BuildEvent::Progress { message, fraction } => on_progress(&message, fraction),
|
||||
_ => {}
|
||||
})?;
|
||||
messages.extend(result.messages);
|
||||
}
|
||||
@@ -456,6 +458,7 @@ mod tests {
|
||||
Path::new("unused.jar"),
|
||||
&directory.path().join("private"),
|
||||
&CancellationToken::new(),
|
||||
&|_, _| {},
|
||||
)
|
||||
.err()
|
||||
.unwrap();
|
||||
|
||||
@@ -486,6 +486,38 @@ pub struct LanguageCodeStyle {
|
||||
/// SQL › Case › Identifiers (unquoted names): `upper` | `lower` | `keep`.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub identifier_case: Option<String>,
|
||||
/// Java: organize imports switches to a wildcard import once this many
|
||||
/// classes of one package are used (jdtls `starThreshold`; IDEA's default
|
||||
/// 5; unset keeps the language server's default).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub class_count_to_use_import_with_star: Option<u32>,
|
||||
/// Java: organize imports switches to a wildcard static import once this
|
||||
/// many statically imported names are used (jdtls `staticStarThreshold`;
|
||||
/// IDEA's default 3; unset keeps the language server's default).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub names_count_to_use_static_import_with_star: Option<u32>,
|
||||
/// 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>,
|
||||
/// JavaScript / TypeScript › Imports › Import paths:
|
||||
/// `shortest` | `relative` | `non-relative` | `project-relative`.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub import_module_specifier: Option<String>,
|
||||
/// JavaScript / TypeScript › Imports › Import path ending: `auto` | `minimal` | `index` | `js`.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub import_module_specifier_ending: Option<String>,
|
||||
/// JavaScript / TypeScript › Imports › Do not auto-import from (globs).
|
||||
#[serde(skip_serializing_if = "Vec::is_empty")]
|
||||
pub auto_import_file_exclude_patterns: Vec<String>,
|
||||
/// JavaScript / TypeScript › Imports › Do not auto-import specifiers matching (regexes).
|
||||
#[serde(skip_serializing_if = "Vec::is_empty")]
|
||||
pub auto_import_specifier_exclude_regexes: Vec<String>,
|
||||
}
|
||||
|
||||
/// Editor › Code Style (General tab + per-language overrides).
|
||||
@@ -543,6 +575,25 @@ pub struct EncodingSettings {
|
||||
pub native_to_ascii: bool,
|
||||
/// Create UTF-8 files: `never` (no BOM) | `always` (with BOM) | `windows` (with BOM on Windows).
|
||||
pub utf8_bom: String,
|
||||
/// Encoding (WHATWG label) of a file or of the files in a folder, by its path
|
||||
/// relative to the project with `/` separators. The status bar's choice is kept here.
|
||||
#[serde(deserialize_with = "labels")]
|
||||
#[specta(type = BTreeMap<String, String>)]
|
||||
pub mappings: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
/// A hand-edited entry that is not a label is left out, rather than failing the whole settings file.
|
||||
fn labels<'de, D: serde::Deserializer<'de>>(d: D) -> Result<BTreeMap<String, String>, D::Error> {
|
||||
let serde_json::Value::Object(entries) = serde_json::Value::deserialize(d)? else {
|
||||
return Ok(BTreeMap::new());
|
||||
};
|
||||
Ok(entries
|
||||
.into_iter()
|
||||
.filter_map(|(path, label)| match label {
|
||||
serde_json::Value::String(label) => Some((path, label)),
|
||||
_ => None,
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
impl Default for EncodingSettings {
|
||||
@@ -553,10 +604,30 @@ impl Default for EncodingSettings {
|
||||
properties: "iso-8859-1".into(),
|
||||
native_to_ascii: false,
|
||||
utf8_bom: "never".into(),
|
||||
mappings: BTreeMap::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod encoding_mappings_tests {
|
||||
use super::EncodingSettings;
|
||||
|
||||
#[test]
|
||||
fn encoding_mappings_keep_the_entries_that_are_labels() {
|
||||
let json = serde_json::json!({
|
||||
"project": "gbk",
|
||||
"mappings": { "src/main/java": "iso-8859-15", "count": 5, "nested": { "a": "utf-8" } },
|
||||
});
|
||||
let settings: EncodingSettings = serde_json::from_value(json).unwrap();
|
||||
assert_eq!(settings.project, "gbk");
|
||||
assert_eq!(settings.mappings.into_iter().collect::<Vec<_>>(), [("src/main/java".into(), "iso-8859-15".into())]);
|
||||
let not_a_table: EncodingSettings = serde_json::from_value(serde_json::json!({ "mappings": 5 })).unwrap();
|
||||
assert!(not_a_table.mappings.is_empty());
|
||||
assert!(EncodingSettings::default().mappings.is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod auto_import_tests {
|
||||
use super::{AutoImportSettings, ImportsOnPaste};
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -13,13 +13,34 @@ use std::sync::Arc;
|
||||
|
||||
/// What a built-in MCP tool asks the project window for. `AgentRun` runs `command` (a shell
|
||||
/// line) in the Run tool window's agent tab `name`, on pipes, answered once the process
|
||||
/// started or failed to.
|
||||
/// started or failed to. `RunConfiguration` starts a run configuration (a serialized
|
||||
/// `RunConfig`, its before launch tasks already done) in the Run tool window as the user's
|
||||
/// Run would, answered the same way.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(tag = "type", rename_all = "camelCase", rename_all_fields = "camelCase")]
|
||||
pub enum McpUiRequest {
|
||||
Confirm { client: String, tool: String, subject: String, project: String, detail: Option<String> },
|
||||
OpenFile { path: crate::IpcPath, line: Option<u32>, column: Option<u32> },
|
||||
AgentRun { name: String, command: String, cwd: crate::IpcPath, env: BTreeMap<String, String> },
|
||||
Confirm {
|
||||
client: String,
|
||||
tool: String,
|
||||
subject: String,
|
||||
project: String,
|
||||
detail: Option<String>,
|
||||
},
|
||||
OpenFile {
|
||||
path: crate::IpcPath,
|
||||
line: Option<u32>,
|
||||
column: Option<u32>,
|
||||
},
|
||||
AgentRun {
|
||||
name: String,
|
||||
command: String,
|
||||
cwd: crate::IpcPath,
|
||||
env: BTreeMap<String, String>,
|
||||
},
|
||||
RunConfiguration {
|
||||
#[specta(type = specta_typescript::Unknown)]
|
||||
config: serde_json::Value,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
|
||||
@@ -14,10 +14,33 @@ pub type Changes = Arc<Vec<(OsString, Option<OsString>)>>;
|
||||
|
||||
struct Entry {
|
||||
root: PathBuf,
|
||||
direnv: Vec<(OsString, Option<OsString>)>,
|
||||
github_token: Option<OsString>,
|
||||
changes: Changes,
|
||||
loading: bool,
|
||||
}
|
||||
|
||||
impl Entry {
|
||||
fn new(root: PathBuf) -> Self {
|
||||
Self { root, direnv: Vec::new(), github_token: None, changes: Changes::default(), loading: false }
|
||||
}
|
||||
|
||||
fn rebuild(&mut self) {
|
||||
let mut combined = Vec::with_capacity(self.direnv.len() + usize::from(self.github_token.is_some()));
|
||||
if let Some(token) = &self.github_token {
|
||||
combined.push(("GH_TOKEN".into(), Some(token.clone())));
|
||||
}
|
||||
// `.envrc` entries override the project GitHub token when both define `GH_TOKEN`.
|
||||
combined.retain(|(k, _)| !self.direnv.iter().any(|(dk, _)| dk == k));
|
||||
combined.extend(self.direnv.iter().cloned());
|
||||
self.changes = Arc::new(combined);
|
||||
}
|
||||
|
||||
fn is_idle_empty(&self) -> bool {
|
||||
!self.loading && self.direnv.is_empty() && self.github_token.is_none()
|
||||
}
|
||||
}
|
||||
|
||||
static ENTRIES: Mutex<Vec<Entry>> = Mutex::new(Vec::new());
|
||||
static SETTLED: Condvar = Condvar::new();
|
||||
|
||||
@@ -31,35 +54,103 @@ pub fn begin_loading(root: &Path) {
|
||||
let mut entries = entries();
|
||||
match entries.iter_mut().find(|e| e.root == root) {
|
||||
Some(entry) => entry.loading = true,
|
||||
None => entries.push(Entry { root: root.to_path_buf(), changes: Changes::default(), loading: true }),
|
||||
None => {
|
||||
let mut entry = Entry::new(root.to_path_buf());
|
||||
entry.loading = true;
|
||||
entries.push(entry);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What children started in `root` (or below it) get on top of the IDE's own environment
|
||||
/// (`None`: removed). Ends a [`begin_loading`].
|
||||
/// What children started in `root` (or below it) get from direnv on top of the IDE's own
|
||||
/// environment (`None`: removed). Ends a [`begin_loading`].
|
||||
pub fn set(root: &Path, changes: Vec<(OsString, Option<OsString>)>) {
|
||||
let mut entries = entries();
|
||||
let changes = Arc::new(changes);
|
||||
match entries.iter_mut().find(|e| e.root == root) {
|
||||
Some(entry) => {
|
||||
entry.changes = changes;
|
||||
match entries.iter_mut().position(|e| e.root == root) {
|
||||
Some(idx) => {
|
||||
let entry = &mut entries[idx];
|
||||
entry.direnv = changes;
|
||||
entry.loading = false;
|
||||
entry.rebuild();
|
||||
if entry.is_idle_empty() {
|
||||
entries.remove(idx);
|
||||
}
|
||||
}
|
||||
None => entries.push(Entry { root: root.to_path_buf(), changes, loading: false }),
|
||||
None if !changes.is_empty() => {
|
||||
let mut entry = Entry::new(root.to_path_buf());
|
||||
entry.direnv = changes;
|
||||
entry.rebuild();
|
||||
entries.push(entry);
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
SETTLED.notify_all();
|
||||
}
|
||||
|
||||
/// Ends a [`begin_loading`] that read nothing new (an error): the last environment stays.
|
||||
pub fn settle(root: &Path) {
|
||||
if let Some(entry) = entries().iter_mut().find(|e| e.root == root) {
|
||||
entry.loading = false;
|
||||
let mut entries = entries();
|
||||
if let Some(idx) = entries.iter().position(|e| e.root == root) {
|
||||
entries[idx].loading = false;
|
||||
if entries[idx].is_idle_empty() {
|
||||
entries.remove(idx);
|
||||
}
|
||||
}
|
||||
SETTLED.notify_all();
|
||||
}
|
||||
|
||||
/// `root` has no environment of its own any more (closed, or not trusted).
|
||||
/// `root` has no direnv environment of its own any more (no `.envrc`, closed, or not trusted).
|
||||
/// Preserves any project-scoped GitHub token until [`remove_all`] or [`set_github_token`].
|
||||
pub fn remove(root: &Path) {
|
||||
let mut entries = entries();
|
||||
if let Some(idx) = entries.iter().position(|e| e.root == root) {
|
||||
let entry = &mut entries[idx];
|
||||
entry.direnv.clear();
|
||||
entry.loading = false;
|
||||
entry.rebuild();
|
||||
if entry.is_idle_empty() {
|
||||
entries.remove(idx);
|
||||
}
|
||||
}
|
||||
SETTLED.notify_all();
|
||||
}
|
||||
|
||||
/// Sets or clears the project-scoped `GH_TOKEN` injected for children started in `root`
|
||||
/// (unless overridden by `root`'s direnv `.envrc`). Returns whether the effective token changed.
|
||||
pub fn set_github_token(root: &Path, token: Option<OsString>) -> bool {
|
||||
let token = token.filter(|t| !t.is_empty());
|
||||
let mut entries = entries();
|
||||
match entries.iter().position(|e| e.root == root) {
|
||||
Some(idx) => {
|
||||
if entries[idx].github_token == token {
|
||||
return false;
|
||||
}
|
||||
let entry = &mut entries[idx];
|
||||
entry.github_token = token;
|
||||
entry.rebuild();
|
||||
if entry.is_idle_empty() {
|
||||
entries.remove(idx);
|
||||
}
|
||||
true
|
||||
}
|
||||
None => {
|
||||
let Some(token) = token else { return false };
|
||||
let mut entry = Entry::new(root.to_path_buf());
|
||||
entry.github_token = Some(token);
|
||||
entry.rebuild();
|
||||
entries.push(entry);
|
||||
true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The project-scoped `GH_TOKEN` configured for the innermost project holding `dir`, if any.
|
||||
pub fn github_token(dir: &Path) -> Option<OsString> {
|
||||
find(&entries(), dir).and_then(|e| e.github_token.clone())
|
||||
}
|
||||
|
||||
/// Removes both direnv and project GitHub token entries for `root` (project closed or untrusted).
|
||||
pub fn remove_all(root: &Path) {
|
||||
entries().retain(|e| e.root != root);
|
||||
SETTLED.notify_all();
|
||||
}
|
||||
@@ -135,4 +226,26 @@ mod tests {
|
||||
assert_eq!(*for_dir(root), [change("NEW", Some("2"))]);
|
||||
remove(root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn github_token_survives_direnv_absence_and_yields_to_explicit_envrc_override() {
|
||||
let root = Path::new("/openidea-test-env/gh-project");
|
||||
let worktrees = Path::new("/openidea-test-env/gh-project.worktrees");
|
||||
assert!(set_github_token(root, Some("gho_work".into())));
|
||||
assert!(!set_github_token(root, Some("gho_work".into())), "idempotent");
|
||||
assert!(set_github_token(worktrees, Some("gho_work".into())));
|
||||
remove(root); // no `.envrc` in `root`
|
||||
assert_eq!(*for_dir(&root.join("src")), [change("GH_TOKEN", Some("gho_work"))]);
|
||||
assert_eq!(*for_dir(&worktrees.join("task-1")), [change("GH_TOKEN", Some("gho_work"))]);
|
||||
assert_eq!(github_token(&worktrees.join("task-1")), Some("gho_work".into()));
|
||||
|
||||
// An explicit `.envrc` GH_TOKEN overrides the project GitHub account token.
|
||||
set(root, vec![change("GH_TOKEN", Some("gho_from_envrc")), change("FOO", Some("bar"))]);
|
||||
assert_eq!(*for_dir(root), [change("GH_TOKEN", Some("gho_from_envrc")), change("FOO", Some("bar"))]);
|
||||
|
||||
remove_all(root);
|
||||
remove_all(worktrees);
|
||||
assert!(for_dir(root).is_empty());
|
||||
assert!(for_dir(worktrees).is_empty());
|
||||
}
|
||||
}
|
||||
@@ -99,6 +99,20 @@ pub struct AgentSettings {
|
||||
pub smooth_text: bool,
|
||||
/// Conversations and the composer expand to the full width of the pane instead of staying in a centred column.
|
||||
pub fit_window_width: bool,
|
||||
/// Chat text follows the interface font (Appearance › Use custom font).
|
||||
pub chat_use_ui_font: bool,
|
||||
/// Chat text family when it does not follow the interface font.
|
||||
pub chat_font_family: String,
|
||||
/// Covers characters the chat font lacks.
|
||||
pub chat_font_fallback: String,
|
||||
pub chat_font_size: u32,
|
||||
/// Code in chat follows the built-in code font.
|
||||
pub code_use_default_font: bool,
|
||||
/// Code family when it does not follow the built-in code font.
|
||||
pub code_font_family: String,
|
||||
/// Covers characters the code font lacks.
|
||||
pub code_font_fallback: String,
|
||||
pub code_font_size: u32,
|
||||
#[serde(deserialize_with = "or_default")]
|
||||
#[specta(type = ThinkingDisplay)]
|
||||
pub thinking: ThinkingDisplay,
|
||||
@@ -145,6 +159,14 @@ impl Default for AgentSettings {
|
||||
show_cost: false,
|
||||
smooth_text: true,
|
||||
fit_window_width: false,
|
||||
chat_use_ui_font: true,
|
||||
chat_font_family: "Inter".into(),
|
||||
chat_font_fallback: String::new(),
|
||||
chat_font_size: 13,
|
||||
code_use_default_font: true,
|
||||
code_font_family: "JetBrains Mono".into(),
|
||||
code_font_fallback: String::new(),
|
||||
code_font_size: 13,
|
||||
thinking: ThinkingDisplay::Auto,
|
||||
tool_calls: ToolCallDisplay::Grouped,
|
||||
expand_tool_output: false,
|
||||
@@ -432,6 +454,12 @@ pub struct ToolDownloadSettings {
|
||||
/// commas or whitespace and tried in order before the official host; empty keeps every
|
||||
/// download on its official host.
|
||||
pub github_mirror: String,
|
||||
/// Package registries only as configured (a company Nexus or Artifactory): npm and pnpm
|
||||
/// installs and update checks never retry against the public npm registry, and the IDE
|
||||
/// fetches nothing from public package registries itself (the JUnit Platform launcher from
|
||||
/// Maven Central, dependency version completion from Maven Central, npm, PyPI and
|
||||
/// crates.io). Off by default.
|
||||
pub configured_registries_only: bool,
|
||||
}
|
||||
|
||||
/// Absent profiles retain automatic discovery for existing projects.
|
||||
@@ -1212,6 +1240,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,
|
||||
@@ -1238,6 +1268,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()
|
||||
@@ -1315,6 +1346,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,
|
||||
}
|
||||
@@ -1328,6 +1360,7 @@ pub enum ExternalFormatter {
|
||||
Prettier,
|
||||
Oxfmt,
|
||||
Biome,
|
||||
Dprint,
|
||||
Ruff,
|
||||
Black,
|
||||
}
|
||||
@@ -1339,6 +1372,7 @@ impl ExternalFormatter {
|
||||
Self::Prettier => "prettier",
|
||||
Self::Oxfmt => "oxfmt",
|
||||
Self::Biome => "biome",
|
||||
Self::Dprint => "dprint",
|
||||
Self::Ruff => "ruff",
|
||||
Self::Black => "black",
|
||||
}
|
||||
@@ -1349,11 +1383,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,
|
||||
@@ -1414,6 +1448,9 @@ pub struct PythonSettings {
|
||||
/// Folders the user added to an interpreter's `sys.path` (All Interpreters › Show Paths),
|
||||
/// by interpreter executable; absolute or `~/`.
|
||||
pub interpreter_paths: BTreeMap<String, Vec<String>>,
|
||||
/// Default test runner (Settings › Python › Testing): `auto` (pytest when the project uses
|
||||
/// it, else unittest), `pytest` or `unittest`.
|
||||
pub test_runner: String,
|
||||
}
|
||||
|
||||
impl Default for PythonSettings {
|
||||
@@ -1426,6 +1463,7 @@ impl Default for PythonSettings {
|
||||
hide_other_project_interpreters: false,
|
||||
show_interpreter_paths: true,
|
||||
interpreter_paths: BTreeMap::new(),
|
||||
test_runner: "auto".into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1724,11 +1762,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 }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -73,6 +73,38 @@ pub fn find_command(command: &str, search: &OsStr, root: &Path) -> Option<PathBu
|
||||
dirs.into_iter().find_map(|dir| names.iter().map(|name| dir.join(name)).find(|p| is_executable(p)))
|
||||
}
|
||||
|
||||
const GH_FALLBACK_PATHS: &[&str] = if cfg!(windows) {
|
||||
&[r"C:\Program Files\GitHub CLI\gh.exe"]
|
||||
} else {
|
||||
&["/opt/homebrew/bin/gh", "/usr/local/bin/gh", "/usr/bin/gh", "/snap/bin/gh"]
|
||||
};
|
||||
|
||||
/// Locates `gh` across `OPENIDEA_GH`, [`search_path`] (which includes IDE-managed tools
|
||||
/// only when installed, then the user's `PATH`), and standard OS install locations.
|
||||
pub fn find_gh_executable() -> Option<PathBuf> {
|
||||
let explicit = std::env::var_os("OPENIDEA_GH").map(PathBuf::from);
|
||||
find_gh_in(explicit.as_deref(), &search_path(), GH_FALLBACK_PATHS)
|
||||
}
|
||||
|
||||
/// Locates a pre-installed `gh` outside [`search_path`] (`OPENIDEA_GH`, Windows Program Files,
|
||||
/// Linux Snap) so tool detection reports it as available without prompting for a duplicate install.
|
||||
pub fn find_gh_outside_search_path() -> Option<PathBuf> {
|
||||
if let Some(explicit) = std::env::var_os("OPENIDEA_GH").map(PathBuf::from).filter(|p| is_executable(p)) {
|
||||
return Some(explicit);
|
||||
}
|
||||
GH_FALLBACK_PATHS.iter().map(PathBuf::from).find(|p| is_executable(p))
|
||||
}
|
||||
|
||||
pub fn find_gh_in(explicit: Option<&Path>, search: &OsStr, fallbacks: &[&str]) -> Option<PathBuf> {
|
||||
if let Some(explicit) = explicit.filter(|p| is_executable(p)) {
|
||||
return Some(explicit.to_path_buf());
|
||||
}
|
||||
if let Some(found) = find_command("gh", search, Path::new("")) {
|
||||
return Some(found);
|
||||
}
|
||||
fallbacks.iter().map(PathBuf::from).find(|p| is_executable(p))
|
||||
}
|
||||
|
||||
fn is_executable(path: &Path) -> bool {
|
||||
let Ok(metadata) = path.metadata() else { return false };
|
||||
#[cfg(unix)]
|
||||
|
||||
@@ -25,6 +25,17 @@ pub struct VcsSettings {
|
||||
pub issue_navigation: Vec<IssueLink>,
|
||||
/// Directory Mappings: repository roots added to or excluded from the detected ones.
|
||||
pub mappings: VcsMappings,
|
||||
/// Settings › Version Control › GitHub: per-project GitHub CLI account selection.
|
||||
pub github: GithubSettings,
|
||||
}
|
||||
|
||||
/// Settings › Version Control › GitHub (`vcs.github`).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct GithubSettings {
|
||||
/// GitHub CLI (`gh`) account login on `github.com` explicitly chosen for this project.
|
||||
/// Empty means automatic (`gh`'s own active account, with no `GH_TOKEN` injected).
|
||||
pub account: String,
|
||||
}
|
||||
|
||||
/// Directory Mappings on top of repository detection. Paths are relative to the project
|
||||
@@ -68,6 +79,7 @@ impl Default for VcsSettings {
|
||||
shelf: ShelfSettings::default(),
|
||||
issue_navigation: Vec::new(),
|
||||
mappings: VcsMappings::default(),
|
||||
github: GithubSettings::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "ide-coverage"
|
||||
description = "Run with Coverage: coverage-tool launch plans (cargo-llvm-cov, vitest / jest / c8, coverage.py, go test, JaCoCo) and report parsers (lcov, Go cover profiles, JaCoCo XML)"
|
||||
description = "Run with Coverage: coverage-tool launch plans (cargo-llvm-cov, vitest / jest / c8, coverage.py, go test, JaCoCo) and report parsers (lcov, Go cover profiles, JaCoCo and Cobertura XML, SimpleCov, coverage.py data)"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
//! Cobertura XML reports (`coverage xml` of coverage.py, and many other tools):
|
||||
//!
|
||||
//! ```xml
|
||||
//! <coverage>
|
||||
//! <sources><source>/home/runner/work/app/app</source></sources>
|
||||
//! <packages><package name="calc"><classes>
|
||||
//! <class filename="src/calc/__init__.py">
|
||||
//! <methods/>
|
||||
//! <lines>
|
||||
//! <line number="2" hits="1" branch="true" condition-coverage="50% (1/2)"/>
|
||||
//! ```
|
||||
//!
|
||||
//! A relative `filename` belongs to the first `<source>` it exists under, else to the
|
||||
//! first `<source>` (whose path may be another machine's; the importer relocates it).
|
||||
//! Lines repeated under `<methods>` are skipped so their hits don't count twice.
|
||||
|
||||
use crate::Accumulator;
|
||||
use quick_xml::events::{BytesStart, Event};
|
||||
use quick_xml::{Reader, XmlVersion};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
fn attr(e: &BytesStart, name: &str) -> Option<String> {
|
||||
e.attributes()
|
||||
.flatten()
|
||||
.find(|a| a.key.as_ref() == name)
|
||||
.and_then(|a| a.normalized_value(XmlVersion::Implicit1_0).ok())
|
||||
.map(Into::into)
|
||||
}
|
||||
|
||||
/// `"50% (1/2)"` → `(1, 2)`.
|
||||
fn conditions(text: &str) -> Option<(u32, u32)> {
|
||||
let (_, rest) = text.split_once('(')?;
|
||||
let (covered, total) = rest.trim_end_matches(')').split_once('/')?;
|
||||
Some((covered.trim().parse().ok()?, total.trim().parse().ok()?))
|
||||
}
|
||||
|
||||
/// `sources` pairs each `<source>` with whether it exists here (asked once: another
|
||||
/// machine's `/home/…` is slow to look up on macOS).
|
||||
fn resolve(filename: &str, sources: &[(PathBuf, bool)], base: &Path) -> PathBuf {
|
||||
let p = Path::new(filename);
|
||||
if p.has_root() {
|
||||
return p.to_path_buf();
|
||||
}
|
||||
sources
|
||||
.iter()
|
||||
.filter(|(_, here)| *here)
|
||||
.map(|(s, _)| s.join(p))
|
||||
.find(|c| c.is_file())
|
||||
.unwrap_or_else(|| sources.first().map_or_else(|| base.join(p), |(s, _)| s.join(p)))
|
||||
}
|
||||
|
||||
/// Relative sources (and filenames without sources) resolve against `base`.
|
||||
pub(crate) fn parse(xml: &str, base: &Path) -> Result<Accumulator, quick_xml::Error> {
|
||||
let mut reader = Reader::from_str(xml);
|
||||
let mut acc = Accumulator::default();
|
||||
let mut sources: Vec<(PathBuf, bool)> = Vec::new();
|
||||
let mut source: Option<String> = None;
|
||||
let mut file: Option<PathBuf> = None;
|
||||
let mut in_methods = false;
|
||||
loop {
|
||||
match reader.read_event()? {
|
||||
Event::Start(e) if e.name().as_ref() == "methods" => in_methods = true,
|
||||
Event::Start(e) | Event::Empty(e) => match e.name().as_ref() {
|
||||
"source" => source = Some(String::new()),
|
||||
"class" => {
|
||||
let path = resolve(&attr(&e, "filename").unwrap_or_default(), &sources, base);
|
||||
acc.file(&path);
|
||||
file = Some(path);
|
||||
}
|
||||
"line" if !in_methods => {
|
||||
let Some(path) = &file else { continue };
|
||||
let Some(number) = attr(&e, "number").and_then(|n| n.parse::<u32>().ok()) else { continue };
|
||||
let line = number.saturating_sub(1);
|
||||
acc.line(path, line, attr(&e, "hits").and_then(|h| h.parse().ok()).unwrap_or(0));
|
||||
if attr(&e, "branch").as_deref() == Some("true")
|
||||
&& let Some((covered, total)) = attr(&e, "condition-coverage").as_deref().and_then(conditions)
|
||||
{
|
||||
acc.has_branches = true;
|
||||
for i in 0..total {
|
||||
acc.branch(path, line, i.to_string(), i < covered);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
},
|
||||
Event::Text(t) => {
|
||||
if let Some(s) = &mut source {
|
||||
s.push_str(t.as_ref());
|
||||
}
|
||||
}
|
||||
Event::GeneralRef(r) => {
|
||||
if let Some(s) = &mut source {
|
||||
s.push('&');
|
||||
s.push_str(r.as_ref());
|
||||
s.push(';');
|
||||
}
|
||||
}
|
||||
Event::End(e) => match e.name().as_ref() {
|
||||
"source" => {
|
||||
let raw = source.take().unwrap_or_default();
|
||||
let text = quick_xml::escape::unescape(raw.trim()).map(|t| t.into_owned()).unwrap_or(raw);
|
||||
if !text.is_empty() {
|
||||
let path = Path::new(&text);
|
||||
// Joining a drive-less foreign root on Windows would add the checkout's drive.
|
||||
let dir = if path.has_root() { path.to_path_buf() } else { base.join(path) };
|
||||
let here = dir.is_dir();
|
||||
sources.push((dir, here));
|
||||
}
|
||||
}
|
||||
"methods" => in_methods = false,
|
||||
"class" => file = None,
|
||||
_ => {}
|
||||
},
|
||||
Event::Eof => break,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Ok(acc)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn reads_lines_branches_and_skips_method_lines() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let second = tmp.path().join("b&c");
|
||||
std::fs::create_dir_all(&second).unwrap();
|
||||
std::fs::write(second.join("m.py"), "").unwrap();
|
||||
let xml = format!(
|
||||
r#"<?xml version="1.0" ?>
|
||||
<!DOCTYPE coverage SYSTEM "http://cobertura.sourceforge.net/xml/coverage-04.dtd">
|
||||
<coverage><sources><source>/elsewhere/a</source><source>{}</source></sources>
|
||||
<packages><package name="p"><classes>
|
||||
<class name="m" filename="m.py">
|
||||
<methods><method name="f"><lines><line number="2" hits="5"/></lines></method></methods>
|
||||
<lines>
|
||||
<line number="1" hits="1"/>
|
||||
<line number="2" hits="5" branch="true" condition-coverage="50% (1/2)" missing-branches="3"/>
|
||||
<line number="3" hits="0"/>
|
||||
</lines>
|
||||
</class>
|
||||
<class name="n" filename="n.py"><lines><line number="1" hits="0"/></lines></class>
|
||||
<class name="abs" filename="/abs/x.py"><lines><line number="7" hits="2"/></lines></class>
|
||||
</classes></package></packages></coverage>"#,
|
||||
tmp.path().join("b&c").display()
|
||||
);
|
||||
let suite = parse(&xml, tmp.path()).unwrap().finish("Cobertura");
|
||||
assert!(suite.has_branches);
|
||||
assert_eq!(suite.files.len(), 3);
|
||||
let file = |path: &Path| suite.files.iter().find(|f| f.path.as_ref() as &Path == path).unwrap();
|
||||
// `m.py` exists under the second source; `n.py` falls back to the first.
|
||||
let m = file(&second.join("m.py"));
|
||||
assert_eq!(file(Path::new("/elsewhere/a/n.py")).lines[0].hits, 0);
|
||||
assert_eq!(
|
||||
m.lines.iter().map(|l| (l.line, l.hits, l.branches_total, l.branches_covered)).collect::<Vec<_>>(),
|
||||
[(0, 1, 0, 0), (1, 5, 2, 1), (2, 0, 0, 0)]
|
||||
);
|
||||
assert!(m.lines[1].partial());
|
||||
assert_eq!(file(Path::new("/abs/x.py")).lines[0].line, 6);
|
||||
assert!(parse("<coverage><packages></coverage>", Path::new("/root")).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn filenames_without_sources_resolve_against_the_base() {
|
||||
let xml = r#"<coverage><packages><package><classes><class filename="a/b.py"><lines><line number="1" hits="1"/></lines></class></classes></package></packages></coverage>"#;
|
||||
let suite = parse(xml, Path::new("/root")).unwrap().finish("Cobertura");
|
||||
assert_eq!(suite.files[0].path.as_ref() as &Path, Path::new("/root/a/b.py"));
|
||||
assert!(!suite.has_branches);
|
||||
assert_eq!(conditions("100% (4/4)"), Some((4, 4)));
|
||||
assert_eq!(conditions("100%"), None);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,281 @@
|
||||
//! coverage.py data files (`.coverage`, and `.coverage.*` of parallel runs): SQLite databases of
|
||||
//! executed lines and arcs. Which lines are statements, excluded or branches only comes from
|
||||
//! analysing the source, so coverage.py in the project's interpreter combines the data into a
|
||||
//! scratch file (`[paths]` of the project's configuration applies) and writes Cobertura XML.
|
||||
|
||||
use crate::{CoverageSuite, cobertura};
|
||||
use ide_core::cli_process::{CliTool, Decoding};
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use std::ffi::OsStr;
|
||||
use std::io::Read;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
use std::time::Duration;
|
||||
|
||||
const COVERAGE_PY: CliTool = CliTool::new("coverage.py", Decoding::ToolOutput);
|
||||
/// Analysing a large project's sources takes a while; a `[run] plugins` that hangs must not
|
||||
/// block the import for good.
|
||||
const TIMEOUT: Duration = Duration::from_secs(600);
|
||||
/// Files of the combined data (`relative_files` keeps them relative to the directory it ran in).
|
||||
const MEASURED: &str = "import sys, json, coverage\n\
|
||||
d = coverage.CoverageData(sys.argv[1]); d.read(); print(json.dumps(sorted(d.measured_files())))";
|
||||
/// The files coverage.py reads its configuration from, in the directory it runs in.
|
||||
const CONFIG_FILES: [&str; 4] = [".coveragerc", "setup.cfg", "tox.ini", "pyproject.toml"];
|
||||
|
||||
/// Whether `path` is an SQLite database (coverage.py 5+ data).
|
||||
pub fn is_data_file(path: &Path) -> bool {
|
||||
let mut head = [0u8; 16];
|
||||
std::fs::File::open(path).and_then(|mut f| f.read_exact(&mut head)).is_ok() && &head == b"SQLite format 3\0"
|
||||
}
|
||||
|
||||
/// `path`, or every `.coverage.*` file next to it when it is one of a parallel run's.
|
||||
fn inputs(path: &Path) -> Vec<PathBuf> {
|
||||
let parallel = path.file_name().and_then(|n| n.to_str()).is_some_and(|n| n.starts_with(".coverage."));
|
||||
let mut files: Vec<PathBuf> = match (parallel, path.parent()) {
|
||||
(true, Some(dir)) => std::fs::read_dir(dir)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.flatten()
|
||||
.map(|e| e.path())
|
||||
.filter(|p| {
|
||||
p.file_name().and_then(|n| n.to_str()).is_some_and(|n| n.starts_with(".coverage.")) && is_data_file(p)
|
||||
})
|
||||
.collect(),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
if files.is_empty() {
|
||||
files.push(path.to_path_buf());
|
||||
}
|
||||
files.sort();
|
||||
files
|
||||
}
|
||||
|
||||
/// Where coverage.py ran: the nearest directory of `path` inside `root` with a coverage.py
|
||||
/// configuration file (a monorepo's `backend/pyproject.toml`), else `root`.
|
||||
fn run_dir(path: &Path, root: &Path) -> PathBuf {
|
||||
path.ancestors()
|
||||
.skip(1)
|
||||
.take_while(|d| d.starts_with(root))
|
||||
.find(|d| CONFIG_FILES.iter().any(|f| d.join(f).is_file()))
|
||||
.unwrap_or(root)
|
||||
.to_path_buf()
|
||||
}
|
||||
|
||||
/// Runs `python -W ignore <args>` in `dir` and returns its stdout. Python warnings are
|
||||
/// ignored so `PYTHONWARNINGS=error` can't turn coverage.py's warnings into failures.
|
||||
fn python(python: &Path, dir: &Path, args: &[&OsStr]) -> IdeResult<String> {
|
||||
let mut cmd = Command::new(python);
|
||||
cmd.current_dir(dir).args(["-W", "ignore"]).args(args);
|
||||
let out = COVERAGE_PY.run(cmd, TIMEOUT, None)?;
|
||||
if out.success {
|
||||
return Ok(out.stdout);
|
||||
}
|
||||
let text = if out.stderr.trim().is_empty() { out.stdout } else { out.stderr };
|
||||
let text = text.trim();
|
||||
if text.contains("No module named coverage") {
|
||||
return Err(IdeError::unavailable(format!(
|
||||
"Reading a .coverage data file needs coverage.py in the project's interpreter ({}). Install it, or import the output of `coverage xml`.",
|
||||
python.display()
|
||||
)));
|
||||
}
|
||||
if text.contains("no such option") {
|
||||
return Err(IdeError::unavailable(format!(
|
||||
"Reading a .coverage data file needs coverage.py 6.3 or later in the project's interpreter ({}): {text}",
|
||||
python.display()
|
||||
)));
|
||||
}
|
||||
Err(IdeError::invalid(format!("coverage.py could not read the data: {text}")))
|
||||
}
|
||||
|
||||
/// Reads the data file at `path` with `python`'s coverage.py, run where the project's coverage.py
|
||||
/// configuration is; `out` holds the scratch files. Blocking.
|
||||
pub(crate) fn import(path: &Path, root: &Path, python_path: &Path, out: &Path) -> IdeResult<CoverageSuite> {
|
||||
let dir = run_dir(path, root);
|
||||
let data = out.join(".coverage");
|
||||
let xml = out.join("coverage.xml");
|
||||
let coverage = |args: &[&OsStr]| {
|
||||
let mut all: Vec<&OsStr> = vec!["-m".as_ref(), "coverage".as_ref()];
|
||||
all.extend(args);
|
||||
python(python_path, &dir, &all)
|
||||
};
|
||||
let inputs = inputs(path);
|
||||
let mut args: Vec<&OsStr> = vec!["combine".as_ref(), "--keep".as_ref(), "--data-file".as_ref(), data.as_ref()];
|
||||
args.extend(inputs.iter().map(|p| p.as_os_str()));
|
||||
coverage(&args)?;
|
||||
// `-i`: report what has source here instead of failing on the first file that has none.
|
||||
// `--fail-under=0`: a `[report] fail_under` the data misses must not fail the import.
|
||||
coverage(&[
|
||||
"xml".as_ref(),
|
||||
"-i".as_ref(),
|
||||
"--fail-under=0".as_ref(),
|
||||
"--data-file".as_ref(),
|
||||
data.as_ref(),
|
||||
"-o".as_ref(),
|
||||
xml.as_ref(),
|
||||
])?;
|
||||
let text = std::fs::read_to_string(&xml)?;
|
||||
let mut acc = cobertura::parse(&text, &dir).map_err(|e| IdeError::invalid(format!("{}: {e}", xml.display())))?;
|
||||
// The files the report left out (no source here): listed without lines.
|
||||
let measured = python(python_path, &dir, &["-c".as_ref(), MEASURED.as_ref(), data.as_ref()])?;
|
||||
let measured: Vec<PathBuf> = serde_json::from_str(measured.trim())
|
||||
.map_err(|e| IdeError::invalid(format!("coverage.py listed the measured files unreadably: {e}")))?;
|
||||
for file in measured {
|
||||
acc.file(&dir.join(file));
|
||||
}
|
||||
Ok(acc.finish("coverage.py"))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn finds_the_files_of_a_parallel_run() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let db = |name: &str| {
|
||||
let p = tmp.path().join(name);
|
||||
std::fs::write(&p, b"SQLite format 3\0rest").unwrap();
|
||||
p
|
||||
};
|
||||
let a = db(".coverage.host.1.x");
|
||||
let b = db(".coverage.host.2.y");
|
||||
let single = db(".coverage");
|
||||
std::fs::write(tmp.path().join(".coverage.notes"), "text").unwrap();
|
||||
std::fs::write(tmp.path().join(".coveragerc"), "[run]\n").unwrap();
|
||||
assert!(is_data_file(&a) && !is_data_file(&tmp.path().join(".coveragerc")));
|
||||
assert_eq!(inputs(&a), [a.clone(), b]);
|
||||
assert_eq!(inputs(&single), [single]);
|
||||
}
|
||||
|
||||
/// Two parallel runs recorded on another machine (`…/ci/app`), mapped by the project's `[paths]`.
|
||||
/// Needs coverage.py in `python3`; skipped without it.
|
||||
#[test]
|
||||
fn combines_parallel_data_with_the_projects_paths() {
|
||||
let has_coverage = Command::new("python3").args(["-m", "coverage", "--version"]).output();
|
||||
if !has_coverage.is_ok_and(|o| o.status.success()) {
|
||||
eprintln!("skipped: no coverage.py in python3");
|
||||
return;
|
||||
}
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
// coverage.py reports real paths (`/private/var/…` for macOS's `/var/…`).
|
||||
let base = tmp.path().canonicalize().unwrap();
|
||||
let ci = base.join("ci/app");
|
||||
let root = base.join("project");
|
||||
let calc = "def sign(n):\n if n < 0:\n return -1\n return 1\n";
|
||||
for dir in [&ci, &root] {
|
||||
std::fs::create_dir_all(dir).unwrap();
|
||||
std::fs::write(dir.join("calc.py"), calc).unwrap();
|
||||
}
|
||||
std::fs::write(ci.join("gone.py"), "x = 1\n").unwrap();
|
||||
std::fs::write(ci.join("neg.py"), "import calc, gone\ncalc.sign(-1)\n").unwrap();
|
||||
std::fs::write(ci.join("pos.py"), "import calc\ncalc.sign(1)\n").unwrap();
|
||||
for script in ["neg.py", "pos.py"] {
|
||||
let ok = Command::new("python3")
|
||||
.current_dir(&ci)
|
||||
.args(["-m", "coverage", "run", "--branch", "--parallel-mode", script])
|
||||
.status()
|
||||
.unwrap();
|
||||
assert!(ok.success());
|
||||
}
|
||||
let data = root.join("data");
|
||||
std::fs::create_dir_all(&data).unwrap();
|
||||
for e in std::fs::read_dir(&ci).unwrap().flatten() {
|
||||
if e.file_name().to_string_lossy().starts_with(".coverage.") {
|
||||
std::fs::rename(e.path(), data.join(e.file_name())).unwrap();
|
||||
}
|
||||
}
|
||||
std::fs::remove_dir_all(&ci).unwrap();
|
||||
std::fs::write(root.join(".coveragerc"), "[paths]\nsource =\n ./\n */ci/app/\n").unwrap();
|
||||
let first = std::fs::read_dir(&data).unwrap().flatten().next().unwrap().path();
|
||||
let out = base.join("out");
|
||||
std::fs::create_dir_all(&out).unwrap();
|
||||
let suite = import(&first, &root, Path::new("python3"), &out).unwrap();
|
||||
|
||||
let calc = suite.files.iter().find(|f| f.path.as_ref() as &Path == root.join("calc.py")).unwrap();
|
||||
// Both runs together take both branches of line 2.
|
||||
assert_eq!((calc.lines_total, calc.lines_covered, calc.branches_total, calc.branches_covered), (4, 4, 2, 2));
|
||||
// The scripts and `gone.py` have no source in the project: listed without lines.
|
||||
let empty: Vec<&str> = suite
|
||||
.files
|
||||
.iter()
|
||||
.filter(|f| f.lines.is_empty())
|
||||
.filter_map(|f| (f.path.as_ref() as &Path).file_name()?.to_str())
|
||||
.collect();
|
||||
assert_eq!(empty, ["gone.py", "neg.py", "pos.py"]);
|
||||
// They keep the recorded path, so the import notification counts them as not in the project.
|
||||
assert!(suite.files.iter().filter(|f| f.lines.is_empty()).all(|f| (f.path.as_ref() as &Path).starts_with(&ci)));
|
||||
assert_eq!(std::fs::read_dir(&data).unwrap().count(), 2, "the user's data files are kept");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn runs_where_the_coverage_configuration_is() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
std::fs::create_dir_all(root.join("backend/reports")).unwrap();
|
||||
std::fs::create_dir_all(root.join("data")).unwrap();
|
||||
std::fs::write(root.join("backend/pyproject.toml"), "").unwrap();
|
||||
assert_eq!(run_dir(&root.join("backend/reports/.coverage"), root), root.join("backend"));
|
||||
assert_eq!(run_dir(&root.join("data/.coverage"), root), root);
|
||||
// A data file outside the project runs in the project.
|
||||
assert_eq!(run_dir(Path::new("/elsewhere/.coverage"), root), root);
|
||||
}
|
||||
|
||||
/// A stand-in interpreter that prints `stderr` and exits with `code`.
|
||||
#[cfg(unix)]
|
||||
fn fake_python(dir: &Path, stderr: &str, code: i32) -> PathBuf {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let p = dir.join("python");
|
||||
std::fs::write(&p, format!("#!/bin/sh\necho '{stderr}' >&2\nexit {code}\n")).unwrap();
|
||||
std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
p
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn reports_why_coverage_py_failed() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let data = tmp.path().join(".coverage");
|
||||
let err = |stderr: &str| {
|
||||
let python = fake_python(tmp.path(), stderr, 1);
|
||||
import(&data, tmp.path(), &python, tmp.path()).unwrap_err().to_string()
|
||||
};
|
||||
assert!(err("No module named coverage").contains("needs coverage.py in the project's interpreter"));
|
||||
assert!(err("no such option: --data-file").contains("needs coverage.py 6.3 or later"));
|
||||
assert!(err("No usable data files").contains("coverage.py could not read the data: No usable data files"));
|
||||
}
|
||||
|
||||
/// A monorepo member's data recorded with `relative_files`, below its `fail_under`, with
|
||||
/// coverage.py's warnings turned off. Needs coverage.py in `python3`; skipped without it.
|
||||
#[test]
|
||||
fn reads_a_members_relative_data_below_fail_under() {
|
||||
let has_coverage = Command::new("python3").args(["-m", "coverage", "--version"]).output();
|
||||
if !has_coverage.is_ok_and(|o| o.status.success()) {
|
||||
eprintln!("skipped: no coverage.py in python3");
|
||||
return;
|
||||
}
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path().canonicalize().unwrap();
|
||||
let member = root.join("backend");
|
||||
std::fs::create_dir_all(member.join("app")).unwrap();
|
||||
std::fs::write(
|
||||
member.join("pyproject.toml"),
|
||||
"[tool.coverage.run]\nrelative_files = true\nbranch = true\ndisable_warnings = [\"couldnt-parse\"]\n\
|
||||
[tool.coverage.report]\nfail_under = 90\n",
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::write(member.join("app/x.py"), "def f(n):\n if n:\n return 1\n return 2\n").unwrap();
|
||||
std::fs::write(member.join("t.py"), "from app import x\nx.f(1)\n").unwrap();
|
||||
let ok = Command::new("python3").current_dir(&member).args(["-m", "coverage", "run", "t.py"]).status().unwrap();
|
||||
assert!(ok.success());
|
||||
std::fs::remove_file(member.join("t.py")).unwrap();
|
||||
let out = root.join("out");
|
||||
std::fs::create_dir_all(&out).unwrap();
|
||||
let suite = import(&member.join(".coverage"), &root, Path::new("python3"), &out).unwrap();
|
||||
|
||||
let x = suite.files.iter().find(|f| f.path.as_ref() as &Path == member.join("app/x.py")).unwrap();
|
||||
assert_eq!((x.lines_total, x.lines_covered, x.branches_total, x.branches_covered), (4, 3, 2, 1));
|
||||
// `t.py` has no source any more and its warning is off: still listed, without lines.
|
||||
let t = suite.files.iter().find(|f| f.path.as_ref() as &Path == member.join("t.py")).unwrap();
|
||||
assert!(t.lines.is_empty());
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,10 @@
|
||||
//! "Import a report collected in CI from disk": the format is sniffed from the
|
||||
//! content (lcov, Go cover profile, JaCoCo XML, SimpleCov resultset) and paths recorded on another
|
||||
//! content (lcov, Go cover profile, JaCoCo or Cobertura XML, SimpleCov resultset) and paths recorded on another
|
||||
//! machine are mapped into the project by their longest existing suffix.
|
||||
|
||||
use crate::{Accumulator, CoverageSuite, goprofile, jacoco, lcov, simplecov};
|
||||
use crate::{Accumulator, CoverageSuite, cobertura, goprofile, jacoco, lcov, simplecov};
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
@@ -11,13 +12,19 @@ pub(crate) enum Format {
|
||||
Lcov,
|
||||
GoProfile,
|
||||
Jacoco,
|
||||
Cobertura,
|
||||
SimpleCov,
|
||||
}
|
||||
|
||||
pub(crate) fn detect(text: &str) -> Option<Format> {
|
||||
let head = text.trim_start_matches('\u{feff}').trim_start();
|
||||
if head.starts_with('<') {
|
||||
return head.contains("<report").then_some(Format::Jacoco);
|
||||
// The root element, after any prolog or DOCTYPE naming it.
|
||||
return match (head.find("<report"), head.find("<coverage")) {
|
||||
(Some(r), c) if c.is_none_or(|c| r < c) => Some(Format::Jacoco),
|
||||
(_, Some(_)) => Some(Format::Cobertura),
|
||||
_ => None,
|
||||
};
|
||||
}
|
||||
if head.starts_with('{') {
|
||||
return head.contains("\"coverage\"").then_some(Format::SimpleCov);
|
||||
@@ -39,6 +46,9 @@ pub fn import(path: &Path, root: &Path) -> IdeResult<CoverageSuite> {
|
||||
let (module, module_dir) = go_module_for(root, &text);
|
||||
goprofile::parse(&text, &module, &module_dir).finish("go test -cover")
|
||||
}
|
||||
Some(Format::Cobertura) => cobertura::parse(&text, root)
|
||||
.map_err(|e| IdeError::invalid(format!("{}: {e}", path.display())))?
|
||||
.finish("Cobertura"),
|
||||
Some(Format::Jacoco) => {
|
||||
// A report inside the project (`<module>/target/site/jacoco/…`) knows its module.
|
||||
let module = jacoco::module_dir(path);
|
||||
@@ -53,18 +63,24 @@ pub fn import(path: &Path, root: &Path) -> IdeResult<CoverageSuite> {
|
||||
.map_err(|e| IdeError::invalid(format!("{}: {e}", path.display())))?;
|
||||
acc.finish("JaCoCo")
|
||||
}
|
||||
None if text.starts_with("!coverage.py: This is a private format") => {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"{} is coverage.py 4 data, which current coverage.py can't read. Import the output of `coverage xml` instead.",
|
||||
path.display()
|
||||
)));
|
||||
}
|
||||
None => {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"{} is not an lcov tracefile, Go cover profile, JaCoCo XML report or SimpleCov resultset",
|
||||
"{} is not an lcov tracefile, Go cover profile, JaCoCo or Cobertura XML report or SimpleCov resultset",
|
||||
path.display()
|
||||
)));
|
||||
}
|
||||
};
|
||||
let mut dirs = HashMap::new();
|
||||
for f in &mut suite.files {
|
||||
let p: &Path = f.path.as_ref();
|
||||
if !p.exists()
|
||||
&& let Some(found) = relocate(p, root)
|
||||
{
|
||||
let present = p.parent().is_none_or(|d| dir_exists(d, &mut dirs)) && p.exists();
|
||||
if !present && let Some(found) = relocate(p, root) {
|
||||
f.path = found.into();
|
||||
}
|
||||
}
|
||||
@@ -72,6 +88,24 @@ pub fn import(path: &Path, root: &Path) -> IdeResult<CoverageSuite> {
|
||||
Ok(suite)
|
||||
}
|
||||
|
||||
/// Reads a coverage.py data file (see [`crate::is_data_file`]) with the coverage.py of `python`,
|
||||
/// run in `root`; `out` is an empty scratch directory. Blocking.
|
||||
pub fn import_data(path: &Path, root: &Path, python: &Path, out: &Path) -> IdeResult<CoverageSuite> {
|
||||
crate::coveragepy::import(path, root, python, out)
|
||||
}
|
||||
|
||||
/// Whether `dir` exists, without asking again below a directory known to be missing: every
|
||||
/// lookup under macOS's `/home` (autofs) takes tens of milliseconds, and CI reports
|
||||
/// (`/home/runner/work/…`) name thousands of files there.
|
||||
fn dir_exists(dir: &Path, known: &mut HashMap<PathBuf, bool>) -> bool {
|
||||
if let Some(&e) = known.get(dir) {
|
||||
return e;
|
||||
}
|
||||
let e = dir.parent().is_none_or(|p| dir_exists(p, known)) && dir.is_dir();
|
||||
known.insert(dir.to_path_buf(), e);
|
||||
e
|
||||
}
|
||||
|
||||
/// `/home/runner/work/app/app/src/lib.rs` → `<root>/src/lib.rs`: the longest suffix of
|
||||
/// `path` that exists under `root`.
|
||||
pub(crate) fn relocate(path: &Path, root: &Path) -> Option<PathBuf> {
|
||||
@@ -129,12 +163,30 @@ mod tests {
|
||||
detect("<?xml version=\"1.0\"?><!DOCTYPE report><report name=\"x\"></report>"),
|
||||
Some(Format::Jacoco)
|
||||
);
|
||||
assert_eq!(detect("<?xml version=\"1.0\"?><coverage/>"), None);
|
||||
assert_eq!(detect("<?xml version=\"1.0\"?><coverage/>"), Some(Format::Cobertura));
|
||||
assert_eq!(
|
||||
detect("<?xml version=\"1.0\"?><!DOCTYPE coverage SYSTEM \"x.dtd\"><coverage/>"),
|
||||
Some(Format::Cobertura)
|
||||
);
|
||||
assert_eq!(detect("<?xml version=\"1.0\"?><html/>"), None);
|
||||
assert_eq!(detect("{\"RSpec\": {\"coverage\": {}}}"), Some(Format::SimpleCov));
|
||||
assert_eq!(detect("{\"name\": \"package.json\"}"), None);
|
||||
assert_eq!(detect("hello"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_directories_are_looked_up_once() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mut known = HashMap::new();
|
||||
assert!(dir_exists(tmp.path(), &mut known));
|
||||
let gone = tmp.path().join("gone");
|
||||
assert!(!dir_exists(&gone.join("a/b"), &mut known));
|
||||
std::fs::create_dir_all(gone.join("a/c")).unwrap();
|
||||
// Known to be missing, so its subdirectories are not looked up.
|
||||
assert!(!dir_exists(&gone.join("a/c"), &mut known));
|
||||
assert_eq!(known.get(&gone), Some(&false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn imports_ci_simplecov_with_foreign_paths() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
@@ -168,8 +220,75 @@ mod tests {
|
||||
assert!(import(&tmp.path().join("missing"), &root).is_err());
|
||||
std::fs::write(&report, "nothing").unwrap();
|
||||
assert!(import(&report, &root).is_err());
|
||||
std::fs::write(&report, "!coverage.py: This is a private format, don't read it directly!{\"lines\":{}}")
|
||||
.unwrap();
|
||||
assert!(import(&report, &root).unwrap_err().to_string().contains("coverage.py 4 data"));
|
||||
}
|
||||
|
||||
/// `coverage xml` (coverage.py 7.17, `--branch`) of a project checked out on a CI runner.
|
||||
#[test]
|
||||
fn imports_coverage_py_xml_with_foreign_sources() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path().join("app");
|
||||
std::fs::create_dir_all(root.join("src/calc")).unwrap();
|
||||
std::fs::write(root.join("src/calc/__init__.py"), "").unwrap();
|
||||
let report = tmp.path().join("coverage.xml");
|
||||
std::fs::write(&report, COVERAGE_PY_XML).unwrap();
|
||||
let suite = import(&report, &root).unwrap();
|
||||
assert_eq!(suite.runner, "Cobertura");
|
||||
assert!(suite.has_branches);
|
||||
let calc = suite.files.iter().find(|f| f.path.as_ref() as &Path == root.join("src/calc/__init__.py")).unwrap();
|
||||
assert_eq!((calc.lines_total, calc.lines_covered, calc.branches_total, calc.branches_covered), (8, 5, 4, 2));
|
||||
assert_eq!(calc.lines.iter().filter(|l| l.partial()).map(|l| l.line).collect::<Vec<_>>(), [1, 3]);
|
||||
// The test file is not in this checkout: it keeps the runner's path.
|
||||
assert!(
|
||||
suite.files.iter().any(|f| f.path.as_ref() as &Path == Path::new("/home/runner/work/app/app/test_calc.py"))
|
||||
);
|
||||
}
|
||||
|
||||
const COVERAGE_PY_XML: &str = r#"<?xml version="1.0" ?>
|
||||
<coverage version="7.17.5" timestamp="1795754882920" lines-valid="13" lines-covered="10" line-rate="0.7692" branches-valid="4" branches-covered="2" branch-rate="0.5" complexity="0">
|
||||
<!-- Generated by coverage.py: https://coverage.readthedocs.io/en/7.17.5 -->
|
||||
<!-- Based on https://raw.githubusercontent.com/cobertura/web/master/htdocs/xml/coverage-04.dtd -->
|
||||
<sources>
|
||||
<source>/home/runner/work/app/app</source>
|
||||
</sources>
|
||||
<packages>
|
||||
<package name="." line-rate="1" branch-rate="1" complexity="0">
|
||||
<classes>
|
||||
<class name="test_calc.py" filename="test_calc.py" complexity="0" line-rate="1" branch-rate="1">
|
||||
<methods/>
|
||||
<lines>
|
||||
<line number="1" hits="1"/>
|
||||
<line number="2" hits="1"/>
|
||||
<line number="3" hits="1"/>
|
||||
<line number="6" hits="1"/>
|
||||
<line number="7" hits="1"/>
|
||||
</lines>
|
||||
</class>
|
||||
</classes>
|
||||
</package>
|
||||
<package name="src.calc" line-rate="0.625" branch-rate="0.5" complexity="0">
|
||||
<classes>
|
||||
<class name="__init__.py" filename="src/calc/__init__.py" complexity="0" line-rate="0.625" branch-rate="0.5">
|
||||
<methods/>
|
||||
<lines>
|
||||
<line number="1" hits="1"/>
|
||||
<line number="2" hits="1" branch="true" condition-coverage="50% (1/2)" missing-branches="3"/>
|
||||
<line number="3" hits="0"/>
|
||||
<line number="4" hits="1" branch="true" condition-coverage="50% (1/2)" missing-branches="5"/>
|
||||
<line number="5" hits="0"/>
|
||||
<line number="6" hits="1"/>
|
||||
<line number="13" hits="1"/>
|
||||
<line number="14" hits="0"/>
|
||||
</lines>
|
||||
</class>
|
||||
</classes>
|
||||
</package>
|
||||
</packages>
|
||||
</coverage>
|
||||
"#;
|
||||
|
||||
#[test]
|
||||
fn imports_go_profiles_of_nested_modules() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -16,6 +16,8 @@
|
||||
//!
|
||||
//! Lines in the model are 0-based, like every IPC coordinate.
|
||||
|
||||
mod cobertura;
|
||||
mod coveragepy;
|
||||
mod goprofile;
|
||||
mod import;
|
||||
mod jacoco;
|
||||
@@ -23,7 +25,8 @@ mod lcov;
|
||||
mod plan;
|
||||
mod simplecov;
|
||||
|
||||
pub use import::import;
|
||||
pub use coveragepy::is_data_file;
|
||||
pub use import::{import, import_data};
|
||||
pub use plan::prepare;
|
||||
|
||||
use ide_core::{IdeError, IdeResult, IpcPath};
|
||||
|
||||
@@ -326,7 +326,8 @@ fn python(config: &RunConfig, dir: &Path, out: &Path, py: wrap::PythonCommand) -
|
||||
argv.extend(py.target.iter().cloned());
|
||||
let report = CoverageReportSpec::Exported {
|
||||
runner: s("coverage.py"),
|
||||
argv: with(&["-m", "coverage", "lcov", "-o", &path(&lcov)]),
|
||||
// `--fail-under=0`: a `[report] fail_under` the run misses must not lose its report.
|
||||
argv: with(&["-m", "coverage", "lcov", "--fail-under=0", "-o", &path(&lcov)]),
|
||||
cwd: dir.to_path_buf().into(),
|
||||
env: config.env.clone(),
|
||||
lcov: lcov.into(),
|
||||
|
||||
@@ -859,6 +859,21 @@ async fn connect_with_retries(
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A user's `languages/python.toml` `[debugger]` is the one debugpy runs with: no other
|
||||
/// language (a template one) declares debugpy before Python.
|
||||
#[test]
|
||||
fn debugpy_comes_from_the_python_language() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let python = include_str!("../../../languages/python.toml").replace(
|
||||
"args = [\"-m\", \"debugpy.adapter\"]",
|
||||
"args = [\"-X\", \"frozen_modules=off\", \"-m\", \"debugpy.adapter\"]",
|
||||
);
|
||||
assert!(python.contains("frozen_modules"));
|
||||
std::fs::write(dir.path().join("python.toml"), python).unwrap();
|
||||
let languages = LanguageRegistry::load(Some(dir.path())).unwrap();
|
||||
assert_eq!(find_config(&languages, "debugpy").unwrap().args[0], "-X");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adapters_run_on_the_tool_search_path() {
|
||||
let search = ide_core::tool_path::search_path();
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
//! Python Debug Server (`attach` with `listen`): the program connects with its own debugpy,
|
||||
//! which may differ from the IDE's adapter. Nothing in the protocol compares them.
|
||||
|
||||
use crate::session::Session;
|
||||
use ide_core::IdeError;
|
||||
use ide_core::event::DebugEvent;
|
||||
use serde_json::{Value, json};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
pub(crate) fn listens(adapter: &str, request: &str, arguments: &Value) -> bool {
|
||||
adapter == "debugpy" && request == "attach" && arguments.get("listen").is_some()
|
||||
}
|
||||
|
||||
/// debugpy's adapter leaves an `attach` whose port is taken unanswered (it only logs the error),
|
||||
/// which would wait for the program forever: find out before starting it. Listening again right
|
||||
/// after a program ended races the previous adapter, which still listens until its shutdown ends.
|
||||
pub(crate) async fn require_free_port(arguments: &Value) -> Result<(), IdeError> {
|
||||
// ponytail: polls; waiting on the previous session's shutdown would report a taken port sooner.
|
||||
const RELEASE: Duration = Duration::from_secs(5);
|
||||
let listen = &arguments["listen"];
|
||||
let host = listen["host"].as_str().unwrap_or("127.0.0.1");
|
||||
let Some(port) = listen["port"].as_u64().and_then(|p| u16::try_from(p).ok()) else { return Ok(()) };
|
||||
let deadline = tokio::time::Instant::now() + RELEASE;
|
||||
loop {
|
||||
match std::net::TcpListener::bind((host, port)) {
|
||||
Ok(_) => return Ok(()),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::AddrInUse && tokio::time::Instant::now() < deadline => {
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
}
|
||||
Err(e) => return Err(IdeError::unavailable(format!("Cannot listen on {host}:{port}: {e}"))),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// On the program's first stop: warns in the Debug console when its debugpy is not the adapter's.
|
||||
/// Evaluated in the stopped frame as a hover: without a frame, debugpy before 1.8 runs the
|
||||
/// expression as a statement and prints its value into the program's output.
|
||||
pub(crate) async fn check_version(s: Arc<Session>, thread: i64) {
|
||||
const WAIT: Duration = Duration::from_secs(5);
|
||||
let request = |command: &'static str, arguments: Value| s.conn.request_timeout(command, arguments, WAIT);
|
||||
let Ok(info) = request("debugpySystemInfo", json!({})).await else { return };
|
||||
let Some(ide) = info.pointer("/debugpy/version").and_then(Value::as_str) else { return };
|
||||
let Ok(trace) = request("stackTrace", json!({ "threadId": thread, "levels": 1 })).await else { return };
|
||||
let Some(frame) = trace.pointer("/stackFrames/0/id").and_then(Value::as_i64) else { return };
|
||||
let expression = json!({ "expression": "__import__('debugpy').__version__", "frameId": frame, "context": "hover" });
|
||||
let Ok(reply) = request("evaluate", expression).await else { return };
|
||||
let Some(program) = reply.get("result").and_then(Value::as_str) else { return };
|
||||
if let Some(warning) = version_warning(ide, program) {
|
||||
s.emit(DebugEvent::Output { category: "console".into(), output: warning });
|
||||
}
|
||||
}
|
||||
|
||||
fn version_warning(ide: &str, program: &str) -> Option<String> {
|
||||
let program = program.trim_matches(|c| c == '\'' || c == '"');
|
||||
(program != ide).then(|| {
|
||||
format!(
|
||||
"The program uses debugpy {program}, the IDE's debugger debugpy {ide}. If breakpoints or stepping \
|
||||
misbehave, install the same version where the program runs: pip install debugpy=={ide}\n"
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn warns_only_when_versions_differ() {
|
||||
assert_eq!(version_warning("1.8.22", "'1.8.22'"), None);
|
||||
assert_eq!(version_warning("1.8.22", "1.8.22"), None);
|
||||
let w = version_warning("1.8.22", "'1.8.0'").unwrap();
|
||||
assert!(w.contains("debugpy 1.8.0") && w.ends_with("pip install debugpy==1.8.22\n"), "{w}");
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn a_taken_port_is_reported_before_the_adapter_starts() {
|
||||
let taken = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap();
|
||||
let port = taken.local_addr().unwrap().port();
|
||||
let listen = json!({"listen": {"host": "127.0.0.1", "port": port}});
|
||||
let e = require_free_port(&listen).await.unwrap_err();
|
||||
assert!(e.to_string().contains(&format!("Cannot listen on 127.0.0.1:{port}")), "{e}");
|
||||
drop(taken);
|
||||
assert!(require_free_port(&listen).await.is_ok());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_address_the_machine_lacks_is_reported_at_once() {
|
||||
// 192.0.2.0/24 is reserved for documentation, never a local address.
|
||||
let started = std::time::Instant::now();
|
||||
let e = require_free_port(&json!({"listen": {"host": "192.0.2.1", "port": 5678}})).await.unwrap_err();
|
||||
assert!(e.to_string().contains("Cannot listen on 192.0.2.1:5678"), "{e}");
|
||||
assert!(started.elapsed() < Duration::from_secs(1));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn waits_for_the_previous_adapter_to_release_the_port() {
|
||||
let previous = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap();
|
||||
let port = previous.local_addr().unwrap().port();
|
||||
let released = tokio::spawn(async move {
|
||||
tokio::time::sleep(Duration::from_millis(300)).await;
|
||||
drop(previous);
|
||||
});
|
||||
require_free_port(&json!({"listen": {"host": "127.0.0.1", "port": port}})).await.unwrap();
|
||||
released.await.unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_debugpy_listen_attaches_check() {
|
||||
assert!(listens("debugpy", "attach", &json!({"listen": {"port": 5678}})));
|
||||
assert!(!listens("debugpy", "attach", &json!({"connect": {"port": 5678}})));
|
||||
assert!(!listens("debugpy", "launch", &json!({"listen": {}})));
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,7 @@ pub mod adapter;
|
||||
pub mod attach;
|
||||
mod cargo;
|
||||
pub mod connection;
|
||||
mod debugpy;
|
||||
mod exception_classes;
|
||||
pub mod jdwp;
|
||||
mod js_cdp;
|
||||
@@ -308,6 +309,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 +345,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>,
|
||||
@@ -818,8 +826,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)),
|
||||
})
|
||||
@@ -839,8 +845,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`).
|
||||
@@ -880,6 +902,9 @@ impl DebugManager {
|
||||
exception_classes: Option<Arc<dyn ide_jvm_inspect::ExceptionClassBreakpoints>>,
|
||||
) -> IdeResult<DebugSessionId> {
|
||||
let mut arguments = launch_arguments(&config)?;
|
||||
if debugpy::listens(&config.adapter, &config.request, &arguments) {
|
||||
debugpy::require_free_port(&arguments).await?;
|
||||
}
|
||||
// An IDE-side marker (never sent to the adapter): the session is a Flutter
|
||||
// one regardless of what the working directory holds.
|
||||
let force_flutter =
|
||||
@@ -1128,6 +1153,9 @@ impl DebugManager {
|
||||
});
|
||||
tokio::spawn(session::event_loop(self.me.clone(), session.clone(), incoming));
|
||||
|
||||
if debugpy::listens(&session.adapter, &session.request, &arguments) {
|
||||
session.debugpy_version_unchecked.store(true, Ordering::Release);
|
||||
}
|
||||
let configured = tokio::select! {
|
||||
biased;
|
||||
_ = session.startup_cancel.cancelled() => return Err(IdeError::cancelled()),
|
||||
@@ -1291,8 +1319,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.
|
||||
@@ -1310,14 +1340,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
|
||||
@@ -1470,26 +1500,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);
|
||||
@@ -1640,16 +1703,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);
|
||||
@@ -1661,7 +1747,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>> {
|
||||
@@ -1853,7 +1939,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?;
|
||||
@@ -1868,10 +1954,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) {
|
||||
@@ -1885,11 +1976,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;
|
||||
}
|
||||
@@ -1899,8 +1991,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 {
|
||||
@@ -1908,13 +2003,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}");
|
||||
}
|
||||
@@ -2124,14 +2219,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 {
|
||||
@@ -2144,12 +2242,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 {
|
||||
|
||||
@@ -75,6 +75,8 @@ pub(crate) struct Session {
|
||||
pub jdwp_port: std::sync::OnceLock<u16>,
|
||||
/// The attach goes through the listen-mode relay of [`crate::jdwp::listen_for_jvm`].
|
||||
pub listen_relay: AtomicBool,
|
||||
/// A Python Debug Server session whose program's debugpy version is checked on its first stop.
|
||||
pub(crate) debugpy_version_unchecked: AtomicBool,
|
||||
pub suspended: Suspension,
|
||||
/// Pids signalled for the current stop: the reported pid and everything it started (an
|
||||
/// adapter may report the launcher shell, whose child is the program).
|
||||
@@ -316,6 +318,7 @@ impl Session {
|
||||
jvm_pid: AtomicI64::new(0),
|
||||
jdwp_port: std::sync::OnceLock::new(),
|
||||
listen_relay: AtomicBool::new(false),
|
||||
debugpy_version_unchecked: AtomicBool::new(false),
|
||||
suspended: Suspension::default(),
|
||||
stop_pids: parking_lot::Mutex::new(Vec::new()),
|
||||
#[cfg(windows)]
|
||||
@@ -854,6 +857,11 @@ async fn on_event(mgr: &Arc<DebugManager>, s: &Arc<Session>, event: &str, mut bo
|
||||
all_threads_stopped: all,
|
||||
});
|
||||
});
|
||||
if let Some(thread) = int("threadId")
|
||||
&& s.debugpy_version_unchecked.swap(false, Ordering::AcqRel)
|
||||
{
|
||||
tokio::spawn(crate::debugpy::check_version(s.clone(), thread));
|
||||
}
|
||||
}
|
||||
"continued" => {
|
||||
let all = body.get("allThreadsContinued").and_then(Value::as_bool);
|
||||
|
||||
@@ -126,6 +126,8 @@ struct Script {
|
||||
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.
|
||||
@@ -206,6 +208,7 @@ impl Default for Script {
|
||||
child_request: None,
|
||||
ignore_configuration_done: false,
|
||||
source_path: None,
|
||||
failing_frame: None,
|
||||
debuggee_pid: None,
|
||||
java_process_id: false,
|
||||
output_after_terminate: false,
|
||||
@@ -520,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": [
|
||||
@@ -899,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();
|
||||
@@ -981,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();
|
||||
@@ -1005,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();
|
||||
@@ -1037,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(),
|
||||
@@ -1889,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(),
|
||||
@@ -1898,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!(
|
||||
@@ -1914,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();
|
||||
@@ -1958,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> {
|
||||
@@ -1995,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();
|
||||
@@ -2009,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());
|
||||
@@ -2209,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")));
|
||||
@@ -2236,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();
|
||||
@@ -2270,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!() };
|
||||
@@ -2292,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() {
|
||||
@@ -2299,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();
|
||||
@@ -2323,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();
|
||||
@@ -3418,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 }],
|
||||
)
|
||||
|
||||
@@ -127,7 +127,10 @@ mod tests {
|
||||
fn schema(name: &str, tables: &[&str]) -> CatalogSchema {
|
||||
CatalogSchema {
|
||||
name: name.into(),
|
||||
tables: tables.iter().map(|t| TableInfo { name: (*t).into(), kind: DbTableKind::Table }).collect(),
|
||||
tables: tables
|
||||
.iter()
|
||||
.map(|t| TableInfo { name: (*t).into(), kind: DbTableKind::Table, comment: None })
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -655,7 +655,7 @@ impl DbManager {
|
||||
}
|
||||
}
|
||||
|
||||
/// The bridge's `schemaColumns` rows (table, name, type, nullable, default) by table.
|
||||
/// The bridge's `schemaColumns` rows (table, name, type, nullable, default, comment) by table.
|
||||
fn schema_columns(rows: Vec<Vec<Option<String>>>) -> HashMap<String, Vec<crate::CompletionColumn>> {
|
||||
let mut by_table: HashMap<String, Vec<crate::CompletionColumn>> = HashMap::new();
|
||||
for row in rows {
|
||||
@@ -664,12 +664,15 @@ fn schema_columns(rows: Vec<Vec<Option<String>>>) -> HashMap<String, Vec<crate::
|
||||
let data_type = it.next().flatten().unwrap_or_default();
|
||||
let nullable = it.next().flatten().as_deref() != Some("0");
|
||||
let has_default = it.next().flatten().is_some();
|
||||
// Bridges built before the comment column send five fields.
|
||||
let comment = it.next().flatten().filter(|c| !c.trim().is_empty());
|
||||
by_table.entry(table).or_default().push(crate::CompletionColumn {
|
||||
name,
|
||||
data_type,
|
||||
nullable,
|
||||
primary_key: false,
|
||||
has_default,
|
||||
comment,
|
||||
});
|
||||
}
|
||||
by_table
|
||||
@@ -684,16 +687,18 @@ mod tests {
|
||||
let row = |t: &str, n: &str, null: &str, def: Option<&str>| {
|
||||
vec![Some(t.into()), Some(n.into()), Some("INT".into()), Some(null.into()), def.map(Into::into)]
|
||||
};
|
||||
let by_table = schema_columns(vec![
|
||||
row("orders", "id", "0", None),
|
||||
row("orders", "note", "1", Some("'none'")),
|
||||
row("items", "sku", "1", None),
|
||||
vec![None, Some("orphan".into())],
|
||||
]);
|
||||
let mut commented = row("orders", "note", "1", Some("'none'"));
|
||||
commented.push(Some("free text".into()));
|
||||
let mut blank = row("items", "sku", "1", None);
|
||||
blank.push(Some(" ".into()));
|
||||
let by_table =
|
||||
schema_columns(vec![row("orders", "id", "0", None), commented, blank, vec![None, Some("orphan".into())]]);
|
||||
let orders = &by_table["orders"];
|
||||
assert_eq!(orders.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(), ["id", "note"]);
|
||||
assert_eq!((orders[0].nullable, orders[0].has_default), (false, false));
|
||||
assert_eq!((orders[1].nullable, orders[1].has_default), (true, true));
|
||||
assert_eq!((orders[0].comment.as_deref(), orders[1].comment.as_deref()), (None, Some("free text")));
|
||||
assert_eq!(by_table["items"][0].comment, None);
|
||||
assert_eq!(by_table["items"].len(), 1);
|
||||
assert_eq!(by_table.len(), 2);
|
||||
}
|
||||
|
||||
+100
-22
@@ -31,7 +31,7 @@ pub use history::HistoryEntry;
|
||||
pub use plan::{PlanNode, PlanProperty};
|
||||
pub use source::{
|
||||
DataSource, DbColor, DbDriver, DbExternalTunnel, DbIntrospection, DbOptions, DbProperty, DbSchemaSelection,
|
||||
DbSnowflake, DbSnowflakeAuth, DbSsh, DbSshAuth, DbSslMode, DbTxMode, DbVisibilityChange,
|
||||
DbSnowflake, DbSnowflakeAuth, DbSourceFolder, DbSsh, DbSshAuth, DbSslMode, DbTxMode, DbVisibilityChange,
|
||||
};
|
||||
pub use sql::{CellValue, DbRowEdit, SortKey};
|
||||
|
||||
@@ -146,6 +146,10 @@ pub struct SchemaObject {
|
||||
pub struct TableInfo {
|
||||
pub name: String,
|
||||
pub kind: DbTableKind,
|
||||
/// The table's or view's comment; `None` when it has none, or the engine keeps no comments.
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub comment: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
@@ -157,6 +161,10 @@ pub struct ColumnInfo {
|
||||
pub nullable: bool,
|
||||
pub default: Option<String>,
|
||||
pub primary_key: bool,
|
||||
/// `None` when it has none, or the engine keeps no comments.
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub comment: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
@@ -172,6 +180,10 @@ pub struct IndexInfo {
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[serde(rename = "DbTableDetails")]
|
||||
pub struct TableDetails {
|
||||
/// The table's comment; `None` when it has none, or the engine keeps no comments.
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub comment: Option<String>,
|
||||
pub columns: Vec<ColumnInfo>,
|
||||
pub indexes: Vec<IndexInfo>,
|
||||
pub foreign_keys: Vec<ForeignKey>,
|
||||
@@ -200,6 +212,10 @@ pub struct CompletionColumn {
|
||||
pub primary_key: bool,
|
||||
/// Has a default (or is generated): optional in INSERT.
|
||||
pub has_default: bool,
|
||||
/// The column's comment; `None` when it has none, or the engine keeps no comments.
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub comment: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
@@ -297,6 +313,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).
|
||||
@@ -558,6 +576,18 @@ impl DbManager {
|
||||
None => {}
|
||||
}
|
||||
source::save(&self.root, &project)?;
|
||||
if let Ok(mut folders) = source::load_folders(&self.root) {
|
||||
let known: std::collections::HashSet<&str> = sources.iter().map(|source| source.id.as_str()).collect();
|
||||
let mut changed = false;
|
||||
for folder in &mut folders {
|
||||
let before = folder.sources.len();
|
||||
folder.sources.retain(|id| known.contains(id.as_str()));
|
||||
changed |= folder.sources.len() != before;
|
||||
}
|
||||
if changed {
|
||||
source::save_folders(&self.root, &folders)?;
|
||||
}
|
||||
}
|
||||
old
|
||||
};
|
||||
for o in old {
|
||||
@@ -1093,7 +1123,11 @@ impl DbManager {
|
||||
.filter_map(|r| {
|
||||
let mut it = r.into_iter();
|
||||
let name = it.next().flatten()?;
|
||||
Some(TableInfo { name, kind: DbTableKind::from_catalog(it.next().flatten().as_deref()) })
|
||||
Some(TableInfo {
|
||||
name,
|
||||
kind: DbTableKind::from_catalog(it.next().flatten().as_deref()),
|
||||
comment: it.next().flatten().filter(|comment| !comment.is_empty()),
|
||||
})
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
@@ -1117,11 +1151,18 @@ impl DbManager {
|
||||
let nullable = flag(&it.next().flatten());
|
||||
let default = it.next().flatten();
|
||||
let primary_key = flag(&it.next().flatten());
|
||||
Some(ColumnInfo { name, data_type, nullable, default, primary_key })
|
||||
let comment = it.next().flatten().filter(|c| !c.is_empty());
|
||||
Some(ColumnInfo { name, data_type, nullable, default, primary_key, comment })
|
||||
})
|
||||
.collect();
|
||||
if driver == DbDriver::Jdbc {
|
||||
return Ok(TableDetails { columns, indexes: vec![], foreign_keys: vec![], triggers: vec![] });
|
||||
return Ok(TableDetails {
|
||||
comment: None,
|
||||
columns,
|
||||
indexes: vec![],
|
||||
foreign_keys: vec![],
|
||||
triggers: vec![],
|
||||
});
|
||||
}
|
||||
let mut indexes: Vec<IndexInfo> = Vec::new();
|
||||
for r in pool.rows(&sql::indexes(driver, schema, table), MAX_META_ROWS).await? {
|
||||
@@ -1173,7 +1214,17 @@ impl DbManager {
|
||||
Some(TriggerInfo { name, timing, events })
|
||||
})
|
||||
.collect();
|
||||
Ok(TableDetails { columns, indexes, foreign_keys, triggers })
|
||||
let comment = match sql::table_comment(driver, schema, table) {
|
||||
Some(q) => pool.rows(&q, 1).await.map_or_else(
|
||||
|e| {
|
||||
tracing::warn!("table comment: {}", e.message);
|
||||
None
|
||||
},
|
||||
|rows| rows.into_iter().next().and_then(|r| r.into_iter().next().flatten()).filter(|c| !c.is_empty()),
|
||||
),
|
||||
None => None,
|
||||
};
|
||||
Ok(TableDetails { comment, columns, indexes, foreign_keys, triggers })
|
||||
}
|
||||
|
||||
/// The object privileges granted on `table`; empty, without a query, on the engines
|
||||
@@ -1383,10 +1434,13 @@ impl DbManager {
|
||||
}
|
||||
DbDriver::Postgres => {
|
||||
let rel = pool.rows(&sql::postgres_relation(schema, name), 1).await?.into_iter().next();
|
||||
let (oid, kind) = match rel.as_deref() {
|
||||
Some([Some(oid), Some(kind)]) => {
|
||||
(oid.parse::<u32>().map_err(|e| IdeError::invalid(e.to_string()))?, kind.clone())
|
||||
}
|
||||
let (oid, kind, owner, comment) = match rel.as_deref() {
|
||||
Some([Some(oid), Some(kind), owner, comment]) => (
|
||||
oid.parse::<u32>().map_err(|e| IdeError::invalid(e.to_string()))?,
|
||||
kind.clone(),
|
||||
owner.clone(),
|
||||
comment.clone(),
|
||||
),
|
||||
_ => return Err(missing()),
|
||||
};
|
||||
if kind == "v" || kind == "m" {
|
||||
@@ -1407,6 +1461,7 @@ impl DbManager {
|
||||
data_type: it.next().flatten().unwrap_or_default(),
|
||||
not_null: flag(&it.next().flatten()),
|
||||
default: it.next().flatten(),
|
||||
comment: it.next().flatten(),
|
||||
})
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
@@ -1420,7 +1475,18 @@ impl DbManager {
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let indexes = cells(pool.rows(&sql::postgres_ddl_indexes(oid), MAX_META_ROWS).await?, 0);
|
||||
Ok(sql::postgres_table_ddl(schema, name, &columns, &constraints, &indexes))
|
||||
let grants = pool
|
||||
.rows(&sql::postgres_ddl_grants(oid), MAX_META_ROWS)
|
||||
.await?
|
||||
.into_iter()
|
||||
.filter_map(|r| {
|
||||
let mut it = r.into_iter();
|
||||
Some((it.next().flatten()?, it.next().flatten()?, flag(&it.next().flatten())))
|
||||
})
|
||||
.collect();
|
||||
let triggers = cells(pool.rows(&sql::postgres_ddl_triggers(oid), MAX_META_ROWS).await?, 0);
|
||||
let extras = sql::DdlExtras { comment, owner, grants, triggers };
|
||||
Ok(sql::postgres_table_ddl(schema, name, &columns, &constraints, &indexes, &extras))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1429,13 +1495,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);
|
||||
@@ -1447,6 +1534,7 @@ impl DbManager {
|
||||
nullable: flag(&Some(next())),
|
||||
primary_key: flag(&Some(next())),
|
||||
has_default: flag(&Some(next())),
|
||||
comment: Some(next()).filter(|c| !c.trim().is_empty()),
|
||||
};
|
||||
if name.is_empty() || column.name.is_empty() {
|
||||
continue;
|
||||
@@ -1471,16 +1559,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 })
|
||||
}
|
||||
|
||||
|
||||
@@ -113,7 +113,11 @@ pub(crate) async fn tables(pool: &SnowflakePool, schema: &str) -> IdeResult<Vec<
|
||||
Ok(shown
|
||||
.records()
|
||||
.filter_map(|r| {
|
||||
Some(TableInfo { name: r.get("name")?.to_owned(), kind: table_kind(r.get("kind").unwrap_or("TABLE")) })
|
||||
Some(TableInfo {
|
||||
name: r.get("name")?.to_owned(),
|
||||
kind: table_kind(r.get("kind").unwrap_or("TABLE")),
|
||||
comment: r.get("comment").filter(|comment| !comment.is_empty()).map(str::to_owned),
|
||||
})
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
@@ -132,6 +136,7 @@ pub(crate) async fn table_details(pool: &SnowflakePool, schema: &str, table: &st
|
||||
nullable: yes(r.get("null?")),
|
||||
default: r.get("default").filter(|d| !d.is_empty()).map(str::to_owned),
|
||||
primary_key: yes(r.get("primary key")),
|
||||
comment: r.get("comment").filter(|c| !c.is_empty()).map(str::to_owned),
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
@@ -140,7 +145,16 @@ pub(crate) async fn table_details(pool: &SnowflakePool, schema: &str, table: &st
|
||||
Ok(keys) => foreign_keys(&keys),
|
||||
Err(_) => Vec::new(),
|
||||
};
|
||||
Ok(TableDetails { columns, indexes: Vec::new(), foreign_keys, triggers: Vec::new() })
|
||||
// `LIKE` matches without case and with wildcards: the exact name picks the row.
|
||||
let like = format!("SHOW TABLES LIKE {} IN SCHEMA {}", quote_literal(DRIVER, table), schema_path(pool, schema));
|
||||
let comment = match show(pool, &like).await {
|
||||
Ok(shown) => shown
|
||||
.records()
|
||||
.find(|r| r.get("name") == Some(table))
|
||||
.and_then(|r| r.get("comment").filter(|c| !c.is_empty()).map(str::to_owned)),
|
||||
Err(_) => None,
|
||||
};
|
||||
Ok(TableDetails { comment, columns, indexes: Vec::new(), foreign_keys, triggers: Vec::new() })
|
||||
}
|
||||
|
||||
fn foreign_keys(shown: &Shown) -> Vec<ForeignKey> {
|
||||
@@ -228,7 +242,11 @@ pub(crate) async fn catalog(pool: &SnowflakePool, database: &str) -> IdeResult<V
|
||||
let (Some(&index), Some(name)) = (at.get(r.get("schema_name").unwrap_or_default()), r.get("name")) else {
|
||||
continue;
|
||||
};
|
||||
out[index].tables.push(TableInfo { name: name.to_owned(), kind: table_kind(r.get("kind").unwrap_or("TABLE")) });
|
||||
out[index].tables.push(TableInfo {
|
||||
name: name.to_owned(),
|
||||
kind: table_kind(r.get("kind").unwrap_or("TABLE")),
|
||||
comment: r.get("comment").filter(|comment| !comment.is_empty()).map(str::to_owned),
|
||||
});
|
||||
}
|
||||
for schema in &mut out {
|
||||
schema.tables.sort_by(|a, b| a.name.cmp(&b.name));
|
||||
@@ -437,6 +455,7 @@ pub(crate) async fn completion(pool: &SnowflakePool) -> IdeResult<Vec<Completion
|
||||
primary_key: false,
|
||||
has_default: r.get("default").is_some_and(|d| !d.is_empty())
|
||||
|| r.get("autoincrement").is_some_and(|a| !a.is_empty()),
|
||||
comment: r.get("comment").filter(|c| !c.trim().is_empty()).map(str::to_owned),
|
||||
});
|
||||
}
|
||||
Ok(tables)
|
||||
|
||||
@@ -1,15 +1,17 @@
|
||||
//! Data sources: per-project connection settings in `.openidea/data-sources.toml`, and
|
||||
//! global ones (IDEA's Make Global: listed in every project) in `data-sources.toml` of the
|
||||
//! app data directory. Passwords never go there: saved ones live in [`crate::secrets`],
|
||||
//! app data directory. Project folder grouping is in `.openidea/data-source-folders.toml`.
|
||||
//! Passwords never go there: saved ones live in [`crate::secrets`],
|
||||
//! the others only in memory for the session.
|
||||
|
||||
use ide_core::{IdeError, IdeResult, IpcPath, project_dir};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::collections::BTreeMap;
|
||||
use std::collections::{BTreeMap, HashSet};
|
||||
use std::path::Path;
|
||||
|
||||
pub(crate) const FILE: &str = "data-sources.toml";
|
||||
pub(crate) const FOLDERS_FILE: &str = "data-source-folders.toml";
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
@@ -697,6 +699,108 @@ fn write(path: &Path, sources: &[DataSource]) -> IdeResult<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A user folder grouping data sources in one project's Database tree.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct DbSourceFolder {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
/// Reserved for nested folders; the first UI version only creates root folders.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub parent: Option<String>,
|
||||
pub order: i32,
|
||||
pub sources: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
struct SourceFoldersFile {
|
||||
#[serde(default = "folders_version")]
|
||||
version: u32,
|
||||
#[serde(default, rename = "folder")]
|
||||
folders: Vec<DbSourceFolder>,
|
||||
}
|
||||
|
||||
fn folders_version() -> u32 {
|
||||
1
|
||||
}
|
||||
|
||||
/// The project's data source folders and their members.
|
||||
pub fn load_folders(root: &Path) -> IdeResult<Vec<DbSourceFolder>> {
|
||||
let path = project_dir::path(root, FOLDERS_FILE);
|
||||
let text = match std::fs::read_to_string(&path) {
|
||||
Ok(text) => text,
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
|
||||
Err(e) => return Err(e.into()),
|
||||
};
|
||||
let file: SourceFoldersFile =
|
||||
toml::from_str(&text).map_err(|e| IdeError::invalid(format!("{}: {e}", path.display())))?;
|
||||
if file.version > 1 {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"{}: folder format version {} is newer than this OpenIDEA",
|
||||
path.display(),
|
||||
file.version
|
||||
)));
|
||||
}
|
||||
Ok(file.folders)
|
||||
}
|
||||
|
||||
/// Replaces the project's data source folders after validating ids, parents and memberships.
|
||||
pub fn save_folders(root: &Path, folders: &[DbSourceFolder]) -> IdeResult<()> {
|
||||
validate_folders(folders)?;
|
||||
let path = project_dir::path(root, FOLDERS_FILE);
|
||||
if let Some(dir) = path.parent() {
|
||||
std::fs::create_dir_all(dir)?;
|
||||
}
|
||||
let file = SourceFoldersFile { version: folders_version(), folders: folders.to_vec() };
|
||||
let text = toml::to_string_pretty(&file).map_err(|e| IdeError::internal(e.to_string()))?;
|
||||
let tmp = path.with_file_name(format!(".{FOLDERS_FILE}.{}.tmp", uuid::Uuid::new_v4()));
|
||||
std::fs::write(&tmp, text)?;
|
||||
if let Err(e) = std::fs::rename(&tmp, &path) {
|
||||
let _ = std::fs::remove_file(&tmp);
|
||||
return Err(e.into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_folders(folders: &[DbSourceFolder]) -> IdeResult<()> {
|
||||
let mut ids = HashSet::new();
|
||||
let mut members = HashSet::new();
|
||||
for folder in folders {
|
||||
if folder.id.trim().is_empty() || folder.name.trim().is_empty() {
|
||||
return Err(IdeError::invalid("every data source folder needs an id and a name"));
|
||||
}
|
||||
if !ids.insert(folder.id.as_str()) {
|
||||
return Err(IdeError::invalid(format!("duplicate data source folder id '{}'", folder.id)));
|
||||
}
|
||||
for source in &folder.sources {
|
||||
if source.is_empty() {
|
||||
return Err(IdeError::invalid(format!("folder '{}' has an empty data source id", folder.name)));
|
||||
}
|
||||
if !members.insert(source.as_str()) {
|
||||
return Err(IdeError::invalid(format!("data source '{source}' belongs to more than one folder")));
|
||||
}
|
||||
}
|
||||
}
|
||||
for folder in folders {
|
||||
let mut seen = HashSet::new();
|
||||
let mut parent = folder.parent.as_deref();
|
||||
while let Some(id) = parent {
|
||||
if id == folder.id || !seen.insert(id) {
|
||||
return Err(IdeError::invalid(format!("data source folder '{}' has a parent cycle", folder.name)));
|
||||
}
|
||||
parent =
|
||||
folders.iter().find(|candidate| candidate.id == id).and_then(|candidate| candidate.parent.as_deref());
|
||||
if parent.is_none() && !folders.iter().any(|candidate| candidate.id == id) {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"data source folder '{}' has an unknown parent '{id}'",
|
||||
folder.name
|
||||
)));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Credential store access. Blocking (may show an OS prompt): call off the async runtime.
|
||||
/// Keys are data source ids; [`secrets::ssh_key`] names the SSH password / passphrase.
|
||||
#[cfg(test)]
|
||||
@@ -724,6 +828,38 @@ mod tests {
|
||||
assert!(save(tmp.path(), &[DataSource::default()]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn source_folders_round_trip_and_reject_invalid_memberships() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let folders = vec![
|
||||
DbSourceFolder {
|
||||
id: "prod".into(),
|
||||
name: "Production".into(),
|
||||
parent: None,
|
||||
order: 0,
|
||||
sources: vec!["pg".into(), "mysql".into()],
|
||||
},
|
||||
DbSourceFolder { id: "empty".into(), name: "Empty".into(), parent: None, order: 1, sources: vec![] },
|
||||
];
|
||||
save_folders(tmp.path(), &folders).unwrap();
|
||||
assert_eq!(load_folders(tmp.path()).unwrap(), folders);
|
||||
|
||||
let duplicate = vec![
|
||||
DbSourceFolder { sources: vec!["pg".into()], ..folders[0].clone() },
|
||||
DbSourceFolder { id: "other".into(), sources: vec!["pg".into()], ..folders[1].clone() },
|
||||
];
|
||||
assert!(save_folders(tmp.path(), &duplicate).is_err());
|
||||
|
||||
let cycle = vec![
|
||||
DbSourceFolder { parent: Some("b".into()), ..folders[0].clone() },
|
||||
DbSourceFolder { id: "b".into(), parent: Some("prod".into()), ..folders[1].clone() },
|
||||
];
|
||||
assert!(save_folders(tmp.path(), &cycle).is_err());
|
||||
|
||||
let missing = vec![DbSourceFolder { parent: Some("missing".into()), ..folders[0].clone() }];
|
||||
assert!(save_folders(tmp.path(), &missing).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_configs_written_before_the_new_settings() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
+304
-72
@@ -95,46 +95,52 @@ pub fn schemas(driver: DbDriver, system: bool) -> &'static str {
|
||||
}
|
||||
}
|
||||
|
||||
/// Rows: `name, kind` where kind is `table`, `view` or `materialized view`.
|
||||
/// Rows: `name, kind, comment` where kind is `table`, `view` or `materialized view`.
|
||||
pub fn tables(driver: DbDriver, schema: &str) -> String {
|
||||
match driver {
|
||||
DbDriver::Jdbc => unreachable!("JDBC introspection uses DatabaseMetaData"),
|
||||
DbDriver::Clickhouse => format!(
|
||||
"SELECT name, CASE engine WHEN 'View' THEN 'view' WHEN 'MaterializedView' THEN 'materialized view' \
|
||||
WHEN 'WindowView' THEN 'view' ELSE 'table' END FROM system.tables \
|
||||
WHEN 'WindowView' THEN 'view' ELSE 'table' END, comment FROM system.tables \
|
||||
WHERE database = {} AND is_temporary = 0 ORDER BY name",
|
||||
quote_literal(driver, schema)
|
||||
),
|
||||
DbDriver::Sqlite => format!(
|
||||
"SELECT name, type FROM {}.sqlite_master WHERE type IN ('table', 'view') \
|
||||
"SELECT name, type, NULL FROM {}.sqlite_master WHERE type IN ('table', 'view') \
|
||||
AND name NOT LIKE 'sqlite\\_%' ESCAPE '\\' ORDER BY name",
|
||||
quote_ident(driver, schema)
|
||||
),
|
||||
DbDriver::Snowflake => format!(
|
||||
"SELECT table_name, CASE table_type WHEN 'VIEW' THEN 'view' WHEN 'MATERIALIZED VIEW' THEN 'materialized view' \
|
||||
ELSE 'table' END FROM information_schema.tables WHERE table_schema = {} ORDER BY 1",
|
||||
ELSE 'table' END, comment FROM information_schema.tables WHERE table_schema = {} ORDER BY 1",
|
||||
quote_literal(driver, schema)
|
||||
),
|
||||
DbDriver::Oracle => format!(
|
||||
"SELECT table_name, 'table' FROM all_tables WHERE owner = {} \
|
||||
UNION ALL SELECT view_name, 'view' FROM all_views WHERE owner = {} ORDER BY 1",
|
||||
quote_literal(driver, schema),
|
||||
"SELECT table_name, CASE WHEN table_type = 'VIEW' THEN 'view' ELSE 'table' END, comments \
|
||||
FROM all_tab_comments WHERE owner = {} ORDER BY 1",
|
||||
quote_literal(driver, schema)
|
||||
),
|
||||
DbDriver::Postgres => format!(
|
||||
"SELECT c.relname, CASE c.relkind WHEN 'v' THEN 'view' WHEN 'm' THEN 'materialized view' ELSE 'table' END \
|
||||
"SELECT c.relname, CASE c.relkind WHEN 'v' THEN 'view' WHEN 'm' THEN 'materialized view' ELSE 'table' END, \
|
||||
obj_description(c.oid, 'pg_class') \
|
||||
FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace \
|
||||
WHERE n.nspname = {} AND c.relkind IN ('r', 'v', 'm', 'p', 'f') ORDER BY 1",
|
||||
quote_literal(driver, schema)
|
||||
),
|
||||
DbDriver::Mysql => format!(
|
||||
"SELECT table_name, CASE WHEN table_type LIKE '%VIEW%' THEN 'view' ELSE 'table' END \
|
||||
"SELECT table_name, CASE WHEN table_type LIKE '%VIEW%' THEN 'view' ELSE 'table' END, \
|
||||
CASE WHEN table_type LIKE '%VIEW%' THEN NULL ELSE NULLIF(table_comment, '') END \
|
||||
FROM information_schema.tables WHERE table_schema = {} ORDER BY 1",
|
||||
quote_literal(driver, schema)
|
||||
),
|
||||
DbDriver::SqlServer => format!(
|
||||
"SELECT TABLE_NAME, CASE WHEN TABLE_TYPE LIKE '%VIEW%' THEN 'view' ELSE 'table' END \
|
||||
FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = {} ORDER BY 1",
|
||||
"SELECT t.TABLE_NAME, CASE WHEN t.TABLE_TYPE LIKE '%VIEW%' THEN 'view' ELSE 'table' END, \
|
||||
CAST(ep.value AS nvarchar(max)) \
|
||||
FROM INFORMATION_SCHEMA.TABLES t \
|
||||
LEFT JOIN sys.extended_properties ep \
|
||||
ON ep.major_id = OBJECT_ID(QUOTENAME(t.TABLE_SCHEMA) + '.' + QUOTENAME(t.TABLE_NAME)) \
|
||||
AND ep.minor_id = 0 AND ep.name = 'MS_Description' \
|
||||
WHERE t.TABLE_SCHEMA = {} ORDER BY 1",
|
||||
quote_literal(driver, schema)
|
||||
),
|
||||
}
|
||||
@@ -145,7 +151,8 @@ const SNOWFLAKE_TYPE: &str = "CASE WHEN data_type = 'NUMBER' THEN 'NUMBER(' || n
|
||||
WHEN data_type = 'TEXT' THEN 'VARCHAR(' || character_maximum_length || ')' \
|
||||
WHEN data_type LIKE 'TIME%' THEN data_type || '(' || datetime_precision || ')' ELSE data_type END";
|
||||
|
||||
/// Rows: `name, type, nullable (YES/NO or 0/1), default, is_pk (0/1)`.
|
||||
/// Rows: `name, type, nullable (YES/NO or 0/1), default, is_pk (0/1)`, and the column's
|
||||
/// comment on the engines that keep one (PostgreSQL, MySQL, Oracle, ClickHouse).
|
||||
pub fn columns(driver: DbDriver, schema: &str, table: &str) -> String {
|
||||
let (s, t) = (quote_literal(driver, schema), quote_literal(driver, table));
|
||||
match driver {
|
||||
@@ -153,7 +160,7 @@ pub fn columns(driver: DbDriver, schema: &str, table: &str) -> String {
|
||||
DbDriver::Clickhouse => format!(
|
||||
"SELECT name, type, CASE WHEN startsWith(type, 'Nullable(') \
|
||||
OR startsWith(type, 'LowCardinality(Nullable(') THEN 'YES' ELSE 'NO' END, \
|
||||
if(default_kind = '', NULL, default_expression), is_in_primary_key \
|
||||
if(default_kind = '', NULL, default_expression), is_in_primary_key, comment \
|
||||
FROM system.columns WHERE database = {s} AND table = {t} ORDER BY position"
|
||||
),
|
||||
DbDriver::Sqlite => format!(
|
||||
@@ -166,13 +173,14 @@ pub fn columns(driver: DbDriver, schema: &str, table: &str) -> String {
|
||||
JOIN information_schema.key_column_usage k ON k.constraint_name = tc.constraint_name \
|
||||
AND k.table_schema = tc.table_schema AND k.table_name = tc.table_name \
|
||||
WHERE tc.constraint_type = 'PRIMARY KEY' AND tc.table_schema = c.table_schema \
|
||||
AND tc.table_name = c.table_name AND k.column_name = c.column_name) THEN 1 ELSE 0 END \
|
||||
AND tc.table_name = c.table_name AND k.column_name = c.column_name) THEN 1 ELSE 0 END, \
|
||||
col_description(format('%I.%I', c.table_schema, c.table_name)::regclass, c.ordinal_position::int) \
|
||||
FROM information_schema.columns c WHERE c.table_schema = {s} AND c.table_name = {t} \
|
||||
ORDER BY c.ordinal_position"
|
||||
),
|
||||
DbDriver::Mysql => format!(
|
||||
"SELECT column_name, column_type, is_nullable, column_default, \
|
||||
CASE WHEN column_key = 'PRI' THEN 1 ELSE 0 END \
|
||||
CASE WHEN column_key = 'PRI' THEN 1 ELSE 0 END, column_comment \
|
||||
FROM information_schema.columns WHERE table_schema = {s} AND table_name = {t} \
|
||||
ORDER BY ordinal_position"
|
||||
),
|
||||
@@ -192,8 +200,10 @@ pub fn columns(driver: DbDriver, schema: &str, table: &str) -> String {
|
||||
),
|
||||
DbDriver::Oracle => format!(
|
||||
"SELECT c.column_name, c.data_type, DECODE(c.nullable, 'Y', 'YES', 'NO'), c.data_default, \
|
||||
CASE WHEN k.column_name IS NOT NULL THEN 1 ELSE 0 END \
|
||||
CASE WHEN k.column_name IS NOT NULL THEN 1 ELSE 0 END, cc.comments \
|
||||
FROM all_tab_columns c \
|
||||
LEFT JOIN all_col_comments cc ON cc.owner = c.owner AND cc.table_name = c.table_name \
|
||||
AND cc.column_name = c.column_name \
|
||||
LEFT JOIN (SELECT kc.column_name FROM all_constraints con \
|
||||
JOIN all_cons_columns kc ON kc.owner = con.owner AND kc.table_name = con.table_name \
|
||||
AND kc.constraint_name = con.constraint_name \
|
||||
@@ -204,6 +214,28 @@ pub fn columns(driver: DbDriver, schema: &str, table: &str) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// One row, one column: the table's comment (`NULL` or empty for none). `None` for the
|
||||
/// engines whose comments the IDE doesn't read here (Snowflake reads it with `SHOW`).
|
||||
pub fn table_comment(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 obj_description(c.oid, 'pg_class') FROM pg_class c \
|
||||
JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = {s} AND c.relname = {t}"
|
||||
)),
|
||||
// A view's `table_comment` is the word `VIEW`.
|
||||
DbDriver::Mysql => Some(format!(
|
||||
"SELECT CASE WHEN table_type = 'VIEW' THEN NULL ELSE table_comment END \
|
||||
FROM information_schema.tables WHERE table_schema = {s} AND table_name = {t}"
|
||||
)),
|
||||
DbDriver::Oracle => {
|
||||
Some(format!("SELECT comments FROM all_tab_comments WHERE owner = {s} AND table_name = {t}"))
|
||||
}
|
||||
DbDriver::Clickhouse => Some(format!("SELECT comment FROM system.tables WHERE database = {s} AND name = {t}")),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Rows: `index name, unique (0/1), column` (one row per indexed column, in order).
|
||||
// Key columns are paired from one series up to `max_index_keys` (the server's INDEX_MAX_KEYS, the
|
||||
// most columns an index or key has): unlike a series per catalog row, it lets the planner find the
|
||||
@@ -252,54 +284,72 @@ 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 \
|
||||
OR startsWith(c.type, 'LowCardinality(Nullable(') THEN 'YES' ELSE 'NO' END, c.is_in_primary_key, 1, c.comment \
|
||||
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 \
|
||||
AND (SELECT count(*) FROM pragma_table_info(m.name) k WHERE k.pk > 0) = 1 THEN 1 ELSE 0 END, NULL \
|
||||
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 \
|
||||
AND a.attnum = ANY(i.indkey)) THEN 1 ELSE 0 END, \
|
||||
CASE WHEN a.atthasdef OR EXISTS (SELECT 1 FROM pg_depend d WHERE d.refclassid = 'pg_class'::regclass \
|
||||
AND d.refobjid = c.oid AND d.refobjsubid = a.attnum AND d.classid = 'pg_class'::regclass \
|
||||
AND d.deptype = 'i') THEN 1 ELSE 0 END \
|
||||
AND d.deptype = 'i') THEN 1 ELSE 0 END, col_description(c.oid, a.attnum) \
|
||||
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 \
|
||||
CASE WHEN c.column_default IS NOT NULL OR c.extra LIKE '%auto_increment%' THEN 1 ELSE 0 END, c.column_comment \
|
||||
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 \
|
||||
@@ -307,37 +357,53 @@ pub fn completion_columns(driver: DbDriver) -> &'static str {
|
||||
AND k.TABLE_SCHEMA = tc.TABLE_SCHEMA AND k.TABLE_NAME = tc.TABLE_NAME \
|
||||
WHERE tc.CONSTRAINT_TYPE = 'PRIMARY KEY' AND tc.TABLE_SCHEMA = c.TABLE_SCHEMA \
|
||||
AND tc.TABLE_NAME = c.TABLE_NAME AND k.COLUMN_NAME = c.COLUMN_NAME) THEN 1 ELSE 0 END, \
|
||||
CASE WHEN c.COLUMN_DEFAULT IS NOT NULL THEN 1 ELSE 0 END \
|
||||
CASE WHEN c.COLUMN_DEFAULT IS NOT NULL THEN 1 ELSE 0 END, NULL \
|
||||
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 \
|
||||
c.is_nullable, 0, CASE WHEN c.column_default IS NOT NULL THEN 1 ELSE 0 END, c.comment \
|
||||
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, \
|
||||
CASE WHEN c.data_default IS NOT NULL THEN 1 ELSE 0 END \
|
||||
CASE WHEN c.data_default IS NOT NULL THEN 1 ELSE 0 END, cc.comments \
|
||||
FROM all_tab_columns c \
|
||||
LEFT JOIN all_col_comments cc ON cc.owner = c.owner AND cc.table_name = c.table_name \
|
||||
AND cc.column_name = c.column_name \
|
||||
LEFT JOIN all_views v ON v.owner = c.owner AND v.view_name = c.table_name \
|
||||
LEFT JOIN (SELECT con.owner, con.table_name, kc.column_name FROM all_constraints con \
|
||||
JOIN all_cons_columns kc ON kc.owner = con.owner AND kc.table_name = con.table_name \
|
||||
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`
|
||||
@@ -600,21 +666,22 @@ pub fn sqlite_ddl(schema: &str, name: &str) -> String {
|
||||
)
|
||||
}
|
||||
|
||||
/// Rows: `oid, relkind` of a PostgreSQL relation.
|
||||
/// Rows: `oid, relkind, owner, comment` of a PostgreSQL relation.
|
||||
pub fn postgres_relation(schema: &str, name: &str) -> String {
|
||||
format!(
|
||||
"SELECT c.oid::text, c.relkind::text FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace \
|
||||
"SELECT c.oid::text, c.relkind::text, pg_get_userbyid(c.relowner), obj_description(c.oid, 'pg_class') \
|
||||
FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace \
|
||||
WHERE n.nspname = {} AND c.relname = {}",
|
||||
quote_literal(DbDriver::Postgres, schema),
|
||||
quote_literal(DbDriver::Postgres, name)
|
||||
)
|
||||
}
|
||||
|
||||
/// Rows: `name, type, not null (0/1), default` of relation `oid`.
|
||||
/// Rows: `name, type, not null (0/1), default, comment` of relation `oid`.
|
||||
pub fn postgres_ddl_columns(oid: u32) -> String {
|
||||
format!(
|
||||
"SELECT a.attname, format_type(a.atttypid, a.atttypmod), CASE WHEN a.attnotnull THEN 1 ELSE 0 END, \
|
||||
pg_get_expr(d.adbin, d.adrelid) FROM pg_attribute a \
|
||||
pg_get_expr(d.adbin, d.adrelid), col_description(a.attrelid, a.attnum) FROM pg_attribute a \
|
||||
LEFT JOIN pg_attrdef d ON d.adrelid = a.attrelid AND d.adnum = a.attnum \
|
||||
WHERE a.attrelid = {oid} AND a.attnum > 0 AND NOT a.attisdropped ORDER BY a.attnum"
|
||||
)
|
||||
@@ -637,6 +704,27 @@ pub fn postgres_ddl_indexes(oid: u32) -> String {
|
||||
)
|
||||
}
|
||||
|
||||
/// Rows: `grantee` (`PUBLIC` for everyone), privileges (`insert, select`), grantable (0/1) of
|
||||
/// the privileges relation `oid` grants beyond its owner's. A relation whose ACL was never
|
||||
/// changed (`relacl` null) grants none.
|
||||
pub fn postgres_ddl_grants(oid: u32) -> String {
|
||||
format!(
|
||||
"SELECT CASE WHEN a.grantee = 0 THEN 'PUBLIC' ELSE pg_get_userbyid(a.grantee) END, \
|
||||
string_agg(lower(a.privilege_type), ', ' ORDER BY a.privilege_type), \
|
||||
CASE WHEN a.is_grantable THEN 1 ELSE 0 END \
|
||||
FROM pg_class c CROSS JOIN LATERAL aclexplode(c.relacl) a \
|
||||
WHERE c.oid = {oid} AND a.grantee <> c.relowner GROUP BY 1, 3 ORDER BY 1, 3"
|
||||
)
|
||||
}
|
||||
|
||||
/// Rows: `CREATE TRIGGER …` of the user triggers of relation `oid`.
|
||||
pub fn postgres_ddl_triggers(oid: u32) -> String {
|
||||
format!(
|
||||
"SELECT pg_get_triggerdef(oid, true) FROM pg_trigger WHERE tgrelid = {oid} AND NOT tgisinternal \
|
||||
ORDER BY tgname"
|
||||
)
|
||||
}
|
||||
|
||||
/// Rows: `name, timing, events` of the triggers of a table (SQLite: `name, sql`).
|
||||
pub fn triggers(driver: DbDriver, schema: &str, table: &str) -> String {
|
||||
let (s, t) = (quote_literal(driver, schema), quote_literal(driver, table));
|
||||
@@ -876,6 +964,18 @@ pub struct DdlColumn {
|
||||
pub data_type: String,
|
||||
pub not_null: bool,
|
||||
pub default: Option<String>,
|
||||
pub comment: Option<String>,
|
||||
}
|
||||
|
||||
/// What [`postgres_table_ddl`] adds after `create table` so the script rebuilds the table.
|
||||
#[derive(Default)]
|
||||
pub struct DdlExtras {
|
||||
pub comment: Option<String>,
|
||||
pub owner: Option<String>,
|
||||
/// `grantee` (`PUBLIC` for everyone), privileges (`insert, select`), with grant option.
|
||||
pub grants: Vec<(String, String, bool)>,
|
||||
/// `CREATE TRIGGER …` statements.
|
||||
pub triggers: Vec<String>,
|
||||
}
|
||||
|
||||
/// `create table` of a PostgreSQL table from its catalog (the server has no `SHOW CREATE`).
|
||||
@@ -885,6 +985,7 @@ pub fn postgres_table_ddl(
|
||||
columns: &[DdlColumn],
|
||||
constraints: &[(String, String)],
|
||||
indexes: &[String],
|
||||
extras: &DdlExtras,
|
||||
) -> String {
|
||||
let d = DbDriver::Postgres;
|
||||
let mut items: Vec<String> = columns
|
||||
@@ -901,9 +1002,31 @@ pub fn postgres_table_ddl(
|
||||
})
|
||||
.collect();
|
||||
items.extend(constraints.iter().map(|(name, def)| format!(" constraint {} {def}", quote_ident(d, name))));
|
||||
let mut out = format!("create table {}\n(\n{}\n);\n", qualified(d, schema, table), items.join(",\n"));
|
||||
for i in indexes {
|
||||
out.push_str(&format!("\n{i};\n"));
|
||||
let target = qualified(d, schema, table);
|
||||
let mut out = format!("create table {target}\n(\n{}\n);\n", items.join(",\n"));
|
||||
// The order a script runs in: comments, owner and privileges, then indexes and triggers.
|
||||
if let Some(comment) = &extras.comment {
|
||||
out.push_str(&format!("\ncomment on table {target} is {};\n", quote_literal(d, comment)));
|
||||
}
|
||||
for c in columns {
|
||||
if let Some(comment) = &c.comment {
|
||||
let column = format!("{target}.{}", quote_ident(d, &c.name));
|
||||
out.push_str(&format!("\ncomment on column {column} is {};\n", quote_literal(d, comment)));
|
||||
}
|
||||
}
|
||||
if let Some(owner) = &extras.owner {
|
||||
out.push_str(&format!("\nalter table {target}\n owner to {};\n", quote_ident(d, owner)));
|
||||
}
|
||||
if !extras.grants.is_empty() {
|
||||
out.push('\n');
|
||||
}
|
||||
for (grantee, privileges, grantable) in &extras.grants {
|
||||
let to = if grantee == "PUBLIC" { "public".to_owned() } else { quote_ident(d, grantee) };
|
||||
let option = if *grantable { " with grant option" } else { "" };
|
||||
out.push_str(&format!("grant {privileges} on {target} to {to}{option};\n"));
|
||||
}
|
||||
for statement in indexes.iter().chain(&extras.triggers) {
|
||||
out.push_str(&format!("\n{};\n", statement.trim_end().trim_end_matches(';')));
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -924,6 +1047,40 @@ mod tests {
|
||||
assert_eq!(quote_literal(DbDriver::Mysql, "it's \\"), "'it''s \\\\'");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn comments_are_read_where_the_engine_keeps_them() {
|
||||
assert!(columns(DbDriver::Postgres, "public", "t").contains("col_description("));
|
||||
assert!(columns(DbDriver::Mysql, "db", "t").contains("column_comment"));
|
||||
assert!(columns(DbDriver::Oracle, "S", "T").contains("all_col_comments"));
|
||||
assert!(columns(DbDriver::Clickhouse, "db", "t").contains("is_in_primary_key, comment"));
|
||||
assert!(tables(DbDriver::Postgres, "public").contains("obj_description(c.oid, 'pg_class')"));
|
||||
assert!(tables(DbDriver::Mysql, "db").contains("table_comment"));
|
||||
assert!(tables(DbDriver::Oracle, "S").contains("all_tab_comments"));
|
||||
assert!(tables(DbDriver::Clickhouse, "db").contains("END, comment FROM system.tables"));
|
||||
assert!(tables(DbDriver::SqlServer, "dbo").contains("sys.extended_properties"));
|
||||
// Completion (the hover card of a table or column) carries them too, as the ninth field.
|
||||
let completion = |driver| completion_columns(driver, CompletionScope::All);
|
||||
assert!(completion(DbDriver::Postgres).contains("col_description(c.oid, a.attnum)"));
|
||||
assert!(completion(DbDriver::Mysql).contains("ELSE 0 END, c.column_comment"));
|
||||
assert!(
|
||||
completion(DbDriver::Oracle).contains("cc.comments")
|
||||
&& completion(DbDriver::Oracle).contains("all_col_comments")
|
||||
);
|
||||
assert!(completion(DbDriver::Clickhouse).contains("c.is_in_primary_key, 1, c.comment"));
|
||||
assert!(completion(DbDriver::Snowflake).contains("ELSE 0 END, c.comment"));
|
||||
for driver in [DbDriver::Sqlite, DbDriver::SqlServer] {
|
||||
assert!(completion(driver).contains("ELSE 0 END, NULL"), "{driver:?}");
|
||||
}
|
||||
let pg = table_comment(DbDriver::Postgres, "public", "o'rders").unwrap();
|
||||
assert!(pg.contains("obj_description(c.oid, 'pg_class')") && pg.contains("'o''rders'"), "{pg}");
|
||||
assert!(table_comment(DbDriver::Mysql, "db", "t").unwrap().contains("table_comment"));
|
||||
assert!(table_comment(DbDriver::Oracle, "S", "T").unwrap().contains("all_tab_comments"));
|
||||
assert!(table_comment(DbDriver::Clickhouse, "db", "t").unwrap().contains("system.tables"));
|
||||
for driver in [DbDriver::Sqlite, DbDriver::SqlServer, DbDriver::Snowflake] {
|
||||
assert_eq!(table_comment(driver, "s", "t"), None);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clickhouse_escapes_backslashes_and_delimiters() {
|
||||
let driver = DbDriver::Clickhouse;
|
||||
@@ -941,6 +1098,7 @@ mod tests {
|
||||
assert_eq!(current_schema(driver), Some("SELECT currentDatabase()"));
|
||||
let relations = tables(driver, "event's\\db");
|
||||
assert!(relations.contains("WHEN 'MaterializedView' THEN 'materialized view'"));
|
||||
assert!(relations.contains(r"END, comment FROM system.tables"));
|
||||
assert!(relations.contains(r"WHERE database = 'event''s\\db' AND is_temporary = 0"));
|
||||
let fields = columns(driver, "default", "events");
|
||||
assert!(fields.starts_with("SELECT name, type, CASE WHEN startsWith(type, 'Nullable(')"));
|
||||
@@ -950,7 +1108,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"));
|
||||
}
|
||||
@@ -1056,11 +1214,12 @@ mod tests {
|
||||
#[test]
|
||||
fn sqlserver_introspection_queries() {
|
||||
assert!(tables(DbDriver::SqlServer, "dbo").contains("INFORMATION_SCHEMA.TABLES"));
|
||||
assert!(tables(DbDriver::SqlServer, "dbo").contains("sys.extended_properties"));
|
||||
assert!(columns(DbDriver::SqlServer, "dbo", "t").contains("INFORMATION_SCHEMA.COLUMNS"));
|
||||
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:
|
||||
@@ -1074,7 +1233,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(),
|
||||
@@ -1132,8 +1291,10 @@ mod tests {
|
||||
assert_eq!(DbDriver::Oracle.default_port(), Some(1521));
|
||||
assert!(schemas(DbDriver::Oracle, true).contains("all_users"));
|
||||
assert!(schemas(DbDriver::Oracle, false).contains("'MDSYS'"));
|
||||
assert!(tables(DbDriver::Oracle, "hr").contains("all_tables"));
|
||||
assert!(tables(DbDriver::Oracle, "hr").contains("all_views"));
|
||||
let relations = tables(DbDriver::Oracle, "hr");
|
||||
assert!(relations.contains("all_tab_comments"));
|
||||
assert!(relations.contains("table_type = 'VIEW'"));
|
||||
assert!(relations.contains("comments"));
|
||||
let cols = columns(DbDriver::Oracle, "hr", "employees");
|
||||
assert!(cols.contains("all_tab_columns"));
|
||||
assert!(cols.contains("DECODE(c.nullable, 'Y', 'YES', 'NO')"));
|
||||
@@ -1141,7 +1302,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'"));
|
||||
@@ -1222,12 +1383,13 @@ mod tests {
|
||||
#[test]
|
||||
fn postgres_ddl() {
|
||||
let cols = [
|
||||
DdlColumn { name: "id".into(), data_type: "integer".into(), not_null: true, default: None },
|
||||
DdlColumn { name: "id".into(), data_type: "integer".into(), not_null: true, default: None, comment: None },
|
||||
DdlColumn {
|
||||
name: "name".into(),
|
||||
data_type: "character varying(40)".into(),
|
||||
not_null: false,
|
||||
default: Some("'x'::character varying".into()),
|
||||
comment: None,
|
||||
},
|
||||
];
|
||||
assert_eq!(
|
||||
@@ -1236,12 +1398,53 @@ mod tests {
|
||||
"t",
|
||||
&cols,
|
||||
&[("t_pkey".into(), "PRIMARY KEY (id)".into())],
|
||||
&["CREATE INDEX t_name ON public.t USING btree (name)".into()]
|
||||
&["CREATE INDEX t_name ON public.t USING btree (name)".into()],
|
||||
&DdlExtras::default(),
|
||||
),
|
||||
"create table \"public\".\"t\"\n(\n \"id\" integer not null,\n \"name\" character varying(40) default 'x'::character varying,\n constraint \"t_pkey\" PRIMARY KEY (id)\n);\n\nCREATE INDEX t_name ON public.t USING btree (name);\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn postgres_ddl_rebuilds_comments_owner_grants_and_triggers() {
|
||||
let cols = [
|
||||
DdlColumn { name: "id".into(), data_type: "integer".into(), not_null: true, default: None, comment: None },
|
||||
DdlColumn {
|
||||
name: "note".into(),
|
||||
data_type: "text".into(),
|
||||
not_null: false,
|
||||
default: None,
|
||||
comment: Some("what's this".into()),
|
||||
},
|
||||
];
|
||||
let extras = DdlExtras {
|
||||
comment: Some("Orders".into()),
|
||||
owner: Some("app owner".into()),
|
||||
grants: vec![("PUBLIC".into(), "select".into(), false), ("reader".into(), "insert, select".into(), true)],
|
||||
triggers: vec![
|
||||
"CREATE TRIGGER t_audit AFTER INSERT ON public.t FOR EACH ROW EXECUTE FUNCTION audit()".into(),
|
||||
],
|
||||
};
|
||||
assert_eq!(
|
||||
postgres_table_ddl(
|
||||
"public",
|
||||
"t",
|
||||
&cols,
|
||||
&[],
|
||||
&["CREATE INDEX t_note ON public.t USING btree (note)".into()],
|
||||
&extras
|
||||
),
|
||||
"create table \"public\".\"t\"\n(\n \"id\" integer not null,\n \"note\" text\n);\n\
|
||||
\ncomment on table \"public\".\"t\" is 'Orders';\n\
|
||||
\ncomment on column \"public\".\"t\".\"note\" is 'what''s this';\n\
|
||||
\nalter table \"public\".\"t\"\n owner to \"app owner\";\n\
|
||||
\ngrant select on \"public\".\"t\" to public;\n\
|
||||
grant insert, select on \"public\".\"t\" to \"reader\" with grant option;\n\
|
||||
\nCREATE INDEX t_note ON public.t USING btree (note);\n\
|
||||
\nCREATE TRIGGER t_audit AFTER INSERT ON public.t FOR EACH ROW EXECUTE FUNCTION audit();\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn snowflake_quotes_names_and_reads_its_information_schema() {
|
||||
let driver = DbDriver::Snowflake;
|
||||
@@ -1256,7 +1459,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!(
|
||||
@@ -1268,6 +1471,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;
|
||||
@@ -1279,7 +1511,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"),
|
||||
@@ -1290,7 +1522,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,9 +1,9 @@
|
||||
//! Data source files edited outside the Database tool window (by hand, by a coding
|
||||
//! agent, by `git checkout`) are picked up while the project is open, as IDEA does
|
||||
//! Data source and data source folder files edited outside the Database tool window
|
||||
//! (by hand, by a coding agent, by `git checkout`) are picked up while the project is open, as IDEA does
|
||||
//! for `dataSources.xml`. The project file tree's watcher is no help here: it never
|
||||
//! reports a modification inside a gitignored `.openidea/`.
|
||||
|
||||
use crate::source::FILE;
|
||||
use crate::source::{FILE, FOLDERS_FILE};
|
||||
use ide_core::{IdeError, IdeResult, project_dir};
|
||||
use notify::{RecommendedWatcher, RecursiveMode, Watcher};
|
||||
use parking_lot::Mutex;
|
||||
@@ -15,8 +15,8 @@ use std::time::Duration;
|
||||
/// the files are read.
|
||||
const SETTLE: Duration = Duration::from_millis(200);
|
||||
|
||||
/// Watches `<root>/.openidea/data-sources.toml` and `<global>/data-sources.toml`;
|
||||
/// stops when dropped.
|
||||
/// Watches `<root>/.openidea/data-sources.toml`, `data-source-folders.toml` and
|
||||
/// `<global>/data-sources.toml`; stops when dropped.
|
||||
pub struct SourcesWatch {
|
||||
_watcher: Arc<Mutex<RecommendedWatcher>>,
|
||||
}
|
||||
@@ -29,7 +29,7 @@ impl SourcesWatch {
|
||||
let (tx, rx) = mpsc::channel::<()>();
|
||||
let relevant = {
|
||||
let config = config.clone();
|
||||
move |p: &Path| p.file_name().is_some_and(|n| n == FILE) || p == config
|
||||
move |p: &Path| p.file_name().is_some_and(|n| n == FILE || n == FOLDERS_FILE) || p == config
|
||||
};
|
||||
let watcher = notify::recommended_watcher(move |res: notify::Result<notify::Event>| {
|
||||
if let Ok(e) = res
|
||||
@@ -131,6 +131,10 @@ mod tests {
|
||||
std::fs::write(project.join(".openidea/data-sources.toml"), "").unwrap();
|
||||
assert!(wait_for(&count, seen + 1), "project file");
|
||||
|
||||
let seen = count.load(Ordering::SeqCst);
|
||||
std::fs::write(project.join(".openidea/data-source-folders.toml"), "").unwrap();
|
||||
assert!(wait_for(&count, seen + 1), "project folders file");
|
||||
|
||||
let seen = count.load(Ordering::SeqCst);
|
||||
std::fs::write(global.join("data-sources.toml"), "").unwrap();
|
||||
assert!(wait_for(&count, seen + 1), "global file");
|
||||
|
||||
@@ -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<()> {
|
||||
|
||||
@@ -40,7 +40,8 @@ async fn create_schemas(db: &DbManager) {
|
||||
format!("DROP DATABASE IF EXISTS `{s}`"),
|
||||
format!("CREATE DATABASE `{s}` CHARACTER SET utf8mb4 COLLATE utf8mb4_bin"),
|
||||
format!(
|
||||
"CREATE TABLE `{s}`.`用户` (id INT PRIMARY KEY, name VARCHAR(20) COLLATE utf8mb4_bin, raw VARBINARY(4))"
|
||||
"CREATE TABLE `{s}`.`用户` (id INT PRIMARY KEY, name VARCHAR(20) COLLATE utf8mb4_bin COMMENT '名字', \
|
||||
raw VARBINARY(4)) COMMENT = '用户表'"
|
||||
),
|
||||
format!("CREATE INDEX `名字` ON `{s}`.`用户` (name)"),
|
||||
format!("INSERT INTO `{s}`.`用户` VALUES (1, 'ann', 0xCAFE)"),
|
||||
@@ -56,9 +57,13 @@ async fn assert_metadata_is_text(db: &DbManager) -> IdeResult<()> {
|
||||
assert!(schemas.iter().any(|n| n == s), "{s} missing from {schemas:?}");
|
||||
let tables = db.tables("m", s).await?;
|
||||
assert_eq!(tables.iter().map(|t| t.name.as_str()).collect::<Vec<_>>(), ["用户"], "tables of {s}");
|
||||
assert_eq!(tables[0].comment.as_deref(), Some("用户表"));
|
||||
let d = db.table_details("m", s, "用户").await?;
|
||||
let cols: Vec<_> = d.columns.iter().map(|c| c.name.as_str()).collect();
|
||||
assert_eq!(cols, ["id", "name", "raw"]);
|
||||
assert_eq!(d.comment.as_deref(), Some("用户表"));
|
||||
let comments: Vec<_> = d.columns.iter().map(|c| c.comment.as_deref()).collect();
|
||||
assert_eq!(comments, [None, Some("名字"), None]);
|
||||
assert!(d.indexes.iter().any(|i| i.name == "名字"), "{:?}", d.indexes);
|
||||
assert!(db.ddl("m", s, "用户").await?.contains("CREATE TABLE `用户`"));
|
||||
}
|
||||
|
||||
@@ -338,6 +338,8 @@ async fn table_details_routines_and_completion_on_older_catalogs() -> IdeResult<
|
||||
"CREATE TABLE oi_meta.lines (n INT PRIMARY KEY, o_region INT, o_id INT, \
|
||||
FOREIGN KEY (o_region, o_id) REFERENCES oi_meta.orders (region, id))",
|
||||
"CREATE INDEX lines_order ON oi_meta.lines (o_id, o_region)",
|
||||
"COMMENT ON TABLE oi_meta.orders IS 'Customer''s orders'",
|
||||
"COMMENT ON COLUMN oi_meta.orders.note IS 'Free text'",
|
||||
"CREATE FUNCTION oi_meta.twice(v INT) RETURNS INT AS 'SELECT v * 2' LANGUAGE sql",
|
||||
] {
|
||||
db.execute("p", stmt, 10, &c).await?;
|
||||
@@ -350,6 +352,13 @@ async fn table_details_routines_and_completion_on_older_catalogs() -> IdeResult<
|
||||
assert_eq!(details.foreign_keys[0].columns, ["o_region", "o_id"]);
|
||||
assert_eq!(details.foreign_keys[0].ref_columns, ["region", "id"]);
|
||||
let orders = db.table_details("p", "oi_meta", "orders").await?;
|
||||
assert_eq!(orders.comment.as_deref(), Some("Customer's orders"));
|
||||
let listed = db.tables("p", "oi_meta").await?;
|
||||
let listed_orders = listed.iter().find(|table| table.name == "orders").expect("orders in the table list");
|
||||
assert_eq!(listed_orders.comment.as_deref(), Some("Customer's orders"));
|
||||
let comments: Vec<_> = orders.columns.iter().map(|c| c.comment.as_deref()).collect();
|
||||
assert_eq!(comments, [None, None, Some("Free text")]);
|
||||
assert_eq!(details.comment, None);
|
||||
let key = orders.indexes.iter().find(|i| i.unique).expect("primary key index");
|
||||
assert_eq!(key.columns, ["region", "id"]);
|
||||
|
||||
@@ -414,7 +423,29 @@ async fn opening_a_table_reads_multi_column_keys_in_order() -> IdeResult<()> {
|
||||
db.execute("p", "CREATE SEQUENCE oi_keys.seq", 10, &c).await?;
|
||||
let objects = db.schema_objects("p", "oi_keys").await?;
|
||||
assert_eq!(objects.sequences.len(), 1);
|
||||
assert!(db.ddl("p", "oi_keys", "refs").await?.contains("FOREIGN KEY"));
|
||||
let plain = db.ddl("p", "oi_keys", "refs").await?;
|
||||
assert!(plain.contains("FOREIGN KEY"), "{plain}");
|
||||
assert!(plain.contains("\n owner to "), "{plain}");
|
||||
assert!(!plain.contains("comment on") && !plain.contains("grant ") && !plain.contains("TRIGGER"), "{plain}");
|
||||
// Comments, privileges and triggers come back too, so the script rebuilds the table.
|
||||
for statement in [
|
||||
"COMMENT ON TABLE oi_keys.refs IS 'Refs'",
|
||||
"COMMENT ON COLUMN oi_keys.refs.x IS 'it''s x'",
|
||||
"GRANT SELECT, INSERT ON oi_keys.refs TO PUBLIC",
|
||||
"CREATE FUNCTION oi_keys.touch() RETURNS trigger LANGUAGE plpgsql AS 'BEGIN RETURN NEW; END'",
|
||||
"CREATE TRIGGER refs_touch BEFORE UPDATE ON oi_keys.refs FOR EACH ROW EXECUTE FUNCTION oi_keys.touch()",
|
||||
] {
|
||||
db.execute("p", statement, 10, &c).await?;
|
||||
}
|
||||
let full = db.ddl("p", "oi_keys", "refs").await?;
|
||||
for part in [
|
||||
"comment on table \"oi_keys\".\"refs\" is 'Refs';",
|
||||
"comment on column \"oi_keys\".\"refs\".\"x\" is 'it''s x';",
|
||||
"grant insert, select on \"oi_keys\".\"refs\" to public;",
|
||||
"CREATE TRIGGER refs_touch BEFORE UPDATE ON oi_keys.refs FOR EACH ROW EXECUTE FUNCTION oi_keys.touch();",
|
||||
] {
|
||||
assert!(full.contains(part), "{part}\n{full}");
|
||||
}
|
||||
db.execute("p", "DROP SCHEMA oi_keys CASCADE", 10, &c).await?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -779,3 +810,40 @@ async fn table_grants_expand_the_acl_per_grantee() -> IdeResult<()> {
|
||||
}
|
||||
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
|
||||
|
||||
@@ -27,18 +27,24 @@ const QUICK: Duration = Duration::from_secs(20);
|
||||
/// Stop / restart wait for the container's grace period (10 s by default).
|
||||
const LIFECYCLE: Duration = Duration::from_secs(90);
|
||||
|
||||
/// Locates the docker executable once per process. GUI apps on macOS start with a
|
||||
/// minimal `PATH`, so the usual install locations are probed after the lookup.
|
||||
/// Locates the docker executable. GUI apps on macOS start with a minimal `PATH`, so
|
||||
/// the login/reloaded `PATH` and usual install locations are probed after the lookup.
|
||||
/// Only a found path is cached, so installing Docker while the backend runs is picked up.
|
||||
pub fn docker_executable() -> Option<PathBuf> {
|
||||
static DOCKER: OnceLock<Option<PathBuf>> = OnceLock::new();
|
||||
DOCKER
|
||||
.get_or_init(|| {
|
||||
if let Some(explicit) = std::env::var_os("OPENIDEA_DOCKER").map(PathBuf::from).filter(|p| p.is_file()) {
|
||||
return Some(explicit);
|
||||
}
|
||||
if let Ok(found) = which::which("docker") {
|
||||
return Some(found);
|
||||
}
|
||||
if let Some(explicit) = std::env::var_os("OPENIDEA_DOCKER").map(PathBuf::from).filter(|p| p.is_file()) {
|
||||
return Some(explicit);
|
||||
}
|
||||
static DOCKER: OnceLock<PathBuf> = OnceLock::new();
|
||||
if let Some(cached) = DOCKER.get().filter(|p| p.is_file()) {
|
||||
return Some(cached.clone());
|
||||
}
|
||||
let found = which::which("docker")
|
||||
.ok()
|
||||
.or_else(|| {
|
||||
let path = ide_core::process::host_var_os("PATH")?;
|
||||
which::which_in("docker", Some(path), ".").ok()
|
||||
})
|
||||
.or_else(|| {
|
||||
let home = std::env::var_os(if cfg!(windows) { "USERPROFILE" } else { "HOME" }).map(PathBuf::from);
|
||||
let mut candidates: Vec<PathBuf> = if cfg!(windows) {
|
||||
vec![PathBuf::from(r"C:\Program Files\Docker\Docker\resources\bin\docker.exe")]
|
||||
@@ -60,8 +66,11 @@ pub fn docker_executable() -> Option<PathBuf> {
|
||||
candidates.push(home.join(".docker/bin/docker"));
|
||||
}
|
||||
candidates.into_iter().find(|p| p.is_file())
|
||||
})
|
||||
.clone()
|
||||
});
|
||||
if let Some(ref path) = found {
|
||||
let _ = DOCKER.set(path.clone());
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
/// Environment for docker command lines a run configuration launches: the endpoint's
|
||||
|
||||
@@ -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.17.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}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -12,4 +12,3 @@ serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
specta.workspace = true
|
||||
tracing.workspace = true
|
||||
which = "8"
|
||||
@@ -16,30 +16,15 @@ use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
use std::sync::OnceLock;
|
||||
use std::time::Duration;
|
||||
|
||||
/// API calls normally answer within a few seconds.
|
||||
const QUICK: Duration = Duration::from_secs(60);
|
||||
|
||||
/// Locates the gh executable once per process (GUI apps on macOS have a minimal `PATH`).
|
||||
/// Locates the gh executable (GUI apps on macOS have a minimal `PATH`, and the IDE can
|
||||
/// install or remove a managed copy in its tools directory at runtime).
|
||||
pub fn gh_executable() -> Option<PathBuf> {
|
||||
static GH: OnceLock<Option<PathBuf>> = OnceLock::new();
|
||||
GH.get_or_init(|| {
|
||||
if let Some(explicit) = std::env::var_os("OPENIDEA_GH").map(PathBuf::from).filter(|p| p.is_file()) {
|
||||
return Some(explicit);
|
||||
}
|
||||
if let Ok(found) = which::which("gh") {
|
||||
return Some(found);
|
||||
}
|
||||
let candidates: &[&str] = if cfg!(windows) {
|
||||
&[r"C:\Program Files\GitHub CLI\gh.exe"]
|
||||
} else {
|
||||
&["/opt/homebrew/bin/gh", "/usr/local/bin/gh", "/usr/bin/gh", "/snap/bin/gh"]
|
||||
};
|
||||
candidates.iter().map(PathBuf::from).find(|p| p.is_file())
|
||||
})
|
||||
.clone()
|
||||
ide_core::tool_path::find_gh_executable()
|
||||
}
|
||||
|
||||
fn command(root: &Path, args: &[&str]) -> IdeResult<Command> {
|
||||
@@ -386,3 +371,37 @@ pub fn prepare_diff(
|
||||
let files = repo.diff_files(&base, head_oid)?;
|
||||
Ok(PrDiffRevisions { base, head: head_oid.to_owned(), files, root: ide_core::IpcPath(repo.root().to_path_buf()) })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn gh_executable_picks_up_newly_installed_binary_without_restart() {
|
||||
let dir = std::env::temp_dir().join(format!("openidea-gh-test-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let search = std::env::join_paths([&dir]).unwrap();
|
||||
assert_eq!(ide_core::tool_path::find_gh_in(None, &search, &[]), None);
|
||||
|
||||
let gh = dir.join(if cfg!(windows) { "gh.exe" } else { "gh" });
|
||||
std::fs::write(&gh, "#!/bin/sh\n").unwrap();
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::set_permissions(&gh, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
}
|
||||
assert_eq!(ide_core::tool_path::find_gh_in(None, &search, &[]), Some(gh.clone()));
|
||||
|
||||
let explicit = dir.join(if cfg!(windows) { "custom-gh.exe" } else { "custom-gh" });
|
||||
std::fs::write(&explicit, "#!/bin/sh\n").unwrap();
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::set_permissions(&explicit, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
}
|
||||
assert_eq!(ide_core::tool_path::find_gh_in(Some(&explicit), &search, &[]), Some(explicit));
|
||||
|
||||
std::fs::remove_file(&gh).unwrap();
|
||||
assert_eq!(ide_core::tool_path::find_gh_in(None, &search, &[]), None);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
@@ -82,6 +82,11 @@ impl Environment {
|
||||
}
|
||||
}
|
||||
|
||||
/// True on `openidea-server`, where the backend runs on a remote/headless host rather than the desktop shell.
|
||||
pub fn is_remote(&self) -> bool {
|
||||
self.project_env
|
||||
}
|
||||
|
||||
/// A trusted project at `root` opened or became trusted: loads its direnv environment in
|
||||
/// the background, unless another window of it already did. Its language servers wait.
|
||||
pub(crate) fn direnv_opened(&self, root: &Path, sink: &SharedSink) {
|
||||
|
||||
@@ -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.
|
||||
@@ -152,6 +261,12 @@ fn supports_external_format(language: &LanguageConfig, tool: ExternalFormatter)
|
||||
}
|
||||
}
|
||||
|
||||
/// The entry of the formatters' language lists that covers `language`. MDX was part of Markdown
|
||||
/// and follows its entry, so lists saved before it had its own language keep formatting it.
|
||||
fn formatter_language(language: &str) -> &str {
|
||||
if language == "mdx" { "markdown" } else { language }
|
||||
}
|
||||
|
||||
/// The external formatter of a file, for a language with an external formatter.
|
||||
/// `forced` names the tool (Reformat with Prettier, oxfmt, Biome, Ruff, or Black). Ruff is
|
||||
/// the base formatter for Python, replaced by Black when configured or selected; Biome,
|
||||
@@ -186,7 +301,8 @@ fn external_tool(
|
||||
)))
|
||||
};
|
||||
}
|
||||
let enabled = |tool| settings.formatter(tool).languages.iter().any(|l| l == language.id.as_str());
|
||||
let id = formatter_language(language.id.as_str());
|
||||
let enabled = |tool| settings.formatter(tool).languages.iter().any(|l| l == id);
|
||||
if language.formatter.as_ref().is_some_and(|f| f.tool == "ruff") {
|
||||
return Ok(if enabled(Black) && (settings.black.prefer || black_configured(file)) {
|
||||
Some(Black)
|
||||
@@ -533,18 +649,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 {
|
||||
@@ -566,17 +722,24 @@ async fn provider_edits(
|
||||
.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);
|
||||
@@ -727,7 +890,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;
|
||||
|
||||
@@ -741,6 +904,24 @@ mod tests {
|
||||
external_tool(forced, language.as_ref(), file, settings)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mdx_follows_the_markdown_entry_of_saved_language_lists() {
|
||||
// Saved before MDX had its own language: the whole list, with no `mdx` in it.
|
||||
let old: ide_core::settings::Settings = serde_json::from_str(
|
||||
r#"{"languages":{"prettier":{"languages":["markdown","css"]},"oxfmt":{"languages":["css"]}}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let file = Path::new("/project/docs/intro.mdx");
|
||||
assert_eq!(tool(None, "mdx", file, &old.languages).unwrap(), Some(Prettier));
|
||||
let mut no_markdown = old.languages.clone();
|
||||
no_markdown.prettier.languages.retain(|l| l != "markdown");
|
||||
assert_eq!(tool(None, "mdx", file, &no_markdown).unwrap(), None);
|
||||
let mut oxfmt = old.languages.clone();
|
||||
oxfmt.oxfmt.languages.push("markdown".into());
|
||||
oxfmt.oxfmt.prefer = true;
|
||||
assert_eq!(tool(None, "mdx", file, &oxfmt).unwrap(), Some(Oxfmt));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_settings_use_ruff_for_python_and_prettier_for_the_web() {
|
||||
let settings = LanguagesSettings::default();
|
||||
@@ -945,6 +1126,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();
|
||||
@@ -1011,6 +1276,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();
|
||||
|
||||
@@ -0,0 +1,340 @@
|
||||
//! Project-scoped GitHub CLI (`gh`) account selection and opt-in `GH_TOKEN` injection.
|
||||
//!
|
||||
//! Each project may pin a GitHub login in `vcs.github.account` (`.openidea/settings.toml`) or
|
||||
//! leave it empty (`Automatic`). `Automatic` leaves `gh`'s own behaviour untouched—no `GH_TOKEN`
|
||||
//! is injected into [`ide_core::project_env`] and opening a project makes no GitHub API calls.
|
||||
//! When the user inspects GitHub settings or Pull Requests with multiple `gh` keyring accounts,
|
||||
//! OpenIDEA probes the repository remote (`owner/repo`) to suggest a matching non-active account
|
||||
//! ("Use <login> for this project"). Only when an account is explicitly chosen does OpenIDEA
|
||||
//! resolve its token into [`ide_core::project_env`] (for both `project.root` and `.worktrees`).
|
||||
|
||||
use crate::Project;
|
||||
use ide_agent::GhAuthAccount;
|
||||
use ide_core::cli_process::{CliTool, Decoding};
|
||||
use parking_lot::Mutex;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
use std::sync::LazyLock;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
const AMBIENT_GH_VARS: [&str; 3] = ["COPILOT_GITHUB_TOKEN", "GH_TOKEN", "GITHUB_TOKEN"];
|
||||
const GH_TOOL: CliTool = CliTool::new("gh", Decoding::Utf8Lossy);
|
||||
const LOCAL_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
const PROBE_TIMEOUT: Duration = Duration::from_secs(6);
|
||||
const CACHE_TTL: Duration = Duration::from_secs(10 * 60);
|
||||
|
||||
/// GitHub CLI accounts available on this machine and which one applies to the project.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct GhProjectAccountStatus {
|
||||
pub gh_installed: bool,
|
||||
pub accounts: Vec<GhAuthAccount>,
|
||||
/// Value of `vcs.github.account` (`""` = Automatic).
|
||||
pub configured_account: String,
|
||||
/// Account login currently used (`configured_account` if signed in, else `gh`'s active account).
|
||||
pub effective_account: Option<String>,
|
||||
/// Non-active `gh` account with access to this project's GitHub remote when `configured_account` is empty.
|
||||
pub suggested_account: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct CachedAutoAccount {
|
||||
login: Option<String>,
|
||||
at: Instant,
|
||||
}
|
||||
|
||||
type AutoCacheMap = HashMap<(String, Vec<String>), CachedAutoAccount>;
|
||||
static AUTO_CACHE: LazyLock<Mutex<AutoCacheMap>> = LazyLock::new(|| Mutex::new(HashMap::new()));
|
||||
|
||||
pub(crate) fn is_valid_github_login(login: &str) -> bool {
|
||||
let bytes = login.as_bytes();
|
||||
!bytes.is_empty()
|
||||
&& bytes.len() <= 39
|
||||
&& bytes[0].is_ascii_alphanumeric()
|
||||
&& bytes.iter().all(|b| b.is_ascii_alphanumeric() || *b == b'-' || *b == b'_')
|
||||
}
|
||||
|
||||
fn find_gh_executable() -> Option<PathBuf> {
|
||||
ide_core::tool_path::find_gh_executable()
|
||||
}
|
||||
|
||||
fn clean_gh_command(program: &Path, args: &[&str]) -> Command {
|
||||
let mut cmd = Command::new(program);
|
||||
cmd.current_dir(std::env::temp_dir())
|
||||
.args(args)
|
||||
.env("GH_PROMPT_DISABLED", "1")
|
||||
.env("GH_NO_UPDATE_NOTIFIER", "1")
|
||||
.env("NO_COLOR", "1")
|
||||
.env("CLICOLOR", "0");
|
||||
// Strip ambient tokens by setting empty then removing after `prepare`: `CliTool::run` calls
|
||||
// `ide_core::process::prepare`, which skips keys already present in `cmd.get_envs()`.
|
||||
for key in AMBIENT_GH_VARS {
|
||||
cmd.env_remove(key);
|
||||
}
|
||||
cmd
|
||||
}
|
||||
|
||||
fn gh_token_for_account(program: &Path, login: &str) -> Option<String> {
|
||||
if !is_valid_github_login(login) {
|
||||
return None;
|
||||
}
|
||||
let cmd = clean_gh_command(program, &["auth", "token", "--hostname", "github.com", "--user", login]);
|
||||
let out = GH_TOOL.run(cmd, LOCAL_TIMEOUT, None).ok().filter(|o| o.success)?;
|
||||
let token = out.stdout.trim();
|
||||
(!token.is_empty()).then(|| token.to_owned())
|
||||
}
|
||||
|
||||
/// Access level of an account for a specific `owner/repo` on `github.com`.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
|
||||
enum RepoAccess {
|
||||
None = 0,
|
||||
Read = 1,
|
||||
Push = 2,
|
||||
}
|
||||
|
||||
fn probe_repo_access(program: &Path, token: &str, owner: &str, name: &str) -> RepoAccess {
|
||||
let endpoint = format!("repos/{owner}/{name}");
|
||||
let mut cmd =
|
||||
clean_gh_command(program, &["api", "--hostname", "github.com", &endpoint, "--jq", ".permissions.push"]);
|
||||
cmd.env("GH_TOKEN", token);
|
||||
let Ok(out) = GH_TOOL.run(cmd, PROBE_TIMEOUT, None) else {
|
||||
return RepoAccess::None;
|
||||
};
|
||||
if !out.success {
|
||||
return RepoAccess::None;
|
||||
}
|
||||
if out.stdout.trim() == "true" { RepoAccess::Push } else { RepoAccess::Read }
|
||||
}
|
||||
|
||||
fn pick_best_account(candidates: &[(GhAuthAccount, RepoAccess)]) -> Option<(&GhAuthAccount, bool)> {
|
||||
let active_access =
|
||||
candidates.iter().find(|(a, _)| a.active).map(|(_, access)| *access).unwrap_or(RepoAccess::None);
|
||||
// Prefer higher RepoAccess; break ties in favor of the globally active account.
|
||||
let (best, best_access) = candidates.iter().max_by_key(|(acc, access)| (*access, acc.active))?;
|
||||
if *best_access == RepoAccess::None {
|
||||
// Nobody could reach the repo (offline or SSO required): keep the active account.
|
||||
return candidates.iter().find(|(a, _)| a.active).or_else(|| candidates.first()).map(|(a, _)| (a, false));
|
||||
}
|
||||
let auto_detected = !best.active && *best_access > active_access;
|
||||
Some((best, auto_detected))
|
||||
}
|
||||
|
||||
/// Parses `github.com` `(owner, repo)` from HTTPS, SSH, or SCP-style remote URLs.
|
||||
pub(crate) fn parse_github_owner_repo(url: &str) -> Option<(String, String)> {
|
||||
let url = url.trim();
|
||||
let path = if let Some(rest) =
|
||||
url.strip_prefix("https://github.com/").or_else(|| url.strip_prefix("http://github.com/"))
|
||||
{
|
||||
rest
|
||||
} else if let Some(rest) = url.strip_prefix("ssh://") {
|
||||
rest.strip_prefix("[email protected]/").or_else(|| rest.strip_prefix("github.com/"))?
|
||||
} else {
|
||||
url.strip_prefix("[email protected]:")?
|
||||
};
|
||||
let path = path.trim_matches('/');
|
||||
let (owner, rest) = path.split_once('/')?;
|
||||
let repo = rest.split('/').next()?;
|
||||
let repo = repo.strip_suffix(".git").unwrap_or(repo);
|
||||
if owner.is_empty() || repo.is_empty() {
|
||||
return None;
|
||||
}
|
||||
Some((owner.to_owned(), repo.to_owned()))
|
||||
}
|
||||
|
||||
fn primary_github_repo(project: &Project) -> Option<(String, String)> {
|
||||
let repos = project.repos();
|
||||
let mut ordered = Vec::new();
|
||||
if let Some(primary) = repos.primary() {
|
||||
ordered.push(primary);
|
||||
}
|
||||
for repo in repos.all() {
|
||||
if ordered.first().is_none_or(|p| p.root() != repo.root()) {
|
||||
ordered.push(repo);
|
||||
}
|
||||
}
|
||||
for repo in ordered {
|
||||
let Ok(mut remotes) = repo.remotes() else { continue };
|
||||
remotes.sort_by_key(|r| r.name != "origin");
|
||||
for remote in remotes {
|
||||
let url = remote.resolved_url.as_deref().unwrap_or(&remote.url);
|
||||
if let Some(coords) = parse_github_owner_repo(url) {
|
||||
return Some(coords);
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn auto_detect_account(program: &Path, accounts: &[GhAuthAccount], owner: &str, repo: &str) -> Option<(String, bool)> {
|
||||
// Fast path: the repository owner matches one of the signed-in accounts directly.
|
||||
if let Some(matched) = accounts.iter().find(|a| a.login.eq_ignore_ascii_case(owner)) {
|
||||
return Some((matched.login.clone(), !matched.active));
|
||||
}
|
||||
let key_repo = format!("{}/{}", owner.to_ascii_lowercase(), repo.to_ascii_lowercase());
|
||||
let key_logins: Vec<String> = accounts.iter().map(|a| format!("{}:{}", a.login, a.active)).collect();
|
||||
let cache_key = (key_repo, key_logins);
|
||||
if let Some(cached) = AUTO_CACHE.lock().get(&cache_key).cloned()
|
||||
&& cached.at.elapsed() < CACHE_TTL
|
||||
{
|
||||
if let Some(login) = cached.login {
|
||||
let is_active = accounts.iter().any(|a| a.login == login && a.active);
|
||||
return Some((login, !is_active));
|
||||
}
|
||||
return None;
|
||||
}
|
||||
|
||||
let tokens: Vec<(GhAuthAccount, Option<String>)> =
|
||||
accounts.iter().map(|acc| (acc.clone(), gh_token_for_account(program, &acc.login))).collect();
|
||||
let results: Vec<(GhAuthAccount, RepoAccess)> = std::thread::scope(|s| {
|
||||
let handles: Vec<_> = tokens
|
||||
.into_iter()
|
||||
.map(|(acc, token)| {
|
||||
s.spawn(move || {
|
||||
let access = match token {
|
||||
Some(tok) => probe_repo_access(program, &tok, owner, repo),
|
||||
None => RepoAccess::None,
|
||||
};
|
||||
(acc, access)
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
handles.into_iter().filter_map(|h| h.join().ok()).collect()
|
||||
});
|
||||
let picked = pick_best_account(&results).map(|(acc, auto)| (acc.login.clone(), auto));
|
||||
AUTO_CACHE
|
||||
.lock()
|
||||
.insert(cache_key, CachedAutoAccount { login: picked.as_ref().map(|(l, _)| l.clone()), at: Instant::now() });
|
||||
picked
|
||||
}
|
||||
|
||||
/// Resolves global status when no project is open.
|
||||
pub fn global_status(configured_account: String) -> GhProjectAccountStatus {
|
||||
let configured_account = configured_account.trim().to_owned();
|
||||
let (gh_installed, accounts) = ide_agent::gh_authenticated_accounts();
|
||||
let effective_account = if !configured_account.is_empty() {
|
||||
accounts.iter().any(|a| a.login == configured_account).then(|| configured_account.clone())
|
||||
} else {
|
||||
accounts.iter().find(|a| a.active).or_else(|| accounts.first()).map(|a| a.login.clone())
|
||||
};
|
||||
GhProjectAccountStatus { gh_installed, accounts, configured_account, effective_account, suggested_account: None }
|
||||
}
|
||||
|
||||
/// Applies the project's explicit `vcs.github.account` setting to [`ide_core::project_env`]
|
||||
/// without making any network requests. `Automatic` (`""`) clears any injected `GH_TOKEN` so
|
||||
/// processes use `gh`'s own behaviour.
|
||||
pub fn apply_to_project(project: &Project) {
|
||||
if project.light || !project.is_trusted() {
|
||||
clear_project_env(project);
|
||||
return;
|
||||
}
|
||||
let configured_account = project.settings.effective().vcs.github.account.trim().to_owned();
|
||||
if configured_account.is_empty() {
|
||||
set_project_token(project, None);
|
||||
return;
|
||||
}
|
||||
let token = find_gh_executable().and_then(|program| gh_token_for_account(&program, &configured_account));
|
||||
set_project_token(project, token);
|
||||
}
|
||||
|
||||
/// Applies the project's explicit account setting and returns the full account status,
|
||||
/// probing the project's GitHub remote to suggest a matching non-active `gh` account when
|
||||
/// `vcs.github.account` is `Automatic` (`""`) and multiple `gh` accounts are signed in.
|
||||
pub fn project_status(project: &Project) -> GhProjectAccountStatus {
|
||||
let configured_account = project.settings.effective().vcs.github.account.trim().to_owned();
|
||||
if project.light || !project.is_trusted() {
|
||||
clear_project_env(project);
|
||||
return GhProjectAccountStatus { configured_account, ..GhProjectAccountStatus::default() };
|
||||
}
|
||||
apply_to_project(project);
|
||||
let Some(program) = find_gh_executable() else {
|
||||
return GhProjectAccountStatus { configured_account, ..GhProjectAccountStatus::default() };
|
||||
};
|
||||
let (gh_installed, accounts) = ide_agent::gh_authenticated_accounts();
|
||||
let active_login = accounts.iter().find(|a| a.active).or_else(|| accounts.first()).map(|a| a.login.clone());
|
||||
|
||||
let effective_account = if !configured_account.is_empty() {
|
||||
accounts.iter().any(|a| a.login == configured_account).then(|| configured_account.clone())
|
||||
} else {
|
||||
active_login
|
||||
};
|
||||
|
||||
let suggested_account = if configured_account.is_empty() && accounts.len() >= 2 {
|
||||
primary_github_repo(project)
|
||||
.and_then(|(owner, repo)| auto_detect_account(&program, &accounts, &owner, &repo))
|
||||
.and_then(|(login, non_active_match)| non_active_match.then_some(login))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
GhProjectAccountStatus { gh_installed, accounts, configured_account, effective_account, suggested_account }
|
||||
}
|
||||
|
||||
fn set_project_token(project: &Project, token: Option<String>) {
|
||||
let os_tok = token.map(std::ffi::OsString::from);
|
||||
let changed_root = ide_core::project_env::set_github_token(&project.root, os_tok.clone());
|
||||
let changed_wt = ide_core::project_env::set_github_token(project.agents.worktrees_dir(), os_tok);
|
||||
if changed_root || changed_wt {
|
||||
project.agents.notify_mcp_servers_changed();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn clear_project_env(project: &Project) {
|
||||
ide_core::project_env::remove_all(&project.root);
|
||||
ide_core::project_env::remove_all(project.agents.worktrees_dir());
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parses_github_owner_repo_across_https_ssh_and_scp_remotes() {
|
||||
assert_eq!(
|
||||
parse_github_owner_repo("https://github.com/l0ng-ai/openidea.git"),
|
||||
Some(("l0ng-ai".into(), "openidea".into()))
|
||||
);
|
||||
assert_eq!(
|
||||
parse_github_owner_repo("[email protected]:acme-corp/payments.git"),
|
||||
Some(("acme-corp".into(), "payments".into()))
|
||||
);
|
||||
assert_eq!(parse_github_owner_repo("ssh://[email protected]/alice/demo/"), Some(("alice".into(), "demo".into())));
|
||||
assert_eq!(parse_github_owner_repo("https://gitlab.com/foo/bar.git"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validates_github_logins_against_flag_injection() {
|
||||
assert!(is_valid_github_login("alice"));
|
||||
assert!(is_valid_github_login("alice-work"));
|
||||
assert!(is_valid_github_login("l0ng-ai"));
|
||||
assert!(!is_valid_github_login(""));
|
||||
assert!(!is_valid_github_login("--hostname"));
|
||||
assert!(!is_valid_github_login("bad space"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn picks_account_with_push_or_private_access_and_preserves_active_on_ties() {
|
||||
let personal = GhAuthAccount { login: "alice".into(), active: true };
|
||||
let work = GhAuthAccount { login: "alice-work".into(), active: false };
|
||||
|
||||
// Private org repo: personal gets 404 (None), work gets Push -> auto-detects work.
|
||||
let private_org = vec![(personal.clone(), RepoAccess::None), (work.clone(), RepoAccess::Push)];
|
||||
let (picked, auto) = pick_best_account(&private_org).unwrap();
|
||||
assert_eq!(picked.login, "alice-work");
|
||||
assert!(auto);
|
||||
|
||||
// Public org repo: personal gets Read, work gets Push -> auto-detects work.
|
||||
let public_org = vec![(personal.clone(), RepoAccess::Read), (work.clone(), RepoAccess::Push)];
|
||||
let (picked, auto) = pick_best_account(&public_org).unwrap();
|
||||
assert_eq!(picked.login, "alice-work");
|
||||
assert!(auto);
|
||||
|
||||
// Third-party public repo: both get Read -> keeps active personal account without auto flag.
|
||||
let oss = vec![(personal.clone(), RepoAccess::Read), (work.clone(), RepoAccess::Read)];
|
||||
let (picked, auto) = pick_best_account(&oss).unwrap();
|
||||
assert_eq!(picked.login, "alice");
|
||||
assert!(!auto);
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
use ide_build::kotlin_bridge::{self, Outcome, ProjectLibraries};
|
||||
use ide_core::event::NotifyLevel;
|
||||
use ide_core::{CancellationToken, Diagnostic, IdeEvent, Pos, Range, Severity, SharedSink};
|
||||
use ide_core::{CancellationToken, Diagnostic, IdeEvent, Pos, Range, Severity, SharedSink, TaskId};
|
||||
use ide_lsp::LspManager;
|
||||
use ide_workspace::SettingsStore;
|
||||
use ide_workspace::documents::DocumentObserver;
|
||||
@@ -223,9 +223,15 @@ impl KotlinBridge {
|
||||
let staging = directory.clone();
|
||||
let root = self.root.clone();
|
||||
let token = cancel.clone();
|
||||
let result =
|
||||
tokio::task::spawn_blocking(move || kotlin_bridge::build(&root, &model, &bundle, &staging, &token))
|
||||
.await;
|
||||
// The build runs Maven over the Kotlin modules, which can take a minute: it shows in
|
||||
// the status bar and can be stopped there (the next saved change builds again).
|
||||
let task = BuildTask::start(self.sink.clone(), &cancel);
|
||||
let progress = task.reporter();
|
||||
let result = tokio::task::spawn_blocking(move || {
|
||||
kotlin_bridge::build(&root, &model, &bundle, &staging, &token, &progress)
|
||||
})
|
||||
.await;
|
||||
drop(task);
|
||||
if !self.revision.lock().current(generation) || self.lifetime.is_cancelled() {
|
||||
remove_directory(directory).await;
|
||||
continue;
|
||||
@@ -306,6 +312,58 @@ impl KotlinBridge {
|
||||
}
|
||||
}
|
||||
|
||||
/// The status bar's background task for one bridge build; ends when dropped.
|
||||
struct BuildTask {
|
||||
id: TaskId,
|
||||
sink: SharedSink,
|
||||
_cancel: ide_core::task::CancelHandle,
|
||||
}
|
||||
|
||||
impl BuildTask {
|
||||
const TITLE: &str = "Compiling Kotlin for Java";
|
||||
|
||||
fn start(sink: SharedSink, cancel: &CancellationToken) -> Self {
|
||||
let id = TaskId::next();
|
||||
let cancel = cancel.clone();
|
||||
let handle = ide_core::task::on_cancel(id, move || cancel.cancel());
|
||||
let task = Self { id, sink, _cancel: handle };
|
||||
task.emit(None, None, false);
|
||||
task
|
||||
}
|
||||
|
||||
fn emit(&self, message: Option<String>, fraction: Option<f32>, done: bool) {
|
||||
self.sink.emit(IdeEvent::Task {
|
||||
id: self.id,
|
||||
title: Self::TITLE.into(),
|
||||
message,
|
||||
fraction,
|
||||
done,
|
||||
cancellable: !done,
|
||||
});
|
||||
}
|
||||
|
||||
/// Forwards Maven's progress to the task.
|
||||
fn reporter(&self) -> impl Fn(&str, Option<f32>) + Send + Sync + 'static {
|
||||
let (id, sink) = (self.id, self.sink.clone());
|
||||
move |message: &str, fraction| {
|
||||
sink.emit(IdeEvent::Task {
|
||||
id,
|
||||
title: Self::TITLE.into(),
|
||||
message: Some(message.to_owned()),
|
||||
fraction,
|
||||
done: false,
|
||||
cancellable: true,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for BuildTask {
|
||||
fn drop(&mut self) {
|
||||
self.emit(None, None, true);
|
||||
}
|
||||
}
|
||||
|
||||
/// The error text of a failed bridge build, and whether to notify about it. Compiler errors
|
||||
/// in the user's own Kotlin already show in its editor and stay in Problems; only a build
|
||||
/// that failed without one (Maven itself, a missing plugin) is worth a notification.
|
||||
@@ -369,6 +427,41 @@ impl DocumentObserver for KotlinBridge {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_build_shows_as_a_cancellable_background_task() {
|
||||
let events = Arc::new(Mutex::new(Vec::new()));
|
||||
let sink: SharedSink = Arc::new({
|
||||
let events = events.clone();
|
||||
move |e: IdeEvent| events.lock().push(e)
|
||||
});
|
||||
let cancel = CancellationToken::new();
|
||||
let task = BuildTask::start(sink, &cancel);
|
||||
let progress = task.reporter();
|
||||
progress("Building app 1.0 [2/3]", Some(0.5));
|
||||
assert!(ide_core::task::cancel(task.id), "the status bar can stop it");
|
||||
assert!(cancel.is_cancelled());
|
||||
drop(task);
|
||||
let seen: Vec<_> = events
|
||||
.lock()
|
||||
.iter()
|
||||
.map(|e| match e {
|
||||
IdeEvent::Task { title, message, fraction, done, cancellable, .. } => {
|
||||
assert_eq!(title, "Compiling Kotlin for Java");
|
||||
(message.clone(), *fraction, *done, *cancellable)
|
||||
}
|
||||
other => panic!("{other:?}"),
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(
|
||||
seen,
|
||||
[
|
||||
(None, None, false, true),
|
||||
(Some("Building app 1.0 [2/3]".into()), Some(0.5), false, true),
|
||||
(None, None, true, false),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn target_package_directory_does_not_trigger() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -12,9 +12,11 @@ pub mod diagnostics_store;
|
||||
mod direnv;
|
||||
pub mod environment;
|
||||
mod formatter;
|
||||
pub mod github_auth;
|
||||
mod java_runtime;
|
||||
mod kotlin_bridge;
|
||||
pub mod mcp;
|
||||
pub mod menu;
|
||||
pub mod notebook;
|
||||
pub mod ops;
|
||||
mod phpstan;
|
||||
@@ -26,6 +28,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};
|
||||
|
||||
@@ -120,6 +125,7 @@ pub struct Host {
|
||||
pub(crate) rebase_editors: Arc<ops::vcs::RebaseEditors>,
|
||||
/// The IDE's Java build: resident javac processes shared by every window's launches.
|
||||
pub(crate) java_build: Arc<ide_build::jbuild::JavaBuildService>,
|
||||
pub(crate) metrics_sampler: Mutex<ops::host_metrics::HostMetricsSampler>,
|
||||
/// SSH connections of Settings › SSH Configurations.
|
||||
pub ssh: Arc<ide_ssh::SshManager>,
|
||||
/// SFTP deployment, remote file editing and runs on run targets.
|
||||
@@ -250,6 +256,7 @@ impl Host {
|
||||
heap_requests: Default::default(),
|
||||
rebase_editors: Default::default(),
|
||||
java_build: Default::default(),
|
||||
metrics_sampler: Default::default(),
|
||||
languages,
|
||||
syntax,
|
||||
config_dir,
|
||||
@@ -378,6 +385,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 +393,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();
|
||||
@@ -412,6 +422,7 @@ impl Host {
|
||||
self.environment.project_closed();
|
||||
if self.windows_for_root(&project.root).is_empty() {
|
||||
self.environment.direnv_closed(&project.root);
|
||||
crate::github_auth::clear_project_env(&project);
|
||||
}
|
||||
}
|
||||
if let Some(bridge) = &project.kotlin_bridge {
|
||||
@@ -420,6 +431,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 +663,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();
|
||||
@@ -688,6 +705,12 @@ impl Host {
|
||||
self.requests.begin(id)
|
||||
}
|
||||
|
||||
/// Settings › Tools › Download Mirrors › Use only the configured package registries: nothing
|
||||
/// is fetched from public package registries the user's tools weren't pointed at.
|
||||
pub fn configured_registries_only(&self) -> bool {
|
||||
self.global_settings.effective().tool_downloads.configured_registries_only
|
||||
}
|
||||
|
||||
pub fn begin_project_request(&self, window: &str, id: RequestId) -> CancellationToken {
|
||||
let token = self.begin_project_read_request(window, id);
|
||||
if self.project(window).is_ok_and(|p| !p.is_trusted()) {
|
||||
|
||||
@@ -38,6 +38,11 @@ impl Requests {
|
||||
let _ = pending.answer.send(error.map_or(Ok(allow), Err));
|
||||
Ok(())
|
||||
}
|
||||
/// Whether `window` answers requests (a project loaded for MCP alone has no window).
|
||||
pub(super) fn window_ready(&self, window: &str) -> bool {
|
||||
self.0.lock().ready.contains(window)
|
||||
}
|
||||
|
||||
pub(super) async fn ask(&self, call: &Call, request: McpUiRequest) -> IdeResult<()> {
|
||||
let id = super::tool::request_id().0;
|
||||
let (tx, rx) = oneshot::channel();
|
||||
|
||||
@@ -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,10 @@ 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::{HashMap, HashSet};
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::{Arc, LazyLock};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
const DEFAULT_TIMEOUT_MS: usize = 10_000;
|
||||
@@ -281,7 +283,92 @@ 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);
|
||||
|
||||
/// Run configuration parameter naming the `execute_run_configuration` call a start belongs to.
|
||||
pub const CONFIG_RUN_PARAM: &str = "mcp.configRun";
|
||||
|
||||
/// The `execute_run_configuration` calls waiting for the Run tool window to start their run.
|
||||
struct ConfigLaunch {
|
||||
output: Arc<Mutex<OutputCollector>>,
|
||||
started: Option<Result<ide_run::RunInfo, String>>,
|
||||
}
|
||||
static LAUNCHES: LazyLock<Mutex<HashMap<u64, ConfigLaunch>>> = LazyLock::new(Default::default);
|
||||
static NEXT_LAUNCH: AtomicU64 = AtomicU64::new(1);
|
||||
|
||||
/// The Run tool window's start of an `execute_run_configuration` run: its output also goes to
|
||||
/// the call's output file, and the call learns the run it started.
|
||||
pub(crate) struct ConfigRunLaunch {
|
||||
token: u64,
|
||||
output: Arc<Mutex<OutputCollector>>,
|
||||
}
|
||||
|
||||
/// The call `config` was started for (its first start only; a rerun from the tab is the user's).
|
||||
pub(crate) fn config_run_launch(config: &RunConfig) -> Option<ConfigRunLaunch> {
|
||||
let token = config.extras.params.get(CONFIG_RUN_PARAM)?.parse().ok()?;
|
||||
let launches = LAUNCHES.lock();
|
||||
let launch = launches.get(&token).filter(|l| l.started.is_none())?;
|
||||
Some(ConfigRunLaunch { token, output: launch.output.clone() })
|
||||
}
|
||||
|
||||
impl ConfigRunLaunch {
|
||||
pub(crate) fn wrap_output(&self, on_output: crate::ops::Emit<OutputChunk>) -> crate::ops::Emit<OutputChunk> {
|
||||
let output = self.output.clone();
|
||||
Arc::new(move |chunk: OutputChunk| {
|
||||
// As JetBrains skips `ProcessOutputType.SYSTEM` (`Process finished…`).
|
||||
if let OutputChunk::Stdout { text } | OutputChunk::Stderr { text } = &chunk {
|
||||
output.lock().append(text);
|
||||
}
|
||||
on_output(chunk);
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn started(&self, result: &IdeResult<ide_run::RunInfo>) {
|
||||
if let Some(launch) = LAUNCHES.lock().get_mut(&self.token) {
|
||||
launch.started = Some(result.clone().map_err(|e| e.message));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Starts `config` in the Run tool window, as the user's Run would: a tab with its console and
|
||||
/// Stop. Its before launch tasks already ran.
|
||||
async fn start_in_run_window(
|
||||
call: &Call,
|
||||
mut config: RunConfig,
|
||||
output: Arc<Mutex<OutputCollector>>,
|
||||
) -> IdeResult<ide_run::RunInfo> {
|
||||
struct Forget(u64);
|
||||
impl Drop for Forget {
|
||||
fn drop(&mut self) {
|
||||
LAUNCHES.lock().remove(&self.0);
|
||||
}
|
||||
}
|
||||
let token = NEXT_LAUNCH.fetch_add(1, Ordering::Relaxed);
|
||||
LAUNCHES.lock().insert(token, ConfigLaunch { output, started: None });
|
||||
let _forget = Forget(token);
|
||||
config.extras.params.insert(CONFIG_RUN_PARAM.into(), token.to_string());
|
||||
let config = serde_json::to_value(&config).map_err(|e| IdeError::invalid(e.to_string()))?;
|
||||
let asked = call.ask(ide_core::event::McpUiRequest::RunConfiguration { config }).await;
|
||||
let started = LAUNCHES.lock().get_mut(&token).and_then(|l| l.started.take());
|
||||
match (asked, started) {
|
||||
(_, Some(Ok(info))) => Ok(info),
|
||||
(_, Some(Err(message))) => Err(IdeError::invalid(message)),
|
||||
(Err(e), None) => Err(e),
|
||||
(Ok(()), None) => Err(IdeError::invalid("the run did not start")),
|
||||
}
|
||||
}
|
||||
|
||||
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 +381,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) {
|
||||
@@ -740,8 +827,9 @@ 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.",
|
||||
arguments (appended to a command that is one shell line, such as `npm run dev`); the run appears in the Run tool \
|
||||
window like a run the user started, with its console and Stop; 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")?,
|
||||
@@ -797,9 +885,15 @@ one by one",
|
||||
};
|
||||
let collector = Arc::new(Mutex::new(OutputCollector::create(&config.name)?));
|
||||
let output_path = collector.lock().path.clone();
|
||||
let sink = collector.clone();
|
||||
let emit = process_output(move |text| sink.lock().append(text));
|
||||
let info = match crate::ops::run::run_start(&call.host(), call.window(), config, emit, None).await {
|
||||
let started = if call.has_window() {
|
||||
start_in_run_window(&call, config, collector.clone()).await
|
||||
} else {
|
||||
// A project loaded for MCP alone has no Run tool window to show it in.
|
||||
let sink = collector.clone();
|
||||
let emit = process_output(move |text| sink.lock().append(text));
|
||||
crate::ops::run::run_start(&call.host(), call.window(), config, emit, None).await
|
||||
};
|
||||
let info = match started {
|
||||
Ok(info) => info,
|
||||
Err(e) => {
|
||||
let _ = std::fs::remove_file(&output_path);
|
||||
@@ -807,14 +901,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.
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
pub(crate) mod agent;
|
||||
mod agent_tools;
|
||||
mod build;
|
||||
mod configs;
|
||||
pub(crate) mod configs;
|
||||
mod output;
|
||||
mod process;
|
||||
mod targets;
|
||||
|
||||
@@ -493,7 +493,7 @@ fn test_kinds(rel: &str) -> &'static [&'static str] {
|
||||
if JS_FILE.is_match(rel) {
|
||||
&["npm", "deno", "bun"]
|
||||
} else if rel.ends_with(".py") {
|
||||
&["pytest", "python"]
|
||||
&["pytest", "unittest", "python"]
|
||||
} else if rel.ends_with(".go") {
|
||||
&["go"]
|
||||
} else if rel.ends_with(".rs") {
|
||||
@@ -644,6 +644,11 @@ fn test_config_for(root: &Path, rel: &str, configs: &[RunConfig]) -> Option<RunC
|
||||
"npm" | "bun" if base.args.iter().any(|a| a == "--") => derived(&base, rel, with(&[file])),
|
||||
"npm" | "bun" => derived(&base, rel, with(&["--".into(), file])),
|
||||
"deno" | "pytest" | "python" => derived(&base, rel, with(&[file])),
|
||||
// `python -m unittest <file>`; a `discover` selection gives way to the file.
|
||||
"unittest" => {
|
||||
let end = base.args.iter().position(|a| a == "discover").unwrap_or(base.args.len());
|
||||
derived(&base, rel, [base.args[..end].to_vec(), vec![file]].concat())
|
||||
}
|
||||
"go" => {
|
||||
let dir = dir_of(&file);
|
||||
let target = if dir.is_empty() { ".".to_owned() } else { format!("./{dir}") };
|
||||
@@ -790,6 +795,11 @@ pub fn target_config(
|
||||
"pytest" | "python" => {
|
||||
Some(named(replace_last(file.args.clone(), |f| format!("{f}::{}", target.path.join("::")))))
|
||||
}
|
||||
// unittest names tests by dotted module path: `tests.test_calc.TestCalc.test_add`.
|
||||
"unittest" => Some(named(replace_last(file.args.clone(), |f| {
|
||||
let module = f.strip_suffix(".py").unwrap_or(f).replace(['/', '\\'], ".");
|
||||
format!("{module}.{}", target.path.join("."))
|
||||
}))),
|
||||
"go" => {
|
||||
let pattern = format!("^{}$", target.path.iter().map(|p| escape_regexp(p)).collect::<Vec<_>>().join("$/^"));
|
||||
let benchmark = target.path.first().is_some_and(|p| p.starts_with("Benchmark"));
|
||||
@@ -921,6 +931,30 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn narrows_unittest_configs_to_files_and_dotted_tests() {
|
||||
let root = Path::new("/p");
|
||||
let mut unittest =
|
||||
blank("unittest".into(), "unittest", "unittest", "python3".into(), vec!["-m".into(), "unittest".into()]);
|
||||
unittest.is_test = true;
|
||||
let mut discover = unittest.clone();
|
||||
discover.args.extend(["discover".into(), "-s".into(), "tests".into()]);
|
||||
let src = "import unittest\n\nclass TestCalc(unittest.TestCase):\n def test_add(self):\n pass\n";
|
||||
let rel = "tests/test_calc.py";
|
||||
for configs in [vec![unittest], vec![discover]] {
|
||||
let c = context_config(root, rel, &configs, src).unwrap();
|
||||
assert_eq!(
|
||||
(c.kind.as_str(), c.args.as_slice()),
|
||||
("unittest", ["-m", "unittest", rel].map(String::from).as_slice())
|
||||
);
|
||||
let ts = detect(src, rel);
|
||||
let c = target_config(root, &ts[1], rel, &configs, src).unwrap();
|
||||
assert_eq!(c.args, ["-m", "unittest", "tests.test_calc.TestCalc.test_add"]);
|
||||
let c = target_config(root, &ts[0], rel, &configs, src).unwrap();
|
||||
assert_eq!(c.args, ["-m", "unittest", "tests.test_calc.TestCalc"]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn narrows_cargo_test_configs() {
|
||||
let root = Path::new("/p");
|
||||
|
||||
@@ -70,6 +70,10 @@ impl Call {
|
||||
pub async fn ask(&self, request: ide_core::event::McpUiRequest) -> IdeResult<()> {
|
||||
self.host.mcp_requests.ask(self, request).await
|
||||
}
|
||||
/// Whether the project has a window to show what the tool starts (not one loaded for MCP alone).
|
||||
pub fn has_window(&self) -> bool {
|
||||
self.host.mcp_requests.window_ready(&self.window)
|
||||
}
|
||||
/// Asks the user before a tool changes the project or starts a process, unless brave mode
|
||||
/// is on — read from the IDE's own settings only, which a project's settings can't set.
|
||||
pub async fn confirm(&self, subject: &str, detail: Option<String>) -> IdeResult<()> {
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -6,11 +6,11 @@ use crate::agent_secrets::{AgentSecrets, Kept};
|
||||
use ide_agent::registry::{AgentRegistry, RegistryPaths};
|
||||
use ide_agent::{
|
||||
AcpImportOutcome, AgentAcceptOutcome, AgentChange, AgentChanges, AgentChangesView, AgentCliOffer,
|
||||
AgentCliUpdateResult, AgentCommand, AgentContextUsage, AgentEntry, AgentEvent, AgentModelCatalog, AgentProbe,
|
||||
AgentPrompt, AgentProvider, AgentQueued, AgentSkillMode, AgentSkillPolicy, AgentSkillState, AgentTask,
|
||||
CustomAgentInput, ExternalSession, InstallRemoteSkillRequest, McpExternalSource, McpImportSelection,
|
||||
McpProbeResult, McpScope, McpServer, McpServerInput, McpTransport, NewAgentTask, RemoteSkillBrowseResult,
|
||||
RemoteSkillPreview, SkillsPolicy,
|
||||
AgentCliUpdateResult, AgentCommand, AgentContextUsage, AgentEntry, AgentEvent, AgentLoginEvent, AgentModelCatalog,
|
||||
AgentProbe, AgentPrompt, AgentProvider, AgentQueued, AgentSkillMode, AgentSkillPolicy, AgentSkillState, AgentTask,
|
||||
CopilotAuthStatus, CustomAgentInput, ExternalSession, InstallRemoteSkillRequest, LoginLaunch, McpExternalSource,
|
||||
McpImportSelection, McpProbeResult, McpScope, McpServer, McpServerInput, McpTransport, NewAgentTask,
|
||||
RemoteSkillBrowseResult, RemoteSkillPreview, SkillsPolicy,
|
||||
};
|
||||
use ide_command::command;
|
||||
use ide_core::error::ErrorKind;
|
||||
@@ -80,6 +80,19 @@ pub fn agent_refresh_models(
|
||||
host.project(window)?.agents.refresh_models(&provider, force, model.as_deref())
|
||||
}
|
||||
|
||||
/// Probes Copilot's model catalog for a staged GitHub account without persisting until Apply.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn agent_preview_copilot_models(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
account: String,
|
||||
model: Option<String>,
|
||||
) -> IdeResult<AgentModelCatalog> {
|
||||
host.require_trust(window)?;
|
||||
let agents = host.project(window)?.agents.clone();
|
||||
agents.preview_copilot_models(&account, model.as_deref()).await
|
||||
}
|
||||
|
||||
/// Overrides built-in agent `id`'s command with `command` (its agent file keeps the
|
||||
/// built-in's driver and arguments), or returns it to auto-detection with `None`.
|
||||
#[command(trust = trusted)]
|
||||
@@ -88,6 +101,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)]
|
||||
@@ -101,6 +121,141 @@ pub fn agent_set_env(
|
||||
host.project(window)?.agents.set_builtin_env(&id, env)
|
||||
}
|
||||
|
||||
/// Default Copilot CLI sign-in status alongside authenticated `github.com` accounts in `gh`.
|
||||
#[command(trust = outside_restricted)]
|
||||
pub async fn agent_copilot_auth_status(host: &Host, window: &str) -> IdeResult<CopilotAuthStatus> {
|
||||
host.require_trust_if_project(window)?;
|
||||
match host.project(window) {
|
||||
Ok(project) => Ok(project.agents.copilot_auth_status().await),
|
||||
Err(_) => {
|
||||
let custom_dir = host.config_dir.join("agents");
|
||||
let cwd = dirs::home_dir().unwrap_or_else(std::env::temp_dir);
|
||||
Ok(ide_agent::copilot_auth_status_with(Some(&custom_dir), None, &cwd).await)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const REMOTE_SESSION_ENV_VARS: [&str; 5] =
|
||||
["SSH_CONNECTION", "SSH_CLIENT", "SSH_TTY", "CODESPACES", "REMOTE_CONTAINERS"];
|
||||
|
||||
fn prepare_login_launch_env(
|
||||
is_remote: bool,
|
||||
target_is_gh: bool,
|
||||
env: &mut std::collections::BTreeMap<String, String>,
|
||||
host_has: impl Fn(&str) -> bool,
|
||||
) {
|
||||
if !is_remote {
|
||||
return;
|
||||
}
|
||||
let has_non_empty = |env: &std::collections::BTreeMap<String, String>, key: &str| {
|
||||
env.get(key).is_some_and(|v| !v.is_empty()) || host_has(key)
|
||||
};
|
||||
// `openidea-server` spawns sign-in commands in a real PTY even inside WSL, dev containers,
|
||||
// and `--web`, where `SSH_*` variables are absent; mark the session remote so CLIs such as
|
||||
// `copilot login` choose OAuth device-code sign-in over a remote-only loopback server.
|
||||
if !REMOTE_SESSION_ENV_VARS.iter().any(|key| has_non_empty(env, key)) {
|
||||
env.insert("REMOTE_CONTAINERS".into(), "1".into());
|
||||
}
|
||||
if target_is_gh && !has_non_empty(env, "GH_BROWSER") && !has_non_empty(env, "BROWSER") {
|
||||
env.insert("GH_BROWSER".into(), "true".into());
|
||||
}
|
||||
}
|
||||
|
||||
fn apply_remote_login_env(host: &Host, cwd: &std::path::Path, target_is_gh: bool, launch: &mut LoginLaunch) {
|
||||
let cwd = if cwd.is_dir() { cwd.to_path_buf() } else { dirs::home_dir().unwrap_or_else(std::env::temp_dir) };
|
||||
prepare_login_launch_env(host.environment.is_remote(), target_is_gh, &mut launch.env, |key| {
|
||||
ide_core::process::host_var_os_in(&cwd, key).is_some_and(|v| !v.is_empty())
|
||||
});
|
||||
}
|
||||
|
||||
fn spawn_login_pty(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
cwd: std::path::PathBuf,
|
||||
launch: LoginLaunch,
|
||||
cols: u16,
|
||||
rows: u16,
|
||||
on_event: Channel<AgentLoginEvent>,
|
||||
) -> IdeResult<ide_terminal::TerminalInfo> {
|
||||
crate::ops::term::apply_output_rate(host, window);
|
||||
let cwd = if cwd.is_dir() { cwd } else { dirs::home_dir().unwrap_or_else(std::env::temp_dir) };
|
||||
let options = ide_terminal::TerminalOptions {
|
||||
cwd: cwd.into(),
|
||||
shell: Some(launch.program.to_string_lossy().into_owned()),
|
||||
args: launch.args,
|
||||
env: launch.env,
|
||||
cols: if cols == 0 { 80 } else { cols },
|
||||
rows: if rows == 0 { 20 } else { rows },
|
||||
shell_integration: false,
|
||||
};
|
||||
let exit_channel = on_event.clone();
|
||||
host.terminals.spawn_program(
|
||||
options,
|
||||
format!("agent-login:{window}"),
|
||||
host.window_sink(window),
|
||||
Box::new(move |data| {
|
||||
let _ = on_event.send(AgentLoginEvent::Output { data });
|
||||
}),
|
||||
Some(std::sync::Arc::new(move |code| {
|
||||
let _ = exit_channel.send(AgentLoginEvent::Exited { code });
|
||||
})),
|
||||
)
|
||||
}
|
||||
|
||||
/// Starts agent `id`'s interactive sign-in flow in an IDE-managed PTY and streams its output and exit code.
|
||||
#[command(trust = outside_restricted)]
|
||||
pub async fn agent_login_spawn(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
id: String,
|
||||
cols: u16,
|
||||
rows: u16,
|
||||
on_event: Channel<AgentLoginEvent>,
|
||||
) -> IdeResult<ide_terminal::TerminalInfo> {
|
||||
host.require_trust_if_project(window)?;
|
||||
let (cwd, mut launch) = match host.project(window) {
|
||||
Ok(project) => {
|
||||
let root = project.root.clone();
|
||||
let agents = project.agents.clone();
|
||||
let launch = host.blocking(move || agents.login_launch(&id)).await?;
|
||||
(root, launch)
|
||||
}
|
||||
Err(_) => {
|
||||
let custom_dir = host.config_dir.join("agents");
|
||||
let cwd = dirs::home_dir().unwrap_or_else(std::env::temp_dir);
|
||||
let cwd_for_lookup = cwd.clone();
|
||||
let launch = host
|
||||
.blocking(move || {
|
||||
ide_agent::login_launch_without_project(Some(&custom_dir), None, &cwd_for_lookup, &id)
|
||||
})
|
||||
.await?;
|
||||
(cwd, launch)
|
||||
}
|
||||
};
|
||||
apply_remote_login_env(host, &cwd, false, &mut launch);
|
||||
spawn_login_pty(host, window, cwd, launch, cols, rows, on_event)
|
||||
}
|
||||
|
||||
/// Starts `gh auth login --hostname github.com` in an IDE-managed PTY (with ambient token
|
||||
/// variables cleared) and streams its output and exit code.
|
||||
#[command(trust = outside_restricted)]
|
||||
pub async fn agent_gh_login_spawn(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
cols: u16,
|
||||
rows: u16,
|
||||
on_event: Channel<AgentLoginEvent>,
|
||||
) -> IdeResult<ide_terminal::TerminalInfo> {
|
||||
host.require_trust_if_project(window)?;
|
||||
let cwd = host
|
||||
.project(window)
|
||||
.map(|p| p.root.clone())
|
||||
.unwrap_or_else(|_| dirs::home_dir().unwrap_or_else(std::env::temp_dir));
|
||||
let mut launch = host.blocking(ide_agent::gh_login_launch).await?;
|
||||
apply_remote_login_env(host, &cwd, true, &mut launch);
|
||||
spawn_login_pty(host, window, cwd, launch, cols, rows, on_event)
|
||||
}
|
||||
|
||||
/// Saves a new custom ACP agent through its agent file.
|
||||
pub fn save_custom_agent(host: &Host, window: &str, input: CustomAgentInput) -> IdeResult<()> {
|
||||
host.require_trust(window)?;
|
||||
@@ -178,6 +333,7 @@ pub async fn agent_registry_install(
|
||||
) -> IdeResult<()> {
|
||||
// The agent then shows in `agent_providers`.
|
||||
let paths = registry_paths(host);
|
||||
let public_npm_fallback = !host.configured_registries_only();
|
||||
let installing = Installing::begin(&id)?;
|
||||
let cancel = host.begin_request(request);
|
||||
// Also a background task of every project window, so it stays visible and can be
|
||||
@@ -204,7 +360,7 @@ pub async fn agent_registry_install(
|
||||
move || cancel.cancel()
|
||||
});
|
||||
report(None, None, false);
|
||||
let result = ide_agent::registry::install(&paths, &id, &cancel, &|e| {
|
||||
let result = ide_agent::registry::install(&paths, &id, public_npm_fallback, &cancel, &|e| {
|
||||
match &e {
|
||||
InstallEvent::Line { text } => report(Some(text.clone()), None, false),
|
||||
InstallEvent::Progress { fraction, message } => {
|
||||
@@ -281,6 +437,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)?;
|
||||
@@ -1426,6 +1597,29 @@ mod tests {
|
||||
assert!(reloaded.approved(&root, "extra", &extra));
|
||||
assert!(!reloaded.approved(&tmp.path().join("other"), "extra", &extra));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prepare_login_launch_env_marks_remote_sessions_for_device_code_auth() {
|
||||
let mut desktop_env = std::collections::BTreeMap::new();
|
||||
prepare_login_launch_env(false, true, &mut desktop_env, |_| false);
|
||||
assert!(desktop_env.is_empty());
|
||||
|
||||
let mut remote_agent_env = std::collections::BTreeMap::new();
|
||||
prepare_login_launch_env(true, false, &mut remote_agent_env, |_| false);
|
||||
assert_eq!(remote_agent_env.get("REMOTE_CONTAINERS").map(String::as_str), Some("1"));
|
||||
assert!(!remote_agent_env.contains_key("GH_BROWSER"));
|
||||
|
||||
let mut remote_gh_env = std::collections::BTreeMap::new();
|
||||
prepare_login_launch_env(true, true, &mut remote_gh_env, |_| false);
|
||||
assert_eq!(remote_gh_env.get("REMOTE_CONTAINERS").map(String::as_str), Some("1"));
|
||||
assert_eq!(remote_gh_env.get("GH_BROWSER").map(String::as_str), Some("true"));
|
||||
|
||||
// Preserves existing SSH/remote indicators and explicit browser settings.
|
||||
let mut ssh_env = std::collections::BTreeMap::new();
|
||||
prepare_login_launch_env(true, true, &mut ssh_env, |k| matches!(k, "SSH_CONNECTION" | "BROWSER"));
|
||||
assert!(!ssh_env.contains_key("REMOTE_CONTAINERS"));
|
||||
assert!(!ssh_env.contains_key("GH_BROWSER"));
|
||||
}
|
||||
}
|
||||
|
||||
ide_command::domain!(
|
||||
@@ -1440,14 +1634,18 @@ ide_command::domain!(
|
||||
agent_cli_update,
|
||||
agent_cli_update_check,
|
||||
agent_commands,
|
||||
agent_copilot_auth_status,
|
||||
agent_create,
|
||||
agent_delete,
|
||||
agent_entries,
|
||||
agent_external_sessions,
|
||||
agent_fork,
|
||||
agent_fork_session,
|
||||
agent_gh_login_spawn,
|
||||
agent_grouped_changes,
|
||||
agent_hermes_profiles,
|
||||
agent_import_session,
|
||||
agent_login_spawn,
|
||||
agent_mcp_discover_sources,
|
||||
agent_mcp_import,
|
||||
agent_mcp_import_selected,
|
||||
@@ -1457,6 +1655,7 @@ ide_command::domain!(
|
||||
agent_mcp_save_json,
|
||||
agent_mcp_set_enabled,
|
||||
agent_mcp_test,
|
||||
agent_preview_copilot_models,
|
||||
agent_probe,
|
||||
agent_prompt,
|
||||
agent_providers,
|
||||
@@ -1469,6 +1668,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,
|
||||
|
||||
@@ -767,6 +767,7 @@ pub async fn maven_dependency_completion(
|
||||
use ide_build::maven::completion::{PomCompletionKind, local_options};
|
||||
let project = host.project(window)?;
|
||||
let cache = host.dependency_versions.clone();
|
||||
let central = !host.configured_registries_only();
|
||||
let cancel = host.begin_project_read_request(window, request);
|
||||
let result = host
|
||||
.blocking(move || {
|
||||
@@ -785,7 +786,10 @@ pub async fn maven_dependency_completion(
|
||||
// The local repository answers at once: Central gets `CENTRAL_WAIT`, then the
|
||||
// lookup finishes in the background and fills the cache for the next request.
|
||||
// Offline, behind a proxy or rate-limited, a failed fetch never fails completion.
|
||||
let remote = {
|
||||
// Only the configured package registries: the local repository alone.
|
||||
let remote = if !central {
|
||||
Vec::new()
|
||||
} else {
|
||||
let (cache, target) = (cache.clone(), target.clone());
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
std::thread::spawn(move || {
|
||||
|
||||
@@ -3,7 +3,7 @@ use crate::Host;
|
||||
use ide_command::command;
|
||||
|
||||
use super::blocking;
|
||||
use ide_core::{IdeResult, IpcPath};
|
||||
use ide_core::{IdeError, IdeResult, IpcPath};
|
||||
use ide_coverage::{CoveragePrepared, CoverageReportSpec, CoverageSuite};
|
||||
use ide_run::RunConfig;
|
||||
|
||||
@@ -35,9 +35,30 @@ pub async fn coverage_collect(host: &Host, window: &str, report: CoverageReportS
|
||||
/// with paths mapped into this project.
|
||||
#[command(trust = always)]
|
||||
pub async fn coverage_import(host: &Host, window: &str, path: IpcPath) -> IdeResult<CoverageSuite> {
|
||||
// Also reads a SimpleCov resultset.
|
||||
let root = host.project(window)?.root.clone();
|
||||
blocking(move || ide_coverage::import(&path, &root)).await
|
||||
// Also reads Cobertura XML, a SimpleCov resultset and coverage.py data files.
|
||||
let project = host.project(window)?;
|
||||
let (root, cache, config_dir) =
|
||||
(project.root.clone(), project.cache_dir.join("coverage-import"), host.config_dir.clone());
|
||||
let trusted = project.require_trust();
|
||||
blocking(move || {
|
||||
if !ide_coverage::is_data_file(&path) {
|
||||
return ide_coverage::import(&path, &root);
|
||||
}
|
||||
// coverage.py analyses the sources with the project's interpreter: that runs project code.
|
||||
trusted.map_err(|_| {
|
||||
IdeError::unavailable(
|
||||
"Reading a .coverage data file runs the project's Python. Trust the project, or import the output of `coverage xml`.",
|
||||
)
|
||||
})?;
|
||||
let python = super::sdk::effective_python(&config_dir, &project, path.parent()).ok_or_else(|| {
|
||||
IdeError::unavailable(
|
||||
"Reading a .coverage data file needs the project's Python interpreter. Choose one, or import the output of `coverage xml`.",
|
||||
)
|
||||
})?;
|
||||
let out = ide_run::wrap::new_output_dir(&cache, KEEP_RUNS)?;
|
||||
ide_coverage::import_data(&path, &root, &python, &out)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
ide_command::domain!(coverage: coverage_collect, coverage_import, coverage_prepare);
|
||||
@@ -8,8 +8,8 @@ use ide_command::command;
|
||||
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, TableGrant, TableInfo, TablePage,
|
||||
CompletionModel, DataSource, Databases, DbObjectKind, DbRowEdit, DbSourceFolder, DbVisibilityChange, HistoryEntry,
|
||||
PlanNode, QueryResult, SchemaObjects, SortKey, TableDetails, TableGrant, TableInfo, TablePage,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
@@ -75,6 +75,20 @@ pub async fn db_save_sources(host: &Host, window: &str, sources: Vec<DataSource>
|
||||
sources_changed(host, window)
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub fn db_source_folders(host: &Host, window: &str) -> IdeResult<Vec<DbSourceFolder>> {
|
||||
// The project's user-created folders and their data source members.
|
||||
ide_db::source::load_folders(&host.project(window)?.root)
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub fn db_save_source_folders(host: &Host, window: &str, folders: Vec<DbSourceFolder>) -> IdeResult<()> {
|
||||
// Replaces the project's data source folders; only grouping changes, never a source.
|
||||
let root = host.project(window)?.root.clone();
|
||||
ide_db::source::save_folders(&root, &folders)?;
|
||||
sources_changed(host, window)
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn db_save_source_visibility(
|
||||
host: &Host,
|
||||
@@ -612,7 +626,16 @@ pub fn db_consoles(host: &Host, id: String, create: bool) -> IdeResult<Vec<IpcPa
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// `<dataDir>/consoles/db/<id>`: `<id>` for the default database, `<id>.<database>` for the others.
|
||||
/// The project view root for every data source's query consoles (`<dataDir>/consoles/db`).
|
||||
#[command(trust = always)]
|
||||
pub fn db_consoles_dir(host: &Host) -> IdeResult<IpcPath> {
|
||||
let dir = host.data_dir.join("consoles").join("db");
|
||||
std::fs::create_dir_all(&dir)?;
|
||||
Ok(dir.into())
|
||||
}
|
||||
|
||||
/// `<dataDir>/consoles/db/<id>`: `<id>` for the default database,
|
||||
/// `<id>.<database>` for the others.
|
||||
fn console_dir(host: &Host, id: &str) -> IdeResult<PathBuf> {
|
||||
let (source, database) = ide_db::split_target(id);
|
||||
if source.is_empty() || !source.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') {
|
||||
@@ -670,6 +693,7 @@ ide_command::domain!(
|
||||
db_connect,
|
||||
db_connected,
|
||||
db_console_path,
|
||||
db_consoles_dir,
|
||||
db_consoles,
|
||||
db_create_database,
|
||||
db_database_catalog,
|
||||
@@ -692,6 +716,7 @@ ide_command::domain!(
|
||||
db_result_row,
|
||||
db_remove_history,
|
||||
db_retain_catalog,
|
||||
db_save_source_folders,
|
||||
db_save_source_visibility,
|
||||
db_save_sources,
|
||||
db_saved_catalog,
|
||||
@@ -701,6 +726,7 @@ ide_command::domain!(
|
||||
db_set_manual_commit,
|
||||
db_set_password,
|
||||
db_set_ssh_secret,
|
||||
db_source_folders,
|
||||
db_sources,
|
||||
db_statements,
|
||||
db_table_details,
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -212,6 +212,8 @@ pub async fn dependency_versions(
|
||||
let project = host.project(window)?;
|
||||
let cache = host.dependency_versions.clone();
|
||||
let config_dir = host.config_dir.clone();
|
||||
// npm and crates.io are asked directly; `go` goes through the configured GOPROXY.
|
||||
let public_registries = !host.configured_registries_only();
|
||||
let cancel = host.begin_project_read_request(window, request);
|
||||
let result = host
|
||||
.blocking(move || {
|
||||
@@ -228,6 +230,9 @@ pub async fn dependency_versions(
|
||||
let versions = cache.versions(&source, &dependency.package, &cancel)?;
|
||||
return Ok(vec![DependencyVersions { dependency, versions, update: None }]);
|
||||
}
|
||||
if !public_registries {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
if snap.path.file_name().is_some_and(|name| name == "package.json") {
|
||||
let Some(dependency) = offset.and_then(|offset| npm::dependency_at(&snap.text, offset)) else {
|
||||
return Ok(Vec::new());
|
||||
@@ -310,6 +315,9 @@ pub async fn pypi_package(
|
||||
request: RequestId,
|
||||
) -> IdeResult<Option<pypi::PypiPackage>> {
|
||||
let url = pypi::project_url(name.trim()).ok_or_else(|| IdeError::invalid("not a package name"))?;
|
||||
if host.configured_registries_only() {
|
||||
return Ok(None);
|
||||
}
|
||||
let cancel = host.begin_project_read_request(window, request);
|
||||
let result = host
|
||||
.blocking(move || {
|
||||
@@ -334,6 +342,9 @@ pub async fn pypi_package(
|
||||
/// PyPI's name list, which the first search downloads and a search a day later refreshes.
|
||||
#[command(trust = outside_restricted)]
|
||||
pub async fn pypi_search(host: &Host, window: &str, query: String, request: RequestId) -> IdeResult<Vec<String>> {
|
||||
if host.configured_registries_only() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let names = host.pypi_names.clone();
|
||||
let cancel = host.begin_project_read_request(window, request);
|
||||
let result = host
|
||||
|
||||
@@ -67,7 +67,12 @@ pub async fn doc_edit(host: &Host, window: &str, doc: DocId, base_version: u32,
|
||||
#[command(trust = always)]
|
||||
pub async fn doc_save(host: &Host, window: &str, doc: DocId) -> IdeResult<()> {
|
||||
let project = host.project(window)?;
|
||||
host.blocking(move || project.documents.save(doc)).await?;
|
||||
host.blocking(move || {
|
||||
project.documents.save(doc)?;
|
||||
remember_saved_encodings(&project);
|
||||
Ok(())
|
||||
})
|
||||
.await?;
|
||||
host.debugger.refresh_source_mirrors(host.owner_window(window)).await
|
||||
}
|
||||
|
||||
@@ -83,7 +88,13 @@ pub async fn doc_reload_from_disk(host: &Host, window: &str, doc: DocId) -> IdeR
|
||||
#[command(trust = always)]
|
||||
pub async fn doc_autosave(host: &Host, window: &str, doc: DocId) -> IdeResult<bool> {
|
||||
let project = host.project(window)?;
|
||||
let saved = host.blocking(move || project.documents.autosave(doc)).await?;
|
||||
let saved = host
|
||||
.blocking(move || {
|
||||
let saved = project.documents.autosave(doc)?;
|
||||
remember_saved_encodings(&project);
|
||||
Ok(saved)
|
||||
})
|
||||
.await?;
|
||||
if saved {
|
||||
host.debugger.refresh_source_mirrors(host.owner_window(window)).await?;
|
||||
}
|
||||
@@ -93,7 +104,12 @@ pub async fn doc_autosave(host: &Host, window: &str, doc: DocId) -> IdeResult<bo
|
||||
#[command(trust = always)]
|
||||
pub async fn doc_save_all(host: &Host, window: &str) -> IdeResult<()> {
|
||||
let project = host.project(window)?;
|
||||
host.blocking(move || project.documents.save_all()).await?;
|
||||
host.blocking(move || {
|
||||
let saved = project.documents.save_all();
|
||||
remember_saved_encodings(&project);
|
||||
saved
|
||||
})
|
||||
.await?;
|
||||
host.debugger.refresh_source_mirrors(host.owner_window(window)).await
|
||||
}
|
||||
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
use crate::Host;
|
||||
use crate::ops::blocking;
|
||||
use crate::project::Project;
|
||||
use ide_command::command;
|
||||
use ide_core::{DocId, IdeResult, OutlineItem, Range, TextEdit};
|
||||
use ide_core::{DocId, IdeEvent, IdeResult, OutlineItem, Range, TextEdit};
|
||||
use ide_language::{FoldRange, SyntaxHighlights};
|
||||
use ide_text::LineEnding;
|
||||
use ide_workspace::{DocumentEncoding, DocumentInfo, DocumentLanguage, HistoryEntry};
|
||||
use std::path::PathBuf;
|
||||
use ide_workspace::settings::SettingsScope;
|
||||
use ide_workspace::{DocumentEncoding, DocumentInfo, DocumentLanguage, FileDefaults, HistoryEntry};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// Opens a read-only virtual document (see `lsp_virtual_document`) as an
|
||||
/// editor buffer, so syntax features and language-server requests work in it.
|
||||
@@ -66,6 +68,49 @@ pub async fn doc_set_encoding(
|
||||
host.blocking(move || project.documents.set_encoding(doc, &encoding, reload)).await
|
||||
}
|
||||
|
||||
/// Keeps the encoding the user chose for a project file in the project's File Encodings
|
||||
/// mappings, so the file opens in it again. A converted document is kept once it is saved:
|
||||
/// until then its file is still in the old encoding. Nothing is kept for a document without
|
||||
/// a file in the project.
|
||||
#[command(trust = always)]
|
||||
pub async fn doc_remember_encoding(host: &Host, window: &str, doc: DocId) -> IdeResult<()> {
|
||||
let project = host.project(window)?;
|
||||
blocking(move || {
|
||||
let info = project.documents.snapshot(doc)?;
|
||||
if info.uri.is_some() || project.documents.keep_encoding_when_saved(doc)? {
|
||||
return Ok(());
|
||||
}
|
||||
remember_encoding(&project, &info.path, &info.encoding)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Keeps the encodings of the converted documents a save has just written.
|
||||
pub(super) fn remember_saved_encodings(project: &Project) {
|
||||
for (path, encoding) in project.documents.take_saved_encodings() {
|
||||
if let Err(e) = remember_encoding(project, &path, &encoding) {
|
||||
tracing::warn!("the encoding of {} was not kept: {e}", path.display());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn remember_encoding(project: &Project, path: &Path, encoding: &str) -> IdeResult<()> {
|
||||
const MAPPINGS: &str = "editor.encodings.mappings";
|
||||
if project.light {
|
||||
return Ok(());
|
||||
}
|
||||
let Some(file) = ide_workspace::file_defaults::mapping_key(&project.root, path) else {
|
||||
return Ok(());
|
||||
};
|
||||
if project.settings.effective().editor.encodings.mappings.get(&file).is_some_and(|kept| kept == encoding) {
|
||||
return Ok(());
|
||||
}
|
||||
let settings = project.settings.set_map_entry(SettingsScope::Project, MAPPINGS, &file, encoding.into())?;
|
||||
project.documents.set_file_defaults(FileDefaults::from_settings(&settings, Some(&project.root)));
|
||||
project.sink.emit(IdeEvent::SettingsChanged { key: MAPPINGS.into() });
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[command(trust = always)]
|
||||
pub async fn doc_set_bom(host: &Host, window: &str, doc: DocId, has_bom: bool) -> IdeResult<DocumentEncoding> {
|
||||
// Adds or removes the BOM on a UTF-8 document; the change is written on save.
|
||||
@@ -81,8 +126,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 +163,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 && !matches!(snap.language.as_str(), "markdown" | "mdx") => Vec::new(),
|
||||
None => syntax(),
|
||||
})
|
||||
})
|
||||
@@ -263,6 +308,7 @@ ide_command::domain!(
|
||||
doc_outline,
|
||||
doc_python_facts,
|
||||
doc_rearrange,
|
||||
doc_remember_encoding,
|
||||
doc_selection_ranges,
|
||||
doc_set_bom,
|
||||
doc_set_encoding,
|
||||
|
||||
@@ -221,3 +221,98 @@ async fn rearrange_returns_utf16_edits_that_put_methods_in_order() {
|
||||
f.sync().await;
|
||||
assert!(doc_rearrange(&f.host, "main", doc).await.unwrap().is_empty());
|
||||
}
|
||||
|
||||
const MAPPINGS_CHANGED: &str = "editor.encodings.mappings";
|
||||
|
||||
impl Fixture {
|
||||
fn project_settings(&self) -> PathBuf {
|
||||
self.project.settings.file(ide_workspace::settings::SettingsScope::Project).unwrap().to_path_buf()
|
||||
}
|
||||
|
||||
fn mappings_changed(&self) -> usize {
|
||||
let events = self.events.lock();
|
||||
events.iter().filter(|e| matches!(e, IdeEvent::SettingsChanged { key } if key == MAPPINGS_CHANGED)).count()
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn remembered_encoding_is_written_once_and_used_when_the_file_is_reopened() {
|
||||
let f = Fixture::new();
|
||||
let settings = f.project_settings();
|
||||
std::fs::write(&f.path, "ação\n").unwrap();
|
||||
let doc = f.open(&f.path).await;
|
||||
assert_eq!(doc.encoding, "utf-8");
|
||||
// Changing the encoding alone (Reload from Disk, an RPC client) keeps nothing.
|
||||
doc_set_encoding(&f.host, "main", doc.id, "iso-8859-15".into(), true).await.unwrap();
|
||||
assert!(!settings.exists());
|
||||
|
||||
doc_remember_encoding(&f.host, "main", doc.id).await.unwrap();
|
||||
let written = std::fs::read_to_string(&settings).unwrap();
|
||||
assert_eq!(written, "[editor.encodings.mappings]\n\"node_modules/file.txt\" = \"iso-8859-15\"\n");
|
||||
assert_eq!(f.mappings_changed(), 1);
|
||||
|
||||
// The same choice again leaves the file alone.
|
||||
let stamp = std::fs::metadata(&settings).unwrap().modified().unwrap();
|
||||
doc_remember_encoding(&f.host, "main", doc.id).await.unwrap();
|
||||
assert_eq!(std::fs::read_to_string(&settings).unwrap(), written);
|
||||
assert_eq!(std::fs::metadata(&settings).unwrap().modified().unwrap(), stamp);
|
||||
assert_eq!(f.mappings_changed(), 1);
|
||||
|
||||
doc_close(&f.host, "main", doc.id).await.unwrap();
|
||||
let reopened = f.open(&f.path).await;
|
||||
assert_eq!((reopened.encoding.as_str(), reopened.text.as_str()), ("iso-8859-15", "ação\n"));
|
||||
|
||||
// A file outside the project has no place in the project's settings.
|
||||
let outside = f.open(&f.outside).await;
|
||||
doc_set_encoding(&f.host, "main", outside.id, "iso-8859-15".into(), true).await.unwrap();
|
||||
doc_remember_encoding(&f.host, "main", outside.id).await.unwrap();
|
||||
assert_eq!(std::fs::read_to_string(&settings).unwrap(), written);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn converted_encoding_is_remembered_once_the_file_is_saved_in_it() {
|
||||
let f = Fixture::new();
|
||||
let settings = f.project_settings();
|
||||
std::fs::write(&f.path, "ação\n").unwrap();
|
||||
let doc = f.open(&f.path).await;
|
||||
doc_set_encoding(&f.host, "main", doc.id, "iso-8859-15".into(), false).await.unwrap();
|
||||
doc_remember_encoding(&f.host, "main", doc.id).await.unwrap();
|
||||
// The file is still UTF-8 on disk: closing without saving must not leave it mapped.
|
||||
assert!(!settings.exists());
|
||||
doc_close(&f.host, "main", doc.id).await.unwrap();
|
||||
let reopened = f.open(&f.path).await;
|
||||
assert_eq!((reopened.encoding.as_str(), reopened.text.as_str()), ("utf-8", "ação\n"));
|
||||
|
||||
doc_set_encoding(&f.host, "main", reopened.id, "iso-8859-15".into(), false).await.unwrap();
|
||||
doc_remember_encoding(&f.host, "main", reopened.id).await.unwrap();
|
||||
doc_save(&f.host, "main", reopened.id).await.unwrap();
|
||||
assert_eq!(std::fs::read(&f.path).unwrap(), b"a\xe7\xe3o\n");
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(&settings).unwrap(),
|
||||
"[editor.encodings.mappings]\n\"node_modules/file.txt\" = \"iso-8859-15\"\n"
|
||||
);
|
||||
assert_eq!(f.mappings_changed(), 1);
|
||||
// Later saves keep nothing more.
|
||||
doc_save(&f.host, "main", reopened.id).await.unwrap();
|
||||
assert_eq!(f.mappings_changed(), 1);
|
||||
|
||||
doc_close(&f.host, "main", reopened.id).await.unwrap();
|
||||
let again = f.open(&f.path).await;
|
||||
assert_eq!((again.encoding.as_str(), again.text.as_str()), ("iso-8859-15", "ação\n"));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn encoding_stays_changed_when_it_cannot_be_remembered() {
|
||||
let f = Fixture::new();
|
||||
let settings = f.project_settings();
|
||||
std::fs::create_dir_all(settings.parent().unwrap()).unwrap();
|
||||
std::fs::write(&settings, "[editor\n").unwrap();
|
||||
let doc = f.open(&f.path).await;
|
||||
doc_set_encoding(&f.host, "main", doc.id, "iso-8859-15".into(), true).await.unwrap();
|
||||
|
||||
let err = doc_remember_encoding(&f.host, "main", doc.id).await.unwrap_err();
|
||||
assert_eq!(err.kind, ide_core::error::ErrorKind::InvalidInput);
|
||||
assert_eq!(std::fs::read_to_string(&settings).unwrap(), "[editor\n");
|
||||
assert_eq!(f.project.documents.snapshot(doc.id).unwrap().encoding, "iso-8859-15");
|
||||
assert_eq!(f.mappings_changed(), 0);
|
||||
}
|
||||
@@ -1,9 +1,14 @@
|
||||
//! Docker run configurations: the environment their `docker` command line runs with; and Docker
|
||||
//! connections through an SSH configuration, tunnelled with the IDE's own SSH client.
|
||||
//! Services tool window › Docker (`ide-docker`) and Docker run configurations: run on the
|
||||
//! project host (`Host` locally, `openidea-server` in a remote window), with SSH connections
|
||||
//! tunnelled through the host's own SSH client.
|
||||
use super::Channel;
|
||||
use crate::Host;
|
||||
use ide_command::command;
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use ide_docker::DockerEndpoint;
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult, RequestId};
|
||||
use ide_docker::{
|
||||
ComposeOp, ContainerOp, DockerContainerStats, DockerEndpoint, DockerEvent, DockerImageLayer, DockerLogLine,
|
||||
DockerObject, DockerProcessList, DockerRegistry, DockerSettings, DockerSnapshot, PruneTarget, RegistryAuth,
|
||||
};
|
||||
use ide_ssh::Tunnel;
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
|
||||
@@ -54,6 +59,242 @@ pub async fn disconnect(host: &Host, endpoint: &DockerEndpoint) {
|
||||
host.ssh.release(id);
|
||||
}
|
||||
|
||||
/// Runs a cancellable docker command (`request` → `cancel_request`) off the async workers.
|
||||
async fn cancellable<T: Send + 'static>(
|
||||
host: &Host,
|
||||
request: RequestId,
|
||||
f: impl FnOnce(&CancellationToken) -> IdeResult<T> + Send + 'static,
|
||||
) -> IdeResult<T> {
|
||||
let cancel = host.begin_request(request);
|
||||
let result = host.blocking(move || f(&cancel)).await;
|
||||
host.end_request(request);
|
||||
result
|
||||
}
|
||||
|
||||
/// Closes the connection's SSH tunnel and, when nothing else uses it, its SSH connection
|
||||
/// (Services › Disconnect); other endpoints keep nothing open.
|
||||
#[command(trust = always)]
|
||||
pub async fn docker_disconnect(host: &Host, endpoint: DockerEndpoint) -> IdeResult<()> {
|
||||
disconnect(host, &endpoint).await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Availability plus containers, images, volumes and networks.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn docker_snapshot(host: &Host, endpoint: DockerEndpoint) -> IdeResult<DockerSnapshot> {
|
||||
let endpoint = resolve(host, endpoint).await?;
|
||||
host.blocking(move || Ok(ide_docker::snapshot(&endpoint))).await
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn docker_container_op(
|
||||
host: &Host,
|
||||
endpoint: DockerEndpoint,
|
||||
ids: Vec<String>,
|
||||
op: ContainerOp,
|
||||
) -> IdeResult<()> {
|
||||
let endpoint = resolve(host, endpoint).await?;
|
||||
host.blocking(move || ide_docker::container_op(&endpoint, &ids, op)).await
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn docker_remove(
|
||||
host: &Host,
|
||||
endpoint: DockerEndpoint,
|
||||
object: DockerObject,
|
||||
ids: Vec<String>,
|
||||
force: bool,
|
||||
) -> IdeResult<()> {
|
||||
let endpoint = resolve(host, endpoint).await?;
|
||||
host.blocking(move || ide_docker::remove(&endpoint, object, &ids, force)).await
|
||||
}
|
||||
|
||||
/// Pretty-printed `docker inspect` JSON.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn docker_inspect(
|
||||
host: &Host,
|
||||
endpoint: DockerEndpoint,
|
||||
object: DockerObject,
|
||||
id: String,
|
||||
) -> IdeResult<String> {
|
||||
let endpoint = resolve(host, endpoint).await?;
|
||||
host.blocking(move || ide_docker::inspect(&endpoint, object, &id)).await
|
||||
}
|
||||
|
||||
/// Layers of an image (`docker image history`).
|
||||
#[command(trust = trusted)]
|
||||
pub async fn docker_image_history(
|
||||
host: &Host,
|
||||
endpoint: DockerEndpoint,
|
||||
id: String,
|
||||
) -> IdeResult<Vec<DockerImageLayer>> {
|
||||
let endpoint = resolve(host, endpoint).await?;
|
||||
host.blocking(move || ide_docker::image_history(&endpoint, &id)).await
|
||||
}
|
||||
|
||||
/// Processes running inside a container (`docker top`).
|
||||
#[command(trust = trusted)]
|
||||
pub async fn docker_container_top(host: &Host, endpoint: DockerEndpoint, id: String) -> IdeResult<DockerProcessList> {
|
||||
let endpoint = resolve(host, endpoint).await?;
|
||||
host.blocking(move || ide_docker::container_top(&endpoint, &id)).await
|
||||
}
|
||||
|
||||
/// One-shot resource usage snapshot of a running container (`docker stats --no-stream`).
|
||||
#[command(trust = trusted)]
|
||||
pub async fn docker_container_stats(
|
||||
host: &Host,
|
||||
endpoint: DockerEndpoint,
|
||||
id: String,
|
||||
) -> IdeResult<DockerContainerStats> {
|
||||
let endpoint = resolve(host, endpoint).await?;
|
||||
host.blocking(move || ide_docker::container_stats(&endpoint, &id)).await
|
||||
}
|
||||
|
||||
/// Disk usage per volume name (`docker system df -v`).
|
||||
#[command(trust = trusted)]
|
||||
pub async fn docker_volume_sizes(host: &Host, endpoint: DockerEndpoint) -> IdeResult<BTreeMap<String, String>> {
|
||||
let endpoint = resolve(host, endpoint).await?;
|
||||
host.blocking(move || ide_docker::volume_sizes(&endpoint)).await
|
||||
}
|
||||
|
||||
/// Streams a container's log lines, in batches, until it stops or the request is cancelled.
|
||||
#[command(trust = trusted)]
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub async fn docker_logs(
|
||||
host: &Host,
|
||||
request: RequestId,
|
||||
endpoint: DockerEndpoint,
|
||||
id: String,
|
||||
tail: u32,
|
||||
follow: bool,
|
||||
timestamps: bool,
|
||||
on_lines: Channel<Vec<DockerLogLine>>,
|
||||
) -> IdeResult<()> {
|
||||
let endpoint = resolve(host, endpoint).await?;
|
||||
cancellable(host, request, move |cancel| {
|
||||
ide_docker::logs(&endpoint, &id, tail, follow, timestamps, cancel, &|lines| {
|
||||
let _ = on_lines.send(lines);
|
||||
})
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Follows `docker events` until the daemon goes away or the request is cancelled.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn docker_events(
|
||||
host: &Host,
|
||||
request: RequestId,
|
||||
endpoint: DockerEndpoint,
|
||||
on_event: Channel<DockerEvent>,
|
||||
) -> IdeResult<()> {
|
||||
let endpoint = resolve(host, endpoint).await?;
|
||||
cancellable(host, request, move |cancel| {
|
||||
ide_docker::watch_events(&endpoint, cancel, &|e| {
|
||||
let _ = on_event.send(e);
|
||||
})
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// `docker pull`, logging in first when a saved registry with a password serves the image.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn docker_pull(
|
||||
host: &Host,
|
||||
request: RequestId,
|
||||
endpoint: DockerEndpoint,
|
||||
reference: String,
|
||||
on_output: Channel<String>,
|
||||
) -> IdeResult<()> {
|
||||
let endpoint = resolve(host, endpoint).await?;
|
||||
let data_dir = host.data_dir.clone();
|
||||
cancellable(host, request, move |cancel| {
|
||||
let auth = ide_docker::auth_for(&data_dir, &reference);
|
||||
ide_docker::pull(&endpoint, &reference, auth.as_ref(), cancel, &|line| {
|
||||
let _ = on_output.send(line);
|
||||
})
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn docker_prune(
|
||||
host: &Host,
|
||||
request: RequestId,
|
||||
endpoint: DockerEndpoint,
|
||||
target: PruneTarget,
|
||||
on_output: Channel<String>,
|
||||
) -> IdeResult<()> {
|
||||
let endpoint = resolve(host, endpoint).await?;
|
||||
cancellable(host, request, move |cancel| {
|
||||
ide_docker::prune(&endpoint, target, cancel, &|line| {
|
||||
let _ = on_output.send(line);
|
||||
})
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// `docker compose` start / stop / restart / down of a project found through labels.
|
||||
#[command(trust = trusted)]
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub async fn docker_compose_op(
|
||||
host: &Host,
|
||||
request: RequestId,
|
||||
endpoint: DockerEndpoint,
|
||||
project: String,
|
||||
files: Vec<String>,
|
||||
working_dir: Option<String>,
|
||||
op: ComposeOp,
|
||||
on_output: Channel<String>,
|
||||
) -> IdeResult<()> {
|
||||
let endpoint = resolve(host, endpoint).await?;
|
||||
cancellable(host, request, move |cancel| {
|
||||
ide_docker::compose_op(&endpoint, &project, &files, working_dir.as_deref(), op, cancel, &|line| {
|
||||
let _ = on_output.send(line);
|
||||
})
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Docker connections and registries of the project host.
|
||||
#[command(trust = always)]
|
||||
pub async fn docker_settings(host: &Host) -> IdeResult<DockerSettings> {
|
||||
let data_dir = host.data_dir.clone();
|
||||
host.blocking(move || Ok(ide_docker::load_settings(&data_dir))).await
|
||||
}
|
||||
|
||||
#[command(trust = always)]
|
||||
pub async fn docker_save_settings(host: &Host, settings: DockerSettings) -> IdeResult<()> {
|
||||
let data_dir = host.data_dir.clone();
|
||||
host.blocking(move || ide_docker::save_settings(&data_dir, &settings)).await
|
||||
}
|
||||
|
||||
/// Saves (`None`: forgets) a registry's password.
|
||||
#[command(trust = always)]
|
||||
pub async fn docker_set_registry_password(host: &Host, id: String, password: Option<String>) -> IdeResult<()> {
|
||||
let data_dir = host.data_dir.clone();
|
||||
host.blocking(move || ide_docker::set_registry_password(&data_dir, &id, password.as_deref())).await
|
||||
}
|
||||
|
||||
/// Test login to `registry` (`password`, else the saved one) through `endpoint`'s daemon.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn docker_registry_login(
|
||||
host: &Host,
|
||||
endpoint: DockerEndpoint,
|
||||
registry: DockerRegistry,
|
||||
password: Option<String>,
|
||||
) -> IdeResult<String> {
|
||||
let endpoint = resolve(host, endpoint).await?;
|
||||
let data_dir = host.data_dir.clone();
|
||||
host.blocking(move || {
|
||||
let password = password
|
||||
.or_else(|| ide_docker::registry_password(&data_dir, ®istry.id))
|
||||
.ok_or_else(|| IdeError::invalid("enter the registry password"))?;
|
||||
let auth = RegistryAuth { address: registry.address, username: registry.username, password };
|
||||
ide_docker::login(&endpoint, &auth)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Environment for a Docker run configuration's command line: selects `endpoint`'s
|
||||
/// daemon and puts the docker executable on `PATH`.
|
||||
#[command(trust = always)]
|
||||
@@ -64,4 +305,25 @@ pub async fn docker_run_env(host: &Host, endpoint: DockerEndpoint) -> IdeResult<
|
||||
host.blocking(move || Ok(ide_docker::run_env(&endpoint))).await
|
||||
}
|
||||
|
||||
ide_command::domain!(docker: docker_run_env);
|
||||
ide_command::domain!(
|
||||
docker:
|
||||
docker_compose_op,
|
||||
docker_container_op,
|
||||
docker_container_stats,
|
||||
docker_container_top,
|
||||
docker_disconnect,
|
||||
docker_events,
|
||||
docker_image_history,
|
||||
docker_inspect,
|
||||
docker_logs,
|
||||
docker_prune,
|
||||
docker_pull,
|
||||
docker_registry_login,
|
||||
docker_remove,
|
||||
docker_run_env,
|
||||
docker_save_settings,
|
||||
docker_set_registry_password,
|
||||
docker_settings,
|
||||
docker_snapshot,
|
||||
docker_volume_sizes,
|
||||
);
|
||||
@@ -0,0 +1,264 @@
|
||||
//! Host resource metrics (`host_metrics`, `host_end_process`) for the Remote Host
|
||||
//! Resources status bar widget and popover dashboard.
|
||||
|
||||
use crate::Host;
|
||||
use ide_command::command;
|
||||
use ide_core::IdeResult;
|
||||
use ide_workspace::memory::{self, CpuSampler, MemoryCategory, MemoryRoot, ProcessMemory, ProcessTable};
|
||||
use ide_workspace::system::SystemSampler;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::collections::HashSet;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct HostMetricsSampler {
|
||||
system: SystemSampler,
|
||||
cpu: CpuSampler,
|
||||
}
|
||||
|
||||
/// One process outside OpenIDEA's own process tree on the host (read-only in the UI).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct HostProcess {
|
||||
pub pid: u32,
|
||||
pub name: String,
|
||||
pub cpu_percent: Option<f32>,
|
||||
pub memory_bytes: Option<u64>,
|
||||
}
|
||||
|
||||
/// Snapshot of host-wide CPU, memory, network, disk and process usage.
|
||||
#[derive(Clone, Debug, Default, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct HostMetrics {
|
||||
/// Overall CPU utilization across all logical cores (`0..=100`); `null` on the first sample.
|
||||
pub cpu_percent: Option<f32>,
|
||||
/// Logical CPU cores available to this host or container.
|
||||
pub cpu_cores: u32,
|
||||
/// Unix 1m, 5m, 15m load averages; `null` on Windows.
|
||||
pub load_average: Option<[f32; 3]>,
|
||||
/// Host or container memory in use, in bytes.
|
||||
pub memory_used_bytes: Option<u64>,
|
||||
/// Total physical (or container limit) memory, in bytes.
|
||||
pub memory_total_bytes: Option<u64>,
|
||||
/// Bytes/s received across non-loopback network interfaces; `null` on the first sample or unsupported OS.
|
||||
pub net_rx_bytes_per_sec: Option<f64>,
|
||||
/// Bytes/s sent across non-loopback network interfaces; `null` on the first sample or unsupported OS.
|
||||
pub net_tx_bytes_per_sec: Option<f64>,
|
||||
/// Bytes/s read from block storage; `null` on the first sample or unsupported OS.
|
||||
pub disk_read_bytes_per_sec: Option<f64>,
|
||||
/// Bytes/s written to block storage; `null` on the first sample or unsupported OS.
|
||||
pub disk_write_bytes_per_sec: Option<f64>,
|
||||
/// Free bytes available to the user on the project volume (or `$HOME` fallback).
|
||||
pub disk_available_bytes: Option<u64>,
|
||||
/// Total capacity in bytes of the project volume (or `$HOME` fallback).
|
||||
pub disk_total_bytes: Option<u64>,
|
||||
/// Uptime of the backend process in milliseconds.
|
||||
pub uptime_ms: f64,
|
||||
/// OpenIDEA backend, language servers, runs, terminals, debug adapters and agents (`includeProcesses = true`).
|
||||
pub processes: Vec<ProcessMemory>,
|
||||
/// Highest-usage processes on the host outside OpenIDEA's own process tree (`includeProcesses = true`).
|
||||
pub external_processes: Vec<HostProcess>,
|
||||
}
|
||||
|
||||
const MAX_EXTERNAL_PROCESSES: usize = 5;
|
||||
const MIN_EXTERNAL_CPU_PERCENT: f32 = 0.5;
|
||||
const MIN_EXTERNAL_MEMORY_BYTES: u64 = 32 << 20;
|
||||
|
||||
fn project_name(root: &Path) -> String {
|
||||
root.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| root.display().to_string())
|
||||
}
|
||||
|
||||
fn process_root(pid: u32, label: String, kind: &str) -> MemoryRoot {
|
||||
MemoryRoot { pid, category: MemoryCategory::Process, label, detail: Some(kind.into()), with_children: true }
|
||||
}
|
||||
|
||||
fn volume_path(host: &Host, window: &str) -> PathBuf {
|
||||
if let Ok(p) = host.project(window) {
|
||||
return p.root.clone();
|
||||
}
|
||||
if let Some(p) = host.projects().into_iter().next() {
|
||||
return p.root.clone();
|
||||
}
|
||||
dirs::home_dir().unwrap_or_else(|| host.data_dir.clone())
|
||||
}
|
||||
|
||||
fn disk_space(path: &Path) -> Option<(u64, u64)> {
|
||||
#[cfg(unix)]
|
||||
#[allow(clippy::unnecessary_cast)]
|
||||
{
|
||||
let stat = rustix::fs::statvfs(path).ok()?;
|
||||
let frsize = stat.f_frsize as u64;
|
||||
let total = (stat.f_blocks as u64).saturating_mul(frsize);
|
||||
let avail = (stat.f_bavail as u64).saturating_mul(frsize);
|
||||
(total > 0).then_some((avail.min(total), total))
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::os::windows::ffi::OsStrExt;
|
||||
let wide: Vec<u16> = path.as_os_str().encode_wide().chain(std::iter::once(0)).collect();
|
||||
let (mut avail, mut total, mut free) = (0u64, 0u64, 0u64);
|
||||
// SAFETY: `wide` is NUL-terminated and all three u64 out-pointers are writable.
|
||||
let ok = unsafe {
|
||||
windows_sys::Win32::Storage::FileSystem::GetDiskFreeSpaceExW(
|
||||
wide.as_ptr(),
|
||||
&mut avail,
|
||||
&mut total,
|
||||
&mut free,
|
||||
)
|
||||
};
|
||||
(ok != 0 && total > 0).then_some((avail.min(total), total))
|
||||
}
|
||||
#[cfg(not(any(unix, windows)))]
|
||||
{
|
||||
let _ = path;
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn collect_roots(host: &Host) -> Vec<MemoryRoot> {
|
||||
let mut roots = Vec::new();
|
||||
for p in host.projects() {
|
||||
for s in p.lsp.servers() {
|
||||
if let Some(pid) = s.pid {
|
||||
roots.push(MemoryRoot {
|
||||
pid,
|
||||
category: MemoryCategory::LanguageServer,
|
||||
label: s.name,
|
||||
detail: Some(project_name(s.root.as_ref())),
|
||||
with_children: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
for r in host.processes.list().into_iter().filter(|r| r.running) {
|
||||
if let Some(pid) = r.pid {
|
||||
roots.push(process_root(pid, r.name, "Run"));
|
||||
}
|
||||
}
|
||||
for t in host.terminals.list() {
|
||||
if let Some(pid) = t.pid {
|
||||
roots.push(process_root(pid, t.title, "Terminal"));
|
||||
}
|
||||
}
|
||||
roots
|
||||
}
|
||||
|
||||
fn resource_share(p: &HostProcess, cores: u32, total_memory: Option<u64>) -> f64 {
|
||||
let cpu_share = p.cpu_percent.map(|c| c as f64 / (cores.max(1) as f64 * 100.0)).unwrap_or(0.0);
|
||||
let mem_share = match (p.memory_bytes, total_memory.filter(|&t| t > 0)) {
|
||||
(Some(b), Some(t)) => b as f64 / t as f64,
|
||||
_ => 0.0,
|
||||
};
|
||||
cpu_share.max(mem_share)
|
||||
}
|
||||
|
||||
/// Snapshot of host-wide resource counters (CPU, memory, network, disk) and, when
|
||||
/// `include_processes` is true, the process breakdown of OpenIDEA and top host processes.
|
||||
#[command(trust = always)]
|
||||
pub async fn host_metrics(host: &Arc<Host>, window: &str, include_processes: bool) -> IdeResult<HostMetrics> {
|
||||
let disk_target = volume_path(host, window);
|
||||
let roots = if include_processes { collect_roots(host) } else { Vec::new() };
|
||||
let h = host.clone();
|
||||
host.blocking(move || {
|
||||
let table = include_processes.then(ProcessTable::snapshot);
|
||||
let (disk_available_bytes, disk_total_bytes) = match disk_space(&disk_target) {
|
||||
Some((a, t)) => (Some(a), Some(t)),
|
||||
None => (None, None),
|
||||
};
|
||||
let uptime_ms =
|
||||
ide_workspace::process::process_age().unwrap_or_else(ide_workspace::process::uptime).as_secs_f64() * 1000.0;
|
||||
|
||||
let mut sampler = h.metrics_sampler.lock();
|
||||
let rates = sampler.system.sample();
|
||||
|
||||
let (processes, external_processes) = if let Some(table) = table {
|
||||
sampler.cpu.retain(&table);
|
||||
let me = std::process::id();
|
||||
let processes =
|
||||
memory::attribute(&table, me, &roots, memory::footprint_bytes, |pid| sampler.cpu.percent(pid));
|
||||
let claimed: HashSet<u32> = table.tree(me).into_iter().collect();
|
||||
let mut external: Vec<HostProcess> = table
|
||||
.entries()
|
||||
.filter(|e| e.pid != 0 && !claimed.contains(&e.pid))
|
||||
.filter_map(|e| {
|
||||
let cpu_percent = sampler.cpu.percent(e.pid);
|
||||
let memory_bytes = memory::fast_resident_bytes(e.pid);
|
||||
let active = cpu_percent.unwrap_or(0.0) >= MIN_EXTERNAL_CPU_PERCENT
|
||||
|| memory_bytes.unwrap_or(0) >= MIN_EXTERNAL_MEMORY_BYTES;
|
||||
active.then(|| HostProcess { pid: e.pid, name: e.name.clone(), cpu_percent, memory_bytes })
|
||||
})
|
||||
.collect();
|
||||
external.sort_by(|a, b| {
|
||||
resource_share(b, rates.cpu_cores, rates.memory_total_bytes)
|
||||
.total_cmp(&resource_share(a, rates.cpu_cores, rates.memory_total_bytes))
|
||||
.then_with(|| b.memory_bytes.unwrap_or(0).cmp(&a.memory_bytes.unwrap_or(0)))
|
||||
.then_with(|| a.pid.cmp(&b.pid))
|
||||
});
|
||||
external.truncate(MAX_EXTERNAL_PROCESSES);
|
||||
(processes, external)
|
||||
} else {
|
||||
(Vec::new(), Vec::new())
|
||||
};
|
||||
|
||||
Ok(HostMetrics {
|
||||
cpu_percent: rates.cpu_percent,
|
||||
cpu_cores: rates.cpu_cores,
|
||||
load_average: rates.load_average,
|
||||
memory_used_bytes: rates.memory_used_bytes,
|
||||
memory_total_bytes: rates.memory_total_bytes,
|
||||
net_rx_bytes_per_sec: rates.net_rx_bytes_per_sec,
|
||||
net_tx_bytes_per_sec: rates.net_tx_bytes_per_sec,
|
||||
disk_read_bytes_per_sec: rates.disk_read_bytes_per_sec,
|
||||
disk_write_bytes_per_sec: rates.disk_write_bytes_per_sec,
|
||||
disk_available_bytes,
|
||||
disk_total_bytes,
|
||||
uptime_ms,
|
||||
processes,
|
||||
external_processes,
|
||||
})
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Ends a child process started by this OpenIDEA host (language server, run, terminal,
|
||||
/// debug adapter or agent) and its descendants; refuses processes outside this host's tree.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn host_end_process(host: &Arc<Host>, pid: u32) -> IdeResult<bool> {
|
||||
host.blocking(move || Ok(memory::end_process_tree(std::process::id(), pid, Duration::from_secs(3)))).await
|
||||
}
|
||||
|
||||
ide_command::domain!(host_metrics: host_metrics, host_end_process);
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::HostConfig;
|
||||
|
||||
#[tokio::test]
|
||||
async fn collects_light_and_detailed_host_metrics() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let host = Arc::new(Host::new(HostConfig::for_test(dir.path())));
|
||||
|
||||
let light = host_metrics(&host, "main", false).await.unwrap();
|
||||
assert!(light.cpu_cores >= 1);
|
||||
assert!(light.processes.is_empty());
|
||||
assert!(light.external_processes.is_empty());
|
||||
if cfg!(any(unix, windows)) {
|
||||
let avail = light.disk_available_bytes.expect("disk_available_bytes");
|
||||
let total = light.disk_total_bytes.expect("disk_total_bytes");
|
||||
assert!(total > 0 && avail <= total, "{avail} / {total}");
|
||||
}
|
||||
|
||||
let detailed = host_metrics(&host, "main", true).await.unwrap();
|
||||
assert!(!detailed.processes.is_empty());
|
||||
assert_eq!(detailed.processes[0].label, "Backend");
|
||||
assert!(detailed.external_processes.len() <= MAX_EXTERNAL_PROCESSES);
|
||||
|
||||
// Refuses to terminate the backend itself or PID 1.
|
||||
assert!(!host_end_process(&host, std::process::id()).await.unwrap());
|
||||
assert!(!host_end_process(&host, 1).await.unwrap());
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
@@ -139,7 +142,8 @@ pub(crate) async fn resolve_launch(
|
||||
};
|
||||
if let Some(outputs) = built {
|
||||
progress("Resolving the classpath");
|
||||
let mut info = project.lsp.java_launch(&module, test, false, false, false, cancel).await?;
|
||||
let server = project.lsp.java_launch(&module, test, false, false, false, cancel);
|
||||
let mut info = server_launch_extras(server, SERVER_EXTRAS_WAIT).await?;
|
||||
let data_dir = host.local_data_dir.clone();
|
||||
let cancel = cancel.clone();
|
||||
return tokio::task::spawn_blocking(move || {
|
||||
@@ -383,9 +387,40 @@ 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.
|
||||
/// How long a launch whose classpath the IDE's Java build resolved waits for what jdtls adds
|
||||
/// (the JDK it compiles against, the Java project root). jdtls can be busy for minutes importing
|
||||
/// a Maven project (resolving plugin dependencies), and the run doesn't need it:
|
||||
/// [`finish_launch`] picks the project's JDK or an installed one.
|
||||
const SERVER_EXTRAS_WAIT: std::time::Duration = std::time::Duration::from_secs(5);
|
||||
|
||||
/// jdtls' launch info, or an empty one when it doesn't answer within `wait` or fails.
|
||||
async fn server_launch_extras(
|
||||
server: impl std::future::Future<Output = IdeResult<JavaLaunchInfo>>,
|
||||
wait: std::time::Duration,
|
||||
) -> IdeResult<JavaLaunchInfo> {
|
||||
let fallback =
|
||||
|| JavaLaunchInfo { path_list_separator: if cfg!(windows) { ";" } else { ":" }.into(), ..Default::default() };
|
||||
match tokio::time::timeout(wait, server).await {
|
||||
Ok(Ok(info)) => Ok(info),
|
||||
Ok(Err(e)) if e.kind == ErrorKind::Cancelled => Err(e),
|
||||
Ok(Err(e)) => {
|
||||
tracing::warn!("Java launch without the language server's JDK: {}", e.message);
|
||||
Ok(fallback())
|
||||
}
|
||||
Err(_) => {
|
||||
tracing::info!(wait_ms = wait.as_millis(), "Java language server busy; launching without its JDK");
|
||||
Ok(fallback())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn served_by_service(root: &Path, model: &BuildModel, settings: &Settings, path: &Path) -> bool {
|
||||
let maven = model.maven.iter().flat_map(|m| m.projects.iter().map(|p| (root.join(&p.dir), true)));
|
||||
let gradle = model.gradle.iter().flat_map(|g| g.projects.iter().map(|p| (root.join(&p.dir), false)));
|
||||
@@ -418,31 +453,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 +491,7 @@ async fn resolve_launch_without_jdtls(
|
||||
&model,
|
||||
&module,
|
||||
test,
|
||||
Some(kind),
|
||||
(policy != BuildPolicy::NoBuild).then_some(kind),
|
||||
&cancel,
|
||||
&on_event,
|
||||
) {
|
||||
@@ -467,6 +503,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 +525,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 +543,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 +570,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()),
|
||||
@@ -903,7 +950,7 @@ 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, or has JUnit 4 alone; from the engine's repository, else downloaded once from
|
||||
/// Maven Central), and,
|
||||
/// Maven Central unless only the configured package registries are allowed), and,
|
||||
/// for a Maven module, what its Surefire configuration gives the forked test JVM.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn java_junit_runner(
|
||||
@@ -916,6 +963,7 @@ pub async fn java_junit_runner(
|
||||
let project = host.project(window)?;
|
||||
let module = ide_core::project_roots::resolve(&project.root, &module);
|
||||
let data_dir = host.local_data_dir.clone();
|
||||
let registries_only = host.configured_registries_only();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let scope = workspace::scope_for(&project, &module)?;
|
||||
let model = load_launch_model(&scope);
|
||||
@@ -929,7 +977,9 @@ pub async fn java_junit_runner(
|
||||
let launcher = match ide_sdk::java::junit_launcher(&class_paths) {
|
||||
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::Missing(version) => {
|
||||
Some(download_junit_launcher(&data_dir, &version, registries_only)?)
|
||||
}
|
||||
ide_sdk::java::JunitLauncher::NoPlatform => {
|
||||
return Err(IdeError::unavailable(
|
||||
"Neither JUnit 5 (junit-platform-engine) nor JUnit 4 is on the test classpath. To run these tests \
|
||||
@@ -998,7 +1048,9 @@ fn junit_launch(
|
||||
}
|
||||
}
|
||||
|
||||
fn download_junit_launcher(data_dir: &Path, version: &str) -> IdeResult<PathBuf> {
|
||||
/// The launcher jar downloaded once from Maven Central; with only the configured package
|
||||
/// registries allowed (Settings › Tools › Download Mirrors), only one downloaded before.
|
||||
fn download_junit_launcher(data_dir: &Path, version: &str, registries_only: bool) -> IdeResult<PathBuf> {
|
||||
if version.is_empty() || !version.chars().all(|c| c.is_ascii_alphanumeric() || "._-".contains(c)) {
|
||||
return Err(IdeError::invalid(format!("Unexpected JUnit Platform version '{version}'")));
|
||||
}
|
||||
@@ -1007,6 +1059,14 @@ fn download_junit_launcher(data_dir: &Path, version: &str) -> IdeResult<PathBuf>
|
||||
if dest.is_file() {
|
||||
return Ok(dest);
|
||||
}
|
||||
if registries_only {
|
||||
return Err(IdeError::unavailable(format!(
|
||||
"{name} is not on the test classpath, and Settings › Tools › Download Mirrors allows only the \
|
||||
configured package registries, so it is not downloaded from Maven Central. Add \
|
||||
org.junit.platform:junit-platform-launcher to the test dependencies, or set Settings › Build Tools › \
|
||||
Maven › Run tests using to Maven."
|
||||
)));
|
||||
}
|
||||
std::fs::create_dir_all(dest.parent().expect("has a parent"))?;
|
||||
let url = format!("https://repo1.maven.org/maven2/org/junit/platform/junit-platform-launcher/{version}/{name}");
|
||||
let partial = dest.with_extension("jar.part");
|
||||
@@ -1041,6 +1101,22 @@ fn drop_processor_recreate_errors(info: &mut JavaLaunchInfo) {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn a_busy_or_failing_language_server_does_not_block_a_resolved_launch() {
|
||||
let wait = std::time::Duration::from_secs(5);
|
||||
// jdtls importing a Maven project: no answer for minutes (#6122).
|
||||
let busy = server_launch_extras(std::future::pending(), wait).await.unwrap();
|
||||
assert!(busy.java_home.is_none() && busy.class_paths.is_empty());
|
||||
assert!(!busy.path_list_separator.is_empty());
|
||||
let failed = server_launch_extras(async { Err(IdeError::unavailable("timed out")) }, wait).await.unwrap();
|
||||
assert!(failed.java_home.is_none());
|
||||
let home = JavaLaunchInfo { java_home: Some(PathBuf::from("/jdk").into()), ..Default::default() };
|
||||
let answered = server_launch_extras(async { Ok(home) }, wait).await.unwrap();
|
||||
assert!(answered.java_home.is_some());
|
||||
let cancelled = server_launch_extras(async { Err(IdeError::cancelled()) }, wait).await;
|
||||
assert_eq!(cancelled.unwrap_err().kind, ErrorKind::Cancelled);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn junit_launch_applies_the_surefire_configuration() {
|
||||
let surefire = ide_build::surefire::SurefireConfig {
|
||||
|
||||
@@ -1881,6 +1881,29 @@ pub async fn lsp_snapshot_diagnostics(
|
||||
result
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn lsp_snapshot_completion(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
path: std::path::PathBuf,
|
||||
text: String,
|
||||
pos: Pos,
|
||||
request: RequestId,
|
||||
) -> IdeResult<Vec<CompletionItem>> {
|
||||
let project = host.project(window)?;
|
||||
if !path.is_absolute() || path.file_name().is_none() {
|
||||
return Err(IdeError::invalid("a text snapshot requires a file path"));
|
||||
}
|
||||
if text.len() as u64 > ide_vfs::LARGE_FILE_THRESHOLD {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let language = project.documents.language_of(&path, text.lines().next()).language;
|
||||
let cancel = host.begin_project_read_request(window, request);
|
||||
let result = project.lsp.snapshot_completion(&path, &language, &text, pos, &cancel).await;
|
||||
host.end_request(request);
|
||||
result
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn lsp_inlay_hints(host: &Host, window: &str, doc: DocId, range: Range) -> IdeResult<Vec<InlayHint>> {
|
||||
let lsp = host.project(window)?.lsp.clone();
|
||||
@@ -2292,6 +2315,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 +2335,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,
|
||||
@@ -3235,6 +3259,7 @@ ide_command::domain!(
|
||||
lsp_extract_interface_info,
|
||||
lsp_format,
|
||||
lsp_format_text,
|
||||
lsp_snapshot_completion,
|
||||
lsp_snapshot_diagnostics,
|
||||
lsp_source_action_text,
|
||||
lsp_goto,
|
||||
|
||||
@@ -19,6 +19,7 @@ pub mod flutter;
|
||||
pub mod fs;
|
||||
pub mod heap;
|
||||
pub mod history;
|
||||
pub mod host_metrics;
|
||||
pub mod http;
|
||||
pub mod java;
|
||||
pub mod jvm_icons;
|
||||
@@ -27,6 +28,7 @@ pub mod maven_placeholder;
|
||||
pub mod nav;
|
||||
pub mod notebook;
|
||||
pub mod project;
|
||||
pub mod pytest_fixtures;
|
||||
mod python;
|
||||
pub mod python_stubs;
|
||||
pub mod refactor;
|
||||
@@ -93,6 +95,7 @@ ide_command::domains!(
|
||||
fs: crate::ops::fs,
|
||||
heap: crate::ops::heap,
|
||||
history: crate::ops::history,
|
||||
host_metrics: crate::ops::host_metrics,
|
||||
http: crate::ops::http,
|
||||
java: crate::ops::java,
|
||||
jvm_icons: crate::ops::jvm_icons,
|
||||
|
||||
Loaded 100 of 1454 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Заблокувати користувача