дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-02 07:04:12 +02:00
Порівняти коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
21c7de45d9 | ||
|
|
a372385788 | ||
|
|
7ff8d472f7 | ||
|
|
4de01a91c5 | ||
|
|
657d49e30a | ||
|
|
2a7975a077 | ||
|
|
71d88d0b55 | ||
|
|
c6faf280db | ||
|
|
fba7705acf | ||
|
|
f87fb35be5 | ||
|
|
f4236a0ea1 | ||
|
|
1eece0ae51 | ||
|
|
7361707b63 | ||
|
|
8e56d3b73e | ||
|
|
e5453a8a97 | ||
|
|
27689f09d3 | ||
|
|
9b468b0873 | ||
|
|
cb887dad80 | ||
|
|
3cfbf80e26 | ||
|
|
97add1f448 | ||
|
|
35a6bec1c2 | ||
|
|
f8ba067e1d | ||
|
|
85cbc6bacd | ||
|
|
3f490684d6 | ||
|
|
8f6200c3fa | ||
|
|
0aa64c2c6e | ||
|
|
8d4e016cb0 | ||
|
|
a1ef8ca749 | ||
|
|
669462c4de | ||
|
|
90eb6bac1b | ||
|
|
674e925c9a | ||
|
|
ddd27a6e50 | ||
|
|
d4791ea0c2 | ||
|
|
baea2733f8 | ||
|
|
0d2401705e | ||
|
|
6c96b79538 | ||
|
|
878e86e10c | ||
|
|
6c36723a7d | ||
|
|
ed58f1aba0 | ||
|
|
adda2cbb93 | ||
|
|
132259242a | ||
|
|
1a400d3405 | ||
|
|
aa1711194c | ||
|
|
83dcdc8eca | ||
|
|
783daaa041 | ||
|
|
dc74595bca | ||
|
|
aa596f1125 | ||
|
|
6927b787b2 | ||
|
|
e1e9ede2d6 | ||
|
|
839292fb30 | ||
|
|
2a4bf1f848 | ||
|
|
3e41c93a95 | ||
|
|
b85027dc47 | ||
|
|
63c2ced086 | ||
|
|
d73b8d8ec1 | ||
|
|
74b90a114a | ||
|
|
e70b516ca0 | ||
|
|
7d15681313 | ||
|
|
2ecaefe859 | ||
|
|
895e5bd56e | ||
|
|
2dc577614b | ||
|
|
a9e92d0665 | ||
|
|
fa0be07436 | ||
|
|
fea27f5608 | ||
|
|
a4d172ac83 | ||
|
|
c40d06c702 | ||
|
|
619ae7f727 | ||
|
|
c725b1629d | ||
|
|
b0033a869d | ||
|
|
4ed4ced5b1 | ||
|
|
7668e4a5ba | ||
|
|
4a6e0dfac1 | ||
|
|
11e8f8a101 | ||
|
|
7a27f285e6 | ||
|
|
f21ae03bdd | ||
|
|
5dacbcd0cd | ||
|
|
281c2ff1e5 | ||
|
|
4276250056 | ||
|
|
ba04491ace | ||
|
|
660a311f21 | ||
|
|
92bf9354fe | ||
|
|
54da9c2c12 | ||
|
|
9ba3150998 | ||
|
|
190e5639f1 | ||
|
|
5f782e9c5d | ||
|
|
10fe5d21af | ||
|
|
16c30e819c | ||
|
|
43c8699beb | ||
|
|
071fbf7639 | ||
|
|
bde1e5f7a0 | ||
|
|
c1e8864138 | ||
|
|
5966d193c4 | ||
|
|
6d38521498 | ||
|
|
52e6a0f84b | ||
|
|
72873981aa | ||
|
|
d44a104ff8 | ||
|
|
23ea9cf07d | ||
|
|
cea3f4ac9c | ||
|
|
aee715f797 | ||
|
|
711349c6c1 | ||
|
|
9b2d783322 | ||
|
|
72ae354d29 | ||
|
|
dd8de05013 | ||
|
|
a547c8cdee | ||
|
|
a74d5b5dbb | ||
|
|
b895093f6b | ||
|
|
cbb9079577 | ||
|
|
44418411b8 | ||
|
|
5e23076766 | ||
|
|
689d3fd877 | ||
|
|
608ab44fca | ||
|
|
41545d38e5 | ||
|
|
4f86211dd6 | ||
|
|
203e4fbcb2 | ||
|
|
869e52f837 | ||
|
|
02e4c9c7a2 | ||
|
|
61be657209 | ||
|
|
52294c51c2 | ||
|
|
222d0b5ee3 | ||
|
|
cd8f29ea63 | ||
|
|
ba94abcb8b | ||
|
|
937eb0c3a0 | ||
|
|
b2d03ac5f0 | ||
|
|
4e735eadcb | ||
|
|
50ba6b5c56 | ||
|
|
36910712d1 | ||
|
|
5b99b8b5ab | ||
|
|
f3874b9b2e | ||
|
|
18b87b066b | ||
|
|
41a76ca0d7 | ||
|
|
1bf29ab3d7 | ||
|
|
49b52a8bfa | ||
|
|
77342b8e71 | ||
|
|
369ff7cec8 | ||
|
|
4016c410db | ||
|
|
3c3d02d7be | ||
|
|
2f66eb0503 | ||
|
|
63db10a688 | ||
|
|
1dd3d64781 | ||
|
|
8ac194cf50 | ||
|
|
3b488a7824 | ||
|
|
b5e89aace0 | ||
|
|
81c95b2ab7 | ||
|
|
f7b5cc388c | ||
|
|
277d0e9d1e | ||
|
|
d6adb7aa40 | ||
|
|
6e5e482410 | ||
|
|
cc02c2fe40 | ||
|
|
74a3f6470a | ||
|
|
4c8c078666 | ||
|
|
e672b14d52 | ||
|
|
c0300f8959 | ||
|
|
11cf9864a1 |
No files matched your search
@@ -11,3 +11,10 @@ package(=ide-clipboard) & (
|
||||
)
|
||||
'''
|
||||
test-group = "windows-clipboard"
|
||||
|
||||
# The Subversion tests run svn against throwaway servers: none should take minutes. A test
|
||||
# that hangs (a server left stopped) is ended after 5 minutes instead of waiting for svn's own
|
||||
# timeout.
|
||||
[[profile.default.overrides]]
|
||||
filter = 'package(=ide-svn) | (package(=ide-host) & (binary(=svn) | binary(=ij_svn_roots)))'
|
||||
slow-timeout = { period = "60s", terminate-after = 5 }
|
||||
@@ -150,8 +150,18 @@ jobs:
|
||||
- name: Linux deps
|
||||
if: runner.os == 'Linux'
|
||||
run: |
|
||||
pkgs=(libwebkit2gtk-4.1-dev libayatana-appindicator3-dev librsvg2-dev libxdo-dev libssl-dev patchelf)
|
||||
pkgs=(libwebkit2gtk-4.1-dev libayatana-appindicator3-dev librsvg2-dev libxdo-dev libssl-dev patchelf subversion sqlite3)
|
||||
dpkg -s "${pkgs[@]}" >/dev/null 2>&1 || { sudo apt-get update && sudo apt-get install -y "${pkgs[@]}"; }
|
||||
# The Subversion tests run the real svn, svnadmin and svnserve (and sqlite3, to write a
|
||||
# working copy's database); with CI set they fail instead of skipping when these are
|
||||
# missing. Linux gets them with the deps above; macOS has sqlite3. Windows runners skip them.
|
||||
- name: Subversion (macOS)
|
||||
if: runner.os == 'macOS'
|
||||
run: command -v svnadmin >/dev/null || brew install subversion
|
||||
- name: Subversion version
|
||||
if: runner.os != 'Windows'
|
||||
shell: bash
|
||||
run: svn --version --quiet && svnadmin --version --quiet && svnserve --version --quiet && sqlite3 --version
|
||||
# tauri-build checks that frontendDist exists.
|
||||
- run: pnpm install --frozen-lockfile && mkdir -p dist
|
||||
shell: bash
|
||||
|
||||
@@ -34,6 +34,7 @@ on:
|
||||
- "src/editor/relatedProviders.ts"
|
||||
- "src/editor/core/cm/cornerInset.ts"
|
||||
- "src/editor/core/cm/iconArea.ts"
|
||||
- "src/editor/core/cm/inlineBg.ts"
|
||||
- "src/editor/core/cm/localAppearance.ts"
|
||||
- "src/editor/lsp/availability.ts"
|
||||
- "src/editor/lsp/diagnostics.ts"
|
||||
@@ -109,7 +110,7 @@ jobs:
|
||||
# ide-lsp/dap/run/sdk/tools.
|
||||
unused='^crates/(ide-agent|ide-analysis|ide-android|ide-cli|ide-clipboard|ide-coverage|ide-db|ide-docker|ide-fonts|ide-github|ide-mcp|ide-notebook|ide-profiler|ide-scaffold|ide-spell|ide-ssh|ide-vcs|ide-web)/'
|
||||
# The workflow's paths, less those handled per language below.
|
||||
smoke='^(crates/|Cargo\.(toml|lock)$|src/features/(run|debugger|build|build-tools)/|src/platform/|src/workbench/|src/ui/|src/editor/(api|navigationProviders|refactorProviders|relatedProviders|core/cm/(cornerInset|iconArea|localAppearance)|lsp/(availability|diagnostics|files|hint|lsp|positions|snippet))\.ts$|src/bindings\.ts$|src/styles/tokens\.css$|src/test/setup\.ts$|src-tauri/icons/128x128\.png$|smoke/|vite\.config\.ts$|tsconfig\.json$|package\.json$|pnpm-(lock|workspace)\.yaml$|patches/|\.github/workflows/language-smoke\.yml$|\.github/tool-versions\.env$)'
|
||||
smoke='^(crates/|Cargo\.(toml|lock)$|src/features/(run|debugger|build|build-tools)/|src/platform/|src/workbench/|src/ui/|src/editor/(api|navigationProviders|refactorProviders|relatedProviders|core/cm/(cornerInset|iconArea|inlineBg|localAppearance)|lsp/(availability|diagnostics|files|hint|lsp|positions|snippet))\.ts$|src/bindings\.ts$|src/styles/tokens\.css$|src/test/setup\.ts$|src-tauri/icons/128x128\.png$|smoke/|vite\.config\.ts$|tsconfig\.json$|package\.json$|pnpm-(lock|workspace)\.yaml$|patches/|\.github/workflows/language-smoke\.yml$|\.github/tool-versions\.env$)'
|
||||
langs=""
|
||||
while read -r f; do
|
||||
case "$f" in
|
||||
|
||||
@@ -284,6 +284,8 @@ jobs:
|
||||
return;
|
||||
}
|
||||
// Bundle suffix → updater platform keys, as tauri-action names them.
|
||||
// Nightly builds skip RPM because RPM rejects `-` in SemVer prerelease versions.
|
||||
const nightly = tag.includes("-nightly.");
|
||||
const windows = (arch, msi, nsis) => [
|
||||
[msi, [`windows-${arch}`, `windows-${arch}-msi`]],
|
||||
[nsis, [`windows-${arch}-nsis`]],
|
||||
@@ -291,10 +293,10 @@ jobs:
|
||||
const kinds = [
|
||||
[/_aarch64\.AppImage$/, ["linux-aarch64", "linux-aarch64-appimage"]],
|
||||
[/_arm64\.deb$/, ["linux-aarch64-deb"]],
|
||||
[/\.aarch64\.rpm$/, ["linux-aarch64-rpm"]],
|
||||
...(nightly ? [] : [[/\.aarch64\.rpm$/, ["linux-aarch64-rpm"]]]),
|
||||
[/_amd64\.AppImage$/, ["linux-x86_64", "linux-x86_64-appimage"]],
|
||||
[/_amd64\.deb$/, ["linux-x86_64-deb"]],
|
||||
[/\.x86_64\.rpm$/, ["linux-x86_64-rpm"]],
|
||||
...(nightly ? [] : [[/\.x86_64\.rpm$/, ["linux-x86_64-rpm"]]]),
|
||||
[/_aarch64\.app\.tar\.gz$/, ["darwin-aarch64", "darwin-aarch64-app"]],
|
||||
[/_x64\.app\.tar\.gz$/, ["darwin-x86_64", "darwin-x86_64-app"]],
|
||||
...windows("aarch64", /_arm64_en-US\.msi$/, /_arm64-setup\.exe$/),
|
||||
|
||||
@@ -15,6 +15,7 @@
|
||||
"src/editor/core/cm/jsp/parser*.ts",
|
||||
"src/editor/core/cm/astro/parser*.ts",
|
||||
"src/editor/core/cm/django/parser*.ts",
|
||||
"src/editor/core/cm/freemarker/parser*.ts",
|
||||
"plugins/themes.md",
|
||||
"pnpm-lock.yaml",
|
||||
"**/*.toml",
|
||||
|
||||
@@ -152,7 +152,10 @@
|
||||
"files": ["**/*.ts", "**/*.tsx", "**/*.mts", "**/*.cts"],
|
||||
"excludeFiles": ["e2e/**"],
|
||||
"rules": {
|
||||
"no-await-in-loop": "error"
|
||||
"no-await-in-loop": "error",
|
||||
"react/no-array-index-key": "error",
|
||||
"react/jsx-no-constructed-context-values": "error",
|
||||
"react/no-object-type-as-default-prop": "error"
|
||||
}
|
||||
}
|
||||
]
|
||||
|
||||
Створено
+32
-1
@@ -2766,6 +2766,7 @@ dependencies = [
|
||||
"gix-ignore",
|
||||
"gix-index",
|
||||
"gix-lock",
|
||||
"gix-mailmap",
|
||||
"gix-note",
|
||||
"gix-object",
|
||||
"gix-odb",
|
||||
@@ -3132,6 +3133,18 @@ dependencies = [
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gix-mailmap"
|
||||
version = "0.36.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a30866257cc7f0af5b85f98a9e87dc73e46de8cb1838ee18c9dbe08a2461717e"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"gix-actor",
|
||||
"gix-date",
|
||||
"gix-error",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gix-note"
|
||||
version = "0.3.1"
|
||||
@@ -4166,6 +4179,7 @@ dependencies = [
|
||||
"ide-tools",
|
||||
"ide-vcs",
|
||||
"ide-vfs",
|
||||
"jiff",
|
||||
"parking_lot 0.12.5",
|
||||
"rustix",
|
||||
"semver",
|
||||
@@ -4173,12 +4187,13 @@ dependencies = [
|
||||
"serde_json",
|
||||
"sha1 0.10.7",
|
||||
"specta",
|
||||
"sqlx",
|
||||
"tempfile",
|
||||
"tokio",
|
||||
"toml 0.9.12+spec-1.1.0",
|
||||
"toml_edit 0.25.17+spec-1.1.0",
|
||||
"tracing",
|
||||
"uuid",
|
||||
"which",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4513,6 +4528,7 @@ dependencies = [
|
||||
"ide-spell",
|
||||
"ide-ssh",
|
||||
"ide-streams",
|
||||
"ide-svn",
|
||||
"ide-syntax",
|
||||
"ide-terminal",
|
||||
"ide-text",
|
||||
@@ -4971,6 +4987,21 @@ dependencies = [
|
||||
"tree-sitter",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ide-svn"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"encoding_rs",
|
||||
"ide-core",
|
||||
"ide-vcs",
|
||||
"parking_lot 0.12.5",
|
||||
"quick-xml 0.42.0",
|
||||
"tempfile",
|
||||
"which",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ide-syntax"
|
||||
version = "0.1.56"
|
||||
|
||||
@@ -24,6 +24,7 @@ ide-jsonrpc = { path = "crates/ide-jsonrpc" }
|
||||
ide-lsp = { path = "crates/ide-lsp" }
|
||||
ide-dap = { path = "crates/ide-dap" }
|
||||
ide-vcs = { path = "crates/ide-vcs" }
|
||||
ide-svn = { path = "crates/ide-svn" }
|
||||
ide-github = { path = "crates/ide-github" }
|
||||
ide-terminal = { path = "crates/ide-terminal" }
|
||||
ide-run = { path = "crates/ide-run" }
|
||||
@@ -90,6 +91,7 @@ trash = "5"
|
||||
blake3 = "1"
|
||||
dunce = "1"
|
||||
dirs = "6"
|
||||
jiff = "0.2"
|
||||
memmap2 = "0.9"
|
||||
zip = { version = "9.2.3", default-features = false, features = ["deflate"] }
|
||||
flate2 = "1"
|
||||
|
||||
@@ -6,6 +6,11 @@ contributors as part of the IntelliJ Platform (https://github.com/JetBrains/inte
|
||||
https://github.com/JetBrains/intellij-plugins), licensed under the Apache License 2.0.
|
||||
Copyright 2000-2026 JetBrains s.r.o. and contributors.
|
||||
|
||||
The Subversion tests (crates/ide-svn/tests/matrix.rs) take the tree-conflict scenarios,
|
||||
their names and file contents from IntelliJ's svn4idea TreeConflictData
|
||||
(plugins/svn4idea/testSource/org/jetbrains/idea/svn/), Apache License 2.0, Copyright
|
||||
2000-2026 JetBrains s.r.o. and contributors.
|
||||
|
||||
Some Simplified Chinese UI terms follow the Visual Studio Code Simplified Chinese
|
||||
language pack (https://github.com/microsoft/vscode-loc), Copyright (c) Microsoft
|
||||
Corporation, licensed under the MIT License.
|
||||
|
||||
+1
-1
@@ -71,7 +71,7 @@ the [official plugins](plugins/official). The plugin API is still a preview.
|
||||
|
||||
## Community
|
||||
|
||||
- [Discord](https://discord.gg/2Zy4yn7gP) — questions, feedback and release news.
|
||||
- [Discord](https://discord.gg/AsZqMgxZm) — questions, feedback and release news.
|
||||
- WeChat group — scan to join:
|
||||
|
||||
<img src=".github/assets/wechat-group-4.png" alt="WeChat group QR code" width="200">
|
||||
|
||||
+1
-1
@@ -71,7 +71,7 @@ Eklentileri Ayarlar › Eklentiler (Settings › Plugins) bölümünden kur ya d
|
||||
|
||||
## Topluluk
|
||||
|
||||
- [Discord](https://discord.gg/2Zy4yn7gP): sorular, geri bildirim ve sürüm haberleri.
|
||||
- [Discord](https://discord.gg/AsZqMgxZm): sorular, geri bildirim ve sürüm haberleri.
|
||||
- WeChat grubu, katılmak için kodu okut:
|
||||
|
||||
<img src=".github/assets/wechat-group-4.png" alt="WeChat grubu QR kodu" width="200">
|
||||
|
||||
@@ -69,7 +69,7 @@ WebAssembly 组件运行;主题、图标主题和语言无需编写代码。
|
||||
|
||||
## 社区
|
||||
|
||||
- [Discord](https://discord.gg/2Zy4yn7gP):提问、反馈和版本发布消息。
|
||||
- [Discord](https://discord.gg/AsZqMgxZm):提问、反馈和版本发布消息。
|
||||
- 微信群,扫码加入:
|
||||
|
||||
<img src=".github/assets/wechat-group-4.png" alt="微信群二维码" width="200">
|
||||
|
||||
@@ -18,14 +18,16 @@ ide-tools = { path = "../ide-tools" }
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
specta.workspace = true
|
||||
sqlx.workspace = true
|
||||
tokio.workspace = true
|
||||
toml.workspace = true
|
||||
toml_edit.workspace = true
|
||||
tracing.workspace = true
|
||||
parking_lot.workspace = true
|
||||
dunce.workspace = true
|
||||
jiff.workspace = true
|
||||
uuid.workspace = true
|
||||
tempfile.workspace = true
|
||||
which = "8"
|
||||
semver = "1"
|
||||
sha1 = "0.10"
|
||||
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -58,7 +58,9 @@ impl AgentManager {
|
||||
if spec.source != AgentSource::Builtin {
|
||||
return Ok(AgentCliUpdateResult::Unmanaged);
|
||||
}
|
||||
let Ok(npm) = which::which("npm") else { return Ok(AgentCliUpdateResult::Unmanaged) };
|
||||
let Some(npm) = ide_core::process::find_executable("npm", &ide_core::tool_path::search_path()) else {
|
||||
return Ok(AgentCliUpdateResult::Unmanaged);
|
||||
};
|
||||
let program = spec.resolve_for_launch(&self.shared.paths.project_root).command;
|
||||
match maintain(&npm, Path::new(&program), &builtin.command, pkg, offer, cancel) {
|
||||
Err(e) if e.kind == ErrorKind::Unavailable => Ok(AgentCliUpdateResult::Error { code: e.message }),
|
||||
|
||||
@@ -131,7 +131,263 @@ fn is_bypass_mode(mode: &str) -> bool {
|
||||
let lower = mode.to_lowercase();
|
||||
let m: String =
|
||||
lower.rsplit(['#', '/']).next().unwrap_or_default().chars().filter(char::is_ascii_lowercase).collect();
|
||||
m.contains("bypass") || m == "yolo" || m.contains("fullaccess") || m == "dangerous"
|
||||
m.contains("bypass") || m == "yolo" || m.contains("fullaccess") || m == "dangerous" || m == "autopilot"
|
||||
}
|
||||
|
||||
fn upsert_choice(wanted: &mut Vec<crate::model::AgentConfigChoice>, id: &str, value: &str) {
|
||||
if let Some(existing) = wanted.iter_mut().find(|c| c.id == id) {
|
||||
existing.value = value.to_owned();
|
||||
} else {
|
||||
wanted.push(crate::model::AgentConfigChoice { id: id.to_owned(), value: value.to_owned() });
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn is_approval_option(opt: &AgentConfigOption) -> bool {
|
||||
opt.id == CURSOR_APPROVAL || matches!(opt.category.as_deref(), Some("mode" | "permissions" | "approval"))
|
||||
}
|
||||
|
||||
fn wanted_val(wanted: &[crate::model::AgentConfigChoice], id: &str) -> Option<String> {
|
||||
wanted.iter().find(|c| c.id == id).map(|c| c.value.clone())
|
||||
}
|
||||
|
||||
/// Applies an automation's permission policy (`mode`) to `config` and `wanted`, enforcing the
|
||||
/// user's interactive approval setting (`interactive`) as a strict ceiling. When `mode` is `None`
|
||||
/// (an in-session `/loop` or `Send Later` turn), clamps any bypass options down when `interactive`
|
||||
/// is [`ide_core::settings::NewTaskApprovals::Ask`].
|
||||
pub(crate) fn clamp_automation_permissions(
|
||||
provider: &str,
|
||||
mode: Option<crate::automation::AutomationPermissionMode>,
|
||||
interactive: ide_core::settings::NewTaskApprovals,
|
||||
config: &mut [AgentConfigOption],
|
||||
wanted: &mut Vec<crate::model::AgentConfigChoice>,
|
||||
) {
|
||||
use crate::automation::AutomationPermissionMode;
|
||||
use ide_core::settings::NewTaskApprovals;
|
||||
|
||||
if mode.is_none() && interactive == NewTaskApprovals::Bypass {
|
||||
return;
|
||||
}
|
||||
|
||||
let allow_bypass = interactive == NewTaskApprovals::Bypass && mode == Some(AutomationPermissionMode::AllowAll);
|
||||
|
||||
if !allow_bypass {
|
||||
// Strip any explicit bypass choices from `wanted` first so they cannot re-elevate later.
|
||||
wanted.retain(|c| match c.id.as_str() {
|
||||
"mode" => !is_bypass_mode(&c.value),
|
||||
"allow_all" | "permissions" => !matches!(c.value.to_ascii_lowercase().as_str(), "on" | "true"),
|
||||
"approval" | CURSOR_APPROVAL => !c.value.eq_ignore_ascii_case("bypass"),
|
||||
"approval_policy" => !c.value.eq_ignore_ascii_case("never"),
|
||||
_ => true,
|
||||
});
|
||||
ask_for_approvals(config);
|
||||
}
|
||||
|
||||
match provider {
|
||||
"claude" | "claude-acp" => {
|
||||
let cur_wanted = wanted_val(wanted, "mode");
|
||||
let target = if allow_bypass {
|
||||
match cur_wanted.as_deref() {
|
||||
Some("default" | "plan" | "acceptEdits") => cur_wanted.as_deref().unwrap().to_owned(),
|
||||
_ => "bypassPermissions".to_owned(),
|
||||
}
|
||||
} else if interactive == NewTaskApprovals::Bypass && mode == Some(AutomationPermissionMode::Assisted) {
|
||||
match cur_wanted.as_deref() {
|
||||
Some("default" | "plan") => cur_wanted.as_deref().unwrap().to_owned(),
|
||||
_ => "acceptEdits".to_owned(),
|
||||
}
|
||||
} else {
|
||||
// Either Default mode or interactive policy is Ask (where interactive Claude starts in `default`).
|
||||
match cur_wanted.as_deref() {
|
||||
Some("plan") => "plan".to_owned(),
|
||||
_ => "default".to_owned(),
|
||||
}
|
||||
};
|
||||
if let Some(opt) = config.iter_mut().find(|o| o.id == "mode" || o.category.as_deref() == Some("mode"))
|
||||
&& opt.values.iter().any(|v| v.value == target)
|
||||
{
|
||||
let id = opt.id.clone();
|
||||
opt.current = Some(target.clone());
|
||||
upsert_choice(wanted, &id, &target);
|
||||
} else if mode.is_some() || cur_wanted.is_some() {
|
||||
upsert_choice(wanted, "mode", &target);
|
||||
}
|
||||
}
|
||||
"codex" | "codex-acp" => {
|
||||
let cur_wanted = wanted_val(wanted, "mode");
|
||||
let target = if allow_bypass {
|
||||
match cur_wanted.as_deref() {
|
||||
Some("read-only" | "ask" | "auto") => cur_wanted.as_deref().unwrap().to_owned(),
|
||||
_ => "full-access".to_owned(),
|
||||
}
|
||||
} else if mode == Some(AutomationPermissionMode::Default) {
|
||||
"read-only".to_owned()
|
||||
} else if mode.is_some() {
|
||||
// Assisted, or AllowAll clamped by interactive Ask (`ask_for_approvals` maps full-access -> ask).
|
||||
match cur_wanted.as_deref() {
|
||||
Some("read-only") => "read-only".to_owned(),
|
||||
_ => "ask".to_owned(),
|
||||
}
|
||||
} else {
|
||||
// Scheduled /loop or Send Later under interactive Ask: never full-access.
|
||||
match cur_wanted.as_deref() {
|
||||
Some("read-only" | "ask" | "auto") => cur_wanted.as_deref().unwrap().to_owned(),
|
||||
_ => "ask".to_owned(),
|
||||
}
|
||||
};
|
||||
if let Some(opt) = config.iter_mut().find(|o| o.id == "mode" || o.category.as_deref() == Some("mode"))
|
||||
&& opt.values.iter().any(|v| v.value == target)
|
||||
{
|
||||
let id = opt.id.clone();
|
||||
opt.current = Some(target.clone());
|
||||
upsert_choice(wanted, &id, &target);
|
||||
} else if mode.is_some() || cur_wanted.is_some() {
|
||||
upsert_choice(wanted, "mode", &target);
|
||||
}
|
||||
}
|
||||
"copilot" => {
|
||||
if allow_bypass {
|
||||
if !matches!(wanted_val(wanted, "allow_all").as_deref(), Some("off" | "false")) {
|
||||
upsert_choice(wanted, "allow_all", "on");
|
||||
if let Some(opt) = config.iter_mut().find(|o| o.id == "allow_all") {
|
||||
opt.current = Some("on".into());
|
||||
}
|
||||
}
|
||||
} else {
|
||||
upsert_choice(wanted, "allow_all", "off");
|
||||
if let Some(opt) = config.iter_mut().find(|o| o.id == "allow_all") {
|
||||
opt.current = Some("off".into());
|
||||
}
|
||||
let non_auto = match wanted_val(wanted, "mode").as_deref() {
|
||||
Some("plan") => "plan",
|
||||
_ => "agent",
|
||||
};
|
||||
if mode.is_some() || config.iter().any(|o| o.id == "mode" && o.current.as_deref() == Some("autopilot"))
|
||||
{
|
||||
upsert_choice(wanted, "mode", non_auto);
|
||||
}
|
||||
if let Some(opt) = config.iter_mut().find(|o| o.id == "mode")
|
||||
&& (mode.is_some() || opt.current.as_deref() == Some("autopilot"))
|
||||
&& opt.values.iter().any(|v| v.value == non_auto)
|
||||
{
|
||||
opt.current = Some(non_auto.into());
|
||||
}
|
||||
}
|
||||
}
|
||||
"cursor" => {
|
||||
let target = if allow_bypass && wanted_val(wanted, CURSOR_APPROVAL).as_deref() != Some("ask") {
|
||||
"bypass"
|
||||
} else {
|
||||
"ask"
|
||||
};
|
||||
upsert_choice(wanted, CURSOR_APPROVAL, target);
|
||||
if let Some(opt) = config.iter_mut().find(|o| o.id == CURSOR_APPROVAL) {
|
||||
opt.current = Some(target.into());
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
if allow_bypass {
|
||||
let user_chose_non_bypass = config.iter().any(|o| {
|
||||
is_approval_option(o)
|
||||
&& wanted.iter().any(|c| {
|
||||
c.id == o.id && o.category.as_deref().and_then(bypass_value).is_some_and(|b| !b(&c.value))
|
||||
})
|
||||
});
|
||||
if !user_chose_non_bypass {
|
||||
apply_bypass_approvals(config);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Ensure every approval-bearing option in `config` has its enforced value mirrored in `wanted`
|
||||
// so `open_session` actively configures the live session even if the CLI's own config differs.
|
||||
for opt in config.iter().filter(|o| is_approval_option(o)) {
|
||||
if let Some(cur) = opt.current.as_deref() {
|
||||
upsert_choice(wanted, &opt.id, cur);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Verifies that the session's reported `config` options do not exceed the required automation
|
||||
/// permission ceiling (`min(mode, interactive)`). Returns `Err(reason)` if the provider remained
|
||||
/// in a more permissive mode than allowed.
|
||||
pub(crate) fn verify_automation_ceiling(
|
||||
provider: &str,
|
||||
mode: Option<crate::automation::AutomationPermissionMode>,
|
||||
interactive: ide_core::settings::NewTaskApprovals,
|
||||
config: &[AgentConfigOption],
|
||||
) -> Result<(), String> {
|
||||
use crate::automation::AutomationPermissionMode;
|
||||
use ide_core::settings::NewTaskApprovals;
|
||||
|
||||
if mode.is_none() && interactive == NewTaskApprovals::Bypass {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let allow_bypass = interactive == NewTaskApprovals::Bypass && mode == Some(AutomationPermissionMode::AllowAll);
|
||||
if !allow_bypass && bypass_approvals(config) {
|
||||
return Err("Agent did not confirm the required approval ceiling (session remained in bypass mode).".into());
|
||||
}
|
||||
|
||||
let cur_of = |id: &str| config.iter().find(|o| o.id == id).and_then(|o| o.current.as_deref());
|
||||
let mode_cur = config
|
||||
.iter()
|
||||
.find(|o| o.id == "mode" || o.category.as_deref() == Some("mode"))
|
||||
.and_then(|o| o.current.as_deref());
|
||||
|
||||
if !allow_bypass {
|
||||
match provider {
|
||||
"claude" | "claude-acp" => {
|
||||
if let Some(cur) = mode_cur {
|
||||
let allowed = if interactive == NewTaskApprovals::Bypass
|
||||
&& mode == Some(AutomationPermissionMode::Assisted)
|
||||
{
|
||||
matches!(cur, "default" | "plan" | "acceptEdits")
|
||||
} else {
|
||||
matches!(cur, "default" | "plan")
|
||||
};
|
||||
if !allowed {
|
||||
return Err(format!(
|
||||
"Claude session remained in mode '{cur}', exceeding the required approval ceiling."
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
"codex" | "codex-acp" => {
|
||||
if let Some(cur) = mode_cur {
|
||||
let allowed = if mode == Some(AutomationPermissionMode::Default) {
|
||||
cur == "read-only"
|
||||
} else if mode.is_some() {
|
||||
matches!(cur, "read-only" | "ask")
|
||||
} else {
|
||||
matches!(cur, "read-only" | "ask" | "auto")
|
||||
};
|
||||
if !allowed {
|
||||
return Err(format!(
|
||||
"Codex session remained in mode '{cur}', exceeding the required approval ceiling."
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
"copilot" => {
|
||||
if let Some(cur) = cur_of("allow_all")
|
||||
&& matches!(cur.to_ascii_lowercase().as_str(), "on" | "true")
|
||||
{
|
||||
return Err("Copilot session kept allow_all enabled above the approval ceiling.".into());
|
||||
}
|
||||
if let Some(cur) = mode_cur
|
||||
&& cur.eq_ignore_ascii_case("autopilot")
|
||||
{
|
||||
return Err("Copilot session remained in autopilot mode above the approval ceiling.".into());
|
||||
}
|
||||
}
|
||||
"cursor" if cur_of(CURSOR_APPROVAL).is_some_and(|cur| cur.eq_ignore_ascii_case("bypass")) => {
|
||||
return Err("Cursor session remained in bypass mode above the approval ceiling.".into());
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The settings in a `session/new` or `session/load` result: its select `configOptions`,
|
||||
@@ -669,6 +925,87 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn automation_permissions_respect_interactive_approval_ceiling() {
|
||||
use crate::automation::AutomationPermissionMode;
|
||||
use crate::model::AgentConfigChoice;
|
||||
use ide_core::settings::NewTaskApprovals;
|
||||
|
||||
let claude_opts = || {
|
||||
options_of(&json!({"configOptions": [{
|
||||
"id": "mode", "category": "mode", "type": "select", "currentValue": "bypassPermissions",
|
||||
"defaultValue": "default",
|
||||
"options": [
|
||||
{"value": "default"}, {"value": "acceptEdits"}, {"value": "plan"}, {"value": "bypassPermissions"}
|
||||
]
|
||||
}]}))
|
||||
};
|
||||
|
||||
// Claude Assisted under interactive Bypass -> acceptEdits; under interactive Ask -> default!
|
||||
let mut c = claude_opts();
|
||||
let mut wanted = Vec::new();
|
||||
clamp_automation_permissions(
|
||||
"claude",
|
||||
Some(AutomationPermissionMode::Assisted),
|
||||
NewTaskApprovals::Bypass,
|
||||
&mut c,
|
||||
&mut wanted,
|
||||
);
|
||||
assert_eq!(c[0].current.as_deref(), Some("acceptEdits"));
|
||||
assert!(wanted.iter().any(|w| w.id == "mode" && w.value == "acceptEdits"));
|
||||
|
||||
let mut c_ask = claude_opts();
|
||||
let mut wanted_ask = vec![AgentConfigChoice { id: "mode".into(), value: "bypassPermissions".into() }];
|
||||
clamp_automation_permissions(
|
||||
"claude",
|
||||
Some(AutomationPermissionMode::AllowAll),
|
||||
NewTaskApprovals::Ask,
|
||||
&mut c_ask,
|
||||
&mut wanted_ask,
|
||||
);
|
||||
assert_eq!(c_ask[0].current.as_deref(), Some("default"));
|
||||
assert_eq!(wanted_ask, vec![AgentConfigChoice { id: "mode".into(), value: "default".into() }]);
|
||||
|
||||
// Copilot AllowAll under interactive Ask clamps allow_all -> off and autopilot -> agent.
|
||||
let mut copilot = options_of(&json!({"configOptions": [
|
||||
{"id": "mode", "category": "mode", "type": "select", "currentValue": "autopilot",
|
||||
"options": [{"value": "agent"}, {"value": "plan"}, {"value": "autopilot"}]},
|
||||
{"id": "allow_all", "category": "permissions", "type": "select", "currentValue": "on",
|
||||
"options": [{"value": "off"}, {"value": "on"}]}
|
||||
]}));
|
||||
let mut copilot_wanted = vec![AgentConfigChoice { id: "allow_all".into(), value: "on".into() }];
|
||||
clamp_automation_permissions(
|
||||
"copilot",
|
||||
Some(AutomationPermissionMode::AllowAll),
|
||||
NewTaskApprovals::Ask,
|
||||
&mut copilot,
|
||||
&mut copilot_wanted,
|
||||
);
|
||||
assert_eq!(ids(&copilot), [("mode", Some("agent")), ("allow_all", Some("off"))]);
|
||||
assert!(!bypass_approvals(&copilot));
|
||||
|
||||
// Codex Default -> read-only, Assisted -> ask, AllowAll + Ask -> ask, AllowAll + Bypass -> full-access.
|
||||
let codex_opts = || {
|
||||
options_of(&json!({"configOptions": [{
|
||||
"id": "mode", "category": "mode", "type": "select", "currentValue": "full-access",
|
||||
"defaultValue": "ask",
|
||||
"options": [{"value": "read-only"}, {"value": "ask"}, {"value": "auto"}, {"value": "full-access"}]
|
||||
}]}))
|
||||
};
|
||||
for (perm, interactive, expected) in [
|
||||
(AutomationPermissionMode::Default, NewTaskApprovals::Bypass, "read-only"),
|
||||
(AutomationPermissionMode::Assisted, NewTaskApprovals::Bypass, "ask"),
|
||||
(AutomationPermissionMode::AllowAll, NewTaskApprovals::Ask, "ask"),
|
||||
(AutomationPermissionMode::AllowAll, NewTaskApprovals::Bypass, "full-access"),
|
||||
] {
|
||||
let mut opts = codex_opts();
|
||||
let mut w = Vec::new();
|
||||
clamp_automation_permissions("codex", Some(perm), interactive, &mut opts, &mut w);
|
||||
assert_eq!(opts[0].current.as_deref(), Some(expected), "{perm:?} + {interactive:?}");
|
||||
assert!(w.iter().any(|c| c.id == "mode" && c.value == expected));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn command_sources_in_updates_and_stored_tasks() {
|
||||
let update = json!({"availableCommands": [
|
||||
|
||||
@@ -2,9 +2,10 @@
|
||||
//! scanned so they can be listed and imported as tasks instead of re-explained (#312).
|
||||
//!
|
||||
//! Only the native providers keep transcripts on disk in a readable form: Claude Code
|
||||
//! (`<config>/projects/*/<id>.jsonl`, see `native::claude::history`) and Codex
|
||||
//! (`<config>/projects/*/<id>.jsonl`, see `native::claude::history`), Codex
|
||||
//! (`<home>/.codex/sessions/**`, rollout files with a `session_meta` line, named in
|
||||
//! `<home>/.codex/session_index.jsonl`).
|
||||
//! `<home>/.codex/session_index.jsonl`), and Copilot
|
||||
//! (`<config>/session-state/<id>/workspace.yaml` plus `events.jsonl`).
|
||||
|
||||
use super::native::claude::history;
|
||||
use serde::Serialize;
|
||||
@@ -17,7 +18,7 @@ use std::path::{Path, PathBuf};
|
||||
#[derive(Clone, Debug, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ExternalSession {
|
||||
/// The [`crate::AgentProvider`] id that owns it (`claude`, `codex`).
|
||||
/// The [`crate::AgentProvider`] id that owns it (`claude`, `codex`, `copilot`).
|
||||
pub provider: String,
|
||||
/// The id resuming it names (`--resume`, `thread/resume`).
|
||||
pub session_id: String,
|
||||
@@ -26,6 +27,9 @@ pub struct ExternalSession {
|
||||
pub cwd: Option<String>,
|
||||
/// File modification time, ms since the epoch.
|
||||
pub updated_ms: f64,
|
||||
/// Another live process (VS Code, a terminal Copilot CLI) has it open: importing would let two
|
||||
/// apps write the same session, so forking a copy is the safe choice.
|
||||
pub in_use: bool,
|
||||
}
|
||||
|
||||
/// Modification time of `path` in ms, else 0.
|
||||
@@ -123,6 +127,7 @@ pub fn claude_sessions(config_dir: &Path, root: &Path) -> Vec<ExternalSession> {
|
||||
title,
|
||||
cwd,
|
||||
updated_ms: mtime(&path),
|
||||
in_use: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -193,6 +198,7 @@ fn codex_file(path: &Path) -> Option<ExternalSession> {
|
||||
session_id,
|
||||
cwd,
|
||||
updated_ms: mtime(path),
|
||||
in_use: false,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -246,6 +252,289 @@ pub fn codex_sessions(codex_home: &Path, root: &Path) -> Vec<ExternalSession> {
|
||||
sessions
|
||||
}
|
||||
|
||||
/// Whether `raw` is a YAML block-scalar header (`|`, `|-`, `|+`, `>`, `>-`, `>+`, with optional indent digit).
|
||||
fn is_yaml_block_header(raw: &str) -> bool {
|
||||
let mut chars = raw.chars();
|
||||
matches!(chars.next(), Some('|' | '>')) && chars.all(|c| matches!(c, '-' | '+') || c.is_ascii_digit())
|
||||
}
|
||||
|
||||
/// Unquotes a single-line YAML scalar value from Copilot's `workspace.yaml`.
|
||||
fn parse_yaml_inline_value(raw: &str) -> String {
|
||||
if raw.starts_with('"') {
|
||||
serde_json::from_str(raw).unwrap_or_else(|_| raw.trim_matches('"').to_owned())
|
||||
} else if raw.starts_with('\'') && raw.ends_with('\'') && raw.len() >= 2 {
|
||||
raw[1..raw.len() - 1].replace("''", "'")
|
||||
} else {
|
||||
raw.to_owned()
|
||||
}
|
||||
}
|
||||
|
||||
/// Metadata for one Copilot session, read without opening its potentially multi-gigabyte event log.
|
||||
/// Supports both inline scalars (`name: "Fix\nbug"`) and block scalars (`name: |-\n Fix\n bug`).
|
||||
fn copilot_metadata(path: &Path) -> Option<HashMap<String, String>> {
|
||||
let file = std::fs::File::open(path).ok()?;
|
||||
let mut lines = std::io::BufReader::new(file).lines().map_while(Result::ok).peekable();
|
||||
let mut metadata = HashMap::new();
|
||||
while let Some(line) = lines.next() {
|
||||
if line.is_empty() || line.starts_with(char::is_whitespace) || line.trim_start().starts_with('#') {
|
||||
continue;
|
||||
}
|
||||
let Some((key, raw)) = line.split_once(':') else { continue };
|
||||
let key = key.trim();
|
||||
let raw = raw.trim();
|
||||
if key.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if is_yaml_block_header(raw) {
|
||||
let folded = raw.starts_with('>');
|
||||
let mut block = Vec::new();
|
||||
while let Some(next) = lines.peek() {
|
||||
if next.is_empty() || next.starts_with(' ') || next.starts_with('\t') {
|
||||
block.push(lines.next().unwrap_or_default());
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
while block.last().is_some_and(|l| l.trim().is_empty()) {
|
||||
block.pop();
|
||||
}
|
||||
let indent = block
|
||||
.iter()
|
||||
.filter(|l| !l.trim().is_empty())
|
||||
.map(|l| l.bytes().take_while(|&b| b == b' ').count())
|
||||
.min()
|
||||
.unwrap_or(0);
|
||||
let sep = if folded { " " } else { "\n" };
|
||||
let joined = block
|
||||
.iter()
|
||||
.map(|l| if l.len() >= indent { &l[indent..] } else { l.trim_start() })
|
||||
.collect::<Vec<_>>()
|
||||
.join(sep);
|
||||
if !joined.trim().is_empty() {
|
||||
metadata.insert(key.to_owned(), joined);
|
||||
}
|
||||
} else if !raw.is_empty() {
|
||||
metadata.insert(key.to_owned(), parse_yaml_inline_value(raw));
|
||||
}
|
||||
}
|
||||
(!metadata.is_empty()).then_some(metadata)
|
||||
}
|
||||
|
||||
/// The first real prompt in a Copilot event log, used when an old or unnamed session has no title.
|
||||
fn copilot_prompt(path: &Path) -> Option<String> {
|
||||
let file = std::fs::File::open(path).ok()?;
|
||||
std::io::BufReader::new(file)
|
||||
.lines()
|
||||
.take(400)
|
||||
.filter_map(|line| line.ok())
|
||||
.filter_map(|line| serde_json::from_str::<serde_json::Value>(&line).ok())
|
||||
.find_map(|event| {
|
||||
(event.get("type").and_then(serde_json::Value::as_str) == Some("user.message"))
|
||||
.then(|| event.pointer("/data/content").and_then(serde_json::Value::as_str).map(str::trim))
|
||||
.flatten()
|
||||
.filter(|text| !text.is_empty())
|
||||
.map(short)
|
||||
})
|
||||
}
|
||||
|
||||
/// Candidate VS Code Agent Host SQLite databases (`<user>/globalStorage/agent-host.db`),
|
||||
/// ordered oldest-first so a newer database wins when two editions share a session.
|
||||
fn vscode_agent_host_dbs(home: &Path) -> Vec<PathBuf> {
|
||||
let mut bases = vec![home.join("Library/Application Support"), home.join(".config"), home.join("AppData/Roaming")];
|
||||
let real_home = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE"));
|
||||
if real_home.as_deref().is_some_and(|h| Path::new(h) == home) {
|
||||
for var in ["XDG_CONFIG_HOME", "APPDATA"] {
|
||||
if let Some(dir) = std::env::var_os(var).filter(|v| !v.is_empty()).map(PathBuf::from)
|
||||
&& !bases.contains(&dir)
|
||||
{
|
||||
bases.push(dir);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut dbs = Vec::new();
|
||||
for base in bases {
|
||||
for app in ["Code", "Code - Insiders"] {
|
||||
dbs.push(base.join(app).join("User/globalStorage/agent-host.db"));
|
||||
}
|
||||
}
|
||||
for server in [".vscode-server", ".vscode-server-insiders"] {
|
||||
dbs.push(home.join(server).join("data/User/globalStorage/agent-host.db"));
|
||||
}
|
||||
dbs.retain(|p| p.is_file());
|
||||
dbs.sort_by(|a, b| mtime(a).total_cmp(&mtime(b)));
|
||||
dbs
|
||||
}
|
||||
|
||||
fn is_generic_vscode_placeholder(title: &str, source: Option<&str>) -> bool {
|
||||
source != Some("user") && (title.eq_ignore_ascii_case("new session") || title.eq_ignore_ascii_case("new chat"))
|
||||
}
|
||||
|
||||
fn pick_vscode_chat_title(
|
||||
scs_title: Option<&str>,
|
||||
scs_source: Option<&str>,
|
||||
metadata_json: Option<&str>,
|
||||
payload_json: Option<&str>,
|
||||
) -> Option<String> {
|
||||
if let Some(t) = scs_title.map(str::trim).filter(|t| !t.is_empty())
|
||||
&& !is_generic_vscode_placeholder(t, scs_source)
|
||||
{
|
||||
return Some(t.to_owned());
|
||||
}
|
||||
for blob in [metadata_json, payload_json].into_iter().flatten() {
|
||||
let Ok(v) = serde_json::from_str::<serde_json::Value>(blob) else { continue };
|
||||
let summary = v.pointer("/data/summary").and_then(serde_json::Value::as_str).map(str::trim);
|
||||
let source = v.pointer("/data/titleSource").and_then(serde_json::Value::as_str);
|
||||
if let Some(t) = summary.filter(|t| !t.is_empty())
|
||||
&& !is_generic_vscode_placeholder(t, source)
|
||||
{
|
||||
return Some(t.to_owned());
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// The rows of one `agent-host.db` that map a backing Copilot session (`sdkSessionId`) to its
|
||||
/// title. Read through a read-only connection that sets no `journal_mode` or other write pragma,
|
||||
/// so VS Code's database is never changed. An unknown schema (a newer VS Code) reads nothing.
|
||||
async fn read_vscode_chat_rows(path: &Path) -> Vec<[Option<String>; 5]> {
|
||||
use sqlx::{Connection, Row};
|
||||
const FULL_QUERY: &str = "\
|
||||
SELECT c.provider_data, scs.title, scs.title_source, c.metadata, s.payload \
|
||||
FROM chats_v2 c \
|
||||
LEFT JOIN session_chat_state scs \
|
||||
ON scs.session_uri = c.owner_session_uri AND scs.chat_uri = c.chat_uri \
|
||||
LEFT JOIN sessions_v2 s \
|
||||
ON s.session_uri = c.owner_session_uri \
|
||||
WHERE c.tombstoned = 0 \
|
||||
ORDER BY COALESCE(s.modified_time, 0) ASC, COALESCE(c.chat_order, 0) ASC";
|
||||
const FALLBACK_QUERY: &str = "SELECT provider_data, NULL, NULL, metadata, NULL FROM chats_v2 WHERE tombstoned = 0";
|
||||
|
||||
let options = sqlx::sqlite::SqliteConnectOptions::new()
|
||||
.filename(path)
|
||||
.read_only(true)
|
||||
.create_if_missing(false)
|
||||
.busy_timeout(std::time::Duration::from_millis(200));
|
||||
let Ok(mut conn) = sqlx::SqliteConnection::connect_with(&options).await else { return Vec::new() };
|
||||
let rows = match sqlx::query(FULL_QUERY).fetch_all(&mut conn).await {
|
||||
Ok(rows) => rows,
|
||||
Err(_) => sqlx::query(FALLBACK_QUERY).fetch_all(&mut conn).await.unwrap_or_default(),
|
||||
};
|
||||
let _ = conn.close().await;
|
||||
rows.iter().map(|row| std::array::from_fn(|i| row.try_get::<Option<String>, _>(i).ok().flatten())).collect()
|
||||
}
|
||||
|
||||
/// Session titles VS Code's Agent Host (`vscode-agent-host`) assigns to backing Copilot CLI
|
||||
/// sessions (`sdkSessionId` → summary or user rename). VS Code keeps these in its own
|
||||
/// `agent-host.db` rather than in Copilot's `workspace.yaml`, so without them a renamed chat
|
||||
/// would be listed under its first prompt. Best-effort: any failure leaves the CLI titles.
|
||||
fn vscode_copilot_titles(home: Option<&Path>) -> HashMap<String, String> {
|
||||
let Some(home) = home else { return HashMap::new() };
|
||||
let dbs = vscode_agent_host_dbs(home);
|
||||
if dbs.is_empty() {
|
||||
return HashMap::new();
|
||||
}
|
||||
// Callers are sync and may run on a runtime thread or none: a private runtime on its own
|
||||
// thread works from either without blocking a runtime worker.
|
||||
let rows: Vec<[Option<String>; 5]> = std::thread::scope(|scope| {
|
||||
scope
|
||||
.spawn(|| {
|
||||
let Ok(rt) = tokio::runtime::Builder::new_current_thread().enable_all().build() else {
|
||||
return Vec::new();
|
||||
};
|
||||
rt.block_on(async {
|
||||
let mut all = Vec::new();
|
||||
for path in &dbs {
|
||||
all.extend(read_vscode_chat_rows(path).await);
|
||||
}
|
||||
all
|
||||
})
|
||||
})
|
||||
.join()
|
||||
.unwrap_or_default()
|
||||
});
|
||||
let mut titles = HashMap::new();
|
||||
for [pdata, scs_title, scs_source, metadata, payload] in rows {
|
||||
let Some(pdata) = pdata else { continue };
|
||||
let Ok(pv) = serde_json::from_str::<serde_json::Value>(&pdata) else { continue };
|
||||
let Some(sdk_id) = pv.get("sdkSessionId").and_then(serde_json::Value::as_str).filter(|s| !s.is_empty()) else {
|
||||
continue;
|
||||
};
|
||||
if let Some(title) =
|
||||
pick_vscode_chat_title(scs_title.as_deref(), scs_source.as_deref(), metadata.as_deref(), payload.as_deref())
|
||||
{
|
||||
titles.insert(sdk_id.to_owned(), title);
|
||||
}
|
||||
}
|
||||
titles
|
||||
}
|
||||
|
||||
/// Whether a live process holds the Copilot session in `dir`. Copilot writes `inuse.<pid>.lock`
|
||||
/// while a CLI or SDK host (such as VS Code) has the session open; a crash leaves a stale one,
|
||||
/// so only a lock whose process still runs counts.
|
||||
fn copilot_session_in_use(dir: &Path) -> bool {
|
||||
std::fs::read_dir(dir).into_iter().flatten().flatten().any(|entry| {
|
||||
let name = entry.file_name();
|
||||
let Some(pid) = name
|
||||
.to_str()
|
||||
.and_then(|n| n.strip_prefix("inuse."))
|
||||
.and_then(|n| n.strip_suffix(".lock"))
|
||||
.and_then(|n| n.parse::<u32>().ok())
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
ide_core::process::process_alive(pid)
|
||||
})
|
||||
}
|
||||
|
||||
/// Copilot sessions of the project at `root`: `<config>/session-state/<id>`, titled by VS Code's
|
||||
/// Agent Host summary/rename (when started from VS Code), their recorded CLI name, or first prompt.
|
||||
/// Directories without an event log are unfinished sessions and are not listed.
|
||||
pub fn copilot_sessions(copilot_home: &Path, home: Option<&Path>, root: &Path) -> Vec<ExternalSession> {
|
||||
let mut pending: Vec<(ExternalSession, bool)> = std::fs::read_dir(copilot_home.join("session-state"))
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.flatten()
|
||||
.filter_map(|entry| {
|
||||
let dir = entry.path();
|
||||
let events = dir.join("events.jsonl");
|
||||
if !events.is_file() {
|
||||
return None;
|
||||
}
|
||||
let metadata = copilot_metadata(&dir.join("workspace.yaml"))?;
|
||||
let session_id = metadata.get("id").cloned().or_else(|| entry.file_name().to_str().map(str::to_owned))?;
|
||||
let cwd = metadata.get("cwd").cloned().or_else(|| metadata.get("git_root").cloned());
|
||||
if !in_project(cwd.as_deref(), root) {
|
||||
return None;
|
||||
}
|
||||
let raw_name = metadata.get("name").map(String::as_str).map(str::trim).filter(|name| !name.is_empty());
|
||||
let cli_user_named = metadata.get("user_named").is_some_and(|v| v == "true")
|
||||
&& raw_name.is_some_and(|n| !n.eq_ignore_ascii_case("new session"));
|
||||
let title = raw_name
|
||||
.map(short)
|
||||
.or_else(|| copilot_prompt(&events))
|
||||
.unwrap_or_else(|| format!("Copilot session {}", &session_id[..session_id.len().min(8)]));
|
||||
let session = ExternalSession {
|
||||
provider: "copilot".to_owned(),
|
||||
session_id,
|
||||
title,
|
||||
cwd,
|
||||
updated_ms: mtime(&events),
|
||||
in_use: copilot_session_in_use(&dir),
|
||||
};
|
||||
Some((session, cli_user_named))
|
||||
})
|
||||
.collect();
|
||||
if !pending.is_empty() {
|
||||
let vscode_titles = vscode_copilot_titles(home);
|
||||
for (session, cli_user_named) in &mut pending {
|
||||
if !*cli_user_named && let Some(title) = vscode_titles.get(&session.session_id) {
|
||||
session.title = short(title);
|
||||
}
|
||||
}
|
||||
}
|
||||
pending.into_iter().map(|(s, _)| s).collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -344,6 +633,111 @@ mod tests {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
assert!(claude_sessions(&tmp.path().join("nope"), Path::new("/work")).is_empty());
|
||||
assert!(codex_sessions(&tmp.path().join("nope"), Path::new("/work")).is_empty());
|
||||
assert!(copilot_sessions(&tmp.path().join("nope"), None, Path::new("/work")).is_empty());
|
||||
}
|
||||
|
||||
fn exec_sqlite(path: &Path, sql: &'static str) {
|
||||
use sqlx::Connection;
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
|
||||
rt.block_on(async {
|
||||
let options = sqlx::sqlite::SqliteConnectOptions::new().filename(path).create_if_missing(true);
|
||||
let mut conn = sqlx::SqliteConnection::connect_with(&options).await.unwrap();
|
||||
sqlx::raw_sql(sql).execute(&mut conn).await.unwrap();
|
||||
conn.close().await.unwrap();
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lists_copilot_sessions_with_names_block_scalars_vscode_titles_and_prompt_fallbacks() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let copilot_home = tmp.path().join(".copilot");
|
||||
let session = copilot_home.join("session-state/copilot-1");
|
||||
write(
|
||||
&session.join("events.jsonl"),
|
||||
&[
|
||||
json!({"type": "session.start", "data": {}}),
|
||||
json!({"type": "user.message", "data": {"content": "fix the parser"}}),
|
||||
],
|
||||
);
|
||||
std::fs::write(
|
||||
session.join("workspace.yaml"),
|
||||
"id: copilot-1\ncwd: /work/app/api\nname: \"Fix parser\\nand tests\"\n",
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let block_scalar = copilot_home.join("session-state/copilot-block");
|
||||
write(&block_scalar.join("events.jsonl"), &[json!({"type": "session.start", "data": {}})]);
|
||||
std::fs::write(
|
||||
block_scalar.join("workspace.yaml"),
|
||||
"id: copilot-block\ncwd: /work/app\nname: |-\n check why excalidraw font\n is not displayed\nuser_named: false\n",
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let vscode_renamed = copilot_home.join("session-state/copilot-vscode");
|
||||
write(
|
||||
&vscode_renamed.join("events.jsonl"),
|
||||
&[json!({"type": "user.message", "data": {"content": "create a branch deng/session add Create Session"}})],
|
||||
);
|
||||
std::fs::write(
|
||||
vscode_renamed.join("workspace.yaml"),
|
||||
"id: copilot-vscode\ncwd: /work/app\nclient_name: vscode-agent-host\nname: create a branch deng/session add Create Session\nuser_named: false\n",
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let vscode_placeholder = copilot_home.join("session-state/copilot-placeholder");
|
||||
write(&vscode_placeholder.join("events.jsonl"), &[json!({"type": "session.start", "data": {}})]);
|
||||
std::fs::write(
|
||||
vscode_placeholder.join("workspace.yaml"),
|
||||
"id: copilot-placeholder\ncwd: /work/app\nname: Greeting exchange\nuser_named: false\n",
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let unnamed = copilot_home.join("session-state/copilot-2");
|
||||
write(
|
||||
&unnamed.join("events.jsonl"),
|
||||
&[json!({"type": "user.message", "data": {"content": "add a regression test"}})],
|
||||
);
|
||||
std::fs::write(unnamed.join("workspace.yaml"), "id: copilot-2\ncwd: /work/app\n").unwrap();
|
||||
// A live holder marks the session in use; a lock left by a process that exited does not.
|
||||
std::fs::write(session.join(format!("inuse.{}.lock", std::process::id())), "").unwrap();
|
||||
std::fs::write(unnamed.join("inuse.2147483646.lock"), "").unwrap();
|
||||
|
||||
let empty = copilot_home.join("session-state/copilot-empty");
|
||||
std::fs::create_dir_all(&empty).unwrap();
|
||||
std::fs::write(empty.join("workspace.yaml"), "id: copilot-empty\ncwd: /work/app\n").unwrap();
|
||||
|
||||
let other = copilot_home.join("session-state/copilot-other");
|
||||
write(
|
||||
&other.join("events.jsonl"),
|
||||
&[json!({"type": "user.message", "data": {"content": "unrelated project"}})],
|
||||
);
|
||||
std::fs::write(other.join("workspace.yaml"), "id: copilot-other\ncwd: /other\n").unwrap();
|
||||
|
||||
exec_sqlite(
|
||||
&tmp.path().join(".config/Code/User/globalStorage/agent-host.db"),
|
||||
"CREATE TABLE sessions_v2 (session_uri TEXT PRIMARY KEY, payload TEXT, modified_time INTEGER);
|
||||
CREATE TABLE session_chat_state (session_uri TEXT, chat_uri TEXT, title TEXT, title_source TEXT);
|
||||
CREATE TABLE chats_v2 (chat_uri TEXT PRIMARY KEY, owner_session_uri TEXT, chat_order INTEGER, provider_data TEXT, metadata TEXT, tombstoned INTEGER);
|
||||
INSERT INTO sessions_v2 VALUES ('copilotcli:/vs1', '{}', 100);
|
||||
INSERT INTO chats_v2 VALUES ('chat:/vs1', 'copilotcli:/vs1', 0, '{\"sdkSessionId\":\"copilot-vscode\"}', '{\"data\":{\"summary\":\"Session\",\"titleSource\":\"user\"}}', 0);
|
||||
INSERT INTO sessions_v2 VALUES ('copilotcli:/vs2', '{}', 100);
|
||||
INSERT INTO chats_v2 VALUES ('chat:/vs2', 'copilotcli:/vs2', 0, '{\"sdkSessionId\":\"copilot-placeholder\"}', '{\"data\":{\"summary\":\"New session\",\"titleSource\":\"auto\"}}', 0);",
|
||||
);
|
||||
|
||||
let sessions = copilot_sessions(&copilot_home, Some(tmp.path()), Path::new("/work"));
|
||||
assert_eq!(sessions.len(), 5);
|
||||
let mut by_id: HashMap<_, _> = sessions.into_iter().map(|s| (s.session_id.clone(), s)).collect();
|
||||
let named = by_id.remove("copilot-1").unwrap();
|
||||
assert_eq!((named.provider.as_str(), named.title.as_str()), ("copilot", "Fix parser and tests"));
|
||||
assert_eq!(named.cwd.as_deref(), Some("/work/app/api"));
|
||||
assert!(named.in_use);
|
||||
assert_eq!(by_id.remove("copilot-block").unwrap().title, "check why excalidraw font is not displayed");
|
||||
assert_eq!(by_id.remove("copilot-vscode").unwrap().title, "Session");
|
||||
assert_eq!(by_id.remove("copilot-placeholder").unwrap().title, "Greeting exchange");
|
||||
let unnamed = by_id.remove("copilot-2").unwrap();
|
||||
assert_eq!(unnamed.title, "add a regression test");
|
||||
assert!(!unnamed.in_use);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -68,9 +68,25 @@ fn to_mcp_server(scope: McpScope, name: &str, cfg: &AgentMcpServer) -> McpServer
|
||||
headers: cfg.headers.iter().map(|(k, v)| McpKeyValue { name: k.clone(), value: v.clone() }).collect(),
|
||||
agents: cfg.agents.clone(),
|
||||
unapproved: false,
|
||||
plugin_id: None,
|
||||
plugin_name: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Merges `projected` MCP servers from enabled agent plugins behind `configured` User and
|
||||
/// Workspace servers so standalone settings entries always take precedence on name clashes.
|
||||
pub fn merge_projected_servers(mut configured: Vec<McpServer>, projected: Vec<McpServer>) -> Vec<McpServer> {
|
||||
let existing: HashSet<String> = configured.iter().map(|s| s.name.clone()).collect();
|
||||
// Same-named servers from different bundles are distinct rows (ids are `plugin:<bundle>:<server>`).
|
||||
let mut seen_projected: HashSet<String> = HashSet::new();
|
||||
for srv in projected {
|
||||
if !existing.contains(&srv.name) && seen_projected.insert(srv.id.clone()) {
|
||||
configured.push(srv);
|
||||
}
|
||||
}
|
||||
configured
|
||||
}
|
||||
|
||||
fn normalize_provider(id: &str) -> &str {
|
||||
id.strip_suffix("-acp").unwrap_or(id)
|
||||
}
|
||||
@@ -399,13 +415,8 @@ pub fn apply_save_json(
|
||||
Ok(saved_names)
|
||||
}
|
||||
|
||||
const COPILOT_PLUGIN_MANIFESTS: &[&str] = &[
|
||||
".github/plugin/plugin.json",
|
||||
".plugin/plugin.json",
|
||||
".claude-plugin/plugin.json",
|
||||
".cursor-plugin/plugin.json",
|
||||
"plugin.json",
|
||||
];
|
||||
const COPILOT_PLUGIN_MANIFESTS: &[&str] =
|
||||
&[".github/plugin/plugin.json", ".plugin/plugin.json", ".claude-plugin/plugin.json", "plugin.json"];
|
||||
|
||||
#[derive(Clone, PartialEq, Eq)]
|
||||
enum SourceFormat {
|
||||
@@ -1051,6 +1062,14 @@ fn extract_servers_from_root(root: &Value, fallback_name: Option<&str>) -> BTree
|
||||
out
|
||||
}
|
||||
|
||||
pub(crate) fn read_external_mcp_file(path: &Path) -> BTreeMap<String, AgentMcpServer> {
|
||||
read_external_file(path)
|
||||
}
|
||||
|
||||
pub(crate) fn parse_mcp_value(root: &Value) -> Result<BTreeMap<String, AgentMcpServer>, String> {
|
||||
Ok(extract_servers_from_root(root, None))
|
||||
}
|
||||
|
||||
fn read_external_file(path: &Path) -> BTreeMap<String, AgentMcpServer> {
|
||||
let Ok(text) = std::fs::read_to_string(path) else {
|
||||
return BTreeMap::new();
|
||||
@@ -1088,15 +1107,7 @@ pub async fn probe_stdio_server(server: &AgentMcpServer, cwd: &Path) -> McpProbe
|
||||
env.push((k.clone(), v.clone()));
|
||||
}
|
||||
}
|
||||
let search_path = env
|
||||
.iter()
|
||||
.find(|(k, _)| k.eq_ignore_ascii_case("PATH"))
|
||||
.map(|(_, v)| std::ffi::OsString::from(v))
|
||||
.or_else(|| ide_core::process::host_var_os("PATH"))
|
||||
.unwrap_or_default();
|
||||
let program = ide_core::process::find_executable(raw_cmd, &search_path)
|
||||
.map(|p| p.to_string_lossy().into_owned())
|
||||
.unwrap_or_else(|| raw_cmd.to_owned());
|
||||
let program = ide_jsonrpc::resolve_spawn_program(raw_cmd, &env).to_string_lossy().into_owned();
|
||||
|
||||
let stderr_lines = std::sync::Arc::new(parking_lot::Mutex::new(Vec::<String>::new()));
|
||||
let stderr_capture = stderr_lines.clone();
|
||||
@@ -1259,6 +1270,8 @@ mod tests {
|
||||
headers: Vec::new(),
|
||||
agents: Vec::new(),
|
||||
unapproved: false,
|
||||
plugin_id: None,
|
||||
plugin_name: None,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -453,6 +453,26 @@ pub fn discover_memories(workspaces: &[PathBuf], home: Option<&Path>) -> Vec<Age
|
||||
out
|
||||
}
|
||||
|
||||
/// Discovers all standalone memory entries across `workspaces` and `home`, then appends
|
||||
/// projected rule/context entries from enabled agent plugins (deduplicated by canonical path).
|
||||
pub fn discover_memories_with_plugins(
|
||||
workspaces: &[PathBuf],
|
||||
home: Option<&Path>,
|
||||
projected: Vec<AgentMemoryEntry>,
|
||||
) -> Vec<AgentMemoryEntry> {
|
||||
let mut out = discover_memories(workspaces, home);
|
||||
let mut seen: HashSet<PathBuf> =
|
||||
out.iter().map(|e| dunce::canonicalize(&e.path.0).unwrap_or_else(|_| e.path.0.clone())).collect();
|
||||
for mut entry in projected {
|
||||
let canon = dunce::canonicalize(&entry.path.0).unwrap_or_else(|_| entry.path.0.clone());
|
||||
entry.path = canon.clone().into();
|
||||
if seen.insert(canon) {
|
||||
out.push(entry);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Resolves the full [`AgentMemoryCatalog`] (entries + per-provider auto-memory statuses)
|
||||
/// against `policy` and optional per-session `session_overrides`.
|
||||
pub fn resolve_catalog(
|
||||
@@ -1412,6 +1432,8 @@ fn parse_cursor_mdc(path: &Path, rel: &str) -> Option<AgentMemoryEntry> {
|
||||
writable: false,
|
||||
valid: true,
|
||||
warnings,
|
||||
plugin_id: None,
|
||||
plugin_name: None,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1482,6 +1504,8 @@ fn parse_entry(
|
||||
writable,
|
||||
valid: true,
|
||||
warnings,
|
||||
plugin_id: None,
|
||||
plugin_name: None,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -199,6 +199,10 @@ pub struct AgentTask {
|
||||
/// Per-session recovery / network auto-retry window override in minutes (`0` = Off; `None` = inherit global).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub recovery_window_mins: Option<u32>,
|
||||
/// Provenance metadata when this task was created or continued by an [`crate::automation::AgentAutomation`].
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub automation: Option<Box<crate::automation::AgentTaskAutomation>>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
@@ -454,11 +458,29 @@ pub struct AgentPrompt {
|
||||
pub images: Vec<AgentImage>,
|
||||
}
|
||||
|
||||
/// Provenance carried with a scheduled turn (`SameTask`, `Send Later`, or `/loop`), including
|
||||
/// while queued behind a busy turn, so trust and approval ceilings are re-checked at dispatch.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ScheduledTurnMeta {
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub permissions: Option<crate::automation::AutomationPermissionMode>,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub extra_choices: Vec<AgentConfigChoice>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub automation_id: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub session_schedule_id: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentQueued {
|
||||
pub id: String,
|
||||
pub prompt: AgentPrompt,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(skip)]
|
||||
pub scheduled: Option<ScheduledTurnMeta>,
|
||||
}
|
||||
|
||||
/// A setting chosen for a new task, by [`AgentConfigOption::id`].
|
||||
@@ -920,7 +942,7 @@ pub struct AgentModelCatalog {
|
||||
}
|
||||
|
||||
/// Streamed to the window that subscribed (`AgentManager::subscribe_as`).
|
||||
#[derive(Clone, Debug, Serialize, Type)]
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(tag = "type", rename_all = "camelCase", rename_all_fields = "camelCase")]
|
||||
pub enum AgentEvent {
|
||||
/// A task was created or its metadata changed.
|
||||
@@ -1018,6 +1040,14 @@ pub struct McpServer {
|
||||
/// True when this Workspace server was added outside OpenIDEA and has not been approved yet.
|
||||
#[serde(default)]
|
||||
pub unapproved: bool,
|
||||
/// Parent agent plugin ID when this server is live-projected from an enabled agent plugin bundle.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub plugin_id: Option<String>,
|
||||
/// Display name of the parent agent plugin.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub plugin_name: Option<String>,
|
||||
}
|
||||
|
||||
/// Payload for creating or updating a user or workspace MCP server.
|
||||
@@ -1051,8 +1081,8 @@ fn default_true() -> bool {
|
||||
}
|
||||
|
||||
pub use ide_core::settings::{
|
||||
AgentMemoryEntryPolicy, AgentMemoryMode, AgentMemorySettings, AgentProviderMemoryPolicy, AgentSkillMode,
|
||||
AgentSkillPolicy, AutoMemoryMode,
|
||||
AgentMemoryEntryPolicy, AgentMemoryMode, AgentMemorySettings, AgentPluginEntryPolicy, AgentPluginSettings,
|
||||
AgentProviderMemoryPolicy, AgentSkillMode, AgentSkillPolicy, AutoMemoryMode,
|
||||
};
|
||||
|
||||
/// Kind of discovered agent memory entry.
|
||||
@@ -1165,6 +1195,14 @@ pub struct AgentMemoryEntry {
|
||||
pub valid: bool,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub warnings: Vec<String>,
|
||||
/// Parent agent plugin ID when this rule/instruction is live-projected from an enabled agent plugin bundle.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub plugin_id: Option<String>,
|
||||
/// Display name of the parent agent plugin.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub plugin_name: Option<String>,
|
||||
}
|
||||
|
||||
/// A discovered memory entry paired with its resolved [`AgentMemoryMode`] and origin.
|
||||
@@ -1337,6 +1375,14 @@ pub struct AgentSkill {
|
||||
pub valid: bool,
|
||||
/// What validation found (`name` mismatch, missing or over-long description…).
|
||||
pub warnings: Vec<String>,
|
||||
/// Parent agent plugin ID when this skill comes from an agent plugin bundle.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub plugin_id: Option<String>,
|
||||
/// Display name of the parent agent plugin.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub plugin_name: Option<String>,
|
||||
}
|
||||
|
||||
/// A skill as Settings › Agents › Skills shows it: discovery plus the effective mode and
|
||||
@@ -1398,6 +1444,371 @@ pub struct McpDiscoveredServer {
|
||||
pub header_keys: Vec<String>,
|
||||
}
|
||||
|
||||
/// Which workspace, user, or CLI store an agent plugin bundle was discovered in.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum AgentPluginSource {
|
||||
/// `~/.copilot/installed-plugins/{<marketplace>,_direct}/*`.
|
||||
#[default]
|
||||
CopilotUser,
|
||||
/// `~/.claude/plugins/installed_plugins.json` & `~/.claude/plugins/cache/*`.
|
||||
ClaudeUser,
|
||||
/// `~/.codex/plugins/cache/*`.
|
||||
CodexUser,
|
||||
/// `~/.gemini/extensions/*`.
|
||||
GeminiUser,
|
||||
}
|
||||
|
||||
/// Manifest format(s) recognized inside an agent plugin directory.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum AgentPluginFormat {
|
||||
/// Vendor-neutral Agent Plugins 1.0 / 1.1 (`plugin.json` with `$schema`).
|
||||
#[default]
|
||||
AgentPluginsV1,
|
||||
/// `.openidea/plugin.json`.
|
||||
OpenIdea,
|
||||
/// `.claude-plugin/plugin.json`.
|
||||
Claude,
|
||||
/// `.plugin/plugin.json`, `.github/plugin/plugin.json`, or legacy root `plugin.json`.
|
||||
Copilot,
|
||||
/// `.codex-plugin/plugin.json`.
|
||||
Codex,
|
||||
/// `gemini-extension.json`.
|
||||
GeminiExtension,
|
||||
}
|
||||
|
||||
/// Which policy layer decided an [`AgentPluginState::enabled`] status.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum AgentPluginOrigin {
|
||||
/// Native harness configuration owns the enabled state.
|
||||
#[default]
|
||||
None,
|
||||
/// Locked `Off` because the workspace is untrusted.
|
||||
Trust,
|
||||
/// Locked `Off` until executable capabilities (stdio MCP / lifecycle hooks) are approved.
|
||||
Consent,
|
||||
}
|
||||
|
||||
/// Data type of a plugin `userConfig` / `variables` / `settings` option.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum AgentPluginConfigFieldKind {
|
||||
#[default]
|
||||
String,
|
||||
Number,
|
||||
Boolean,
|
||||
Secret,
|
||||
}
|
||||
|
||||
/// One configurable option declared by an agent plugin (`userConfig`, `variables`, or Gemini `settings`).
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentPluginConfigField {
|
||||
pub key: String,
|
||||
pub title: String,
|
||||
#[serde(default)]
|
||||
pub description: String,
|
||||
pub kind: AgentPluginConfigFieldKind,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub default_value: Option<String>,
|
||||
#[serde(default)]
|
||||
pub required: bool,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub env_var: Option<String>,
|
||||
/// Current non-sensitive value (always empty when `kind == Secret`).
|
||||
#[serde(default)]
|
||||
pub value: String,
|
||||
/// True when a secret is stored in OS Keychain for this field.
|
||||
#[serde(default)]
|
||||
pub has_secret: bool,
|
||||
}
|
||||
|
||||
/// Summary of components and executable capabilities bundled inside an agent plugin.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentPluginCapabilities {
|
||||
pub skill_count: u32,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub skill_names: Vec<String>,
|
||||
pub mcp_count: u32,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub mcp_names: Vec<String>,
|
||||
pub rule_count: u32,
|
||||
pub subagent_count: u32,
|
||||
pub command_count: u32,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub hook_files: Vec<String>,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub stdio_commands: Vec<String>,
|
||||
#[serde(default)]
|
||||
pub has_lsp: bool,
|
||||
#[serde(default)]
|
||||
pub has_canvas_or_app: bool,
|
||||
/// Harnesses that have native non-portable components (hooks, subagents, canvases/apps, LSP) in this bundle.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub native_harnesses: Vec<String>,
|
||||
/// Deterministic BLAKE3 hex digest of executable capabilities (`stdio_commands` + `hook_files` contents).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub capability_hash: Option<String>,
|
||||
#[serde(default)]
|
||||
pub requires_consent: bool,
|
||||
}
|
||||
|
||||
/// One discovered agent plugin bundle on disk (or built-in).
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentPlugin {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub display_name: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub version: Option<String>,
|
||||
pub description: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub author: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub homepage: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub repository: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub license: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub marketplace: Option<String>,
|
||||
pub source: AgentPluginSource,
|
||||
/// Scope this bundle is installed in. Native plugin folders and enablement config are
|
||||
/// resolved relative to this scope.
|
||||
pub scope: McpScope,
|
||||
/// Workspace whose native configuration owns this row's enablement (workspace scope only).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub workspace_root: Option<IpcPath>,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub also_in: Vec<AgentPluginSource>,
|
||||
pub formats: Vec<AgentPluginFormat>,
|
||||
pub root_path: IpcPath,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub manifest_path: Option<IpcPath>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub readme_path: Option<IpcPath>,
|
||||
pub default_enabled: bool,
|
||||
pub approx_tokens: u32,
|
||||
pub capabilities: AgentPluginCapabilities,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub config_fields: Vec<AgentPluginConfigField>,
|
||||
pub valid: bool,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub warnings: Vec<String>,
|
||||
}
|
||||
|
||||
/// Resolved agent plugin state paired with its policy origin and consent status.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentPluginState {
|
||||
pub plugin: AgentPlugin,
|
||||
pub enabled: bool,
|
||||
pub origin: AgentPluginOrigin,
|
||||
/// True when executable stdio MCP / hook capabilities require user approval before enabling.
|
||||
pub consent_required: bool,
|
||||
}
|
||||
|
||||
/// Summary of a configured or repository-discovered plugin marketplace.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentMarketplaceInfo {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub source: String,
|
||||
pub scope: McpScope,
|
||||
/// True when discovered from a harness-native marketplace/configuration file.
|
||||
pub discovered: bool,
|
||||
}
|
||||
|
||||
/// Full catalog returned to Settings › Agents › Plugins.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentPluginCatalog {
|
||||
pub plugins: Vec<AgentPluginState>,
|
||||
pub marketplaces: Vec<AgentMarketplaceInfo>,
|
||||
pub projected_skills: u32,
|
||||
pub projected_mcp_servers: u32,
|
||||
pub projected_rules: u32,
|
||||
}
|
||||
|
||||
/// One installable plugin entry listed inside a marketplace or repository.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentMarketplaceCandidate {
|
||||
pub name: String,
|
||||
pub display_name: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub version: Option<String>,
|
||||
pub description: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub author: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub marketplace: Option<String>,
|
||||
/// Source spec to pass to preview (`"owner/repo[/subpath][@ref]"` or local directory path).
|
||||
pub source_spec: String,
|
||||
pub subpath: String,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub keywords: Vec<String>,
|
||||
pub already_installed_user: bool,
|
||||
pub already_installed_workspace: bool,
|
||||
}
|
||||
|
||||
/// Result of browsing a marketplace (`owner/repo`, local marketplace path, or direct plugin repo).
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentMarketplaceBrowseResult {
|
||||
pub source: String,
|
||||
pub marketplace_name: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub owner: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub repo: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub git_ref: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub tree_sha: Option<String>,
|
||||
pub candidates: Vec<AgentMarketplaceCandidate>,
|
||||
}
|
||||
|
||||
/// Whether a previewed plugin can be installed for one harness, and where it is already installed.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentPluginInstallTarget {
|
||||
pub harness: String,
|
||||
pub supported: bool,
|
||||
/// Why the harness cannot install this plugin.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub reason: Option<String>,
|
||||
/// Whether this harness can enable the plugin for just one workspace.
|
||||
pub workspace_supported: bool,
|
||||
/// This harness already records the plugin for the user / for the current workspace.
|
||||
pub installed_user: bool,
|
||||
pub installed_workspace: bool,
|
||||
/// The harness store already holds this plugin version's folder, so installing replaces it.
|
||||
pub overwrite_required: bool,
|
||||
}
|
||||
|
||||
/// Security and capability preview of an agent plugin bundle before installation.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentPluginPreview {
|
||||
/// `"github"` or `"local"`.
|
||||
pub source_kind: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub owner: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub repo: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub git_ref: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub tree_sha: Option<String>,
|
||||
/// Pinned commit SHA from preview when `source_kind == "github"`.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub commit_sha: Option<String>,
|
||||
#[serde(default)]
|
||||
pub subpath: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub local_path: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub marketplace: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub marketplace_source: Option<String>,
|
||||
pub name: String,
|
||||
pub display_name: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub version: Option<String>,
|
||||
pub description: String,
|
||||
pub formats: Vec<AgentPluginFormat>,
|
||||
pub capabilities: AgentPluginCapabilities,
|
||||
pub files: Vec<crate::skill_installer::RemoteSkillFile>,
|
||||
pub scan_warnings: Vec<crate::skill_installer::SkillScanWarning>,
|
||||
/// Per-harness install eligibility and existing installs for this plugin and marketplace.
|
||||
pub targets: Vec<AgentPluginInstallTarget>,
|
||||
}
|
||||
|
||||
/// Request payload to install a previewed agent plugin into a selected harness's native plugin directory.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct InstallAgentPluginRequest {
|
||||
/// `"github"` or `"local"`.
|
||||
pub source_kind: String,
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub owner: Option<String>,
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub repo: Option<String>,
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub git_ref: Option<String>,
|
||||
/// Pinned root tree SHA from preview when `source_kind == "github"`.
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub tree_sha: Option<String>,
|
||||
/// Pinned commit SHA from preview when `source_kind == "github"`.
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub commit_sha: Option<String>,
|
||||
#[serde(default)]
|
||||
pub subpath: String,
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub local_path: Option<String>,
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub marketplace: Option<String>,
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub marketplace_source: Option<String>,
|
||||
pub scope: McpScope,
|
||||
/// Native harness the plugin is installed for (`claude`, `copilot`, `codex`, or `gemini`).
|
||||
pub harness: String,
|
||||
#[serde(default)]
|
||||
pub approve_capabilities: bool,
|
||||
/// The preview's `capabilityHash` the user approved; the install is refused if the installed
|
||||
/// folder resolves to different executable capabilities.
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub approved_capability_hash: Option<String>,
|
||||
#[serde(default)]
|
||||
pub confirm_warnings: bool,
|
||||
#[serde(default)]
|
||||
pub overwrite: bool,
|
||||
}
|
||||
|
||||
/// Selection of one server from an external MCP configuration source to import.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
|
||||
@@ -1484,3 +1484,34 @@ async fn session_merges_skills_and_memory_into_claude_settings_and_add_dir_env()
|
||||
"claude-md-and-agents-md"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn session_merges_memory_settings_without_plugin_dir_or_plugin_config_injection() {
|
||||
let cli = replay_cli(load_fixture("simple"));
|
||||
let (config, cwd) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
|
||||
let cwd_path = std::fs::canonicalize(cwd.path()).unwrap();
|
||||
let h =
|
||||
Harness::connect(cli.clone(), config.path().into(), config.path().join("pending"), cwd_path, Vec::new()).await;
|
||||
let params = json!({
|
||||
"cwd": h.cwd,
|
||||
"mcpServers": [],
|
||||
"_meta": {
|
||||
"openidea": {
|
||||
"memory": {
|
||||
"claudeInstructionFiles": "claude-md-and-agents-md"
|
||||
},
|
||||
"plugins": { "activePlugins": ["azure", "linear@mkt"] }
|
||||
}
|
||||
}
|
||||
});
|
||||
h.request("session/new", params).await.unwrap();
|
||||
let args = cli.launched.lock()[0].clone();
|
||||
assert!(!args.iter().any(|a| a == "--plugin-dir"), "{args:?}");
|
||||
let settings_idx = args.iter().position(|a| a == "--settings").expect("--settings flag");
|
||||
let parsed: Value = serde_json::from_str(&args[settings_idx + 1]).unwrap();
|
||||
assert_eq!(
|
||||
parsed["pluginConfigs"]["cc-plugin-agents-md@builtin"]["options"]["instructionFiles"],
|
||||
"claude-md-and-agents-md"
|
||||
);
|
||||
assert!(parsed["pluginConfigs"]["azure"].is_null());
|
||||
}
|
||||
@@ -37,6 +37,15 @@ const DISCOVER_TIMEOUT: Duration = if cfg!(test) { Duration::from_secs(5) } else
|
||||
const EARLY_CANCEL: Duration = Duration::from_secs(2);
|
||||
const EXIT_GRACE: Duration = Duration::from_millis(100);
|
||||
|
||||
/// Copilot's configuration directory (`COPILOT_HOME`, otherwise `<home>/.copilot`).
|
||||
pub(crate) fn config_dir(env: &[(String, String)], home: Option<&Path>) -> Option<PathBuf> {
|
||||
env.iter()
|
||||
.find(|(key, _)| key == "COPILOT_HOME")
|
||||
.map(|(_, value)| PathBuf::from(value))
|
||||
.or_else(|| std::env::var_os("COPILOT_HOME").map(PathBuf::from))
|
||||
.or_else(|| home.map(|home| home.join(".copilot")))
|
||||
}
|
||||
|
||||
/// Pre-session discovery result for `Shared::fetch_settings`.
|
||||
pub(crate) struct Discovered {
|
||||
pub commands: Vec<Value>,
|
||||
@@ -551,6 +560,7 @@ impl CopilotShim {
|
||||
"initialize" => self.initialize().await,
|
||||
"session/new" => self.new_session(¶ms).await,
|
||||
"session/load" => self.load_session(¶ms).await,
|
||||
"session/fork" => self.fork_session(¶ms).await,
|
||||
"session/set_config_option" => self.set_config(¶ms).await,
|
||||
"session/prompt" => self.prompt(¶ms, false).await,
|
||||
"_openidea/steer" => self.prompt(¶ms, true).await,
|
||||
@@ -569,7 +579,7 @@ impl CopilotShim {
|
||||
"loadSession": true,
|
||||
"promptCapabilities": { "image": true, "audio": false, "embeddedContext": true },
|
||||
"mcpCapabilities": { "http": true, "sse": true, "stdio": true },
|
||||
"sessionCapabilities": { "close": {}, "list": {} },
|
||||
"sessionCapabilities": { "fork": {}, "close": {}, "list": {} },
|
||||
"_meta": { "openidea": { "steer": true, "backgroundTasks": true, "contextUsage": true } },
|
||||
},
|
||||
"agentInfo": {
|
||||
@@ -649,6 +659,25 @@ impl CopilotShim {
|
||||
|
||||
async fn load_session(self: &Arc<Self>, params: &Value) -> Result<Value, ResponseError> {
|
||||
let session_id = str_param(params, "sessionId")?.to_owned();
|
||||
let loaded = self.resume_session(params, &session_id).await?;
|
||||
let actual_id = loaded.get("sessionId").and_then(Value::as_str).unwrap_or(&session_id).to_owned();
|
||||
self.replay_history(&actual_id).await;
|
||||
Ok(loaded)
|
||||
}
|
||||
|
||||
async fn fork_session(self: &Arc<Self>, params: &Value) -> Result<Value, ResponseError> {
|
||||
let source = str_param(params, "sessionId")?;
|
||||
let forked = self.call("sessions.fork", json!({ "sessionId": source })).await?;
|
||||
let target = forked
|
||||
.get("sessionId")
|
||||
.and_then(Value::as_str)
|
||||
.filter(|id| !id.is_empty())
|
||||
.ok_or_else(|| error(codes::INTERNAL_ERROR, "Copilot fork returned no sessionId"))?
|
||||
.to_owned();
|
||||
self.resume_session(params, &target).await
|
||||
}
|
||||
|
||||
async fn resume_session(self: &Arc<Self>, params: &Value, session_id: &str) -> Result<Value, ResponseError> {
|
||||
let cwd = str_param(params, "cwd")?;
|
||||
let catalog = self.models().await?;
|
||||
let defaults = fetch_user_defaults(self.copilot(), &self.args).await;
|
||||
@@ -675,7 +704,8 @@ impl CopilotShim {
|
||||
apply_memory(params, &mut req);
|
||||
|
||||
let resumed = self.call("session.resume", req).await?;
|
||||
if let Ok(current) = self.call("session.model.getCurrent", json!({ "sessionId": session_id })).await {
|
||||
let actual_id = resumed.get("sessionId").and_then(Value::as_str).unwrap_or(session_id).to_owned();
|
||||
if let Ok(current) = self.call("session.model.getCurrent", json!({ "sessionId": actual_id })).await {
|
||||
if let Some(model_id) = current.get("modelId").or_else(|| current.get("model")).and_then(Value::as_str) {
|
||||
let _ = settings.set(&catalog, MODEL, model_id);
|
||||
}
|
||||
@@ -686,7 +716,6 @@ impl CopilotShim {
|
||||
let _ = settings.set(&catalog, CONTEXT_TIER, tier);
|
||||
}
|
||||
}
|
||||
let actual_id = resumed.get("sessionId").and_then(Value::as_str).unwrap_or(&session_id).to_owned();
|
||||
let options = models::config_options(&catalog, &settings);
|
||||
self.state.lock().sessions.insert(actual_id.clone(), SessionEntry::new(settings));
|
||||
self.publish_commands(&actual_id, cwd);
|
||||
@@ -697,6 +726,28 @@ impl CopilotShim {
|
||||
}))
|
||||
}
|
||||
|
||||
async fn replay_history(&self, session_id: &str) {
|
||||
let history = match self.call("session.getMessages", json!({ "sessionId": session_id })).await {
|
||||
Ok(history) => history,
|
||||
Err(error) => {
|
||||
tracing::warn!("copilot session {session_id}: could not load history: {}", error.message);
|
||||
return;
|
||||
}
|
||||
};
|
||||
let events = history.get("events").and_then(Value::as_array).map(Vec::as_slice).unwrap_or_default();
|
||||
let updates = {
|
||||
let mut state = self.state.lock();
|
||||
let Some(entry) = state.sessions.get_mut(session_id) else { return };
|
||||
events
|
||||
.iter()
|
||||
.flat_map(|event| entry.translator.translate_history(session_id, event, None).updates)
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
for (target_session, update) in updates {
|
||||
self.send_update(&target_session, update);
|
||||
}
|
||||
}
|
||||
|
||||
fn sync_usage_metrics(self: &Arc<Self>, session_id: &str) {
|
||||
let shim = self.clone();
|
||||
let sid = session_id.to_owned();
|
||||
|
||||
@@ -115,6 +115,18 @@ fn sample_price_units() -> Value {
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolves_copilot_home_from_agent_env_or_user_home() {
|
||||
let home = std::path::Path::new("/home/test");
|
||||
assert_eq!(
|
||||
super::config_dir(&[("COPILOT_HOME".into(), "/custom/copilot".into())], Some(home)).as_deref(),
|
||||
Some(std::path::Path::new("/custom/copilot"))
|
||||
);
|
||||
if std::env::var_os("COPILOT_HOME").is_none() {
|
||||
assert_eq!(super::config_dir(&[], Some(home)), Some(home.join(".copilot")));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_an_enabled_auto_only_catalog() {
|
||||
let list = json!({
|
||||
@@ -434,6 +446,39 @@ impl Handler for FakeCopilotServer {
|
||||
"skills.discover" => Ok(json!({ "skills": [] })),
|
||||
"session.create" => Ok(json!({ "sessionId": "cop-sess-1" })),
|
||||
"session.resume" => Ok(json!({ "sessionId": params["sessionId"] })),
|
||||
"sessions.fork" => Ok(json!({ "sessionId": "cop-sess-fork" })),
|
||||
"session.getMessages" => Ok(json!({
|
||||
"events": [
|
||||
{
|
||||
"type": "user.message",
|
||||
"data": { "content": "Fix the parser" }
|
||||
},
|
||||
{
|
||||
"type": "assistant.message",
|
||||
"data": {
|
||||
"messageId": "history-message",
|
||||
"reasoningText": "Inspect the grammar first.",
|
||||
"content": "I fixed the parser."
|
||||
}
|
||||
},
|
||||
{
|
||||
"type": "tool.execution_start",
|
||||
"data": {
|
||||
"toolCallId": "history-tool",
|
||||
"toolName": "view",
|
||||
"arguments": { "path": "/tmp/parser.rs" }
|
||||
}
|
||||
},
|
||||
{
|
||||
"type": "tool.execution_complete",
|
||||
"data": {
|
||||
"toolCallId": "history-tool",
|
||||
"success": true,
|
||||
"result": { "content": "fn parse() {}" }
|
||||
}
|
||||
}
|
||||
]
|
||||
})),
|
||||
"session.model.getCurrent" => Ok(json!({ "modelId": "gemini-4-carbon" })),
|
||||
"session.model.switchTo" => Ok(json!({ "modelId": params["modelId"] })),
|
||||
"session.mode.set" => Ok(json!({})),
|
||||
@@ -674,6 +719,81 @@ async fn shim_creates_session_with_copilot_defaults_switches_tiers_and_streams_t
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn shim_loads_and_replays_copilot_history() {
|
||||
let server =
|
||||
Arc::new(FakeCopilotServer { peer: OnceLock::new(), calls: Mutex::new(Vec::new()), background_shell: false });
|
||||
let updates = Arc::new(CollectUpdates(Mutex::new(Vec::new())));
|
||||
let server_clone = server.clone();
|
||||
let client = attach(updates.clone(), move |events| {
|
||||
let (a, b) = tokio::io::duplex(1 << 16);
|
||||
let (ar, aw) = tokio::io::split(a);
|
||||
let (br, bw) = tokio::io::split(b);
|
||||
let srv_peer = Peer::connect_framed(br, bw, server_clone.clone(), Framing::ContentLength);
|
||||
let _ = server_clone.peer.set(srv_peer);
|
||||
Ok(Peer::connect_framed(ar, aw, events, Framing::ContentLength))
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
let init: Value = client.request("initialize", json!({}), None).await.unwrap();
|
||||
assert!(init["agentCapabilities"]["sessionCapabilities"]["fork"].is_object());
|
||||
let loaded: Value = client
|
||||
.request("session/load", json!({ "sessionId": "cop-sess-1", "cwd": "/tmp", "mcpServers": [] }), None)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(loaded["sessionId"], "cop-sess-1");
|
||||
|
||||
assert!(
|
||||
server
|
||||
.calls
|
||||
.lock()
|
||||
.iter()
|
||||
.any(|(method, params)| { method == "session.getMessages" && params["sessionId"] == "cop-sess-1" })
|
||||
);
|
||||
let seen = updates.0.lock();
|
||||
assert!(
|
||||
seen.iter().any(|u| u["sessionUpdate"] == "user_message_chunk" && u["content"]["text"] == "Fix the parser")
|
||||
);
|
||||
assert!(
|
||||
seen.iter().any(
|
||||
|u| u["sessionUpdate"] == "agent_thought_chunk" && u["content"]["text"] == "Inspect the grammar first."
|
||||
)
|
||||
);
|
||||
assert!(
|
||||
seen.iter()
|
||||
.any(|u| u["sessionUpdate"] == "agent_message_chunk" && u["content"]["text"] == "I fixed the parser.")
|
||||
);
|
||||
assert!(seen.iter().any(|u| u["sessionUpdate"] == "tool_call" && u["toolCallId"] == "history-tool"));
|
||||
assert!(seen.iter().any(|u| u["sessionUpdate"] == "tool_call_update" && u["toolCallId"] == "history-tool"));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn shim_forks_copilot_sessions_and_resumes_the_new_id() {
|
||||
let server =
|
||||
Arc::new(FakeCopilotServer { peer: OnceLock::new(), calls: Mutex::new(Vec::new()), background_shell: false });
|
||||
let updates = Arc::new(CollectUpdates(Mutex::new(Vec::new())));
|
||||
let server_clone = server.clone();
|
||||
let client = attach(updates, move |events| {
|
||||
let (a, b) = tokio::io::duplex(1 << 16);
|
||||
let (ar, aw) = tokio::io::split(a);
|
||||
let (br, bw) = tokio::io::split(b);
|
||||
let srv_peer = Peer::connect_framed(br, bw, server_clone.clone(), Framing::ContentLength);
|
||||
let _ = server_clone.peer.set(srv_peer);
|
||||
Ok(Peer::connect_framed(ar, aw, events, Framing::ContentLength))
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
let _: Value = client.request("initialize", json!({}), None).await.unwrap();
|
||||
let forked: Value = client
|
||||
.request("session/fork", json!({ "sessionId": "cop-sess-1", "cwd": "/tmp", "mcpServers": [] }), None)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(forked["sessionId"], "cop-sess-fork");
|
||||
let calls = server.calls.lock();
|
||||
assert!(calls.iter().any(|(method, params)| method == "sessions.fork" && params["sessionId"] == "cop-sess-1"));
|
||||
assert!(calls.iter().any(|(method, params)| method == "session.resume" && params["sessionId"] == "cop-sess-fork"));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn shim_forwards_disabled_mcp_servers_on_create_and_resume() {
|
||||
let server =
|
||||
|
||||
@@ -370,6 +370,55 @@ impl EventTranslator {
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Translates one persisted Copilot event returned by `session.getMessages`. The live
|
||||
/// event stream omits historical user messages and emits reasoning deltas, while the
|
||||
/// persisted form has complete user and assistant messages.
|
||||
pub fn translate_history(&mut self, main_session: &str, event: &Value, fallback_limit: Option<u32>) -> Translated {
|
||||
let event_type = str_of(event, "type").unwrap_or_default();
|
||||
let data = event.get("data").unwrap_or(&Value::Null);
|
||||
if event_type == "user.message" {
|
||||
let Some(text) = str_of(data, "content").map(str::trim).filter(|text| !text.is_empty()) else {
|
||||
return Translated { updates: Vec::new(), terminal: None };
|
||||
};
|
||||
let target_session = str_of(event, "agentId")
|
||||
.filter(|id| !id.is_empty())
|
||||
.map(|id| format!("{main_session}:sub:{id}"))
|
||||
.unwrap_or_else(|| main_session.to_owned());
|
||||
return Translated {
|
||||
updates: vec![(
|
||||
target_session,
|
||||
json!({
|
||||
"sessionUpdate": "user_message_chunk",
|
||||
"content": { "type": "text", "text": text },
|
||||
}),
|
||||
)],
|
||||
terminal: None,
|
||||
};
|
||||
}
|
||||
|
||||
let mut translated = self.translate(main_session, event, fallback_limit);
|
||||
if event_type == "assistant.message"
|
||||
&& !(data.get("parentToolCallId").and_then(Value::as_str).is_some() && str_of(event, "agentId").is_none())
|
||||
&& let Some(reasoning) = str_of(data, "reasoningText").map(str::trim).filter(|text| !text.is_empty())
|
||||
{
|
||||
let target_session = str_of(event, "agentId")
|
||||
.filter(|id| !id.is_empty())
|
||||
.map(|id| format!("{main_session}:sub:{id}"))
|
||||
.unwrap_or_else(|| main_session.to_owned());
|
||||
translated.updates.insert(
|
||||
0,
|
||||
(
|
||||
target_session,
|
||||
json!({
|
||||
"sessionUpdate": "agent_thought_chunk",
|
||||
"content": { "type": "text", "text": reasoning },
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
translated
|
||||
}
|
||||
}
|
||||
|
||||
fn describe_tool(name: &str, args: &Value) -> ToolInfo {
|
||||
|
||||
@@ -25,11 +25,7 @@ use std::sync::Arc;
|
||||
/// A path, or a name not found on `PATH`, is used as it is; a single match returns its
|
||||
/// resolved path so Windows `PATHEXT` shims (`claude.cmd`, `codex.cmd`) start.
|
||||
pub(crate) fn newest_install(command: &str) -> String {
|
||||
let path = ide_core::process::host_var_os("PATH")
|
||||
.or_else(|| ide_core::process::shell_env().find(|(k, _)| *k == "PATH").map(|(_, v)| v.to_owned()))
|
||||
.unwrap_or_default();
|
||||
// Windows: read afresh, so a tool the user installed since the IDE started is found too.
|
||||
newest_install_in(command, &ide_core::process::with_user_path(&path))
|
||||
newest_install_in(command, &ide_core::tool_path::search_path())
|
||||
}
|
||||
|
||||
fn newest_install_in(command: &str, search: &std::ffi::OsStr) -> String {
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -114,7 +114,7 @@ impl ProviderSpec {
|
||||
if !program.is_absolute() {
|
||||
return self.login_hint.clone();
|
||||
}
|
||||
let search = ide_core::process::host_var_os("PATH").unwrap_or_default();
|
||||
let search = ide_core::tool_path::search_path();
|
||||
let builtin = builtin_spec(&self.id);
|
||||
let on_path = builtin.as_ref().and_then(|b| ide_core::process::find_executable(&b.command, &search));
|
||||
render_login_hint(self, program, on_path.as_deref(), cfg!(windows))
|
||||
@@ -623,7 +623,7 @@ pub(crate) fn describe(spec: &ProviderSpec) -> AgentProvider {
|
||||
command_overridden: builtin.as_ref().is_some_and(|b| b.command != spec.command),
|
||||
command_editable: reason.is_none(),
|
||||
command_read_only_reason: reason,
|
||||
installed: installed(&spec.command),
|
||||
installed: installed_with_env(&spec.command, &spec.env),
|
||||
can_sign_in: spec.can_sign_in(Path::new("."), None),
|
||||
can_check_cli_update: spec.source == AgentSource::Builtin && crate::cli_update::package(&spec.id).is_some(),
|
||||
env: spec.env.iter().cloned().collect(),
|
||||
@@ -1057,19 +1057,23 @@ pub(crate) fn load(custom_dir: Option<&Path>, secrets: Option<&dyn EnvSecrets>)
|
||||
specs
|
||||
}
|
||||
|
||||
/// Whether `command` resolves to an executable (a path, or a name on `PATH`).
|
||||
/// Whether `command` resolves to an executable (a path, or a name on [`ide_core::tool_path::search_path`]).
|
||||
#[cfg(test)]
|
||||
pub(crate) fn installed(command: &str) -> bool {
|
||||
installed_with_env(command, &[])
|
||||
}
|
||||
|
||||
pub(crate) fn installed_with_env(command: &str, env: &[(String, String)]) -> bool {
|
||||
let p = Path::new(command);
|
||||
if p.components().count() > 1 {
|
||||
if p.components().count() > 1 || p.is_absolute() {
|
||||
return is_executable(p);
|
||||
}
|
||||
let exts: &[&str] = if cfg!(windows) { &["exe", "cmd", "bat"] } else { &[] };
|
||||
std::env::var_os("PATH").is_some_and(|path| {
|
||||
std::env::split_paths(&path).any(|dir| {
|
||||
let c = dir.join(command);
|
||||
is_executable(&c) || exts.iter().any(|e| is_executable(&c.with_extension(e)))
|
||||
})
|
||||
})
|
||||
if let Some((_, path)) = env.iter().find(|(k, _)| k.eq_ignore_ascii_case("PATH"))
|
||||
&& ide_core::process::find_executable(command, std::ffi::OsStr::new(path)).is_some()
|
||||
{
|
||||
return true;
|
||||
}
|
||||
ide_core::process::find_executable(command, &ide_core::tool_path::search_path()).is_some()
|
||||
}
|
||||
|
||||
fn is_executable(p: &Path) -> bool {
|
||||
@@ -1326,6 +1330,22 @@ mod tests {
|
||||
assert!(installed("sh"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn installed_with_env_resolves_executables_on_provider_path() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let name = if cfg!(windows) { "fake-agent.cmd" } else { "fake-agent" };
|
||||
let exe = dir.path().join(name);
|
||||
std::fs::write(&exe, "").unwrap();
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::set_permissions(&exe, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
}
|
||||
assert!(!installed("fake-agent"));
|
||||
let env = vec![("PATH".to_owned(), dir.path().to_string_lossy().into_owned())];
|
||||
assert!(installed_with_env("fake-agent", &env));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_builtin_env_writes_and_clears_the_environment() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -320,7 +320,7 @@ fn is_builtin(id: &str) -> bool {
|
||||
}
|
||||
|
||||
fn on_path(command: &str) -> bool {
|
||||
which::which(command).is_ok()
|
||||
ide_core::process::find_executable(command, &ide_core::tool_path::search_path()).is_some()
|
||||
}
|
||||
|
||||
/// `1.10.0` > `1.9.2`; a release is newer than its pre-releases.
|
||||
@@ -708,7 +708,8 @@ fn install_npm(
|
||||
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}")))?;
|
||||
let npm = ide_core::process::find_executable("npm", &ide_core::tool_path::search_path())
|
||||
.ok_or_else(|| IdeError::unavailable(format!("npm is required to install {name}")))?;
|
||||
install_npm_with(&npm, p, entry, dir, platform, public_fallback, cancel, emit)
|
||||
}
|
||||
|
||||
@@ -789,7 +790,8 @@ fn install_uv(
|
||||
_ => format!("{name}=={}", entry.version),
|
||||
};
|
||||
check_spec(&spec)?;
|
||||
let uv = which::which("uv").map_err(|_| IdeError::unavailable(format!("uv is required to install {name}")))?;
|
||||
let uv = ide_core::process::find_executable("uv", &ide_core::tool_path::search_path())
|
||||
.ok_or_else(|| IdeError::unavailable(format!("uv is required to install {name}")))?;
|
||||
let bin = dir.join("bin");
|
||||
let mut cmd = Command::new(uv);
|
||||
cmd.args(["tool", "install", "--force"])
|
||||
|
||||
@@ -185,22 +185,7 @@ pub(crate) fn recorder(out: PathBuf) -> Connector {
|
||||
let file = Arc::new(Mutex::new(String::new()));
|
||||
let connections = Arc::new(Mutex::new(0u32));
|
||||
Arc::new(move |spec, cwd, client, on_stderr| {
|
||||
let program = {
|
||||
let path = Path::new(&spec.command);
|
||||
if path.components().count() > 1 || path.is_absolute() {
|
||||
path.to_path_buf()
|
||||
} else {
|
||||
let search = spec
|
||||
.env
|
||||
.iter()
|
||||
.find(|(k, _)| k.eq_ignore_ascii_case("PATH"))
|
||||
.map(|(_, v)| std::ffi::OsString::from(v))
|
||||
.or_else(|| ide_core::process::shell_env().find(|(k, _)| k == "PATH").map(|(_, v)| v))
|
||||
.or_else(|| ide_core::process::host_var_os("PATH"))
|
||||
.unwrap_or_default();
|
||||
ide_core::process::find_executable(&spec.command, &search).unwrap_or_else(|| path.to_path_buf())
|
||||
}
|
||||
};
|
||||
let program = ide_jsonrpc::resolve_spawn_program(&spec.command, &spec.env);
|
||||
let mut cmd = tokio::process::Command::new(&program);
|
||||
ide_core::process::prepare(cmd.as_std_mut());
|
||||
let mut child = cmd
|
||||
|
||||
@@ -163,6 +163,15 @@ pub struct RepoRef<'a> {
|
||||
|
||||
pub trait SkillSourceFetcher: Send + Sync {
|
||||
fn default_branch(&self, owner: &str, repo: &str, cancel: &CancellationToken) -> IdeResult<String>;
|
||||
fn git_commit_sha(&self, target: RepoRef<'_>, cancel: &CancellationToken) -> IdeResult<String>;
|
||||
/// The root tree SHA recorded in commit `commit_sha`.
|
||||
fn git_commit_tree_sha(
|
||||
&self,
|
||||
owner: &str,
|
||||
repo: &str,
|
||||
commit_sha: &str,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<String>;
|
||||
fn git_tree(&self, target: RepoRef<'_>, cancel: &CancellationToken) -> IdeResult<GitTree>;
|
||||
fn read_blob(
|
||||
&self,
|
||||
@@ -238,6 +247,63 @@ impl SkillSourceFetcher for GitHubHttpFetcher {
|
||||
.map_err(|e| IdeError::new(ErrorKind::Protocol, format!("{owner}/{repo}@{git_ref}: invalid Git tree: {e}")))
|
||||
}
|
||||
|
||||
fn git_commit_sha(&self, target: RepoRef<'_>, cancel: &CancellationToken) -> IdeResult<String> {
|
||||
#[derive(Deserialize)]
|
||||
struct CommitMeta {
|
||||
sha: String,
|
||||
}
|
||||
|
||||
let RepoRef { owner, repo, git_ref } = target;
|
||||
validate_repo_coord(owner, "owner")?;
|
||||
validate_repo_coord(repo, "repository")?;
|
||||
validate_git_ref(git_ref)?;
|
||||
let encoded_ref = encode_url_segment(git_ref);
|
||||
let url = format!("https://api.github.com/repos/{owner}/{repo}/commits/{encoded_ref}");
|
||||
let body = self.get_github_json(&url, MAX_REPO_META_BYTES, cancel)?;
|
||||
let meta: CommitMeta = serde_json::from_str(&body).map_err(|e| {
|
||||
IdeError::new(ErrorKind::Protocol, format!("{owner}/{repo}@{git_ref}: invalid GitHub commit: {e}"))
|
||||
})?;
|
||||
if !is_git_object_id(&meta.sha) {
|
||||
return Err(IdeError::new(
|
||||
ErrorKind::Protocol,
|
||||
format!("{owner}/{repo}@{git_ref}: invalid GitHub commit SHA"),
|
||||
));
|
||||
}
|
||||
Ok(meta.sha)
|
||||
}
|
||||
|
||||
fn git_commit_tree_sha(
|
||||
&self,
|
||||
owner: &str,
|
||||
repo: &str,
|
||||
commit_sha: &str,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<String> {
|
||||
#[derive(Deserialize)]
|
||||
struct TreeRef {
|
||||
sha: String,
|
||||
}
|
||||
#[derive(Deserialize)]
|
||||
struct GitCommit {
|
||||
tree: TreeRef,
|
||||
}
|
||||
|
||||
validate_repo_coord(owner, "owner")?;
|
||||
validate_repo_coord(repo, "repository")?;
|
||||
if !is_git_object_id(commit_sha) {
|
||||
return Err(IdeError::invalid("Invalid commit SHA"));
|
||||
}
|
||||
let url = format!("https://api.github.com/repos/{owner}/{repo}/git/commits/{commit_sha}");
|
||||
let body = self.get_github_json(&url, MAX_REPO_META_BYTES, cancel)?;
|
||||
let commit: GitCommit = serde_json::from_str(&body).map_err(|e| {
|
||||
IdeError::new(ErrorKind::Protocol, format!("{owner}/{repo}@{commit_sha}: invalid Git commit: {e}"))
|
||||
})?;
|
||||
if !is_git_object_id(&commit.tree.sha) {
|
||||
return Err(IdeError::new(ErrorKind::Protocol, format!("{owner}/{repo}@{commit_sha}: invalid tree SHA")));
|
||||
}
|
||||
Ok(commit.tree.sha)
|
||||
}
|
||||
|
||||
fn read_blob(
|
||||
&self,
|
||||
target: RepoRef<'_>,
|
||||
@@ -616,6 +682,17 @@ fn sanitize_repo_as_skill_name(repo: &str) -> String {
|
||||
out.trim_matches('-').to_owned()
|
||||
}
|
||||
|
||||
pub(crate) struct FetchedSubtree {
|
||||
pub tree_sha: String,
|
||||
pub normalized_subpath: String,
|
||||
pub files: Vec<RemoteSkillFile>,
|
||||
pub scan_warnings: Vec<SkillScanWarning>,
|
||||
/// `(relative_path, bytes, executable)` for safe non-symlink files to write on disk.
|
||||
pub regular_files: Vec<(PathBuf, Vec<u8>, bool)>,
|
||||
/// `(relative_path, relative_target)` for safe internal symlinks.
|
||||
pub in_root_symlinks: Vec<(PathBuf, PathBuf)>,
|
||||
}
|
||||
|
||||
struct PreparedSkillBundle {
|
||||
tree_sha: String,
|
||||
skill_name: String,
|
||||
@@ -629,14 +706,19 @@ struct PreparedSkillBundle {
|
||||
in_root_symlinks: Vec<(PathBuf, PathBuf)>,
|
||||
}
|
||||
|
||||
/// Fetches `target`'s tree (or exactly the tree `pinned_tree_sha` when set) and scans the `subpath` subtree.
|
||||
fn fetch_and_scan_bundle(
|
||||
/// Fetches `target`'s tree (or exactly `pinned_tree_sha` when set) and scans `subpath` with hardened
|
||||
/// symlink-graph, executable-script, and hidden-Unicode checks.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(crate) fn fetch_and_scan_subtree(
|
||||
fetcher: &dyn SkillSourceFetcher,
|
||||
target: RepoRef<'_>,
|
||||
subpath: &str,
|
||||
pinned_tree_sha: Option<&str>,
|
||||
max_files: usize,
|
||||
max_subtree_bytes: u64,
|
||||
noun: &str,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<PreparedSkillBundle> {
|
||||
) -> IdeResult<FetchedSubtree> {
|
||||
let RepoRef { owner, repo, git_ref } = target;
|
||||
validate_repo_coord(owner, "owner")?;
|
||||
validate_repo_coord(repo, "repository")?;
|
||||
@@ -646,9 +728,8 @@ fn fetch_and_scan_bundle(
|
||||
let tree = match pinned_tree_sha {
|
||||
Some(sha) => {
|
||||
if !is_git_object_id(sha) {
|
||||
return Err(IdeError::invalid("Preview the skill again before installing it"));
|
||||
return Err(IdeError::invalid(format!("Preview the {noun} again before installing it")));
|
||||
}
|
||||
// The Git trees API accepts a tree SHA in place of a ref.
|
||||
let tree = fetcher.git_tree(RepoRef { owner, repo, git_ref: sha }, cancel)?;
|
||||
if !tree.sha.eq_ignore_ascii_case(sha) {
|
||||
return Err(IdeError::new(
|
||||
@@ -660,6 +741,14 @@ fn fetch_and_scan_bundle(
|
||||
}
|
||||
None => fetcher.git_tree(target, cancel)?,
|
||||
};
|
||||
if tree.truncated {
|
||||
return Err(IdeError::new(
|
||||
ErrorKind::Protocol,
|
||||
format!(
|
||||
"{owner}/{repo}@{git_ref}: GitHub returned a truncated file listing; the {noun} cannot be verified"
|
||||
),
|
||||
));
|
||||
}
|
||||
let prefix = if normalized_subpath.is_empty() { String::new() } else { format!("{normalized_subpath}/") };
|
||||
|
||||
let subtree_entries: Vec<&GitTreeEntry> = tree
|
||||
@@ -672,27 +761,32 @@ fn fetch_and_scan_bundle(
|
||||
|
||||
if subtree_entries.is_empty() {
|
||||
return Err(IdeError::not_found(format!(
|
||||
"Skill path {:?} was not found in {owner}/{repo}@{git_ref}",
|
||||
"{} path {:?} was not found in {owner}/{repo}@{git_ref}",
|
||||
capitalize(noun),
|
||||
normalized_subpath
|
||||
)));
|
||||
}
|
||||
if subtree_entries.len() > MAX_SKILL_FILES {
|
||||
if subtree_entries.len() > max_files {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"Skill exceeds maximum of {MAX_SKILL_FILES} files ({} found)",
|
||||
"{} exceeds maximum of {max_files} files ({} found)",
|
||||
capitalize(noun),
|
||||
subtree_entries.len()
|
||||
)));
|
||||
}
|
||||
|
||||
let declared_total: u64 = subtree_entries.iter().map(|e| e.size.unwrap_or(0)).sum();
|
||||
if declared_total > MAX_SKILL_SUBTREE_BYTES {
|
||||
return Err(IdeError::invalid(format!("Skill exceeds {} MiB size cap", MAX_SKILL_SUBTREE_BYTES >> 20)));
|
||||
if declared_total > max_subtree_bytes {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"{} exceeds {} MiB size cap",
|
||||
capitalize(noun),
|
||||
max_subtree_bytes >> 20
|
||||
)));
|
||||
}
|
||||
|
||||
let mut files = Vec::with_capacity(subtree_entries.len());
|
||||
let mut scan_warnings = Vec::new();
|
||||
let mut regular_files = Vec::new();
|
||||
let mut symlinks: Vec<(PathBuf, String, String)> = Vec::new();
|
||||
let mut skill_markdown: Option<String> = None;
|
||||
let mut actual_total = 0u64;
|
||||
|
||||
for entry in subtree_entries {
|
||||
@@ -709,12 +803,16 @@ fn fetch_and_scan_bundle(
|
||||
target,
|
||||
&entry.path,
|
||||
&entry.sha,
|
||||
MAX_SINGLE_BLOB_BYTES.min(MAX_SKILL_SUBTREE_BYTES - actual_total),
|
||||
MAX_SINGLE_BLOB_BYTES.min(max_subtree_bytes - actual_total),
|
||||
cancel,
|
||||
)?;
|
||||
actual_total = actual_total.saturating_add(bytes.len() as u64);
|
||||
if actual_total > MAX_SKILL_SUBTREE_BYTES {
|
||||
return Err(IdeError::invalid(format!("Skill exceeds {} MiB size cap", MAX_SKILL_SUBTREE_BYTES >> 20)));
|
||||
if actual_total > max_subtree_bytes {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"{} exceeds {} MiB size cap",
|
||||
capitalize(noun),
|
||||
max_subtree_bytes >> 20
|
||||
)));
|
||||
}
|
||||
|
||||
if is_symlink {
|
||||
@@ -748,11 +846,15 @@ fn fetch_and_scan_bundle(
|
||||
|
||||
if let Ok(text) = std::str::from_utf8(&bytes) {
|
||||
scan_hidden_unicode(rel_str, text, &mut scan_warnings);
|
||||
if rel_str == "SKILL.md" {
|
||||
skill_markdown = Some(text.to_owned());
|
||||
if rel_str == "SKILL.md" || rel_str.ends_with("/SKILL.md") {
|
||||
for tool in frontmatter_shell_tools(text) {
|
||||
scan_warnings.push(SkillScanWarning {
|
||||
kind: SkillScanWarningKind::AllowedToolsShell,
|
||||
file: rel_str.to_owned(),
|
||||
message: format!("`allowed-tools` grants shell/command execution (`{tool}`)"),
|
||||
});
|
||||
}
|
||||
}
|
||||
} else if rel_str == "SKILL.md" {
|
||||
return Err(IdeError::invalid("SKILL.md is not valid UTF-8 text"));
|
||||
}
|
||||
|
||||
files.push(RemoteSkillFile {
|
||||
@@ -767,13 +869,12 @@ fn fetch_and_scan_bundle(
|
||||
files.sort_by(|a, b| a.path.cmp(&b.path));
|
||||
regular_files.sort_by(|a, b| a.0.cmp(&b.0));
|
||||
|
||||
// Symlinks are judged together: one link may point through another, and an entry placed beneath
|
||||
// a symlink would be written wherever that link points.
|
||||
let graph = SymlinkGraph::new(symlinks.iter().map(|(path, _, target)| (path.as_path(), target.as_str())));
|
||||
for path in regular_files.iter().map(|(p, _, _)| p).chain(symlinks.iter().map(|(p, _, _)| p)) {
|
||||
if let Some(link) = graph.symlink_ancestor(path) {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"Skill entry {:?} is inside symlink {link:?}; the repository tree is malformed",
|
||||
"{} entry {:?} is inside symlink {link:?}; the repository tree is malformed",
|
||||
capitalize(noun),
|
||||
path.display().to_string()
|
||||
)));
|
||||
}
|
||||
@@ -786,26 +887,65 @@ fn fetch_and_scan_bundle(
|
||||
scan_warnings.push(SkillScanWarning {
|
||||
kind: SkillScanWarningKind::OutOfRootSymlink,
|
||||
file: rel_str,
|
||||
message: format!("Symlink target {target_raw:?} leaves the skill folder (omitted on install)"),
|
||||
message: format!("Symlink target {target_raw:?} leaves the {noun} folder (omitted on install)"),
|
||||
});
|
||||
}
|
||||
}
|
||||
in_root_symlinks.sort();
|
||||
|
||||
let Some(skill_markdown) = skill_markdown else {
|
||||
return Err(IdeError::invalid("Selected folder does not contain a regular SKILL.md file"));
|
||||
};
|
||||
Ok(FetchedSubtree { tree_sha: tree.sha, normalized_subpath, files, scan_warnings, regular_files, in_root_symlinks })
|
||||
}
|
||||
|
||||
let folder_hint = normalized_subpath
|
||||
fn capitalize(s: &str) -> String {
|
||||
let mut c = s.chars();
|
||||
match c.next() {
|
||||
None => String::new(),
|
||||
Some(f) => f.to_uppercase().collect::<String>() + c.as_str(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Fetches `target`'s tree (or exactly the tree `pinned_tree_sha` when set) and scans the `subpath` subtree.
|
||||
fn fetch_and_scan_bundle(
|
||||
fetcher: &dyn SkillSourceFetcher,
|
||||
target: RepoRef<'_>,
|
||||
subpath: &str,
|
||||
pinned_tree_sha: Option<&str>,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<PreparedSkillBundle> {
|
||||
let RepoRef { repo, .. } = target;
|
||||
let mut sub = fetch_and_scan_subtree(
|
||||
fetcher,
|
||||
target,
|
||||
subpath,
|
||||
pinned_tree_sha,
|
||||
MAX_SKILL_FILES,
|
||||
MAX_SKILL_SUBTREE_BYTES,
|
||||
"skill",
|
||||
cancel,
|
||||
)?;
|
||||
|
||||
let skill_bytes = sub
|
||||
.regular_files
|
||||
.iter()
|
||||
.find(|(p, _, _)| p == Path::new("SKILL.md"))
|
||||
.map(|(_, b, _)| b.as_slice())
|
||||
.ok_or_else(|| IdeError::invalid("Selected folder does not contain a regular SKILL.md file"))?;
|
||||
let skill_markdown =
|
||||
std::str::from_utf8(skill_bytes).map_err(|_| IdeError::invalid("SKILL.md is not valid UTF-8 text"))?.to_owned();
|
||||
|
||||
let folder_hint = sub
|
||||
.normalized_subpath
|
||||
.rsplit('/')
|
||||
.next()
|
||||
.filter(|s| !s.is_empty())
|
||||
.map(str::to_owned)
|
||||
.unwrap_or_else(|| sanitize_repo_as_skill_name(repo));
|
||||
|
||||
// Strip any `SKILL.md` shell-tool warnings already collected so `parse_skill_markdown_metadata` emits them in order.
|
||||
sub.scan_warnings.retain(|w| !(w.kind == SkillScanWarningKind::AllowedToolsShell && w.file == "SKILL.md"));
|
||||
let parsed_meta = parse_skill_markdown_metadata(&folder_hint, &skill_markdown)?;
|
||||
for tool in &parsed_meta.shell_tools {
|
||||
scan_warnings.push(SkillScanWarning {
|
||||
sub.scan_warnings.push(SkillScanWarning {
|
||||
kind: SkillScanWarningKind::AllowedToolsShell,
|
||||
file: "SKILL.md".into(),
|
||||
message: format!("`allowed-tools` grants shell/command execution (`{tool}`)"),
|
||||
@@ -813,14 +953,14 @@ fn fetch_and_scan_bundle(
|
||||
}
|
||||
|
||||
Ok(PreparedSkillBundle {
|
||||
tree_sha: tree.sha,
|
||||
tree_sha: sub.tree_sha,
|
||||
skill_name: parsed_meta.name,
|
||||
description: parsed_meta.description,
|
||||
skill_markdown,
|
||||
files,
|
||||
scan_warnings,
|
||||
regular_files,
|
||||
in_root_symlinks,
|
||||
files: sub.files,
|
||||
scan_warnings: sub.scan_warnings,
|
||||
regular_files: sub.regular_files,
|
||||
in_root_symlinks: sub.in_root_symlinks,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1140,6 +1280,33 @@ fn create_parent_dirs_no_follow(root: &Path, rel: &Path) -> IdeResult<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Creates `target` below the existing `anchor` (the home or project folder) without following a
|
||||
/// symlink in any directory between them, the harness store root included.
|
||||
fn create_dirs_below_anchor(anchor: &Path, target: &Path) -> IdeResult<()> {
|
||||
if !anchor.is_dir() {
|
||||
return Err(IdeError::not_found(format!("{} does not exist", anchor.display())));
|
||||
}
|
||||
let rel = target
|
||||
.strip_prefix(anchor)
|
||||
.map_err(|_| IdeError::invalid(format!("{} is outside {}", target.display(), anchor.display())))?;
|
||||
let mut dir = anchor.to_path_buf();
|
||||
for component in rel.components() {
|
||||
if !matches!(component, Component::Normal(_)) {
|
||||
return Err(IdeError::invalid(format!("{} is not a plain path below the store", target.display())));
|
||||
}
|
||||
dir.push(component);
|
||||
match std::fs::symlink_metadata(&dir) {
|
||||
Ok(meta) if meta.is_dir() => {}
|
||||
Ok(_) => {
|
||||
return Err(IdeError::invalid(format!("{} passes through a symlink or file", dir.display())));
|
||||
}
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => std::fs::create_dir(&dir)?,
|
||||
Err(e) => return Err(e.into()),
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Whether the symlink at `link` resolves strictly inside `root` (canonical), following links on disk.
|
||||
/// Components that do not exist are resolved lexically.
|
||||
#[cfg(unix)]
|
||||
@@ -1220,15 +1387,16 @@ pub fn install_skill(
|
||||
workspace_root: Option<&Path>,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<PathBuf> {
|
||||
let target_root = match req.scope {
|
||||
// Anchored at the home or project folder: nothing below it may be a symlink, store included.
|
||||
let (anchor, target_root) = match req.scope {
|
||||
McpScope::User => {
|
||||
let home = user_home.ok_or_else(|| IdeError::unavailable("Cannot locate user home directory"))?;
|
||||
home.join(".agents").join("skills")
|
||||
(home.to_path_buf(), home.join(".agents").join("skills"))
|
||||
}
|
||||
McpScope::Workspace => {
|
||||
let ws = workspace_root
|
||||
.ok_or_else(|| IdeError::invalid("Open a trusted project to install workspace skills"))?;
|
||||
ws.join(".agents").join("skills")
|
||||
(ws.to_path_buf(), ws.join(".agents").join("skills"))
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1245,20 +1413,60 @@ pub fn install_skill(
|
||||
));
|
||||
}
|
||||
|
||||
std::fs::create_dir_all(&target_root)?;
|
||||
let final_dir = target_root.join(&bundle.skill_name);
|
||||
if final_dir.exists() && !req.overwrite {
|
||||
write_staged_subtree(
|
||||
&anchor,
|
||||
&target_root,
|
||||
&bundle.skill_name,
|
||||
req.overwrite,
|
||||
"Skill",
|
||||
&bundle.regular_files,
|
||||
&bundle.in_root_symlinks,
|
||||
&[],
|
||||
)
|
||||
}
|
||||
|
||||
/// Atomically writes `regular_files`, `in_root_symlinks`, and `extra_files` into a staging folder
|
||||
/// under `target_root`, verifies created symlinks stay inside the folder, and swaps into `<target_root>/<folder_name>`.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(crate) fn write_staged_subtree(
|
||||
anchor: &Path,
|
||||
target_root: &Path,
|
||||
folder_name: &str,
|
||||
overwrite: bool,
|
||||
noun_cap: &str,
|
||||
regular_files: &[(PathBuf, Vec<u8>, bool)],
|
||||
in_root_symlinks: &[(PathBuf, PathBuf)],
|
||||
extra_files: &[(&str, &[u8])],
|
||||
) -> IdeResult<PathBuf> {
|
||||
create_dirs_below_anchor(anchor, target_root)?;
|
||||
if folder_name.is_empty() || !Path::new(folder_name).components().all(|c| matches!(c, Component::Normal(_))) {
|
||||
return Err(IdeError::invalid(format!("Invalid {} folder name", noun_cap.to_ascii_lowercase())));
|
||||
}
|
||||
let final_dir = target_root.join(folder_name);
|
||||
let existing = match std::fs::symlink_metadata(&final_dir) {
|
||||
Ok(meta) if meta.is_dir() => true,
|
||||
Ok(_) => {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"{} is a symlink or file, not a {} folder",
|
||||
final_dir.display(),
|
||||
noun_cap.to_ascii_lowercase()
|
||||
)));
|
||||
}
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => false,
|
||||
Err(e) => return Err(e.into()),
|
||||
};
|
||||
if existing && !overwrite {
|
||||
return Err(IdeError::new(
|
||||
ErrorKind::AlreadyExists,
|
||||
format!("Skill `{}` is already installed in {}", bundle.skill_name, target_root.display()),
|
||||
format!("{noun_cap} `{folder_name}` is already installed in {}", target_root.display()),
|
||||
));
|
||||
}
|
||||
|
||||
let nonce = SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or_default();
|
||||
let staging = target_root.join(format!(".staging-{}-{nonce}-{}", bundle.skill_name, std::process::id()));
|
||||
let staging = target_root.join(format!(".staging-{folder_name}-{nonce}-{}", std::process::id()));
|
||||
let write_res = (|| -> IdeResult<()> {
|
||||
std::fs::create_dir_all(&staging)?;
|
||||
for (rel_path, bytes, is_exec) in &bundle.regular_files {
|
||||
for (rel_path, bytes, is_exec) in regular_files {
|
||||
create_parent_dirs_no_follow(&staging, rel_path)?;
|
||||
let dest = staging.join(rel_path);
|
||||
std::fs::write(&dest, bytes)?;
|
||||
@@ -1270,7 +1478,12 @@ pub fn install_skill(
|
||||
#[cfg(not(unix))]
|
||||
let _ = is_exec;
|
||||
}
|
||||
for (rel_link, target) in &bundle.in_root_symlinks {
|
||||
for (rel_str, bytes) in extra_files {
|
||||
let rel_path = validate_rel_skill_file(rel_str)?;
|
||||
create_parent_dirs_no_follow(&staging, &rel_path)?;
|
||||
std::fs::write(staging.join(&rel_path), bytes)?;
|
||||
}
|
||||
for (rel_link, target) in in_root_symlinks {
|
||||
create_parent_dirs_no_follow(&staging, rel_link)?;
|
||||
let dest = staging.join(rel_link);
|
||||
#[cfg(unix)]
|
||||
@@ -1288,17 +1501,18 @@ pub fn install_skill(
|
||||
#[cfg(unix)]
|
||||
{
|
||||
let root = std::fs::canonicalize(&staging)?;
|
||||
for (rel_link, _) in &bundle.in_root_symlinks {
|
||||
for (rel_link, _) in in_root_symlinks {
|
||||
if !link_resolves_inside(&root, &staging.join(rel_link)) {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"Symlink {:?} leaves the skill folder",
|
||||
rel_link.display().to_string()
|
||||
"Symlink {:?} leaves the {} folder",
|
||||
rel_link.display().to_string(),
|
||||
noun_cap.to_ascii_lowercase()
|
||||
)));
|
||||
}
|
||||
}
|
||||
}
|
||||
let backup = if final_dir.exists() {
|
||||
let bak = target_root.join(format!(".old-{}-{nonce}", bundle.skill_name));
|
||||
let backup = if existing {
|
||||
let bak = target_root.join(format!(".old-{folder_name}-{nonce}"));
|
||||
std::fs::rename(&final_dir, &bak)?;
|
||||
Some(bak)
|
||||
} else {
|
||||
@@ -1323,6 +1537,179 @@ pub fn install_skill(
|
||||
Ok(final_dir)
|
||||
}
|
||||
|
||||
/// Scans a local directory on disk with the same symlink-graph, executable-script, and hidden-Unicode
|
||||
/// checks used for remote GitHub subtrees.
|
||||
/// Content digest of a scanned local folder, used to pin a local preview to its install.
|
||||
fn local_subtree_digest(regular_files: &[(PathBuf, Vec<u8>, bool)], symlinks: &[(PathBuf, PathBuf)]) -> String {
|
||||
let mut hasher = blake3::Hasher::new();
|
||||
hasher.update(b"openidea-local-subtree-v1\0");
|
||||
for (path, bytes, executable) in regular_files {
|
||||
hasher.update(b"f\0");
|
||||
hasher.update(path.to_string_lossy().replace('\\', "/").as_bytes());
|
||||
hasher.update(&[0, u8::from(*executable)]);
|
||||
hasher.update(&(bytes.len() as u64).to_le_bytes());
|
||||
hasher.update(bytes);
|
||||
}
|
||||
for (path, target) in symlinks {
|
||||
hasher.update(b"l\0");
|
||||
hasher.update(path.to_string_lossy().replace('\\', "/").as_bytes());
|
||||
hasher.update(b"\0");
|
||||
hasher.update(target.to_string_lossy().replace('\\', "/").as_bytes());
|
||||
hasher.update(b"\0");
|
||||
}
|
||||
format!("local-blake3:{}", hasher.finalize().to_hex())
|
||||
}
|
||||
|
||||
pub(crate) fn scan_local_subtree(
|
||||
dir: &Path,
|
||||
max_files: usize,
|
||||
max_subtree_bytes: u64,
|
||||
noun: &str,
|
||||
) -> IdeResult<FetchedSubtree> {
|
||||
if !dir.is_dir() {
|
||||
return Err(IdeError::not_found(format!("Directory {} does not exist", dir.display())));
|
||||
}
|
||||
let mut files = Vec::new();
|
||||
let mut scan_warnings = Vec::new();
|
||||
let mut regular_files = Vec::new();
|
||||
let mut symlinks: Vec<(PathBuf, String, String)> = Vec::new();
|
||||
let mut actual_total = 0u64;
|
||||
|
||||
let mut stack = vec![(dir.to_path_buf(), String::new())];
|
||||
while let Some((cur_dir, rel_prefix)) = stack.pop() {
|
||||
let mut entries: Vec<_> = std::fs::read_dir(&cur_dir)?.filter_map(Result::ok).collect();
|
||||
entries.sort_by_key(|e| e.file_name());
|
||||
for entry in entries {
|
||||
let name = entry.file_name();
|
||||
let Some(name_str) = name.to_str() else {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"{} contains a file name that is not valid UTF-8: {}",
|
||||
capitalize(noun),
|
||||
entry.path().display()
|
||||
)));
|
||||
};
|
||||
if name_str == ".git" || name_str == "node_modules" || name_str == "target" {
|
||||
continue;
|
||||
}
|
||||
let rel_str = if rel_prefix.is_empty() { name_str.to_owned() } else { format!("{rel_prefix}/{name_str}") };
|
||||
let rel_path = validate_rel_skill_file(&rel_str)?;
|
||||
let full = entry.path();
|
||||
let meta = std::fs::symlink_metadata(&full)?;
|
||||
if (meta.file_type().is_symlink() || meta.file_type().is_file())
|
||||
&& regular_files.len() + symlinks.len() >= max_files
|
||||
{
|
||||
return Err(IdeError::invalid(format!("{} exceeds maximum of {max_files} files", capitalize(noun))));
|
||||
}
|
||||
if meta.file_type().is_symlink() {
|
||||
let target_raw = std::fs::read_link(&full)?.to_string_lossy().replace('\\', "/");
|
||||
symlinks.push((rel_path, rel_str.clone(), target_raw));
|
||||
files.push(RemoteSkillFile { path: rel_str, size: 0, executable: false, symlink: true });
|
||||
continue;
|
||||
}
|
||||
if meta.file_type().is_dir() {
|
||||
stack.push((full, rel_str));
|
||||
continue;
|
||||
}
|
||||
if !meta.file_type().is_file() {
|
||||
continue;
|
||||
}
|
||||
if meta.len() > MAX_SINGLE_BLOB_BYTES {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"File {rel_str:?} exceeds {} MiB size cap",
|
||||
MAX_SINGLE_BLOB_BYTES >> 20
|
||||
)));
|
||||
}
|
||||
let bytes = std::fs::read(&full)?;
|
||||
actual_total = actual_total.saturating_add(bytes.len() as u64);
|
||||
if actual_total > max_subtree_bytes {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"{} exceeds {} MiB size cap",
|
||||
capitalize(noun),
|
||||
max_subtree_bytes >> 20
|
||||
)));
|
||||
}
|
||||
#[cfg(unix)]
|
||||
let is_exec_mode = {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
meta.permissions().mode() & 0o111 != 0
|
||||
};
|
||||
#[cfg(not(unix))]
|
||||
let is_exec_mode = false;
|
||||
let has_shebang = bytes.starts_with(b"#!");
|
||||
let is_script_path = is_executable_or_script_path(&rel_path);
|
||||
if is_exec_mode || has_shebang || is_script_path {
|
||||
let reason = if is_exec_mode {
|
||||
"executable file mode"
|
||||
} else if has_shebang {
|
||||
"script with `#!` interpreter header"
|
||||
} else {
|
||||
"bundled script or native binary"
|
||||
};
|
||||
scan_warnings.push(SkillScanWarning {
|
||||
kind: SkillScanWarningKind::ExecutableScript,
|
||||
file: rel_str.clone(),
|
||||
message: format!("Contains {reason}"),
|
||||
});
|
||||
}
|
||||
if let Ok(text) = std::str::from_utf8(&bytes) {
|
||||
scan_hidden_unicode(&rel_str, text, &mut scan_warnings);
|
||||
if rel_str == "SKILL.md" || rel_str.ends_with("/SKILL.md") {
|
||||
for tool in frontmatter_shell_tools(text) {
|
||||
scan_warnings.push(SkillScanWarning {
|
||||
kind: SkillScanWarningKind::AllowedToolsShell,
|
||||
file: rel_str.clone(),
|
||||
message: format!("`allowed-tools` grants shell/command execution (`{tool}`)"),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
files.push(RemoteSkillFile {
|
||||
path: rel_str,
|
||||
size: bytes.len() as u64,
|
||||
executable: is_exec_mode || has_shebang,
|
||||
symlink: false,
|
||||
});
|
||||
regular_files.push((rel_path, bytes, is_exec_mode));
|
||||
}
|
||||
}
|
||||
|
||||
files.sort_by(|a, b| a.path.cmp(&b.path));
|
||||
regular_files.sort_by(|a, b| a.0.cmp(&b.0));
|
||||
|
||||
let graph = SymlinkGraph::new(symlinks.iter().map(|(path, _, target)| (path.as_path(), target.as_str())));
|
||||
for path in regular_files.iter().map(|(p, _, _)| p).chain(symlinks.iter().map(|(p, _, _)| p)) {
|
||||
if let Some(link) = graph.symlink_ancestor(path) {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"{} entry {:?} is inside symlink {link:?}",
|
||||
capitalize(noun),
|
||||
path.display().to_string()
|
||||
)));
|
||||
}
|
||||
}
|
||||
let mut in_root_symlinks = Vec::new();
|
||||
for (rel_path, rel_str, target_raw) in symlinks {
|
||||
if graph.stays_inside(&rel_path, &target_raw) {
|
||||
in_root_symlinks.push((rel_path, PathBuf::from(target_raw)));
|
||||
} else {
|
||||
scan_warnings.push(SkillScanWarning {
|
||||
kind: SkillScanWarningKind::OutOfRootSymlink,
|
||||
file: rel_str,
|
||||
message: format!("Symlink target {target_raw:?} leaves the {noun} folder (omitted on install)"),
|
||||
});
|
||||
}
|
||||
}
|
||||
in_root_symlinks.sort();
|
||||
|
||||
Ok(FetchedSubtree {
|
||||
tree_sha: local_subtree_digest(®ular_files, &in_root_symlinks),
|
||||
normalized_subpath: String::new(),
|
||||
files,
|
||||
scan_warnings,
|
||||
regular_files,
|
||||
in_root_symlinks,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -1374,6 +1761,25 @@ mod tests {
|
||||
.cloned()
|
||||
.ok_or_else(|| IdeError::not_found(format!("unknown ref {}", target.git_ref)))
|
||||
}
|
||||
fn git_commit_sha(&self, target: RepoRef<'_>, _cancel: &CancellationToken) -> IdeResult<String> {
|
||||
self.trees
|
||||
.get(target.git_ref)
|
||||
.map(|_| git_blob_id(format!("commit:{}", target.git_ref).as_bytes()))
|
||||
.ok_or_else(|| IdeError::not_found(format!("unknown ref {}", target.git_ref)))
|
||||
}
|
||||
fn git_commit_tree_sha(
|
||||
&self,
|
||||
_owner: &str,
|
||||
_repo: &str,
|
||||
commit_sha: &str,
|
||||
_cancel: &CancellationToken,
|
||||
) -> IdeResult<String> {
|
||||
self.trees
|
||||
.iter()
|
||||
.find(|(git_ref, _)| git_blob_id(format!("commit:{git_ref}").as_bytes()) == commit_sha)
|
||||
.map(|(_, tree)| tree.sha.clone())
|
||||
.ok_or_else(|| IdeError::not_found(format!("unknown commit {commit_sha}")))
|
||||
}
|
||||
|
||||
fn read_blob(
|
||||
&self,
|
||||
@@ -1440,7 +1846,9 @@ mod tests {
|
||||
let cancel = CancellationToken::new();
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let home = tmp.path().join("home");
|
||||
std::fs::create_dir_all(&home).unwrap();
|
||||
let ws = tmp.path().join("ws");
|
||||
std::fs::create_dir_all(&ws).unwrap();
|
||||
|
||||
// Bare `owner/repo` lists both skills; `owner/repo@clean-skill` falls back from ref lookup to skill filter!
|
||||
let all = browse_skills(&fetcher, "acme/skills", &cancel).unwrap();
|
||||
@@ -1796,4 +2204,66 @@ mod tests {
|
||||
.unwrap();
|
||||
assert!(dest.join("SKILL.md").is_file());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn local_scan_counts_symlinks_toward_the_file_cap() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
std::fs::write(tmp.path().join("SKILL.md"), "x").unwrap();
|
||||
for i in 0..3 {
|
||||
std::os::unix::fs::symlink("SKILL.md", tmp.path().join(format!("link-{i}"))).unwrap();
|
||||
}
|
||||
let Err(err) = scan_local_subtree(tmp.path(), 3, 1 << 20, "plugin") else { panic!("symlinks must count") };
|
||||
assert!(err.to_string().contains("maximum of 3 files"), "{err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn truncated_tree_listings_are_rejected() {
|
||||
let mut fetcher = FakeFetcher::new();
|
||||
fetcher.add_tree("main", vec![("skills/a/SKILL.md", "100644", b"---\nname: a\ndescription: a\n---\n")]);
|
||||
fetcher.trees.get_mut("main").unwrap().truncated = true;
|
||||
let cancel = CancellationToken::new();
|
||||
let target = RepoRef { owner: "o", repo: "r", git_ref: "main" };
|
||||
let Err(err) = fetch_and_scan_subtree(&fetcher, target, "skills/a", None, 10, 1 << 20, "skill", &cancel) else {
|
||||
panic!("a truncated listing cannot be verified")
|
||||
};
|
||||
assert!(err.to_string().contains("truncated"), "{err}");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn staged_installs_do_not_follow_symlinks_below_the_store() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let store = tmp.path().join("store");
|
||||
let outside = tmp.path().join("outside");
|
||||
std::fs::create_dir_all(&store).unwrap();
|
||||
std::fs::create_dir_all(&outside).unwrap();
|
||||
std::os::unix::fs::symlink(&outside, store.join("mkt")).unwrap();
|
||||
let files = vec![(PathBuf::from("plugin.json"), b"{}".to_vec(), false)];
|
||||
let Err(err) = write_staged_subtree(&store, &store.join("mkt"), "plugin", false, "Plugin", &files, &[], &[])
|
||||
else {
|
||||
panic!("a symlinked marketplace folder must not be written through")
|
||||
};
|
||||
assert!(err.to_string().contains("symlink"), "{err}");
|
||||
assert!(std::fs::read_dir(&outside).unwrap().next().is_none(), "nothing was written outside the store");
|
||||
|
||||
// The store root itself (`<home>/.claude/plugins` → elsewhere) is checked as well.
|
||||
let home = tmp.path().join("home");
|
||||
std::fs::create_dir_all(home.join(".claude")).unwrap();
|
||||
std::os::unix::fs::symlink(&outside, home.join(".claude/plugins")).unwrap();
|
||||
let store_root = home.join(".claude/plugins/cache/mkt");
|
||||
let Err(err) = write_staged_subtree(&home, &store_root, "plugin", false, "Plugin", &files, &[], &[]) else {
|
||||
panic!("a symlinked store root must not be written through")
|
||||
};
|
||||
assert!(err.to_string().contains("symlink"), "{err}");
|
||||
assert!(std::fs::read_dir(&outside).unwrap().next().is_none());
|
||||
|
||||
std::fs::create_dir_all(store.join("real")).unwrap();
|
||||
std::os::unix::fs::symlink(&outside, store.join("real/plugin")).unwrap();
|
||||
let Err(err) = write_staged_subtree(&store, &store.join("real"), "plugin", true, "Plugin", &files, &[], &[])
|
||||
else {
|
||||
panic!("an existing symlinked plugin folder must not be replaced through")
|
||||
};
|
||||
assert!(err.to_string().contains("symlink"), "{err}");
|
||||
}
|
||||
}
|
||||
@@ -275,12 +275,27 @@ pub fn discover_skills_in(workspaces: &[PathBuf], home: Option<&Path>) -> Vec<Ag
|
||||
}
|
||||
|
||||
/// [`discover_skills_in`] plus the `<dir>` skill folders contributed by enabled OpenIDEA
|
||||
/// plugins (`[[contributes.skills]]`). Workspace and user skills take precedence on a name
|
||||
/// clash; a plugin skill is never silently renamed.
|
||||
/// plugins (`[[contributes.skills]]`) and unified agent plugin bundles (`plugins.rs`).
|
||||
/// Workspace and user skills take precedence on a name clash; a plugin skill is never silently renamed.
|
||||
pub fn discover_skills_with_plugins(
|
||||
workspaces: &[PathBuf],
|
||||
home: Option<&Path>,
|
||||
plugin_skill_dirs: &[PathBuf],
|
||||
) -> Vec<AgentSkill> {
|
||||
let default_policy = crate::plugins::PluginsPolicy { workspace_roots: workspaces.to_vec(), ..Default::default() };
|
||||
let states =
|
||||
crate::plugins::resolve_plugins(crate::plugins::discover_plugins(workspaces, home), &default_policy, None);
|
||||
let projected = crate::plugins::projected_skill_roots(&states, None);
|
||||
discover_skills_with_agent_plugins(workspaces, home, plugin_skill_dirs, &projected)
|
||||
}
|
||||
|
||||
/// Discovers skills across `workspaces`, `home`, OpenIDEA IDE-plugin skill folders (`plugin_skill_dirs`),
|
||||
/// and resolved agent plugin bundle roots (`agent_plugin_roots`).
|
||||
pub fn discover_skills_with_agent_plugins(
|
||||
workspaces: &[PathBuf],
|
||||
home: Option<&Path>,
|
||||
plugin_skill_dirs: &[PathBuf],
|
||||
agent_plugin_roots: &[crate::plugins::ProjectedSkillRoot],
|
||||
) -> Vec<AgentSkill> {
|
||||
let mut out: Vec<AgentSkill> = Vec::new();
|
||||
let mut seen_paths: HashSet<PathBuf> = HashSet::new();
|
||||
@@ -338,9 +353,19 @@ pub fn discover_skills_with_plugins(
|
||||
let Ok(text) = std::fs::read_to_string(dir.join("SKILL.md")) else { continue };
|
||||
push_skill(parse_skill_file(dir, &folder, &text, AgentSkillSource::Plugin));
|
||||
}
|
||||
if let Some(home) = home {
|
||||
for (root, source) in copilot_installed_plugin_roots(&home.join(".copilot")) {
|
||||
for skill in skills_of(&root, source) {
|
||||
for proj in agent_plugin_roots {
|
||||
if proj.dir.join("SKILL.md").is_file() && proj.dir.file_name().and_then(|s| s.to_str()) != Some("skills") {
|
||||
let Some(folder) = file_name(&proj.dir) else { continue };
|
||||
if let Ok(text) = std::fs::read_to_string(proj.dir.join("SKILL.md")) {
|
||||
let mut skill = parse_skill_file(&proj.dir, &folder, &text, proj.source);
|
||||
skill.plugin_id = Some(proj.plugin_id.clone());
|
||||
skill.plugin_name = Some(proj.plugin_name.clone());
|
||||
push_skill(skill);
|
||||
}
|
||||
} else {
|
||||
for mut skill in skills_of(&proj.dir, proj.source) {
|
||||
skill.plugin_id = Some(proj.plugin_id.clone());
|
||||
skill.plugin_name = Some(proj.plugin_name.clone());
|
||||
push_skill(skill);
|
||||
}
|
||||
}
|
||||
@@ -388,83 +413,6 @@ fn monorepo_subdirs(root: &Path, max_depth: usize) -> Vec<PathBuf> {
|
||||
out
|
||||
}
|
||||
|
||||
/// Discovers skill roots inside `~/.copilot/installed-plugins`, supporting both Copilot CLI's
|
||||
/// 2-level `<marketplace-or-_direct>/<plugin>` layout (and `config.json` `installedPlugins`
|
||||
/// enablement) and flat 1-level `<plugin>` folders.
|
||||
fn copilot_installed_plugin_roots(copilot_dir: &Path) -> Vec<(PathBuf, AgentSkillSource)> {
|
||||
let mut disabled_paths: HashSet<PathBuf> = HashSet::new();
|
||||
let mut plugin_dirs: Vec<PathBuf> = Vec::new();
|
||||
let mut seen_dirs: HashSet<PathBuf> = HashSet::new();
|
||||
let mut push_plugin = |dir: PathBuf, disabled: &HashSet<PathBuf>| {
|
||||
if !dir.is_dir() {
|
||||
return;
|
||||
}
|
||||
let canon = dunce::canonicalize(&dir).unwrap_or_else(|_| dir.clone());
|
||||
if disabled.contains(&canon) || !seen_dirs.insert(canon) {
|
||||
return;
|
||||
}
|
||||
plugin_dirs.push(dir);
|
||||
};
|
||||
|
||||
if let Ok(text) = std::fs::read_to_string(copilot_dir.join("config.json"))
|
||||
&& let Ok(root) = serde_json::from_str::<serde_json::Value>(&ide_core::jsonc::strip(&text))
|
||||
&& let Some(installed) = root.get("installedPlugins").and_then(serde_json::Value::as_array)
|
||||
{
|
||||
for entry in installed {
|
||||
let Some(raw_cache) = entry.get("cache_path").and_then(serde_json::Value::as_str).map(str::trim) else {
|
||||
continue;
|
||||
};
|
||||
if raw_cache.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let dir =
|
||||
if Path::new(raw_cache).is_relative() { copilot_dir.join(raw_cache) } else { PathBuf::from(raw_cache) };
|
||||
if entry.get("enabled").and_then(serde_json::Value::as_bool) == Some(false) {
|
||||
disabled_paths.insert(dunce::canonicalize(&dir).unwrap_or(dir));
|
||||
} else {
|
||||
push_plugin(dir, &disabled_paths);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let plugins_root = copilot_dir.join("installed-plugins");
|
||||
for entry in sorted(&plugins_root) {
|
||||
if !entry.is_dir() {
|
||||
continue;
|
||||
}
|
||||
if looks_like_plugin_dir(&entry) {
|
||||
push_plugin(entry, &disabled_paths);
|
||||
} else {
|
||||
// 2-level `<marketplace>/<plugin>` or `_direct/<plugin>`.
|
||||
for sub in sorted(&entry) {
|
||||
if sub.is_dir() {
|
||||
push_plugin(sub, &disabled_paths);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut roots = Vec::new();
|
||||
for plugin in plugin_dirs {
|
||||
let skills_sub = plugin.join("skills");
|
||||
if skills_sub.is_dir() {
|
||||
roots.push((skills_sub, AgentSkillSource::CopilotUser));
|
||||
} else {
|
||||
roots.push((plugin, AgentSkillSource::CopilotUser));
|
||||
}
|
||||
}
|
||||
roots
|
||||
}
|
||||
|
||||
fn looks_like_plugin_dir(dir: &Path) -> bool {
|
||||
dir.join("skills").is_dir()
|
||||
|| dir.join("plugin.json").is_file()
|
||||
|| dir.join(".plugin").is_dir()
|
||||
|| dir.join(".claude-plugin").is_dir()
|
||||
|| dir.join(".cursor-plugin").is_dir()
|
||||
|| dir.join("SKILL.md").is_file()
|
||||
}
|
||||
|
||||
/// The skills of one root: `<name>/SKILL.md` folders and `<category>/<name>/SKILL.md`
|
||||
/// category folders, validated.
|
||||
fn skills_of(root: &Path, source: AgentSkillSource) -> Vec<AgentSkill> {
|
||||
@@ -544,6 +492,8 @@ fn parse_skill_file(dir: &Path, folder: &str, text: &str, source: AgentSkillSour
|
||||
paths,
|
||||
valid: warnings.is_empty(),
|
||||
warnings,
|
||||
plugin_id: None,
|
||||
plugin_name: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1070,6 +1020,8 @@ mod tests {
|
||||
paths: Vec::new(),
|
||||
valid: true,
|
||||
warnings: Vec::new(),
|
||||
plugin_id: None,
|
||||
plugin_name: None,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2191,6 +2191,41 @@ async fn a_session_that_fails_to_load_is_reported_and_replaced_only_when_sent_ag
|
||||
assert_eq!(calls(&agent), ["session/load", "session/new", "session/prompt"]);
|
||||
}
|
||||
|
||||
/// A locked Codex recording can be forked without resuming it or moving its writer between tasks.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn codex_writer_conflict_can_retry_or_fork_on_a_new_connection() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let task = {
|
||||
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
let task = mgr
|
||||
.create(NewAgentTask { prompt: text("again"), provider: "codex".into(), ..Default::default() })
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
mgr.shutdown();
|
||||
task
|
||||
};
|
||||
let agent = Arc::new(FakeAgent {
|
||||
load_error: Some((codes::INVALID_PARAMS, "thread s1 already has an active writer".into())),
|
||||
..Default::default()
|
||||
});
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
for _ in 0..2 {
|
||||
mgr.prompt(&task.id, text("again"), false).await.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Failed).await;
|
||||
}
|
||||
assert!(!agent.calls.lock().iter().any(|c| c == "session/new"));
|
||||
let copy = mgr.fork(&task.id, None).await.unwrap();
|
||||
assert_eq!(agent.forks.lock().last().unwrap()["sessionId"], "s1");
|
||||
let copy_handle = mgr.task(©.id).unwrap();
|
||||
assert_eq!(copy_handle.live.lock().as_ref().unwrap().session, "s2");
|
||||
let loads = agent.calls.lock().iter().filter(|c| *c == "session/load").count();
|
||||
mgr.prompt(©.id, text("again"), false).await.unwrap();
|
||||
wait_for(&mgr, ©.id, AgentStatus::Ready).await;
|
||||
assert_eq!(agent.calls.lock().iter().filter(|c| *c == "session/load").count(), loads);
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
fn text(t: &str) -> AgentPrompt {
|
||||
AgentPrompt { text: t.into(), ..AgentPrompt::default() }
|
||||
}
|
||||
@@ -3241,6 +3276,58 @@ fn plant_codex_session(root: &Path, session_id: &str) {
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
/// Plants a recorded Copilot session below the test home.
|
||||
fn plant_copilot_session(root: &Path, session_id: &str) {
|
||||
let dir = root.join(".copilot").join("session-state").join(session_id);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::write(
|
||||
dir.join("workspace.yaml"),
|
||||
format!("id: {session_id}\ncwd: {}\nname: Fix the Copilot parser\n", root.to_string_lossy()),
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::write(
|
||||
dir.join("events.jsonl"),
|
||||
format!(
|
||||
"{}\n",
|
||||
json!({
|
||||
"type": "user.message",
|
||||
"data": {"content": "fix the Copilot parser"}
|
||||
})
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn imports_copilot_sessions_and_loads_their_history() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
plant_copilot_session(tmp.path(), NATIVE_SOURCE);
|
||||
|
||||
let sessions = mgr.external_sessions();
|
||||
assert!(sessions.iter().any(|session| session.provider == "copilot" && session.session_id == NATIVE_SOURCE));
|
||||
let task = mgr.import_session("copilot", NATIVE_SOURCE).unwrap();
|
||||
assert_eq!(task.provider, "copilot");
|
||||
|
||||
for _ in 0..200 {
|
||||
if agent.calls.lock().iter().any(|call| call == "session/load")
|
||||
&& mgr.entries(&task.id, None).unwrap().len() >= 2
|
||||
{
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
assert!(agent.calls.lock().iter().any(|call| call == "session/load"));
|
||||
assert!(
|
||||
mgr.entries(&task.id, None)
|
||||
.unwrap()
|
||||
.iter()
|
||||
.any(|entry| matches!(entry, AgentEntry::User { text, .. } if text == "earlier question"))
|
||||
);
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn fork_session_uses_the_id_codex_assigns() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
@@ -3261,6 +3348,28 @@ async fn fork_session_uses_the_id_codex_assigns() {
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn fork_session_uses_the_id_copilot_assigns() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
plant_copilot_session(tmp.path(), NATIVE_SOURCE);
|
||||
|
||||
let task = mgr.fork_session("copilot", NATIVE_SOURCE, tmp.path()).unwrap();
|
||||
for _ in 0..200 {
|
||||
if !agent.forks.lock().is_empty() {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).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(), "copilot 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();
|
||||
@@ -5947,6 +6056,8 @@ async fn per_session_mcp_overrides_filter_session_and_reload_when_idle() {
|
||||
headers: Vec::new(),
|
||||
agents: Vec::new(),
|
||||
unapproved: false,
|
||||
plugin_id: None,
|
||||
plugin_name: None,
|
||||
},
|
||||
McpServer {
|
||||
id: "user::slack".into(),
|
||||
@@ -5961,6 +6072,8 @@ async fn per_session_mcp_overrides_filter_session_and_reload_when_idle() {
|
||||
headers: Vec::new(),
|
||||
agents: Vec::new(),
|
||||
unapproved: false,
|
||||
plugin_id: None,
|
||||
plugin_name: None,
|
||||
},
|
||||
]
|
||||
}));
|
||||
|
||||
@@ -9,12 +9,34 @@ use std::path::{Path, PathBuf};
|
||||
use std::time::{Duration, UNIX_EPOCH};
|
||||
|
||||
pub(crate) struct Created {
|
||||
#[cfg_attr(not(test), allow(dead_code))]
|
||||
pub path: PathBuf,
|
||||
pub cwd: PathBuf,
|
||||
pub branch: String,
|
||||
pub base: String,
|
||||
pub base_commit: String,
|
||||
}
|
||||
|
||||
const OWNERSHIP_MARKER: &str = "openidea-worktree.json";
|
||||
const OWNERSHIP_TAG: &str = "openidea-agent";
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct WorktreeOwnership {
|
||||
owner: String,
|
||||
task_id: String,
|
||||
worktree_root: PathBuf,
|
||||
repo_root: PathBuf,
|
||||
}
|
||||
|
||||
/// Returns the canonical root of the Git repository containing `project_root`, if any.
|
||||
pub fn canonical_repo_root(project_root: &Path) -> IdeResult<Option<PathBuf>> {
|
||||
match Repo::discover(project_root)? {
|
||||
Some(repo) => Ok(Some(dunce::canonicalize(repo.root())?)),
|
||||
None => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
/// The repository of `path`, free to execute: the host runs every agent command that
|
||||
/// reaches a repository only in a trusted project.
|
||||
fn discover(path: &Path) -> IdeResult<Option<Repo>> {
|
||||
@@ -157,9 +179,38 @@ pub(crate) fn head_commit(cwd: &Path) -> IdeResult<Option<String>> {
|
||||
}
|
||||
}
|
||||
|
||||
/// `git worktree add -b agent/<slug> <dir>/<slug> <base>`.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn create(project_root: &Path, worktrees_dir: &Path, title: &str, base: Option<&str>) -> IdeResult<Created> {
|
||||
create_for_task(project_root, worktrees_dir, "", title, base)
|
||||
}
|
||||
|
||||
/// `git worktree add -b agent/<slug> <dir>/<slug> <base>`.
|
||||
/// Records an ownership marker in the linked worktree's private `git_dir` and preserves any
|
||||
/// project-relative subdirectory inside `project_root` when `project_root` is below `repo.root()`.
|
||||
pub(crate) fn create_for_task(
|
||||
project_root: &Path,
|
||||
worktrees_dir: &Path,
|
||||
task_id: &str,
|
||||
title: &str,
|
||||
base: Option<&str>,
|
||||
) -> IdeResult<Created> {
|
||||
let repo = repo_at(project_root)?;
|
||||
let canon_repo = dunce::canonicalize(repo.root())?;
|
||||
let canon_proj = dunce::canonicalize(project_root)?;
|
||||
let rel_subdir = if canon_proj != canon_repo {
|
||||
canon_proj
|
||||
.strip_prefix(&canon_repo)
|
||||
.map_err(|_| {
|
||||
IdeError::invalid(format!(
|
||||
"{} is outside git repository {}",
|
||||
canon_proj.display(),
|
||||
canon_repo.display()
|
||||
))
|
||||
})?
|
||||
.to_path_buf()
|
||||
} else {
|
||||
PathBuf::new()
|
||||
};
|
||||
let (base, base_commit) = match base.map(str::trim).filter(|b| !b.is_empty()) {
|
||||
Some(b) => {
|
||||
let commit =
|
||||
@@ -177,7 +228,125 @@ pub(crate) fn create(project_root: &Path, worktrees_dir: &Path, title: &str, bas
|
||||
let path = worktrees_dir.join(&slug);
|
||||
let branch = format!("agent/{slug}");
|
||||
repo.add_worktree(&path, &base_commit, Some(&branch))?;
|
||||
Ok(Created { path, branch, base, base_commit })
|
||||
|
||||
let canon_wt = match dunce::canonicalize(&path) {
|
||||
Ok(p) => p,
|
||||
Err(e) => {
|
||||
let _ = repo.remove_worktree(&path, false);
|
||||
return Err(e.into());
|
||||
}
|
||||
};
|
||||
let wt_repo = match repo_at(&canon_wt) {
|
||||
Ok(r) => r,
|
||||
Err(e) => {
|
||||
let _ = repo.remove_worktree(&path, false);
|
||||
return Err(e);
|
||||
}
|
||||
};
|
||||
let [git_dir, common_dir] = match wt_repo.metadata_dirs() {
|
||||
Ok(dirs) => dirs,
|
||||
Err(e) => {
|
||||
let _ = repo.remove_worktree(&path, false);
|
||||
return Err(e);
|
||||
}
|
||||
};
|
||||
if dunce::canonicalize(&git_dir).ok() == dunce::canonicalize(&common_dir).ok() {
|
||||
let _ = repo.remove_worktree(&path, false);
|
||||
return Err(IdeError::internal("linked worktree did not receive a separate git metadata directory"));
|
||||
}
|
||||
let marker = WorktreeOwnership {
|
||||
owner: OWNERSHIP_TAG.to_owned(),
|
||||
task_id: task_id.to_owned(),
|
||||
worktree_root: canon_wt.clone(),
|
||||
repo_root: canon_repo,
|
||||
};
|
||||
if let Err(e) = serde_json::to_vec_pretty(&marker)
|
||||
.map_err(|e| IdeError::internal(e.to_string()))
|
||||
.and_then(|bytes| ide_vfs::write_atomic(&git_dir.join(OWNERSHIP_MARKER), &bytes))
|
||||
{
|
||||
let _ = repo.remove_worktree(&path, false);
|
||||
return Err(e);
|
||||
}
|
||||
|
||||
let raw_cwd = if rel_subdir.as_os_str().is_empty() { canon_wt.clone() } else { canon_wt.join(&rel_subdir) };
|
||||
if !raw_cwd.is_dir() {
|
||||
let _ = repo.remove_worktree(&path, false);
|
||||
return Err(IdeError::invalid(format!(
|
||||
"project folder {} does not exist in base revision {}",
|
||||
rel_subdir.display(),
|
||||
base
|
||||
)));
|
||||
}
|
||||
let canon_cwd = match verify_confined_worktree_subdir(&canon_wt, &raw_cwd) {
|
||||
Ok(c) => c,
|
||||
Err(e) => {
|
||||
let _ = repo.remove_worktree(&path, false);
|
||||
return Err(e);
|
||||
}
|
||||
};
|
||||
Ok(Created { path, cwd: canon_cwd, branch, base, base_commit })
|
||||
}
|
||||
|
||||
fn verify_confined_worktree_subdir(canon_wt_root: &Path, target_cwd: &Path) -> IdeResult<PathBuf> {
|
||||
let canon_cwd = dunce::canonicalize(target_cwd)?;
|
||||
let real_wt = ide_core::real_path::resolve_real(canon_wt_root);
|
||||
let real_cwd = ide_core::real_path::resolve_real(target_cwd);
|
||||
if !canon_cwd.starts_with(canon_wt_root)
|
||||
|| !real_cwd.starts_with(&real_wt)
|
||||
|| ide_core::real_path::reaches_git_dir(&real_wt, &real_cwd)
|
||||
{
|
||||
return Err(IdeError::invalid(format!(
|
||||
"worktree working directory {} resolves outside worktree {}",
|
||||
target_cwd.display(),
|
||||
canon_wt_root.display()
|
||||
)));
|
||||
}
|
||||
Ok(canon_cwd)
|
||||
}
|
||||
|
||||
/// Canonicalizes `cwd` of an existing `Isolation::Worktree` task and verifies that it still
|
||||
/// resolves strictly inside its own worktree checkout root under `worktrees_dir` (preventing
|
||||
/// symlink escapes on reused sessions/turns).
|
||||
pub(crate) fn verify_confined_worktree_cwd(worktrees_dir: &Path, cwd: &Path) -> IdeResult<PathBuf> {
|
||||
let (wt_root, wt_base) = worktree_checkout_root(worktrees_dir, cwd);
|
||||
if !wt_root.starts_with(&wt_base) || wt_root == wt_base {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"worktree working directory {} is outside managed worktrees directory {}",
|
||||
cwd.display(),
|
||||
worktrees_dir.display()
|
||||
)));
|
||||
}
|
||||
let canon_wt_root = dunce::canonicalize(&wt_root)?;
|
||||
let canon_wt_dir = dunce::canonicalize(worktrees_dir)?;
|
||||
if !canon_wt_root.starts_with(&canon_wt_dir)
|
||||
|| canon_wt_root == canon_wt_dir
|
||||
|| canon_wt_root.parent() != Some(canon_wt_dir.as_path())
|
||||
{
|
||||
return Err(IdeError::invalid("worktree checkout root escaped managed worktrees directory"));
|
||||
}
|
||||
verify_confined_worktree_subdir(&canon_wt_root, cwd)
|
||||
}
|
||||
|
||||
fn worktree_checkout_root(worktrees_dir: &Path, path: &Path) -> (PathBuf, PathBuf) {
|
||||
if let Ok(rel) = path.strip_prefix(worktrees_dir)
|
||||
&& let Some(first) = rel.components().next()
|
||||
{
|
||||
return (worktrees_dir.join(first), worktrees_dir.to_path_buf());
|
||||
}
|
||||
if let Ok(canon_wt_dir) = dunce::canonicalize(worktrees_dir) {
|
||||
if let Ok(rel) = path.strip_prefix(&canon_wt_dir)
|
||||
&& let Some(first) = rel.components().next()
|
||||
{
|
||||
return (canon_wt_dir.join(first), canon_wt_dir);
|
||||
}
|
||||
if let Ok(canon_path) = dunce::canonicalize(path)
|
||||
&& let Ok(rel) = canon_path.strip_prefix(&canon_wt_dir)
|
||||
&& let Some(first) = rel.components().next()
|
||||
{
|
||||
return (canon_wt_dir.join(first), canon_wt_dir);
|
||||
}
|
||||
}
|
||||
(path.to_path_buf(), worktrees_dir.to_path_buf())
|
||||
}
|
||||
|
||||
/// `git worktree remove --force -- <path>`. When git no longer recognizes the
|
||||
@@ -186,19 +355,94 @@ pub(crate) fn create(project_root: &Path, worktrees_dir: &Path, title: &str, bas
|
||||
/// ours, so it is removed directly to keep the task deletable (a stale
|
||||
/// registration prunes later); anything else keeps git's error.
|
||||
pub(crate) fn remove(project_root: &Path, worktrees_dir: &Path, path: &Path) -> IdeResult<()> {
|
||||
let (target, wt_base) = worktree_checkout_root(worktrees_dir, path);
|
||||
let repo = repo_at(project_root)?;
|
||||
let err = match repo.remove_worktree(path, true) {
|
||||
let err = match repo.remove_worktree(&target, true) {
|
||||
Ok(()) => return Ok(()),
|
||||
Err(e) => e,
|
||||
};
|
||||
if !path.exists() {
|
||||
if !target.exists() {
|
||||
return Ok(());
|
||||
}
|
||||
if !path.starts_with(worktrees_dir) || path == worktrees_dir {
|
||||
if !target.starts_with(&wt_base) || target == wt_base {
|
||||
return Err(err);
|
||||
}
|
||||
retrying(REMOVE_ATTEMPTS, REMOVE_PAUSE, || std::fs::remove_dir_all(path))
|
||||
.map_err(|e| IdeError::internal(format!("{}: {e}", path.display())))
|
||||
retrying(REMOVE_ATTEMPTS, REMOVE_PAUSE, || std::fs::remove_dir_all(&target))
|
||||
.map_err(|e| IdeError::internal(format!("{}: {e}", target.display())))
|
||||
}
|
||||
|
||||
/// Safely removes an automation worktree ONLY after verifying its private `git_dir` ownership
|
||||
/// marker (`openidea-worktree.json`) matches `task_id` and `worktrees_dir`.
|
||||
///
|
||||
/// - When `require_clean` is `true` (zero-diff GC): verifies `HEAD == base_commit` and both the
|
||||
/// Git index (staged) and working tree (unstaged + untracked) are completely clean right before
|
||||
/// running **non-forced** `git worktree remove` (`force = false`). Returns `Ok(false)` without
|
||||
/// modifying disk if the worktree has any commits, staged changes, unstaged edits, or untracked
|
||||
/// files.
|
||||
/// - Never falls back to `remove_dir_all` on any ownership or Git error: any error keeps the
|
||||
/// checkout intact.
|
||||
pub(crate) fn remove_owned_automation_worktree(
|
||||
project_root: &Path,
|
||||
worktrees_dir: &Path,
|
||||
cwd: &Path,
|
||||
task_id: &str,
|
||||
base_commit: Option<&str>,
|
||||
require_clean: bool,
|
||||
) -> IdeResult<bool> {
|
||||
if !cwd.exists() || !worktrees_dir.exists() {
|
||||
return Ok(false);
|
||||
}
|
||||
let canon_worktrees = dunce::canonicalize(worktrees_dir)?;
|
||||
let canon_cwd = dunce::canonicalize(cwd)?;
|
||||
if !canon_cwd.starts_with(&canon_worktrees) || canon_cwd == canon_worktrees {
|
||||
return Err(IdeError::invalid("refusing to clean worktree outside managed worktrees directory"));
|
||||
}
|
||||
let main_repo = repo_at(project_root)?;
|
||||
let wt_repo = repo_at(&canon_cwd)?;
|
||||
let canon_wt_root = dunce::canonicalize(wt_repo.root())?;
|
||||
if !canon_wt_root.starts_with(&canon_worktrees)
|
||||
|| canon_wt_root == canon_worktrees
|
||||
|| canon_wt_root.parent() != Some(canon_worktrees.as_path())
|
||||
{
|
||||
return Err(IdeError::invalid("worktree root does not match managed worktrees directory"));
|
||||
}
|
||||
let [git_dir, wt_common] = wt_repo.metadata_dirs()?;
|
||||
let [_, main_common] = main_repo.metadata_dirs()?;
|
||||
let canon_git_dir = dunce::canonicalize(&git_dir)?;
|
||||
let canon_wt_common = dunce::canonicalize(&wt_common)?;
|
||||
let canon_main_common = dunce::canonicalize(&main_common)?;
|
||||
if canon_git_dir == canon_wt_common || canon_wt_common != canon_main_common {
|
||||
return Err(IdeError::invalid("target checkout is not a linked worktree of this repository"));
|
||||
}
|
||||
let marker_bytes = std::fs::read(canon_git_dir.join(OWNERSHIP_MARKER))
|
||||
.map_err(|_| IdeError::invalid("refusing to remove worktree without OpenIDEA ownership marker"))?;
|
||||
let marker: WorktreeOwnership = serde_json::from_slice(&marker_bytes)
|
||||
.map_err(|_| IdeError::invalid("corrupt OpenIDEA worktree ownership marker"))?;
|
||||
let marker_root = dunce::canonicalize(&marker.worktree_root).unwrap_or(marker.worktree_root);
|
||||
if marker.owner != OWNERSHIP_TAG || marker.task_id != task_id || marker_root != canon_wt_root {
|
||||
return Err(IdeError::invalid("worktree ownership marker does not match task"));
|
||||
}
|
||||
|
||||
if require_clean {
|
||||
let Some(base) = base_commit else {
|
||||
return Ok(false);
|
||||
};
|
||||
if wt_repo.head()?.1.as_deref() != Some(base) {
|
||||
return Ok(false);
|
||||
}
|
||||
// `status()` checks BOTH HEAD↔index (staged) and index↔worktree (unstaged + untracked).
|
||||
if !wt_repo.status()?.is_empty() {
|
||||
return Ok(false);
|
||||
}
|
||||
if !wt_repo.diff_with_worktree(base)?.is_empty() {
|
||||
return Ok(false);
|
||||
}
|
||||
main_repo.remove_worktree(&canon_wt_root, false)?;
|
||||
return Ok(true);
|
||||
}
|
||||
|
||||
main_repo.remove_worktree(&canon_wt_root, true)?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// On Windows a folder can't be deleted while a process still has a file in it open
|
||||
@@ -1944,4 +2188,130 @@ mod tests {
|
||||
changed.sort();
|
||||
assert_eq!(changed, ["edited", "new", "reverted"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn owned_worktree_cleanup_preserves_subproject_cwd_catches_staged_changes_and_verifies_ownership() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let repo = tmp.path().join("repo");
|
||||
let sub = repo.join("packages").join("subapp");
|
||||
std::fs::create_dir_all(&sub).unwrap();
|
||||
git(&repo, &["init", "-q", "-b", "main"]);
|
||||
git(&repo, &["config", "core.autocrlf", "false"]);
|
||||
std::fs::write(repo.join("root.txt"), "root\n").unwrap();
|
||||
std::fs::write(sub.join("index.ts"), "export const x = 1;\n").unwrap();
|
||||
git(&repo, &["add", "."]);
|
||||
git(&repo, &["commit", "-q", "-m", "init"]);
|
||||
|
||||
let wt_dir = tmp.path().join("wt");
|
||||
let created = create_for_task(&sub, &wt_dir, "task-1", "Sub Audit", None).unwrap();
|
||||
assert_eq!(
|
||||
dunce::canonicalize(&created.cwd).unwrap(),
|
||||
dunce::canonicalize(&created.path).unwrap().join("packages").join("subapp"),
|
||||
"project-relative cwd inside parent repo must be preserved inside worktree"
|
||||
);
|
||||
|
||||
// Wrong task_id is refused and keeps the checkout untouched.
|
||||
assert!(
|
||||
remove_owned_automation_worktree(
|
||||
&sub,
|
||||
&wt_dir,
|
||||
&created.cwd,
|
||||
"wrong-task",
|
||||
Some(&created.base_commit),
|
||||
true,
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
assert!(created.path.exists());
|
||||
|
||||
// Staged-only change (index differs from HEAD while working tree matches HEAD!) is NOT clean!
|
||||
std::fs::write(created.cwd.join("index.ts"), "export const x = 2;\n").unwrap();
|
||||
git(&created.path, &["add", "packages/subapp/index.ts"]);
|
||||
std::fs::write(created.cwd.join("index.ts"), "export const x = 1;\n").unwrap();
|
||||
let removed_staged =
|
||||
remove_owned_automation_worktree(&sub, &wt_dir, &created.cwd, "task-1", Some(&created.base_commit), true)
|
||||
.unwrap();
|
||||
assert!(!removed_staged, "staged-only index change must prevent zero-diff worktree GC");
|
||||
assert!(created.path.exists());
|
||||
|
||||
// Reset index back to HEAD -> zero-diff GC removes the worktree via non-forced `git worktree remove`.
|
||||
git(&created.path, &["reset", "-q", "HEAD", "--", "packages/subapp/index.ts"]);
|
||||
let removed_clean =
|
||||
remove_owned_automation_worktree(&sub, &wt_dir, &created.cwd, "task-1", Some(&created.base_commit), true)
|
||||
.unwrap();
|
||||
assert!(removed_clean);
|
||||
assert!(!created.path.exists());
|
||||
|
||||
// Foreign / manually created git worktree inside `wt_dir` without ownership marker is NEVER deleted.
|
||||
let manual_wt = wt_dir.join("foreign");
|
||||
git(&repo, &["worktree", "add", "-q", "-b", "manual-branch", manual_wt.to_str().unwrap(), "HEAD"]);
|
||||
assert!(
|
||||
remove_owned_automation_worktree(&repo, &wt_dir, &manual_wt, "task-2", Some(&created.base_commit), false,)
|
||||
.is_err()
|
||||
);
|
||||
assert!(manual_wt.exists(), "worktree without OpenIDEA ownership marker must never be deleted");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn symlinked_subproject_cwd_escaping_worktree_is_rejected_on_create_and_reuse() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let outside = tmp.path().join("outside");
|
||||
std::fs::create_dir_all(&outside).unwrap();
|
||||
std::fs::write(outside.join("secret.txt"), "nope\n").unwrap();
|
||||
|
||||
let repo = tmp.path().join("repo");
|
||||
let packages = repo.join("packages");
|
||||
std::fs::create_dir_all(&packages).unwrap();
|
||||
git(&repo, &["init", "-q", "-b", "main"]);
|
||||
git(&repo, &["config", "core.autocrlf", "false"]);
|
||||
|
||||
// 1a. Direct symlink pointing outside git is rejected immediately.
|
||||
let escape_link = packages.join("escape");
|
||||
std::os::unix::fs::symlink(&outside, &escape_link).unwrap();
|
||||
git(&repo, &["add", "."]);
|
||||
git(&repo, &["commit", "-q", "-m", "symlink escape"]);
|
||||
|
||||
let wt_dir = tmp.path().join("wt");
|
||||
assert!(create_for_task(&escape_link, &wt_dir, "task-escape-direct", "Escape", None).is_err());
|
||||
|
||||
// 1b. Committed symlink in `HEAD` (`packages/tricky -> ../../outside`) while the main
|
||||
// checkout temporarily has a real directory at `packages/tricky`: `git worktree add`
|
||||
// checks out `HEAD`'s symlink inside the worktree, and `verify_confined_worktree_subdir`
|
||||
// must catch the escape and clean up the worktree!
|
||||
let tricky = packages.join("tricky");
|
||||
std::os::unix::fs::symlink(&outside, &tricky).unwrap();
|
||||
git(&repo, &["add", "."]);
|
||||
git(&repo, &["commit", "-q", "-m", "committed tricky symlink"]);
|
||||
std::fs::remove_file(&tricky).unwrap();
|
||||
std::fs::create_dir_all(&tricky).unwrap();
|
||||
|
||||
let Err(err) = create_for_task(&tricky, &wt_dir, "task-escape-head", "Tricky", None) else {
|
||||
panic!("expected committed symlink escaping worktree root to be rejected");
|
||||
};
|
||||
assert!(
|
||||
err.to_string().contains("outside worktree") || err.to_string().contains("escapes worktree root"),
|
||||
"unexpected error for committed symlink cwd: {err}"
|
||||
);
|
||||
|
||||
// 2. Normal directory at creation time, later replaced with an escaping symlink before reuse,
|
||||
// must be rejected by `verify_confined_worktree_cwd`!
|
||||
let legit_sub = packages.join("legit");
|
||||
std::fs::create_dir_all(&legit_sub).unwrap();
|
||||
std::fs::write(legit_sub.join("ok.txt"), "ok\n").unwrap();
|
||||
git(&repo, &["add", "."]);
|
||||
git(&repo, &["commit", "-q", "-m", "legit sub"]);
|
||||
|
||||
let created = create_for_task(&legit_sub, &wt_dir, "task-reuse", "Legit", None).unwrap();
|
||||
let verified = super::verify_confined_worktree_cwd(&wt_dir, &created.cwd).unwrap();
|
||||
assert!(verified.starts_with(dunce::canonicalize(&created.path).unwrap()));
|
||||
|
||||
std::fs::remove_dir_all(&created.cwd).unwrap();
|
||||
std::os::unix::fs::symlink(&outside, &created.cwd).unwrap();
|
||||
let reuse_err = super::verify_confined_worktree_cwd(&wt_dir, &created.cwd).unwrap_err();
|
||||
assert!(
|
||||
reuse_err.to_string().contains("outside worktree") || reuse_err.to_string().contains("escapes"),
|
||||
"symlink swap on worktree reuse must be rejected: {reuse_err}"
|
||||
);
|
||||
}
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"version": 2,
|
||||
"plugins": {
|
||||
"evidence-plugin@evidence-mkt": [
|
||||
{
|
||||
"scope": "user",
|
||||
"installPath": "$HOME/.claude/plugins/cache/evidence-mkt/evidence-plugin/1.2.3",
|
||||
"version": "1.2.3",
|
||||
"installedAt": "2026-11-30T21:50:25.665Z",
|
||||
"lastUpdated": "2026-11-30T21:50:25.665Z",
|
||||
"gitCommitSha": "1111111111111111111111111111111111111111"
|
||||
},
|
||||
{
|
||||
"scope": "project",
|
||||
"projectPath": "$WORKSPACE",
|
||||
"installPath": "$HOME/.claude/plugins/cache/evidence-mkt/evidence-plugin/1.2.3",
|
||||
"version": "1.2.3",
|
||||
"installedAt": "2026-11-30T21:50:25.665Z",
|
||||
"lastUpdated": "2026-11-30T21:50:25.665Z",
|
||||
"gitCommitSha": "1111111111111111111111111111111111111111"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
[marketplaces.evidence-mkt]
|
||||
source_type = "local"
|
||||
source = "$HOME/.codex/.tmp/marketplaces/evidence-mkt"
|
||||
|
||||
[plugins."evidence-plugin@evidence-mkt"]
|
||||
enabled = false
|
||||
@@ -0,0 +1,19 @@
|
||||
// This file is managed automatically.
|
||||
{
|
||||
"installedPlugins": [
|
||||
{
|
||||
"name": "evidence-plugin",
|
||||
"marketplace": "evidence-mkt",
|
||||
"installed_at": "2026-11-30T21:50:25.665Z",
|
||||
"enabled": true,
|
||||
"version": "1.2.3",
|
||||
"cache_path": "$HOME/.copilot/installed-plugins/evidence-mkt/evidence-plugin",
|
||||
"source": {
|
||||
"source": "github",
|
||||
"repo": "acme/plugins",
|
||||
"sha": "1111111111111111111111111111111111111111",
|
||||
"path": "plugins/evidence-plugin"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"evidence-extension": {
|
||||
"overrides": [
|
||||
"$HOME/*",
|
||||
"!$WORKSPACE/*"
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -17,8 +17,8 @@ pub use launch_resources::process_launch_resources;
|
||||
pub use modules::record_module_build;
|
||||
pub use single::{
|
||||
SingleFileTarget, compile_file_plan, compile_file_plan_cancellable, find_javac, gradle_compile_file_plan,
|
||||
has_gradle_file_target, javac_step, module_classpath, module_classpath_without_build, module_classpaths,
|
||||
single_file_classpath, single_file_target,
|
||||
has_gradle_file_target, javac_step, maven_system_classpath, 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,
|
||||
@@ -986,7 +986,7 @@ fn maven_launch_projects<'a>(
|
||||
}
|
||||
projects.push(p);
|
||||
for dep in &p.dependencies {
|
||||
if !dep.resolved() || (dep.scope == "test" && (!test || p.pom != start.pom)) {
|
||||
if !dep.resolved() || dep.scope == "system" || (dep.scope == "test" && (!test || p.pom != start.pom)) {
|
||||
continue;
|
||||
}
|
||||
if let Some(upstream) = reactor.iter().find(|u| {
|
||||
|
||||
@@ -180,6 +180,30 @@ pub fn find_javac(env: &BTreeMap<String, String>) -> String {
|
||||
exe.to_owned()
|
||||
}
|
||||
|
||||
/// Existing system-scope dependencies of this module. Maven resolves these from
|
||||
/// their local files and does not pass them transitively to reactor dependents.
|
||||
pub fn maven_system_classpath(root: &Path, model: &BuildModel, module: &Path) -> Vec<PathBuf> {
|
||||
let Some(maven) = &model.maven else { return Vec::new() };
|
||||
let module = root.join(module);
|
||||
maven
|
||||
.projects
|
||||
.iter()
|
||||
.find(|p| root.join(&p.dir) == module)
|
||||
.into_iter()
|
||||
.flat_map(|p| &p.system_paths)
|
||||
.filter(|p| p.is_file())
|
||||
.cloned()
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn with_system_classpath(root: &Path, model: &BuildModel, module: &Path, classpath: String) -> String {
|
||||
let system = maven_system_classpath(root, model, module);
|
||||
if system.is_empty() {
|
||||
return classpath;
|
||||
}
|
||||
join_classpath(std::env::split_paths(&classpath).chain(system).map(|p| p.to_string_lossy().into_owned()))
|
||||
}
|
||||
|
||||
/// Dependency classpath of the module: existing reactor class directories plus
|
||||
/// `mvn dependency:build-classpath` (which resolves without compiling anything,
|
||||
/// so `-am` stays cheap). Entries are platform-separated (`;` on Windows).
|
||||
@@ -233,7 +257,7 @@ pub fn module_classpath_without_build(
|
||||
&& cached.version == CLASSPATH_CACHE_VERSION
|
||||
&& classpath_entries_exist(root, &cached.classpath)
|
||||
{
|
||||
return Ok(cached.classpath);
|
||||
return Ok(with_system_classpath(root, model, &target.module, cached.classpath));
|
||||
}
|
||||
classpath(root, model, &target, if test { "test" } else { "runtime" }, false, cancel)
|
||||
}
|
||||
@@ -270,7 +294,7 @@ pub fn module_classpaths(
|
||||
&& classpath_entries_exist(root, &cached.classpath)
|
||||
{
|
||||
if i == 0 {
|
||||
return Ok(cached.classpath);
|
||||
return Ok(with_system_classpath(root, model, &target.module, cached.classpath));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
@@ -298,7 +322,7 @@ pub fn module_classpaths(
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(classpaths.into_iter().next().unwrap())
|
||||
Ok(with_system_classpath(root, model, &modules[0], classpaths.into_iter().next().unwrap()))
|
||||
}
|
||||
|
||||
/// A module whose classpath the Maven probe resolves, with its cache key and file.
|
||||
@@ -346,7 +370,8 @@ fn classpath(
|
||||
compile_first: bool,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<String> {
|
||||
Ok(classpaths(root, model, &[target], scope, compile_first, cancel)?.pop().unwrap())
|
||||
let classpath = classpaths(root, model, &[target], scope, compile_first, cancel)?.pop().unwrap();
|
||||
Ok(with_system_classpath(root, model, &target.module, classpath))
|
||||
}
|
||||
|
||||
/// The classpath of each of `targets` (modules of one reactor) from one Maven probe.
|
||||
@@ -912,6 +937,64 @@ mod tests {
|
||||
assert!(args.lines().any(|a| a == "-Dmdep.includeScope=test"), "{args}");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn system_jars_augment_maven_javac_and_launch_classpaths() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(dir.path()).unwrap();
|
||||
write(
|
||||
&root,
|
||||
"pom.xml",
|
||||
r#"<project><groupId>demo</groupId><artifactId>parent</artifactId><version>1</version>
|
||||
<packaging>pom</packaging><modules><module>app</module></modules>
|
||||
<properties><lib.dir>src/main/resources/lib</lib.dir></properties></project>"#,
|
||||
);
|
||||
write(
|
||||
&root,
|
||||
"app/pom.xml",
|
||||
r#"<project><parent><groupId>demo</groupId><artifactId>parent</artifactId><version>1</version></parent>
|
||||
<artifactId>app</artifactId>
|
||||
<properties><lib.file>${lib.dir}/offline.jar</lib.file></properties>
|
||||
<dependencies>
|
||||
<dependency><groupId>local</groupId><artifactId>offline</artifactId><version>1</version>
|
||||
<scope>system</scope><systemPath>${pom.basedir}/${lib.file}</systemPath></dependency>
|
||||
<dependency><groupId>local</groupId><artifactId>late</artifactId><version>1</version>
|
||||
<scope>system</scope><systemPath>${project.basedir}/${lib.dir}/late.jar</systemPath></dependency>
|
||||
<dependency><groupId>local</groupId><artifactId>directory</artifactId><version>1</version>
|
||||
<scope>system</scope><systemPath>${project.basedir}/${lib.dir}</systemPath></dependency>
|
||||
</dependencies></project>"#,
|
||||
);
|
||||
let jars = "app/src/main/resources/lib";
|
||||
write(&root, &format!("{jars}/offline.jar"), "");
|
||||
write(&root, "app/src/main/java/demo/Main.java", "class Main {}");
|
||||
// The scope-filtered Maven classpath can contain no dependencies.
|
||||
write(&root, "mvnw", "#!/bin/sh\nmkdir -p app/target\n: > app/target/ide-compile-cp.txt\n");
|
||||
fs::set_permissions(root.join("mvnw"), fs::Permissions::from_mode(0o755)).unwrap();
|
||||
|
||||
let cache = root.join("cache");
|
||||
let model = crate::load(&root, &cache, None);
|
||||
let module = root.join("app");
|
||||
let file = module.join("src/main/java/demo/Main.java");
|
||||
let jar = root.join(jars).join("offline.jar");
|
||||
let plan = compile_file_plan(&root, &model, &file).unwrap();
|
||||
assert!(plan.steps[0].args.windows(2).any(|arg| arg[0] == "-cp" && Path::new(&arg[1]) == jar));
|
||||
let cancel = CancellationToken::new();
|
||||
let cp = module_classpath(&root, &model, &module, false, None, &cache, &cancel).unwrap();
|
||||
let paths: Vec<_> = std::env::split_paths(&cp).collect();
|
||||
assert_eq!(paths, [module.join("target/classes"), jar.clone()]);
|
||||
assert!(maven_system_classpath(&root, &model, &root).is_empty());
|
||||
|
||||
// Adding a previously absent jar or deleting an old one updates a no-build launch.
|
||||
fs::remove_file(jar).unwrap();
|
||||
write(&root, &format!("{jars}/late.jar"), "");
|
||||
fs::remove_file(root.join("mvnw")).unwrap();
|
||||
let cp = module_classpath_without_build(&root, &model, &module, false, &cache, &cancel).unwrap();
|
||||
let paths: Vec<_> = std::env::split_paths(&cp).collect();
|
||||
assert_eq!(paths, [module.join("target/classes"), root.join(jars).join("late.jar")]);
|
||||
}
|
||||
|
||||
/// Modules launched together resolve their classpaths in one Maven probe and leave
|
||||
/// the others' cached; a probe another module breaks still resolves the first one.
|
||||
#[cfg(unix)]
|
||||
|
||||
@@ -234,9 +234,7 @@ fn members(r: &mut Bytes, pool: &Pool, refs: &mut BTreeSet<String>) -> Option<Ve
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// Parses a class file; `None` when it isn't a well-formed one.
|
||||
pub fn parse(data: &[u8]) -> Option<ClassFile> {
|
||||
let mut r = Bytes { data, pos: 0 };
|
||||
fn read_pool(r: &mut Bytes<'_>) -> Option<Pool> {
|
||||
if r.u4()? != 0xCAFE_BABE {
|
||||
return None;
|
||||
}
|
||||
@@ -283,11 +281,28 @@ pub fn parse(data: &[u8]) -> Option<ClassFile> {
|
||||
entries.push(entry);
|
||||
i += 1;
|
||||
if wide {
|
||||
if i == count {
|
||||
return None;
|
||||
}
|
||||
entries.push(Entry::Empty);
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
let pool = Pool(entries);
|
||||
Some(Pool(entries))
|
||||
}
|
||||
|
||||
/// Reads the internal class name (e.g. `com/acme/Order$Line`) from `this_class`.
|
||||
pub fn class_file_name(data: &[u8]) -> Option<String> {
|
||||
let mut r = Bytes { data, pos: 0 };
|
||||
let pool = read_pool(&mut r)?;
|
||||
r.u2()?; // access_flags
|
||||
Some(pool.class(r.u2()?)?.to_owned())
|
||||
}
|
||||
|
||||
/// Parses a class file; `None` when it isn't a well-formed one.
|
||||
pub fn parse(data: &[u8]) -> Option<ClassFile> {
|
||||
let mut r = Bytes { data, pos: 0 };
|
||||
let pool = read_pool(&mut r)?;
|
||||
let mut refs = BTreeSet::new();
|
||||
for entry in &pool.0 {
|
||||
match entry {
|
||||
|
||||
@@ -22,7 +22,7 @@ mod incremental;
|
||||
mod javac;
|
||||
mod model;
|
||||
|
||||
pub use classfile::ClassFile;
|
||||
pub use classfile::{ClassFile, class_file_name};
|
||||
pub use javac::{JavacPool, Reply, ServerKey};
|
||||
|
||||
use incremental::{ClassRecord, SetStamp, SetState};
|
||||
|
||||
@@ -69,6 +69,9 @@ pub struct MavenProject {
|
||||
pub aggregated: bool,
|
||||
pub plugins: Vec<MavenPlugin>,
|
||||
pub dependencies: Vec<MavenDependency>,
|
||||
/// Local classpath entries from the POM. The synced dependency tree has coordinates only.
|
||||
#[serde(skip)]
|
||||
pub system_paths: Vec<PathBuf>,
|
||||
/// Profile ids declared in this POM.
|
||||
pub profiles: Vec<String>,
|
||||
/// Java feature version the project compiles for (`maven.compiler.release`, `java.version`…).
|
||||
@@ -176,6 +179,7 @@ struct RawDep {
|
||||
kind: Option<String>,
|
||||
classifier: Option<String>,
|
||||
scope: Option<String>,
|
||||
system_path: Option<String>,
|
||||
optional: bool,
|
||||
}
|
||||
|
||||
@@ -248,6 +252,7 @@ fn read_dep(e: &Element) -> Option<RawDep> {
|
||||
kind: e.text_of("type"),
|
||||
classifier: e.text_of("classifier"),
|
||||
scope: e.text_of("scope"),
|
||||
system_path: e.text_of("systemPath"),
|
||||
optional: e.text_of("optional").is_some_and(|o| o == "true"),
|
||||
})
|
||||
}
|
||||
@@ -1519,7 +1524,13 @@ pub fn load_with_linked_jdk(
|
||||
let packaging = i(pom.packaging.as_deref().unwrap_or("jar"));
|
||||
let managed: HashMap<String, &RawDep> = ctx.managed.iter().map(|m| (m.key(), m)).collect();
|
||||
let managed_version = |d: &RawDep| managed.get(&d.key()).and_then(|m| m.version.clone());
|
||||
let managed_scope = |d: &RawDep| managed.get(&d.key()).and_then(|m| m.scope.clone());
|
||||
let scope = |d: &RawDep| {
|
||||
d.scope
|
||||
.as_deref()
|
||||
.or_else(|| managed.get(&d.key()).and_then(|m| m.scope.as_deref()))
|
||||
.map(i)
|
||||
.unwrap_or_else(|| "compile".into())
|
||||
};
|
||||
let dependencies = ctx
|
||||
.deps
|
||||
.iter()
|
||||
@@ -1529,11 +1540,26 @@ pub fn load_with_linked_jdk(
|
||||
version: d.version.clone().or_else(|| managed_version(d)).map(|v| i(&v)),
|
||||
kind: d.kind.clone().unwrap_or_else(|| "jar".into()),
|
||||
classifier: d.classifier.clone(),
|
||||
scope: d.scope.clone().or_else(|| managed_scope(d)).unwrap_or_else(|| "compile".into()),
|
||||
scope: scope(d),
|
||||
optional: d.optional,
|
||||
..MavenDependency::default()
|
||||
})
|
||||
.collect();
|
||||
let system_paths = ctx
|
||||
.deps
|
||||
.iter()
|
||||
.filter(|d| scope(d) == "system")
|
||||
.filter_map(|d| {
|
||||
let path = d
|
||||
.system_path
|
||||
.as_deref()
|
||||
.or_else(|| managed.get(&d.key()).and_then(|m| m.system_path.as_deref()))?;
|
||||
let path = i(path);
|
||||
// Rebuilt from its components: `${pom.basedir}/lib/x.jar` on Windows mixes `\\` and `/`.
|
||||
(!path.contains("${") && Path::new(&path).is_absolute())
|
||||
.then(|| Path::new(&path).components().collect::<PathBuf>())
|
||||
})
|
||||
.collect();
|
||||
|
||||
let mut plugins: Vec<RawPlugin> = ctx.plugins.clone();
|
||||
for a in lifecycle_plugins(&packaging) {
|
||||
@@ -1592,6 +1618,7 @@ pub fn load_with_linked_jdk(
|
||||
aggregated,
|
||||
plugins,
|
||||
dependencies,
|
||||
system_paths,
|
||||
profiles: ctx.profiles.iter().map(|(id, _)| id.clone()).collect(),
|
||||
java_version: jv,
|
||||
command: wrapper(&canonical_root, &dir_canon),
|
||||
|
||||
@@ -27,6 +27,10 @@ pub enum McpUiRequest {
|
||||
subject: String,
|
||||
project: String,
|
||||
detail: Option<String>,
|
||||
/// The project is served without a window: the request shows in another project's window,
|
||||
/// which names it and keeps the keyboard focus where it is.
|
||||
#[serde(default)]
|
||||
background: bool,
|
||||
},
|
||||
OpenFile {
|
||||
path: crate::IpcPath,
|
||||
@@ -95,6 +99,8 @@ pub enum IdeEvent {
|
||||
WindowGroupsChanged,
|
||||
/// A project was loaded or unloaded for the MCP server without a window of its own.
|
||||
McpBackgroundProjectsChanged,
|
||||
/// Agent automations, run history, or session schedules changed on the host.
|
||||
AutomationsChanged,
|
||||
/// A window entered or left full screen, itself or as a member of a full-screen window group.
|
||||
WindowFullscreenChanged,
|
||||
/// This remote window's connection ended or another window took over the session.
|
||||
|
||||
@@ -63,13 +63,30 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn a_burst_of_calls_runs_once_after_the_delay() {
|
||||
// Timing-based: a loaded CI machine can oversleep, so each check allows for that.
|
||||
let delay = Duration::from_millis(500);
|
||||
let (mut last, mut widest_gap) = (None::<Instant>, Duration::ZERO);
|
||||
for _ in 0..5 {
|
||||
debounce(&DUE, Duration::from_millis(100), count);
|
||||
debounce(&DUE, delay, count);
|
||||
let now = Instant::now();
|
||||
widest_gap = widest_gap.max(last.map_or(Duration::ZERO, |l| now - l));
|
||||
last = Some(now);
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
assert_eq!(RUNS.load(SeqCst), 0);
|
||||
std::thread::sleep(Duration::from_millis(400));
|
||||
assert_eq!(RUNS.load(SeqCst), 1);
|
||||
if last.unwrap().elapsed() < delay {
|
||||
assert_eq!(RUNS.load(SeqCst), 0, "ran before the delay passed");
|
||||
}
|
||||
let deadline = Instant::now() + Duration::from_secs(10);
|
||||
while RUNS.load(SeqCst) == 0 && Instant::now() < deadline {
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
// A second run would come within another delay.
|
||||
std::thread::sleep(delay);
|
||||
if widest_gap < delay {
|
||||
assert_eq!(RUNS.load(SeqCst), 1);
|
||||
} else {
|
||||
assert!(RUNS.load(SeqCst) >= 1);
|
||||
}
|
||||
release_free_pages_soon();
|
||||
}
|
||||
}
|
||||
@@ -83,6 +83,24 @@ pub fn own_group(cmd: &mut Command) -> &mut Command {
|
||||
cmd
|
||||
}
|
||||
|
||||
/// Starts the child as the leader of a session of its own on Unix. Like [`own_group`] it leads
|
||||
/// its process group, so [`kill_tree`] and [`terminate_tree`] reach what it starts; unlike it,
|
||||
/// the child has no controlling terminal, so a tool that would ask on `/dev/tty` (and be
|
||||
/// stopped there as a background job when the app was started from a shell) falls back to
|
||||
/// its pipes. Use it in place of `own_group`: a group leader cannot start a session. A no-op
|
||||
/// elsewhere.
|
||||
pub fn own_session(cmd: &mut Command) -> &mut Command {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::process::CommandExt;
|
||||
// SAFETY: `setsid` is async-signal-safe and touches none of the parent's memory.
|
||||
unsafe {
|
||||
cmd.pre_exec(|| if libc::setsid() == -1 { Err(std::io::Error::last_os_error()) } else { Ok(()) });
|
||||
}
|
||||
}
|
||||
cmd
|
||||
}
|
||||
|
||||
/// Kills the child and everything it started, then reaps it.
|
||||
///
|
||||
/// - Unix: `SIGKILL` to its process group, so spawn it with [`own_group`].
|
||||
@@ -622,6 +640,30 @@ pub fn host_vars_in(dir: &Path) -> impl Iterator<Item = (OsString, OsString)> {
|
||||
apply_changes(std::env::vars_os().collect(), &child_env_changes(Some(dir))).into_iter()
|
||||
}
|
||||
|
||||
/// Whether `(key, value)` can go into a Windows environment block (`KEY=VALUE\0`
|
||||
/// entries, then a final `\0`). `CreateProcessW` / `NtCreateUserProcess` returns
|
||||
/// `ERROR_INVALID_PARAMETER` (os error 87) when an entry has an empty name or an
|
||||
/// interior NUL. That happens when a `REG_MULTI_SZ` user environment value is
|
||||
/// loaded into the process or re-read from the registry (#6806): the extra NUL
|
||||
/// is treated as an entry separator and leaves a fragment with no `=`.
|
||||
pub fn is_spawnable_env_pair(key: &OsStr, value: &OsStr) -> bool {
|
||||
!key.is_empty() && !contains_ascii(key, 0) && !contains_ascii(key, b'=') && !contains_ascii(value, 0)
|
||||
}
|
||||
|
||||
fn contains_ascii(s: &OsStr, byte: u8) -> bool {
|
||||
s.as_encoded_bytes().contains(&byte)
|
||||
}
|
||||
|
||||
/// [`host_vars`] without pairs that a Windows PTY spawn would reject.
|
||||
pub fn spawnable_host_vars() -> impl Iterator<Item = (OsString, OsString)> {
|
||||
host_vars().filter(|(k, v)| is_spawnable_env_pair(k, v))
|
||||
}
|
||||
|
||||
/// [`host_vars_in`] without pairs that a Windows PTY spawn would reject.
|
||||
pub fn spawnable_host_vars_in(dir: &Path) -> impl Iterator<Item = (OsString, OsString)> {
|
||||
host_vars_in(dir).filter(|(k, v)| is_spawnable_env_pair(k, v))
|
||||
}
|
||||
|
||||
/// [`std::env::var_os`] as a child should see it (see [`host_env`]), the login shell's value
|
||||
/// included when this process lacks the variable.
|
||||
pub fn host_var_os(key: impl AsRef<OsStr>) -> Option<OsString> {
|
||||
@@ -946,6 +988,28 @@ fn append_path_entries(path: &OsStr, extra: &OsStr) -> OsString {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn own_session_leaves_the_controlling_terminal_behind() {
|
||||
// `ps` prints `?` (Linux) or `??` (macOS) for a process without a controlling terminal.
|
||||
let mut cmd = Command::new("sh");
|
||||
cmd.args(["-c", "ps -o tty= -p $$"]);
|
||||
let out = own_session(&mut cmd).output().unwrap();
|
||||
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
|
||||
assert!(String::from_utf8_lossy(&out.stdout).trim().chars().all(|c| c == '?'), "{:?}", out.stdout);
|
||||
// Without a terminal (CI) the line above holds anyway: the child must lead a session
|
||||
// of its own, which only `setsid` makes it.
|
||||
let mut cmd = Command::new("sleep");
|
||||
cmd.arg("5");
|
||||
let mut child = own_session(&mut cmd).spawn().unwrap();
|
||||
let pid = libc::pid_t::try_from(child.id()).unwrap();
|
||||
// SAFETY: plain syscall on a child not reaped yet.
|
||||
let session = unsafe { libc::getsid(pid) };
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
assert_eq!(session, pid, "the child leads its own session");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn process_alive_tells_live_from_dead_pids() {
|
||||
assert!(process_alive(std::process::id()));
|
||||
@@ -1240,6 +1304,35 @@ mod tests {
|
||||
assert!(host_vars_in(root).all(|(k, _)| k != "OPENIDEA_PROJECT_VAR"));
|
||||
}
|
||||
|
||||
fn os_from_bytes(bytes: &[u8]) -> OsString {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::ffi::OsStringExt;
|
||||
OsString::from_vec(bytes.to_vec())
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::os::windows::ffi::OsStringExt;
|
||||
OsString::from_wide(&bytes.iter().copied().map(u16::from).collect::<Vec<_>>())
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spawnable_env_pairs_reject_empty_keys_equals_and_interior_nuls() {
|
||||
let ok_key = OsString::from("PATH");
|
||||
let ok_val = OsString::from("/bin");
|
||||
assert!(is_spawnable_env_pair(&ok_key, &ok_val));
|
||||
assert!(!is_spawnable_env_pair(OsStr::new(""), &ok_val));
|
||||
assert!(!is_spawnable_env_pair(OsStr::new("FOO=BAR"), &ok_val));
|
||||
// A REG_MULTI_SZ value's interior NUL would split the environment block,
|
||||
// leaving a fragment with no `=` (#6806). An empty name is also rejected.
|
||||
assert!(!is_spawnable_env_pair(&os_from_bytes(b""), &os_from_bytes(b"132786")));
|
||||
assert!(!is_spawnable_env_pair(&ok_key, &os_from_bytes(b"1788051509\x00132786")));
|
||||
assert!(!is_spawnable_env_pair(&os_from_bytes(b"132786\x00"), &ok_val));
|
||||
assert!(spawnable_host_vars().all(|(k, v)| is_spawnable_env_pair(&k, &v)));
|
||||
assert!(spawnable_host_vars().any(|(k, _)| k == "PATH" || k == "Path"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn changes_apply_in_order() {
|
||||
let vars = apply_changes(
|
||||
|
||||
@@ -5,6 +5,29 @@ use std::path::{Component, Path, PathBuf};
|
||||
|
||||
pub const SEARCH_DEPTH: usize = 3;
|
||||
|
||||
/// Folders that hold dependencies or build output rather than the project's own builds: hidden
|
||||
/// folders (`.build`, `.git`), package checkouts (`node_modules`, `SourcePackages`, `Pods`,
|
||||
/// `Carthage`) and build products (`target`, `build`, `DerivedData`, …).
|
||||
pub fn is_skipped_dir(name: &str) -> bool {
|
||||
name.starts_with('.')
|
||||
|| matches!(
|
||||
name,
|
||||
"node_modules"
|
||||
| "target"
|
||||
| "build"
|
||||
| "dist"
|
||||
| "vendor"
|
||||
| "out"
|
||||
| "bin"
|
||||
| "obj"
|
||||
| "venv"
|
||||
| "SourcePackages"
|
||||
| "Pods"
|
||||
| "Carthage"
|
||||
| "DerivedData"
|
||||
)
|
||||
}
|
||||
|
||||
pub fn children(dir: &Path) -> Vec<PathBuf> {
|
||||
let Ok(entries) = std::fs::read_dir(dir) else { return Vec::new() };
|
||||
let mut dirs: Vec<_> = entries
|
||||
@@ -13,13 +36,7 @@ pub fn children(dir: &Path) -> Vec<PathBuf> {
|
||||
if !entry.file_type().is_ok_and(|kind| kind.is_dir()) {
|
||||
return false;
|
||||
}
|
||||
let name = entry.file_name();
|
||||
let name = name.to_string_lossy();
|
||||
!name.starts_with('.')
|
||||
&& !matches!(
|
||||
name.as_ref(),
|
||||
"node_modules" | "target" | "build" | "dist" | "vendor" | "out" | "bin" | "obj" | "venv"
|
||||
)
|
||||
!is_skipped_dir(&entry.file_name().to_string_lossy())
|
||||
})
|
||||
.map(|entry| entry.path())
|
||||
.collect();
|
||||
|
||||
@@ -203,6 +203,9 @@ pub enum RunTargetKind {
|
||||
Docker,
|
||||
/// A new container of a Compose service (`docker compose run --rm`).
|
||||
Compose,
|
||||
/// A WSL distribution on this Windows machine (`wsl.exe -d <distro>`), the project read
|
||||
/// through `/mnt/<drive>`.
|
||||
Wsl,
|
||||
}
|
||||
|
||||
/// Build, Execution, Deployment › Run Targets: run configurations on another machine
|
||||
@@ -215,7 +218,8 @@ pub struct RunTarget {
|
||||
pub name: String,
|
||||
/// [`SshConfiguration::id`] (SSH).
|
||||
pub ssh_config: String,
|
||||
/// Remote folder the project is synchronised to and run from (SSH).
|
||||
/// Remote folder the project is synchronised to and run from (SSH); the project's Linux
|
||||
/// path, empty = its `/mnt/<drive>` path (WSL).
|
||||
pub project_root: String,
|
||||
/// Upload changed project files before each run (SSH).
|
||||
pub sync_before_run: bool,
|
||||
@@ -241,6 +245,8 @@ pub struct RunTarget {
|
||||
pub run_options: String,
|
||||
/// Run as the image's user instead of the project folder's owner (Linux).
|
||||
pub image_user: bool,
|
||||
/// Distribution name, as `wsl.exe -l -q` lists it (WSL).
|
||||
pub distro: String,
|
||||
}
|
||||
|
||||
/// A plugin-owned argv wrapper for project runs (API 1.4).
|
||||
|
||||
@@ -170,6 +170,15 @@ pub struct AgentSettings {
|
||||
#[serde(deserialize_with = "or_default")]
|
||||
#[specta(type = AgentMemorySettings)]
|
||||
pub memory: AgentMemorySettings,
|
||||
/// Agent plugin bundle policies (`[agents.plugins]`): registered marketplaces and non-sensitive
|
||||
/// config. Enablement lives in each harness's native config; capability consent is stored per machine.
|
||||
#[serde(deserialize_with = "or_default")]
|
||||
#[specta(type = AgentPluginSettings)]
|
||||
pub plugins: AgentPluginSettings,
|
||||
/// Scheduled agent automations and headless scheduler host policies (`[agents.automations]`).
|
||||
#[serde(deserialize_with = "or_default")]
|
||||
#[specta(type = AgentAutomationSettings)]
|
||||
pub automations: AgentAutomationSettings,
|
||||
}
|
||||
|
||||
impl Default for AgentSettings {
|
||||
@@ -202,6 +211,8 @@ impl Default for AgentSettings {
|
||||
mcp_servers: BTreeMap::new(),
|
||||
skills: BTreeMap::new(),
|
||||
memory: AgentMemorySettings::default(),
|
||||
plugins: AgentPluginSettings::default(),
|
||||
automations: AgentAutomationSettings::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -358,6 +369,96 @@ pub struct AgentMemorySettings {
|
||||
pub entries: BTreeMap<String, AgentMemoryEntryPolicy>,
|
||||
}
|
||||
|
||||
/// One agent plugin bundle's policy in Settings › Agents › Plugins
|
||||
/// (`[agents.plugins.entries."<harness>:<plugin>@<marketplace>"]`).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct AgentPluginEntryPolicy {
|
||||
/// Non-sensitive `userConfig` / `variables` key-value pairs; sensitive values live in OS Keychain.
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub config: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
/// Agent plugin bundle settings (`[agents.plugins]`).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct AgentPluginSettings {
|
||||
/// Registered plugin marketplaces (`owner/repo[#ref]`, GitHub URL, or local directory/manifest path).
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub marketplaces: Vec<String>,
|
||||
/// Per-plugin non-sensitive native option hints, keyed by `<harness>:<plugin>@<marketplace>`.
|
||||
#[serde(deserialize_with = "or_default", skip_serializing_if = "BTreeMap::is_empty")]
|
||||
#[specta(type = BTreeMap<String, AgentPluginEntryPolicy>)]
|
||||
pub entries: BTreeMap<String, AgentPluginEntryPolicy>,
|
||||
}
|
||||
|
||||
/// When OpenIDEA holds an OS idle-sleep assertion during active automation turns.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum AutomationPreventSleep {
|
||||
/// Prevent idle sleep while plugged into AC power.
|
||||
#[default]
|
||||
Ac,
|
||||
/// Prevent idle sleep whenever an automated turn is running.
|
||||
Always,
|
||||
/// Never hold an idle-sleep assertion.
|
||||
Never,
|
||||
}
|
||||
|
||||
/// What the scheduler does when one or more scheduled occurrences fell due while asleep or offline.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum AutomationMisfirePolicy {
|
||||
/// Coalesce all missed occurrences into at most one catch-up run once awake and online.
|
||||
#[default]
|
||||
RunOnce,
|
||||
/// Skip missed occurrences and advance to the next future slot.
|
||||
Skip,
|
||||
}
|
||||
|
||||
/// Agent automation and headless scheduler settings (`[agents.automations]`).
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct AgentAutomationSettings {
|
||||
/// Automatically register the headless login/boot scheduler service while at least one
|
||||
/// automation is enabled, and unregister it when none remain enabled.
|
||||
pub auto_start_service: bool,
|
||||
/// Keep the local OpenIDEA host alive in the background when windows close while local
|
||||
/// automations are enabled.
|
||||
pub keep_alive_in_background: bool,
|
||||
/// Prevent system idle sleep while an automated turn is running.
|
||||
#[serde(deserialize_with = "or_default")]
|
||||
#[specta(type = AutomationPreventSleep)]
|
||||
pub prevent_sleep: AutomationPreventSleep,
|
||||
/// Default policy for scheduled occurrences missed during sleep, offline downtime, or reboot.
|
||||
#[serde(deserialize_with = "or_default")]
|
||||
#[specta(type = AutomationMisfirePolicy)]
|
||||
pub misfire_policy: AutomationMisfirePolicy,
|
||||
/// Keep `openidea-server --daemon` alive across disconnects while the remote host has
|
||||
/// enabled scheduled automations.
|
||||
pub keep_remote_daemon_alive: bool,
|
||||
/// Automatically remove temporary automation worktrees when a run finishes with zero diff
|
||||
/// and zero commits.
|
||||
pub auto_clean_worktrees: bool,
|
||||
/// Maximum retained non-clean automation worktrees per automation before pruning oldest
|
||||
/// finished ones.
|
||||
pub max_dirty_worktrees: u32,
|
||||
}
|
||||
|
||||
impl Default for AgentAutomationSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
auto_start_service: false,
|
||||
keep_alive_in_background: true,
|
||||
prevent_sleep: AutomationPreventSleep::Ac,
|
||||
misfire_policy: AutomationMisfirePolicy::RunOnce,
|
||||
keep_remote_daemon_alive: true,
|
||||
auto_clean_worktrees: true,
|
||||
max_dirty_worktrees: 5,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A hand-edited value these settings don't know reads as the default, rather than
|
||||
/// failing the whole settings file.
|
||||
fn or_default<'de, D, T>(d: D) -> Result<T, D::Error>
|
||||
@@ -1509,6 +1610,9 @@ pub struct MarkdownSettings {
|
||||
pub preview_layout: MarkdownPreviewLayout,
|
||||
/// Preview (and notebook Markdown cell) font size in px; unset follows the editor font size.
|
||||
pub preview_font_size: Option<u32>,
|
||||
/// Whether `.mdx` previews ask before running JSX components/imports, run automatically in
|
||||
/// trusted projects, or stay in static safe mode.
|
||||
pub mdx_execution: MdxExecutionPolicy,
|
||||
/// "Detect commands that can be run right from Markdown files": gutter run icons on
|
||||
/// shell code blocks and on command lines in code blocks.
|
||||
pub run_commands: bool,
|
||||
@@ -1521,12 +1625,22 @@ impl Default for MarkdownSettings {
|
||||
Self {
|
||||
preview_layout: MarkdownPreviewLayout::default(),
|
||||
preview_font_size: None,
|
||||
mdx_execution: MdxExecutionPolicy::default(),
|
||||
run_commands: true,
|
||||
command_directory: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum MdxExecutionPolicy {
|
||||
#[default]
|
||||
Ask,
|
||||
Trusted,
|
||||
Off,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum MarkdownPreviewLayout {
|
||||
|
||||
@@ -27,6 +27,35 @@ pub struct VcsSettings {
|
||||
pub mappings: VcsMappings,
|
||||
/// Settings › Version Control › GitHub: per-project GitHub CLI account selection.
|
||||
pub github: GithubSettings,
|
||||
/// Settings › Version Control › Subversion.
|
||||
pub svn: SvnSettings,
|
||||
}
|
||||
|
||||
/// Settings › Version Control › Subversion (`vcs.svn`).
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct SvnSettings {
|
||||
/// Path to the svn executable; empty = auto-detect.
|
||||
pub executable: String,
|
||||
/// Run svn as if in a terminal: its password, passphrase and certificate prompts open
|
||||
/// dialogs. Off, svn runs with `--non-interactive` and a rejected login asks once.
|
||||
pub interactive: bool,
|
||||
/// Pass `--config-dir config_dir` to every svn command.
|
||||
pub use_custom_config_dir: bool,
|
||||
pub config_dir: String,
|
||||
}
|
||||
|
||||
impl Default for SvnSettings {
|
||||
/// Interactive except on Windows: svn there asks on the console, which an IDE's child
|
||||
/// process has hidden, so a prompt could not be answered (not verified on Windows yet).
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
executable: String::new(),
|
||||
interactive: !cfg!(windows),
|
||||
use_custom_config_dir: false,
|
||||
config_dir: String::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Settings › Version Control › GitHub (`vcs.github`).
|
||||
@@ -80,6 +109,7 @@ impl Default for VcsSettings {
|
||||
issue_navigation: Vec::new(),
|
||||
mappings: VcsMappings::default(),
|
||||
github: GithubSettings::default(),
|
||||
svn: SvnSettings::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -530,6 +560,7 @@ pub struct DebuggerSettings {
|
||||
/// Java: whether to reload changed classes into running debug sessions after compilation.
|
||||
pub hot_swap_after_compile: HotSwapPolicy,
|
||||
pub python: PythonDebuggerSettings,
|
||||
pub cpp: CppDebuggerSettings,
|
||||
}
|
||||
|
||||
impl Default for DebuggerSettings {
|
||||
@@ -552,6 +583,7 @@ impl Default for DebuggerSettings {
|
||||
flutter_hot_reload_on_save: true,
|
||||
hot_swap_after_compile: HotSwapPolicy::Ask,
|
||||
python: PythonDebuggerSettings::default(),
|
||||
cpp: CppDebuggerSettings::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -570,6 +602,14 @@ impl Default for PythonDebuggerSettings {
|
||||
}
|
||||
}
|
||||
|
||||
/// C/C++ debugger executables. Empty paths use automatic discovery.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct CppDebuggerSettings {
|
||||
pub gdb_executable: String,
|
||||
pub lldb_dap_executable: String,
|
||||
}
|
||||
|
||||
/// Run/Debug configuration behaviour.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
@@ -616,6 +656,8 @@ pub struct TerminalSettings {
|
||||
pub close_on_exit: bool,
|
||||
pub mouse_reporting: bool,
|
||||
pub copy_on_selection: bool,
|
||||
/// Programs may set the clipboard with OSC 52 (tmux, Neovim, TUIs over SSH); never read it.
|
||||
pub osc52_clipboard: bool,
|
||||
pub paste_on_middle_click: bool,
|
||||
/// Right-click pastes instead of opening the context menu (Ctrl or Shift + right-click still opens it).
|
||||
pub right_click_paste: bool,
|
||||
@@ -656,6 +698,7 @@ impl Default for TerminalSettings {
|
||||
close_on_exit: true,
|
||||
mouse_reporting: true,
|
||||
copy_on_selection: false,
|
||||
osc52_clipboard: true,
|
||||
paste_on_middle_click: true,
|
||||
right_click_paste: false,
|
||||
override_ide_shortcuts: true,
|
||||
@@ -800,4 +843,17 @@ mod tests {
|
||||
assert_eq!(serialized["hotSwapAfterCompile"], raw);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cpp_debugger_paths_default_to_empty_and_roundtrip() {
|
||||
let missing: DebuggerSettings = serde_json::from_str("{}").unwrap();
|
||||
assert!(missing.cpp.gdb_executable.is_empty());
|
||||
assert!(missing.cpp.lldb_dap_executable.is_empty());
|
||||
|
||||
let cpp = serde_json::json!({"gdbExecutable": "tools/gdb-16", "lldbDapExecutable": "/opt/llvm/bin/lldb-dap"});
|
||||
let settings: DebuggerSettings = serde_json::from_value(serde_json::json!({"cpp": cpp})).unwrap();
|
||||
assert_eq!(settings.cpp.gdb_executable, "tools/gdb-16");
|
||||
assert_eq!(settings.cpp.lldb_dap_executable, "/opt/llvm/bin/lldb-dap");
|
||||
assert_eq!(serde_json::to_value(&settings).unwrap()["cpp"], cpp);
|
||||
}
|
||||
}
|
||||
@@ -35,6 +35,24 @@ pub fn parse(path: &Path) -> Option<WslPath> {
|
||||
Some(WslPath { distro: distro.to_owned(), path: format!("/{}", tail.trim_end_matches('/')) })
|
||||
}
|
||||
|
||||
/// The Linux path of a Windows path seen from `distro`: `C:\a` → `/mnt/c/a` (WSL's default
|
||||
/// automount root), `\\wsl.localhost\<distro>\a` → `/a`. `None` for another distro's share,
|
||||
/// other network shares and relative paths.
|
||||
pub fn linux_path(path: &Path, distro: &str) -> Option<String> {
|
||||
if let Some(w) = parse(path) {
|
||||
return w.distro.eq_ignore_ascii_case(distro).then_some(w.path);
|
||||
}
|
||||
let s = path.to_string_lossy().replace('\\', "/");
|
||||
let s = s.strip_prefix("//?/").unwrap_or(&s);
|
||||
let mut chars = s.chars();
|
||||
let drive = chars.next().filter(char::is_ascii_alphabetic)?;
|
||||
let rest = chars.as_str().strip_prefix(':')?;
|
||||
if !(rest.is_empty() || rest.starts_with('/')) {
|
||||
return None;
|
||||
}
|
||||
Some(format!("/mnt/{}{}", drive.to_ascii_lowercase(), rest.trim_end_matches('/')))
|
||||
}
|
||||
|
||||
/// A distro name `wsl.exe -d` can be given safely: Windows creates them from letters, digits,
|
||||
/// `.`, `_` and `-`. A leading `-` would be read as an option, so it is refused too.
|
||||
pub fn is_valid_distro(name: &str) -> bool {
|
||||
@@ -86,6 +104,57 @@ pub fn list_distros() -> Vec<String> {
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
/// Where this machine reads `distro`'s file system.
|
||||
pub fn share_root(distro: &str) -> std::path::PathBuf {
|
||||
format!(r"\\wsl.localhost\{distro}").into()
|
||||
}
|
||||
|
||||
/// The names of a Linux path, `.` dropped and `..` taking the name before it.
|
||||
pub fn path_parts(linux: &str) -> Vec<&str> {
|
||||
let mut parts: Vec<&str> = Vec::new();
|
||||
for c in linux.split('/').filter(|c| !c.is_empty() && *c != ".") {
|
||||
if c == ".." {
|
||||
parts.pop();
|
||||
} else {
|
||||
parts.push(c);
|
||||
}
|
||||
}
|
||||
parts
|
||||
}
|
||||
|
||||
/// Where this machine reads the absolute path `linux` of `distro`: a drive mounted at
|
||||
/// `/mnt/<drive>` is read directly, anything else through [`share_root`]. `..` goes up
|
||||
/// within `linux`, never above the drive or the share.
|
||||
pub fn windows_path(linux: &str, distro: &str) -> std::path::PathBuf {
|
||||
let parts = path_parts(linux);
|
||||
let base = match parts.as_slice() {
|
||||
["mnt", drive, ..] if drive.len() == 1 && drive.chars().all(|c| c.is_ascii_alphabetic()) => {
|
||||
let base = std::path::PathBuf::from(format!("{}:\\", drive.to_ascii_uppercase()));
|
||||
return parts[2..].iter().fold(base, |p, c| p.join(c));
|
||||
}
|
||||
_ => share_root(distro),
|
||||
};
|
||||
parts.iter().fold(base, |p, c| p.join(c))
|
||||
}
|
||||
|
||||
/// Runs `args` in `distro` without its shell and returns the standard output; a failed
|
||||
/// run is an error with its output. `wsl.exe`'s own messages are UTF-16: their NULs go.
|
||||
pub fn exec(distro: &str, args: &[&str], timeout: std::time::Duration) -> crate::IdeResult<String> {
|
||||
use crate::cli_process::{CliTool, Decoding};
|
||||
if !is_valid_distro(distro) {
|
||||
return Err(crate::IdeError::invalid(format!("'{distro}' is not a WSL distribution name")));
|
||||
}
|
||||
let mut cmd = std::process::Command::new(EXE);
|
||||
cmd.args(["-d", distro, "--exec"]).args(args);
|
||||
let out = CliTool::new(EXE, Decoding::Utf8Lossy).run(cmd, timeout, None)?;
|
||||
let (stdout, stderr) = (out.stdout.replace('\0', ""), out.stderr.replace('\0', ""));
|
||||
if out.success {
|
||||
return Ok(stdout);
|
||||
}
|
||||
let detail = if stderr.trim().is_empty() { stdout.trim() } else { stderr.trim() };
|
||||
Err(crate::IdeError::internal(format!("{EXE} -d {distro} --exec {}: {detail}", args.first().unwrap_or(&""))))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -103,6 +172,21 @@ mod tests {
|
||||
assert_eq!(p(r"\\?\UNC\WSL.LOCALHOST\Ubuntu-24.04\home\me\app"), want);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn windows_paths_map_onto_the_distro() {
|
||||
let l = |s: &str| linux_path(Path::new(s), "Ubuntu");
|
||||
assert_eq!(l(r"C:\Users\me\app"), Some("/mnt/c/Users/me/app".into()));
|
||||
assert_eq!(l(r"D:\"), Some("/mnt/d".into()));
|
||||
assert_eq!(l("e:/work/x/"), Some("/mnt/e/work/x".into()));
|
||||
assert_eq!(l(r"\\?\C:\proj"), Some("/mnt/c/proj".into()));
|
||||
assert_eq!(l(r"\\wsl.localhost\ubuntu\home\me"), Some("/home/me".into()));
|
||||
assert_eq!(l(r"\\wsl$\Debian\home\me"), None);
|
||||
assert_eq!(l(r"\\server\share\a"), None);
|
||||
assert_eq!(l(r"C:relative"), None);
|
||||
assert_eq!(l("app"), None);
|
||||
assert_eq!(l("/home/me"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn distro_root_and_foreign_paths() {
|
||||
assert_eq!(p(r"\\wsl.localhost\Debian"), Some(("Debian".to_owned(), "/".to_owned())));
|
||||
@@ -127,6 +211,14 @@ mod tests {
|
||||
assert!(parse_distro_list(b"").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn linux_paths_are_read_on_their_drive_or_through_the_share() {
|
||||
use std::path::PathBuf;
|
||||
assert_eq!(windows_path("/mnt/d/lib/../x.py", "U"), PathBuf::from("D:\\").join("x.py"));
|
||||
assert_eq!(windows_path("/usr/lib/a.py", "U"), share_root("U").join("usr").join("lib").join("a.py"));
|
||||
assert_eq!(windows_path("/mnt/wsl/x", "U"), share_root("U").join("mnt").join("wsl").join("x"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn distro_names_cannot_smuggle_options_or_paths() {
|
||||
for bad in ["", "-d", "--exec", "a b", "a/b", r"a\b", "a;b", "a$(x)", "a\"b"] {
|
||||
|
||||
@@ -360,9 +360,46 @@ fn find_binary_in(
|
||||
}
|
||||
|
||||
/// [`find_binary`], plus Xcode's toolchain on macOS (`xcrun -f lldb-dap`): Xcode ships
|
||||
/// lldb-dap without putting it on `PATH`.
|
||||
/// lldb-dap without putting it on `PATH`. Elsewhere lldb-dap may carry its LLVM version.
|
||||
pub fn resolve_binary(command: &str, cwd: &Path) -> Option<PathBuf> {
|
||||
find_binary(command, cwd).or_else(|| xcrun_tool(command, cwd))
|
||||
find_binary(command, cwd).or_else(|| xcrun_tool(command, cwd)).or_else(|| {
|
||||
(command == "lldb-dap" && !cfg!(windows))
|
||||
.then(|| versioned_lldb_dap(&search_dirs(cwd), Path::new("/usr/lib")))
|
||||
.flatten()
|
||||
})
|
||||
}
|
||||
|
||||
/// Debian and Ubuntu install LLVM's lldb-dap as `lldb-dap-18` (`lldb-vscode-14` before
|
||||
/// LLVM 18 renamed it; same protocol) on `PATH`, or only as `/usr/lib/llvm-18/bin/lldb-dap`.
|
||||
/// The newest LLVM wins.
|
||||
fn versioned_lldb_dap(dirs: &[PathBuf], lib: &Path) -> Option<PathBuf> {
|
||||
let version = |name: &str| -> Option<u32> {
|
||||
let v = name.strip_prefix("lldb-dap-").or_else(|| name.strip_prefix("lldb-vscode-"))?;
|
||||
v.parse().ok()
|
||||
};
|
||||
let mut found: Vec<(u32, PathBuf)> = Vec::new();
|
||||
for dir in dirs {
|
||||
for entry in std::fs::read_dir(dir).into_iter().flatten().flatten() {
|
||||
let path = entry.path();
|
||||
if let Some(v) = path.file_name().and_then(|n| n.to_str()).and_then(version)
|
||||
&& is_executable(&path, false)
|
||||
{
|
||||
found.push((v, path));
|
||||
}
|
||||
}
|
||||
}
|
||||
for entry in std::fs::read_dir(lib).into_iter().flatten().flatten() {
|
||||
let Some(v) = entry.file_name().to_str().and_then(|n| n.strip_prefix("llvm-")?.parse::<u32>().ok()) else {
|
||||
continue;
|
||||
};
|
||||
for name in ["lldb-dap", "lldb-vscode"] {
|
||||
let path = entry.path().join("bin").join(name);
|
||||
if is_executable(&path, false) {
|
||||
found.push((v, path));
|
||||
}
|
||||
}
|
||||
}
|
||||
found.into_iter().max_by_key(|(v, _)| *v).map(|(_, p)| p)
|
||||
}
|
||||
|
||||
/// `cwd`, inside a project, picks the project's Xcode (`DEVELOPER_DIR`).
|
||||
@@ -472,7 +509,7 @@ fn is_app_execution_alias(path: &Path) -> bool {
|
||||
|
||||
/// GDB's DAP interpreter (`-i dap`) shipped in GDB 14; older ones exit with
|
||||
/// "Interpreter `dap' unrecognized".
|
||||
const GDB_MIN_MAJOR: u32 = 14;
|
||||
pub(crate) const GDB_MIN_MAJOR: u32 = 14;
|
||||
|
||||
/// `(major, minor)` of the first version number in the output of `gdb --version`
|
||||
/// (`GNU gdb (GDB) 14.2`, `GNU gdb (Ubuntu 12.1-0ubuntu1~22.04.2) 12.1`, `GNU gdb
|
||||
@@ -513,24 +550,29 @@ pub fn parse_gdb_version(output: &str) -> Option<(u32, u32)> {
|
||||
|
||||
/// Probe the already resolved and verified executable with its launch environment.
|
||||
async fn gdb_version(binary: &Path, spec: &AdapterSpec) -> IdeResult<Option<(u32, u32)>> {
|
||||
Ok(probe_gdb_version(binary, &spec.cwd, &spec.env).await)
|
||||
}
|
||||
|
||||
/// `(major, minor)` of `binary --version`, run in `cwd` with `env`; `None` when it doesn't say.
|
||||
pub(crate) async fn probe_gdb_version(binary: &Path, cwd: &Path, env: &[(String, String)]) -> Option<(u32, u32)> {
|
||||
let mut probe = Command::new(binary);
|
||||
if let Some(path) = adapter_path(&spec.env, &spec.cwd) {
|
||||
if let Some(path) = adapter_path(env, cwd) {
|
||||
probe.env("PATH", path);
|
||||
}
|
||||
probe.current_dir(&spec.cwd);
|
||||
probe.current_dir(cwd);
|
||||
ide_core::process::prepare(probe.as_std_mut());
|
||||
let probe = probe
|
||||
.arg("--version")
|
||||
.envs(spec.env.iter().cloned())
|
||||
.envs(env.iter().cloned())
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::null())
|
||||
.kill_on_drop(true)
|
||||
.output();
|
||||
let Ok(Ok(out)) = tokio::time::timeout(Duration::from_secs(15), probe).await else {
|
||||
return Ok(None);
|
||||
return None;
|
||||
};
|
||||
Ok(parse_gdb_version(&String::from_utf8_lossy(&out.stdout)))
|
||||
parse_gdb_version(&String::from_utf8_lossy(&out.stdout))
|
||||
}
|
||||
|
||||
/// Refuse old GDB versions and report whether launch must follow configurationDone.
|
||||
@@ -543,8 +585,9 @@ async fn prepare_gdb(spec: &AdapterSpec, binary: &Path) -> IdeResult<bool> {
|
||||
return Ok(major == 15);
|
||||
}
|
||||
let mut msg = format!(
|
||||
"debugging with GDB needs GDB {GDB_MIN_MAJOR} or newer (found {major}.{minor}): \
|
||||
this one has no DAP interpreter (`gdb -i dap`)"
|
||||
"debugging with GDB needs GDB {GDB_MIN_MAJOR} or newer (found {major}.{minor} at {}): \
|
||||
this one has no DAP interpreter (`gdb -i dap`)",
|
||||
binary.display(),
|
||||
);
|
||||
if let Some(hint) = &spec.install_hint {
|
||||
msg.push_str(". ");
|
||||
@@ -1026,6 +1069,48 @@ mod tests {
|
||||
assert!(builtin("nope").is_none());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn gdb_version_check_probes_the_adapter_command() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let binary = dir.path().join("custom gdb");
|
||||
std::fs::write(&binary, "#!/bin/sh\n[ \"$1\" = --version ] && echo 'GNU gdb (GDB) 13.2'\n").unwrap();
|
||||
std::fs::set_permissions(&binary, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
let mut spec = resolve(&builtin("gdb").unwrap(), dir.path().to_path_buf());
|
||||
spec.command = binary.to_str().unwrap().to_owned();
|
||||
|
||||
let Err(error) = ProcessLauncher.launch(spec, None).await else {
|
||||
panic!("GDB 13 was started as a DAP adapter");
|
||||
};
|
||||
assert_eq!(error.kind, ide_core::error::ErrorKind::Unavailable);
|
||||
assert!(error.message.contains("needs GDB 14 or newer (found 13.2 at "), "{}", error.message);
|
||||
assert!(error.message.contains(binary.to_str().unwrap()), "{}", error.message);
|
||||
}
|
||||
|
||||
/// Debian/Ubuntu's versioned lldb-dap (and lldb-vscode before LLVM 18): the newest LLVM wins.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn finds_versioned_lldb_dap() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let exe = |p: &Path| {
|
||||
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
|
||||
std::fs::write(p, "").unwrap();
|
||||
std::fs::set_permissions(p, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
};
|
||||
let (bin, lib) = (tmp.path().join("bin"), tmp.path().join("lib"));
|
||||
exe(&bin.join("lldb-vscode-14"));
|
||||
std::fs::write(bin.join("lldb-dap-99"), "").unwrap(); // not executable
|
||||
assert_eq!(versioned_lldb_dap(std::slice::from_ref(&bin), &lib), Some(bin.join("lldb-vscode-14")));
|
||||
exe(&lib.join("llvm-18/bin/lldb-dap"));
|
||||
assert_eq!(versioned_lldb_dap(std::slice::from_ref(&bin), &lib), Some(lib.join("llvm-18/bin/lldb-dap")));
|
||||
exe(&bin.join("lldb-dap-19"));
|
||||
assert_eq!(versioned_lldb_dap(std::slice::from_ref(&bin), &lib), Some(bin.join("lldb-dap-19")));
|
||||
assert_eq!(versioned_lldb_dap(&[], &tmp.path().join("none")), None);
|
||||
}
|
||||
|
||||
/// The first version number of `gdb --version`'s first line, however the distro decorates it.
|
||||
#[test]
|
||||
fn parses_gdb_versions() {
|
||||
|
||||
@@ -22,6 +22,7 @@ mod jvm_memory;
|
||||
pub mod kotlin;
|
||||
pub mod kotlin_lsp;
|
||||
mod memory;
|
||||
pub mod native;
|
||||
mod session;
|
||||
mod stream_trace;
|
||||
mod swiftpm;
|
||||
@@ -507,6 +508,11 @@ fn child_name(configuration: &Value, parent: &str) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// LLDB-based adapters, which debug native programs (and Swift on Apple platforms).
|
||||
fn is_native(adapter: &str) -> bool {
|
||||
matches!(adapter, "lldb-dap" | "codelldb")
|
||||
}
|
||||
|
||||
/// `extra_json` key naming the run whose JVM an attach debugs; IDE-side, never sent to the
|
||||
/// adapter.
|
||||
pub const RUN_LINK: &str = "__openideaRun";
|
||||
@@ -1637,11 +1643,16 @@ impl DebugManager {
|
||||
let _ = s.conn.request_timeout("terminate", json!({ "restart": false }), SHUTDOWN_TIMEOUT).await;
|
||||
}
|
||||
if !graceful && (!own_terminate || killed) {
|
||||
// A native attach to a program a run started for the debugger (an Xcode app launched
|
||||
// with `simctl launch --wait-for-debugger`) ends it too: detached, the app can be
|
||||
// left stopped with the SIGTERM the run's Stop sent while it was traced, and the
|
||||
// simulator then holds its launch (and the next one) forever.
|
||||
let ends_debuggee = s.request == "launch" || (terminate && s.run.is_some() && is_native(&s.adapter));
|
||||
let _ = s
|
||||
.conn
|
||||
.request_timeout(
|
||||
"disconnect",
|
||||
json!({ "restart": false, "terminateDebuggee": s.request == "launch" }),
|
||||
json!({ "restart": false, "terminateDebuggee": ends_debuggee }),
|
||||
SHUTDOWN_TIMEOUT,
|
||||
)
|
||||
.await;
|
||||
@@ -1785,7 +1796,8 @@ impl DebugManager {
|
||||
let mut states = self.states.lock();
|
||||
let Some(slot) = states.get_mut(path).and_then(|v| v.get_mut(index)) else { return false };
|
||||
let next = session::state_from(bp, slot.line);
|
||||
let next = BreakpointState { message: next.message.or_else(|| slot.message.clone()), ..next };
|
||||
let kept = slot.message.clone().filter(|m| !(next.verified && m == session::UNBOUND_NATIVE));
|
||||
let next = BreakpointState { message: next.message.or(kept), ..next };
|
||||
let changed = *slot != next;
|
||||
*slot = next;
|
||||
changed
|
||||
|
||||
@@ -0,0 +1,206 @@
|
||||
//! C/C++ launches made for lldb-dap (CMake, Swift packages) fall back to CodeLLDB, then to
|
||||
//! GDB 14 or newer, when the host has no lldb-dap: Linux hosts rarely put one on `PATH`, and
|
||||
//! CodeLLDB is the debugger OpenIDEA can install itself.
|
||||
|
||||
use crate::LaunchConfig;
|
||||
use crate::adapter::{GDB_MIN_MAJOR, probe_gdb_version};
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use serde_json::{Map, Value, json};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// Prefix of the error when none of them is there; the UI offers to install CodeLLDB on it.
|
||||
pub const NO_NATIVE_DEBUGGER: &str = "No C/C++ debugger found";
|
||||
|
||||
/// `config` for the first of lldb-dap, CodeLLDB and GDB 14+ that `lookup` finds (it resolves a
|
||||
/// debugger command: a configured tool path, else the search path). Other launches pass through.
|
||||
pub async fn choose(
|
||||
mut config: LaunchConfig,
|
||||
lookup: impl Fn(&str) -> Option<PathBuf> + Send + 'static,
|
||||
) -> IdeResult<LaunchConfig> {
|
||||
if config.adapter != "lldb-dap" || config.request != "launch" {
|
||||
return Ok(config);
|
||||
}
|
||||
let found = tokio::task::spawn_blocking(move || {
|
||||
if lookup("lldb-dap").is_some() {
|
||||
return Found::LldbDap;
|
||||
}
|
||||
if lookup("codelldb").is_some() {
|
||||
return Found::CodeLldb;
|
||||
}
|
||||
lookup("gdb").map_or(Found::Nothing, Found::Gdb)
|
||||
})
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()))?;
|
||||
let cwd = config.cwd.clone().map(PathBuf::from).unwrap_or_else(|| PathBuf::from("/"));
|
||||
match found {
|
||||
Found::LldbDap => {}
|
||||
Found::CodeLldb => convert(&mut config, "codelldb")?,
|
||||
Found::Gdb(gdb) => match probe_gdb_version(&gdb, &cwd, &[]).await {
|
||||
Some((major, minor)) if major < GDB_MIN_MAJOR => return Err(missing(Some((&gdb, major, minor)))),
|
||||
// Unknown versions are left to GDB itself, as a GDB launch does.
|
||||
_ => convert(&mut config, "gdb")?,
|
||||
},
|
||||
Found::Nothing => return Err(missing(None)),
|
||||
}
|
||||
Ok(config)
|
||||
}
|
||||
|
||||
enum Found {
|
||||
LldbDap,
|
||||
CodeLldb,
|
||||
Gdb(PathBuf),
|
||||
Nothing,
|
||||
}
|
||||
|
||||
fn missing(gdb: Option<(&Path, u32, u32)>) -> IdeError {
|
||||
let found = match gdb {
|
||||
Some((path, major, minor)) => format!(
|
||||
"lldb-dap and CodeLLDB are not installed, and GDB {major}.{minor} at {} cannot debug through DAP \
|
||||
(it needs GDB {GDB_MIN_MAJOR} or newer)",
|
||||
path.display(),
|
||||
),
|
||||
None => "lldb-dap, CodeLLDB and GDB are not installed".to_owned(),
|
||||
};
|
||||
IdeError::unavailable(format!(
|
||||
"{NO_NATIVE_DEBUGGER}: {found}. Install CodeLLDB, or install lldb-dap or GDB {GDB_MIN_MAJOR} or newer on this host"
|
||||
))
|
||||
}
|
||||
|
||||
/// Rewrites an lldb-dap launch for `to` (`codelldb` or `gdb`). lldb-dap takes the environment as
|
||||
/// `KEY=VALUE` strings and the source map as pairs; the others take the run configuration's
|
||||
/// environment map (`config.env`), CodeLLDB its source map as an object, GDB none.
|
||||
fn convert(config: &mut LaunchConfig, to: &str) -> IdeResult<()> {
|
||||
let mut extra = match config.extra_json.as_deref().filter(|e| !e.trim().is_empty()).map(serde_json::from_str) {
|
||||
None => Map::new(),
|
||||
Some(Ok(Value::Object(extra))) => extra,
|
||||
Some(Ok(other)) => return Err(IdeError::invalid(format!("launch arguments are not an object: {other}"))),
|
||||
Some(Err(e)) => return Err(IdeError::invalid(format!("invalid launch JSON: {e}"))),
|
||||
};
|
||||
extra.remove("env");
|
||||
let source_map = extra.remove("sourceMap");
|
||||
if to == "codelldb" {
|
||||
if let Some(Value::Array(pairs)) = source_map {
|
||||
let map: Map<String, Value> = pairs
|
||||
.iter()
|
||||
.filter_map(|pair| match pair.as_array().map(Vec::as_slice) {
|
||||
Some([Value::String(from), to]) => Some((from.clone(), to.clone())),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
if !map.is_empty() {
|
||||
extra.insert("sourceMap".into(), Value::Object(map));
|
||||
}
|
||||
}
|
||||
// CodeLLDB evaluates as Rust unless told otherwise (ide-dap's default for it).
|
||||
let language = if extra.contains_key("swiftpm") { "swift" } else { "cpp" };
|
||||
extra.entry("sourceLanguages").or_insert_with(|| json!([language]));
|
||||
}
|
||||
config.adapter = to.to_owned();
|
||||
config.extra_json = (!extra.is_empty()).then(|| Value::Object(extra).to_string());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
fn cmake_launch() -> LaunchConfig {
|
||||
LaunchConfig {
|
||||
name: "hello".into(),
|
||||
adapter: "lldb-dap".into(),
|
||||
request: "launch".into(),
|
||||
program: Some("/home/dev/hello/build/hello".into()),
|
||||
args: vec![],
|
||||
cwd: Some(std::path::PathBuf::from("/").into()),
|
||||
env: BTreeMap::from([("A".into(), "1".into())]),
|
||||
extra_json: Some(json!({"env": ["A=1"], "sourceMap": [["/src", "/real/src"]]}).to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
fn extra(config: &LaunchConfig) -> Value {
|
||||
config.extra_json.as_deref().map_or(Value::Null, |e| serde_json::from_str(e).unwrap())
|
||||
}
|
||||
|
||||
fn only(names: &'static [&'static str]) -> impl Fn(&str) -> Option<PathBuf> + Send + 'static {
|
||||
move |c| names.contains(&c).then(|| PathBuf::from(format!("/usr/bin/{c}")))
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn keeps_lldb_dap_when_it_is_there() {
|
||||
let config = choose(cmake_launch(), only(&["lldb-dap", "codelldb", "gdb"])).await.unwrap();
|
||||
assert_eq!(config.adapter, "lldb-dap");
|
||||
assert_eq!(config.extra_json, cmake_launch().extra_json);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn falls_back_to_codelldb_with_its_launch_shape() {
|
||||
let config = choose(cmake_launch(), only(&["codelldb", "gdb"])).await.unwrap();
|
||||
assert_eq!(config.adapter, "codelldb");
|
||||
assert_eq!(config.env, cmake_launch().env, "the environment comes from the run configuration's map");
|
||||
assert_eq!(
|
||||
extra(&config),
|
||||
json!({"sourceMap": {"/src": "/real/src"}, "sourceLanguages": ["cpp"]}),
|
||||
"no KEY=VALUE env strings; the source map as an object; C++ evaluation"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_swift_package_evaluates_swift_under_codelldb() {
|
||||
let mut launch = cmake_launch();
|
||||
launch.extra_json = Some(json!({"env": [], "swiftpm": {"product": "app", "buildArgs": []}}).to_string());
|
||||
let config = choose(launch, only(&["codelldb"])).await.unwrap();
|
||||
assert_eq!(extra(&config)["sourceLanguages"], json!(["swift"]));
|
||||
assert_eq!(extra(&config)["swiftpm"]["product"], "app");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn without_any_debugger_says_what_to_install() {
|
||||
let e = choose(cmake_launch(), only(&[])).await.unwrap_err();
|
||||
assert_eq!(e.kind, ide_core::error::ErrorKind::Unavailable);
|
||||
assert!(e.message.starts_with(NO_NATIVE_DEBUGGER), "{}", e.message);
|
||||
assert!(e.message.contains("Install CodeLLDB"), "{}", e.message);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn other_launches_pass_through() {
|
||||
let mut attach = cmake_launch();
|
||||
attach.request = "attach".into();
|
||||
assert_eq!(choose(attach, only(&[])).await.unwrap().adapter, "lldb-dap");
|
||||
let mut rust = cmake_launch();
|
||||
rust.adapter = "codelldb".into();
|
||||
assert_eq!(choose(rust, only(&[])).await.unwrap().adapter, "codelldb");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn fake_gdb(dir: &Path, version: &str) -> PathBuf {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let gdb = dir.join("gdb");
|
||||
std::fs::write(&gdb, format!("#!/bin/sh\necho '{version}'\n")).unwrap();
|
||||
std::fs::set_permissions(&gdb, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
gdb
|
||||
}
|
||||
|
||||
/// Ubuntu 22.04's GDB 12 has no DAP interpreter: the error names its version (#7001).
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn an_old_gdb_is_named_in_the_error() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let gdb = fake_gdb(dir.path(), "GNU gdb (Ubuntu 12.1-0ubuntu1~22.04.2) 12.1");
|
||||
let path = gdb.clone();
|
||||
let e = choose(cmake_launch(), move |c| (c == "gdb").then(|| path.clone())).await.unwrap_err();
|
||||
assert!(e.message.starts_with(NO_NATIVE_DEBUGGER), "{}", e.message);
|
||||
assert!(e.message.contains("GDB 12.1"), "{}", e.message);
|
||||
assert!(e.message.contains(gdb.to_str().unwrap()), "{}", e.message);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn falls_back_to_a_gdb_with_dap() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let gdb = fake_gdb(dir.path(), "GNU gdb (GDB) 14.2");
|
||||
let config = choose(cmake_launch(), move |c| (c == "gdb").then(|| gdb.clone())).await.unwrap();
|
||||
assert_eq!(config.adapter, "gdb");
|
||||
assert_eq!(extra(&config), Value::Null, "GDB takes the environment map and has no source map");
|
||||
}
|
||||
}
|
||||
@@ -293,6 +293,11 @@ impl Suspension {
|
||||
/// symlinked path (`/tmp/game` while the editor has `/private/tmp/game`).
|
||||
const RESOLVES_PATHS: &[&str] = &["godot"];
|
||||
|
||||
/// LLDB answers a breakpoint it can't bind yet with no reason: the code may simply not be loaded.
|
||||
const NATIVE_ADAPTERS: &[&str] = &["lldb-dap", "codelldb"];
|
||||
/// One literal: the UI looks it up in the text catalogs to translate it.
|
||||
pub(crate) const UNBOUND_NATIVE: &str = "No loaded code at this line yet. If it stays unbound after its module loads, the debug info may record this file under another path (through a symlink, or /tmp for /private/tmp): set a source map from that path to this one";
|
||||
|
||||
impl Session {
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn new(
|
||||
@@ -514,6 +519,9 @@ impl Session {
|
||||
ids.insert(id, (path.to_path_buf(), i));
|
||||
}
|
||||
states[i] = state_from(r, breakpoints[i].line);
|
||||
if !states[i].verified && states[i].message.is_none() && NATIVE_ADAPTERS.contains(&self.adapter.as_str()) {
|
||||
states[i].message = Some(UNBOUND_NATIVE.to_owned());
|
||||
}
|
||||
}
|
||||
Ok(states)
|
||||
}
|
||||
@@ -1134,21 +1142,27 @@ pub(crate) fn run_in_terminal(s: &Arc<Session>, args: &Value) -> Result<Value, S
|
||||
// CodeLLDB's launcher clears the terminal first; the console keeps the session's earlier output.
|
||||
cmd.args(rest.iter().filter(|a| *a != "--clear-screen"));
|
||||
let cwd = args.get("cwd").and_then(Value::as_str).filter(|c| !c.is_empty()).map_or(s.spec.cwd.as_path(), Path::new);
|
||||
for (k, v) in ide_core::process::host_env_fixes_in(cwd) {
|
||||
match v {
|
||||
Some(v) => cmd.env(k, v),
|
||||
None => cmd.env_remove(k),
|
||||
}
|
||||
// See #6806: do not inherit portable-pty's registry-built Windows env block.
|
||||
cmd.env_clear();
|
||||
for (k, v) in ide_core::process::spawnable_host_vars_in(cwd) {
|
||||
cmd.env(k, v);
|
||||
}
|
||||
for (k, v) in ide_core::process::shell_env_in(cwd) {
|
||||
cmd.env(k, v);
|
||||
if ide_core::process::is_spawnable_env_pair(&k, &v) {
|
||||
cmd.env(k, v);
|
||||
}
|
||||
}
|
||||
cmd.env("TERM", "xterm-256color");
|
||||
cmd.cwd(cwd);
|
||||
if let Some(env) = args.get("env").and_then(Value::as_object) {
|
||||
for (k, v) in env {
|
||||
match v.as_str() {
|
||||
Some(v) => cmd.env(k, v),
|
||||
Some(v)
|
||||
if ide_core::process::is_spawnable_env_pair(std::ffi::OsStr::new(k), std::ffi::OsStr::new(v)) =>
|
||||
{
|
||||
cmd.env(k, v)
|
||||
}
|
||||
Some(_) => {}
|
||||
None => cmd.env_remove(k),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -138,6 +138,8 @@ struct Script {
|
||||
output_after_terminate: bool,
|
||||
/// Advertise `supportsTerminateRequest` (java-debug does not, so Stop signals the program).
|
||||
supports_terminate: bool,
|
||||
/// Answer `setBreakpoints` with unverified breakpoints and no reason (LLDB before the code loads).
|
||||
unbound_breakpoints: bool,
|
||||
/// Answer `setBreakpoints` only once this many are waiting (a client that waits for each never gets one).
|
||||
hold_set_breakpoints: usize,
|
||||
/// Send a `continued` event right after the first `stopped` one.
|
||||
@@ -220,6 +222,7 @@ impl Default for Script {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
run_in_terminal: None,
|
||||
unbound_breakpoints: false,
|
||||
start_debugging: false,
|
||||
child_request: None,
|
||||
ignore_configuration_done: false,
|
||||
@@ -414,7 +417,7 @@ async fn fake_adapter<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(stream
|
||||
.unwrap()
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, b)| json!({"id": i + 1, "verified": true, "line": b["line"]}))
|
||||
.map(|(i, b)| json!({"id": i + 1, "verified": !script.unbound_breakpoints, "line": b["line"]}))
|
||||
.collect();
|
||||
ok!(msg, json!({"breakpoints": bps}));
|
||||
}
|
||||
@@ -4019,6 +4022,50 @@ async fn stop_detaches_from_an_attached_program() {
|
||||
assert_eq!(h.request("disconnect")["arguments"]["terminateDebuggee"], false);
|
||||
}
|
||||
|
||||
/// Xcode Debug: lldb-dap attaches to the app a run launched suspended. Stop ends the app through
|
||||
/// the debugger; detaching would leave it stopped with the run's SIGTERM, holding the simulator.
|
||||
#[tokio::test]
|
||||
async fn stop_ends_a_native_program_a_run_started_for_the_debugger() {
|
||||
let h = harness(Script::default());
|
||||
let linked = |adapter: &str| LaunchConfig {
|
||||
adapter: adapter.into(),
|
||||
request: "attach".into(),
|
||||
extra_json: Some(json!({ RUN_LINK: 7, "pid": 4242 }).to_string()),
|
||||
..config()
|
||||
};
|
||||
let id = h.start(linked("lldb-dap")).await.unwrap();
|
||||
h.manager.stop(id).await.unwrap();
|
||||
assert_eq!(h.request("disconnect")["arguments"]["terminateDebuggee"], true);
|
||||
|
||||
// Another adapter's attach to a run (a Gradle test worker JVM) still only detaches.
|
||||
let h = harness(Script::default());
|
||||
let id = h.start(linked("debugpy")).await.unwrap();
|
||||
h.manager.stop(id).await.unwrap();
|
||||
assert_eq!(h.request("disconnect")["arguments"]["terminateDebuggee"], false);
|
||||
}
|
||||
|
||||
/// LLDB leaves a breakpoint it can't bind unverified without a reason: say what may be wrong
|
||||
/// (#6665 E1b: Xcode's debug info had `/tmp/…` for a project under `/private/tmp`).
|
||||
#[tokio::test]
|
||||
async fn an_unbound_native_breakpoint_says_why() {
|
||||
for (adapter, hint) in [("lldb-dap", true), ("codelldb", true), ("debugpy", false)] {
|
||||
let h = harness(Script { unbound_breakpoints: true, ..Script::default() });
|
||||
h.start(LaunchConfig { adapter: adapter.into(), ..config() }).await.unwrap();
|
||||
let path = PathBuf::from("/private/tmp/app/Counter.swift");
|
||||
let states = h.manager.set_breakpoints(&h.owner.key, path, vec![bp(6)]).await.unwrap();
|
||||
assert!(!states[0].verified);
|
||||
assert_eq!(states[0].message.as_deref() == Some(crate::session::UNBOUND_NATIVE), hint, "{adapter}");
|
||||
}
|
||||
|
||||
// Bound once the module loads (lldb-dap's `breakpoint` event has no message): the hint goes.
|
||||
let path = PathBuf::from("/private/tmp/app/Counter.swift");
|
||||
let h = harness(Script { unbound_breakpoints: true, ..Script::default() });
|
||||
h.start(LaunchConfig { adapter: "lldb-dap".into(), ..config() }).await.unwrap();
|
||||
h.manager.set_breakpoints(&h.owner.key, path.clone(), vec![bp(6)]).await.unwrap();
|
||||
assert!(h.manager.update_breakpoint_state(&path, 0, &json!({"id": 1, "verified": true, "line": 7})));
|
||||
assert_eq!(h.manager.breakpoint_states(&path)[0].message, None);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cell_breakpoints_go_only_to_their_notebooks_kernel_session() {
|
||||
use crate::jvm_memory::test_support::bare_session_of;
|
||||
|
||||
+134
-62
@@ -447,6 +447,15 @@ fn read_table_properties(details: &mut TableDetails, row: Vec<Option<String>>) {
|
||||
);
|
||||
details.partitioning = next();
|
||||
details.persistence = next().as_deref().and_then(DbPersistence::from_catalog);
|
||||
// PostgreSQL's `table_properties` carries the comment as its last column, so reading it here
|
||||
// saves the separate query `table_comment` would make on the same `pg_class` row.
|
||||
if let Some(comment) = next() {
|
||||
// `table_comment` this replaces yielded `NULL` or empty for no comment, so an empty
|
||||
// comment must not become `Some("")` — the DDL would emit an empty `COMMENT ON`.
|
||||
if !comment.is_empty() {
|
||||
details.comment = Some(comment);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn flag(v: &Option<String>) -> bool {
|
||||
@@ -1384,8 +1393,61 @@ impl DbManager {
|
||||
if driver == DbDriver::Jdbc {
|
||||
return Ok(TableDetails { columns, ..Default::default() });
|
||||
}
|
||||
// Everything below describes the same table and none of it feeds the next, so it goes
|
||||
// out together. Serialised, this is four round trips on the path that opens a table
|
||||
// (`table_page_on` calls this for the primary key), which is what makes opening a table
|
||||
// feel slow on a remote server. Five queries against a pool of four (`conn.rs`'s `MAX`),
|
||||
// so one waits — still one round trip rather than five.
|
||||
type Rows = Vec<Vec<Option<String>>>;
|
||||
let keys = !matches!(driver, DbDriver::Clickhouse | DbDriver::Snowflake);
|
||||
let (index_q, fk_q, trigger_q) = (
|
||||
sql::indexes(driver, schema, table),
|
||||
sql::table_foreign_keys(driver, schema, table),
|
||||
sql::triggers(driver, schema, table),
|
||||
);
|
||||
let (index_rows, fk_rows, trigger_rows, comment_rows, property_rows) = futures::join!(
|
||||
pool.rows(&index_q, MAX_META_ROWS),
|
||||
async {
|
||||
if !keys {
|
||||
return Ok::<Rows, IdeError>(Vec::new());
|
||||
}
|
||||
match pool.rows(&fk_q, MAX_META_ROWS).await {
|
||||
Ok(rows) => Ok(rows),
|
||||
Err(e) => {
|
||||
tracing::warn!("foreign keys: {}", e.message);
|
||||
Ok(Vec::new())
|
||||
}
|
||||
}
|
||||
},
|
||||
async {
|
||||
if !keys {
|
||||
return Ok::<Rows, IdeError>(Vec::new());
|
||||
}
|
||||
match pool.rows(&trigger_q, MAX_META_ROWS).await {
|
||||
Ok(rows) => Ok(rows),
|
||||
Err(e) => {
|
||||
tracing::warn!("triggers: {}", e.message);
|
||||
Ok(Vec::new())
|
||||
}
|
||||
}
|
||||
},
|
||||
async {
|
||||
// PostgreSQL reads it with the properties above; the engines without a
|
||||
// `table_properties` query ask for it here.
|
||||
match sql::table_comment(driver, schema, table) {
|
||||
Some(q) if sql::table_properties(driver, schema, table).is_none() => pool.rows(&q, 1).await,
|
||||
_ => Ok::<Rows, IdeError>(Vec::new()),
|
||||
}
|
||||
},
|
||||
async {
|
||||
match sql::table_properties(driver, schema, table) {
|
||||
Some(q) => catalog_rows(pool, &q).await,
|
||||
None => Ok::<Rows, IdeError>(Vec::new()),
|
||||
}
|
||||
},
|
||||
);
|
||||
let mut indexes: Vec<IndexInfo> = Vec::new();
|
||||
for r in pool.rows(&sql::indexes(driver, schema, table), MAX_META_ROWS).await? {
|
||||
for r in index_rows? {
|
||||
let mut it = r.into_iter();
|
||||
let (Some(name), unique, Some(col)) = (it.next().flatten(), it.next().flatten(), it.next().flatten())
|
||||
else {
|
||||
@@ -1401,11 +1463,7 @@ impl DbManager {
|
||||
}),
|
||||
}
|
||||
}
|
||||
let fk_rows = if matches!(driver, DbDriver::Clickhouse | DbDriver::Snowflake) {
|
||||
Vec::new()
|
||||
} else {
|
||||
pool.rows(&sql::table_foreign_keys(driver, schema, table), MAX_META_ROWS).await.unwrap_or_default()
|
||||
};
|
||||
let fk_rows = fk_rows?;
|
||||
let mut foreign_keys = group_foreign_keys(fk_rows, &[]);
|
||||
// SQLite keys that reference the primary key implicitly: look it up.
|
||||
for k in foreign_keys.iter_mut().filter(|k| k.ref_columns.is_empty()) {
|
||||
@@ -1418,15 +1476,7 @@ impl DbManager {
|
||||
.collect();
|
||||
}
|
||||
foreign_keys.retain(|k| k.columns.len() == k.ref_columns.len());
|
||||
let trigger_rows = if matches!(driver, DbDriver::Clickhouse | DbDriver::Snowflake) {
|
||||
Vec::new()
|
||||
} else {
|
||||
pool.rows(&sql::triggers(driver, schema, table), MAX_META_ROWS).await.unwrap_or_else(|e| {
|
||||
tracing::warn!("triggers: {}", e.message);
|
||||
Vec::new()
|
||||
})
|
||||
};
|
||||
let triggers = trigger_rows
|
||||
let triggers = trigger_rows?
|
||||
.into_iter()
|
||||
.filter_map(|r| {
|
||||
let mut it = r.into_iter();
|
||||
@@ -1439,26 +1489,21 @@ impl DbManager {
|
||||
Some(TriggerInfo { name, timing, events })
|
||||
})
|
||||
.collect();
|
||||
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,
|
||||
};
|
||||
let comment = comment_rows.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()),
|
||||
);
|
||||
let mut details = TableDetails { comment, columns, indexes, foreign_keys, triggers, ..Default::default() };
|
||||
if let Some(q) = sql::table_properties(driver, schema, table) {
|
||||
match catalog_rows(pool, &q).await {
|
||||
Ok(rows) => {
|
||||
if let Some(row) = rows.into_iter().next() {
|
||||
read_table_properties(&mut details, row);
|
||||
}
|
||||
match property_rows {
|
||||
Ok(rows) => {
|
||||
if let Some(row) = rows.into_iter().next() {
|
||||
read_table_properties(&mut details, row);
|
||||
}
|
||||
Err(e) => tracing::warn!("table properties: {}", e.message),
|
||||
}
|
||||
Err(e) => tracing::warn!("table properties: {}", e.message),
|
||||
}
|
||||
Ok(details)
|
||||
}
|
||||
@@ -1669,16 +1714,16 @@ impl DbManager {
|
||||
ddl.map(|d| format!("{};\n", d.trim_end().trim_end_matches(';'))).ok_or_else(missing)
|
||||
}
|
||||
DbDriver::Postgres => {
|
||||
let rel = pool.rows(&sql::postgres_relation(schema, name), 1).await?.into_iter().next();
|
||||
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()),
|
||||
// Everything the script needs depends on the relation oid, so read that first and
|
||||
// then the rest at once — five queries in flight against a pool of four, so one
|
||||
// waits, but that is still two round trips instead of six.
|
||||
let rel = catalog_rows(&pool, &sql::postgres_relation(schema, name)).await?.into_iter().next();
|
||||
let Some([Some(oid), Some(kind), owner, comment, persistence, partition_key, parent @ ..]) =
|
||||
rel.as_deref()
|
||||
else {
|
||||
return Err(missing());
|
||||
};
|
||||
let oid = oid.parse::<u32>().map_err(|e| IdeError::invalid(e.to_string()))?;
|
||||
if kind == "v" || kind == "m" {
|
||||
let def = cells(pool.rows(&format!("SELECT pg_get_viewdef({oid}, true)"), 1).await?, 0);
|
||||
let what = if kind == "m" { "materialized view" } else { "view" };
|
||||
@@ -1686,43 +1731,70 @@ impl DbManager {
|
||||
let target = sql::qualified(driver, schema, name);
|
||||
return Ok(format!("create {what} {target} as\n{};\n", body.trim_end().trim_end_matches(';')));
|
||||
}
|
||||
let columns = pool
|
||||
.rows(&sql::postgres_ddl_columns(oid), MAX_META_ROWS)
|
||||
.await?
|
||||
let partition = match parent {
|
||||
[Some(parent_schema), Some(parent_table), Some(bound)] => Some(sql::DdlPartition {
|
||||
parent_schema: parent_schema.clone(),
|
||||
parent_table: parent_table.clone(),
|
||||
bound: bound.clone(),
|
||||
}),
|
||||
_ => None,
|
||||
};
|
||||
let is_partition = partition.is_some();
|
||||
let (cols_q, keys_q, grants_q, index_q, trigger_q) = (
|
||||
sql::postgres_ddl_columns(oid, is_partition),
|
||||
sql::postgres_ddl_constraints(oid, is_partition),
|
||||
sql::postgres_ddl_grants(oid),
|
||||
sql::postgres_ddl_indexes(oid, is_partition),
|
||||
sql::postgres_ddl_triggers(oid, is_partition),
|
||||
);
|
||||
let (col_rows, key_rows, grant_rows, index_rows, trigger_rows) = futures::join!(
|
||||
catalog_rows(&pool, &cols_q),
|
||||
pool.rows(&keys_q, MAX_META_ROWS),
|
||||
pool.rows(&grants_q, MAX_META_ROWS),
|
||||
pool.rows(&index_q, MAX_META_ROWS),
|
||||
catalog_rows(&pool, &trigger_q),
|
||||
);
|
||||
let columns = col_rows?
|
||||
.into_iter()
|
||||
.filter_map(|r| {
|
||||
let mut it = r.into_iter();
|
||||
Some(sql::DdlColumn {
|
||||
name: it.next().flatten()?,
|
||||
data_type: it.next().flatten().unwrap_or_default(),
|
||||
not_null: flag(&it.next().flatten()),
|
||||
default: it.next().flatten(),
|
||||
comment: it.next().flatten(),
|
||||
})
|
||||
let name = it.next().flatten()?;
|
||||
let data_type = it.next().flatten()?;
|
||||
let not_null = flag(&it.next().flatten());
|
||||
let expression = it.next().flatten();
|
||||
let comment = it.next().flatten().filter(|c| !c.is_empty());
|
||||
let identity = it.next().flatten();
|
||||
let generated = it.next().flatten();
|
||||
let value =
|
||||
sql::DdlColumnValue::from_catalog(identity.as_deref(), generated.as_deref(), expression);
|
||||
Some(sql::DdlColumn { name, data_type, not_null, value, comment })
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let constraints = pool
|
||||
.rows(&sql::postgres_ddl_constraints(oid), MAX_META_ROWS)
|
||||
.await?
|
||||
let constraints = key_rows?
|
||||
.into_iter()
|
||||
.filter_map(|r| {
|
||||
let mut it = r.into_iter();
|
||||
Some((it.next().flatten()?, it.next().flatten()?))
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let indexes = cells(pool.rows(&sql::postgres_ddl_indexes(oid), MAX_META_ROWS).await?, 0);
|
||||
let grants = pool
|
||||
.rows(&sql::postgres_ddl_grants(oid), MAX_META_ROWS)
|
||||
.await?
|
||||
let indexes =
|
||||
index_rows?.into_iter().filter_map(|r| r.into_iter().next().flatten()).collect::<Vec<_>>();
|
||||
let grants = grant_rows?
|
||||
.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))
|
||||
.collect::<Vec<_>>();
|
||||
let triggers =
|
||||
trigger_rows?.into_iter().filter_map(|r| r.into_iter().next().flatten()).collect::<Vec<_>>();
|
||||
let options = sql::DdlTableOptions {
|
||||
unlogged: persistence.as_deref() == Some("u"),
|
||||
partition_key: partition_key.clone(),
|
||||
partition,
|
||||
};
|
||||
let extras = sql::DdlExtras { comment: comment.clone(), owner: owner.clone(), grants, triggers };
|
||||
Ok(sql::postgres_table_ddl(schema, name, &columns, &constraints, &indexes, &options, &extras))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+224
-24
@@ -249,7 +249,7 @@ pub fn table_properties(driver: DbDriver, schema: &str, table: &str) -> Option<S
|
||||
JOIN pg_tablespace dt ON dt.oid = d.dattablespace WHERE d.datname = current_database())), \
|
||||
am.amname, array_to_string(array_cat(c.reloptions, \
|
||||
(SELECT array_agg('toast.' || o) FROM unnest(tc.reloptions) o)), chr(10)), \
|
||||
pg_get_partkeydef(c.oid), c.relpersistence \
|
||||
pg_get_partkeydef(c.oid), c.relpersistence, obj_description(c.oid, 'pg_class') \
|
||||
FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace \
|
||||
LEFT JOIN pg_class tc ON tc.oid = c.reltoastrelid \
|
||||
LEFT JOIN pg_tablespace ts ON ts.oid = c.reltablespace LEFT JOIN pg_am am ON am.oid = c.relam \
|
||||
@@ -697,40 +697,70 @@ pub fn sqlite_ddl(schema: &str, name: &str) -> String {
|
||||
)
|
||||
}
|
||||
|
||||
/// Rows: `oid, relkind, owner, comment` of a PostgreSQL relation.
|
||||
/// Rows: `oid, relkind, owner, comment, persistence, partition key, parent schema, parent name, bound`.
|
||||
pub fn postgres_relation(schema: &str, name: &str) -> String {
|
||||
format!(
|
||||
"SELECT c.oid::text, c.relkind::text, pg_get_userbyid(c.relowner), obj_description(c.oid, 'pg_class') \
|
||||
"SELECT c.oid::text, c.relkind::text, pg_get_userbyid(c.relowner), obj_description(c.oid, 'pg_class'), \
|
||||
c.relpersistence::text, pg_get_partkeydef(c.oid), pn.nspname, p.relname, pg_get_expr(c.relpartbound, c.oid) \
|
||||
FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace \
|
||||
LEFT JOIN pg_inherits i ON i.inhrelid = c.oid AND c.relispartition \
|
||||
LEFT JOIN pg_class p ON p.oid = i.inhparent LEFT JOIN pg_namespace pn ON pn.oid = p.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, comment` of relation `oid`.
|
||||
pub fn postgres_ddl_columns(oid: u32) -> String {
|
||||
/// Rows: `name, type, not null (0/1), expression, comment, identity, generated` of relation `oid`.
|
||||
/// On a partition, the not-null flag and expression describe overrides of the parent column.
|
||||
///
|
||||
/// Read from `pg_attribute` with `format_type` rather than from `information_schema.columns`:
|
||||
/// that view reports `character varying` without the length, `numeric` without the precision,
|
||||
/// `ARRAY` for every array and `USER-DEFINED` for an enum, so a script built from it would not
|
||||
/// recreate the table. It also lists only the columns the current role holds privileges on.
|
||||
pub fn postgres_ddl_columns(oid: u32, partition: bool) -> String {
|
||||
// Generated clauses add their own parentheses. Keep the original deparser style for defaults.
|
||||
let pretty = "(a.attgenerated::text = 's') IS TRUE";
|
||||
let expression = format!("pg_get_expr(d.adbin, d.adrelid, {pretty})");
|
||||
let (not_null, expression, identity, parent_join) = if partition {
|
||||
let parent_expression = format!("pg_get_expr(pd.adbin, pd.adrelid, {pretty})");
|
||||
(
|
||||
"a.attnotnull AND NOT pa.attnotnull",
|
||||
format!(
|
||||
"CASE WHEN {expression} IS DISTINCT FROM {parent_expression} THEN COALESCE({expression}, 'NULL') END"
|
||||
),
|
||||
"NULL",
|
||||
"JOIN pg_inherits i ON i.inhrelid = a.attrelid \
|
||||
JOIN pg_attribute pa ON pa.attrelid = i.inhparent AND pa.attname = a.attname AND NOT pa.attisdropped \
|
||||
LEFT JOIN pg_attrdef pd ON pd.adrelid = pa.attrelid AND pd.adnum = pa.attnum",
|
||||
)
|
||||
} else {
|
||||
("a.attnotnull", expression, "a.attidentity::text", "")
|
||||
};
|
||||
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), 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 \
|
||||
"SELECT a.attname, format_type(a.atttypid, a.atttypmod), CASE WHEN {not_null} THEN 1 ELSE 0 END, \
|
||||
{expression}, col_description(a.attrelid, a.attnum), {identity}, a.attgenerated::text FROM pg_attribute a \
|
||||
LEFT JOIN pg_attrdef d ON d.adrelid = a.attrelid AND d.adnum = a.attnum {parent_join} \
|
||||
WHERE a.attrelid = {oid} AND a.attnum > 0 AND NOT a.attisdropped ORDER BY a.attnum"
|
||||
)
|
||||
}
|
||||
|
||||
/// Rows: `name, definition` of the constraints of relation `oid` (primary key first).
|
||||
pub fn postgres_ddl_constraints(oid: u32) -> String {
|
||||
pub fn postgres_ddl_constraints(oid: u32, partition: bool) -> String {
|
||||
let local = if partition { " AND conislocal AND coninhcount = 0" } else { "" };
|
||||
format!(
|
||||
"SELECT conname, pg_get_constraintdef(oid, true) FROM pg_constraint WHERE conrelid = {oid} \
|
||||
"SELECT conname, pg_get_constraintdef(oid, true) FROM pg_constraint WHERE conrelid = {oid}{local} \
|
||||
ORDER BY CASE contype WHEN 'p' THEN 0 WHEN 'u' THEN 1 WHEN 'c' THEN 2 WHEN 'f' THEN 3 ELSE 4 END, conname"
|
||||
)
|
||||
}
|
||||
|
||||
/// Rows: `CREATE INDEX …` of relation `oid`, except the indexes behind constraints.
|
||||
pub fn postgres_ddl_indexes(oid: u32) -> String {
|
||||
pub fn postgres_ddl_indexes(oid: u32, partition: bool) -> String {
|
||||
let local =
|
||||
if partition { " AND NOT EXISTS (SELECT 1 FROM pg_inherits WHERE inhrelid = i.indexrelid)" } else { "" };
|
||||
format!(
|
||||
"SELECT pg_get_indexdef(i.indexrelid) FROM pg_index i WHERE i.indrelid = {oid} \
|
||||
AND NOT EXISTS (SELECT 1 FROM pg_constraint c WHERE c.conindid = i.indexrelid AND c.conrelid = i.indrelid) \
|
||||
AND NOT EXISTS (SELECT 1 FROM pg_constraint c WHERE c.conindid = i.indexrelid AND c.conrelid = i.indrelid){local} \
|
||||
ORDER BY 1"
|
||||
)
|
||||
}
|
||||
@@ -749,9 +779,10 @@ pub fn postgres_ddl_grants(oid: u32) -> String {
|
||||
}
|
||||
|
||||
/// Rows: `CREATE TRIGGER …` of the user triggers of relation `oid`.
|
||||
pub fn postgres_ddl_triggers(oid: u32) -> String {
|
||||
pub fn postgres_ddl_triggers(oid: u32, partition: bool) -> String {
|
||||
let local = if partition { " AND tgparentid = 0" } else { "" };
|
||||
format!(
|
||||
"SELECT pg_get_triggerdef(oid, true) FROM pg_trigger WHERE tgrelid = {oid} AND NOT tgisinternal \
|
||||
"SELECT pg_get_triggerdef(oid, true) FROM pg_trigger t WHERE tgrelid = {oid} AND NOT tgisinternal{local} \
|
||||
ORDER BY tgname"
|
||||
)
|
||||
}
|
||||
@@ -840,6 +871,12 @@ pub fn postgres_legacy(sql: &str) -> Option<String> {
|
||||
.replace(" LEFT JOIN pg_am am ON am.oid = c.relam", "")
|
||||
.replace("am.amname", "NULL")
|
||||
.replace("pg_get_partkeydef(c.oid)", "NULL")
|
||||
.replace("c.relispartition", "false")
|
||||
.replace("pg_get_expr(c.relpartbound, c.oid)", "NULL")
|
||||
// These flags entered the catalog in different releases. Keep whichever ones exist.
|
||||
.replace("a.attidentity::text", "to_jsonb(a)->>'attidentity'")
|
||||
.replace("a.attgenerated::text", "to_jsonb(a)->>'attgenerated'")
|
||||
.replace("tgparentid = 0", "COALESCE(to_jsonb(t)->>'tgparentid', '0') = '0'")
|
||||
.replace("c.relkind IN ('r', 'p')", "c.relkind = 'r'");
|
||||
(legacy != sql).then_some(legacy)
|
||||
}
|
||||
@@ -999,10 +1036,42 @@ pub struct DdlColumn {
|
||||
pub name: String,
|
||||
pub data_type: String,
|
||||
pub not_null: bool,
|
||||
pub default: Option<String>,
|
||||
pub value: Option<DdlColumnValue>,
|
||||
pub comment: Option<String>,
|
||||
}
|
||||
|
||||
pub enum DdlColumnValue {
|
||||
Default(String),
|
||||
IdentityByDefault,
|
||||
IdentityAlways,
|
||||
GeneratedStored(String),
|
||||
}
|
||||
|
||||
impl DdlColumnValue {
|
||||
pub fn from_catalog(identity: Option<&str>, generated: Option<&str>, expression: Option<String>) -> Option<Self> {
|
||||
match (identity, generated) {
|
||||
(Some("d"), _) => Some(Self::IdentityByDefault),
|
||||
(Some("a"), _) => Some(Self::IdentityAlways),
|
||||
(_, Some("s")) => expression.map(Self::GeneratedStored),
|
||||
(_, None | Some("")) => expression.map(Self::Default),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct DdlTableOptions {
|
||||
pub unlogged: bool,
|
||||
pub partition_key: Option<String>,
|
||||
pub partition: Option<DdlPartition>,
|
||||
}
|
||||
|
||||
pub struct DdlPartition {
|
||||
pub parent_schema: String,
|
||||
pub parent_table: String,
|
||||
pub bound: String,
|
||||
}
|
||||
|
||||
/// What [`postgres_table_ddl`] adds after `create table` so the script rebuilds the table.
|
||||
#[derive(Default)]
|
||||
pub struct DdlExtras {
|
||||
@@ -1021,17 +1090,30 @@ pub fn postgres_table_ddl(
|
||||
columns: &[DdlColumn],
|
||||
constraints: &[(String, String)],
|
||||
indexes: &[String],
|
||||
options: &DdlTableOptions,
|
||||
extras: &DdlExtras,
|
||||
) -> String {
|
||||
let d = DbDriver::Postgres;
|
||||
let partition = options.partition.as_ref();
|
||||
let mut items: Vec<String> = columns
|
||||
.iter()
|
||||
.filter(|c| partition.is_none() || c.not_null || c.value.is_some())
|
||||
.map(|c| {
|
||||
let mut s = format!(" {} {}", quote_ident(d, &c.name), c.data_type);
|
||||
if let Some(v) = &c.default {
|
||||
s.push_str(&format!(" default {v}"));
|
||||
let mut s = format!(" {}", quote_ident(d, &c.name));
|
||||
if partition.is_none() {
|
||||
s.push(' ');
|
||||
s.push_str(&c.data_type);
|
||||
}
|
||||
if c.not_null {
|
||||
match &c.value {
|
||||
Some(DdlColumnValue::Default(v)) => s.push_str(&format!(" default {v}")),
|
||||
Some(DdlColumnValue::IdentityByDefault) => s.push_str(" generated by default as identity"),
|
||||
Some(DdlColumnValue::IdentityAlways) => s.push_str(" generated always as identity"),
|
||||
Some(DdlColumnValue::GeneratedStored(v)) => s.push_str(&format!(" generated always as ({v}) stored")),
|
||||
None => {}
|
||||
}
|
||||
if c.not_null
|
||||
&& !matches!(c.value, Some(DdlColumnValue::IdentityByDefault | DdlColumnValue::IdentityAlways))
|
||||
{
|
||||
s.push_str(" not null");
|
||||
}
|
||||
s
|
||||
@@ -1039,7 +1121,35 @@ pub fn postgres_table_ddl(
|
||||
.collect();
|
||||
items.extend(constraints.iter().map(|(name, def)| format!(" constraint {} {def}", quote_ident(d, name))));
|
||||
let target = qualified(d, schema, table);
|
||||
let mut out = format!("create table {target}\n(\n{}\n);\n", items.join(",\n"));
|
||||
let persistence = if options.unlogged { "unlogged " } else { "" };
|
||||
let mut out = format!("create {persistence}table {target}");
|
||||
if let Some(partition) = partition {
|
||||
let parent = qualified(d, &partition.parent_schema, &partition.parent_table);
|
||||
out.push_str(&format!(" partition of {parent}"));
|
||||
}
|
||||
if partition.is_none() || !items.is_empty() {
|
||||
out.push_str(&format!("\n(\n{}\n)", items.join(",\n")));
|
||||
}
|
||||
if let Some(partition) = partition {
|
||||
out.push_str("\n ");
|
||||
// pg_get_expr deparses bounds as keywords and constants. Preserve quoted constants,
|
||||
// including doubled quotes, while matching the casing of the generated DDL.
|
||||
for (i, part) in partition.bound.split('\'').enumerate() {
|
||||
if i != 0 {
|
||||
out.push('\'');
|
||||
}
|
||||
if i % 2 == 0 {
|
||||
out.push_str(&part.to_ascii_lowercase());
|
||||
} else {
|
||||
out.push_str(part);
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(key) = &options.partition_key {
|
||||
let (method, expression) = key.split_at(key.find(' ').unwrap_or(key.len()));
|
||||
out.push_str(&format!("\n partition by {}{expression}", method.to_ascii_lowercase()));
|
||||
}
|
||||
out.push_str(";\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)));
|
||||
@@ -1416,15 +1526,31 @@ mod tests {
|
||||
assert_eq!(use_schema(DbDriver::Clickhouse, "default"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn postgres_ddl_columns_reads_pg_attribute_not_information_schema() {
|
||||
// `information_schema.columns.data_type` loses what a script needs to recreate the table:
|
||||
// `character varying` without the length, `numeric` without the precision, `ARRAY` for
|
||||
// every array and `USER-DEFINED` for an enum. It also lists only the columns the current
|
||||
// role holds privileges on. The DDL must therefore read `pg_attribute` with
|
||||
// `format_type(atttypid, atttypmod)`, which is what makes `varchar(255)`, `numeric(10,2)`,
|
||||
// `text[]` and an enum name come out as written.
|
||||
let q = postgres_ddl_columns(42, false);
|
||||
assert!(q.contains("format_type(a.atttypid, a.atttypmod)"), "{q}");
|
||||
assert!(q.contains("FROM pg_attribute a"), "{q}");
|
||||
assert!(q.contains("left join pg_attrdef") || q.contains("LEFT JOIN pg_attrdef"), "{q}");
|
||||
assert!(q.contains("attrelid = 42"), "{q}");
|
||||
assert!(!q.contains("information_schema"), "{q}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn postgres_ddl() {
|
||||
let cols = [
|
||||
DdlColumn { name: "id".into(), data_type: "integer".into(), not_null: true, default: None, comment: None },
|
||||
DdlColumn { name: "id".into(), data_type: "integer".into(), not_null: true, value: None, comment: None },
|
||||
DdlColumn {
|
||||
name: "name".into(),
|
||||
data_type: "character varying(40)".into(),
|
||||
not_null: false,
|
||||
default: Some("'x'::character varying".into()),
|
||||
value: Some(DdlColumnValue::Default("'x'::character varying".into())),
|
||||
comment: None,
|
||||
},
|
||||
];
|
||||
@@ -1435,21 +1561,94 @@ mod tests {
|
||||
&cols,
|
||||
&[("t_pkey".into(), "PRIMARY KEY (id)".into())],
|
||||
&["CREATE INDEX t_name ON public.t USING btree (name)".into()],
|
||||
&DdlTableOptions::default(),
|
||||
&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_renders_identity_and_stored_columns() {
|
||||
let columns = [
|
||||
("id_default", "bigint", true, "d", "", Some("ignored()")),
|
||||
("id_always", "bigint", true, "a", "", None),
|
||||
("total", "integer", true, "", "s", Some("qty * price")),
|
||||
]
|
||||
.map(|(name, data_type, not_null, identity, generated, expression)| DdlColumn {
|
||||
name: name.into(),
|
||||
data_type: data_type.into(),
|
||||
not_null,
|
||||
value: DdlColumnValue::from_catalog(Some(identity), Some(generated), expression.map(Into::into)),
|
||||
comment: None,
|
||||
});
|
||||
let ddl =
|
||||
postgres_table_ddl("public", "t", &columns, &[], &[], &DdlTableOptions::default(), &DdlExtras::default());
|
||||
assert_eq!(
|
||||
ddl,
|
||||
concat!(
|
||||
"create table \"public\".\"t\"\n(\n",
|
||||
" \"id_default\" bigint generated by default as identity,\n",
|
||||
" \"id_always\" bigint generated always as identity,\n",
|
||||
" \"total\" integer generated always as (qty * price) stored not null\n",
|
||||
");\n",
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn postgres_ddl_renders_unlogged_partitioned_parent() {
|
||||
let columns =
|
||||
[DdlColumn { name: "Day".into(), data_type: "date".into(), not_null: true, value: None, comment: None }];
|
||||
let options =
|
||||
DdlTableOptions { unlogged: true, partition_key: Some("RANGE (\"Day\")".into()), partition: None };
|
||||
assert_eq!(
|
||||
postgres_table_ddl("public", "events", &columns, &[], &[], &options, &DdlExtras::default()),
|
||||
"create unlogged table \"public\".\"events\"\n(\n \"Day\" date not null\n)\n partition by range (\"Day\");\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn postgres_ddl_renders_partitions_and_preserves_bound_literals() {
|
||||
let columns = [DdlColumn {
|
||||
name: "region".into(),
|
||||
data_type: "text".into(),
|
||||
not_null: false,
|
||||
value: None,
|
||||
comment: None,
|
||||
}];
|
||||
for (bound, rendered) in [
|
||||
("FOR VALUES FROM (MINVALUE) TO ('A) TO (B')", "for values from (minvalue) to ('A) TO (B')"),
|
||||
("FOR VALUES IN ('East''s', 'SOUTH', NULL)", "for values in ('East''s', 'SOUTH', null)"),
|
||||
("FOR VALUES WITH (modulus 2, remainder 0)", "for values with (modulus 2, remainder 0)"),
|
||||
("DEFAULT", "default"),
|
||||
] {
|
||||
let options = DdlTableOptions {
|
||||
partition: Some(DdlPartition {
|
||||
parent_schema: "other".into(),
|
||||
parent_table: "Parent\"Table".into(),
|
||||
bound: bound.into(),
|
||||
}),
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(
|
||||
postgres_table_ddl("public", "child", &columns, &[], &[], &options, &DdlExtras::default()),
|
||||
format!(
|
||||
"create table \"public\".\"child\" partition of \"other\".\"Parent\"\"Table\"\n {rendered};\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: "id".into(), data_type: "integer".into(), not_null: true, value: None, comment: None },
|
||||
DdlColumn {
|
||||
name: "note".into(),
|
||||
data_type: "text".into(),
|
||||
not_null: false,
|
||||
default: None,
|
||||
value: None,
|
||||
comment: Some("what's this".into()),
|
||||
},
|
||||
];
|
||||
@@ -1468,6 +1667,7 @@ mod tests {
|
||||
&cols,
|
||||
&[],
|
||||
&["CREATE INDEX t_note ON public.t USING btree (note)".into()],
|
||||
&DdlTableOptions::default(),
|
||||
&extras
|
||||
),
|
||||
"create table \"public\".\"t\"\n(\n \"id\" integer not null,\n \"note\" text\n);\n\
|
||||
|
||||
@@ -391,9 +391,12 @@ impl Manifest {
|
||||
if !self.capabilities.reasons.is_empty() {
|
||||
self.needs_api("`capabilities.reasons`", 19)?;
|
||||
}
|
||||
let derived = self.derived_capabilities();
|
||||
for (key, text) in &self.capabilities.reasons {
|
||||
if !self.capabilities.all().any(|c| c.to_string() == *key) {
|
||||
return Err(format!("capabilities.reasons: {key:?} is not under `required` or `optional`"));
|
||||
if !self.capabilities.all().chain(&derived).any(|c| c.to_string() == *key) {
|
||||
return Err(format!(
|
||||
"capabilities.reasons: {key:?} is not under `required` or `optional`, nor comes from a contribution"
|
||||
));
|
||||
}
|
||||
if text.trim().is_empty() || text.chars().count() > MAX_CAPABILITY_REASON {
|
||||
return Err(format!(
|
||||
@@ -522,6 +525,17 @@ impl Manifest {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Capabilities the plugin's contributions bring without being listed under `[capabilities]`:
|
||||
/// `java.agent` from `[[contributes.javaAgents]]`, `project.read` from
|
||||
/// `[[contributes.documentIndexers]]` (the extension points in `ide-host` add them to the grant).
|
||||
pub fn derived_capabilities(&self) -> Vec<Capability> {
|
||||
[("javaAgents", Capability::JavaAgent), ("documentIndexers", Capability::ProjectRead)]
|
||||
.into_iter()
|
||||
.filter(|(point, _)| self.contributes.contains_key(*point))
|
||||
.map(|(_, cap)| cap)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The declarations of one extension point: `[[contributes.x]]` gives
|
||||
/// several, `[contributes.x]` one.
|
||||
pub fn declarations(&self, point: &str) -> Vec<toml::Value> {
|
||||
@@ -843,6 +857,17 @@ required = [\"lsp:phoxite\"]
|
||||
assert!(err(&src(&long)).contains("1 to 500 characters"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn capability_reasons_explain_capabilities_that_contributions_bring() {
|
||||
let src = |rest: &str| format!("{}{rest}", BASE.replace("^1.2", "^1.19"));
|
||||
let reason = "[capabilities.reasons]\n\"java.agent\" = \"Captures the SQL MyBatis runs.\"\n";
|
||||
let agent = "[[contributes.javaAgents]]\npath = \"agent.jar\"\n";
|
||||
let m = Manifest::parse(&src(&format!("{reason}{agent}"))).unwrap();
|
||||
assert_eq!(m.derived_capabilities(), [Capability::JavaAgent]);
|
||||
assert_eq!(m.capabilities.reason(&Capability::JavaAgent), Some("Captures the SQL MyBatis runs."));
|
||||
assert!(err(&src(reason)).contains("nor comes from a contribution"), "no javaAgents declaration");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_clipboard_read_capability_needs_api_1_11() {
|
||||
let caps = "[capabilities]\noptional = [\"clipboard.read\"]\n";
|
||||
|
||||
@@ -28,6 +28,7 @@ ide-syntax.workspace = true
|
||||
ide-search.workspace = true
|
||||
ide-lsp.workspace = true
|
||||
ide-vcs.workspace = true
|
||||
ide-svn.workspace = true
|
||||
ide-github.workspace = true
|
||||
ide-dap.workspace = true
|
||||
ide-heap.workspace = true
|
||||
|
||||
@@ -111,6 +111,24 @@ impl AgentSecrets {
|
||||
}
|
||||
}
|
||||
|
||||
impl ide_agent::EnvSecrets for AgentSecrets {
|
||||
fn get(&self, key: &str) -> Option<String> {
|
||||
AgentSecrets::get(self, key)
|
||||
}
|
||||
|
||||
fn set(&self, key: &str, value: &str) -> IdeResult<()> {
|
||||
AgentSecrets::set(self, key, value).map(|_| ())
|
||||
}
|
||||
|
||||
fn delete(&self, key: &str) {
|
||||
AgentSecrets::delete(self, key);
|
||||
}
|
||||
|
||||
fn keys(&self, prefix: &str) -> Vec<String> {
|
||||
AgentSecrets::keys(self, prefix)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -0,0 +1,775 @@
|
||||
//! Per-user OS login / boot service registration for `openidea-server --scheduler`
|
||||
//! (or `<desktop-exe> --scheduler`).
|
||||
//!
|
||||
//! Off by default (`agents.automations.autoStartService = false`). When the user enables it
|
||||
//! and at least one scheduled automation is active, registers the user login service; when
|
||||
//! disabled or when zero scheduled automations remain (after any in-flight claimed runs finish),
|
||||
//! stops and unregisters the service.
|
||||
|
||||
use ide_core::{IdeError, IdeResult, IpcPath};
|
||||
use parking_lot::{Mutex, RwLock};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
|
||||
pub const SERVICE_LABEL: &str = "ai.l0ng.openidea.scheduler";
|
||||
pub const SYSTEMD_UNIT_NAME: &str = "openidea-scheduler.service";
|
||||
const WINDOWS_SCRIPT_NAME: &str = "openidea-scheduler.cmd";
|
||||
const OVERRIDE_ENV: &str = "OPENIDEA_BOOT_SERVICE_DIR";
|
||||
const DISABLE_OS_CALLS_ENV: &str = "OPENIDEA_DISABLE_OS_SERVICE_CALLS";
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum ServicePlatform {
|
||||
Macos,
|
||||
Linux,
|
||||
Windows,
|
||||
Other,
|
||||
}
|
||||
|
||||
impl ServicePlatform {
|
||||
pub fn host() -> Self {
|
||||
if cfg!(target_os = "macos") {
|
||||
Self::Macos
|
||||
} else if cfg!(target_os = "linux") {
|
||||
Self::Linux
|
||||
} else if cfg!(target_os = "windows") {
|
||||
Self::Windows
|
||||
} else {
|
||||
Self::Other
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub type CommandRunner = Arc<dyn Fn(&str, &[&str]) -> std::io::Result<(i32, String, String)> + Send + Sync>;
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct BootServiceManager {
|
||||
sync_lock: Mutex<()>,
|
||||
override_dir: RwLock<Option<PathBuf>>,
|
||||
executable_override: RwLock<Option<PathBuf>>,
|
||||
platform_override: RwLock<Option<ServicePlatform>>,
|
||||
command_runner: RwLock<Option<CommandRunner>>,
|
||||
last_error: Mutex<Option<String>>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct BootServiceState {
|
||||
pub kind: String,
|
||||
pub registered: bool,
|
||||
pub path: Option<IpcPath>,
|
||||
pub error: Option<String>,
|
||||
pub linux_linger_enabled: Option<bool>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum OsServicePresence {
|
||||
RegisteredAndActive,
|
||||
RegisteredIdle,
|
||||
ActiveUnregistered,
|
||||
Absent,
|
||||
}
|
||||
|
||||
impl OsServicePresence {
|
||||
fn is_registered(self) -> bool {
|
||||
matches!(self, Self::RegisteredAndActive | Self::RegisteredIdle)
|
||||
}
|
||||
|
||||
fn is_loaded_or_active(self) -> bool {
|
||||
!matches!(self, Self::Absent)
|
||||
}
|
||||
}
|
||||
|
||||
impl BootServiceManager {
|
||||
pub fn with_override_dir(dir: Option<PathBuf>) -> Self {
|
||||
Self {
|
||||
sync_lock: Mutex::new(()),
|
||||
override_dir: RwLock::new(dir),
|
||||
executable_override: RwLock::new(None),
|
||||
platform_override: RwLock::new(None),
|
||||
command_runner: RwLock::new(None),
|
||||
last_error: Mutex::new(None),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_override_dir(&self, dir: Option<PathBuf>) {
|
||||
*self.override_dir.write() = dir;
|
||||
}
|
||||
|
||||
pub fn set_executable_override(&self, exe: Option<PathBuf>) {
|
||||
*self.executable_override.write() = exe;
|
||||
}
|
||||
|
||||
pub fn set_command_runner_for_test(&self, platform: ServicePlatform, runner: Option<CommandRunner>) {
|
||||
*self.platform_override.write() = runner.as_ref().map(|_| platform);
|
||||
*self.command_runner.write() = runner;
|
||||
}
|
||||
|
||||
fn effective_platform(&self) -> ServicePlatform {
|
||||
self.platform_override.read().unwrap_or_else(ServicePlatform::host)
|
||||
}
|
||||
|
||||
fn effective_override_dir(&self) -> Option<PathBuf> {
|
||||
self.override_dir
|
||||
.read()
|
||||
.clone()
|
||||
.or_else(|| std::env::var_os(OVERRIDE_ENV).filter(|v| !v.is_empty()).map(PathBuf::from))
|
||||
}
|
||||
|
||||
fn uses_os_commands(&self) -> bool {
|
||||
if self.command_runner.read().is_some() {
|
||||
return true;
|
||||
}
|
||||
self.effective_override_dir().is_none() && std::env::var_os(DISABLE_OS_CALLS_ENV).is_none_or(|v| v != "1")
|
||||
}
|
||||
|
||||
fn run_command(&self, program: &str, args: &[&str]) -> IdeResult<(i32, String, String)> {
|
||||
if let Some(runner) = self.command_runner.read().clone() {
|
||||
return runner(program, args).map_err(|e| IdeError::internal(format!("{program} failed to spawn: {e}")));
|
||||
}
|
||||
let out = std::process::Command::new(program)
|
||||
.args(args)
|
||||
.output()
|
||||
.map_err(|e| IdeError::internal(format!("{program} failed to spawn: {e}")))?;
|
||||
let code = out.status.code().unwrap_or(-1);
|
||||
let stdout = String::from_utf8_lossy(&out.stdout).into_owned();
|
||||
let stderr = String::from_utf8_lossy(&out.stderr).into_owned();
|
||||
Ok((code, stdout, stderr))
|
||||
}
|
||||
|
||||
fn run_checked(&self, program: &str, args: &[&str]) -> IdeResult<String> {
|
||||
let (code, stdout, stderr) = self.run_command(program, args)?;
|
||||
if code == 0 {
|
||||
return Ok(stdout);
|
||||
}
|
||||
let detail = stderr.trim();
|
||||
let msg = if detail.is_empty() { stdout.trim() } else { detail };
|
||||
Err(IdeError::internal(format!("{program} {} exited with {code}: {msg}", args.join(" "))))
|
||||
}
|
||||
|
||||
fn scheduler_executable(&self) -> Option<PathBuf> {
|
||||
self.executable_override.read().clone().or_else(|| std::env::current_exe().ok())
|
||||
}
|
||||
|
||||
pub fn service_kind_for(platform: ServicePlatform, remote: bool) -> &'static str {
|
||||
if remote && platform == ServicePlatform::Linux {
|
||||
"systemdUser"
|
||||
} else {
|
||||
match platform {
|
||||
ServicePlatform::Macos => "launchAgent",
|
||||
ServicePlatform::Linux => "systemdUser",
|
||||
ServicePlatform::Windows => "windowsStartup",
|
||||
ServicePlatform::Other => "backgroundHost",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn service_kind(remote: bool) -> &'static str {
|
||||
Self::service_kind_for(ServicePlatform::host(), remote)
|
||||
}
|
||||
|
||||
pub fn service_file_path(&self, home_dir: Option<&Path>) -> Option<PathBuf> {
|
||||
let platform = self.effective_platform();
|
||||
if let Some(dir) = self.effective_override_dir() {
|
||||
let filename = match platform {
|
||||
ServicePlatform::Macos => format!("{SERVICE_LABEL}.plist"),
|
||||
ServicePlatform::Windows => WINDOWS_SCRIPT_NAME.to_owned(),
|
||||
ServicePlatform::Linux | ServicePlatform::Other => SYSTEMD_UNIT_NAME.to_owned(),
|
||||
};
|
||||
return Some(dir.join(filename));
|
||||
}
|
||||
let home = home_dir?;
|
||||
match platform {
|
||||
ServicePlatform::Macos => {
|
||||
Some(home.join("Library").join("LaunchAgents").join(format!("{SERVICE_LABEL}.plist")))
|
||||
}
|
||||
ServicePlatform::Linux => Some(home.join(".config").join("systemd").join("user").join(SYSTEMD_UNIT_NAME)),
|
||||
ServicePlatform::Windows => {
|
||||
let appdata = std::env::var_os("APPDATA")
|
||||
.map(PathBuf::from)
|
||||
.unwrap_or_else(|| home.join("AppData").join("Roaming"));
|
||||
Some(
|
||||
appdata
|
||||
.join("Microsoft")
|
||||
.join("Windows")
|
||||
.join("Start Menu")
|
||||
.join("Programs")
|
||||
.join("Startup")
|
||||
.join(WINDOWS_SCRIPT_NAME),
|
||||
)
|
||||
}
|
||||
ServicePlatform::Other => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn macos_domain() -> String {
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
format!("gui/{}", rustix::process::getuid().as_raw())
|
||||
}
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
{
|
||||
"gui/501".to_owned()
|
||||
}
|
||||
}
|
||||
|
||||
/// Queries the OS service manager, distinguishing confirmed `Absent` from `Err(...)` (unknown
|
||||
/// status, e.g. D-Bus / launchd unreachable) so `sync(..., false)` never deletes the service
|
||||
/// file when status cannot be determined.
|
||||
fn query_os_presence(&self, platform: ServicePlatform) -> IdeResult<OsServicePresence> {
|
||||
if !self.uses_os_commands() {
|
||||
return Ok(OsServicePresence::Absent);
|
||||
}
|
||||
match platform {
|
||||
ServicePlatform::Macos => {
|
||||
let job = format!("{}/{SERVICE_LABEL}", Self::macos_domain());
|
||||
let (code, stdout, stderr) = self.run_command("launchctl", &["print", &job])?;
|
||||
if code == 0 {
|
||||
return Ok(OsServicePresence::RegisteredAndActive);
|
||||
}
|
||||
let combined = format!("{stdout}\n{stderr}");
|
||||
if code == 113 || combined.contains("Could not find service") {
|
||||
return Ok(OsServicePresence::Absent);
|
||||
}
|
||||
let detail = if stderr.trim().is_empty() { stdout.trim() } else { stderr.trim() };
|
||||
Err(IdeError::internal(format!("launchctl print {job} returned unknown status {code}: {detail}")))
|
||||
}
|
||||
ServicePlatform::Linux => {
|
||||
let (en_code, en_out, en_err) =
|
||||
self.run_command("systemctl", &["--user", "is-enabled", SYSTEMD_UNIT_NAME])?;
|
||||
let en_state = en_out.trim();
|
||||
let enabled = if en_code == 0 && matches!(en_state, "enabled" | "enabled-runtime") {
|
||||
true
|
||||
} else if matches!(
|
||||
en_state,
|
||||
"disabled" | "not-found" | "static" | "indirect" | "masked" | "linked" | "generated"
|
||||
) {
|
||||
false
|
||||
} else {
|
||||
let detail = if en_err.trim().is_empty() { en_state } else { en_err.trim() };
|
||||
return Err(IdeError::internal(format!(
|
||||
"systemctl --user is-enabled {SYSTEMD_UNIT_NAME} returned unknown status {en_code}: {detail}"
|
||||
)));
|
||||
};
|
||||
|
||||
let (ac_code, ac_out, ac_err) =
|
||||
self.run_command("systemctl", &["--user", "is-active", SYSTEMD_UNIT_NAME])?;
|
||||
let ac_state = ac_out.trim();
|
||||
let active = if ac_code == 0 && matches!(ac_state, "active" | "activating" | "reloading") {
|
||||
true
|
||||
} else if matches!(ac_state, "inactive" | "failed" | "deactivating") {
|
||||
false
|
||||
} else {
|
||||
let detail = if ac_err.trim().is_empty() { ac_state } else { ac_err.trim() };
|
||||
return Err(IdeError::internal(format!(
|
||||
"systemctl --user is-active {SYSTEMD_UNIT_NAME} returned unknown status {ac_code}: {detail}"
|
||||
)));
|
||||
};
|
||||
|
||||
Ok(match (enabled, active) {
|
||||
(true, true) => OsServicePresence::RegisteredAndActive,
|
||||
(true, false) => OsServicePresence::RegisteredIdle,
|
||||
(false, true) => OsServicePresence::ActiveUnregistered,
|
||||
(false, false) => OsServicePresence::Absent,
|
||||
})
|
||||
}
|
||||
ServicePlatform::Windows | ServicePlatform::Other => Ok(OsServicePresence::Absent),
|
||||
}
|
||||
}
|
||||
|
||||
fn is_os_registered(&self, platform: ServicePlatform, path: &Path) -> bool {
|
||||
if !path.is_file() {
|
||||
return false;
|
||||
}
|
||||
if !self.uses_os_commands() {
|
||||
return true;
|
||||
}
|
||||
match platform {
|
||||
ServicePlatform::Macos | ServicePlatform::Linux => {
|
||||
self.query_os_presence(platform).is_ok_and(OsServicePresence::is_registered)
|
||||
}
|
||||
ServicePlatform::Windows => std::fs::metadata(path).is_ok_and(|m| m.is_file() && m.len() > 0),
|
||||
ServicePlatform::Other => false,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn status(&self, home_dir: Option<&Path>, remote: bool) -> BootServiceState {
|
||||
let platform = self.effective_platform();
|
||||
let path = self.service_file_path(home_dir);
|
||||
let registered = path.as_ref().is_some_and(|p| self.is_os_registered(platform, p));
|
||||
let linux_linger_enabled = if platform == ServicePlatform::Linux { Some(check_linux_linger()) } else { None };
|
||||
BootServiceState {
|
||||
kind: Self::service_kind_for(platform, remote).to_owned(),
|
||||
registered,
|
||||
path: path.map(IpcPath),
|
||||
error: self.last_error.lock().clone(),
|
||||
linux_linger_enabled,
|
||||
}
|
||||
}
|
||||
|
||||
/// Synchronizes the OS user service file and service manager state to match
|
||||
/// `(should_register, base_dir)`. Checks command results, retries activation even when the
|
||||
/// unit/plist file on disk is unchanged, and stops + unloads the worker BEFORE deleting the
|
||||
/// unit/plist file (keeping the file when status is unknown) so failed unregistrations retry.
|
||||
pub fn sync(&self, home_dir: Option<&Path>, base_dir: &Path, should_register: bool) -> IdeResult<BootServiceState> {
|
||||
let _guard = self.sync_lock.lock();
|
||||
let result = self.sync_locked(home_dir, base_dir, should_register);
|
||||
match &result {
|
||||
Ok(_) => *self.last_error.lock() = None,
|
||||
Err(err) => *self.last_error.lock() = Some(err.to_string()),
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
fn sync_locked(
|
||||
&self,
|
||||
home_dir: Option<&Path>,
|
||||
base_dir: &Path,
|
||||
should_register: bool,
|
||||
) -> IdeResult<BootServiceState> {
|
||||
let platform = self.effective_platform();
|
||||
let Some(target) = self.service_file_path(home_dir) else {
|
||||
return Ok(self.status(home_dir, false));
|
||||
};
|
||||
let use_os = self.uses_os_commands();
|
||||
|
||||
if should_register {
|
||||
let exe = self
|
||||
.scheduler_executable()
|
||||
.ok_or_else(|| IdeError::unavailable("cannot locate OpenIDEA executable for --scheduler"))?;
|
||||
let content = render_service_file_for(platform, &exe, base_dir)?;
|
||||
if let Some(parent) = target.parent() {
|
||||
std::fs::create_dir_all(parent)?;
|
||||
}
|
||||
let file_changed = std::fs::read_to_string(&target).ok().as_deref() != Some(content.as_str());
|
||||
if file_changed {
|
||||
ide_vfs::write_atomic(&target, content.as_bytes())?;
|
||||
}
|
||||
if use_os {
|
||||
let already_registered = self.is_os_registered(platform, &target);
|
||||
if file_changed || !already_registered {
|
||||
self.activate_os_service(platform, &target)?;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if use_os {
|
||||
// Propagate unknown status BEFORE touching `target` so the file stays for retry!
|
||||
let presence = self.query_os_presence(platform)?;
|
||||
if presence.is_loaded_or_active() || target.exists() {
|
||||
self.deactivate_os_service(platform, presence)?;
|
||||
}
|
||||
}
|
||||
if target.exists() {
|
||||
match std::fs::remove_file(&target) {
|
||||
Ok(()) => {}
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
|
||||
Err(e) => return Err(e.into()),
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(BootServiceState {
|
||||
kind: Self::service_kind_for(platform, false).to_owned(),
|
||||
registered: self.is_os_registered(platform, &target),
|
||||
path: Some(IpcPath(target)),
|
||||
error: None,
|
||||
linux_linger_enabled: if platform == ServicePlatform::Linux { Some(check_linux_linger()) } else { None },
|
||||
})
|
||||
}
|
||||
|
||||
fn activate_os_service(&self, platform: ServicePlatform, path: &Path) -> IdeResult<()> {
|
||||
let path_str = path
|
||||
.to_str()
|
||||
.ok_or_else(|| IdeError::invalid(format!("service file path is not valid UTF-8: {}", path.display())))?;
|
||||
match platform {
|
||||
ServicePlatform::Macos => {
|
||||
let domain = Self::macos_domain();
|
||||
let job = format!("{domain}/{SERVICE_LABEL}");
|
||||
if self.query_os_presence(platform).is_ok_and(OsServicePresence::is_loaded_or_active) {
|
||||
let _ = self.run_command("launchctl", &["bootout", &job]);
|
||||
}
|
||||
self.run_checked("launchctl", &["bootstrap", &domain, path_str])?;
|
||||
Ok(())
|
||||
}
|
||||
ServicePlatform::Linux => {
|
||||
self.run_checked("systemctl", &["--user", "daemon-reload"])?;
|
||||
self.run_checked("systemctl", &["--user", "enable", SYSTEMD_UNIT_NAME])?;
|
||||
Ok(())
|
||||
}
|
||||
ServicePlatform::Windows | ServicePlatform::Other => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
fn deactivate_os_service(&self, platform: ServicePlatform, presence: OsServicePresence) -> IdeResult<()> {
|
||||
match platform {
|
||||
ServicePlatform::Macos => {
|
||||
let domain = Self::macos_domain();
|
||||
let job = format!("{domain}/{SERVICE_LABEL}");
|
||||
if presence.is_loaded_or_active() {
|
||||
let (code, stdout, stderr) = self.run_command("launchctl", &["bootout", &job])?;
|
||||
let after = self.query_os_presence(platform)?;
|
||||
if code != 0 && after.is_loaded_or_active() {
|
||||
let detail = if stderr.trim().is_empty() { stdout.trim() } else { stderr.trim() };
|
||||
return Err(IdeError::internal(format!(
|
||||
"launchctl bootout {job} exited with {code}: {detail}"
|
||||
)));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
ServicePlatform::Linux => {
|
||||
match presence {
|
||||
OsServicePresence::RegisteredAndActive | OsServicePresence::RegisteredIdle => {
|
||||
self.run_checked("systemctl", &["--user", "disable", "--now", SYSTEMD_UNIT_NAME])?;
|
||||
}
|
||||
OsServicePresence::ActiveUnregistered => {
|
||||
self.run_checked("systemctl", &["--user", "stop", SYSTEMD_UNIT_NAME])?;
|
||||
}
|
||||
OsServicePresence::Absent => {}
|
||||
}
|
||||
self.run_checked("systemctl", &["--user", "daemon-reload"])?;
|
||||
Ok(())
|
||||
}
|
||||
ServicePlatform::Windows | ServicePlatform::Other => Ok(()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn render_service_file(exe: &Path, base_dir: &Path) -> IdeResult<String> {
|
||||
render_service_file_for(ServicePlatform::host(), exe, base_dir)
|
||||
}
|
||||
|
||||
pub fn render_service_file_for(platform: ServicePlatform, exe: &Path, base_dir: &Path) -> IdeResult<String> {
|
||||
match platform {
|
||||
ServicePlatform::Macos => render_macos_plist(exe, base_dir),
|
||||
ServicePlatform::Windows => render_windows_cmd(exe, base_dir),
|
||||
ServicePlatform::Linux | ServicePlatform::Other => render_systemd_unit(exe, base_dir),
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_roundtrip_path<'a>(path: &'a Path, label: &str) -> IdeResult<&'a str> {
|
||||
let s = path.to_str().ok_or_else(|| IdeError::invalid(format!("{label} path is not valid UTF-8")))?;
|
||||
if s.is_empty() {
|
||||
return Err(IdeError::invalid(format!("{label} path cannot be empty")));
|
||||
}
|
||||
let has_root = path.is_absolute() || s.starts_with('/') || (s.len() >= 3 && s.as_bytes()[1] == b':');
|
||||
if !has_root {
|
||||
return Err(IdeError::invalid(format!("{label} path must be absolute: {s}")));
|
||||
}
|
||||
if s.chars().any(char::is_control) {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"{label} path contains control characters or line breaks that cannot round-trip in a service file"
|
||||
)));
|
||||
}
|
||||
Ok(s)
|
||||
}
|
||||
|
||||
pub fn render_macos_plist(exe: &Path, base_dir: &Path) -> IdeResult<String> {
|
||||
let exe_str = validate_roundtrip_path(exe, "scheduler executable")?;
|
||||
let home_str = validate_roundtrip_path(base_dir, "scheduler data")?;
|
||||
let log_path = base_dir.join("logs").join("scheduler.log");
|
||||
let log_str = validate_roundtrip_path(&log_path, "scheduler log")?;
|
||||
let exe_esc = xml_escape(exe_str);
|
||||
let home_esc = xml_escape(home_str);
|
||||
let log_esc = xml_escape(log_str);
|
||||
Ok(format!(
|
||||
r#"<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>Label</key>
|
||||
<string>{SERVICE_LABEL}</string>
|
||||
<key>AssociatedBundleIdentifiers</key>
|
||||
<array>
|
||||
<string>ai.l0ng.openidea</string>
|
||||
</array>
|
||||
<key>LimitLoadToSessionType</key>
|
||||
<string>Aqua</string>
|
||||
<key>ProgramArguments</key>
|
||||
<array>
|
||||
<string>{exe_esc}</string>
|
||||
<string>--scheduler</string>
|
||||
</array>
|
||||
<key>EnvironmentVariables</key>
|
||||
<dict>
|
||||
<key>OPENIDEA_SERVER_HOME</key>
|
||||
<string>{home_esc}</string>
|
||||
</dict>
|
||||
<key>RunAtLoad</key>
|
||||
<true/>
|
||||
<key>StandardErrorPath</key>
|
||||
<string>{log_esc}</string>
|
||||
</dict>
|
||||
</plist>
|
||||
"#
|
||||
))
|
||||
}
|
||||
|
||||
pub fn render_systemd_unit(exe: &Path, base_dir: &Path) -> IdeResult<String> {
|
||||
let exe_raw = validate_roundtrip_path(exe, "scheduler executable")?;
|
||||
let home_raw = validate_roundtrip_path(base_dir, "scheduler data")?;
|
||||
// Both `Environment=` and the executable path (`argv[0]`) of `ExecStart=` are resolved before
|
||||
// `$` variable expansion (`systemd.exec(5)`, `systemd.service(5)`), so `$` stays literal!
|
||||
let exe_str = systemd_escape_literal_quoted(exe_raw);
|
||||
let home_str = systemd_escape_literal_quoted(home_raw);
|
||||
Ok(format!(
|
||||
"[Unit]\n\
|
||||
Description=OpenIDEA Headless Agent Automation Scheduler\n\
|
||||
After=network-online.target\n\
|
||||
\n\
|
||||
[Service]\n\
|
||||
Type=simple\n\
|
||||
Environment=\"OPENIDEA_SERVER_HOME={home_str}\"\n\
|
||||
ExecStart=\"{exe_str}\" --scheduler\n\
|
||||
Restart=on-failure\n\
|
||||
RestartSec=10\n\
|
||||
\n\
|
||||
[Install]\n\
|
||||
WantedBy=default.target\n"
|
||||
))
|
||||
}
|
||||
|
||||
pub fn render_windows_cmd(exe: &Path, base_dir: &Path) -> IdeResult<String> {
|
||||
let exe_raw = validate_roundtrip_path(exe, "scheduler executable")?;
|
||||
let home_raw = validate_roundtrip_path(base_dir, "scheduler data")?;
|
||||
if exe_raw.contains('"') || home_raw.contains('"') {
|
||||
return Err(IdeError::invalid("Windows Startup script path cannot contain '\"'"));
|
||||
}
|
||||
let home_esc = cmd_escape(home_raw);
|
||||
let exe_esc = cmd_escape(exe_raw);
|
||||
Ok(format!("@echo off\r\nset \"OPENIDEA_SERVER_HOME={home_esc}\"\r\nstart \"\" /B \"{exe_esc}\" --scheduler\r\n"))
|
||||
}
|
||||
|
||||
/// Escapes a double-quoted systemd value where `$` is literal (`Environment="KEY=VALUE"` and
|
||||
/// `ExecStart="EXECUTABLE"` `argv[0]`): specifiers (`%` -> `%%`) and C escapes (`\` -> `\\`,
|
||||
/// `"` -> `\"`) are interpreted, while `$` must remain literal.
|
||||
fn systemd_escape_literal_quoted(s: &str) -> String {
|
||||
s.replace('\\', "\\\\").replace('"', "\\\"").replace('%', "%%")
|
||||
}
|
||||
|
||||
fn cmd_escape(s: &str) -> String {
|
||||
s.replace('%', "%%")
|
||||
}
|
||||
|
||||
fn xml_escape(s: &str) -> String {
|
||||
s.replace('&', "&").replace('<', "<").replace('>', ">").replace('"', """).replace('\'', "'")
|
||||
}
|
||||
|
||||
fn check_linux_linger() -> bool {
|
||||
if let Ok(user) = std::env::var("USER").or_else(|_| std::env::var("LOGNAME"))
|
||||
&& !user.is_empty()
|
||||
&& Path::new("/var/lib/systemd/linger").join(user).exists()
|
||||
{
|
||||
return true;
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
|
||||
|
||||
fn unescape_systemd_quoted(s: &str, expand_dollars: bool) -> String {
|
||||
let after_specifiers = s.replace("%%", "%");
|
||||
let after_dollars = if expand_dollars { after_specifiers.replace("$$", "$") } else { after_specifiers };
|
||||
let mut out = String::new();
|
||||
let mut chars = after_dollars.chars();
|
||||
while let Some(c) = chars.next() {
|
||||
if c == '\\' {
|
||||
if let Some(next) = chars.next() {
|
||||
out.push(next);
|
||||
}
|
||||
} else {
|
||||
out.push(c);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn systemd_unit_encodes_environment_and_exec_start_with_distinct_rules_and_rejects_bad_paths() {
|
||||
let exe = Path::new("/opt/openidea$bin/with \"quotes\"\\slash/open%idea");
|
||||
let home = Path::new("/home/dev&co/100%data$dir/\"sub\"\\path");
|
||||
|
||||
let plist = render_macos_plist(exe, home).unwrap();
|
||||
assert!(plist.contains("dev&co"));
|
||||
|
||||
let unit = render_systemd_unit(exe, home).unwrap();
|
||||
let env_line = unit.lines().find(|l| l.starts_with("Environment=")).unwrap();
|
||||
let exec_line = unit.lines().find(|l| l.starts_with("ExecStart=")).unwrap();
|
||||
|
||||
// Both Environment= and ExecStart= argv[0] keep `$` literal while escaping `\`, `"`, and `%`.
|
||||
assert!(env_line.contains("100%%data$dir"));
|
||||
assert!(!env_line.contains("data$$dir"));
|
||||
let env_inner =
|
||||
env_line.strip_prefix("Environment=\"OPENIDEA_SERVER_HOME=").unwrap().strip_suffix('"').unwrap();
|
||||
assert_eq!(unescape_systemd_quoted(env_inner, false), home.to_str().unwrap());
|
||||
|
||||
assert!(exec_line.contains("openidea$bin"));
|
||||
assert!(!exec_line.contains("openidea$$bin"));
|
||||
assert!(exec_line.contains("open%%idea"));
|
||||
let exec_inner = exec_line.strip_prefix("ExecStart=\"").unwrap().strip_suffix("\" --scheduler").unwrap();
|
||||
assert_eq!(unescape_systemd_quoted(exec_inner, false), exe.to_str().unwrap());
|
||||
|
||||
// Windows .cmd rejects embedded quotes and round-trips `%` and `$`.
|
||||
assert!(render_windows_cmd(exe, home).is_err());
|
||||
let win_ok = render_windows_cmd(
|
||||
Path::new(r"C:\Program Files\OpenIDEA\open%idea$1.exe"),
|
||||
Path::new(r"C:\Users\dev&co\100%data$dir"),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(win_ok.contains("100%%data$dir"));
|
||||
assert!(win_ok.contains("open%%idea$1.exe"));
|
||||
|
||||
// Line breaks, NULs, and relative paths are rejected across all platforms.
|
||||
assert!(render_systemd_unit(Path::new("/opt/openidea\nExecStart=/bin/sh"), home).is_err());
|
||||
assert!(render_systemd_unit(exe, Path::new("/home/user\r\nBad=1")).is_err());
|
||||
assert!(render_systemd_unit(Path::new("relative/openidea"), home).is_err());
|
||||
assert!(render_macos_plist(Path::new("/Applications/OpenIDEA\nBad"), home).is_err());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn systemd_unit_rejects_non_utf8_paths() {
|
||||
use std::ffi::OsStr;
|
||||
use std::os::unix::ffi::OsStrExt;
|
||||
let bad = Path::new(OsStr::from_bytes(b"/tmp/openidea-\xff"));
|
||||
assert!(render_systemd_unit(bad, Path::new("/tmp/home")).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn boot_service_checks_real_registration_retries_unchanged_file_and_stops_on_disable() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mgr = BootServiceManager::with_override_dir(Some(tmp.path().join("units")));
|
||||
mgr.set_executable_override(Some(PathBuf::from("/usr/local/bin/openidea-server")));
|
||||
|
||||
let enabled = Arc::new(AtomicBool::new(false));
|
||||
let active = Arc::new(AtomicBool::new(false));
|
||||
let fail_next_enable = Arc::new(AtomicBool::new(true));
|
||||
let fail_next_disable = Arc::new(AtomicBool::new(true));
|
||||
let disable_now_calls = Arc::new(AtomicUsize::new(0));
|
||||
|
||||
let enabled_c = enabled.clone();
|
||||
let active_c = active.clone();
|
||||
let fail_en_c = fail_next_enable.clone();
|
||||
let fail_dis_c = fail_next_disable.clone();
|
||||
let dis_calls_c = disable_now_calls.clone();
|
||||
|
||||
mgr.set_command_runner_for_test(
|
||||
ServicePlatform::Linux,
|
||||
Some(Arc::new(move |prog, args| {
|
||||
assert_eq!(prog, "systemctl");
|
||||
match args {
|
||||
["--user", "is-enabled", u] if *u == SYSTEMD_UNIT_NAME => {
|
||||
if enabled_c.load(Ordering::Acquire) {
|
||||
Ok((0, "enabled\n".into(), String::new()))
|
||||
} else {
|
||||
Ok((1, "disabled\n".into(), String::new()))
|
||||
}
|
||||
}
|
||||
["--user", "is-active", u] if *u == SYSTEMD_UNIT_NAME => {
|
||||
if active_c.load(Ordering::Acquire) {
|
||||
Ok((0, "active\n".into(), String::new()))
|
||||
} else {
|
||||
Ok((3, "inactive\n".into(), String::new()))
|
||||
}
|
||||
}
|
||||
["--user", "daemon-reload"] => Ok((0, String::new(), String::new())),
|
||||
["--user", "enable", u] if *u == SYSTEMD_UNIT_NAME => {
|
||||
if fail_en_c.swap(false, Ordering::AcqRel) {
|
||||
Ok((1, String::new(), "dbus unavailable".into()))
|
||||
} else {
|
||||
enabled_c.store(true, Ordering::Release);
|
||||
active_c.store(true, Ordering::Release);
|
||||
Ok((0, String::new(), String::new()))
|
||||
}
|
||||
}
|
||||
["--user", "disable", "--now", u] if *u == SYSTEMD_UNIT_NAME => {
|
||||
dis_calls_c.fetch_add(1, Ordering::AcqRel);
|
||||
if fail_dis_c.swap(false, Ordering::AcqRel) {
|
||||
Ok((1, String::new(), "unit busy".into()))
|
||||
} else {
|
||||
enabled_c.store(false, Ordering::Release);
|
||||
active_c.store(false, Ordering::Release);
|
||||
Ok((0, String::new(), String::new()))
|
||||
}
|
||||
}
|
||||
other => panic!("unexpected systemctl args: {other:?}"),
|
||||
}
|
||||
})),
|
||||
);
|
||||
|
||||
let home = tmp.path();
|
||||
let data = tmp.path().join("data");
|
||||
std::fs::create_dir_all(&data).unwrap();
|
||||
|
||||
// 1. First sync writes the unit file, `systemctl enable` fails -> returns Err and status is NOT registered
|
||||
// even though the unit file already exists on disk!
|
||||
assert!(mgr.sync(Some(home), &data, true).is_err());
|
||||
let st_failed = mgr.status(Some(home), true);
|
||||
assert!(!st_failed.registered, "file exists alone must not report registered when systemctl failed");
|
||||
assert!(st_failed.error.as_deref().unwrap_or_default().contains("dbus unavailable"));
|
||||
|
||||
// 2. Second sync with identical parameters (unchanged file on disk!) retries `systemctl enable` and succeeds.
|
||||
let st_ok = mgr.sync(Some(home), &data, true).unwrap();
|
||||
assert!(st_ok.registered);
|
||||
assert!(st_ok.error.is_none());
|
||||
|
||||
// 3. Disabling when `systemctl disable --now` fails preserves the unit file and retryability.
|
||||
assert!(mgr.sync(Some(home), &data, false).is_err());
|
||||
assert!(mgr.service_file_path(Some(home)).unwrap().is_file(), "unit file kept so unregister can retry");
|
||||
assert!(mgr.status(Some(home), true).registered);
|
||||
|
||||
// 4. Retrying disable runs `systemctl --user disable --now` (stopping the worker), removes the file, and clears status.
|
||||
let st_off = mgr.sync(Some(home), &data, false).unwrap();
|
||||
assert!(!st_off.registered);
|
||||
assert!(!active.load(Ordering::Acquire), "running worker stopped on disable");
|
||||
assert_eq!(disable_now_calls.load(Ordering::Acquire), 2);
|
||||
assert!(!mgr.service_file_path(Some(home)).unwrap().exists());
|
||||
|
||||
// 5. Unknown OS query status (e.g. D-Bus unreachable) MUST NOT treat worker as absent or delete unit file!
|
||||
let status_unknown = Arc::new(AtomicBool::new(false));
|
||||
let status_unknown_c = status_unknown.clone();
|
||||
let macos_loaded = Arc::new(AtomicBool::new(false));
|
||||
let macos_loaded_c = macos_loaded.clone();
|
||||
mgr.set_command_runner_for_test(
|
||||
ServicePlatform::Macos,
|
||||
Some(Arc::new(move |prog, args| {
|
||||
assert_eq!(prog, "launchctl");
|
||||
match args {
|
||||
["print", _] => {
|
||||
if status_unknown_c.load(Ordering::Acquire) {
|
||||
Ok((1, String::new(), "IPC transport error".into()))
|
||||
} else if macos_loaded_c.load(Ordering::Acquire) {
|
||||
Ok((0, "state = running\n".into(), String::new()))
|
||||
} else {
|
||||
Ok((113, String::new(), "Could not find service\n".into()))
|
||||
}
|
||||
}
|
||||
["bootstrap", _, _] => {
|
||||
macos_loaded_c.store(true, Ordering::Release);
|
||||
Ok((0, String::new(), String::new()))
|
||||
}
|
||||
["bootout", _] => {
|
||||
macos_loaded_c.store(false, Ordering::Release);
|
||||
Ok((0, String::new(), String::new()))
|
||||
}
|
||||
other => panic!("unexpected launchctl args: {other:?}"),
|
||||
}
|
||||
})),
|
||||
);
|
||||
mgr.sync(Some(home), &data, true).unwrap();
|
||||
let plist_path = mgr.service_file_path(Some(home)).unwrap();
|
||||
assert!(plist_path.is_file());
|
||||
|
||||
// Simulate transient launchd query failure on disable -> keeps plist file on disk for retry!
|
||||
status_unknown.store(true, Ordering::Release);
|
||||
assert!(mgr.sync(Some(home), &data, false).is_err());
|
||||
assert!(plist_path.is_file(), "plist must be preserved when OS status is unknown");
|
||||
assert!(macos_loaded.load(Ordering::Acquire));
|
||||
|
||||
// Restore launchd query -> retry succeeds, unloads worker, and deletes plist!
|
||||
status_unknown.store(false, Ordering::Release);
|
||||
mgr.sync(Some(home), &data, false).unwrap();
|
||||
assert!(!macos_loaded.load(Ordering::Acquire));
|
||||
assert!(!plist_path.exists());
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,577 @@
|
||||
//! Cross-process owner locks, abandonment detection, and authenticated loopback RPC bridge
|
||||
//! so live runs owned by `openidea --scheduler` (or `ChatOnly` / headless `AgentManager`s)
|
||||
//! stream `AgentEvent`s to open windows and accept permission approvals (`agent_respond`,
|
||||
//! `agent_answer_question`, `agent_cancel`, `agent_entries`, etc.).
|
||||
|
||||
use ide_agent::{AgentEntry, AgentEvent, AgentManager, AgentPrompt, AgentTask};
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult};
|
||||
use parking_lot::Mutex;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
|
||||
use tokio::net::{TcpListener, TcpStream};
|
||||
use tokio::sync::broadcast;
|
||||
|
||||
const OWNERS_DIR: &str = "owners";
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct OwnerEndpoint {
|
||||
pub instance_id: String,
|
||||
pub pid: u32,
|
||||
pub addr: String,
|
||||
pub token: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct RoutedAgentEvent {
|
||||
pub project_root: Option<PathBuf>,
|
||||
pub event: AgentEvent,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[serde(tag = "op", rename_all = "camelCase", rename_all_fields = "camelCase")]
|
||||
enum PeerRequest {
|
||||
Subscribe { token: String, allowed_roots: Vec<PathBuf>, include_chat_only: bool },
|
||||
Entries { token: String, task: String, subagent: Option<String> },
|
||||
Respond { token: String, task: String, permission: u32, option: Option<String> },
|
||||
AnswerQuestion { token: String, task: String, question: String, answer: Option<String> },
|
||||
Cancel { token: String, task: String, subagent: Option<String> },
|
||||
StopBackground { token: String, task: String, background: String },
|
||||
Prompt { token: String, task: String, prompt: AgentPrompt, now: bool },
|
||||
StopIdleWorker { token: String },
|
||||
}
|
||||
|
||||
pub type ResolveManagerFn = Arc<dyn Fn(&str) -> Option<Arc<AgentManager>> + Send + Sync>;
|
||||
pub type ListLiveTasksFn = Arc<dyn Fn(&[PathBuf], bool) -> Vec<AgentTask> + Send + Sync>;
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[serde(tag = "kind", rename_all = "camelCase", rename_all_fields = "camelCase")]
|
||||
enum PeerStreamItem {
|
||||
Snapshot { tasks: Vec<AgentTask> },
|
||||
Event { event: Box<AgentEvent> },
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[serde(tag = "status", rename_all = "camelCase")]
|
||||
enum PeerReply<T> {
|
||||
Ok { value: T },
|
||||
Err { error: String },
|
||||
}
|
||||
|
||||
pub fn owners_dir(automations_dir: &Path) -> PathBuf {
|
||||
automations_dir.join(OWNERS_DIR)
|
||||
}
|
||||
|
||||
/// Checks whether `owner_id` holds an active OS lock in `automations_dir/owners/`.
|
||||
/// If the lock can be acquired immediately, that process has exited/crashed and its stale
|
||||
/// lock/endpoint files are cleaned up.
|
||||
pub fn is_owner_alive(automations_dir: &Path, self_instance_id: &str, owner_id: &str) -> bool {
|
||||
if owner_id.is_empty() {
|
||||
return false;
|
||||
}
|
||||
if owner_id == self_instance_id {
|
||||
return true;
|
||||
}
|
||||
let dir = owners_dir(automations_dir);
|
||||
let lock_path = dir.join(format!("{owner_id}.lock"));
|
||||
let Ok(file) = std::fs::OpenOptions::new().read(true).write(true).open(&lock_path) else {
|
||||
return false;
|
||||
};
|
||||
if file.try_lock().is_ok() {
|
||||
let _ = file.unlock();
|
||||
drop(file);
|
||||
let _ = std::fs::remove_file(&lock_path);
|
||||
let _ = std::fs::remove_file(dir.join(format!("{owner_id}.json")));
|
||||
false
|
||||
} else {
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
pub fn read_live_endpoint(automations_dir: &Path, self_instance_id: &str, owner_id: &str) -> Option<OwnerEndpoint> {
|
||||
if !is_owner_alive(automations_dir, self_instance_id, owner_id) {
|
||||
return None;
|
||||
}
|
||||
let path = owners_dir(automations_dir).join(format!("{owner_id}.json"));
|
||||
let bytes = std::fs::read(path).ok()?;
|
||||
serde_json::from_slice(&bytes).ok()
|
||||
}
|
||||
|
||||
pub fn list_live_peer_endpoints(automations_dir: &Path, self_instance_id: &str) -> Vec<OwnerEndpoint> {
|
||||
let dir = owners_dir(automations_dir);
|
||||
let Ok(entries) = std::fs::read_dir(&dir) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let mut out = Vec::new();
|
||||
for entry in entries.flatten() {
|
||||
let path = entry.path();
|
||||
if path.extension().is_none_or(|e| e != "json") {
|
||||
continue;
|
||||
}
|
||||
let Some(stem) = path.file_stem().and_then(|s| s.to_str()) else {
|
||||
continue;
|
||||
};
|
||||
if stem == self_instance_id {
|
||||
continue;
|
||||
}
|
||||
if let Some(ep) = read_live_endpoint(automations_dir, self_instance_id, stem) {
|
||||
out.push(ep);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
pub struct OwnerNode {
|
||||
pub instance_id: String,
|
||||
lock_file: Mutex<Option<std::fs::File>>,
|
||||
endpoint_path: Mutex<Option<PathBuf>>,
|
||||
pub events_tx: broadcast::Sender<RoutedAgentEvent>,
|
||||
worker_stop_requested: std::sync::atomic::AtomicBool,
|
||||
subscriptions: Mutex<HashMap<String, CancellationToken>>,
|
||||
}
|
||||
|
||||
impl OwnerNode {
|
||||
pub fn new(instance_id: String) -> Self {
|
||||
let (events_tx, _) = broadcast::channel(512);
|
||||
Self {
|
||||
instance_id,
|
||||
lock_file: Mutex::new(None),
|
||||
endpoint_path: Mutex::new(None),
|
||||
events_tx,
|
||||
worker_stop_requested: std::sync::atomic::AtomicBool::new(false),
|
||||
subscriptions: Mutex::new(HashMap::new()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn worker_stop_requested(&self) -> bool {
|
||||
self.worker_stop_requested.load(std::sync::atomic::Ordering::Acquire)
|
||||
}
|
||||
|
||||
/// Acquires `owners/<instance_id>.lock` (idempotent) so any peer can tell this process is alive.
|
||||
pub fn ensure_lock(&self, automations_dir: &Path) -> IdeResult<()> {
|
||||
let mut guard = self.lock_file.lock();
|
||||
if guard.is_some() {
|
||||
return Ok(());
|
||||
}
|
||||
let dir = owners_dir(automations_dir);
|
||||
std::fs::create_dir_all(&dir)?;
|
||||
let lock_path = dir.join(format!("{}.lock", self.instance_id));
|
||||
let file = std::fs::OpenOptions::new().create(true).read(true).write(true).truncate(false).open(&lock_path)?;
|
||||
file.try_lock()
|
||||
.map_err(|e| IdeError::internal(format!("cannot acquire owner lock {}: {e}", lock_path.display())))?;
|
||||
*guard = Some(file);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Starts the authenticated loopback RPC server for live run events and approvals.
|
||||
pub fn start_server(
|
||||
&self,
|
||||
automations_dir: &Path,
|
||||
runtime: &tokio::runtime::Handle,
|
||||
shutdown: CancellationToken,
|
||||
resolve_mgr: ResolveManagerFn,
|
||||
list_live_tasks: ListLiveTasksFn,
|
||||
node_ref: Arc<OwnerNode>,
|
||||
) {
|
||||
if self.ensure_lock(automations_dir).is_err() {
|
||||
return;
|
||||
}
|
||||
if self.endpoint_path.lock().is_some() {
|
||||
return;
|
||||
}
|
||||
let dir = owners_dir(automations_dir);
|
||||
let token = format!("{}{}", uuid::Uuid::new_v4().simple(), uuid::Uuid::new_v4().simple());
|
||||
let Ok(std_listener) = std::net::TcpListener::bind("127.0.0.1:0") else {
|
||||
return;
|
||||
};
|
||||
if std_listener.set_nonblocking(true).is_err() {
|
||||
return;
|
||||
}
|
||||
let Ok(local_addr) = std_listener.local_addr() else {
|
||||
return;
|
||||
};
|
||||
let instance_id = self.instance_id.clone();
|
||||
let json_path = dir.join(format!("{instance_id}.json"));
|
||||
let ep = OwnerEndpoint {
|
||||
instance_id: instance_id.clone(),
|
||||
pid: std::process::id(),
|
||||
addr: local_addr.to_string(),
|
||||
token: token.clone(),
|
||||
};
|
||||
if let Ok(bytes) = serde_json::to_vec_pretty(&ep) {
|
||||
let _ = write_private_file(&json_path, &bytes);
|
||||
}
|
||||
*self.endpoint_path.lock() = Some(json_path.clone());
|
||||
|
||||
runtime.spawn(async move {
|
||||
let Ok(listener) = TcpListener::from_std(std_listener) else {
|
||||
let _ = std::fs::remove_file(&json_path);
|
||||
return;
|
||||
};
|
||||
|
||||
loop {
|
||||
tokio::select! {
|
||||
_ = shutdown.cancelled() => break,
|
||||
accepted = listener.accept() => {
|
||||
let Ok((stream, _)) = accepted else { continue };
|
||||
let token_c = token.clone();
|
||||
let resolve_c = resolve_mgr.clone();
|
||||
let list_c = list_live_tasks.clone();
|
||||
let shutdown_c = shutdown.clone();
|
||||
let node_c = node_ref.clone();
|
||||
tokio::spawn(async move {
|
||||
handle_peer_conn(stream, token_c, resolve_c, list_c, shutdown_c, node_c).await;
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
let _ = std::fs::remove_file(&json_path);
|
||||
});
|
||||
}
|
||||
|
||||
pub fn stop(&self, automations_dir: &Path) {
|
||||
for (_, cancel) in self.subscriptions.lock().drain() {
|
||||
cancel.cancel();
|
||||
}
|
||||
if let Some(ep_path) = self.endpoint_path.lock().take() {
|
||||
let _ = std::fs::remove_file(ep_path);
|
||||
}
|
||||
if let Some(file) = self.lock_file.lock().take() {
|
||||
let _ = file.unlock();
|
||||
}
|
||||
let _ = std::fs::remove_file(owners_dir(automations_dir).join(format!("{}.lock", self.instance_id)));
|
||||
}
|
||||
|
||||
pub fn replace_subscriber(&self, subscriber: &str) -> CancellationToken {
|
||||
let token = CancellationToken::new();
|
||||
if let Some(prev) = self.subscriptions.lock().insert(subscriber.to_owned(), token.clone()) {
|
||||
prev.cancel();
|
||||
}
|
||||
token
|
||||
}
|
||||
|
||||
pub fn unsubscribe(&self, subscriber: &str) {
|
||||
if let Some(prev) = self.subscriptions.lock().remove(subscriber) {
|
||||
prev.cancel();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn write_private_file(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::io::Write;
|
||||
use std::os::unix::fs::OpenOptionsExt;
|
||||
let mut f = std::fs::OpenOptions::new().create(true).write(true).truncate(true).mode(0o600).open(path)?;
|
||||
f.write_all(bytes)?;
|
||||
f.sync_all()
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
{
|
||||
std::fs::write(path, bytes)
|
||||
}
|
||||
}
|
||||
|
||||
async fn handle_peer_conn(
|
||||
stream: TcpStream,
|
||||
expected_token: String,
|
||||
resolve_mgr: ResolveManagerFn,
|
||||
list_live_tasks: ListLiveTasksFn,
|
||||
shutdown: CancellationToken,
|
||||
node: Arc<OwnerNode>,
|
||||
) {
|
||||
let (reader, mut writer) = stream.into_split();
|
||||
let mut lines = BufReader::new(reader).lines();
|
||||
let Ok(Some(first_line)) = lines.next_line().await else {
|
||||
return;
|
||||
};
|
||||
let Ok(req) = serde_json::from_str::<PeerRequest>(&first_line) else {
|
||||
return;
|
||||
};
|
||||
|
||||
let req_token = match &req {
|
||||
PeerRequest::Subscribe { token, .. }
|
||||
| PeerRequest::Entries { token, .. }
|
||||
| PeerRequest::Respond { token, .. }
|
||||
| PeerRequest::AnswerQuestion { token, .. }
|
||||
| PeerRequest::Cancel { token, .. }
|
||||
| PeerRequest::StopBackground { token, .. }
|
||||
| PeerRequest::Prompt { token, .. }
|
||||
| PeerRequest::StopIdleWorker { token } => token,
|
||||
};
|
||||
if req_token != &expected_token {
|
||||
let _ = write_json_line(&mut writer, &PeerReply::<()>::err("unauthorized")).await;
|
||||
return;
|
||||
}
|
||||
|
||||
match req {
|
||||
PeerRequest::Subscribe { allowed_roots, include_chat_only, .. } => {
|
||||
let mut rx = node.events_tx.subscribe();
|
||||
let canon_allowed: Vec<PathBuf> =
|
||||
allowed_roots.into_iter().map(|p| dunce::canonicalize(&p).unwrap_or(p)).collect();
|
||||
let initial = list_live_tasks(&canon_allowed, include_chat_only);
|
||||
if write_json_line(&mut writer, &PeerStreamItem::Snapshot { tasks: initial }).await.is_err() {
|
||||
return;
|
||||
}
|
||||
loop {
|
||||
tokio::select! {
|
||||
_ = shutdown.cancelled() => break,
|
||||
recv = rx.recv() => {
|
||||
match recv {
|
||||
Ok(routed) => {
|
||||
let matches = match &routed.project_root {
|
||||
None => include_chat_only,
|
||||
Some(actual) => {
|
||||
let cand = dunce::canonicalize(actual).unwrap_or_else(|_| actual.clone());
|
||||
canon_allowed.iter().any(|w| w == &cand)
|
||||
}
|
||||
};
|
||||
if matches
|
||||
&& write_json_line(
|
||||
&mut writer,
|
||||
&PeerStreamItem::Event { event: Box::new(routed.event) },
|
||||
)
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
Err(broadcast::error::RecvError::Lagged(_)) => continue,
|
||||
Err(broadcast::error::RecvError::Closed) => break,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
PeerRequest::Entries { task, subagent, .. } => {
|
||||
let res = match resolve_mgr(&task) {
|
||||
Some(mgr) => tokio::task::spawn_blocking(move || mgr.entries(&task, subagent))
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()))
|
||||
.and_then(|r| r),
|
||||
None => Err(IdeError::not_found(format!("unknown task {task}"))),
|
||||
};
|
||||
let _ = write_json_line(&mut writer, &PeerReply::from_res(res)).await;
|
||||
}
|
||||
PeerRequest::Respond { task, permission, option, .. } => {
|
||||
let res = match resolve_mgr(&task) {
|
||||
Some(mgr) => mgr.respond(&task, permission, option),
|
||||
None => Err(IdeError::not_found(format!("unknown task {task}"))),
|
||||
};
|
||||
let _ = write_json_line(&mut writer, &PeerReply::from_res(res)).await;
|
||||
}
|
||||
PeerRequest::AnswerQuestion { task, question, answer, .. } => {
|
||||
let res = match resolve_mgr(&task) {
|
||||
Some(mgr) => mgr.answer_question(&task, &question, answer).await,
|
||||
None => Err(IdeError::not_found(format!("unknown task {task}"))),
|
||||
};
|
||||
let _ = write_json_line(&mut writer, &PeerReply::from_res(res)).await;
|
||||
}
|
||||
PeerRequest::Cancel { task, subagent, .. } => {
|
||||
let res = match resolve_mgr(&task) {
|
||||
Some(mgr) => mgr.cancel(&task, subagent),
|
||||
None => Err(IdeError::not_found(format!("unknown task {task}"))),
|
||||
};
|
||||
let _ = write_json_line(&mut writer, &PeerReply::from_res(res)).await;
|
||||
}
|
||||
PeerRequest::StopBackground { task, background, .. } => {
|
||||
let res = match resolve_mgr(&task) {
|
||||
Some(mgr) => mgr.stop_background(&task, &background).await,
|
||||
None => Err(IdeError::not_found(format!("unknown task {task}"))),
|
||||
};
|
||||
let _ = write_json_line(&mut writer, &PeerReply::from_res(res)).await;
|
||||
}
|
||||
PeerRequest::Prompt { task, prompt, now, .. } => {
|
||||
let res = match resolve_mgr(&task) {
|
||||
Some(mgr) => mgr.prompt(&task, prompt, now).await,
|
||||
None => Err(IdeError::not_found(format!("unknown task {task}"))),
|
||||
};
|
||||
let _ = write_json_line(&mut writer, &PeerReply::from_res(res)).await;
|
||||
}
|
||||
PeerRequest::StopIdleWorker { .. } => {
|
||||
node.worker_stop_requested.store(true, std::sync::atomic::Ordering::Release);
|
||||
let _ = write_json_line(&mut writer, &PeerReply::from_res(Ok(()))).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> PeerReply<T> {
|
||||
fn from_res(res: IdeResult<T>) -> Self {
|
||||
match res {
|
||||
Ok(value) => Self::Ok { value },
|
||||
Err(e) => Self::Err { error: e.to_string() },
|
||||
}
|
||||
}
|
||||
|
||||
fn err(msg: &str) -> Self {
|
||||
Self::Err { error: msg.to_owned() }
|
||||
}
|
||||
}
|
||||
|
||||
async fn write_json_line<W: AsyncWriteExt + Unpin, T: Serialize>(writer: &mut W, msg: &T) -> std::io::Result<()> {
|
||||
let mut line = serde_json::to_vec(msg).map_err(std::io::Error::other)?;
|
||||
line.push(b'\n');
|
||||
writer.write_all(&line).await?;
|
||||
writer.flush().await
|
||||
}
|
||||
|
||||
async fn call_peer<T: for<'de> Deserialize<'de>>(ep: &OwnerEndpoint, req: &PeerRequest) -> IdeResult<T> {
|
||||
let mut stream = TcpStream::connect(&ep.addr)
|
||||
.await
|
||||
.map_err(|e| IdeError::unavailable(format!("cannot reach live automation worker at {}: {e}", ep.addr)))?;
|
||||
write_json_line(&mut stream, req)
|
||||
.await
|
||||
.map_err(|e| IdeError::unavailable(format!("failed sending request to automation worker: {e}")))?;
|
||||
let mut lines = BufReader::new(stream).lines();
|
||||
let raw = lines
|
||||
.next_line()
|
||||
.await
|
||||
.map_err(|e| IdeError::unavailable(format!("failed reading automation worker reply: {e}")))?
|
||||
.ok_or_else(|| IdeError::unavailable("automation worker closed connection without replying"))?;
|
||||
match serde_json::from_str::<PeerReply<T>>(&raw).map_err(|e| IdeError::internal(e.to_string()))? {
|
||||
PeerReply::Ok { value } => Ok(value),
|
||||
PeerReply::Err { error } => Err(IdeError::internal(error)),
|
||||
}
|
||||
}
|
||||
|
||||
fn call_peer_sync<T: for<'de> Deserialize<'de>>(ep: &OwnerEndpoint, req: &PeerRequest) -> IdeResult<T> {
|
||||
use std::io::{BufRead, Write};
|
||||
let addr: std::net::SocketAddr = ep
|
||||
.addr
|
||||
.parse()
|
||||
.map_err(|e| IdeError::internal(format!("invalid automation worker address {}: {e}", ep.addr)))?;
|
||||
let mut stream = std::net::TcpStream::connect_timeout(&addr, std::time::Duration::from_secs(3))
|
||||
.map_err(|e| IdeError::unavailable(format!("cannot reach live automation worker at {}: {e}", ep.addr)))?;
|
||||
let _ = stream.set_read_timeout(Some(std::time::Duration::from_secs(5)));
|
||||
let _ = stream.set_write_timeout(Some(std::time::Duration::from_secs(5)));
|
||||
let mut line = serde_json::to_vec(req).map_err(|e| IdeError::internal(e.to_string()))?;
|
||||
line.push(b'\n');
|
||||
stream
|
||||
.write_all(&line)
|
||||
.and_then(|()| stream.flush())
|
||||
.map_err(|e| IdeError::unavailable(format!("failed sending request to automation worker: {e}")))?;
|
||||
let mut reader = std::io::BufReader::new(stream);
|
||||
let mut raw = String::new();
|
||||
reader
|
||||
.read_line(&mut raw)
|
||||
.map_err(|e| IdeError::unavailable(format!("failed reading automation worker reply: {e}")))?;
|
||||
if raw.trim().is_empty() {
|
||||
return Err(IdeError::unavailable("automation worker closed connection without replying"));
|
||||
}
|
||||
match serde_json::from_str::<PeerReply<T>>(&raw).map_err(|e| IdeError::internal(e.to_string()))? {
|
||||
PeerReply::Ok { value } => Ok(value),
|
||||
PeerReply::Err { error } => Err(IdeError::internal(error)),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn peer_entries(ep: &OwnerEndpoint, task: String, subagent: Option<String>) -> IdeResult<Vec<AgentEntry>> {
|
||||
call_peer(ep, &PeerRequest::Entries { token: ep.token.clone(), task, subagent }).await
|
||||
}
|
||||
|
||||
pub fn peer_respond(
|
||||
_runtime: &tokio::runtime::Handle,
|
||||
ep: OwnerEndpoint,
|
||||
task: String,
|
||||
permission: u32,
|
||||
option: Option<String>,
|
||||
) -> IdeResult<()> {
|
||||
let token = ep.token.clone();
|
||||
call_peer_sync(&ep, &PeerRequest::Respond { token, task, permission, option })
|
||||
}
|
||||
|
||||
pub async fn peer_answer_question(
|
||||
ep: &OwnerEndpoint,
|
||||
task: String,
|
||||
question: String,
|
||||
answer: Option<String>,
|
||||
) -> IdeResult<()> {
|
||||
call_peer(ep, &PeerRequest::AnswerQuestion { token: ep.token.clone(), task, question, answer }).await
|
||||
}
|
||||
|
||||
pub fn peer_cancel(
|
||||
_runtime: &tokio::runtime::Handle,
|
||||
ep: OwnerEndpoint,
|
||||
task: String,
|
||||
subagent: Option<String>,
|
||||
) -> IdeResult<()> {
|
||||
let token = ep.token.clone();
|
||||
call_peer_sync(&ep, &PeerRequest::Cancel { token, task, subagent })
|
||||
}
|
||||
|
||||
pub async fn peer_stop_background(ep: &OwnerEndpoint, task: String, background: String) -> IdeResult<()> {
|
||||
call_peer(ep, &PeerRequest::StopBackground { token: ep.token.clone(), task, background }).await
|
||||
}
|
||||
|
||||
pub async fn peer_prompt(ep: &OwnerEndpoint, task: String, prompt: AgentPrompt, now: bool) -> IdeResult<()> {
|
||||
call_peer(ep, &PeerRequest::Prompt { token: ep.token.clone(), task, prompt, now }).await
|
||||
}
|
||||
|
||||
pub fn notify_peers_stop_if_headless(runtime: &tokio::runtime::Handle, endpoints: Vec<OwnerEndpoint>) {
|
||||
for ep in endpoints {
|
||||
runtime.spawn(async move {
|
||||
let token = ep.token.clone();
|
||||
let _: IdeResult<()> = call_peer(&ep, &PeerRequest::StopIdleWorker { token }).await;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// Connects to `ep`, fetches its initial live task snapshot synchronously (with a short timeout),
|
||||
/// and spawns an async forwarder streaming subsequent `AgentEvent`s until `cancel` triggers.
|
||||
pub fn attach_peer_stream(
|
||||
runtime: &tokio::runtime::Handle,
|
||||
ep: OwnerEndpoint,
|
||||
allowed_roots: Vec<PathBuf>,
|
||||
include_chat_only: bool,
|
||||
cancel: CancellationToken,
|
||||
on_event: Arc<dyn Fn(AgentEvent) + Send + Sync>,
|
||||
) -> Vec<AgentTask> {
|
||||
let (snap_tx, snap_rx) = std::sync::mpsc::channel();
|
||||
runtime.spawn(async move {
|
||||
let connect_fut = TcpStream::connect(&ep.addr);
|
||||
let Ok(Ok(mut stream)) = tokio::time::timeout(std::time::Duration::from_secs(2), connect_fut).await else {
|
||||
let _ = snap_tx.send(Vec::new());
|
||||
return;
|
||||
};
|
||||
let req = PeerRequest::Subscribe { token: ep.token.clone(), allowed_roots, include_chat_only };
|
||||
if write_json_line(&mut stream, &req).await.is_err() {
|
||||
let _ = snap_tx.send(Vec::new());
|
||||
return;
|
||||
}
|
||||
let mut lines = BufReader::new(stream).lines();
|
||||
match tokio::time::timeout(std::time::Duration::from_secs(2), lines.next_line()).await {
|
||||
Ok(Ok(Some(first))) => match serde_json::from_str::<PeerStreamItem>(&first) {
|
||||
Ok(PeerStreamItem::Snapshot { tasks }) => {
|
||||
let _ = snap_tx.send(tasks);
|
||||
}
|
||||
_ => {
|
||||
let _ = snap_tx.send(Vec::new());
|
||||
return;
|
||||
}
|
||||
},
|
||||
_ => {
|
||||
let _ = snap_tx.send(Vec::new());
|
||||
return;
|
||||
}
|
||||
}
|
||||
loop {
|
||||
tokio::select! {
|
||||
_ = cancel.cancelled() => break,
|
||||
next = lines.next_line() => {
|
||||
match next {
|
||||
Ok(Some(line)) => {
|
||||
if let Ok(PeerStreamItem::Event { event }) = serde_json::from_str::<PeerStreamItem>(&line) {
|
||||
on_event(*event);
|
||||
}
|
||||
}
|
||||
_ => break,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
snap_rx.recv_timeout(std::time::Duration::from_secs(2)).unwrap_or_default()
|
||||
}
|
||||
@@ -18,6 +18,7 @@ use std::sync::{Arc, OnceLock};
|
||||
|
||||
enum Mode {
|
||||
Stdio,
|
||||
Scheduler,
|
||||
#[cfg(unix)]
|
||||
Daemon(PathBuf, ide_host::daemon::BuildId),
|
||||
}
|
||||
@@ -29,6 +30,7 @@ usage:
|
||||
openidea-server --web [options] [<project>]
|
||||
openidea-server --stdio
|
||||
openidea-server --attach <project-path>
|
||||
openidea-server --scheduler
|
||||
openidea-server --mcp-stdio [--project <path>]
|
||||
openidea-server --connect <host> <port>
|
||||
openidea-server --version
|
||||
@@ -233,6 +235,7 @@ fn main() {
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
[flag, _] if flag == "--attach" => Mode::Stdio,
|
||||
_ if args.iter().any(|a| a == "--scheduler") => Mode::Scheduler,
|
||||
_ if args.iter().any(|a| a == "--stdio") => Mode::Stdio,
|
||||
_ => {
|
||||
print_usage();
|
||||
@@ -292,17 +295,21 @@ async fn run(base: PathBuf, mode: Mode) -> i32 {
|
||||
let peer = Arc::new(OnceLock::new());
|
||||
let sink_peer = peer.clone();
|
||||
let plugins_data = data_dir.clone();
|
||||
let host = Arc::new(Host::new(HostConfig {
|
||||
config_dir,
|
||||
local_data_dir: data_dir.clone(),
|
||||
data_dir,
|
||||
languages,
|
||||
syntax: Arc::default(),
|
||||
sink_for: Box::new(move |window| rpc::event_sink(sink_peer.clone(), Some(window.to_owned()))),
|
||||
owner: |w| w,
|
||||
runtime: tokio::runtime::Handle::current(),
|
||||
project_environment: true,
|
||||
}));
|
||||
let host = Arc::new(
|
||||
Host::new(HostConfig {
|
||||
config_dir,
|
||||
local_data_dir: data_dir.clone(),
|
||||
data_dir,
|
||||
languages,
|
||||
syntax: Arc::default(),
|
||||
sink_for: Box::new(move |window| rpc::event_sink(sink_peer.clone(), Some(window.to_owned()))),
|
||||
owner: |w| w,
|
||||
runtime: tokio::runtime::Handle::current(),
|
||||
project_environment: true,
|
||||
})
|
||||
// The client answers no svn prompts here: svn runs non-interactively.
|
||||
.with_subversion(false),
|
||||
);
|
||||
start_mcp(&host, &base);
|
||||
let plugins = start_plugins(&plugins_data, &host, peer.clone());
|
||||
inherit_trust(&host);
|
||||
@@ -312,23 +319,85 @@ async fn run(base: PathBuf, mode: Mode) -> i32 {
|
||||
shutdown_all(&host, plugins.as_ref()).await;
|
||||
0
|
||||
}
|
||||
#[cfg(unix)]
|
||||
Mode::Daemon(socket, build) => {
|
||||
let peer = Arc::new(rpc::PeerSlot::default());
|
||||
let sink_peer = peer.clone();
|
||||
let plugins_data = data_dir.clone();
|
||||
Mode::Scheduler => {
|
||||
let host = Arc::new(Host::new(HostConfig {
|
||||
config_dir,
|
||||
local_data_dir: data_dir.clone(),
|
||||
data_dir,
|
||||
languages,
|
||||
syntax: Arc::default(),
|
||||
sink_for: Box::new(move |window| rpc::event_sink(sink_peer.clone(), Some(window.to_owned()))),
|
||||
sink_for: Box::new(|_| Arc::new(ide_core::NullSink)),
|
||||
owner: |w| w,
|
||||
runtime: tokio::runtime::Handle::current(),
|
||||
project_environment: true,
|
||||
}));
|
||||
start_mcp(&host, &base);
|
||||
inherit_trust(&host);
|
||||
host.automations.set_headless_worker_mode(true);
|
||||
host.automations.start(&host);
|
||||
tracing::info!("openidea-server {} headless scheduler started", env!("CARGO_PKG_VERSION"));
|
||||
let mut idle_ticks = 0u32;
|
||||
let mut check = tokio::time::interval(std::time::Duration::from_secs(5));
|
||||
#[cfg(unix)]
|
||||
let mut terminate =
|
||||
tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()).expect("SIGTERM listener");
|
||||
loop {
|
||||
#[cfg(unix)]
|
||||
tokio::select! {
|
||||
_ = tokio::signal::ctrl_c() => break,
|
||||
_ = terminate.recv() => break,
|
||||
_ = check.tick() => {}
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
tokio::select! {
|
||||
_ = tokio::signal::ctrl_c() => break,
|
||||
_ = check.tick() => {}
|
||||
}
|
||||
let service_enabled = ide_workspace::SettingsStore::load(&host.config_dir, None)
|
||||
.effective()
|
||||
.agents
|
||||
.automations
|
||||
.auto_start_service;
|
||||
let running = host.automations.has_running_runs();
|
||||
if host.automations.worker_stop_requested() || !service_enabled {
|
||||
if !running {
|
||||
tracing::info!("headless scheduler login service disabled; exiting");
|
||||
break;
|
||||
}
|
||||
} else if host.automations.has_enabled_schedules() || running {
|
||||
idle_ticks = 0;
|
||||
} else {
|
||||
idle_ticks += 1;
|
||||
if idle_ticks >= 3 {
|
||||
tracing::info!("no enabled automations remain; headless scheduler exiting");
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
shutdown_all(&host, None).await;
|
||||
0
|
||||
}
|
||||
#[cfg(unix)]
|
||||
Mode::Daemon(socket, build) => {
|
||||
let peer = Arc::new(rpc::PeerSlot::default());
|
||||
let sink_peer = peer.clone();
|
||||
let plugins_data = data_dir.clone();
|
||||
let host = Arc::new(
|
||||
Host::new(HostConfig {
|
||||
config_dir,
|
||||
local_data_dir: data_dir.clone(),
|
||||
data_dir,
|
||||
languages,
|
||||
syntax: Arc::default(),
|
||||
sink_for: Box::new(move |window| rpc::event_sink(sink_peer.clone(), Some(window.to_owned()))),
|
||||
owner: |w| w,
|
||||
runtime: tokio::runtime::Handle::current(),
|
||||
project_environment: true,
|
||||
})
|
||||
// The client answers no svn prompts here: svn runs non-interactively.
|
||||
.with_subversion(false),
|
||||
);
|
||||
start_mcp(&host, &base);
|
||||
let plugins = start_plugins(&plugins_data, &host, peer.clone());
|
||||
inherit_trust(&host);
|
||||
tracing::info!("openidea-server {} daemon ready at {}", env!("CARGO_PKG_VERSION"), socket.display());
|
||||
|
||||
@@ -398,6 +398,7 @@ pub async fn serve(
|
||||
};
|
||||
|
||||
let shutdown = CancellationToken::new();
|
||||
host.automations.start(&host);
|
||||
let idle_policy = RemoteIdlePolicy { override_seconds: idle_override() };
|
||||
let mut check = tokio::time::interval(Duration::from_secs(idle_policy.override_seconds.unwrap_or(5).min(5)));
|
||||
let mut idle = None;
|
||||
@@ -541,6 +542,7 @@ fn has_live_work(host: &Host) -> bool {
|
||||
!host.terminals.list().is_empty()
|
||||
|| host.processes.has_live_runs()
|
||||
|| !host.debugger.sessions(None).is_empty()
|
||||
|| host.automations.keeps_remote_daemon_alive(host)
|
||||
|| host
|
||||
.projects()
|
||||
.iter()
|
||||
|
||||
@@ -1601,15 +1601,21 @@ mod tests {
|
||||
let text = "a\n b\nc\nd\n e\n";
|
||||
let formatted = "a\nb\nc\nd\ne\n";
|
||||
let whole = vec![TextEdit { range: Range::new(Pos::new(0, 0), Pos::new(5, 0)), new_text: formatted.into() }];
|
||||
let started = std::time::Instant::now();
|
||||
let edits = minimal_edits(text, whole);
|
||||
assert_eq!(
|
||||
edits,
|
||||
[
|
||||
TextEdit { range: Range::new(Pos::new(1, 0), Pos::new(1, 2)), new_text: String::new() },
|
||||
TextEdit { range: Range::new(Pos::new(4, 0), Pos::new(4, 2)), new_text: String::new() },
|
||||
]
|
||||
);
|
||||
// Past the diff budget (a loaded machine) the regions may merge, still correctly.
|
||||
if started.elapsed() < ide_text::DIFF_BUDGET {
|
||||
assert_eq!(
|
||||
edits,
|
||||
[
|
||||
TextEdit { range: Range::new(Pos::new(1, 0), Pos::new(1, 2)), new_text: String::new() },
|
||||
TextEdit { range: Range::new(Pos::new(4, 0), Pos::new(4, 2)), new_text: String::new() },
|
||||
]
|
||||
);
|
||||
}
|
||||
assert_eq!(after(text, &edits), formatted);
|
||||
// Merged or not, the edits stay between the first and the last changed line.
|
||||
assert!(edits[0].range.start >= Pos::new(1, 0) && edits[edits.len() - 1].range.end <= Pos::new(4, 2));
|
||||
// Single-line edits are already minimal and pass through.
|
||||
let small = vec![TextEdit { range: Range::new(Pos::new(1, 0), Pos::new(1, 2)), new_text: String::new() }];
|
||||
assert_eq!(minimal_edits(text, small.clone()), small);
|
||||
@@ -1660,11 +1666,17 @@ mod tests {
|
||||
let text = "<?php\n$x = 1;\n$yyy = 2;\n$a = [\n 'a' => 1,\n 'bbb' => 2,\n];\n";
|
||||
// PHP-CS-Fixer formats the whole file (here: adds a line at the top) whatever the selection.
|
||||
let formatted = format!("<?php\n\ndeclare(strict_types=1);\n{}", &text["<?php\n".len()..]);
|
||||
let started = std::time::Instant::now();
|
||||
let edits = whole_file(text, &formatted);
|
||||
// Lines 3..=6 select the array, up to the start of the line after it.
|
||||
let range = Range::new(Pos::new(3, 0), Pos::new(7, 0));
|
||||
let aligned = align_formatted(&syntax, &php, text, edits, Some(range), ALIGN).unwrap();
|
||||
assert_eq!(aligned.len(), 2, "one edit per changed region: {aligned:?}");
|
||||
// Past the diff budget (a loaded machine) the regions may merge, still correctly.
|
||||
if started.elapsed() < ide_text::DIFF_BUDGET {
|
||||
assert_eq!(aligned.len(), 2, "one edit per changed region: {aligned:?}");
|
||||
}
|
||||
// Merged or not, the edits leave the unchanged first and last lines alone.
|
||||
assert!(aligned[0].range.start >= Pos::new(1, 0) && aligned[aligned.len() - 1].range.end <= Pos::new(6, 0));
|
||||
assert_eq!(
|
||||
after(text, &aligned),
|
||||
"<?php\n\ndeclare(strict_types=1);\n$x = 1;\n$yyy = 2;\n$a = [\n 'a' => 1,\n 'bbb' => 2,\n];\n"
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
//! runs one on a remote machine and serves it over JSON-RPC ([`rpc`]).
|
||||
|
||||
pub mod agent_secrets;
|
||||
pub mod automations;
|
||||
pub mod catalogue;
|
||||
#[cfg(unix)]
|
||||
pub mod daemon;
|
||||
@@ -27,6 +28,7 @@ pub mod relay;
|
||||
mod requests;
|
||||
pub mod rpc;
|
||||
pub mod shell_env;
|
||||
pub mod svn;
|
||||
mod swiftlint;
|
||||
pub mod trust;
|
||||
mod ts_code_style;
|
||||
@@ -90,6 +92,10 @@ impl HostConfig {
|
||||
|
||||
pub struct Host {
|
||||
local_database_tunnels: bool,
|
||||
/// Finders of non-Git working copies ([`Host::with_vcs_provider`]); Git is built in.
|
||||
pub(crate) vcs_providers: Vec<Arc<dyn ide_vcs::BackendProvider>>,
|
||||
/// Subversion is on ([`Host::with_subversion`]); `Some(true)` shows svn's prompts in dialogs.
|
||||
pub(crate) subversion: Option<bool>,
|
||||
pub(crate) mcp_executable: Arc<RwLock<Option<PathBuf>>>,
|
||||
pub mcp: mcp::McpService,
|
||||
plugin_host: RwLock<std::sync::Weak<plugins::PluginHost>>,
|
||||
@@ -102,9 +108,12 @@ pub struct Host {
|
||||
pub mcp_agent_runs: mcp::AgentRuns,
|
||||
/// Projects the MCP server serves without a window.
|
||||
pub mcp_background: mcp::BackgroundProjects,
|
||||
/// Host-owned scheduled agent automations and in-session follow-up timers.
|
||||
pub automations: Arc<automations::AutomationService>,
|
||||
pub(crate) agent_catalogs: Arc<ide_agent::AgentCatalogs>,
|
||||
pub trust: std::sync::Arc<trust::TrustStore>,
|
||||
pub(crate) mcp_approvals: Arc<trust::McpServerApprovals>,
|
||||
pub(crate) plugin_approvals: Arc<trust::PluginCapabilityApprovals>,
|
||||
pub config_dir: PathBuf,
|
||||
/// Persistent user state, including credentials and recovery history.
|
||||
pub data_dir: PathBuf,
|
||||
@@ -209,6 +218,21 @@ impl Host {
|
||||
self
|
||||
}
|
||||
|
||||
/// Adds a version control system besides Git: projects opened afterwards look for its
|
||||
/// working copies (when trusted) and route the Changes view, status and log to them.
|
||||
pub fn with_vcs_provider(mut self, provider: Arc<dyn ide_vcs::BackendProvider>) -> Self {
|
||||
self.vcs_providers.push(provider);
|
||||
self
|
||||
}
|
||||
|
||||
/// Adds Subversion: every project gets its own svn settings ([`svn`]) and finds its
|
||||
/// working copies. `prompts` routes svn's login and certificate prompts to the project's
|
||||
/// window (the desktop app, which answers them with `ssh_askpass_answer`).
|
||||
pub fn with_subversion(mut self, prompts: bool) -> Self {
|
||||
self.subversion = Some(prompts);
|
||||
self
|
||||
}
|
||||
|
||||
/// User home directory used by agent memory discovery.
|
||||
pub fn home_dir(&self) -> Option<PathBuf> {
|
||||
self.home_dir.clone()
|
||||
@@ -234,9 +258,13 @@ impl Host {
|
||||
let migration = ssh.clone();
|
||||
runtime.spawn_blocking(move || migration.start_password_migration());
|
||||
ssh.set_configs(global_settings.effective().ssh.configs);
|
||||
let boot_override = if cfg!(test) { Some(data_dir.join("boot-services-test")) } else { None };
|
||||
let automations = automations::AutomationService::new(&data_dir, boot_override);
|
||||
let host = Self {
|
||||
plugin_host: RwLock::default(),
|
||||
local_database_tunnels: false,
|
||||
vcs_providers: Vec::new(),
|
||||
subversion: None,
|
||||
mcp_executable: Arc::default(),
|
||||
mcp: Default::default(),
|
||||
diagnostics,
|
||||
@@ -244,9 +272,11 @@ impl Host {
|
||||
mcp_requests: Default::default(),
|
||||
mcp_agent_runs: Default::default(),
|
||||
mcp_background: Default::default(),
|
||||
automations,
|
||||
agent_catalogs: Arc::default(),
|
||||
trust: std::sync::Arc::new(trust::TrustStore::load(&config_dir, &data_dir)),
|
||||
mcp_approvals: Arc::new(trust::McpServerApprovals::load(&data_dir)),
|
||||
plugin_approvals: Arc::new(trust::PluginCapabilityApprovals::load(&data_dir)),
|
||||
proxy_password: ide_ssh::secrets::SecretFile::new(data_dir.join("proxy-password.json")),
|
||||
jupyter_tokens: ide_ssh::secrets::SecretFile::new(data_dir.join("jupyter-tokens.json")),
|
||||
proxy_session_password: Mutex::default(),
|
||||
@@ -482,13 +512,20 @@ impl Host {
|
||||
let processes = self.processes.detach_project_kills(&project.root);
|
||||
let terminals = self.terminals.detach_key(self.owner_window(window));
|
||||
let root = (!project.light).then(|| project.root.clone());
|
||||
let shutdown_agents = if !project.light
|
||||
&& self.automations.retain_on_window_close(self, &project.root, &project.agents, agent_reason)
|
||||
{
|
||||
Vec::new()
|
||||
} else {
|
||||
vec![project.agents.clone()]
|
||||
};
|
||||
let handle = self.spawn_project_shutdown(ShutdownWork {
|
||||
notebooks: vec![project.notebooks.clone()],
|
||||
bridges: project.kotlin_bridge.iter().cloned().collect(),
|
||||
lsp: Some(project.lsp.clone()),
|
||||
// Debug sessions under the root belong to windows: a project served without one starts none.
|
||||
debug: Some((self.debugger.clone(), window.to_owned(), (!background).then(|| project.root.clone()))),
|
||||
agents: vec![project.agents.clone()],
|
||||
agents: shutdown_agents,
|
||||
agent_reason,
|
||||
terminals: Some(terminals),
|
||||
processes: Some(processes),
|
||||
@@ -617,6 +654,7 @@ impl Host {
|
||||
}
|
||||
|
||||
pub fn shutdown_notebooks_on_exit_with(&self, agent_reason: ide_agent::AgentShutdownReason) {
|
||||
self.automations.stop();
|
||||
let projects = self.projects();
|
||||
let mut pending: Vec<_> = self.closing.lock().drain(..).map(|entry| entry.handle).collect();
|
||||
if !projects.is_empty() {
|
||||
|
||||
@@ -444,7 +444,7 @@ impl BackgroundProjects {
|
||||
|
||||
impl Host {
|
||||
/// The window, and its project, that has `root` open as a project (not in LightEdit).
|
||||
fn window_project(&self, root: &Path) -> Option<(String, Arc<Project>)> {
|
||||
pub(crate) fn window_project(&self, root: &Path) -> Option<(String, Arc<Project>)> {
|
||||
let projects = self.projects.read();
|
||||
let windows = projects.iter().filter(|(w, p)| !BackgroundProjects::is_key(w) && !p.light && p.root == root);
|
||||
windows.min_by_key(|(w, _)| w.as_str()).map(|(w, p)| (w.clone(), p.clone()))
|
||||
|
||||
@@ -213,6 +213,7 @@ In OpenIDEA the user is asked first, then the IDE's own Debug action starts the
|
||||
before-launch tasks and Debug tool window as when you press Debug. This needs a project window (it does not work \
|
||||
for a background project without one). Program output goes to the Debug console, not into this tool's result.",
|
||||
|call| async move {
|
||||
call.needs_window()?;
|
||||
let target =
|
||||
execution_target(call.opt_str("configurationName")?, call.opt_str("filePath")?, call.opt_i64("line")?)?;
|
||||
let envs = call.args.get("envs").filter(|v| !v.is_null()).map(|_| call.str_map("envs")).transpose()?;
|
||||
@@ -490,6 +491,7 @@ optional `message` from the last verification. Function and data breakpoints are
|
||||
`function:` and `data:`. Call this before RESUME to check that an enabled breakpoint will be hit. Breakpoints set \
|
||||
with `xdebug_set_breakpoint` are the same ones the editor shows and persists.",
|
||||
|call| async move {
|
||||
call.needs_window()?;
|
||||
// The editor mirrors every change to the backend synchronously on request, so
|
||||
// flushing its pending debounced syncs makes this the same list the editor shows.
|
||||
call.ask(McpUiRequest::FlushBreakpoints).await?;
|
||||
@@ -589,6 +591,7 @@ suspends the thread and does not implement one-shot or stack-logging breakpoints
|
||||
`lineText` so the placement can be checked before RESUME. The breakpoint is shown in the editor's gutter and \
|
||||
persists with the project; this needs a project window.",
|
||||
|call| async move {
|
||||
call.needs_window()?;
|
||||
let _guard = BREAKPOINT_EDITS.lock().await;
|
||||
let files = editor_breakpoints(&call);
|
||||
let (path, line0, relocate_from) = if let Some(id) = call.opt_str("breakpointId")? {
|
||||
@@ -680,6 +683,7 @@ that file are removed; with neither (the default `owner=agent`), all line breakp
|
||||
Removal of a missing breakpoint is not an error: `removed` says whether anything was removed. `owner` is accepted \
|
||||
for compatibility. Function and data breakpoints are managed in the IDE; this needs a project window.",
|
||||
|call| async move {
|
||||
call.needs_window()?;
|
||||
let _guard = BREAKPOINT_EDITS.lock().await;
|
||||
let owner = call.opt_str("owner")?;
|
||||
if owner.as_deref().is_some_and(|o| o != "agent" && o != "user") {
|
||||
|
||||
@@ -429,6 +429,7 @@ Requires a filePath parameter containing the path to the file to open.
|
||||
The file path can be absolute or relative to the project root.
|
||||
Optionally puts the caret at a 1-based line and column.",
|
||||
|call| async move {
|
||||
call.needs_window()?;
|
||||
let raw = call.str("filePath")?;
|
||||
// Opening shows the file to the user: outside the project the user agrees first.
|
||||
let path = call.resolve_readable(&raw).await?;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::page::{OFFSET, Page};
|
||||
use super::search::{PathScope, paths_param};
|
||||
use super::tool::{Call, Output, Param, ParamType, Tool};
|
||||
use ide_core::{Diagnostic, IdeError, IdeResult, Severity};
|
||||
use ide_core::{Diagnostic, IdeResult, Severity};
|
||||
use serde_json::{Map, Value, json};
|
||||
|
||||
/// Problems `get_project_problems` lists by default.
|
||||
@@ -51,28 +51,16 @@ Lines and UTF-16 columns are 1-based.",
|
||||
]
|
||||
}
|
||||
|
||||
/// Editors and the Problems view are reported by a window: a project served in the
|
||||
/// background has none, and says so instead of answering as if nothing were open.
|
||||
fn reported_by_a_window(call: &Call) -> IdeResult<()> {
|
||||
if !super::BackgroundProjects::is_key(call.window()) {
|
||||
return Ok(());
|
||||
}
|
||||
let (tool, root) = (&call.tool, call.root().display());
|
||||
Err(IdeError::unavailable(format!(
|
||||
"{tool} needs the project open in a window: {root} is served in the background."
|
||||
)))
|
||||
}
|
||||
|
||||
/// [`reported_by_a_window`] for the Problems view, which `check_files` stands in for.
|
||||
/// [`Call::needs_window`] for the Problems view, which `check_files` stands in for.
|
||||
fn problems_reported_by_a_window(call: &Call) -> IdeResult<()> {
|
||||
reported_by_a_window(call).map_err(|mut error| {
|
||||
call.needs_window().map_err(|mut error| {
|
||||
error.message.push_str(" Use check_files for diagnostics.");
|
||||
error
|
||||
})
|
||||
}
|
||||
|
||||
async fn open_editors(call: Call) -> IdeResult<Output> {
|
||||
reported_by_a_window(&call)?;
|
||||
call.needs_window()?;
|
||||
let paths = PathScope::of(&call)?;
|
||||
let windows = call.host.mcp_windows(call.root());
|
||||
let open = call.host.mcp_reports.editors(&windows);
|
||||
@@ -84,7 +72,7 @@ async fn open_editors(call: Call) -> IdeResult<Output> {
|
||||
}
|
||||
|
||||
async fn current_file(call: Call) -> IdeResult<Output> {
|
||||
reported_by_a_window(&call)?;
|
||||
call.needs_window()?;
|
||||
let editor = call.host.mcp_reports.focused(call.window());
|
||||
Output::json(match editor {
|
||||
None => json!({}),
|
||||
|
||||
@@ -242,7 +242,11 @@ marked directory are not marked again.",
|
||||
},
|
||||
)
|
||||
.param(Param::required("directoryPath", ParamType::String, RELATIVE_PATH_IN_PROJECT_DESCRIPTION))
|
||||
.param(Param::optional("maxDepth", ParamType::Integer, "Maximum recursion depth"))
|
||||
.param(Param::optional(
|
||||
"maxDepth",
|
||||
ParamType::Integer,
|
||||
"Levels to list below the directory: 1 lists its entries, 2 their entries too, and so on (default 5)",
|
||||
))
|
||||
.param(Param::optional("limit", ParamType::Integer, "Entries to return at most (default 100)"))
|
||||
.param(Param::optional("offset", ParamType::Integer, OFFSET))
|
||||
.param(Param::optional("timeout", ParamType::Integer, TIMEOUT_MILLISECONDS_DESCRIPTION))
|
||||
@@ -306,6 +310,7 @@ fn marker(git_ignored: bool, ide_excluded: bool) -> &'static str {
|
||||
}
|
||||
|
||||
impl TreeRender {
|
||||
/// `max_depth`: the levels to list below the entry (0 lists the entry alone);
|
||||
/// `mark`: the entry's marker; `marked`: it or a directory above it is marked.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn render(
|
||||
@@ -318,7 +323,7 @@ impl TreeRender {
|
||||
mark: &str,
|
||||
marked: bool,
|
||||
) {
|
||||
if max_depth <= 0 || self.timed_out || self.cancel.is_cancelled() {
|
||||
if self.timed_out || self.cancel.is_cancelled() {
|
||||
return;
|
||||
}
|
||||
if Instant::now() >= self.deadline {
|
||||
@@ -343,7 +348,7 @@ impl TreeRender {
|
||||
} else {
|
||||
self.entry(&line)
|
||||
};
|
||||
if !is_dir {
|
||||
if !is_dir || max_depth <= 0 {
|
||||
return;
|
||||
}
|
||||
// Without exclusions, `ignored` is what `.gitignore` says.
|
||||
@@ -482,6 +487,38 @@ mod tests {
|
||||
assert_eq!(render(0, 100).0, " ├── a/\n │ ├── x.txt\n │ └── y.txt\n └── b.txt\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn max_depth_counts_the_levels_below_the_directory() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
for file in ["a/b/c.txt", "d.txt"] {
|
||||
let path = tmp.path().join(file);
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
std::fs::write(path, "").unwrap();
|
||||
}
|
||||
let render = |max_depth| {
|
||||
let mut tree = TreeRender {
|
||||
out: String::new(),
|
||||
errors: Vec::new(),
|
||||
timed_out: false,
|
||||
deadline: Instant::now() + Duration::from_secs(10),
|
||||
cancel: CancellationToken::new(),
|
||||
page: Page { offset: 0, limit: 100 },
|
||||
seen: 0,
|
||||
above: Vec::new(),
|
||||
marks: Marks { root: tmp.path().to_path_buf(), excludes: None },
|
||||
};
|
||||
tree.render(tmp.path(), "", true, max_depth, true, "", false);
|
||||
let root = format!("{}/\n", tmp.path().display());
|
||||
(tree.out.strip_prefix(&root).unwrap().to_owned(), tree.seen)
|
||||
};
|
||||
assert_eq!(render(0), (String::new(), 0), "0 lists the directory alone");
|
||||
assert_eq!(render(1), (" ├── a/\n └── d.txt\n".to_owned(), 2), "1 lists its entries");
|
||||
assert_eq!(render(2), (" ├── a/\n │ └── b/\n └── d.txt\n".to_owned(), 3));
|
||||
let full = " ├── a/\n │ └── b/\n │ └── c.txt\n └── d.txt\n".to_owned();
|
||||
assert_eq!(render(3), (full.clone(), 4));
|
||||
assert_eq!(render(5), (full, 4), "a depth beyond the tree lists all of it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn what_the_project_leaves_out_is_marked_once() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -18,7 +18,7 @@ pub mod service;
|
||||
mod symbols;
|
||||
mod tool;
|
||||
|
||||
pub(crate) use tool::trusted_attachments;
|
||||
pub(crate) use tool::{PROJECT_PATH, trusted_attachments};
|
||||
mod util;
|
||||
|
||||
use crate::Host;
|
||||
@@ -28,6 +28,7 @@ pub use reports::{
|
||||
FileProblems, FocusedEditor, Reports, mcp_report_problems, mcp_set_focused_editor, mcp_set_open_editors,
|
||||
};
|
||||
pub use run::agent::{AGENT_PARAM, AgentRun, AgentRuns, NAME_PREFIX, SHELL_PARAM};
|
||||
use serde_json::json;
|
||||
pub use service::{McpServerStatus, McpService};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
@@ -55,7 +56,8 @@ fn tools() -> Vec<tool::Tool> {
|
||||
tools
|
||||
}
|
||||
|
||||
// Checked both when listing and calling, so a later trust change takes effect immediately.
|
||||
// What a project lists. A call checks the trust it has then (`call_with_client`), so a later
|
||||
// trust change takes effect immediately.
|
||||
fn allowed(tool: &ide_mcp::Tool, trusted: bool) -> bool {
|
||||
trusted || tool.read_only
|
||||
}
|
||||
@@ -63,11 +65,36 @@ fn allowed(tool: &ide_mcp::Tool, trusted: bool) -> bool {
|
||||
fn tools_for(host: &Host, root: &Path, trusted: bool) -> Vec<ide_mcp::Tool> {
|
||||
let mut all: Vec<_> = tools().into_iter().map(|t| t.metadata).collect();
|
||||
if let Some(plugins) = host.plugin_host() {
|
||||
all.extend(plugins.mcp_tools(root).into_iter().map(|(_, _, tool)| tool));
|
||||
all.extend(plugins.mcp_tools(root).into_iter().map(|(_, _, tool)| with_project_path(tool)));
|
||||
}
|
||||
all.into_iter().filter(|t| allowed(t, trusted)).collect()
|
||||
}
|
||||
|
||||
/// A plugin's tool as clients see it: it takes `projectPath` like every other tool, which the
|
||||
/// plugin gets only if its own schema takes it (`PluginHost::call_mcp_tool`).
|
||||
fn with_project_path(mut tool: ide_mcp::Tool) -> ide_mcp::Tool {
|
||||
if let Some(schema) = tool.input_schema.as_object_mut()
|
||||
&& let Some(properties) = schema.entry("properties").or_insert_with(|| json!({})).as_object_mut()
|
||||
{
|
||||
properties.entry(tool::PROJECT_PATH).or_insert_with(tool::project_path);
|
||||
}
|
||||
tool
|
||||
}
|
||||
|
||||
/// The tool a call runs: a plugin's or a built-in one.
|
||||
enum Found {
|
||||
Plugin { plugins: Arc<crate::plugins::PluginHost>, plugin: String, tool: String, metadata: ide_mcp::Tool },
|
||||
Builtin(tool::Tool),
|
||||
}
|
||||
impl Found {
|
||||
fn writes(&self) -> bool {
|
||||
match self {
|
||||
Self::Plugin { metadata, .. } => !metadata.read_only,
|
||||
Self::Builtin(tool) => !tool.metadata.read_only,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Lists the built-in IDE and plugin-contributed MCP tools visible to `window`.
|
||||
pub(crate) fn list_tools_for_window(host: &Host, window: &str) -> Vec<ide_mcp::Tool> {
|
||||
match host.project(window).ok().filter(|p| !p.light) {
|
||||
@@ -110,6 +137,16 @@ impl Registry {
|
||||
}
|
||||
}
|
||||
|
||||
/// The tool `name` for `root`: a plugin's first. Loads nothing.
|
||||
fn find(&self, root: &Path, name: &str) -> Option<Found> {
|
||||
if let Some(plugins) = self.0.plugin_host()
|
||||
&& let Some((plugin, tool, metadata)) = plugins.mcp_tools(root).into_iter().find(|(_, _, t)| t.name == name)
|
||||
{
|
||||
return Some(Found::Plugin { plugins, plugin, tool, metadata });
|
||||
}
|
||||
tools().into_iter().find(|t| t.metadata.name == name).map(Found::Builtin)
|
||||
}
|
||||
|
||||
/// Whether the tools listed for `root` include those that write and run. Opens nothing:
|
||||
/// a background project that is not loaded is judged as its open will judge it.
|
||||
fn lists_as_trusted(&self, root: &Path) -> Result<bool, String> {
|
||||
@@ -150,6 +187,9 @@ impl ToolRegistry for Registry {
|
||||
let trusted = self.lists_as_trusted(root)?;
|
||||
Ok(tools_for(&self.0, root, trusted))
|
||||
}
|
||||
fn tools_without_project(&self) -> Vec<ide_mcp::Tool> {
|
||||
tools_for(&self.0, Path::new(""), true)
|
||||
}
|
||||
fn call(
|
||||
&self,
|
||||
root: &Path,
|
||||
@@ -167,19 +207,27 @@ impl ToolRegistry for Registry {
|
||||
cancel: CancellationToken,
|
||||
client: &str,
|
||||
) -> Result<String, ToolCallError> {
|
||||
let unknown = || ToolCallError::UnknownTool(format!("unknown tool: {name}"));
|
||||
// Before the project loads, so the refusal neither loads a background project nor
|
||||
// unloads an idle one at the limit to make room.
|
||||
if self.find(root, name).ok_or_else(unknown)?.writes() && self.lists_as_trusted(root) == Ok(false) {
|
||||
return Err(ToolCallError::Failed(crate::project::RESTRICTED_MODE.into()));
|
||||
}
|
||||
// The guard lives until the call ends, whichever way it leaves: neither the idle
|
||||
// sweep nor the limit unloads a background project a call runs in.
|
||||
let (window, project, _activity) = self.target(root).map_err(ToolCallError::Failed)?;
|
||||
if let Some(plugins) = self.0.plugin_host()
|
||||
&& let Some((plugin, tool, metadata)) =
|
||||
plugins.mcp_tools(root).into_iter().find(|(_, _, t)| t.name == name && allowed(t, project.is_trusted()))
|
||||
{
|
||||
return self.call_plugin(window, project, plugins, plugin, tool, metadata, arguments, cancel, client);
|
||||
// Found again: a plugin can change while a background project opens, and the call
|
||||
// runs the tool as it is now.
|
||||
let found = self.find(root, name).ok_or_else(unknown)?;
|
||||
if found.writes() {
|
||||
project.require_trust().map_err(|e| ToolCallError::Failed(e.message))?;
|
||||
}
|
||||
let tool = tools()
|
||||
.into_iter()
|
||||
.find(|t| t.metadata.name == name && allowed(&t.metadata, project.is_trusted()))
|
||||
.ok_or_else(|| ToolCallError::UnknownTool(format!("unknown tool: {name}")))?;
|
||||
let tool = match found {
|
||||
Found::Plugin { plugins, plugin, tool, metadata } => {
|
||||
return self.call_plugin(window, project, plugins, plugin, tool, metadata, arguments, cancel, client);
|
||||
}
|
||||
Found::Builtin(tool) => tool,
|
||||
};
|
||||
let args = serde_json::from_str(arguments).map_err(|e| ToolCallError::Failed(e.to_string()))?;
|
||||
let call = tool::Call {
|
||||
host: self.0.clone(),
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
//! Window-bound requests; missing windows, cancellation and timeout all fail closed.
|
||||
//! Window-bound requests; missing windows, cancellation and timeout all fail closed. A
|
||||
//! confirmation for a project served in the background shows in another project's window
|
||||
//! and moves to the next one when that window stops answering.
|
||||
use super::tool::Call;
|
||||
use crate::Host;
|
||||
use ide_core::{IdeError, IdeEvent, IdeResult, event::McpUiRequest};
|
||||
use parking_lot::Mutex;
|
||||
use parking_lot::{Mutex, MutexGuard};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use tokio::sync::oneshot;
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::{Notify, oneshot};
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct Requests(Mutex<State>);
|
||||
@@ -13,10 +17,24 @@ struct State {
|
||||
pending: HashMap<u32, Pending>,
|
||||
}
|
||||
struct Pending {
|
||||
window: String,
|
||||
/// The window key of the call that asked.
|
||||
owner: String,
|
||||
/// The window that shows the request and may answer it.
|
||||
shown_in: String,
|
||||
/// Signalled when `shown_in` stops answering while `owner` still waits.
|
||||
moved: Arc<Notify>,
|
||||
answer: oneshot::Sender<Result<bool, String>>,
|
||||
value: oneshot::Sender<Option<String>>,
|
||||
}
|
||||
impl State {
|
||||
/// `window` answers no more requests: the ones it shows for another window move on.
|
||||
fn stop_showing(&mut self, window: &str) {
|
||||
self.ready.remove(window);
|
||||
for pending in self.pending.values().filter(|p| p.shown_in == window && p.owner != window) {
|
||||
pending.moved.notify_one();
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Requests {
|
||||
pub fn set_ready(&self, window: &str, ready: bool) {
|
||||
if ready {
|
||||
@@ -25,10 +43,18 @@ impl Requests {
|
||||
self.forget_window(window);
|
||||
}
|
||||
}
|
||||
/// `window` closed: its own requests fail, and the ones it shows for a project served in
|
||||
/// the background move to another window.
|
||||
pub fn forget_window(&self, window: &str) {
|
||||
let mut state = self.0.lock();
|
||||
state.ready.remove(window);
|
||||
state.pending.retain(|_, p| p.window != window);
|
||||
state.pending.retain(|_, p| p.owner != window);
|
||||
state.stop_showing(window);
|
||||
}
|
||||
/// `window` lost its project's trust: the requests it shows for a project served in the
|
||||
/// background move to another window; its own stay there and fail the trust check after
|
||||
/// the answer.
|
||||
pub(crate) fn withdraw(&self, window: &str) {
|
||||
self.0.lock().stop_showing(window);
|
||||
}
|
||||
pub fn answer(&self, window: &str, id: u32, allow: bool, error: Option<String>) -> IdeResult<()> {
|
||||
self.answer_with(window, id, allow, error, None)
|
||||
@@ -43,10 +69,10 @@ impl Requests {
|
||||
value: Option<String>,
|
||||
) -> IdeResult<()> {
|
||||
let mut state = self.0.lock();
|
||||
if !state.pending.get(&id).is_some_and(|p| p.window == window) {
|
||||
if !state.pending.get(&id).is_some_and(|p| p.shown_in == window) {
|
||||
return Err(IdeError::invalid("MCP request expired or belongs to another window"));
|
||||
}
|
||||
let pending = state.pending.remove(&id).unwrap();
|
||||
let pending = state.pending.remove(&id).expect("the request was just found");
|
||||
let _ = pending.value.send(value);
|
||||
let _ = pending.answer.send(error.map_or(Ok(allow), Err));
|
||||
Ok(())
|
||||
@@ -64,30 +90,96 @@ impl Requests {
|
||||
self.ask_inner(call, request).await
|
||||
}
|
||||
|
||||
/// The window to show a background project's request in: the most recently focused ready
|
||||
/// window whose project is trusted. Returns it with the state locked while it is still
|
||||
/// ready, or `None` when there is none.
|
||||
fn pick(&self, host: &Host) -> Option<(MutexGuard<'_, State>, String)> {
|
||||
loop {
|
||||
// Projects and focus are read without the lock, which is never held with theirs.
|
||||
let mut windows: Vec<String> = self.0.lock().ready.iter().cloned().collect();
|
||||
windows.retain(|w| host.project(w).is_ok_and(|p| p.is_trusted()));
|
||||
host.mcp_reports.most_recently_focused_first(&mut windows);
|
||||
let target = windows.into_iter().next()?;
|
||||
let state = self.0.lock();
|
||||
if state.ready.contains(&target) {
|
||||
return Some((state, target));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn ask_inner(&self, call: &Call, request: McpUiRequest) -> IdeResult<Option<String>> {
|
||||
let id = super::tool::request_id().0;
|
||||
let (tx, rx) = oneshot::channel();
|
||||
let (tx, mut rx) = oneshot::channel();
|
||||
let (value_tx, value_rx) = oneshot::channel();
|
||||
{
|
||||
let mut state = self.0.lock();
|
||||
if !state.ready.contains(call.window()) {
|
||||
return Err(IdeError::unavailable("MCP request denied: no project window is available"));
|
||||
}
|
||||
state.pending.insert(id, Pending { window: call.window.clone(), answer: tx, value: value_tx });
|
||||
let moved = Arc::new(Notify::new());
|
||||
let background = matches!(request, McpUiRequest::Confirm { background: true, .. });
|
||||
let shown_in = {
|
||||
let own = self.0.lock();
|
||||
let (mut state, shown_in) = if own.ready.contains(call.window()) {
|
||||
(own, call.window.clone())
|
||||
} else {
|
||||
drop(own);
|
||||
background
|
||||
.then(|| self.pick(&call.host))
|
||||
.flatten()
|
||||
.ok_or_else(|| IdeError::unavailable("MCP request denied: no project window is available"))?
|
||||
};
|
||||
let pending = Pending {
|
||||
owner: call.window.clone(),
|
||||
shown_in: shown_in.clone(),
|
||||
moved: moved.clone(),
|
||||
answer: tx,
|
||||
value: value_tx,
|
||||
};
|
||||
state.pending.insert(id, pending);
|
||||
shown_in
|
||||
};
|
||||
struct Close<'a> {
|
||||
requests: &'a Requests,
|
||||
call: &'a Call,
|
||||
id: u32,
|
||||
shown_in: String,
|
||||
}
|
||||
struct Close<'a>(&'a Requests, &'a Call, u32);
|
||||
impl Drop for Close<'_> {
|
||||
fn drop(&mut self) {
|
||||
self.0.0.lock().pending.remove(&self.2);
|
||||
self.1.project.sink.emit(IdeEvent::McpRequestClosed { id: self.2 });
|
||||
self.requests.0.lock().pending.remove(&self.id);
|
||||
self.call.host.window_sink(&self.shown_in).emit(IdeEvent::McpRequestClosed { id: self.id });
|
||||
}
|
||||
}
|
||||
let _close = Close(self, call, id);
|
||||
call.project.sink.emit(IdeEvent::McpRequest { id, request });
|
||||
let result = tokio::select! {
|
||||
result = rx => result.map_err(|_| IdeError::unavailable("MCP request denied: project window closed"))?,
|
||||
_ = tokio::time::sleep(std::time::Duration::from_secs(180)) => return Err(IdeError::unavailable("MCP request denied: confirmation timed out")),
|
||||
_ = call.cancel.cancelled() => return Err(IdeError::cancelled()),
|
||||
let mut close = Close { requests: self, call, id, shown_in };
|
||||
call.host.window_sink(&close.shown_in).emit(IdeEvent::McpRequest { id, request: request.clone() });
|
||||
// One deadline however often the request moves.
|
||||
let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(180);
|
||||
let result = loop {
|
||||
// An answer that arrives together with a move or a close still counts.
|
||||
tokio::select! {
|
||||
biased;
|
||||
result = &mut rx => break result.map_err(|_| IdeError::unavailable("MCP request denied: project window closed"))?,
|
||||
_ = call.cancel.cancelled() => return Err(IdeError::cancelled()),
|
||||
// A project unloading after its window was forgotten must not reach another window.
|
||||
_ = call.project.closed.cancelled() => return Err(IdeError::unavailable("MCP request denied: project closed")),
|
||||
_ = tokio::time::sleep_until(deadline) => return Err(IdeError::unavailable("MCP request denied: confirmation timed out")),
|
||||
_ = moved.notified() => {
|
||||
if self.window_ready(&close.shown_in) {
|
||||
// The window answers again after a reload, whose new page has not seen the
|
||||
// request: show it there again (the page drops a repeated id).
|
||||
call.host.window_sink(&close.shown_in).emit(IdeEvent::McpRequest { id, request: request.clone() });
|
||||
continue;
|
||||
}
|
||||
let target = {
|
||||
let (mut state, target) = self
|
||||
.pick(&call.host)
|
||||
.ok_or_else(|| IdeError::unavailable("MCP request denied: project window closed"))?;
|
||||
// Answered or dropped meanwhile: `rx` says which.
|
||||
let Some(pending) = state.pending.get_mut(&id) else { continue };
|
||||
pending.shown_in = target.clone();
|
||||
target
|
||||
};
|
||||
let left = std::mem::replace(&mut close.shown_in, target);
|
||||
call.host.window_sink(&left).emit(IdeEvent::McpRequestClosed { id });
|
||||
call.host.window_sink(&close.shown_in).emit(IdeEvent::McpRequest { id, request: request.clone() });
|
||||
}
|
||||
}
|
||||
};
|
||||
match result {
|
||||
Ok(true) => Ok(value_rx.await.unwrap_or(None)),
|
||||
@@ -96,3 +188,109 @@ impl Requests {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{HostConfig, mcp::BackgroundProjects};
|
||||
use futures::FutureExt;
|
||||
use ide_core::{CancellationToken, IdeEvent};
|
||||
use std::path::PathBuf;
|
||||
|
||||
type Events = Arc<Mutex<Vec<(String, IdeEvent)>>>;
|
||||
|
||||
/// A trusted project open in the ready window `main`, and the folder `inventory` loaded in the
|
||||
/// background next to it.
|
||||
struct Fixture {
|
||||
host: Arc<Host>,
|
||||
inventory: PathBuf,
|
||||
events: Events,
|
||||
_temp: tempfile::TempDir,
|
||||
}
|
||||
|
||||
impl Fixture {
|
||||
async fn new() -> Self {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(temp.path()).unwrap();
|
||||
let (root, inventory) = (base.join("project"), base.join("inventory"));
|
||||
for dir in [&root, &inventory] {
|
||||
std::fs::create_dir_all(dir).unwrap();
|
||||
}
|
||||
let events = Events::default();
|
||||
let sink = events.clone();
|
||||
let host = Arc::new(Host::new(HostConfig {
|
||||
local_data_dir: base.join("local"),
|
||||
sink_for: Box::new(move |window| {
|
||||
let (window, events) = (window.to_owned(), sink.clone());
|
||||
Arc::new(move |e| events.lock().push((window.clone(), e)))
|
||||
}),
|
||||
..HostConfig::for_test(&base)
|
||||
}));
|
||||
host.open_project("main", &root).unwrap();
|
||||
host.set_project_trust(&root, true, false).await.unwrap();
|
||||
host.mcp_requests.set_ready("main", true);
|
||||
Self { host, inventory, events, _temp: temp }
|
||||
}
|
||||
|
||||
/// A call from the background project at `inventory`.
|
||||
fn background_call(&self) -> Call {
|
||||
let window = BackgroundProjects::key(&self.inventory);
|
||||
Call {
|
||||
client: "test-client".into(),
|
||||
tool: "build_project".into(),
|
||||
host: self.host.clone(),
|
||||
project: self.host.open_project(&window, &self.inventory).unwrap(),
|
||||
window,
|
||||
args: serde_json::Value::Null,
|
||||
cancel: CancellationToken::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn confirm(&self) -> McpUiRequest {
|
||||
McpUiRequest::Confirm {
|
||||
client: "test-client".into(),
|
||||
tool: "build_project".into(),
|
||||
subject: "build".into(),
|
||||
project: self.inventory.to_string_lossy().into_owned(),
|
||||
detail: None,
|
||||
background: true,
|
||||
}
|
||||
}
|
||||
|
||||
/// The ids of the requests `main` was asked to show, in order.
|
||||
fn shown_in_main(&self) -> Vec<u32> {
|
||||
let events = self.events.lock();
|
||||
let asked = events.iter().filter(|(window, _)| window == "main");
|
||||
asked.filter_map(|(_, e)| if let IdeEvent::McpRequest { id, .. } = e { Some(*id) } else { None }).collect()
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn a_request_of_a_project_that_closed_fails_instead_of_moving() {
|
||||
let f = Fixture::new().await;
|
||||
let call = f.background_call();
|
||||
// Unloading forgets the project's key before it cancels `closed`; a request registered in
|
||||
// between belongs to nobody that will answer it.
|
||||
call.project.closed.cancel();
|
||||
let error = f.host.mcp_requests.ask(&call, f.confirm()).now_or_never().expect("fails at once").unwrap_err();
|
||||
assert_eq!(error.message, "MCP request denied: project closed");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn a_reloaded_window_shows_the_request_again() {
|
||||
let f = Fixture::new().await;
|
||||
let call = f.background_call();
|
||||
let ask = f.host.mcp_requests.ask(&call, f.confirm());
|
||||
tokio::pin!(ask);
|
||||
assert!((&mut ask).now_or_never().is_none());
|
||||
let [id] = f.shown_in_main()[..] else { panic!("{:?}", f.shown_in_main()) };
|
||||
// A reload: the old page stops answering and drops the request, the new one is ready.
|
||||
f.host.mcp_requests.set_ready("main", false);
|
||||
f.host.mcp_requests.set_ready("main", true);
|
||||
assert!((&mut ask).now_or_never().is_none());
|
||||
assert_eq!(f.shown_in_main(), [id, id]);
|
||||
f.host.mcp_requests.answer("main", id, false, None).unwrap();
|
||||
let error = ask.await.unwrap_err();
|
||||
assert_eq!(error.message, "MCP request denied by the user");
|
||||
}
|
||||
}
|
||||
@@ -137,6 +137,7 @@ crashed, stoppedByAgent, stoppedByUser or startFailed; `exitCode`; `crash` with
|
||||
process) and its output so far.{OUTPUT}{SEQUENCE}{INTERVENTIONS}"
|
||||
),
|
||||
|call| async move {
|
||||
call.needs_window()?;
|
||||
let name = tab_name(&call.str("name")?)?;
|
||||
let command = call.str("command")?;
|
||||
if command.trim().is_empty() {
|
||||
|
||||
@@ -5,6 +5,14 @@ use serde_json::{Value, json};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
|
||||
/// The argument that names the project a call is for; the server routes the call by it.
|
||||
pub(crate) const PROJECT_PATH: &str = "projectPath";
|
||||
|
||||
/// The schema of [`PROJECT_PATH`], which every tool takes.
|
||||
pub(crate) fn project_path() -> Value {
|
||||
json!({ "type": "string", "description": "Any directory inside a project that is open in a window or served in the background. Defaults to the connection's project (`?project=`) or the only one open in a window." })
|
||||
}
|
||||
|
||||
pub struct Call {
|
||||
pub client: String,
|
||||
pub tool: String,
|
||||
@@ -88,12 +96,24 @@ impl Call {
|
||||
client: self.client.clone(),
|
||||
tool: self.tool.clone(),
|
||||
subject: subject.into(),
|
||||
project: self.root().to_string_lossy().into_owned(),
|
||||
project: ide_core::ipc_path::to_ipc(self.root()),
|
||||
detail,
|
||||
background: super::BackgroundProjects::is_key(&self.window),
|
||||
})
|
||||
.await?;
|
||||
self.project.require_trust()
|
||||
}
|
||||
/// Refuses a tool that works through the project's window (its editors, Problems view, Run
|
||||
/// tool window or breakpoints) when the project is served in the background without one.
|
||||
pub fn needs_window(&self) -> IdeResult<()> {
|
||||
if !super::BackgroundProjects::is_key(&self.window) {
|
||||
return Ok(());
|
||||
}
|
||||
let (tool, root) = (&self.tool, self.root().display());
|
||||
Err(IdeError::unavailable(format!(
|
||||
"{tool} needs the project open in a window: {root} is served in the background."
|
||||
)))
|
||||
}
|
||||
pub fn host(&self) -> Arc<Host> {
|
||||
self.host.clone()
|
||||
}
|
||||
@@ -242,9 +262,7 @@ impl Tool {
|
||||
read_only: true,
|
||||
destructive: false,
|
||||
output_schema: None,
|
||||
input_schema: json!({ "type": "object", "properties": {
|
||||
"projectPath": { "type": "string", "description": "Any directory inside a project that is open in a window or served in the background. Defaults to the connection's project (`?project=`) or the only one open in a window." }
|
||||
}, "required": [] }),
|
||||
input_schema: json!({ "type": "object", "properties": { PROJECT_PATH: project_path() }, "required": [] }),
|
||||
},
|
||||
handler: Arc::new(move |call| Box::pin(handler(call))),
|
||||
}
|
||||
|
||||
@@ -99,8 +99,8 @@ fn get_repositories() -> Tool {
|
||||
"get_repositories",
|
||||
"Retrieves the list of VCS roots in the project.
|
||||
This is useful to detect all repositories in a multi-repository project.
|
||||
In OpenIDEA each root also tells its current `branch` (absent when HEAD is detached), `headCommit` and a merge, \
|
||||
rebase or cherry-pick in progress (`operationInProgress`).",
|
||||
In OpenIDEA each root also tells its current `branch` (absent when HEAD is detached or the repository is unavailable), \
|
||||
`headCommit`, a merge, rebase or cherry-pick in progress (`operationInProgress`), and `unavailable` (`true` when the repository directory cannot be reached).",
|
||||
|call| async move {
|
||||
let roots = crate::ops::vcs::vcs_roots(&call.host(), &call.window).await?;
|
||||
let list: Vec<Value> = roots
|
||||
@@ -117,6 +117,9 @@ rebase or cherry-pick in progress (`operationInProgress`).",
|
||||
if let Some(op) = r.operation {
|
||||
v["operationInProgress"] = op.into();
|
||||
}
|
||||
if r.unavailable {
|
||||
v["unavailable"] = true.into();
|
||||
}
|
||||
v
|
||||
})
|
||||
.collect();
|
||||
@@ -256,10 +259,10 @@ By default all Git repositories are returned.",
|
||||
let include_ignored = call.flag("includeIgnored", false)?;
|
||||
let page = Page::of(&call, STATUS_DEFAULT_LIMIT)?;
|
||||
let host = call.host();
|
||||
let repos: Vec<(PathBuf, Option<String>)> = crate::ops::vcs::vcs_roots(&host, &call.window)
|
||||
let repos: Vec<(PathBuf, (Option<String>, bool))> = crate::ops::vcs::vcs_roots(&host, &call.window)
|
||||
.await?
|
||||
.into_iter()
|
||||
.map(|r| (r.root.into_path_buf(), r.head))
|
||||
.map(|r| (r.root.into_path_buf(), (r.head, r.unavailable)))
|
||||
.collect();
|
||||
let wanted = call.opt_str("repositoryPathRelativeToProject")?;
|
||||
let paths = super::search::PathScope::of(&call)?;
|
||||
@@ -271,12 +274,25 @@ By default all Git repositories are returned.",
|
||||
};
|
||||
let mut roots: Vec<(PathBuf, Option<String>)> = if targets.is_empty() {
|
||||
repos
|
||||
.into_iter()
|
||||
.filter(|(_, (_, unavailable))| !unavailable)
|
||||
.map(|(root, (head, _))| (root, head))
|
||||
.collect()
|
||||
} else {
|
||||
let mut picked: Vec<(PathBuf, Option<String>)> = Vec::new();
|
||||
for path in targets {
|
||||
// The innermost repository containing the path.
|
||||
let repo = match innermost_repo(repos.clone(), &path) {
|
||||
Some(repo) => repo,
|
||||
Some((root, (_, true))) => {
|
||||
if wanted.is_some() {
|
||||
return Err(IdeError::unavailable(format!(
|
||||
"Git repository '{}' is currently unavailable",
|
||||
relative_to_project(&call, &root)
|
||||
)));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
Some((root, (head, false))) => (root, head),
|
||||
None => match find_git_root(call.root(), &path) {
|
||||
Some(root) => {
|
||||
// JetBrains reads the branch of any repository it reports.
|
||||
|
||||
@@ -264,7 +264,22 @@ pub fn spec(os: Os) -> Vec<Entry> {
|
||||
act("file.save", "Save All"),
|
||||
act("templates.saveFileAsTemplate", "Save File as Template…"),
|
||||
act("file.reloadAllFromDisk", "Reload All from Disk"),
|
||||
sub("fileProperties", "File Properties", vec![act("file.toggleReadOnly", "Make File Read-only / Writable")]),
|
||||
sub(
|
||||
"fileProperties",
|
||||
"File Properties",
|
||||
vec![
|
||||
sub(
|
||||
"lineSeparators",
|
||||
"Line Separators",
|
||||
vec![
|
||||
act("file.lineSeparators.crLf", "CRLF - Windows (\\r\\n)"),
|
||||
act("file.lineSeparators.lf", "LF - Unix and macOS (\\n)"),
|
||||
act("file.lineSeparators.cr", "CR - Classic Mac OS (\\r)"),
|
||||
],
|
||||
),
|
||||
act("file.toggleReadOnly", "Make File Read-only / Writable"),
|
||||
],
|
||||
),
|
||||
SEP,
|
||||
act("file.projectStructure", "Project Structure…"),
|
||||
SEP,
|
||||
@@ -735,6 +750,18 @@ pub fn spec(os: Os) -> Vec<Entry> {
|
||||
act("vcs.syncSubmodules", "Sync Submodule URLs"),
|
||||
],
|
||||
),
|
||||
// What only a Subversion working copy has; disabled for a Git repository.
|
||||
sub(
|
||||
"subversion",
|
||||
"Subversion",
|
||||
vec![
|
||||
act("svn.cleanup", "Cleanup"),
|
||||
act("svn.lock", "Lock…"),
|
||||
act("svn.unlock", "Unlock"),
|
||||
act("svn.relocate", "Relocate…"),
|
||||
act("svn.properties", "Properties…"),
|
||||
],
|
||||
),
|
||||
SEP,
|
||||
act("vcs.showLog", "Show Git Log"),
|
||||
sub(
|
||||
@@ -903,6 +930,7 @@ pub fn spec(os: Os) -> Vec<Entry> {
|
||||
act("editor.moveToOppositeGroup", "Move to Opposite Group"),
|
||||
act("editor.openInOppositeGroup", "Open in Opposite Group"),
|
||||
act("editor.changeSplitOrientation", "Change Splitter Orientation"),
|
||||
act("editor.maximizeInSplit", "Maximize Editor / Normalize Splits"),
|
||||
act("editor.unsplitAll", "Unsplit All"),
|
||||
act("editor.nextSplitter", "Go to Next Splitter"),
|
||||
act("editor.prevSplitter", "Go to Previous Splitter"),
|
||||
|
||||
@@ -5,14 +5,17 @@ use crate::Host;
|
||||
use crate::agent_secrets::{AgentSecrets, Kept};
|
||||
use ide_agent::registry::{AgentRegistry, RegistryPaths};
|
||||
use ide_agent::{
|
||||
AcpImportOutcome, AgentAcceptOutcome, AgentChange, AgentChanges, AgentChangesView, AgentCliOffer,
|
||||
AgentCliUpdateResult, AgentCommand, AgentContextUsage, AgentEntry, AgentEvent, AgentLoginEvent, AgentMemoryCatalog,
|
||||
AgentMemoryEntryPolicy, AgentMemoryMode, AgentMemoryOverrides, AgentMemorySettings, AgentModelCatalog, AgentProbe,
|
||||
AcpImportOutcome, AgentAcceptOutcome, AgentAutomation, AgentChange, AgentChanges, AgentChangesView, AgentCliOffer,
|
||||
AgentCliUpdateResult, AgentCommand, AgentContextUsage, AgentEntry, AgentEvent, AgentLoginEvent,
|
||||
AgentMarketplaceBrowseResult, AgentMemoryCatalog, AgentMemoryEntryPolicy, AgentMemoryMode, AgentMemoryOverrides,
|
||||
AgentMemorySettings, AgentModelCatalog, AgentPluginCatalog, AgentPluginPreview, AgentPluginSettings, AgentProbe,
|
||||
AgentPrompt, AgentProvider, AgentProviderMemoryPolicy, AgentQueued, AgentRecoveryReport, AgentSkillMode,
|
||||
AgentSkillPolicy, AgentSkillState, AgentTask, AutoMemoryMode, CopilotAuthStatus, CreateAgentMemoryInput,
|
||||
CustomAgentInput, ExternalSession, InstallRemoteSkillRequest, LoginLaunch, McpExternalSource, McpImportSelection,
|
||||
McpProbeResult, McpScope, McpServer, McpServerInput, McpTransport, NewAgentTask, PromoteAgentMemoryInput,
|
||||
RemoteSkillBrowseResult, RemoteSkillPreview, SkillsPolicy,
|
||||
AgentSkillPolicy, AgentSkillState, AgentTask, AutoMemoryMode, AutomationRun, AutomationRunsPage,
|
||||
AutomationSnapshot, AutomationTrigger, AutomationWorkspace, CopilotAuthStatus, CreateAgentMemoryInput,
|
||||
CreateSessionScheduleInput, CustomAgentInput, ExternalSession, InstallAgentPluginRequest,
|
||||
InstallRemoteSkillRequest, Isolation, LoginLaunch, McpExternalSource, McpImportSelection, McpProbeResult, McpScope,
|
||||
McpServer, McpServerInput, McpTransport, NewAgentTask, PromoteAgentMemoryInput, RemoteSkillBrowseResult,
|
||||
RemoteSkillPreview, SaveAutomationInput, SessionSchedule, SkillsPolicy,
|
||||
};
|
||||
use ide_command::command;
|
||||
use ide_core::error::ErrorKind;
|
||||
@@ -30,18 +33,47 @@ pub fn agent_subscribe(
|
||||
on_event: Channel<AgentEvent>,
|
||||
subscriber: String,
|
||||
) -> IdeResult<Vec<AgentTask>> {
|
||||
Ok(host.project(window)?.agents.subscribe_as(
|
||||
&subscriber,
|
||||
std::sync::Arc::new(move |e| {
|
||||
let _ = on_event.send(e);
|
||||
}),
|
||||
))
|
||||
let sink: ide_agent::AgentSink = std::sync::Arc::new(move |e| {
|
||||
let _ = on_event.send(e);
|
||||
});
|
||||
let scope = crate::automations::AutomationTaskScope::for_window(host, window);
|
||||
let mut by_id: std::collections::HashMap<String, AgentTask> = std::collections::HashMap::new();
|
||||
match host.project(window) {
|
||||
Ok(proj) => {
|
||||
for t in proj.agents.subscribe_as(&subscriber, sink.clone()) {
|
||||
by_id.insert(t.id.clone(), t);
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
// Without an open project, `scope.allowed_roots` is empty (no wildcard!) so ONLY
|
||||
// `ChatOnly` tasks may be subscribed if any exist.
|
||||
let extras = host.automations.subscribe_window_extras(host, &scope, &subscriber, sink);
|
||||
if extras.is_empty() {
|
||||
return Err(e);
|
||||
}
|
||||
for t in extras {
|
||||
by_id.insert(t.id.clone(), t);
|
||||
}
|
||||
let mut list: Vec<AgentTask> = by_id.into_values().collect();
|
||||
list.sort_by(|a, b| b.updated_ms.total_cmp(&a.updated_ms));
|
||||
return Ok(list);
|
||||
}
|
||||
}
|
||||
for extra in host.automations.subscribe_window_extras(host, &scope, &subscriber, sink) {
|
||||
by_id.insert(extra.id.clone(), extra);
|
||||
}
|
||||
let mut list: Vec<AgentTask> = by_id.into_values().collect();
|
||||
list.sort_by(|a, b| b.updated_ms.total_cmp(&a.updated_ms));
|
||||
Ok(list)
|
||||
}
|
||||
|
||||
/// Stops the events of a window that closed.
|
||||
#[command(trust = always)]
|
||||
pub fn agent_unsubscribe(host: &Host, window: &str, subscriber: String) -> IdeResult<()> {
|
||||
host.project(window)?.agents.unsubscribe(&subscriber);
|
||||
host.automations.unsubscribe_window_extras(&subscriber);
|
||||
if let Ok(proj) = host.project(window) {
|
||||
proj.agents.unsubscribe(&subscriber);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -422,8 +454,7 @@ pub async fn agent_entries(
|
||||
task: String,
|
||||
subagent: Option<String>,
|
||||
) -> IdeResult<Vec<AgentEntry>> {
|
||||
let agents = host.project(window)?.agents.clone();
|
||||
host.blocking(move || agents.entries(&task, subagent)).await
|
||||
host.automations.route_entries(host, window, task, subagent).await
|
||||
}
|
||||
|
||||
/// Sessions of the project on this machine that no task holds yet, newest first.
|
||||
@@ -478,8 +509,8 @@ pub async fn agent_create(host: &Host, window: &str, request: NewAgentTask) -> I
|
||||
/// Sends a message; while the agent works it is queued, or with `now` it interrupts the turn.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn agent_prompt(host: &Host, window: &str, task: String, prompt: AgentPrompt, now: bool) -> IdeResult<()> {
|
||||
host.require_trust(window)?;
|
||||
host.project(window)?.agents.prompt(&task, prompt, now).await
|
||||
host.require_trust_if_project(window)?;
|
||||
host.automations.route_prompt(host, window, task, prompt, now).await
|
||||
}
|
||||
|
||||
/// Runs a `!` line of the composer in the task's folder with the user's shell, without
|
||||
@@ -509,8 +540,8 @@ pub async fn agent_answer_question(
|
||||
question: String,
|
||||
answer: Option<String>,
|
||||
) -> IdeResult<()> {
|
||||
host.require_trust(window)?;
|
||||
host.project(window)?.agents.answer_question(&task, &question, answer).await
|
||||
host.require_trust_if_project(window)?;
|
||||
host.automations.route_answer_question(host, window, task, question, answer).await
|
||||
}
|
||||
|
||||
/// Drops a queued message and returns it (to edit it).
|
||||
@@ -615,7 +646,7 @@ pub async fn agent_context_usage(host: &Host, window: &str, task: String) -> Ide
|
||||
/// Stops the task's current turn, or with `subagent` only that subagent's work.
|
||||
#[command(trust = always)]
|
||||
pub fn agent_cancel(host: &Host, window: &str, task: String, subagent: Option<String>) -> IdeResult<()> {
|
||||
host.project(window)?.agents.cancel(&task, subagent)
|
||||
host.automations.route_cancel(host, window, task, subagent)
|
||||
}
|
||||
|
||||
/// Resumes an interrupted task with a continuation turn (or immediately wakes a task waiting
|
||||
@@ -645,7 +676,10 @@ pub async fn agent_dismiss_interrupted(host: &Host, window: &str, task: String)
|
||||
/// Marks a task as read (`unread = false`) when viewed by the user.
|
||||
#[command(trust = always)]
|
||||
pub async fn agent_mark_read(host: &Host, window: &str, task: String) -> IdeResult<()> {
|
||||
let agents = host.project(window)?.agents.clone();
|
||||
let agents = match host.automations.authorized_local_manager(host, window, &task, false)? {
|
||||
Some(mgr) => mgr,
|
||||
None => host.project(window)?.agents.clone(),
|
||||
};
|
||||
host.blocking(move || agents.mark_read(&task)).await
|
||||
}
|
||||
|
||||
@@ -689,7 +723,7 @@ pub async fn agent_reconcile_interrupted(host: &Host, window: &str) -> IdeResult
|
||||
/// Stops one of the task's background tasks.
|
||||
#[command(trust = always)]
|
||||
pub async fn agent_stop_background(host: &Host, window: &str, task: String, background: String) -> IdeResult<()> {
|
||||
host.project(window)?.agents.stop_background(&task, &background).await
|
||||
host.automations.route_stop_background(host, window, task, background).await
|
||||
}
|
||||
|
||||
/// Answers a permission request; `option: null` cancels it.
|
||||
@@ -701,29 +735,48 @@ pub fn agent_respond(
|
||||
permission: u32,
|
||||
option: Option<String>,
|
||||
) -> IdeResult<()> {
|
||||
host.require_trust(window)?;
|
||||
host.project(window)?.agents.respond(&task, permission, option)
|
||||
host.require_trust_if_project(window)?;
|
||||
host.automations.route_respond(host, window, task, permission, option)
|
||||
}
|
||||
|
||||
#[command(trust = always)]
|
||||
pub fn agent_archive(host: &Host, window: &str, task: String) -> IdeResult<()> {
|
||||
host.project(window)?.agents.archive(&task)
|
||||
match host.automations.authorized_local_manager(host, window, &task, false)? {
|
||||
Some(mgr) => mgr.archive(&task),
|
||||
None => host.project(window)?.agents.archive(&task),
|
||||
}
|
||||
}
|
||||
|
||||
#[command(trust = always)]
|
||||
pub fn agent_unarchive(host: &Host, window: &str, task: String) -> IdeResult<()> {
|
||||
host.project(window)?.agents.unarchive(&task)
|
||||
match host.automations.authorized_local_manager(host, window, &task, false)? {
|
||||
Some(mgr) => mgr.unarchive(&task),
|
||||
None => host.project(window)?.agents.unarchive(&task),
|
||||
}
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub fn agent_rename(host: &Host, window: &str, task: String, title: String) -> IdeResult<()> {
|
||||
host.project(window)?.agents.rename(&task, &title)
|
||||
host.require_trust_if_project(window)?;
|
||||
match host.automations.authorized_local_manager(host, window, &task, true)? {
|
||||
Some(mgr) => mgr.rename(&task, &title),
|
||||
None => {
|
||||
host.require_trust(window)?;
|
||||
host.project(window)?.agents.rename(&task, &title)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn agent_delete(host: &Host, window: &str, task: String, remove_worktree: bool) -> IdeResult<()> {
|
||||
host.require_trust(window)?;
|
||||
host.project(window)?.agents.delete(&task, remove_worktree).await
|
||||
host.require_trust_if_project(window)?;
|
||||
match host.automations.authorized_local_manager(host, window, &task, true)? {
|
||||
Some(mgr) => mgr.delete(&task, remove_worktree).await,
|
||||
None => {
|
||||
host.require_trust(window)?;
|
||||
host.project(window)?.agents.delete(&task, remove_worktree).await
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The task's changed files as `view` compares them (without: since it started).
|
||||
@@ -956,7 +1009,20 @@ fn listed(
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
let plug_policy = host_plugins_policy(host, project.map(|p| p.as_ref()));
|
||||
let home = host.home_dir();
|
||||
let plug_states = ide_agent::plugins::resolve_plugins(
|
||||
ide_agent::plugins::discover_plugins(&plug_policy.workspace_roots, home.as_deref()),
|
||||
&plug_policy,
|
||||
Some(&*host.agent_secrets),
|
||||
);
|
||||
let projected = ide_agent::plugins::projected_mcp_servers(
|
||||
&plug_states,
|
||||
&plug_policy,
|
||||
home.as_deref(),
|
||||
Some(&*host.agent_secrets),
|
||||
);
|
||||
ide_agent::mcp::merge_projected_servers(out, projected)
|
||||
}
|
||||
|
||||
/// The MCP servers agent sessions of the project at `root` get: the user's, values filled in, and
|
||||
@@ -1315,27 +1381,43 @@ pub fn agent_set_memory_overrides(
|
||||
host.project(window)?.agents.set_memory_overrides(&task, overrides)
|
||||
}
|
||||
|
||||
fn resolve_skills_with_host_plugins(
|
||||
policy: &SkillsPolicy,
|
||||
plug_policy: &ide_agent::plugins::PluginsPolicy,
|
||||
home: Option<&std::path::Path>,
|
||||
secrets: Option<&dyn ide_agent::EnvSecrets>,
|
||||
) -> Vec<AgentSkillState> {
|
||||
let plug_states = ide_agent::plugins::resolve_plugins(
|
||||
ide_agent::plugins::discover_plugins(&policy.workspace_roots, home),
|
||||
plug_policy,
|
||||
secrets,
|
||||
);
|
||||
let projected = ide_agent::plugins::projected_skill_roots(&plug_states, None);
|
||||
ide_agent::skills::resolve(
|
||||
ide_agent::skills::discover_skills_with_agent_plugins(
|
||||
&policy.workspace_roots,
|
||||
home,
|
||||
&policy.plugin_dirs,
|
||||
&projected,
|
||||
),
|
||||
None,
|
||||
&policy.workspace,
|
||||
&policy.user,
|
||||
policy.workspace_trusted,
|
||||
)
|
||||
}
|
||||
|
||||
/// Every skill discovered in the project, the user's folders and enabled plugins, with
|
||||
/// the mode a session runs it with (without any session's own overrides).
|
||||
#[command(trust = always)]
|
||||
pub async fn agent_skills_list(host: &Host, window: &str) -> IdeResult<Vec<AgentSkillState>> {
|
||||
let project = host.project(window).ok().filter(|p| !p.light);
|
||||
let policy = host_skills_policy(host, project.as_deref());
|
||||
let home = dirs::home_dir();
|
||||
blocking(move || {
|
||||
Ok(ide_agent::skills::resolve(
|
||||
ide_agent::skills::discover_skills_with_plugins(
|
||||
&policy.workspace_roots,
|
||||
home.as_deref(),
|
||||
&policy.plugin_dirs,
|
||||
),
|
||||
None,
|
||||
&policy.workspace,
|
||||
&policy.user,
|
||||
policy.workspace_trusted,
|
||||
))
|
||||
})
|
||||
.await
|
||||
let plug_policy = host_plugins_policy(host, project.as_deref());
|
||||
let home = host.home_dir();
|
||||
let secrets = host.agent_secrets.clone();
|
||||
blocking(move || Ok(resolve_skills_with_host_plugins(&policy, &plug_policy, home.as_deref(), Some(&*secrets))))
|
||||
.await
|
||||
}
|
||||
|
||||
/// Sets how `name` may run in `scope`, in the settings file of that scope, and returns the
|
||||
@@ -1380,14 +1462,9 @@ pub fn agent_skills_set_mode(
|
||||
}
|
||||
}
|
||||
let policy = host_skills_policy(host, project.as_deref());
|
||||
let home = dirs::home_dir();
|
||||
Ok(ide_agent::skills::resolve(
|
||||
ide_agent::skills::discover_skills_with_plugins(&policy.workspace_roots, home.as_deref(), &policy.plugin_dirs),
|
||||
None,
|
||||
&policy.workspace,
|
||||
&policy.user,
|
||||
policy.workspace_trusted,
|
||||
))
|
||||
let plug_policy = host_plugins_policy(host, project.as_deref());
|
||||
let home = host.home_dir();
|
||||
Ok(resolve_skills_with_host_plugins(&policy, &plug_policy, home.as_deref(), Some(&*host.agent_secrets)))
|
||||
}
|
||||
|
||||
/// Resolves a GitHub `owner/repo[/path][@ref]` source and lists the `SKILL.md` skills in it.
|
||||
@@ -1478,20 +1555,10 @@ pub async fn agent_skills_install(
|
||||
}
|
||||
|
||||
let policy = host_skills_policy(host, project.as_deref());
|
||||
blocking(move || {
|
||||
Ok(ide_agent::skills::resolve(
|
||||
ide_agent::skills::discover_skills_with_plugins(
|
||||
&policy.workspace_roots,
|
||||
home.as_deref(),
|
||||
&policy.plugin_dirs,
|
||||
),
|
||||
None,
|
||||
&policy.workspace,
|
||||
&policy.user,
|
||||
policy.workspace_trusted,
|
||||
))
|
||||
})
|
||||
.await
|
||||
let plug_policy = host_plugins_policy(host, project.as_deref());
|
||||
let secrets = host.agent_secrets.clone();
|
||||
blocking(move || Ok(resolve_skills_with_host_plugins(&policy, &plug_policy, home.as_deref(), Some(&*secrets))))
|
||||
.await
|
||||
}
|
||||
|
||||
/// The user's and the workspace's skill policies (`[agents.skills.<name>]`).
|
||||
@@ -1650,9 +1717,18 @@ fn persist_memory_settings(
|
||||
|
||||
async fn current_memory_catalog(host: &Host, project: Option<&crate::Project>) -> IdeResult<AgentMemoryCatalog> {
|
||||
let policy = host_memory_policy(host, project);
|
||||
let plug_policy = host_plugins_policy(host, project);
|
||||
let home = host.home_dir();
|
||||
let secrets = host.agent_secrets.clone();
|
||||
blocking(move || {
|
||||
let entries = ide_agent::memory::discover_memories(&policy.workspace_roots, home.as_deref());
|
||||
let plug_states = ide_agent::plugins::resolve_plugins(
|
||||
ide_agent::plugins::discover_plugins(&policy.workspace_roots, home.as_deref()),
|
||||
&plug_policy,
|
||||
Some(&*secrets),
|
||||
);
|
||||
let projected = ide_agent::plugins::projected_memory_entries(&plug_states);
|
||||
let entries =
|
||||
ide_agent::memory::discover_memories_with_plugins(&policy.workspace_roots, home.as_deref(), projected);
|
||||
Ok(ide_agent::memory::resolve_catalog(entries, None, &policy, home.as_deref()))
|
||||
})
|
||||
.await
|
||||
@@ -1852,6 +1928,307 @@ pub async fn agent_memory_reset_provider(host: &Host, window: &str, provider: St
|
||||
current_memory_catalog(host, project.as_deref()).await
|
||||
}
|
||||
|
||||
fn host_plugins_policy(host: &Host, project: Option<&crate::Project>) -> ide_agent::plugins::PluginsPolicy {
|
||||
match project {
|
||||
Some(project) => ide_agent::plugins::PluginsPolicy {
|
||||
user: project.settings.layer(ide_workspace::settings::SettingsScope::Global).agents.plugins.clone(),
|
||||
workspace: project.settings.layer(ide_workspace::settings::SettingsScope::Project).agents.plugins.clone(),
|
||||
workspace_trusted: project.trusted.load(std::sync::atomic::Ordering::Acquire),
|
||||
workspace_roots: workspace_skill_roots(&project.root),
|
||||
approved_capabilities: host.plugin_approvals.snapshot(),
|
||||
},
|
||||
None => ide_agent::plugins::PluginsPolicy {
|
||||
user: host.global_settings.effective().agents.plugins.clone(),
|
||||
workspace: Default::default(),
|
||||
workspace_trusted: true,
|
||||
workspace_roots: Vec::new(),
|
||||
approved_capabilities: host.plugin_approvals.snapshot(),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn plugins_settings_layers(
|
||||
host: &Host,
|
||||
project: Option<&std::sync::Arc<crate::Project>>,
|
||||
) -> (AgentPluginSettings, Option<AgentPluginSettings>) {
|
||||
let user = host.global_settings.effective().agents.plugins.clone();
|
||||
let workspace =
|
||||
project.map(|p| p.settings.layer(ide_workspace::settings::SettingsScope::Project).agents.plugins.clone());
|
||||
(user, workspace)
|
||||
}
|
||||
|
||||
fn is_default_plugin_settings(s: &AgentPluginSettings) -> bool {
|
||||
s.marketplaces.is_empty() && s.entries.is_empty()
|
||||
}
|
||||
|
||||
fn persist_plugin_settings(
|
||||
host: &Host,
|
||||
project: Option<&std::sync::Arc<crate::Project>>,
|
||||
scope: McpScope,
|
||||
settings: &AgentPluginSettings,
|
||||
) -> IdeResult<()> {
|
||||
let value = if is_default_plugin_settings(settings) {
|
||||
serde_json::Value::Null
|
||||
} else {
|
||||
serde_json::to_value(settings).map_err(|e| IdeError::invalid(e.to_string()))?
|
||||
};
|
||||
match scope {
|
||||
McpScope::User => {
|
||||
host.global_settings.set(ide_workspace::settings::SettingsScope::Global, "agents.plugins", value)?;
|
||||
for p in host.projects() {
|
||||
p.settings.reload();
|
||||
p.agents.notify_mcp_servers_changed();
|
||||
emit_plugin_projection_events(&p.sink);
|
||||
}
|
||||
}
|
||||
McpScope::Workspace => {
|
||||
let p = project.ok_or_else(|| IdeError::invalid("Open a project to configure workspace agent plugins"))?;
|
||||
p.settings.set(ide_workspace::settings::SettingsScope::Project, "agents.plugins", value)?;
|
||||
p.agents.notify_mcp_servers_changed();
|
||||
emit_plugin_projection_events(&p.sink);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn emit_plugin_projection_events(sink: &SharedSink) {
|
||||
for key in ["agents.plugins", "agents.skills", "agents.mcpServers", "agents.memory"] {
|
||||
sink.emit(IdeEvent::SettingsChanged { key: key.into() });
|
||||
}
|
||||
}
|
||||
|
||||
async fn current_plugins_catalog(host: &Host, project: Option<&crate::Project>) -> IdeResult<AgentPluginCatalog> {
|
||||
let policy = host_plugins_policy(host, project);
|
||||
let home = host.home_dir();
|
||||
let secrets = host.agent_secrets.clone();
|
||||
blocking(move || {
|
||||
let discovered = ide_agent::plugins::discover_plugins(&policy.workspace_roots, home.as_deref());
|
||||
Ok(ide_agent::plugins::resolve_catalog(discovered, &policy, home.as_deref(), Some(&*secrets)))
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Lists all discovered agent plugin bundles, registered/discovered marketplaces, and projection counts.
|
||||
#[command(trust = always)]
|
||||
pub async fn agent_plugins_list(host: &Host, window: &str) -> IdeResult<AgentPluginCatalog> {
|
||||
let project = host.project(window).ok().filter(|p| !p.light);
|
||||
current_plugins_catalog(host, project.as_deref()).await
|
||||
}
|
||||
|
||||
/// Enables or disables an installed plugin in that harness's native configuration.
|
||||
#[command(trust = always)]
|
||||
pub async fn agent_plugins_set_enabled(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
id: String,
|
||||
scope: McpScope,
|
||||
enabled: bool,
|
||||
approve_capabilities: bool,
|
||||
capability_hash: Option<String>,
|
||||
) -> IdeResult<AgentPluginCatalog> {
|
||||
let id = id.trim().to_owned();
|
||||
if id.is_empty() {
|
||||
return Err(IdeError::invalid("Plugin ID is required"));
|
||||
}
|
||||
let project = host.project(window).ok().filter(|p| !p.light);
|
||||
let project_root = project.as_ref().map(|p| p.root.clone());
|
||||
let policy = host_plugins_policy(host, project.as_deref());
|
||||
let home = host.home_dir();
|
||||
let lookup_id = id.clone();
|
||||
let home_for_discovery = home.clone();
|
||||
let found_plugin = blocking(move || {
|
||||
let discovered = ide_agent::plugins::discover_plugins(&policy.workspace_roots, home_for_discovery.as_deref());
|
||||
// Ids are owner-qualified and stable, so only an exact match may be toggled.
|
||||
Ok(discovered.into_iter().find(|p| p.scope == scope && p.id == lookup_id))
|
||||
})
|
||||
.await?;
|
||||
|
||||
let plugin = found_plugin.ok_or_else(|| IdeError::not_found(format!("Plugin `{id}` not found")))?;
|
||||
if plugin.scope == McpScope::Workspace {
|
||||
host.require_trust(window)?;
|
||||
}
|
||||
let approval_key = ide_agent::plugins::capability_approval_key(&plugin);
|
||||
let already_approved = approval_key.as_ref().is_some_and(|key| host.plugin_approvals.snapshot().contains(key));
|
||||
if enabled && plugin.capabilities.requires_consent && !approve_capabilities && !already_approved {
|
||||
return Err(IdeError::invalid("Approve the plugin's executable capabilities before enabling it"));
|
||||
}
|
||||
if approve_capabilities && let Some(key) = approval_key {
|
||||
// Approve only the capabilities the user was shown; re-inspection may have found others.
|
||||
if capability_hash.as_deref() != plugin.capabilities.capability_hash.as_deref() {
|
||||
return Err(IdeError::invalid(
|
||||
"The plugin's executable capabilities changed since they were shown; review them again",
|
||||
));
|
||||
}
|
||||
host.plugin_approvals.approve(key)?;
|
||||
}
|
||||
let plugin_for_write = plugin.clone();
|
||||
let home_for_write = home.clone();
|
||||
blocking(move || {
|
||||
ide_agent::plugins::set_plugin_enabled(
|
||||
&plugin_for_write,
|
||||
enabled,
|
||||
home_for_write.as_deref(),
|
||||
project_root.as_deref(),
|
||||
)
|
||||
})
|
||||
.await?;
|
||||
|
||||
for p in host.projects() {
|
||||
p.agents.notify_mcp_servers_changed();
|
||||
emit_plugin_projection_events(&p.sink);
|
||||
}
|
||||
current_plugins_catalog(host, project.as_deref()).await
|
||||
}
|
||||
|
||||
/// Registers a marketplace source (`owner/repo[#ref]`, GitHub URL, or local path) in `scope`.
|
||||
#[command(trust = always)]
|
||||
pub async fn agent_plugins_add_marketplace(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
scope: McpScope,
|
||||
source: String,
|
||||
) -> IdeResult<AgentPluginCatalog> {
|
||||
let clean = source.trim().to_owned();
|
||||
if clean.is_empty() {
|
||||
return Err(IdeError::invalid("Enter a marketplace repository or local path"));
|
||||
}
|
||||
if scope == McpScope::Workspace {
|
||||
host.require_trust(window)?;
|
||||
}
|
||||
let project = host.project(window).ok().filter(|p| !p.light);
|
||||
let (mut user, mut workspace) = plugins_settings_layers(host, project.as_ref());
|
||||
let target = match scope {
|
||||
McpScope::User => &mut user,
|
||||
McpScope::Workspace => {
|
||||
workspace.as_mut().ok_or_else(|| IdeError::invalid("Open a project to configure workspace marketplaces"))?
|
||||
}
|
||||
};
|
||||
if !target.marketplaces.iter().any(|m| m == &clean) {
|
||||
target.marketplaces.push(clean);
|
||||
let to_save = target.clone();
|
||||
persist_plugin_settings(host, project.as_ref(), scope, &to_save)?;
|
||||
}
|
||||
current_plugins_catalog(host, project.as_deref()).await
|
||||
}
|
||||
|
||||
/// Removes a registered marketplace source from `scope`.
|
||||
#[command(trust = always)]
|
||||
pub async fn agent_plugins_remove_marketplace(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
scope: McpScope,
|
||||
source: String,
|
||||
) -> IdeResult<AgentPluginCatalog> {
|
||||
let clean = source.trim();
|
||||
if scope == McpScope::Workspace {
|
||||
host.require_trust(window)?;
|
||||
}
|
||||
let project = host.project(window).ok().filter(|p| !p.light);
|
||||
let (mut user, mut workspace) = plugins_settings_layers(host, project.as_ref());
|
||||
let target = match scope {
|
||||
McpScope::User => &mut user,
|
||||
McpScope::Workspace => {
|
||||
workspace.as_mut().ok_or_else(|| IdeError::invalid("Open a project to configure workspace marketplaces"))?
|
||||
}
|
||||
};
|
||||
let before = target.marketplaces.len();
|
||||
target.marketplaces.retain(|m| m != clean);
|
||||
if target.marketplaces.len() != before {
|
||||
let to_save = target.clone();
|
||||
persist_plugin_settings(host, project.as_ref(), scope, &to_save)?;
|
||||
}
|
||||
current_plugins_catalog(host, project.as_deref()).await
|
||||
}
|
||||
|
||||
/// Browses installable plugins inside a marketplace (`owner/repo[#ref]`, GitHub URL, or local directory/manifest).
|
||||
#[command(trust = always)]
|
||||
pub async fn agent_plugins_browse_marketplace(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
source: String,
|
||||
request: RequestId,
|
||||
) -> IdeResult<AgentMarketplaceBrowseResult> {
|
||||
let cancel = host.begin_request(request);
|
||||
let ws_root = host.project(window).ok().filter(|p| !p.light).map(|p| p.root.clone());
|
||||
let home = host.home_dir();
|
||||
let search_path = ide_core::tool_path::search_path();
|
||||
let res = blocking(move || {
|
||||
let fetcher = ide_agent::skill_installer::GitHubHttpFetcher::new(&search_path)?;
|
||||
ide_agent::plugins::browse_marketplace(&fetcher, &source, home.as_deref(), ws_root.as_deref(), &cancel)
|
||||
})
|
||||
.await;
|
||||
host.end_request(request);
|
||||
res
|
||||
}
|
||||
|
||||
/// Previews an agent plugin bundle from GitHub or a local folder before installation, scanning files and capabilities.
|
||||
#[command(trust = always)]
|
||||
pub async fn agent_plugins_preview(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
source: String,
|
||||
subpath: Option<String>,
|
||||
marketplace: Option<String>,
|
||||
request: RequestId,
|
||||
) -> IdeResult<AgentPluginPreview> {
|
||||
let cancel = host.begin_request(request);
|
||||
let ws_root = host.project(window).ok().filter(|p| !p.light).map(|p| p.root.clone());
|
||||
let home = host.home_dir();
|
||||
let search_path = ide_core::tool_path::search_path();
|
||||
let res = blocking(move || {
|
||||
let fetcher = ide_agent::skill_installer::GitHubHttpFetcher::new(&search_path)?;
|
||||
ide_agent::plugins::preview_plugin(
|
||||
&fetcher,
|
||||
&source,
|
||||
subpath.as_deref(),
|
||||
marketplace.as_deref(),
|
||||
home.as_deref(),
|
||||
ws_root.as_deref(),
|
||||
&cancel,
|
||||
)
|
||||
})
|
||||
.await;
|
||||
host.end_request(request);
|
||||
res
|
||||
}
|
||||
|
||||
/// Atomically installs a previewed agent plugin into the selected harness's native plugin directory.
|
||||
#[command(trust = always)]
|
||||
pub async fn agent_plugins_install(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
input: InstallAgentPluginRequest,
|
||||
request: RequestId,
|
||||
) -> IdeResult<AgentPluginCatalog> {
|
||||
let project = host.project(window).ok().filter(|p| !p.light);
|
||||
if input.scope == McpScope::Workspace || input.source_kind == "local" {
|
||||
host.require_trust(window)?;
|
||||
}
|
||||
let ws_root = project.as_ref().map(|p| p.root.clone());
|
||||
let home = host.home_dir();
|
||||
let cancel = host.begin_request(request);
|
||||
let search_path = ide_core::tool_path::search_path();
|
||||
let req_clone = input.clone();
|
||||
let install_res = blocking(move || {
|
||||
let fetcher = ide_agent::skill_installer::GitHubHttpFetcher::new(&search_path)?;
|
||||
ide_agent::plugins::install_plugin(&fetcher, &req_clone, home.as_deref(), ws_root.as_deref(), &cancel)
|
||||
})
|
||||
.await;
|
||||
host.end_request(request);
|
||||
let (_, approval_key) = install_res?;
|
||||
if input.approve_capabilities
|
||||
&& let Some(key) = approval_key
|
||||
{
|
||||
host.plugin_approvals.approve(key)?;
|
||||
}
|
||||
for p in host.projects() {
|
||||
p.agents.notify_mcp_servers_changed();
|
||||
emit_plugin_projection_events(&p.sink);
|
||||
}
|
||||
|
||||
current_plugins_catalog(host, project.as_deref()).await
|
||||
}
|
||||
|
||||
fn validate_project_root(root: &std::path::Path, requested: Option<&std::path::Path>) -> IdeResult<std::path::PathBuf> {
|
||||
let Some(requested) = requested else {
|
||||
return Ok(root.to_path_buf());
|
||||
@@ -1869,6 +2246,312 @@ fn validate_project_root(root: &std::path::Path, requested: Option<&std::path::P
|
||||
Err(IdeError::invalid("Agent project must be the window project or a workspace member"))
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Agent Automations & In-Session Schedules
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
fn host_label_for(remote: bool) -> String {
|
||||
std::env::var("HOSTNAME")
|
||||
.ok()
|
||||
.filter(|s| !s.trim().is_empty())
|
||||
.unwrap_or_else(|| if remote { "Remote Server".into() } else { "Local Host".into() })
|
||||
}
|
||||
|
||||
fn window_automation_scope(host: &Host, window: &str) -> (Option<Vec<std::path::PathBuf>>, bool) {
|
||||
if let Some(p) = host.project(window).ok().filter(|p| !p.light) {
|
||||
let trusted = host.trust.window_trusted(&p.root).unwrap_or(false);
|
||||
let mut roots = vec![dunce::canonicalize(&p.root).unwrap_or_else(|_| p.root.clone())];
|
||||
if let Ok(Some(ws)) = ide_workspace::workspace::Workspace::load(&p.root) {
|
||||
for member in ws.projects {
|
||||
let canon = dunce::canonicalize(&member).unwrap_or(member);
|
||||
if !roots.contains(&canon) {
|
||||
roots.push(canon);
|
||||
}
|
||||
}
|
||||
}
|
||||
(Some(roots), trusted)
|
||||
} else {
|
||||
(Some(Vec::new()), true)
|
||||
}
|
||||
}
|
||||
|
||||
fn require_window_trust_if_project(host: &Host, window: &str) -> IdeResult<()> {
|
||||
if let Some(p) = host.project(window).ok().filter(|p| !p.light) {
|
||||
p.require_trust()?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn ensure_window_owns_automation(host: &Host, window: &str, id: &str) -> IdeResult<AgentAutomation> {
|
||||
require_window_trust_if_project(host, window)?;
|
||||
let auto = host.automations.get(id).ok_or_else(|| IdeError::not_found(format!("unknown automation '{id}'")))?;
|
||||
let (allowed_roots, include_chat_only) = window_automation_scope(host, window);
|
||||
if let Some(roots) = allowed_roots {
|
||||
match &auto.workspace {
|
||||
AutomationWorkspace::ChatOnly if include_chat_only => {}
|
||||
AutomationWorkspace::ChatOnly => {
|
||||
return Err(IdeError::invalid("Trust the project before accessing automations"));
|
||||
}
|
||||
AutomationWorkspace::Project { root, .. } => {
|
||||
let cand = dunce::canonicalize(&root.0).unwrap_or_else(|_| root.0.clone());
|
||||
if !roots.contains(&cand) {
|
||||
return Err(IdeError::invalid("Automation belongs to a different project"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(auto)
|
||||
}
|
||||
|
||||
fn ensure_window_owns_session_schedule(host: &Host, window: &str, id: &str) -> IdeResult<()> {
|
||||
host.require_trust(window)?;
|
||||
let (allowed_roots, _) = window_automation_scope(host, window);
|
||||
if let Some(roots) = allowed_roots {
|
||||
let schedules = host.automations.list_session_schedules_scoped(Some(&roots), None);
|
||||
if !schedules.iter().any(|s| s.id == id) {
|
||||
return Err(IdeError::not_found(format!("unknown session schedule '{id}'")));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Returns the current project's automations, first page of run history, active session schedules,
|
||||
/// and scheduler/boot-service status.
|
||||
#[command(trust = always)]
|
||||
pub async fn agent_automation_snapshot(
|
||||
host: &std::sync::Arc<Host>,
|
||||
window: &str,
|
||||
remote: bool,
|
||||
) -> IdeResult<AutomationSnapshot> {
|
||||
let (allowed_roots, include_chat_only) = window_automation_scope(host, window);
|
||||
let h = host.clone();
|
||||
host.blocking(move || {
|
||||
Ok(h.automations.snapshot_scoped(
|
||||
&h,
|
||||
allowed_roots.as_deref(),
|
||||
include_chat_only,
|
||||
remote,
|
||||
host_label_for(remote),
|
||||
))
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Creates or updates an [`AgentAutomation`]. Project-scoped automations require a trusted project.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn agent_automation_save(
|
||||
host: &std::sync::Arc<Host>,
|
||||
window: &str,
|
||||
mut input: SaveAutomationInput,
|
||||
) -> IdeResult<AgentAutomation> {
|
||||
require_window_trust_if_project(host, window)?;
|
||||
if let Some(existing_id) = input.id.as_deref() {
|
||||
let _ = ensure_window_owns_automation(host, window, existing_id)?;
|
||||
}
|
||||
if let AutomationWorkspace::Project { root, isolation, base, auto_clean_worktree } = input.workspace {
|
||||
let project = host.project(window).ok().filter(|p| !p.light);
|
||||
let validated = match &project {
|
||||
Some(p) => {
|
||||
p.require_trust()?;
|
||||
validate_project_root(&p.root, Some(&root.0))?
|
||||
}
|
||||
None => {
|
||||
if !host.trust.window_trusted(&root.0)? {
|
||||
return Err(IdeError::invalid("Trust the project before creating an automation in it"));
|
||||
}
|
||||
dunce::canonicalize(&root.0)?
|
||||
}
|
||||
};
|
||||
input.workspace =
|
||||
AutomationWorkspace::Project { root: IpcPath(validated), isolation, base, auto_clean_worktree };
|
||||
}
|
||||
let h = host.clone();
|
||||
host.blocking(move || h.automations.save(&h, input)).await
|
||||
}
|
||||
|
||||
/// Enables or pauses an automation schedule.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn agent_automation_set_enabled(
|
||||
host: &std::sync::Arc<Host>,
|
||||
window: &str,
|
||||
id: String,
|
||||
enabled: bool,
|
||||
) -> IdeResult<AgentAutomation> {
|
||||
let _ = ensure_window_owns_automation(host, window, &id)?;
|
||||
let h = host.clone();
|
||||
host.blocking(move || h.automations.set_enabled(&h, &id, enabled)).await
|
||||
}
|
||||
|
||||
/// Pauses all enabled schedules (for the current window's project, or across all projects when `all_projects` is true).
|
||||
#[command(trust = trusted)]
|
||||
pub async fn agent_automation_pause_all(
|
||||
host: &std::sync::Arc<Host>,
|
||||
window: &str,
|
||||
all_projects: bool,
|
||||
) -> IdeResult<u32> {
|
||||
require_window_trust_if_project(host, window)?;
|
||||
let (allowed_roots, include_chat_only) =
|
||||
if all_projects { (None, true) } else { window_automation_scope(host, window) };
|
||||
let h = host.clone();
|
||||
host.blocking(move || h.automations.pause_all_scoped(&h, allowed_roots.as_deref(), include_chat_only)).await
|
||||
}
|
||||
|
||||
/// Deletes an automation and its run history entries.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn agent_automation_delete(host: &std::sync::Arc<Host>, window: &str, id: String) -> IdeResult<()> {
|
||||
let _ = ensure_window_owns_automation(host, window, &id)?;
|
||||
let h = host.clone();
|
||||
host.blocking(move || h.automations.delete(&h, &id)).await
|
||||
}
|
||||
|
||||
/// Immediately triggers a manual run of automation `id`.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn agent_automation_run_now(
|
||||
host: &std::sync::Arc<Host>,
|
||||
window: &str,
|
||||
id: String,
|
||||
) -> IdeResult<AutomationRun> {
|
||||
let _ = ensure_window_owns_automation(host, window, &id)?;
|
||||
host.automations.clone().run_now(host, &id).await
|
||||
}
|
||||
|
||||
/// Lists paginated automation run history.
|
||||
#[command(trust = always)]
|
||||
pub async fn agent_automation_runs(
|
||||
host: &std::sync::Arc<Host>,
|
||||
window: &str,
|
||||
automation_id: Option<String>,
|
||||
cursor: Option<u32>,
|
||||
limit: Option<u32>,
|
||||
) -> IdeResult<AutomationRunsPage> {
|
||||
let (allowed_roots, include_chat_only) = window_automation_scope(host, window);
|
||||
let h = host.clone();
|
||||
host.blocking(move || {
|
||||
Ok(h.automations.runs_scoped(
|
||||
allowed_roots.as_deref(),
|
||||
include_chat_only,
|
||||
automation_id.as_deref(),
|
||||
cursor,
|
||||
limit,
|
||||
))
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Marks one run, one automation's runs, or all runs in the current window's scope as read.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn agent_automation_mark_read(
|
||||
host: &std::sync::Arc<Host>,
|
||||
window: &str,
|
||||
run_id: Option<String>,
|
||||
automation_id: Option<String>,
|
||||
) -> IdeResult<()> {
|
||||
require_window_trust_if_project(host, window)?;
|
||||
let (allowed_roots, include_chat_only) = window_automation_scope(host, window);
|
||||
let h = host.clone();
|
||||
host.blocking(move || {
|
||||
h.automations.mark_read_scoped(
|
||||
&h,
|
||||
allowed_roots.as_deref(),
|
||||
include_chat_only,
|
||||
run_id.as_deref(),
|
||||
automation_id.as_deref(),
|
||||
)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Previews the next `count` firing timestamps (epoch ms) for a schedule trigger.
|
||||
#[command(trust = always)]
|
||||
pub async fn agent_automation_preview_schedule(
|
||||
host: &std::sync::Arc<Host>,
|
||||
trigger: AutomationTrigger,
|
||||
count: Option<u32>,
|
||||
) -> IdeResult<Vec<f64>> {
|
||||
let h = host.clone();
|
||||
host.blocking(move || h.automations.preview_schedule(&trigger, count)).await
|
||||
}
|
||||
|
||||
/// Exports automation `id` into portable `.automation.md` text.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn agent_automation_export_markdown(
|
||||
host: &std::sync::Arc<Host>,
|
||||
window: &str,
|
||||
id: String,
|
||||
) -> IdeResult<String> {
|
||||
let _ = ensure_window_owns_automation(host, window, &id)?;
|
||||
let h = host.clone();
|
||||
host.blocking(move || h.automations.export_markdown(&id)).await
|
||||
}
|
||||
|
||||
/// Imports a `.automation.md` template into the current project (or as ChatOnly) with `enabled = false`.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn agent_automation_import_markdown(
|
||||
host: &std::sync::Arc<Host>,
|
||||
window: &str,
|
||||
markdown: String,
|
||||
chat_only: bool,
|
||||
provider: String,
|
||||
) -> IdeResult<AgentAutomation> {
|
||||
require_window_trust_if_project(host, window)?;
|
||||
let workspace = if chat_only {
|
||||
AutomationWorkspace::ChatOnly
|
||||
} else {
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
AutomationWorkspace::Project {
|
||||
root: IpcPath(project.root.clone()),
|
||||
isolation: Isolation::Worktree,
|
||||
base: None,
|
||||
auto_clean_worktree: true,
|
||||
}
|
||||
};
|
||||
let h = host.clone();
|
||||
host.blocking(move || h.automations.import_markdown(&h, &markdown, workspace, provider)).await
|
||||
}
|
||||
|
||||
/// Attaches a `Send Later` one-shot or `/loop` recurring schedule to an existing task session.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn agent_session_schedule_create(
|
||||
host: &std::sync::Arc<Host>,
|
||||
window: &str,
|
||||
input: CreateSessionScheduleInput,
|
||||
) -> IdeResult<SessionSchedule> {
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
let root = project.root.clone();
|
||||
let h = host.clone();
|
||||
host.blocking(move || h.automations.create_session_schedule(&h, root, input)).await
|
||||
}
|
||||
|
||||
/// Pauses or resumes an in-session `/loop` or `Send Later` schedule.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn agent_session_schedule_set_paused(
|
||||
host: &std::sync::Arc<Host>,
|
||||
window: &str,
|
||||
id: String,
|
||||
paused: bool,
|
||||
) -> IdeResult<SessionSchedule> {
|
||||
ensure_window_owns_session_schedule(host, window, &id)?;
|
||||
let h = host.clone();
|
||||
host.blocking(move || h.automations.set_session_schedule_paused(&h, &id, paused)).await
|
||||
}
|
||||
|
||||
/// Sends a queued `Send Later` prompt or fires a `/loop` iteration immediately.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn agent_session_schedule_run_now(host: &std::sync::Arc<Host>, window: &str, id: String) -> IdeResult<()> {
|
||||
ensure_window_owns_session_schedule(host, window, &id)?;
|
||||
host.automations.clone().run_session_schedule_now(host, &id).await
|
||||
}
|
||||
|
||||
/// Cancels and deletes an in-session `Send Later` or `/loop` schedule.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn agent_session_schedule_delete(host: &std::sync::Arc<Host>, window: &str, id: String) -> IdeResult<()> {
|
||||
ensure_window_owns_session_schedule(host, window, &id)?;
|
||||
let h = host.clone();
|
||||
host.blocking(move || h.automations.delete_session_schedule(&h, &id)).await
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -2111,6 +2794,17 @@ ide_command::domain!(
|
||||
agent_context_usage,
|
||||
agent_changes,
|
||||
agent_cli_update,
|
||||
agent_automation_delete,
|
||||
agent_automation_export_markdown,
|
||||
agent_automation_import_markdown,
|
||||
agent_automation_mark_read,
|
||||
agent_automation_pause_all,
|
||||
agent_automation_preview_schedule,
|
||||
agent_automation_run_now,
|
||||
agent_automation_runs,
|
||||
agent_automation_save,
|
||||
agent_automation_set_enabled,
|
||||
agent_automation_snapshot,
|
||||
agent_cli_update_check,
|
||||
agent_commands,
|
||||
agent_copilot_auth_status,
|
||||
@@ -2143,6 +2837,13 @@ ide_command::domain!(
|
||||
agent_memory_reset_provider,
|
||||
agent_memory_set_auto,
|
||||
agent_memory_set_mode,
|
||||
agent_plugins_add_marketplace,
|
||||
agent_plugins_browse_marketplace,
|
||||
agent_plugins_install,
|
||||
agent_plugins_list,
|
||||
agent_plugins_preview,
|
||||
agent_plugins_remove_marketplace,
|
||||
agent_plugins_set_enabled,
|
||||
agent_poke_network,
|
||||
agent_preview_copilot_models,
|
||||
agent_probe,
|
||||
@@ -2160,6 +2861,10 @@ ide_command::domain!(
|
||||
agent_rollback,
|
||||
agent_rollback_changes,
|
||||
agent_send_queued_now,
|
||||
agent_session_schedule_create,
|
||||
agent_session_schedule_delete,
|
||||
agent_session_schedule_run_now,
|
||||
agent_session_schedule_set_paused,
|
||||
agent_set_additional_args,
|
||||
agent_set_auto_resume_once,
|
||||
agent_set_command,
|
||||
|
||||
@@ -1314,7 +1314,11 @@ mod build_tool_settings_tests {
|
||||
let configure = config("configure", &["-S", ".", "-B", "release", "-G", "Ninja"]);
|
||||
let mut build =
|
||||
config("target", &["--build", "release", "--target", "hello", "--config", "Release", "-j", "8"]);
|
||||
build.extras.before_launch.push(ide_run::BeforeLaunchTask { kind: "build".into(), target: "configure".into() });
|
||||
build.extras.before_launch.push(ide_run::BeforeLaunchTask {
|
||||
kind: "build".into(),
|
||||
target: "configure".into(),
|
||||
..Default::default()
|
||||
});
|
||||
let configs = [configure, build];
|
||||
for kind in [BuildKind::Build, BuildKind::Rebuild] {
|
||||
let plan = cmake_plan(root.path(), kind, &configs, "target").unwrap();
|
||||
|
||||
@@ -1,13 +1,15 @@
|
||||
mod kotlin;
|
||||
#[cfg(test)]
|
||||
mod kotlin_tests;
|
||||
#[cfg(test)]
|
||||
mod native_tests;
|
||||
mod output;
|
||||
|
||||
use crate::Host;
|
||||
use ide_command::command;
|
||||
use ide_core::{DebugSessionId, IdeResult};
|
||||
use ide_dap::*;
|
||||
use std::path::PathBuf;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// Starts a session owned by this window: its events (and those of child sessions) go here only.
|
||||
#[command(trust = trusted)]
|
||||
@@ -140,6 +142,17 @@ pub async fn debug_start(host: &Host, window: &str, config: LaunchConfig) -> Ide
|
||||
config = add_java_source_paths(config, &roots);
|
||||
}
|
||||
let root = config.cwd.clone().map(PathBuf::from).unwrap_or_default();
|
||||
// No lldb-dap on this host (most Linux hosts): CodeLLDB, else GDB 14+.
|
||||
if config.adapter == "lldb-dap" {
|
||||
let (root, settings) = (root.clone(), settings.clone());
|
||||
let project_root = project.root.clone();
|
||||
config = ide_dap::native::choose(config, move |command| {
|
||||
native_debugger_command(&project_root, &settings.debugger.cpp, command)
|
||||
.or_else(|| ide_sdk::apply::tool_command(&root, &settings, command))
|
||||
.or_else(|| ide_dap::adapter::resolve_binary(command, &root))
|
||||
})
|
||||
.await?;
|
||||
}
|
||||
let mut ruby_tools = Vec::new();
|
||||
if config.adapter == "rdbg" && config.request == "launch" {
|
||||
let project_root = host.project(window).map(|p| p.root.clone()).unwrap_or_else(|_| root.clone());
|
||||
@@ -152,11 +165,13 @@ pub async fn debug_start(host: &Host, window: &str, config: LaunchConfig) -> Ide
|
||||
.await?;
|
||||
}
|
||||
let java_analyzer = java_analyzer_command(host, window, &config)?;
|
||||
let native = native_debugger_command(&project.root, &settings.debugger.cpp, &config.adapter);
|
||||
let custom = |command: &str| {
|
||||
if let Some(binary) = java_analyzer {
|
||||
return Some(binary.to_string_lossy().into_owned());
|
||||
}
|
||||
let path = ide_sdk::apply::tool_command(&root, &settings, command)
|
||||
let path = native
|
||||
.or_else(|| ide_sdk::apply::tool_command(&root, &settings, command))
|
||||
.or_else(|| ruby_tools.into_iter().find(|(name, _)| *name == command).map(|(_, path)| path))?;
|
||||
Some(path.to_string_lossy().into_owned())
|
||||
};
|
||||
@@ -188,6 +203,19 @@ pub async fn debug_start(host: &Host, window: &str, config: LaunchConfig) -> Ide
|
||||
result
|
||||
}
|
||||
|
||||
fn native_debugger_command(
|
||||
root: &Path,
|
||||
settings: &ide_core::settings::CppDebuggerSettings,
|
||||
adapter: &str,
|
||||
) -> Option<PathBuf> {
|
||||
let path = match adapter {
|
||||
"gdb" => &settings.gdb_executable,
|
||||
"lldb-dap" => &settings.lldb_dap_executable,
|
||||
_ => return None,
|
||||
};
|
||||
ide_sdk::apply::setting_path(root, path)
|
||||
}
|
||||
|
||||
/// For java-analyzer's debugger, the executable of the java-analyzer serving the module
|
||||
/// (`projectRoot`, else the working directory), so the session debugs with the server that
|
||||
/// analyzes the code.
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
use super::*;
|
||||
use ide_core::IdeError;
|
||||
use ide_dap::adapter::{AdapterLauncher, AdapterSpec, LaunchFuture};
|
||||
use ide_workspace::SettingsScope;
|
||||
use parking_lot::Mutex;
|
||||
use std::sync::Arc;
|
||||
|
||||
#[derive(Default)]
|
||||
struct CaptureAdapter(Mutex<Option<AdapterSpec>>);
|
||||
|
||||
impl AdapterLauncher for CaptureAdapter {
|
||||
fn launch(&self, spec: AdapterSpec, _: Option<u16>) -> LaunchFuture {
|
||||
*self.0.lock() = Some(spec);
|
||||
Box::pin(async { Err(IdeError::cancelled()) })
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn cpp_debugger_paths_override_adapter_commands() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(dir.path()).unwrap();
|
||||
let root = base.join("project");
|
||||
let cwd = root.join("build");
|
||||
std::fs::create_dir_all(&cwd).unwrap();
|
||||
let capture = Arc::new(CaptureAdapter::default());
|
||||
let mut host = Host::new(crate::HostConfig::for_test(&base));
|
||||
host.debugger = DebugManager::with_launcher(host.languages.clone(), capture.clone());
|
||||
host.open_project("main", &root).unwrap();
|
||||
host.set_project_trust(&root, true, false).await.unwrap();
|
||||
let project = host.project("main").unwrap();
|
||||
|
||||
for (adapter, key, configured) in [
|
||||
("gdb", "gdbExecutable", root.join("custom gdb").to_str().unwrap().to_owned()),
|
||||
("lldb-dap", "lldbDapExecutable", "tools/lldb-dap-custom".into()),
|
||||
] {
|
||||
let config = LaunchConfig {
|
||||
name: "C++".into(),
|
||||
adapter: adapter.into(),
|
||||
request: "attach".into(),
|
||||
program: None,
|
||||
args: vec![],
|
||||
cwd: Some(cwd.clone().into()),
|
||||
env: Default::default(),
|
||||
extra_json: Some(r#"{"pid":1}"#.into()),
|
||||
};
|
||||
let _ = debug_start(&host, "main", config.clone()).await.unwrap_err();
|
||||
assert_eq!(capture.0.lock().take().unwrap().command, adapter);
|
||||
|
||||
project
|
||||
.settings
|
||||
.set(SettingsScope::Project, &format!("debugger.cpp.{key}"), serde_json::json!(configured))
|
||||
.unwrap();
|
||||
let mut config = config;
|
||||
config.request = "launch".into();
|
||||
config.program = Some(cwd.join("app").to_str().unwrap().to_owned());
|
||||
config.extra_json = None;
|
||||
let _ = debug_start(&host, "main", config).await.unwrap_err();
|
||||
let spec = capture.0.lock().take().unwrap();
|
||||
assert_eq!(spec.adapter, adapter);
|
||||
assert_eq!(Path::new(&spec.command), root.join(configured));
|
||||
assert_eq!(spec.cwd, cwd);
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,52 @@ pub async fn fs_entry_kind(host: &Host, path: PathBuf) -> IdeResult<ide_vfs::Ent
|
||||
.await
|
||||
}
|
||||
|
||||
/// Rejects relative paths and any `..` parent traversal without touching the filesystem.
|
||||
fn reject_parent_traversal(path: &Path) -> Option<PathBuf> {
|
||||
use std::path::Component;
|
||||
if !path.is_absolute() {
|
||||
return None;
|
||||
}
|
||||
let mut out = PathBuf::new();
|
||||
for comp in path.components() {
|
||||
match comp {
|
||||
Component::Prefix(p) => out.push(p.as_os_str()),
|
||||
Component::RootDir => out.push(comp.as_os_str()),
|
||||
Component::CurDir => {}
|
||||
Component::ParentDir => return None,
|
||||
Component::Normal(c) => out.push(c),
|
||||
}
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// Resolves symlinks for a path inside the window's project roots and returns its canonical path.
|
||||
/// Rejects relative paths, `..` parent traversal, and paths outside those roots before touching
|
||||
/// the filesystem, and rejects symlink targets that canonicalize outside those roots.
|
||||
#[command(trust = always)]
|
||||
pub async fn fs_canonicalize(host: &Host, window: &str, path: PathBuf) -> IdeResult<ide_core::IpcPath> {
|
||||
let project = host.project(window)?;
|
||||
host.blocking(move || {
|
||||
let Some(clean) = reject_parent_traversal(&path) else {
|
||||
return Err(IdeError::invalid(format!("{}: outside the project", path.display())));
|
||||
};
|
||||
let raw_roots: Vec<PathBuf> = std::iter::once(project.root.clone()).chain(project.content_roots()).collect();
|
||||
let canonical_roots: Vec<PathBuf> = raw_roots.iter().filter_map(|r| dunce::canonicalize(r).ok()).collect();
|
||||
let mut allowed_lexical: Vec<PathBuf> = raw_roots.iter().filter_map(|r| reject_parent_traversal(r)).collect();
|
||||
allowed_lexical.extend(canonical_roots.iter().cloned());
|
||||
if !inside_any_root(&clean, &allowed_lexical) {
|
||||
return Err(IdeError::invalid(format!("{}: outside the project", path.display())));
|
||||
}
|
||||
let real = dunce::canonicalize(&clean)
|
||||
.map_err(|_| IdeError::not_found(format!("{}: no such file", path.display())))?;
|
||||
if !inside_any_root(&real, &canonical_roots) {
|
||||
return Err(IdeError::invalid(format!("{}: outside the project", path.display())));
|
||||
}
|
||||
Ok(real.into())
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
#[command(trust = always)]
|
||||
pub async fn fs_compare_directories(
|
||||
host: &Host,
|
||||
@@ -243,12 +289,26 @@ pub fn fs_scratches_dir(host: &Host) -> IdeResult<ide_core::IpcPath> {
|
||||
|
||||
/// Toggle Read-only Attribute: sets the writable bit (and the open document's
|
||||
/// state). Returns whether the file is read-only now.
|
||||
/// Off the main thread: opening a file for edit can ask a server (`svn lock`, `p4 edit`) and
|
||||
/// wait for a login.
|
||||
#[command(trust = always)]
|
||||
pub fn fs_set_writable(host: &Host, window: &str, path: PathBuf, writable: bool) -> IdeResult<bool> {
|
||||
match host.project(window) {
|
||||
Ok(p) => p.documents.set_writable(&path, writable),
|
||||
Err(_) => ide_vfs::set_writable(&path, writable).map(|()| !writable),
|
||||
}
|
||||
pub async fn fs_set_writable(host: &Host, window: &str, path: PathBuf, writable: bool) -> IdeResult<bool> {
|
||||
let project = host.project(window).ok();
|
||||
host.blocking(move || match project {
|
||||
Some(p) => {
|
||||
// A checkout backend keeps files read-only until opened for edit (`p4 edit`), so
|
||||
// its server learns about the change to come. `backend_of` is empty unless trusted.
|
||||
if writable
|
||||
&& let Some(backend) = p.backend_of(&path)
|
||||
&& backend.open_for_edit(std::slice::from_ref(&path))?
|
||||
{
|
||||
p.vcs_changed();
|
||||
}
|
||||
p.documents.set_writable(&path, writable)
|
||||
}
|
||||
None => ide_vfs::set_writable(&path, writable).map(|()| !writable),
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Moving to the trash can take a while (large trees): kept off the main thread.
|
||||
@@ -291,7 +351,34 @@ fn delete_recorded(project: Option<&Project>, path: &Path, undoable: bool) -> Id
|
||||
#[command(trust = always)]
|
||||
pub async fn fs_undo_delete(host: &Host, window: &str, undo: DeletionUndo) -> IdeResult<Vec<ide_core::IpcPath>> {
|
||||
let project = host.project(window)?;
|
||||
host.blocking(move || Ok(project.history.restore_deletion_undo(undo))).await
|
||||
host.blocking(move || {
|
||||
let wanted = undo.paths();
|
||||
let skipped = project.history.restore_deletion_undo(undo);
|
||||
// The Delete scheduled the files for deletion in a working copy (`files_deleted`): Undo
|
||||
// takes that back, keeping the restored content. Git records deletions at commit time.
|
||||
// One call per working copy: its first folder takes the tree below with it anyway.
|
||||
let mut by_backend: Vec<(std::sync::Arc<dyn ide_vcs::Backend>, Vec<PathBuf>)> = Vec::new();
|
||||
for path in wanted.iter().filter(|p| !skipped.iter().any(|s| s.0 == **p)) {
|
||||
let Some(backend) = project.backend_of(path) else { continue };
|
||||
match by_backend.iter_mut().find(|(b, _)| b.root() == backend.root()) {
|
||||
Some((_, paths)) => paths.push(path.clone()),
|
||||
None => by_backend.push((backend, vec![path.clone()])),
|
||||
}
|
||||
}
|
||||
for (backend, paths) in by_backend {
|
||||
// The files are back either way; still scheduled for deletion, they would go at commit.
|
||||
if let Err(e) = backend.unstage(&paths) {
|
||||
tracing::warn!("undo of delete in {}: {e}", backend.root().display());
|
||||
project.sink.emit(ide_core::IdeEvent::Notify {
|
||||
level: ide_core::event::NotifyLevel::Warning,
|
||||
title: "The restored files are still scheduled for deletion".into(),
|
||||
body: Some(e.message),
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok(skipped)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
#[command(trust = always)]
|
||||
@@ -367,7 +454,9 @@ pub(crate) fn inside_any_root(path: &Path, roots: &[PathBuf]) -> bool {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::inside_any_root;
|
||||
use super::{fs_canonicalize, inside_any_root};
|
||||
use crate::{Host, HostConfig};
|
||||
use ide_core::error::ErrorKind;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
#[test]
|
||||
@@ -380,10 +469,63 @@ mod tests {
|
||||
assert!(!inside_any_root(Path::new("/home/me/.ssh/id_rsa"), &roots));
|
||||
assert!(!inside_any_root(Path::new("/work/spec.pdf"), &[]));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn fs_canonicalize_enforces_window_project_roots() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let root = base.join("project");
|
||||
let outside = base.join("outside");
|
||||
std::fs::create_dir_all(&root).unwrap();
|
||||
std::fs::create_dir_all(&outside).unwrap();
|
||||
|
||||
let inside = root.join("guide.mdx");
|
||||
std::fs::write(&inside, "# Guide").unwrap();
|
||||
let secret = outside.join("secret.ts");
|
||||
std::fs::write(&secret, "export const secret = 1;").unwrap();
|
||||
|
||||
let host = Host::new(HostConfig { local_data_dir: base.join("local"), ..HostConfig::for_test(&base) });
|
||||
host.open_project("main", &root).unwrap();
|
||||
|
||||
// Valid path inside the window's project root succeeds with its canonical path.
|
||||
let resolved = fs_canonicalize(&host, "main", inside.clone()).await.unwrap();
|
||||
assert_eq!(resolved.0, dunce::canonicalize(&inside).unwrap());
|
||||
|
||||
// Path outside the project (existing or nonexistent) is rejected with InvalidInput before touching disk.
|
||||
let outside_existing = fs_canonicalize(&host, "main", secret.clone()).await.unwrap_err();
|
||||
assert_eq!(outside_existing.kind, ErrorKind::InvalidInput);
|
||||
let outside_missing = fs_canonicalize(&host, "main", outside.join("does-not-exist.ts")).await.unwrap_err();
|
||||
assert_eq!(outside_missing.kind, ErrorKind::InvalidInput);
|
||||
|
||||
// Parent traversal (`..`) is rejected even when lexically inside the project root.
|
||||
let traversal = fs_canonicalize(&host, "main", root.join("../outside/secret.ts")).await.unwrap_err();
|
||||
assert_eq!(traversal.kind, ErrorKind::InvalidInput);
|
||||
let in_root_parent = fs_canonicalize(&host, "main", root.join("sub/../guide.mdx")).await.unwrap_err();
|
||||
assert_eq!(in_root_parent.kind, ErrorKind::InvalidInput);
|
||||
|
||||
// Symlink inside the project pointing outside (directly or via `..`) is rejected.
|
||||
#[cfg(unix)]
|
||||
{
|
||||
let link = root.join("link.ts");
|
||||
std::os::unix::fs::symlink(&secret, &link).unwrap();
|
||||
let escaped = fs_canonicalize(&host, "main", link).await.unwrap_err();
|
||||
assert_eq!(escaped.kind, ErrorKind::InvalidInput);
|
||||
|
||||
let dir_link = root.join("dir-link");
|
||||
std::os::unix::fs::symlink(&outside, &dir_link).unwrap();
|
||||
let symlink_parent =
|
||||
fs_canonicalize(&host, "main", dir_link.join("../outside/secret.ts")).await.unwrap_err();
|
||||
assert_eq!(symlink_parent.kind, ErrorKind::InvalidInput);
|
||||
}
|
||||
|
||||
// Unknown window with no open project is rejected.
|
||||
assert!(fs_canonicalize(&host, "other", inside).await.is_err());
|
||||
}
|
||||
}
|
||||
|
||||
ide_command::domain!(
|
||||
fs:
|
||||
fs_canonicalize,
|
||||
fs_compare_directories,
|
||||
fs_copy,
|
||||
fs_copy_merge,
|
||||
|
||||
@@ -246,6 +246,7 @@ pub(crate) async fn resolve_launch(
|
||||
append_unique_class_paths(&mut class_paths, std::mem::take(&mut info.class_paths));
|
||||
}
|
||||
info.class_paths = class_paths;
|
||||
apply_maven_system_classpath(&mut info, root, &model, &module);
|
||||
apply_library_classpath(&mut info, root, &settings.project_structure.libraries, test);
|
||||
if build && !delegated {
|
||||
match compile::process_launch_resources(root, &model, cache, &info.class_paths, &cancel) {
|
||||
@@ -563,6 +564,9 @@ async fn resolve_launch_without_jdtls(
|
||||
},
|
||||
)?;
|
||||
info.class_paths = class_paths;
|
||||
if !by_service {
|
||||
apply_maven_system_classpath(&mut info, root, &model, &module);
|
||||
}
|
||||
apply_library_classpath(&mut info, root, &settings.project_structure.libraries, test);
|
||||
finish_launch(&mut info, root, &module, settings, &model, &data_dir);
|
||||
if cancel.is_cancelled() {
|
||||
@@ -681,6 +685,15 @@ fn entry_key(path: &str, windows: bool) -> String {
|
||||
if windows { key.to_lowercase() } else { key }
|
||||
}
|
||||
|
||||
fn apply_maven_system_classpath(info: &mut JavaLaunchInfo, root: &Path, model: &BuildModel, module: &Path) {
|
||||
for path in compile::maven_system_classpath(root, model, module) {
|
||||
let path = path.to_string_lossy();
|
||||
if !info.class_paths.iter().chain(&info.module_paths).any(|entry| same_entry(entry, &path, cfg!(windows))) {
|
||||
info.class_paths.push(path.into_owned());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn apply_library_classpath(
|
||||
info: &mut JavaLaunchInfo,
|
||||
root: &std::path::Path,
|
||||
@@ -1275,6 +1288,34 @@ mod tests {
|
||||
assert!(info.hints[0].contains("offline dependency"), "{:?}", info.hints);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn java_server_launch_classpath_includes_local_maven_system_jars() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let jar = ["src", "main", "resources", "lib", "offline.jar"].iter().fold(root.clone(), |p, c| p.join(c));
|
||||
std::fs::create_dir_all(jar.parent().unwrap()).unwrap();
|
||||
std::fs::write(&jar, "").unwrap();
|
||||
std::fs::write(
|
||||
root.join("pom.xml"),
|
||||
r#"<project><groupId>demo</groupId><artifactId>app</artifactId><version>1</version>
|
||||
<dependencies><dependency><groupId>local</groupId><artifactId>offline</artifactId><version>1</version>
|
||||
<scope>system</scope><systemPath>${pom.basedir}/src/main/resources/lib/offline.jar</systemPath>
|
||||
</dependency></dependencies></project>"#,
|
||||
)
|
||||
.unwrap();
|
||||
let model = ide_build::load(&root, &root.join("cache"), None);
|
||||
let jar = jar.to_string_lossy().into_owned();
|
||||
let mut info = JavaLaunchInfo { class_paths: vec!["classes".into()], ..Default::default() };
|
||||
apply_maven_system_classpath(&mut info, &root, &model, &root);
|
||||
apply_maven_system_classpath(&mut info, &root, &model, &root);
|
||||
assert_eq!(info.class_paths, ["classes", &jar]);
|
||||
|
||||
info.class_paths.pop();
|
||||
info.module_paths.push(jar);
|
||||
apply_maven_system_classpath(&mut info, &root, &model, &root);
|
||||
assert_eq!(info.class_paths, ["classes"]);
|
||||
}
|
||||
|
||||
/// Maven's launch classpath lists the module's and its reactor siblings' outputs, which
|
||||
/// the launch already runs from a snapshot: listed twice, MyBatis loads each mapper XML
|
||||
/// twice and fails with "XML fragments parsed from previous mappers already contains value".
|
||||
|
||||
@@ -929,9 +929,14 @@ pub async fn lsp_library_sources(
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn lsp_resolve_class_file(host: &Host, window: &str, path: std::path::PathBuf) -> IdeResult<String> {
|
||||
// Opens compiled classes through JDT as decompiled class documents.
|
||||
let archive = ide_vfs::split_archive_path(&path);
|
||||
host.project(window)?.lsp.java_class_file(&path, archive).await
|
||||
host.project(window)?.lsp.java_class_file(&path, archive, read_internal_class_name(&path)).await
|
||||
}
|
||||
|
||||
async fn read_internal_class_name(path: &Path) -> IdeResult<String> {
|
||||
let bytes = tokio::fs::read(path).await?;
|
||||
ide_build::jbuild::class_file_name(&bytes)
|
||||
.ok_or_else(|| IdeError::not_found(format!("invalid class file: {}", path.display())))
|
||||
}
|
||||
|
||||
/// References of the symbol at `pos`. `project_wide` also searches project files
|
||||
@@ -2492,6 +2497,18 @@ pub fn plugin_formatters() -> IdeResult<Vec<crate::plugins::language_features::F
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[tokio::test]
|
||||
async fn disk_class_name_comes_from_bytecode() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("moved.class");
|
||||
// Class header, UTF-8 and Class constants, then access_flags and this_class.
|
||||
let bytes = b"\xca\xfe\xba\xbe\0\0\0\x3d\0\x03\x01\0\x0d\x70/Outer$Inner\x07\0\x01\0\x21\0\x02";
|
||||
std::fs::write(&path, bytes).unwrap();
|
||||
assert_eq!(read_internal_class_name(&path).await.unwrap(), "p/Outer$Inner");
|
||||
std::fs::write(&path, b"invalid").unwrap();
|
||||
assert_eq!(read_internal_class_name(&path).await.unwrap_err().kind, ErrorKind::NotFound);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_plugin_offering_ghost_text_keeps_the_editor_asking() {
|
||||
use super::*;
|
||||
|
||||
@@ -45,6 +45,7 @@ pub mod settings_sync;
|
||||
pub mod spell;
|
||||
pub mod ssh;
|
||||
pub mod stream_trace;
|
||||
pub mod svn;
|
||||
pub mod syntax;
|
||||
pub mod term;
|
||||
pub mod thread_dump;
|
||||
@@ -133,6 +134,7 @@ ide_command::domains!(
|
||||
search_commands: crate::ops::search::commands,
|
||||
spell: crate::ops::spell,
|
||||
ssh: crate::ops::ssh,
|
||||
svn: crate::ops::svn,
|
||||
stream_trace: crate::ops::stream_trace,
|
||||
syntax: crate::ops::syntax,
|
||||
term: crate::ops::term,
|
||||
|
||||
@@ -116,6 +116,13 @@ pub fn apply_setting(host: &Arc<Host>, window: &str, key: &str) {
|
||||
if key == "mcpServer" || key.starts_with("mcpServer.") {
|
||||
host.mcp.apply(host);
|
||||
}
|
||||
if key == "agents" || key == "agents.automations" || key.starts_with("agents.automations.") {
|
||||
let h = host.clone();
|
||||
host.runtime.spawn_blocking(move || {
|
||||
h.automations.sync_boot_service(&h);
|
||||
h.automations.broadcast_changed(&h);
|
||||
});
|
||||
}
|
||||
if key == "terminal" || key.starts_with("terminal.") {
|
||||
super::term::apply_output_rate(host, window);
|
||||
}
|
||||
@@ -489,12 +496,14 @@ pub fn set_settings(
|
||||
project.agents.notify_mcp_servers_changed();
|
||||
}
|
||||
}
|
||||
// A skill or memory policy change re-resolves the modes; an idle session restarts to pick them up.
|
||||
// A skill, memory, or agent-plugin policy change re-resolves the modes; an idle session restarts to pick them up.
|
||||
if key == "agents"
|
||||
|| key == "agents.skills"
|
||||
|| key.starts_with("agents.skills.")
|
||||
|| key == "agents.memory"
|
||||
|| key.starts_with("agents.memory.")
|
||||
|| key == "agents.plugins"
|
||||
|| key.starts_with("agents.plugins.")
|
||||
{
|
||||
for project in affected() {
|
||||
project.agents.notify_mcp_servers_changed();
|
||||
|
||||
@@ -1,19 +1,34 @@
|
||||
use crate::project::Project;
|
||||
use ide_core::IdeResult;
|
||||
use ide_dap::LaunchConfig;
|
||||
use ide_workspace::roots::RootKind;
|
||||
use std::collections::BTreeMap;
|
||||
use ide_workspace::roots::{RootKind, SourceFolder};
|
||||
use std::collections::{BTreeMap, HashSet};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// The project's import roots, put on `PYTHONPATH` by runs, debug sessions and consoles.
|
||||
pub(super) fn paths(project: &Project) -> Vec<PathBuf> {
|
||||
let mut paths = vec![project.root.clone()];
|
||||
paths.extend(project.content_roots());
|
||||
for root in project.roots().roots {
|
||||
if matches!(root.kind, RootKind::Source | RootKind::Test) {
|
||||
let path = project.root.join(root.path);
|
||||
if !paths.contains(&path) {
|
||||
paths.push(path);
|
||||
}
|
||||
import_roots(&project.root, project.content_roots(), &project.roots().roots)
|
||||
}
|
||||
|
||||
/// `root`, the content roots, then the Source and Test roots. A detected root that is itself a
|
||||
/// package (it holds `__init__.py`, like an Odoo addon or its `tests` folder) is left out:
|
||||
/// importing from it would give its modules a second top-level name, and a project with
|
||||
/// thousands of them made `PYTHONPATH` longer than a process environment can hold (#7083).
|
||||
/// Folders the user marked always count.
|
||||
fn import_roots(root: &Path, content_roots: Vec<PathBuf>, roots: &[SourceFolder]) -> Vec<PathBuf> {
|
||||
let mut paths = vec![root.to_path_buf()];
|
||||
paths.extend(content_roots);
|
||||
let mut seen: HashSet<PathBuf> = paths.iter().cloned().collect();
|
||||
for folder in roots {
|
||||
if !matches!(folder.kind, RootKind::Source | RootKind::Test) {
|
||||
continue;
|
||||
}
|
||||
let path = root.join(&folder.path);
|
||||
if folder.detected_from.is_some() && path.join("__init__.py").is_file() {
|
||||
continue;
|
||||
}
|
||||
if seen.insert(path.clone()) {
|
||||
paths.push(path);
|
||||
}
|
||||
}
|
||||
paths
|
||||
@@ -120,6 +135,38 @@ pub(super) fn prepare_debug(
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn detected_package_folders_are_not_import_roots() {
|
||||
use ide_workspace::roots::{RootKind, SourceFolder};
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
for file in ["src/pkg/__init__.py", "addon/__init__.py", "addon/tests/__init__.py", "marked/__init__.py"] {
|
||||
let path = root.join(file);
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
std::fs::write(path, "").unwrap();
|
||||
}
|
||||
std::fs::create_dir_all(root.join("tests")).unwrap();
|
||||
let folder = |path: &str, kind, detected: bool| SourceFolder {
|
||||
path: path.into(),
|
||||
kind,
|
||||
detected_from: detected.then(|| "pyproject.toml".into()),
|
||||
};
|
||||
let roots = [
|
||||
folder("src", RootKind::Source, true),
|
||||
folder("tests", RootKind::Test, true),
|
||||
folder("addon", RootKind::Source, true),
|
||||
folder("addon/tests", RootKind::Test, true),
|
||||
folder("marked", RootKind::Source, false),
|
||||
folder("build", RootKind::Excluded, true),
|
||||
folder("src", RootKind::Source, true),
|
||||
];
|
||||
assert_eq!(
|
||||
super::import_roots(root, vec![], &roots),
|
||||
[root.to_path_buf(), root.join("src"), root.join("tests"), root.join("marked")],
|
||||
"detected packages are left out, a folder the user marked stays, no duplicates"
|
||||
);
|
||||
}
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -448,13 +448,18 @@ async fn start_inner(
|
||||
}
|
||||
let target = ide_remote::service::run_target(&settings, id)?;
|
||||
if target.kind != RunTargetKind::Ssh {
|
||||
// A local run of the docker CLI: the command is resolved in the container, and
|
||||
// this machine's toolchains and `PYTHONPATH` don't apply.
|
||||
let mut config = config;
|
||||
if ide_run::is_python_kind(&config.kind) {
|
||||
container_python_path(&mut config.env, &super::python::paths(&project), &project.root);
|
||||
}
|
||||
let (config, note) = container::prepare(host, &project.root, target, config).await?;
|
||||
// A local run of the docker CLI or `wsl.exe`: the command is resolved in the
|
||||
// container or distribution, and this machine's toolchains and `PYTHONPATH` don't apply.
|
||||
// The settings of the workspace member it belongs to derived its values.
|
||||
let mut member = config.clone();
|
||||
let (member_root, member_settings, fallback) = settings_for(host, &project, &mut member)?;
|
||||
let derived = Derived { root: &member_root, fallback: fallback.as_deref(), settings: &member_settings };
|
||||
let config = remote_config(&config, derived, &project.root, &super::python::paths(&project));
|
||||
let (config, note) = if target.kind == RunTargetKind::Wsl {
|
||||
(container::prepare_wsl(host, &project.root, target, config).await?, None)
|
||||
} else {
|
||||
container::prepare(host, &project.root, target, config).await?
|
||||
};
|
||||
if let Some(note) = note {
|
||||
on_output(OutputChunk::System { text: format!("{note}\n") });
|
||||
}
|
||||
@@ -462,7 +467,7 @@ async fn start_inner(
|
||||
let options = StartOptions {
|
||||
encoding: Some(encoding).filter(|e| !e.trim().is_empty()),
|
||||
python_paths: Vec::new(),
|
||||
// A folder on this machine: not in the container.
|
||||
// A folder on this machine: not in the container or distribution.
|
||||
ruby_reporter: None,
|
||||
plots: None,
|
||||
capture_junit_reports: false,
|
||||
@@ -547,19 +552,23 @@ async fn start_inner(
|
||||
.then(|| xcode_container(&config).map(|c| run_dir.join(c)))
|
||||
.flatten();
|
||||
if config.kind == "xcode" {
|
||||
let (dir, cache) = (run_dir.clone(), project.cache_dir.clone());
|
||||
let dir = run_dir.clone();
|
||||
let say = on_output.clone();
|
||||
config = host
|
||||
.blocking(move || {
|
||||
ide_run::xcode::prepare(&dir, &cache, &mut config)?;
|
||||
// Reading build settings can take a minute on a large workspace: say what's going on.
|
||||
ide_run::xcode::prepare(&dir, &mut config, &|text| {
|
||||
say(OutputChunk::System { text: format!("{text}\n") })
|
||||
})?;
|
||||
Ok(config)
|
||||
})
|
||||
.await?;
|
||||
}
|
||||
if config.kind == ide_run::xcode_clean::KIND {
|
||||
let (dir, cache) = (run_dir.clone(), project.cache_dir.clone());
|
||||
let dir = run_dir.clone();
|
||||
config = host
|
||||
.blocking(move || {
|
||||
ide_run::xcode_clean::prepare(&dir, &cache, &mut config)?;
|
||||
ide_run::xcode_clean::prepare(&dir, &mut config)?;
|
||||
Ok(config)
|
||||
})
|
||||
.await?;
|
||||
@@ -618,6 +627,8 @@ async fn start_inner(
|
||||
}
|
||||
let on_output = match xcode_container {
|
||||
Some(container) => {
|
||||
let on_output =
|
||||
if config.kind == "xcode" { split_build_log(&project, &config, on_output) } else { on_output };
|
||||
let (output, problems) = xcodebuild_problems(&project, &config.id, &run_dir, container, on_output, sink);
|
||||
sink = problems;
|
||||
output
|
||||
@@ -637,6 +648,53 @@ fn xcode_container(config: &RunConfig) -> Option<String> {
|
||||
|
||||
const XCODEBUILD_SOURCE: &str = "xcodebuild";
|
||||
|
||||
/// Sends an Xcode run's build output to a log file instead of the console, which keeps the app's
|
||||
/// own output ([`ide_run::xcode::RunOutputSplit`]). Each run of the configuration replaces the
|
||||
/// file. It is in the temporary folder: the console links a path only without spaces, and the
|
||||
/// project's cache is under `Application Support`. Problems still sees all of the output: this
|
||||
/// wraps the console, after [`xcodebuild_problems`] has read it.
|
||||
fn split_build_log(
|
||||
project: &crate::project::Project,
|
||||
config: &RunConfig,
|
||||
on_output: Emit<OutputChunk>,
|
||||
) -> Emit<OutputChunk> {
|
||||
use std::io::Write;
|
||||
let name: String =
|
||||
config.id.chars().map(|c| if c.is_ascii_alphanumeric() || "._-".contains(c) { c } else { '_' }).collect();
|
||||
let project_key = project.cache_dir.file_name().unwrap_or_default();
|
||||
let path = std::env::temp_dir().join("openidea-xcode-build").join(project_key).join(format!("{name}.log"));
|
||||
let file = std::fs::create_dir_all(path.parent().unwrap_or(&path))
|
||||
.and_then(|()| std::fs::File::create(&path))
|
||||
.map(std::io::BufWriter::new);
|
||||
let file = match file {
|
||||
Ok(file) => Some(file),
|
||||
Err(e) => {
|
||||
on_output(OutputChunk::System { text: format!("Cannot write the build log {}: {e}\n", path.display()) });
|
||||
None
|
||||
}
|
||||
};
|
||||
let wait = config.extras.params.get(ide_run::xcode::WAIT_FOR_DEBUGGER_PARAM).is_some_and(|v| !v.trim().is_empty());
|
||||
let split = ide_run::xcode::RunOutputSplit::new(&path, wait);
|
||||
let state = parking_lot::Mutex::new((split, file));
|
||||
Arc::new(move |chunk: OutputChunk| {
|
||||
let mut guard = state.lock();
|
||||
let (split, file) = &mut *guard;
|
||||
let out = split.feed(chunk);
|
||||
if let Some(f) = file.as_mut()
|
||||
&& !out.log.is_empty()
|
||||
{
|
||||
let _ = f.write_all(out.log.as_bytes());
|
||||
if !split.building() {
|
||||
let _ = f.flush();
|
||||
}
|
||||
}
|
||||
drop(guard);
|
||||
for chunk in out.console {
|
||||
on_output(chunk);
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Sends the compiler messages in an Xcode configuration's `xcodebuild` output to Problems as they
|
||||
/// arrive, after clearing the ones its previous run reported. Messages without a location (linker
|
||||
/// errors) are listed on the project file (`project.pbxproj` / `contents.xcworkspacedata`).
|
||||
@@ -864,6 +922,44 @@ pub use commands::*;
|
||||
mod ownership_tests {
|
||||
use super::*;
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_remote_run_gets_none_of_this_machines_derived_values() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
let venv = root.join(".venv");
|
||||
std::fs::create_dir_all(venv.join("bin")).unwrap();
|
||||
std::fs::write(venv.join("pyvenv.cfg"), "home = /usr/bin\n").unwrap();
|
||||
std::fs::write(venv.join("bin/python"), "").unwrap();
|
||||
let mut settings = ide_core::settings::Settings::default();
|
||||
settings.languages.python.interpreter = venv.join("bin/python").to_string_lossy().into_owned();
|
||||
let mut config = RunConfig {
|
||||
id: "app".into(),
|
||||
name: "app".into(),
|
||||
kind: "python".into(),
|
||||
command: "python".into(),
|
||||
args: vec!["main.py".into()],
|
||||
cwd: None,
|
||||
env: [("FOO".to_owned(), "bar".to_owned())].into(),
|
||||
detected: false,
|
||||
is_test: false,
|
||||
debug_adapter: None,
|
||||
allow_parallel: false,
|
||||
extras: Default::default(),
|
||||
};
|
||||
config.extras.target = Some("wsl".into());
|
||||
ide_sdk::apply::apply_to_run_configs(std::slice::from_mut(&mut config), root, &settings);
|
||||
assert!(config.env.contains_key("VIRTUAL_ENV") && config.env.contains_key("PATH"), "{:?}", config.env);
|
||||
config.env.insert("GOFLAGS".into(), "-mod=mod".into());
|
||||
let derived = Derived { root, fallback: None, settings: &settings };
|
||||
let out = remote_config(&config, derived, root, &[root.to_path_buf()]);
|
||||
assert_eq!(out.env.keys().collect::<Vec<_>>(), ["FOO", "GOFLAGS", "PYTHONPATH"], "{:?}", out.env);
|
||||
assert_eq!(out.command, "python", "the interpreter is the target's");
|
||||
assert_eq!(out.extras.target.as_deref(), Some("wsl"));
|
||||
assert!(has_local_path("/opt/go") && has_local_path("/a/bin:/b/bin"));
|
||||
assert!(!has_local_path("-mod=mod") && !has_local_path("https://proxy.golang.org,direct"), "kept: not paths");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn source_roots_go_on_the_container_pythonpath() {
|
||||
@@ -1062,6 +1158,9 @@ pub async fn run_container_path(
|
||||
if !path.starts_with('/') {
|
||||
return Ok(None);
|
||||
}
|
||||
if run_target.kind == RunTargetKind::Wsl {
|
||||
return Ok(ide_remote::wsl::local_file(&path, &run_target, &root).filter(|f| f.is_file()).map(Into::into));
|
||||
}
|
||||
let library = snapshots
|
||||
.and_then(|dir| ide_sdk::container_python::current(&dir))
|
||||
.and_then(|(dir, snapshot)| ide_sdk::container_python::snapshot_file(&dir, &snapshot, &path));
|
||||
@@ -1074,9 +1173,39 @@ pub async fn run_container_path(
|
||||
.await
|
||||
}
|
||||
|
||||
/// The project's source roots on `PYTHONPATH` in a container, as a local run gets them:
|
||||
/// they are mounted with the project, and `container::prepare` maps their paths. The
|
||||
/// container's separator is `:`, whatever this machine's is.
|
||||
/// `config` for a container or WSL distribution: without what settings derived from this
|
||||
/// machine (its `PATH`, `VIRTUAL_ENV`, toolchain homes, resolved interpreter paths), which
|
||||
/// would replace the values there, and with the project's source roots on `PYTHONPATH`.
|
||||
/// Values that settings derive but that are not paths of this machine (`GOPROXY`, `GOFLAGS`)
|
||||
/// still apply there and are kept.
|
||||
fn remote_config(config: &RunConfig, derived: Derived<'_>, root: &Path, python_roots: &[PathBuf]) -> RunConfig {
|
||||
let plain = ide_sdk::apply::without_derived_in(config, derived.root, derived.fallback, derived.settings);
|
||||
let mut out = config.clone();
|
||||
out.command = plain.command;
|
||||
out.env.retain(|key, value| plain.env.contains_key(key) || !has_local_path(value));
|
||||
if ide_run::is_python_kind(&out.kind) {
|
||||
container_python_path(&mut out.env, python_roots, root);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The settings a configuration's derived values come from (see [`settings_for`]).
|
||||
#[derive(Clone, Copy)]
|
||||
struct Derived<'a> {
|
||||
root: &'a Path,
|
||||
fallback: Option<&'a Path>,
|
||||
settings: &'a ide_core::settings::Settings,
|
||||
}
|
||||
|
||||
/// `value` is an absolute path of this machine, alone or first in a path list (a URL such
|
||||
/// as `GOPROXY`'s is not: its first part is `https`).
|
||||
fn has_local_path(value: &str) -> bool {
|
||||
std::env::split_paths(value).find(|p| !p.as_os_str().is_empty()).is_some_and(|p| p.is_absolute())
|
||||
}
|
||||
|
||||
/// The project's source roots on `PYTHONPATH` in a container or WSL distribution, as a local
|
||||
/// run gets them: they are mounted with the project, and `container::prepare` /
|
||||
/// `prepare_wsl` map their paths. The separator there is `:`, whatever this machine's is.
|
||||
fn container_python_path(env: &mut std::collections::BTreeMap<String, String>, roots: &[PathBuf], root: &Path) {
|
||||
let mut paths: Vec<String> =
|
||||
roots.iter().filter(|p| p.starts_with(root)).map(|p| p.to_string_lossy().into_owned()).collect();
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//! Docker and Compose run targets: the configuration becomes a local run of the
|
||||
//! docker CLI (see `ide_remote::docker`).
|
||||
//! Docker, Compose and WSL run targets: the configuration becomes a local run of the
|
||||
//! docker CLI (see `ide_remote::docker`) or of `wsl.exe` (see `ide_remote::wsl`).
|
||||
|
||||
use crate::Host;
|
||||
use ide_core::remote_settings::{RunTarget, RunTargetKind};
|
||||
@@ -73,6 +73,37 @@ pub(super) async fn prepare(
|
||||
.await
|
||||
}
|
||||
|
||||
/// `config` rewritten to run in `target`'s WSL distribution.
|
||||
pub(super) async fn prepare_wsl(
|
||||
host: &Host,
|
||||
root: &Path,
|
||||
target: RunTarget,
|
||||
config: RunConfig,
|
||||
) -> IdeResult<RunConfig> {
|
||||
if !cfg!(windows) {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"Run target '{}' is a WSL distribution: WSL needs Windows",
|
||||
target.name
|
||||
)));
|
||||
}
|
||||
let root = root.to_path_buf();
|
||||
host.blocking(move || {
|
||||
let linux_root = ide_remote::wsl::project_root(&target, &root)?;
|
||||
let file_env = env_files(&root, &config)?;
|
||||
let inherited = std::env::var("WSLENV").ok();
|
||||
ide_remote::wsl::wsl_config(
|
||||
&config,
|
||||
&target,
|
||||
&root,
|
||||
&linux_root,
|
||||
ide_core::wsl::EXE,
|
||||
&file_env,
|
||||
inherited.as_deref(),
|
||||
)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// The project can only be bind-mounted from a daemon on this machine.
|
||||
pub(crate) fn require_local(endpoint: &DockerEndpoint, target: &RunTarget) -> IdeResult<()> {
|
||||
if !ide_docker::endpoint_is_local(endpoint)? {
|
||||
|
||||
@@ -12,7 +12,7 @@ use std::sync::Mutex;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
pub mod container_python;
|
||||
pub use container_python::{ContainerPython, sdk_container_python, sdk_container_python_refresh};
|
||||
pub use container_python::{ContainerPython, sdk_container_python, sdk_container_python_refresh, sdk_wsl_pythons};
|
||||
|
||||
/// Executables found for "run this file", and where single files are compiled to.
|
||||
#[derive(Clone, Debug, serde::Serialize, specta::Type)]
|
||||
|
||||
@@ -4,6 +4,9 @@
|
||||
//! A snapshot runs the target's Python once in a new container (the image's entrypoint
|
||||
//! and the service's dependencies skipped), then copies its `sys.path` folders out of
|
||||
//! the stopped container with `docker cp`. Nothing is installed in the container.
|
||||
//!
|
||||
//! A WSL run target's snapshot only records its Python's `sys.path`: the folders are read
|
||||
//! in place through `\\wsl.localhost\<distro>`.
|
||||
|
||||
use crate::Host;
|
||||
use crate::project::Project;
|
||||
@@ -23,6 +26,8 @@ use std::time::Duration;
|
||||
const PROBE_TIMEOUT: Duration = Duration::from_secs(15 * 60);
|
||||
const COPY_TIMEOUT: Duration = Duration::from_secs(10 * 60);
|
||||
const QUICK: Duration = Duration::from_secs(30);
|
||||
/// Starting the distribution may come first.
|
||||
const WSL_TIMEOUT: Duration = Duration::from_secs(2 * 60);
|
||||
|
||||
/// The project interpreter when it is a run target's.
|
||||
#[derive(Clone, Debug, serde::Serialize, specta::Type)]
|
||||
@@ -34,8 +39,10 @@ pub struct ContainerPython {
|
||||
pub name: String,
|
||||
/// The Python version of the snapshot in use; `None`: no snapshot yet.
|
||||
pub version: Option<String>,
|
||||
/// The image the snapshot was copied from.
|
||||
/// The image the snapshot was copied from; `None` for WSL.
|
||||
pub image: Option<String>,
|
||||
/// The interpreter's path in the container or distribution.
|
||||
pub executable: Option<String>,
|
||||
/// The copied library folders on this machine.
|
||||
pub folders: Vec<IpcPath>,
|
||||
/// Packages of the snapshot (read-only).
|
||||
@@ -108,22 +115,25 @@ pub(crate) fn library_group(host: &Host, root: &Path, settings: &Settings) -> Op
|
||||
}
|
||||
|
||||
/// The project interpreter when it is a Docker or Compose run target's, with its snapshot.
|
||||
/// Off the calling thread: a WSL interpreter's packages are read over `\\wsl.localhost`.
|
||||
#[command(trust = trusted)]
|
||||
pub fn sdk_container_python(host: &Host, window: &str) -> IdeResult<Option<ContainerPython>> {
|
||||
pub async fn sdk_container_python(host: &Host, window: &str) -> IdeResult<Option<ContainerPython>> {
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
Ok(describe(host, &project.root, &project.settings.effective()))
|
||||
let (dirs, root, settings) = (Dirs::of(host), project.root.clone(), project.settings.effective());
|
||||
host.blocking(move || Ok(describe(&dirs, &root, &settings))).await
|
||||
}
|
||||
|
||||
fn describe(host: &Host, root: &Path, settings: &Settings) -> Option<ContainerPython> {
|
||||
fn describe(dirs: &Dirs, root: &Path, settings: &Settings) -> Option<ContainerPython> {
|
||||
let target = settings.languages.python.run_target()?;
|
||||
let name = settings.run_targets.iter().find(|t| t.id == target).map(|t| t.name.clone()).unwrap_or_default();
|
||||
let dir = Dirs::of(host).target(root, target);
|
||||
let dir = dirs.target(root, target);
|
||||
let mut out = ContainerPython {
|
||||
target: target.to_owned(),
|
||||
name,
|
||||
version: None,
|
||||
image: None,
|
||||
executable: None,
|
||||
folders: Vec::new(),
|
||||
packages: Vec::new(),
|
||||
updating: updating(&dir),
|
||||
@@ -132,7 +142,8 @@ fn describe(host: &Host, root: &Path, settings: &Settings) -> Option<ContainerPy
|
||||
out.folders = snapshots::local_folders(&dir, &snapshot).into_iter().map(Into::into).collect();
|
||||
out.packages = snapshots::packages(&dir, &snapshot);
|
||||
out.version = Some(snapshot.probe.version);
|
||||
out.image = Some(snapshot.image);
|
||||
out.executable = Some(snapshot.probe.executable);
|
||||
out.image = snapshot.distro.is_none().then_some(snapshot.image);
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
@@ -144,7 +155,8 @@ pub async fn sdk_container_python_refresh(host: &Host, window: &str) -> IdeResul
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
update(Dirs::of(host), &project, true).await?;
|
||||
Ok(describe(host, &project.root, &project.settings.effective()))
|
||||
let (dirs, root, settings) = (Dirs::of(host), project.root.clone(), project.settings.effective());
|
||||
host.blocking(move || Ok(describe(&dirs, &root, &settings))).await
|
||||
}
|
||||
|
||||
/// Takes a snapshot when the project interpreter is a run target's and the current image
|
||||
@@ -154,13 +166,22 @@ pub(crate) fn ensure(host: &Host, project: &Arc<Project>) {
|
||||
return;
|
||||
}
|
||||
let (dirs, project) = (Dirs::of(host), project.clone());
|
||||
let settings = project.settings.effective();
|
||||
let wsl = settings
|
||||
.languages
|
||||
.python
|
||||
.run_target()
|
||||
.and_then(|id| settings.run_targets.iter().find(|t| t.id == id))
|
||||
.is_some_and(|t| t.kind == RunTargetKind::Wsl);
|
||||
let title =
|
||||
if wsl { "Cannot read the WSL Python's libraries" } else { "Cannot copy the container's Python libraries" };
|
||||
host.runtime.spawn(async move {
|
||||
if let Err(e) = update(dirs, &project, false).await
|
||||
&& e.kind != ide_core::error::ErrorKind::Cancelled
|
||||
{
|
||||
project.sink.emit(IdeEvent::Notify {
|
||||
level: NotifyLevel::Warning,
|
||||
title: "Cannot copy the container's Python libraries".into(),
|
||||
title: title.into(),
|
||||
body: Some(e.message),
|
||||
});
|
||||
}
|
||||
@@ -173,7 +194,7 @@ async fn update(dirs: Dirs, project: &Arc<Project>, force: bool) -> IdeResult<()
|
||||
let target = ide_remote::service::run_target(&settings, id)?;
|
||||
if target.kind == RunTargetKind::Ssh {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"Run target '{}' runs over SSH: only a Docker or Compose run target can be the project interpreter",
|
||||
"Run target '{}' is an SSH host: only a Docker, Compose or WSL run target can be the project interpreter",
|
||||
target.name
|
||||
)));
|
||||
}
|
||||
@@ -182,7 +203,10 @@ async fn update(dirs: Dirs, project: &Arc<Project>, force: bool) -> IdeResult<()
|
||||
return Ok(());
|
||||
}
|
||||
let _done = Updating(dir.clone());
|
||||
let endpoint = crate::ops::run::container::endpoint(&dirs.data, &target)?;
|
||||
let endpoint = match target.kind {
|
||||
RunTargetKind::Wsl => None,
|
||||
_ => Some(crate::ops::run::container::endpoint(&dirs.data, &target)?),
|
||||
};
|
||||
let task = TaskId::next();
|
||||
let title = format!("Python libraries of {}", target.name);
|
||||
let (root, sink) = (project.root.clone(), project.sink.clone());
|
||||
@@ -198,7 +222,11 @@ async fn update(dirs: Dirs, project: &Arc<Project>, force: bool) -> IdeResult<()
|
||||
};
|
||||
let report = progress.clone();
|
||||
let result = tokio::task::spawn_blocking(move || {
|
||||
take(&endpoint, &root, &target, &dir, &dirs.cache, force, &|message| report(message, false))
|
||||
let report = |message: &str| report(message, false);
|
||||
match endpoint {
|
||||
Some(endpoint) => take(&endpoint, &root, &target, &dir, &dirs.cache, force, &report),
|
||||
None => take_wsl(&root, &target, &dir, &dirs.cache, &report),
|
||||
}
|
||||
})
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()))
|
||||
@@ -288,6 +316,7 @@ fn take(
|
||||
image: image.clone(),
|
||||
probe,
|
||||
folders,
|
||||
distro: None,
|
||||
};
|
||||
snapshots::write(&partial, &snapshot)?;
|
||||
if dir.exists() {
|
||||
@@ -298,6 +327,72 @@ fn take(
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// Records where the WSL target's Python finds its libraries and makes that the snapshot in
|
||||
/// use; `false` when nothing changed. Nothing is copied, so packages installed later show up.
|
||||
fn take_wsl(
|
||||
root: &Path,
|
||||
target: &RunTarget,
|
||||
target_dir: &Path,
|
||||
cache: &Path,
|
||||
progress: &dyn Fn(&str),
|
||||
) -> IdeResult<bool> {
|
||||
if !cfg!(windows) {
|
||||
return Err(IdeError::unavailable(format!(
|
||||
"Run target '{}' is a WSL distribution: WSL needs Windows",
|
||||
target.name
|
||||
)));
|
||||
}
|
||||
let linux_root = ide_remote::wsl::project_root(target, root)?;
|
||||
let distro = target.distro.trim();
|
||||
progress("Starting the WSL Python");
|
||||
let out = ide_core::wsl::exec(distro, &[ide_remote::wsl::python(target), "-c", snapshots::PROBE], WSL_TIMEOUT)?;
|
||||
let probe = snapshots::parse_probe(&out)?;
|
||||
let id = format!("wsl-{}-{}", probe.executable, probe.version);
|
||||
let snapshot = Snapshot {
|
||||
image: id.clone(),
|
||||
folders: wsl_folders(&probe, &linux_root),
|
||||
neutral_python: snapshots::neutral_python(cache, &probe.version),
|
||||
distro: Some(distro.to_owned()),
|
||||
probe,
|
||||
};
|
||||
// What the language server is given: the probe's other details (its raw `sys.path` order,
|
||||
// say) are kept in the snapshot but don't restart it.
|
||||
let libraries = |s: &Snapshot| (s.image.clone(), s.folders.clone(), s.neutral_python.clone(), s.distro.clone());
|
||||
let changed = snapshots::current(target_dir).map(|(_, s)| libraries(&s)) != Some(libraries(&snapshot));
|
||||
let dir = target_dir.join(snapshots::dir_name(&id));
|
||||
std::fs::create_dir_all(&dir)?;
|
||||
snapshots::write(&dir, &snapshot)?;
|
||||
snapshots::make_current(target_dir, &id)?;
|
||||
Ok(changed)
|
||||
}
|
||||
|
||||
/// The library folders of a WSL Python: as a container's, plus a virtualenv's in the project
|
||||
/// (`.venv/lib/python3.12/site-packages`), which a container mount would hold anyway.
|
||||
fn wsl_folders(probe: &snapshots::Probe, linux_root: &str) -> Vec<String> {
|
||||
let root = linux_root.trim_end_matches('/');
|
||||
let in_project = |f: &str| root.is_empty() || f == root || f.starts_with(&format!("{root}/"));
|
||||
let packages = |f: &str| f.split('/').any(|c| c == "site-packages" || c == "dist-packages");
|
||||
snapshots::folders_to_copy(probe, "").into_iter().filter(|f| !in_project(f) || packages(f)).collect()
|
||||
}
|
||||
|
||||
/// The Pythons found in a WSL distribution, for Add Python Interpreter: the ones on its
|
||||
/// `PATH`, in `/usr/bin` and `/usr/local/bin`, pyenv's, and the project's virtualenv. Empty off Windows.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn sdk_wsl_pythons(host: &Host, window: &str, distro: String) -> IdeResult<Vec<String>> {
|
||||
host.require_trust(window)?;
|
||||
if !cfg!(windows) {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let root = host.project(window)?.root.clone();
|
||||
host.blocking(move || {
|
||||
let distro = distro.trim();
|
||||
let linux_root = ide_core::wsl::linux_path(&root, distro).unwrap_or_default();
|
||||
let script = ["sh", "-c", ide_remote::wsl::FIND_PYTHONS, "sh", &linux_root];
|
||||
Ok(ide_remote::wsl::parse_pythons(&ide_core::wsl::exec(distro, &script, WSL_TIMEOUT)?))
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Distinguishes probe containers.
|
||||
fn unique() -> String {
|
||||
use std::sync::atomic::{AtomicU32, Ordering};
|
||||
@@ -306,4 +401,23 @@ fn unique() -> String {
|
||||
format!("{:x}-{}-{}", secs & 0xff_ffff, std::process::id(), COUNT.fetch_add(1, Ordering::Relaxed))
|
||||
}
|
||||
|
||||
ide_command::domain!(sdk_container_python: sdk_container_python, sdk_container_python_refresh);
|
||||
#[cfg(test)]
|
||||
mod wsl_tests {
|
||||
#[test]
|
||||
fn a_virtualenv_in_the_project_is_read_and_its_sources_are_not() {
|
||||
let probe = super::snapshots::Probe {
|
||||
version: "3.12.3".into(),
|
||||
executable: "/mnt/c/p/.venv/bin/python".into(),
|
||||
stdlib: vec![Some("/usr/lib/python3.12".into())],
|
||||
path: ["/mnt/c/p/src", "/usr/lib/python3.12", "/mnt/c/p/.venv/lib/python3.12/site-packages", "/opt/extra"]
|
||||
.map(String::from)
|
||||
.to_vec(),
|
||||
};
|
||||
assert_eq!(
|
||||
super::wsl_folders(&probe, "/mnt/c/p"),
|
||||
["/mnt/c/p/.venv/lib/python3.12/site-packages", "/opt/extra"]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
ide_command::domain!(sdk_container_python: sdk_container_python, sdk_container_python_refresh, sdk_wsl_pythons);
|
||||
@@ -9,7 +9,11 @@ use std::path::{Path, PathBuf};
|
||||
struct DocumentsHost<'a>(&'a Documents);
|
||||
|
||||
impl ReplaceHost for DocumentsHost<'_> {
|
||||
fn edit_file(&self, path: &Path, compute: &mut dyn FnMut(&str) -> IdeResult<Vec<TextEdit>>) -> IdeResult<u32> {
|
||||
fn edit_file(
|
||||
&self,
|
||||
path: &Path,
|
||||
compute: &mut dyn FnMut(&str) -> IdeResult<Vec<TextEdit>>,
|
||||
) -> IdeResult<(u32, bool)> {
|
||||
let docs = self.0;
|
||||
let (doc, transient) = match docs.by_path(path) {
|
||||
Some(doc) => (doc, false),
|
||||
@@ -24,7 +28,7 @@ impl ReplaceHost for DocumentsHost<'_> {
|
||||
let snap = docs.text_snapshot(doc)?;
|
||||
let edits = compute(&snap.text)?;
|
||||
if edits.is_empty() {
|
||||
return Ok(0);
|
||||
return Ok((0, false));
|
||||
}
|
||||
if docs.text_snapshot(doc)?.version != snap.version {
|
||||
continue;
|
||||
@@ -33,12 +37,13 @@ impl ReplaceHost for DocumentsHost<'_> {
|
||||
// An open tab's file may have changed on disk before the watcher reported it:
|
||||
// autosave keeps that change and leaves the replacement unsaved. A file opened
|
||||
// just for this was read now.
|
||||
if transient {
|
||||
let disk_conflict = if transient {
|
||||
docs.save(doc)?;
|
||||
} else if save {
|
||||
docs.autosave(doc)?;
|
||||
}
|
||||
return Ok(edits.len() as u32);
|
||||
false
|
||||
} else {
|
||||
save && !docs.autosave(doc)?
|
||||
};
|
||||
return Ok((edits.len() as u32, disk_conflict));
|
||||
}
|
||||
Err(ide_core::IdeError::unavailable("the file kept changing during Replace"))
|
||||
})();
|
||||
|
||||
@@ -0,0 +1,265 @@
|
||||
//! What only Subversion has (VCS › Subversion): Cleanup, Lock / Unlock,
|
||||
//! Relocate, Properties, and Checkout from URL. Everything else a Subversion
|
||||
//! working copy does goes through the shared `vcs_*` commands and
|
||||
//! [`ide_vcs::Backend`].
|
||||
|
||||
use crate::Host;
|
||||
use crate::Project;
|
||||
use crate::ops::blocking;
|
||||
use ide_command::command;
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult};
|
||||
use ide_svn::WorkingCopy;
|
||||
use ide_vcs::Backend;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
|
||||
/// The working copy a Subversion backend is, if it is one.
|
||||
pub(crate) fn as_svn(backend: &dyn Backend) -> Option<&WorkingCopy> {
|
||||
(backend as &dyn std::any::Any).downcast_ref::<WorkingCopy>()
|
||||
}
|
||||
|
||||
/// Runs `f` with the Subversion working copy `at` names (its root), or the one holding `path`.
|
||||
fn with_working_copy<T>(
|
||||
project: &Project,
|
||||
at: Option<&Path>,
|
||||
f: impl FnOnce(&WorkingCopy) -> IdeResult<T>,
|
||||
) -> IdeResult<T> {
|
||||
let backend: Option<Arc<dyn Backend>> = match at {
|
||||
Some(path) => project.backend_of(path),
|
||||
None => project.backend_at(None),
|
||||
};
|
||||
match backend.as_deref().and_then(as_svn) {
|
||||
Some(wc) => f(wc),
|
||||
None => Err(IdeError::invalid("not in a Subversion working copy")),
|
||||
}
|
||||
}
|
||||
|
||||
/// VCS › Subversion › Cleanup: finishes or undoes an interrupted operation and
|
||||
/// releases the working copy's lock.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn svn_cleanup(host: &Host, window: &str, repo: Option<PathBuf>) -> IdeResult<()> {
|
||||
let project = host.project(window)?;
|
||||
blocking(move || {
|
||||
with_working_copy(&project, repo.as_deref(), |wc| wc.cleanup(&CancellationToken::new()))?;
|
||||
project.vcs_changed();
|
||||
Ok(())
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// VCS › Subversion › Lock: `svn lock` with a comment; `steal` takes a lock someone else holds.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn svn_lock(host: &Host, window: &str, paths: Vec<PathBuf>, comment: String, steal: bool) -> IdeResult<()> {
|
||||
let project = host.project(window)?;
|
||||
blocking(move || {
|
||||
let first = paths.first().cloned().ok_or_else(|| IdeError::invalid("nothing to lock"))?;
|
||||
with_working_copy(&project, Some(&first), |wc| wc.lock(&paths, &comment, steal, &CancellationToken::new()))?;
|
||||
project.vcs_changed();
|
||||
Ok(())
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// VCS › Subversion › Unlock; `force` breaks a lock this working copy does not hold.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn svn_unlock(host: &Host, window: &str, paths: Vec<PathBuf>, force: bool) -> IdeResult<()> {
|
||||
let project = host.project(window)?;
|
||||
blocking(move || {
|
||||
let first = paths.first().cloned().ok_or_else(|| IdeError::invalid("nothing to unlock"))?;
|
||||
with_working_copy(&project, Some(&first), |wc| wc.unlock(&paths, force, &CancellationToken::new()))?;
|
||||
project.vcs_changed();
|
||||
Ok(())
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Where a working copy points: VCS › Subversion › Relocate shows the current URL.
|
||||
#[derive(Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct SvnRepositoryInfo {
|
||||
pub url: String,
|
||||
pub root_url: String,
|
||||
pub revision: Option<u32>,
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn svn_repository_info(host: &Host, window: &str, repo: Option<PathBuf>) -> IdeResult<SvnRepositoryInfo> {
|
||||
let project = host.project(window)?;
|
||||
blocking(move || {
|
||||
with_working_copy(&project, repo.as_deref(), |wc| {
|
||||
let r = wc.repository();
|
||||
Ok(SvnRepositoryInfo {
|
||||
url: r.url,
|
||||
root_url: r.root_url,
|
||||
revision: r.revision.and_then(|r| u32::try_from(r).ok()),
|
||||
})
|
||||
})
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// VCS › Subversion › Relocate: the same repository at a new URL (another host or scheme).
|
||||
#[command(trust = trusted)]
|
||||
pub async fn svn_relocate(host: &Host, window: &str, repo: Option<PathBuf>, url: String) -> IdeResult<()> {
|
||||
let project = host.project(window)?;
|
||||
blocking(move || {
|
||||
with_working_copy(&project, repo.as_deref(), |wc| wc.relocate(&url, &CancellationToken::new()))?;
|
||||
project.vcs_changed();
|
||||
Ok(())
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// The conflicts dialog's Accept Deletion on a tree conflict whose incoming change deleted
|
||||
/// `path`: the conflict is resolved and the local item removed.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn svn_accept_incoming_delete(host: &Host, window: &str, path: PathBuf) -> IdeResult<()> {
|
||||
let project = host.project(window)?;
|
||||
blocking(move || {
|
||||
project.with_backend_recorded(
|
||||
project.backend_of(&path).as_deref().map(|b| b.root()),
|
||||
Some("Accept deletion"),
|
||||
|b| {
|
||||
as_svn(b)
|
||||
.ok_or_else(|| IdeError::invalid("not in a Subversion working copy"))?
|
||||
.accept_incoming_delete(&path)
|
||||
},
|
||||
)?;
|
||||
project.vcs_changed();
|
||||
Ok(())
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// One versioned property (`svn:ignore`, `svn:needs-lock`, or the user's own).
|
||||
#[derive(Clone, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct SvnProperty {
|
||||
pub name: String,
|
||||
pub value: String,
|
||||
}
|
||||
|
||||
/// VCS › Subversion › Properties: the properties of a file or folder.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn svn_properties(host: &Host, window: &str, path: PathBuf) -> IdeResult<Vec<SvnProperty>> {
|
||||
let project = host.project(window)?;
|
||||
blocking(move || {
|
||||
with_working_copy(&project, Some(&path), |wc| {
|
||||
Ok(wc.properties(&path)?.into_iter().map(|(name, value)| SvnProperty { name, value }).collect())
|
||||
})
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Sets property `name` of `path`, or deletes it when `value` is `None`.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn svn_set_property(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
path: PathBuf,
|
||||
name: String,
|
||||
value: Option<String>,
|
||||
) -> IdeResult<()> {
|
||||
let project = host.project(window)?;
|
||||
blocking(move || {
|
||||
with_working_copy(&project, Some(&path), |wc| wc.set_property(&path, &name, value.as_deref()))?;
|
||||
project.vcs_changed();
|
||||
Ok(())
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Settings › Version Control › Subversion: the svn found on `PATH` or in a usual
|
||||
/// install folder, and the version of `executable` (that one when empty).
|
||||
#[derive(Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct SvnVersion {
|
||||
pub detected: Option<String>,
|
||||
pub version: Option<String>,
|
||||
pub error: Option<String>,
|
||||
}
|
||||
|
||||
/// Settings › Subversion › Test. Auto-detection runs anywhere; a path of the user's or the
|
||||
/// project's choosing runs only in a trusted project (as Git's Test does).
|
||||
#[command(trust = always)]
|
||||
pub async fn svn_version(host: &Host, window: &str, executable: String) -> IdeResult<SvnVersion> {
|
||||
if !executable.trim().is_empty() {
|
||||
host.require_trust_if_project(window)?;
|
||||
}
|
||||
blocking(move || {
|
||||
let detected = ide_svn::detected_executable().map(|p| p.display().to_string());
|
||||
let settings = ide_svn::Settings {
|
||||
executable: (!executable.trim().is_empty()).then(|| PathBuf::from(executable.trim())),
|
||||
..ide_svn::Settings::default()
|
||||
};
|
||||
let (version, error) = match ide_svn::SvnContext::new(settings).version() {
|
||||
Ok((major, minor)) if (major, minor) < ide_svn::MIN_VERSION => (
|
||||
Some(format!("{major}.{minor}")),
|
||||
Some(format!(
|
||||
"OpenIDEA needs Subversion {}.{} or later",
|
||||
ide_svn::MIN_VERSION.0,
|
||||
ide_svn::MIN_VERSION.1
|
||||
)),
|
||||
),
|
||||
Ok((major, minor)) => (Some(format!("{major}.{minor}")), None),
|
||||
Err(e) => (None, Some(e.message)),
|
||||
};
|
||||
Ok(SvnVersion { detected, version, error })
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Get from Version Control › Subversion: `svn checkout` of `url` into `dest`, with the
|
||||
/// window's project settings when it has a project, the global ones otherwise. svn's progress
|
||||
/// lines go to `on_output`; `cancel_request(request)` stops it (as Git's clone).
|
||||
#[command(trust = always)]
|
||||
pub async fn svn_checkout(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
request: ide_core::RequestId,
|
||||
url: String,
|
||||
dest: PathBuf,
|
||||
on_output: crate::ops::Channel<String>,
|
||||
) -> IdeResult<()> {
|
||||
let project = host.project(window).ok();
|
||||
let ctx = match project.as_ref().and_then(|p| p.svn.clone()) {
|
||||
Some(ctx) => {
|
||||
if let Some(p) = &project {
|
||||
p.apply_svn_settings();
|
||||
}
|
||||
ctx
|
||||
}
|
||||
None => {
|
||||
// No project yet: the global settings, and prompts in the window that asked.
|
||||
let ctx = crate::svn::context(&(host.sink_for)(window), host.subversion == Some(true));
|
||||
ctx.set_settings(crate::svn::settings(&host.global_settings.read_effective(|s| s.vcs.svn.clone())));
|
||||
ctx
|
||||
}
|
||||
};
|
||||
let cancel = host.begin_request(request);
|
||||
let result = blocking(move || {
|
||||
let report = |line: String| {
|
||||
let _ = on_output.send(line);
|
||||
};
|
||||
WorkingCopy::checkout_reporting(&url, None, &dest, ide_svn::Depth::Infinity, ctx, &cancel, &report).map(|_| ())
|
||||
})
|
||||
.await;
|
||||
host.end_request(request);
|
||||
result
|
||||
}
|
||||
|
||||
ide_command::domain!(
|
||||
svn:
|
||||
svn_accept_incoming_delete,
|
||||
svn_checkout,
|
||||
svn_cleanup,
|
||||
svn_lock,
|
||||
svn_properties,
|
||||
svn_relocate,
|
||||
svn_repository_info,
|
||||
svn_set_property,
|
||||
svn_unlock,
|
||||
svn_version,
|
||||
);
|
||||
@@ -7,19 +7,7 @@ use ide_vcs::FileStatus;
|
||||
#[command(trust = always)]
|
||||
pub async fn vcs_status(host: &Host, window: &str) -> IdeResult<Vec<FileStatus>> {
|
||||
let project = host.project(window)?;
|
||||
host.blocking(move || {
|
||||
let settings = project.settings.effective();
|
||||
let repos = project.repos();
|
||||
if repos.is_empty() {
|
||||
return Err(ide_core::IdeError::unavailable("project is not a git repository"));
|
||||
}
|
||||
for r in repos.all() {
|
||||
r.set_ignored_names(settings.ignored_names());
|
||||
r.set_cli_status(settings.vcs.git.cli_status);
|
||||
}
|
||||
repos.status()
|
||||
})
|
||||
.await
|
||||
host.blocking(move || merged_status(&project, None)).await
|
||||
}
|
||||
|
||||
#[command(trust = always)]
|
||||
@@ -42,19 +30,82 @@ pub async fn vcs_ignored_files(host: &Host, window: &str) -> IdeResult<Vec<FileS
|
||||
pub async fn vcs_status_paths(host: &Host, window: &str, paths: Vec<std::path::PathBuf>) -> IdeResult<Vec<FileStatus>> {
|
||||
// `paths` that belong to no repository are ignored, and an empty list is the full status.
|
||||
let project = host.project(window)?;
|
||||
host.blocking(move || {
|
||||
let settings = project.settings.effective();
|
||||
let repos = project.repos();
|
||||
if repos.is_empty() {
|
||||
return Err(ide_core::IdeError::unavailable("project is not a git repository"));
|
||||
host.blocking(move || merged_status(&project, Some(&paths))).await
|
||||
}
|
||||
|
||||
/// The Git repositories' changes and those of the non-Git working copies, each file reported
|
||||
/// by the backend [`crate::Project::backend_of`] routes it to. `paths` narrows them (empty:
|
||||
/// everything). A working copy that cannot answer (an unreachable server) is logged and
|
||||
/// skipped while another backend answered, so it never hides the Git changes.
|
||||
/// The last status failure said for each working copy root (see [`merged_status`]).
|
||||
static STATUS_FAILURES: parking_lot::Mutex<std::collections::BTreeMap<std::path::PathBuf, String>> =
|
||||
parking_lot::Mutex::new(std::collections::BTreeMap::new());
|
||||
|
||||
fn merged_status(project: &crate::Project, paths: Option<&[std::path::PathBuf]>) -> IdeResult<Vec<FileStatus>> {
|
||||
let settings = project.settings.effective();
|
||||
let repos = project.repos();
|
||||
let backends = project.backends();
|
||||
if repos.is_empty() && backends.is_empty() {
|
||||
return Err(ide_core::IdeError::unavailable("project is not a git repository"));
|
||||
}
|
||||
for r in repos.all() {
|
||||
r.set_ignored_names(settings.ignored_names());
|
||||
r.set_cli_status(settings.vcs.git.cli_status);
|
||||
}
|
||||
let mut status = if repos.is_empty() {
|
||||
Vec::new()
|
||||
} else {
|
||||
match paths {
|
||||
Some(paths) => repos.status_paths(paths)?,
|
||||
None => repos.status()?,
|
||||
}
|
||||
for r in repos.all() {
|
||||
r.set_ignored_names(settings.ignored_names());
|
||||
r.set_cli_status(settings.vcs.git.cli_status);
|
||||
};
|
||||
if backends.is_empty() {
|
||||
return Ok(status);
|
||||
}
|
||||
// Routed from these snapshots: one lookup per entry, no locks taken again.
|
||||
let owner = |f: &FileStatus| crate::project::backend_for(&backends, &repos, &f.path).map(|b| b.root());
|
||||
status.retain(|f| owner(f).is_none());
|
||||
let mut answered = !repos.is_empty();
|
||||
let mut failure = None;
|
||||
for backend in &backends {
|
||||
let changes = match paths.filter(|p| !p.is_empty()) {
|
||||
Some(paths) => {
|
||||
let mine: Vec<_> = paths.iter().filter(|p| p.starts_with(backend.root())).cloned().collect();
|
||||
if mine.is_empty() {
|
||||
answered = true;
|
||||
continue;
|
||||
}
|
||||
backend.status_paths(&mine)
|
||||
}
|
||||
None => backend.status(),
|
||||
};
|
||||
match changes {
|
||||
Ok(changes) => {
|
||||
answered = true;
|
||||
status.extend(changes.into_iter().filter(|f| owner(f) == Some(backend.root())));
|
||||
STATUS_FAILURES.lock().remove(backend.root());
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!("status of {}: {e}", backend.root().display());
|
||||
// Said once per root and message, not on every refresh: the Changes view would
|
||||
// otherwise show that root as unchanged without a word.
|
||||
let root = backend.root().to_path_buf();
|
||||
if STATUS_FAILURES.lock().insert(root.clone(), e.message.clone()).as_ref() != Some(&e.message) {
|
||||
project.sink.emit(ide_core::IdeEvent::Notify {
|
||||
level: ide_core::event::NotifyLevel::Warning,
|
||||
title: format!("Changes of {} could not be read", root.display()),
|
||||
body: Some(e.message.clone()),
|
||||
});
|
||||
}
|
||||
failure = Some(e);
|
||||
}
|
||||
}
|
||||
repos.status_paths(&paths)
|
||||
})
|
||||
.await
|
||||
}
|
||||
match failure {
|
||||
Some(e) if !answered => Err(e),
|
||||
_ => Ok(status),
|
||||
}
|
||||
}
|
||||
|
||||
pub mod commands;
|
||||
|
||||
@@ -94,13 +94,14 @@ async fn revision_text(
|
||||
project: &Option<std::sync::Arc<Project>>,
|
||||
external: &Option<std::sync::Arc<ide_vcs::Repo>>,
|
||||
path: &Path,
|
||||
f: impl FnOnce(&ide_vcs::Repo) -> IdeResult<T>,
|
||||
f: impl FnOnce(&dyn Backend) -> IdeResult<T>,
|
||||
) -> IdeResult<T> {
|
||||
match project {
|
||||
Some(project) => project.with_log_repo_of(path, f),
|
||||
Some(project) => project.with_log_backend_of(path, f),
|
||||
None => f(external
|
||||
.as_ref()
|
||||
.ok_or_else(|| ide_core::IdeError::unavailable("external Git log is not open"))?),
|
||||
.ok_or_else(|| ide_core::IdeError::unavailable("external Git log is not open"))?
|
||||
.as_ref()),
|
||||
}
|
||||
}
|
||||
let (text_encoding, charset) = match &encoding {
|
||||
@@ -148,20 +149,46 @@ impl LogAccess {
|
||||
.with_log_repo_at(at, f)
|
||||
}
|
||||
|
||||
/// The non-Git working copy `at` names (see [`Project::backend_at`]).
|
||||
fn backend(&self, at: Option<&Path>) -> Option<std::sync::Arc<dyn Backend>> {
|
||||
if self.external.is_some() {
|
||||
return None;
|
||||
}
|
||||
self.project.as_ref().and_then(|p| p.backend_at(at))
|
||||
}
|
||||
|
||||
/// `with_log_repo_at` through the backend-agnostic Changes-view surface.
|
||||
fn with_log_backend_at<T>(&self, at: Option<&Path>, f: impl FnOnce(&dyn Backend) -> IdeResult<T>) -> IdeResult<T> {
|
||||
if let Some(backend) = self.backend(at) {
|
||||
return f(backend.as_ref());
|
||||
}
|
||||
self.with_log_repo_at(at, |r| f(r as &dyn Backend))
|
||||
}
|
||||
|
||||
/// `with_log_repo_at` for a Git-only read: a non-Git working copy answers `T::default()`
|
||||
/// (no refs, users, branches) so its log and branch widget still work.
|
||||
fn with_git_log_or_default<T: Default>(
|
||||
&self,
|
||||
at: Option<&Path>,
|
||||
f: impl FnOnce(&Repo) -> IdeResult<T>,
|
||||
) -> IdeResult<T> {
|
||||
if self.backend(at).is_some() {
|
||||
return Ok(T::default());
|
||||
}
|
||||
self.with_log_repo_at(at, f)
|
||||
}
|
||||
}
|
||||
|
||||
/// A repository of the project (IDEA's VCS root).
|
||||
#[derive(Serialize, Deserialize, Type)]
|
||||
#[derive(Default, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct VcsRoot {
|
||||
/// Worktree root.
|
||||
pub root: ide_core::IpcPath,
|
||||
/// Root representing all mapped worktrees of the same Git repository in branch lists.
|
||||
pub branch_root: ide_core::IpcPath,
|
||||
/// The version control system holding it.
|
||||
pub kind: VcsKind,
|
||||
/// Merge / rebase / cherry-pick / revert in progress.
|
||||
pub operation: Option<String>,
|
||||
/// The current rebase uses Git's interactive mode.
|
||||
@@ -190,6 +217,10 @@ pub struct VcsRoot {
|
||||
/// Conflicts staged during the current operation that can be reopened.
|
||||
#[serde(default)]
|
||||
pub resolved_conflicts: Vec<ide_core::IpcPath>,
|
||||
/// The repository's worktree or git directory is missing or on an unmounted volume.
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub unavailable: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Serialize, Deserialize, Type)]
|
||||
@@ -422,14 +453,32 @@ fn per_repo(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `per_repo` through the backend-agnostic Changes-view surface.
|
||||
/// `per_repo` through the backend-agnostic Changes-view surface: the paths of a non-Git
|
||||
/// working copy go to it, the rest to the Git repositories as before.
|
||||
fn per_backend(
|
||||
project: &Project,
|
||||
paths: &[PathBuf],
|
||||
recorded: Option<&str>,
|
||||
f: impl Fn(&dyn Backend, &[PathBuf]) -> IdeResult<()>,
|
||||
) -> IdeResult<()> {
|
||||
per_repo(project, paths, recorded, |r, paths| f(r as &dyn Backend, paths))
|
||||
let mut git: Vec<PathBuf> = Vec::new();
|
||||
let mut groups: Vec<(std::sync::Arc<dyn Backend>, Vec<PathBuf>)> = Vec::new();
|
||||
for path in paths {
|
||||
match project.backend_of(path) {
|
||||
Some(backend) => match groups.iter_mut().find(|(b, _)| b.root() == backend.root()) {
|
||||
Some((_, mine)) => mine.push(path.clone()),
|
||||
None => groups.push((backend, vec![path.clone()])),
|
||||
},
|
||||
None => git.push(path.clone()),
|
||||
}
|
||||
}
|
||||
for (backend, mine) in &groups {
|
||||
project.backend_recorded(backend.as_ref(), recorded, |b| f(b, mine))?;
|
||||
}
|
||||
if git.is_empty() && !groups.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
per_repo(project, &git, recorded, |r, paths| f(r as &dyn Backend, paths))
|
||||
}
|
||||
|
||||
fn with_shelf_batch<T>(project: &Project, batch: Option<String>, operation: impl FnOnce() -> T) -> T {
|
||||
@@ -531,29 +580,59 @@ pub async fn vcs_detected_roots(host: &Host, window: &str) -> IdeResult<Vec<Path
|
||||
blocking(move || project.detected_repository_roots()).await
|
||||
}
|
||||
|
||||
fn unavailable_vcs_root(root: &Path) -> VcsRoot {
|
||||
VcsRoot {
|
||||
root: root.into(),
|
||||
branch_root: root.into(),
|
||||
// Only Git repositories are mapped (Directory Mappings).
|
||||
kind: VcsKind::Git,
|
||||
operation: None,
|
||||
interactive_rebase: false,
|
||||
head: None,
|
||||
head_commit: None,
|
||||
shallow: false,
|
||||
lfs: false,
|
||||
uninitialized_submodules: Vec::new(),
|
||||
has_remotes: None,
|
||||
resolved_conflicts: Vec::new(),
|
||||
unavailable: true,
|
||||
}
|
||||
}
|
||||
|
||||
/// The project's repositories, the primary one first.
|
||||
#[command(trust = always)]
|
||||
pub async fn vcs_roots(host: &Host, window: &str) -> IdeResult<Vec<VcsRoot>> {
|
||||
let project = host.project(window)?;
|
||||
let repos = project.repos();
|
||||
let backends = project.backends();
|
||||
let trusted = project.is_trusted();
|
||||
blocking(move || {
|
||||
let primary = repos.primary().map(|r| r.root().to_path_buf());
|
||||
let mut all: Vec<_> = repos.all().iter().collect();
|
||||
all.sort_by_key(|r| Some(r.root()) != primary.as_deref());
|
||||
let roots: Vec<_> = all.into_iter().map(|repo| (repo, repo.metadata_dirs().ok())).collect();
|
||||
let roots: Vec<_> = all
|
||||
.into_iter()
|
||||
.map(|repo| {
|
||||
let dirs = repo.check_valid().ok().and_then(|()| repo.metadata_dirs().ok());
|
||||
let available = dirs.is_some() && !repo.is_stale();
|
||||
(repo, available, dirs)
|
||||
})
|
||||
.collect();
|
||||
let mut branch_roots = std::collections::HashMap::new();
|
||||
for (repo, dirs) in &roots {
|
||||
if let Some([git_dir, common_dir]) = dirs {
|
||||
for (repo, available, dirs) in &roots {
|
||||
if *available && let Some([git_dir, common_dir]) = dirs {
|
||||
let first = branch_roots.entry(common_dir).or_insert(repo.root());
|
||||
if git_dir == common_dir {
|
||||
*first = repo.root();
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(roots
|
||||
let mut roots: Vec<VcsRoot> = roots
|
||||
.iter()
|
||||
.map(|(r, dirs)| {
|
||||
.map(|(r, available, dirs)| {
|
||||
if !available {
|
||||
return unavailable_vcs_root(r.root());
|
||||
}
|
||||
let branch_root = dirs.as_ref().and_then(|[_, common_dir]| branch_roots.get(common_dir));
|
||||
let (head, head_commit) = r.head().unwrap_or_default();
|
||||
let operation = r.operation().ok().flatten();
|
||||
@@ -565,14 +644,20 @@ pub async fn vcs_roots(host: &Host, window: &str) -> IdeResult<Vec<VcsRoot>> {
|
||||
.into_iter()
|
||||
.map(Into::into)
|
||||
.collect();
|
||||
let has_remotes = trusted.then(|| r.has_remotes().ok()).flatten();
|
||||
let shallow = r.is_shallow().unwrap_or(false);
|
||||
if r.is_stale() {
|
||||
return unavailable_vcs_root(r.root());
|
||||
}
|
||||
VcsRoot {
|
||||
root: r.root().into(),
|
||||
branch_root: branch_root.copied().unwrap_or_else(|| r.root()).into(),
|
||||
kind: VcsKind::Git,
|
||||
operation,
|
||||
interactive_rebase,
|
||||
head,
|
||||
head_commit,
|
||||
shallow: r.is_shallow().unwrap_or(false),
|
||||
shallow,
|
||||
lfs: r.uses_lfs(),
|
||||
uninitialized_submodules: r
|
||||
.uninitialized_submodules()
|
||||
@@ -580,11 +665,21 @@ pub async fn vcs_roots(host: &Host, window: &str) -> IdeResult<Vec<VcsRoot>> {
|
||||
.iter()
|
||||
.map(|path| ide_core::ipc_path::to_ipc(path))
|
||||
.collect(),
|
||||
has_remotes: trusted.then(|| r.has_remotes().ok()).flatten(),
|
||||
has_remotes,
|
||||
resolved_conflicts,
|
||||
unavailable: false,
|
||||
}
|
||||
})
|
||||
.collect())
|
||||
.collect();
|
||||
// A non-Git working copy shows its own head (a stream, `trunk`) where Git shows the branch.
|
||||
roots.extend(backends.iter().map(|b| VcsRoot {
|
||||
root: b.root().into(),
|
||||
branch_root: b.root().into(),
|
||||
kind: b.kind(),
|
||||
head: b.head_label(),
|
||||
..VcsRoot::default()
|
||||
}));
|
||||
Ok(roots)
|
||||
})
|
||||
.await
|
||||
}
|
||||
@@ -592,7 +687,13 @@ pub async fn vcs_roots(host: &Host, window: &str) -> IdeResult<Vec<VcsRoot>> {
|
||||
#[command(trust = always)]
|
||||
pub async fn vcs_branch_info(host: &Host, window: &str, repo: Option<PathBuf>) -> IdeResult<BranchInfo> {
|
||||
let project = LogAccess::new(host, window, repo.as_deref());
|
||||
blocking(move || project.with_log_repo_at(repo.as_deref(), |r| r.branch_info())).await
|
||||
blocking(move || {
|
||||
if let Some(backend) = project.backend(repo.as_deref()) {
|
||||
return Ok(BranchInfo { head: backend.head_label(), ..BranchInfo::default() });
|
||||
}
|
||||
project.with_log_repo_at(repo.as_deref(), |r| r.branch_info())
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
@@ -863,6 +964,9 @@ pub async fn vcs_log(host: &Host, window: &str, repo: Option<PathBuf>, query: Lo
|
||||
let cancel =
|
||||
request.map_or_else(ide_core::CancellationToken::new, |id| host.begin_project_read_request(window, id));
|
||||
let result = blocking(move || {
|
||||
if let Some(backend) = project.backend(repo.as_deref()) {
|
||||
return backend.log(&query, &cancel);
|
||||
}
|
||||
project.with_log_repo_at(repo.as_deref(), |r| {
|
||||
r.enable_log_index(&project.cache);
|
||||
(r as &dyn Backend).log(&query, &cancel)
|
||||
@@ -900,13 +1004,13 @@ pub async fn vcs_log_refs(
|
||||
repo: Option<PathBuf>,
|
||||
) -> IdeResult<std::collections::BTreeMap<String, String>> {
|
||||
let project = LogAccess::new(host, window, repo.as_deref());
|
||||
blocking(move || project.with_log_repo_at(repo.as_deref(), |r| r.log_refs())).await
|
||||
blocking(move || project.with_git_log_or_default(repo.as_deref(), |r| r.log_refs())).await
|
||||
}
|
||||
|
||||
#[command(trust = always)]
|
||||
pub async fn vcs_log_users(host: &Host, window: &str, repo: Option<PathBuf>) -> IdeResult<Vec<String>> {
|
||||
let project = LogAccess::new(host, window, repo.as_deref());
|
||||
blocking(move || project.with_log_repo_at(repo.as_deref(), |r| r.log_users())).await
|
||||
blocking(move || project.with_git_log_or_default(repo.as_deref(), |r| r.log_users())).await
|
||||
}
|
||||
|
||||
#[command(trust = always)]
|
||||
@@ -936,7 +1040,7 @@ pub async fn vcs_log_details(
|
||||
revision: String,
|
||||
) -> IdeResult<LogDetails> {
|
||||
let project = LogAccess::new(host, window, repo.as_deref());
|
||||
blocking(move || project.with_log_repo_at(repo.as_deref(), |r| r.log_details(&revision))).await
|
||||
blocking(move || project.with_log_backend_at(repo.as_deref(), |b| b.log_details(&revision))).await
|
||||
}
|
||||
|
||||
#[command(trust = always)]
|
||||
@@ -950,6 +1054,9 @@ pub async fn vcs_log_details_batch(
|
||||
let project = LogAccess::new(host, window, repo.as_deref());
|
||||
let cancel = host.begin_project_read_request(window, request);
|
||||
let result = blocking(move || {
|
||||
if let Some(backend) = project.backend(repo.as_deref()) {
|
||||
return revisions.iter().map(|revision| backend.log_details(revision)).collect();
|
||||
}
|
||||
project.with_log_repo_at(repo.as_deref(), |r| {
|
||||
r.enable_log_index(&project.cache);
|
||||
r.log_details_batch_cancellable(&revisions, &cancel)
|
||||
@@ -1007,6 +1114,20 @@ pub async fn vcs_commit_files(
|
||||
blocking(move || project.with_log_backend_at(repo.as_deref(), |r| r.commit_files(&commit))).await
|
||||
}
|
||||
|
||||
/// What `commit` did to one file (`path`, relative to the repository), without listing the
|
||||
/// commit's other changes; `None` when it left the file as it was.
|
||||
#[command(trust = always)]
|
||||
pub async fn vcs_commit_file_change(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
repo: Option<PathBuf>,
|
||||
commit: String,
|
||||
path: String,
|
||||
) -> IdeResult<Option<ChangedFile>> {
|
||||
let project = LogAccess::new(host, window, repo.as_deref());
|
||||
blocking(move || project.with_log_backend_at(repo.as_deref(), |r| r.commit_file_change(&commit, &path))).await
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn vcs_preview_partial_commit(host: &Host, window: &str, file: PartialCommitFile) -> IdeResult<String> {
|
||||
let project = host.project(window)?;
|
||||
@@ -1083,9 +1204,12 @@ pub async fn vcs_commit_selection_changes(
|
||||
) -> IdeResult<Vec<RevisionChange>> {
|
||||
let project = LogAccess::new(host, window, repo.as_deref());
|
||||
let cancel = host.begin_project_read_request(window, request);
|
||||
let result =
|
||||
blocking(move || project.with_log_repo_at(repo.as_deref(), |r| r.commit_selection_changes(&commits, &cancel)))
|
||||
.await;
|
||||
let result = blocking(move || match project.backend(repo.as_deref()) {
|
||||
// Post-commit checks read what a commit changed, in a working copy of another system too.
|
||||
Some(backend) => backend.commits_changes(&commits),
|
||||
None => project.with_log_repo_at(repo.as_deref(), |r| r.commit_selection_changes(&commits, &cancel)),
|
||||
})
|
||||
.await;
|
||||
host.end_request(request);
|
||||
result
|
||||
}
|
||||
@@ -1093,13 +1217,23 @@ pub async fn vcs_commit_selection_changes(
|
||||
#[command(trust = always)]
|
||||
pub async fn vcs_branches(host: &Host, window: &str, repo: Option<PathBuf>) -> IdeResult<Vec<Branch>> {
|
||||
let project = LogAccess::new(host, window, repo.as_deref());
|
||||
blocking(move || project.with_log_repo_at(repo.as_deref(), |r| r.branches())).await
|
||||
blocking(move || match project.backend(repo.as_deref()) {
|
||||
Some(backend) => backend.branches(),
|
||||
None => project.with_log_repo_at(repo.as_deref(), |r| r.branches()),
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
#[command(trust = always)]
|
||||
pub async fn vcs_stashes(host: &Host, window: &str, repo: Option<PathBuf>) -> IdeResult<Vec<Stash>> {
|
||||
let project = host.project(window)?;
|
||||
blocking(move || project.with_repo_at(repo.as_deref(), |r| r.stashes())).await
|
||||
blocking(move || {
|
||||
if project.backend_at(repo.as_deref()).is_some() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
project.with_repo_at(repo.as_deref(), |r| r.stashes())
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
@@ -1303,6 +1437,26 @@ pub async fn vcs_checkout(
|
||||
let options = options.unwrap_or_default();
|
||||
blocking(move || {
|
||||
with_shelf_batch(&project, shelf_batch, || {
|
||||
// A non-Git working copy switches to another line of development (`svn switch`).
|
||||
if project.backend_at(repo.as_deref()).is_some() {
|
||||
return project.with_backend_recorded(repo.as_deref(), Some("Switch"), |b| {
|
||||
if create {
|
||||
// New Branch in a Subversion working copy: Create Branch or Tag (`svn copy` on
|
||||
// the server) to `branches/<name>`, or `tags/<name>` as typed, then switch to it.
|
||||
let wc = crate::ops::svn::as_svn(b).ok_or_else(|| {
|
||||
ide_core::IdeError::unavailable("creating a branch is not supported here")
|
||||
})?;
|
||||
let line = if branch.starts_with("branches/") || branch.starts_with("tags/") {
|
||||
branch.clone()
|
||||
} else {
|
||||
format!("branches/{branch}")
|
||||
};
|
||||
wc.create_line(&line, &format!("Create {line}"), &ide_core::CancellationToken::new())?;
|
||||
return b.switch_to(&line).map(|()| CheckoutOutcome::Done);
|
||||
}
|
||||
b.switch_to(&branch).map(|()| CheckoutOutcome::Done)
|
||||
});
|
||||
}
|
||||
project.with_repo_recorded(repo.as_deref(), Some("Git checkout"), |r| {
|
||||
r.checkout_with(&branch, create, &options)
|
||||
})
|
||||
@@ -1802,6 +1956,15 @@ pub async fn vcs_remote(
|
||||
RemoteOp::PullLfs => Some("Git LFS pull"),
|
||||
_ => None,
|
||||
};
|
||||
// Update Project on a non-Git working copy is its own update (`svn update`, `p4 sync`).
|
||||
if matches!(op, RemoteOp::Pull { .. } | RemoteOp::UpdateProjectBranch { .. })
|
||||
&& project.backend_at(repo.as_deref()).is_some()
|
||||
{
|
||||
return with_shelf_batch(&project, shelf_batch, || {
|
||||
project
|
||||
.with_backend_recorded(repo.as_deref(), Some("Update"), |b| b.update(&cancel, &out).map(|()| None))
|
||||
});
|
||||
}
|
||||
with_shelf_batch(&project, shelf_batch, || {
|
||||
project.with_repo_recorded(repo.as_deref(), recorded, |r| match op {
|
||||
RemoteOp::Fetch { background: true, report, skip_remotes } => {
|
||||
@@ -1932,8 +2095,14 @@ pub async fn vcs_update_branches(
|
||||
#[command(trust = always)]
|
||||
pub async fn vcs_conflict_versions(host: &Host, window: &str, path: PathBuf) -> IdeResult<ide_vcs::MergeVersions> {
|
||||
let project = host.project(window)?;
|
||||
blocking(move || project.with_repo_of(&path, |r| r.merge_versions(&path, project.vcs_encoding(&path, Some(":2"))?)))
|
||||
.await
|
||||
blocking(move || {
|
||||
project.with_backend_of(&path, |b| {
|
||||
// Git reads the user's side from the index; a working copy without one, from the file.
|
||||
let rev = if b.as_git().is_some() { ":2" } else { "WT" };
|
||||
b.conflict_versions(&path, project.vcs_encoding(&path, Some(rev))?)
|
||||
})
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
@@ -1949,8 +2118,7 @@ pub async fn vcs_accept_conflict_side(
|
||||
ide_vcs::ConflictSide::Ours => "Accept yours",
|
||||
ide_vcs::ConflictSide::Theirs => "Accept theirs",
|
||||
};
|
||||
blocking(move || per_repo(&project, &paths, Some(label), |repo, paths| repo.accept_conflict_side(paths, side)))
|
||||
.await
|
||||
blocking(move || per_backend(&project, &paths, Some(label), |b, paths| b.accept_conflict_side(paths, side))).await
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
@@ -1961,6 +2129,23 @@ pub async fn vcs_revert_resolved(host: &Host, window: &str, paths: Vec<PathBuf>)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Marks the conflicts of `paths` resolved with the files as they are (the merge editor
|
||||
/// saved its result): `git add`, `svn resolve --accept working`.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn vcs_mark_resolved(host: &Host, window: &str, paths: Vec<PathBuf>) -> IdeResult<()> {
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
blocking(move || per_backend(&project, &paths, Some("Mark resolved"), |b, paths| b.mark_resolved(paths))).await
|
||||
}
|
||||
|
||||
/// The conflicts of `path` the merge editor does not show (property and tree conflicts of
|
||||
/// a Subversion working copy); none for a Git repository.
|
||||
#[command(trust = always)]
|
||||
pub async fn vcs_conflict_details(host: &Host, window: &str, path: PathBuf) -> IdeResult<Vec<ide_vcs::ConflictDetail>> {
|
||||
let project = host.project(window)?;
|
||||
blocking(move || project.with_backend_of(&path, |b| b.conflict_details(&path))).await
|
||||
}
|
||||
|
||||
#[command(trust = always)]
|
||||
pub async fn vcs_diff_text(host: &Host, window: &str, path: PathBuf, staged: bool) -> IdeResult<String> {
|
||||
let project = host.project(window)?;
|
||||
@@ -3236,6 +3421,103 @@ pub async fn vcs_shelf_import(
|
||||
.await
|
||||
}
|
||||
|
||||
/// The changelists the non-Git working copy at `repo` keeps itself; `None` when the root
|
||||
/// (Git) leaves them to the IDE's lists ([`vcs_changelists_load`]).
|
||||
#[command(trust = trusted)]
|
||||
pub async fn vcs_backend_changelists(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
repo: Option<PathBuf>,
|
||||
) -> IdeResult<Option<Vec<BackendChangelist>>> {
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
blocking(move || match project.backend_at(repo.as_deref()) {
|
||||
Some(backend) => backend.changelists(),
|
||||
None => Ok(None),
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Creates a changelist of the working copy at `repo`; returns its id.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn vcs_backend_changelist_create(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
repo: Option<PathBuf>,
|
||||
name: String,
|
||||
comment: String,
|
||||
) -> IdeResult<String> {
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
blocking(move || {
|
||||
let id = project.with_backend_at(repo.as_deref(), |b| b.create_changelist(&name, &comment))?;
|
||||
project.vcs_changed();
|
||||
Ok(id)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn vcs_backend_changelist_edit(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
repo: Option<PathBuf>,
|
||||
id: String,
|
||||
name: String,
|
||||
comment: String,
|
||||
) -> IdeResult<()> {
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
blocking(move || {
|
||||
project.with_backend_at(repo.as_deref(), |b| b.edit_changelist(&id, &name, &comment))?;
|
||||
project.vcs_changed();
|
||||
Ok(())
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn vcs_backend_changelist_delete(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
repo: Option<PathBuf>,
|
||||
id: String,
|
||||
) -> IdeResult<()> {
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
blocking(move || {
|
||||
project.with_backend_at(repo.as_deref(), |b| b.delete_changelist(&id))?;
|
||||
project.vcs_changed();
|
||||
Ok(())
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Moves `paths` to changelist `id` of the working copy each belongs to.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn vcs_backend_changelist_move(host: &Host, window: &str, paths: Vec<PathBuf>, id: String) -> IdeResult<()> {
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
blocking(move || {
|
||||
let mut groups: Vec<(std::sync::Arc<dyn Backend>, Vec<PathBuf>)> = Vec::new();
|
||||
for path in paths {
|
||||
let backend = project.backend_of(&path).ok_or_else(|| {
|
||||
ide_core::IdeError::invalid(format!("{} is not in a working copy with changelists", path.display()))
|
||||
})?;
|
||||
match groups.iter_mut().find(|(b, _)| b.root() == backend.root()) {
|
||||
Some((_, mine)) => mine.push(path),
|
||||
None => groups.push((backend, vec![path])),
|
||||
}
|
||||
}
|
||||
for (backend, mine) in &groups {
|
||||
backend.move_to_changelist(mine, &id)?;
|
||||
}
|
||||
project.vcs_changed();
|
||||
Ok(())
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
#[command(trust = always)]
|
||||
pub async fn vcs_changelists_load(host: &Host, window: &str) -> IdeResult<ChangelistState> {
|
||||
let project = host.project(window)?;
|
||||
@@ -3319,6 +3601,11 @@ ide_command::domain!(
|
||||
vcs_branch_info,
|
||||
vcs_check_incoming,
|
||||
vcs_branches,
|
||||
vcs_backend_changelists,
|
||||
vcs_backend_changelist_create,
|
||||
vcs_backend_changelist_edit,
|
||||
vcs_backend_changelist_delete,
|
||||
vcs_backend_changelist_move,
|
||||
vcs_changelists_load,
|
||||
vcs_changelists_save,
|
||||
vcs_checkout,
|
||||
@@ -3327,6 +3614,7 @@ ide_command::domain!(
|
||||
vcs_commit,
|
||||
vcs_keep_amend_commit,
|
||||
vcs_commit_crlf_paths,
|
||||
vcs_commit_file_change,
|
||||
vcs_commit_files,
|
||||
vcs_commit_large_files,
|
||||
vcs_preview_partial_commit,
|
||||
@@ -3346,6 +3634,8 @@ ide_command::domain!(
|
||||
vcs_conflict_versions,
|
||||
vcs_accept_conflict_side,
|
||||
vcs_revert_resolved,
|
||||
vcs_mark_resolved,
|
||||
vcs_conflict_details,
|
||||
vcs_create_branch,
|
||||
vcs_undo_branch_creation,
|
||||
vcs_create_patch,
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
//! Code insight for Xcode projects: sourcekit-lsp doesn't read `.xcodeproj` / `.xcworkspace`
|
||||
//! files, it gets their build settings from a Build Server Protocol server named in
|
||||
//! `.bsp/*.json` or the legacy `buildServer.json`. The IDE neither bundles nor installs a BSP
|
||||
//! server: it offers to run the one on `PATH` (xcode-build-server, sourcekit-xcode-bsp) to write
|
||||
//! the config, then restarts sourcekit-lsp.
|
||||
//! server: when a trusted project has none, it runs the one on `PATH` (xcode-build-server,
|
||||
//! sourcekit-xcode-bsp) to write the config, keeps the config out of Git through
|
||||
//! `.git/info/exclude`, then restarts sourcekit-lsp.
|
||||
use crate::Host;
|
||||
use ide_command::command;
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
@@ -14,14 +15,68 @@ use std::process::{Command, Stdio};
|
||||
/// The generators, in order of preference, and their arguments for `container`.
|
||||
const TOOLS: [&str; 2] = ["xcode-build-server", "sourcekit-xcode-bsp"];
|
||||
|
||||
fn tool_args(tool: &str, container: &str) -> Vec<String> {
|
||||
fn tool_args(tool: &str, container: &str, build_root: Option<&Path>) -> Vec<String> {
|
||||
if tool == "sourcekit-xcode-bsp" {
|
||||
// Detects the workspace or project in the working directory itself.
|
||||
return vec!["init".into()];
|
||||
}
|
||||
let flag = if container.ends_with(".xcworkspace") { "-workspace" } else { "-project" };
|
||||
// Without `-scheme` it binds the scheme built last.
|
||||
vec!["config".into(), flag.into(), container.into()]
|
||||
let mut args: Vec<String> = vec!["config".into(), flag.into(), container.into()];
|
||||
if let Some(dir) = build_root {
|
||||
args.extend(["--build_root".into(), dir.to_string_lossy().into_owned()]);
|
||||
}
|
||||
args
|
||||
}
|
||||
|
||||
/// The DerivedData folder Xcode (and a run) builds `container` in, read from the build settings of
|
||||
/// the first scheme in `root`'s projects. Without it xcode-build-server reads the build settings of
|
||||
/// the workspace's first scheme, which may be a package's with none (an `IndexError` on a Tuist
|
||||
/// workspace whose first scheme is a Swift package). `None` leaves it to xcode-build-server.
|
||||
fn build_root(root: &Path, container: &str) -> Option<std::path::PathBuf> {
|
||||
let scheme = ide_run::xcode::schemes(root).into_iter().next()?.name;
|
||||
let flag = if container.ends_with(".xcworkspace") { "-workspace" } else { "-project" };
|
||||
let mut cmd = Command::new("xcodebuild");
|
||||
ide_core::process::prepare(&mut cmd)
|
||||
.args([flag, container, "-scheme", &scheme, "-showBuildSettings", "-json"])
|
||||
.current_dir(root)
|
||||
.stdin(Stdio::null())
|
||||
.stderr(Stdio::null());
|
||||
let out = cmd.output().ok().filter(|o| o.status.success())?;
|
||||
ide_run::xcode_clean::derived_data_of(&String::from_utf8_lossy(&out.stdout))
|
||||
}
|
||||
|
||||
/// The config `tool` writes at the project root.
|
||||
fn config_name(tool: &str) -> &'static str {
|
||||
if tool == "sourcekit-xcode-bsp" { ".bsp" } else { "buildServer.json" }
|
||||
}
|
||||
|
||||
fn git(root: &Path, args: &[&str]) -> Option<std::process::Output> {
|
||||
let mut cmd = Command::new("git");
|
||||
ide_core::process::prepare(&mut cmd).arg("-C").arg(root).args(args).stdin(Stdio::null());
|
||||
cmd.output().ok()
|
||||
}
|
||||
|
||||
/// Adds `name` (a file or folder at `root`) to the repository's `info/exclude`, so a generated
|
||||
/// machine-specific config doesn't show up as a change. Nothing when `root` isn't in a Git
|
||||
/// repository or `name` is already tracked or ignored. Returns whether it added the line.
|
||||
fn exclude_from_git(root: &Path, name: &str) -> std::io::Result<bool> {
|
||||
let ok = |args: &[&str]| git(root, args).filter(|o| o.status.success());
|
||||
let text = |o: std::process::Output| String::from_utf8_lossy(&o.stdout).trim_end_matches('\n').to_owned();
|
||||
let Some(exclude) = ok(&["rev-parse", "--git-path", "info/exclude"]).map(text) else { return Ok(false) };
|
||||
let prefix = ok(&["rev-parse", "--show-prefix"]).map(text).unwrap_or_default();
|
||||
if ok(&["ls-files", "--error-unmatch", "--", name]).is_some() || ok(&["check-ignore", "-q", "--", name]).is_some() {
|
||||
return Ok(false);
|
||||
}
|
||||
let exclude = root.join(exclude);
|
||||
if let Some(dir) = exclude.parent() {
|
||||
std::fs::create_dir_all(dir)?;
|
||||
}
|
||||
let before = std::fs::read_to_string(&exclude).unwrap_or_default();
|
||||
let sep = if before.is_empty() || before.ends_with('\n') { "" } else { "\n" };
|
||||
let mut file = std::fs::OpenOptions::new().create(true).append(true).open(&exclude)?;
|
||||
std::io::Write::write_all(&mut file, format!("{sep}/{prefix}{name}\n").as_bytes())?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// An Xcode project without a BSP config, at the project root.
|
||||
@@ -69,8 +124,8 @@ pub fn xcode_bsp_setup(host: &Host, window: &str) -> IdeResult<Option<XcodeBspSe
|
||||
Ok(Some(XcodeBspSetup { container, tool }))
|
||||
}
|
||||
|
||||
/// Writes the BSP config at the project root with `tool`, then restarts the project's
|
||||
/// sourcekit-lsp so it reads it.
|
||||
/// Writes the BSP config at the project root with `tool`, adds it to `.git/info/exclude`
|
||||
/// ([`exclude_from_git`]), then restarts the project's sourcekit-lsp so it reads it.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn xcode_bsp_generate(host: &Host, window: &str, tool: String, container: String) -> IdeResult<()> {
|
||||
if !TOOLS.contains(&tool.as_str()) {
|
||||
@@ -87,12 +142,17 @@ pub async fn xcode_bsp_generate(host: &Host, window: &str, tool: String, contain
|
||||
.ok_or_else(|| IdeError::unavailable(format!("{tool} is not installed")))?;
|
||||
let mut cmd = Command::new(exe);
|
||||
ide_core::process::prepare(&mut cmd)
|
||||
.args(tool_args(&tool, &container))
|
||||
// An absolute path: with `--build_root` it is written to the config as given.
|
||||
.args(tool_args(&tool, &root.join(&container).to_string_lossy(), build_root(&root, &container).as_deref()))
|
||||
.current_dir(&root)
|
||||
.env("PATH", &search)
|
||||
.stdin(Stdio::null());
|
||||
let out = cmd.output().map_err(|e| IdeError::unavailable(format!("{tool}: {e}")))?;
|
||||
if out.status.success() {
|
||||
// Best effort: a config that shows up in `git status` is a nuisance, not a failure.
|
||||
if let Err(e) = exclude_from_git(&root, config_name(&tool)) {
|
||||
tracing::warn!("could not add {} to .git/info/exclude: {e}", config_name(&tool));
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
let stderr = String::from_utf8_lossy(&out.stderr);
|
||||
@@ -131,9 +191,95 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn passes_the_container_to_xcode_build_server() {
|
||||
assert_eq!(tool_args("xcode-build-server", "A.xcworkspace"), ["config", "-workspace", "A.xcworkspace"]);
|
||||
assert_eq!(tool_args("xcode-build-server", "A.xcodeproj"), ["config", "-project", "A.xcodeproj"]);
|
||||
assert_eq!(tool_args("sourcekit-xcode-bsp", "A.xcodeproj"), ["init"]);
|
||||
assert_eq!(tool_args("xcode-build-server", "A.xcworkspace", None), ["config", "-workspace", "A.xcworkspace"]);
|
||||
assert_eq!(tool_args("xcode-build-server", "A.xcodeproj", None), ["config", "-project", "A.xcodeproj"]);
|
||||
let dd = Path::new("/Users/me/Library/Developer/Xcode/DerivedData/A-abc");
|
||||
assert_eq!(
|
||||
tool_args("xcode-build-server", "A.xcworkspace", Some(dd)),
|
||||
[
|
||||
"config",
|
||||
"-workspace",
|
||||
"A.xcworkspace",
|
||||
"--build_root",
|
||||
"/Users/me/Library/Developer/Xcode/DerivedData/A-abc"
|
||||
]
|
||||
);
|
||||
assert_eq!(tool_args("sourcekit-xcode-bsp", "A.xcodeproj", Some(dd)), ["init"]);
|
||||
}
|
||||
|
||||
fn git_in(dir: &Path, args: &[&str]) {
|
||||
let out = Command::new("git").arg("-C").arg(dir).args(args).output().unwrap();
|
||||
assert!(out.status.success(), "git {args:?}: {}", String::from_utf8_lossy(&out.stderr));
|
||||
}
|
||||
|
||||
fn exclude_file(repo: &Path) -> String {
|
||||
std::fs::read_to_string(repo.join(".git/info/exclude")).unwrap_or_default()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn excludes_the_generated_config_from_git_once() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let repo = tmp.path();
|
||||
git_in(repo, &["init", "-q"]);
|
||||
std::fs::write(repo.join("buildServer.json"), "{}").unwrap();
|
||||
assert!(exclude_from_git(repo, "buildServer.json").unwrap());
|
||||
assert!(exclude_file(repo).ends_with("\n/buildServer.json\n"), "{}", exclude_file(repo));
|
||||
// Now ignored: not added twice.
|
||||
assert!(!exclude_from_git(repo, "buildServer.json").unwrap());
|
||||
assert_eq!(exclude_file(repo).matches("buildServer.json").count(), 1);
|
||||
// sourcekit-xcode-bsp's folder.
|
||||
std::fs::create_dir(repo.join(".bsp")).unwrap();
|
||||
std::fs::write(repo.join(".bsp/x.json"), "{}").unwrap();
|
||||
assert!(exclude_from_git(repo, config_name("sourcekit-xcode-bsp")).unwrap());
|
||||
assert!(exclude_file(repo).ends_with("/buildServer.json\n/.bsp\n"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn leaves_tracked_and_ignored_configs_and_non_repos_alone() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
// Not a Git repository: nothing to do, no `.git` created.
|
||||
let plain = tmp.path().join("plain");
|
||||
std::fs::create_dir(&plain).unwrap();
|
||||
assert!(!exclude_from_git(&plain, "buildServer.json").unwrap());
|
||||
assert!(!plain.join(".git").exists());
|
||||
|
||||
let repo = tmp.path().join("repo");
|
||||
std::fs::create_dir(&repo).unwrap();
|
||||
git_in(&repo, &["init", "-q"]);
|
||||
let before = exclude_file(&repo);
|
||||
// Tracked: the team shares it.
|
||||
std::fs::write(repo.join("buildServer.json"), "{}").unwrap();
|
||||
git_in(&repo, &["add", "buildServer.json"]);
|
||||
assert!(!exclude_from_git(&repo, "buildServer.json").unwrap());
|
||||
// Already in .gitignore.
|
||||
git_in(&repo, &["rm", "-q", "--cached", "buildServer.json"]);
|
||||
std::fs::write(repo.join(".gitignore"), "buildServer.json\n").unwrap();
|
||||
assert!(!exclude_from_git(&repo, "buildServer.json").unwrap());
|
||||
assert_eq!(exclude_file(&repo), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn excludes_the_config_of_a_project_in_a_subfolder_of_the_repository() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let repo = tmp.path();
|
||||
git_in(repo, &["init", "-q"]);
|
||||
let ios = repo.join("apps/ios");
|
||||
std::fs::create_dir_all(&ios).unwrap();
|
||||
assert!(exclude_from_git(&ios, "buildServer.json").unwrap());
|
||||
assert!(exclude_file(repo).ends_with("/apps/ios/buildServer.json\n"));
|
||||
std::fs::write(ios.join("buildServer.json"), "{}").unwrap();
|
||||
// The line matches the file in the subfolder only.
|
||||
git_in(&ios, &["check-ignore", "-q", "buildServer.json"]);
|
||||
assert!(
|
||||
Command::new("git")
|
||||
.arg("-C")
|
||||
.arg(repo)
|
||||
.args(["check-ignore", "-q", "buildServer.json"])
|
||||
.status()
|
||||
.unwrap()
|
||||
.code()
|
||||
== Some(1)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -118,21 +118,50 @@ impl PluginHost {
|
||||
.find(|(p, n, _)| p == plugin && n == tool)
|
||||
.ok_or_else(|| IdeError::not_found("plugin MCP tool is no longer available"))?;
|
||||
let args: serde_json::Value = serde_json::from_str(arguments).map_err(|e| IdeError::invalid(e.to_string()))?;
|
||||
let validator =
|
||||
jsonschema::validator_for(&declared.input_schema).map_err(|e| IdeError::invalid(e.to_string()))?;
|
||||
if !validator.is_valid(&args) {
|
||||
return Err(IdeError::invalid("MCP arguments do not match inputSchema"));
|
||||
}
|
||||
let (tool, arguments) = (tool.to_owned(), arguments.to_owned());
|
||||
let arguments = arguments_for(&declared.input_schema, args)?;
|
||||
let tool = tool.to_owned();
|
||||
self.code_call_cancellable(plugin, invocation, "calling the MCP tool", Some(cancel), move |rt, inv| {
|
||||
rt.mcp_call(&tool, &arguments, inv)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// `args` as the tool's `schema` takes them. Every listed tool takes `projectPath`, which the
|
||||
/// server routes a call by; a schema that refuses it gets the call without it.
|
||||
fn arguments_for(schema: &serde_json::Value, mut args: serde_json::Value) -> IdeResult<String> {
|
||||
let validator = jsonschema::validator_for(schema).map_err(|e| IdeError::invalid(e.to_string()))?;
|
||||
if !validator.is_valid(&args)
|
||||
&& let Some(args) = args.as_object_mut()
|
||||
{
|
||||
args.remove(crate::mcp::PROJECT_PATH);
|
||||
}
|
||||
if !validator.is_valid(&args) {
|
||||
return Err(IdeError::invalid("MCP arguments do not match inputSchema"));
|
||||
}
|
||||
Ok(args.to_string())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_schema_gets_the_project_path_only_when_it_takes_it() {
|
||||
let call = serde_json::json!({ "text": "hi", "projectPath": "/work/inventory" });
|
||||
let strict = serde_json::json!({
|
||||
"type": "object", "properties": { "text": { "type": "string" } }, "additionalProperties": false
|
||||
});
|
||||
assert_eq!(arguments_for(&strict, call.clone()).unwrap(), r#"{"text":"hi"}"#);
|
||||
// Declared through a local `$ref` and required: the plugin keeps it.
|
||||
let declared = serde_json::json!({
|
||||
"$ref": "#/$defs/call",
|
||||
"$defs": { "call": { "type": "object", "required": ["projectPath"], "additionalProperties": false,
|
||||
"properties": { "text": { "type": "string" }, "projectPath": { "type": "string" } } } }
|
||||
});
|
||||
let kept: serde_json::Value = serde_json::from_str(&arguments_for(&declared, call).unwrap()).unwrap();
|
||||
assert_eq!(kept["projectPath"], "/work/inventory");
|
||||
assert!(arguments_for(&strict, serde_json::json!({ "text": 12, "projectPath": "/p" })).is_err());
|
||||
}
|
||||
#[test]
|
||||
fn validates_names_schema_files_versions_and_schema_keywords_at_install() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -760,6 +760,11 @@ impl PluginHost {
|
||||
.filter(|(_, p)| p.dev_root.as_deref() == Some(root))
|
||||
.map(|(id, _)| id.clone())
|
||||
.collect();
|
||||
// Nothing to unload, nothing to announce: `CommandsChanged` makes every window list the
|
||||
// plugins again, and listing restricts an untrusted project again, which looped while idle.
|
||||
if ids.is_empty() {
|
||||
return;
|
||||
}
|
||||
for id in ids {
|
||||
self.unload(&id);
|
||||
}
|
||||
@@ -3003,11 +3008,16 @@ impl PluginHost {
|
||||
{
|
||||
let mut plugins = self.plugins.write();
|
||||
if let Some(existing) = plugins.get(&id) {
|
||||
tracing::warn!(
|
||||
"plugin {id:?} at {} ignored: already loaded from {}",
|
||||
dir.display(),
|
||||
existing.dir().display()
|
||||
);
|
||||
// Every rescan meets the same duplicate again: say it once per directory, not on each scan.
|
||||
static WARNED: std::sync::LazyLock<Mutex<std::collections::HashSet<(String, PathBuf)>>> =
|
||||
std::sync::LazyLock::new(Default::default);
|
||||
if WARNED.lock().insert((id.clone(), dir.to_path_buf())) {
|
||||
tracing::warn!(
|
||||
"plugin {id:?} at {} ignored: already loaded from {}",
|
||||
dir.display(),
|
||||
existing.dir().display()
|
||||
);
|
||||
}
|
||||
return (id, None);
|
||||
}
|
||||
plugins.insert(id.clone(), plugin.clone());
|
||||
|
||||
Loaded 100 of 805 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Заблокувати користувача