дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-01 14:44:34 +02:00
Порівняти коміти
69
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
2b5512d591 | ||
|
|
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 | ||
|
|
04a4d98d68 | ||
|
|
9a984f64a3 | ||
|
|
e35a607556 |
No files matched your search
@@ -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
|
||||
|
||||
@@ -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"
|
||||
}
|
||||
}
|
||||
]
|
||||
|
||||
Створено
@@ -4173,6 +4173,7 @@ dependencies = [
|
||||
"serde_json",
|
||||
"sha1 0.10.7",
|
||||
"specta",
|
||||
"sqlx",
|
||||
"tempfile",
|
||||
"tokio",
|
||||
"toml 0.9.12+spec-1.1.0",
|
||||
|
||||
+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,6 +18,7 @@ ide-tools = { path = "../ide-tools" }
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
specta.workspace = true
|
||||
sqlx.workspace = true
|
||||
tokio.workspace = true
|
||||
toml.workspace = true
|
||||
tracing.workspace = true
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -1409,19 +1409,23 @@ impl AgentManager {
|
||||
out.extend(external::claude_sessions(&dir, &root));
|
||||
}
|
||||
let home = self.shared.paths.home_dir.clone().or_else(home_dir);
|
||||
if let Some(home) = home {
|
||||
if let Some(home) = home.as_deref() {
|
||||
out.extend(external::codex_sessions(&home.join(".codex"), &root));
|
||||
}
|
||||
if let Some(spec) = self.shared.spec("copilot")
|
||||
&& let Some(dir) = native::copilot::config_dir(&spec.env, home.as_deref())
|
||||
{
|
||||
out.extend(external::copilot_sessions(&dir, home.as_deref(), &root));
|
||||
}
|
||||
let known = self.imported_session_ids();
|
||||
out.retain(|s| !known.contains(&s.session_id));
|
||||
out.sort_by(|a, b| b.updated_ms.total_cmp(&a.updated_ms));
|
||||
out.truncate(50);
|
||||
out
|
||||
}
|
||||
|
||||
/// Imports an external session as a task, loading it in the background to show its history (#312).
|
||||
pub fn import_session(&self, provider: &str, session_id: &str) -> IdeResult<AgentTask> {
|
||||
if !matches!(provider, "claude" | "codex") {
|
||||
if !matches!(provider, "claude" | "codex" | "copilot") {
|
||||
return Err(IdeError::invalid(format!("cannot import {provider} sessions")));
|
||||
}
|
||||
let spec = self.shared.spec(provider).ok_or_else(|| IdeError::invalid(format!("unknown agent {provider}")))?;
|
||||
@@ -1488,9 +1492,21 @@ impl AgentManager {
|
||||
pending_native_fork: None,
|
||||
};
|
||||
let handle = Task::restore(file, self.shared.clone());
|
||||
self.tasks.write().insert(task.id.clone(), handle.clone());
|
||||
let epoch = {
|
||||
let mut tasks = self.tasks.write();
|
||||
let epoch = self.shared.shutdown_epoch();
|
||||
tasks.insert(task.id.clone(), handle.clone());
|
||||
epoch
|
||||
};
|
||||
handle.emit_task();
|
||||
handle.persist();
|
||||
// Loading the session replays its history into the task, so it shows before a first message.
|
||||
self.shared.runtime.spawn(async move {
|
||||
match handle.ensure_session(epoch).await {
|
||||
Ok(_) => handle.release_when_idle(),
|
||||
Err(e) => tracing::info!("agent task {}: loading the imported session failed: {e}", handle.id),
|
||||
}
|
||||
});
|
||||
Ok(task)
|
||||
}
|
||||
|
||||
@@ -1498,7 +1514,7 @@ impl AgentManager {
|
||||
/// recording as the agent's own fork, under an id the host chooses. The session must
|
||||
/// belong to this project and have been recorded in `cwd`.
|
||||
pub fn fork_session(&self, provider: &str, session_id: &str, cwd: &Path) -> IdeResult<AgentTask> {
|
||||
if !matches!(provider, "claude" | "codex") {
|
||||
if !matches!(provider, "claude" | "codex" | "copilot") {
|
||||
return Err(IdeError::invalid(format!("cannot fork {provider} sessions")));
|
||||
}
|
||||
if !canonical_uuid(session_id) {
|
||||
@@ -1526,7 +1542,7 @@ impl AgentManager {
|
||||
let config = self.shared.known_config(&spec.id);
|
||||
let now = now_ms();
|
||||
let id = uuid::Uuid::new_v4().simple().to_string();
|
||||
// The host names the fork's session id for claude; codex assigns its own.
|
||||
// The host names the fork's session id for claude; codex and Copilot assign their own.
|
||||
let target = (provider == "claude").then(|| uuid::Uuid::new_v4().to_string());
|
||||
let task = AgentTask {
|
||||
project_root: Some(IpcPath(root)),
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -3241,6 +3241,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 +3313,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();
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -622,6 +622,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> {
|
||||
@@ -1240,6 +1264,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(
|
||||
|
||||
@@ -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).
|
||||
|
||||
@@ -616,6 +616,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 +658,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,
|
||||
|
||||
@@ -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.
|
||||
@@ -1026,6 +1068,28 @@ mod tests {
|
||||
assert!(builtin("nope").is_none());
|
||||
}
|
||||
|
||||
/// 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;
|
||||
|
||||
@@ -0,0 +1,205 @@
|
||||
//! 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::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((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<(u32, u32)>) -> IdeError {
|
||||
let found = match gdb {
|
||||
Some((major, minor)) => format!(
|
||||
"lldb-dap and CodeLLDB are not installed, and GDB {major}.{minor} cannot debug through DAP \
|
||||
(it needs GDB {GDB_MIN_MAJOR} or newer)"
|
||||
),
|
||||
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;
|
||||
#[cfg(unix)]
|
||||
use std::path::Path;
|
||||
|
||||
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 e = choose(cmake_launch(), move |c| (c == "gdb").then(|| gdb.clone())).await.unwrap_err();
|
||||
assert!(e.message.starts_with(NO_NATIVE_DEBUGGER), "{}", e.message);
|
||||
assert!(e.message.contains("GDB 12.1"), "{}", 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");
|
||||
}
|
||||
}
|
||||
@@ -1134,21 +1134,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),
|
||||
};
|
||||
}
|
||||
|
||||
+105
-47
@@ -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,9 +1714,12 @@ impl DbManager {
|
||||
ddl.map(|d| format!("{};\n", d.trim_end().trim_end_matches(';'))).ok_or_else(missing)
|
||||
}
|
||||
DbDriver::Postgres => {
|
||||
// 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 = 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]) => (
|
||||
Some([Some(oid), Some(kind), owner, comment, ..]) => (
|
||||
oid.parse::<u32>().map_err(|e| IdeError::invalid(e.to_string()))?,
|
||||
kind.clone(),
|
||||
owner.clone(),
|
||||
@@ -1686,41 +1734,51 @@ 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 (cols_q, keys_q, grants_q, index_q, trigger_q) = (
|
||||
sql::postgres_ddl_columns(oid),
|
||||
sql::postgres_ddl_constraints(oid),
|
||||
sql::postgres_ddl_grants(oid),
|
||||
sql::postgres_ddl_indexes(oid),
|
||||
sql::postgres_ddl_triggers(oid),
|
||||
);
|
||||
let (col_rows, key_rows, grant_rows, index_rows, trigger_rows) = futures::join!(
|
||||
pool.rows(&cols_q, MAX_META_ROWS),
|
||||
pool.rows(&keys_q, MAX_META_ROWS),
|
||||
pool.rows(&grants_q, MAX_META_ROWS),
|
||||
pool.rows(&index_q, MAX_META_ROWS),
|
||||
pool.rows(&trigger_q, MAX_META_ROWS),
|
||||
);
|
||||
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(),
|
||||
data_type: it.next().flatten()?,
|
||||
not_null: flag(&it.next().flatten()),
|
||||
default: it.next().flatten(),
|
||||
comment: it.next().flatten(),
|
||||
comment: it.next().flatten().filter(|c| !c.is_empty()),
|
||||
})
|
||||
})
|
||||
.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);
|
||||
.collect::<Vec<_>>();
|
||||
let triggers =
|
||||
trigger_rows?.into_iter().filter_map(|r| r.into_iter().next().flatten()).collect::<Vec<_>>();
|
||||
let extras = sql::DdlExtras { comment, owner, grants, triggers };
|
||||
Ok(sql::postgres_table_ddl(schema, name, &columns, &constraints, &indexes, &extras))
|
||||
}
|
||||
|
||||
@@ -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 \
|
||||
@@ -709,6 +709,11 @@ pub fn postgres_relation(schema: &str, name: &str) -> String {
|
||||
}
|
||||
|
||||
/// Rows: `name, type, not null (0/1), default, comment` of relation `oid`.
|
||||
///
|
||||
/// 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) -> String {
|
||||
format!(
|
||||
"SELECT a.attname, format_type(a.atttypid, a.atttypmod), CASE WHEN a.attnotnull THEN 1 ELSE 0 END, \
|
||||
@@ -1416,6 +1421,22 @@ 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);
|
||||
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 = [
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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!({}),
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -140,6 +140,15 @@ 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());
|
||||
config = ide_dap::native::choose(config, move |command| {
|
||||
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());
|
||||
|
||||
@@ -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,
|
||||
@@ -864,6 +869,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 +1105,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 +1120,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);
|
||||
@@ -190,6 +190,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)]
|
||||
@@ -531,6 +535,23 @@ 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(),
|
||||
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>> {
|
||||
@@ -541,10 +562,17 @@ pub async fn vcs_roots(host: &Host, window: &str) -> IdeResult<Vec<VcsRoot>> {
|
||||
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();
|
||||
@@ -553,7 +581,10 @@ pub async fn vcs_roots(host: &Host, window: &str) -> IdeResult<Vec<VcsRoot>> {
|
||||
}
|
||||
Ok(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,6 +596,11 @@ 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(),
|
||||
@@ -572,7 +608,7 @@ pub async fn vcs_roots(host: &Host, window: &str) -> IdeResult<Vec<VcsRoot>> {
|
||||
interactive_rebase,
|
||||
head,
|
||||
head_commit,
|
||||
shallow: r.is_shallow().unwrap_or(false),
|
||||
shallow,
|
||||
lfs: r.uses_lfs(),
|
||||
uninitialized_submodules: r
|
||||
.uninitialized_submodules()
|
||||
@@ -580,8 +616,9 @@ 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())
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -565,6 +565,21 @@ impl Host {
|
||||
.collect();
|
||||
matches!(rest.as_slice(), [first, ..] if first == "worktrees" && rest.len() <= 2)
|
||||
});
|
||||
// `git worktree add` writes the worktree's gitfile before its gitdir's
|
||||
// `HEAD`: a rescan in between finds no repository there yet, so that `HEAD`
|
||||
// rescans too while its worktree is unknown and one a rescan would find.
|
||||
git_dirs |= batch.vcs.iter().any(|p| {
|
||||
let Some(gitdir) = p.parent().filter(|_| p.ends_with("HEAD")) else { return false };
|
||||
if !gitdir.parent().is_some_and(|d| d.ends_with(".git/worktrees")) {
|
||||
return false;
|
||||
}
|
||||
// `gitdir` may be relative to itself (`git worktree add --relative-paths`).
|
||||
let worktree = std::fs::read_to_string(gitdir.join("gitdir"))
|
||||
.and_then(|gitfile| dunce::canonicalize(gitdir.join(gitfile.trim())));
|
||||
worktree.ok().as_deref().and_then(Path::parent).is_some_and(|dir| {
|
||||
!known.iter().any(|r| r == dir) && repository_searched(&root, dir, &settings.effective())
|
||||
})
|
||||
});
|
||||
// A repository folder moved or restored into the project: no `.git` event is
|
||||
// written inside it before the watcher sees the new directory, its creation is
|
||||
// the signal. A `git clone` / `git init` inside the project already arrives
|
||||
@@ -1048,17 +1063,16 @@ impl Host {
|
||||
}
|
||||
}
|
||||
|
||||
/// Why a tool that writes or runs refuses a project the user hasn't trusted.
|
||||
pub(crate) const RESTRICTED_MODE: &str = "Project is in Restricted Mode. Trust the project to enable execution.";
|
||||
|
||||
impl Project {
|
||||
pub fn is_trusted(&self) -> bool {
|
||||
self.trusted.load(Ordering::Acquire)
|
||||
}
|
||||
|
||||
pub fn require_trust(&self) -> IdeResult<()> {
|
||||
if self.is_trusted() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(IdeError::unavailable("Project is in Restricted Mode. Trust the project to enable execution."))
|
||||
}
|
||||
if self.is_trusted() { Ok(()) } else { Err(IdeError::unavailable(RESTRICTED_MODE)) }
|
||||
}
|
||||
|
||||
/// LightEdit: follow external changes to the files of `dir` (its own entries only).
|
||||
@@ -1186,18 +1200,34 @@ fn detect_repositories(
|
||||
build_cache: &Path,
|
||||
trusted: bool,
|
||||
) -> IdeResult<Repos> {
|
||||
let mut roots = vec![root.to_path_buf()];
|
||||
roots.extend(content_roots(settings, root, build_cache, trusted));
|
||||
Repos::discover_roots(&roots, &repository_scan_skips(settings))
|
||||
}
|
||||
|
||||
/// Folders the search for nested repositories leaves out, besides hidden and dependency ones.
|
||||
fn repository_scan_skips(settings: &ide_core::settings::Settings) -> impl Fn(&Path) -> bool {
|
||||
let ignored = settings.ignored_names();
|
||||
let skip = |p: &Path| {
|
||||
move |p: &Path| {
|
||||
p.file_name().is_some_and(|n| {
|
||||
let name = n.to_string_lossy();
|
||||
ignored.is_ignored_name(&name)
|
||||
|| (ide_workspace::unity::GENERATED_DIRS.contains(&name.as_ref())
|
||||
&& p.parent().is_some_and(ide_workspace::unity::is_project))
|
||||
})
|
||||
};
|
||||
let mut roots = vec![root.to_path_buf()];
|
||||
roots.extend(content_roots(settings, root, build_cache, trusted));
|
||||
Repos::discover_roots(&roots, &skip)
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a scan of the project at `root` would look for a repository at `dir` and keep it.
|
||||
fn repository_searched(root: &Path, dir: &Path, settings: &ide_core::settings::Settings) -> bool {
|
||||
settings.vcs.git.enabled
|
||||
&& !settings
|
||||
.vcs
|
||||
.mappings
|
||||
.excluded
|
||||
.iter()
|
||||
.any(|p| dunce::canonicalize(VcsMappings::resolve(root, p)).is_ok_and(|e| e == dir))
|
||||
&& Repos::searched(root, dir, &repository_scan_skips(settings))
|
||||
}
|
||||
|
||||
impl Project {
|
||||
|
||||
@@ -500,6 +500,7 @@ mod tests {
|
||||
subject: "rm -rf".into(),
|
||||
project: "/srv/app".into(),
|
||||
detail: None,
|
||||
background: false,
|
||||
};
|
||||
let update = ide_core::updates::UpdateInfo {
|
||||
version: "9.9.9".into(),
|
||||
|
||||
@@ -314,6 +314,7 @@ impl crate::Host {
|
||||
.map(|(window, _)| window.clone())
|
||||
.collect();
|
||||
for window in windows {
|
||||
self.mcp_requests.withdraw(&window);
|
||||
let requests = self.project_requests.write().remove(&window).unwrap_or_default();
|
||||
for request in requests {
|
||||
self.cancel_request(request);
|
||||
|
||||
@@ -107,7 +107,7 @@ async fn compose_target_is_the_python_interpreter() {
|
||||
eprintln!("run target interpreter: {after:?}");
|
||||
assert!(after.iter().all(|m| !m.contains("could not be resolved")), "{after:?}");
|
||||
|
||||
let info = ops::sdk::sdk_container_python(&host, WINDOW).unwrap().expect("a run target interpreter");
|
||||
let info = ops::sdk::sdk_container_python(&host, WINDOW).await.unwrap().expect("a run target interpreter");
|
||||
eprintln!("snapshot: version {:?}, image {:?}, folders {:?}", info.version, info.image, info.folders);
|
||||
assert_eq!(info.name, "Compose web");
|
||||
assert!(info.version.as_deref().is_some_and(|v| v.starts_with("3.12.")), "{info:?}");
|
||||
|
||||
@@ -742,38 +742,43 @@ async fn typescript_import_style() {
|
||||
..TYPESCRIPT
|
||||
};
|
||||
let smoke = Smoke::start("typescript", &checks).await;
|
||||
let set = |key: &str, value: &str| {
|
||||
let lsp = smoke.host.project(WINDOW).unwrap().lsp.clone();
|
||||
// Returns once vtsls has the change. A completion that runs before it fills tsserver's
|
||||
// module specifier cache for that file under the old preferences, and that cache is keyed
|
||||
// without `autoImportSpecifierExcludeRegexes`, so the file keeps the old answer.
|
||||
let set = async |key: &str, value: &str| {
|
||||
let scope = ide_workspace::settings::SettingsScope::Project;
|
||||
let key = format!("editor.codeStyle.languages.typescript.{key}");
|
||||
ops::project::settings_set(&smoke.host, WINDOW, scope, key, value.into()).unwrap();
|
||||
lsp.reconfigure().await;
|
||||
};
|
||||
let alpha = typed("src/app/main.ts", "export const ready", "alphaH");
|
||||
let beta = typed("src/app/main.ts", "export const ready", "betaW");
|
||||
let import = |typed, label, result| AutoImport { typed, label, result };
|
||||
|
||||
set("importModuleSpecifier", r#""relative""#);
|
||||
set("importModuleSpecifier", r#""relative""#).await;
|
||||
smoke.auto_import(import(alpha, "alphaHelper", r#"from "../lib/alpha""#)).await;
|
||||
set("importModuleSpecifier", r#""non-relative""#);
|
||||
set("importModuleSpecifier", r#""non-relative""#).await;
|
||||
smoke.auto_import(import(alpha, "alphaHelper", r#"from "@/lib/alpha""#)).await;
|
||||
|
||||
set("importModuleSpecifier", r#""relative""#);
|
||||
set("importModuleSpecifierEnding", r#""index""#);
|
||||
set("importModuleSpecifier", r#""relative""#).await;
|
||||
set("importModuleSpecifierEnding", r#""index""#).await;
|
||||
smoke.auto_import(import(beta, "betaWidget", r#"from "./components/index""#)).await;
|
||||
set("importModuleSpecifierEnding", r#""minimal""#);
|
||||
set("importModuleSpecifierEnding", r#""minimal""#).await;
|
||||
smoke.auto_import(import(beta, "betaWidget", r#"from "./components""#)).await;
|
||||
|
||||
// tsserver keeps the auto-import candidates of the file it last completed in until the
|
||||
// program changes; other files see an exclusion at once.
|
||||
set("autoImportFileExcludePatterns", r#"["**/index.ts"]"#);
|
||||
set("autoImportFileExcludePatterns", r#"["**/index.ts"]"#).await;
|
||||
smoke.not_offered(typed("src/app/other.ts", "export const other", "betaW"), "betaWidget", "betaWord").await;
|
||||
set("autoImportSpecifierExcludeRegexes", r#"["lib/alpha$"]"#);
|
||||
set("autoImportSpecifierExcludeRegexes", r#"["lib/alpha$"]"#).await;
|
||||
smoke.not_offered(typed("src/app/third.ts", "export const third", "alphaH"), "alphaHelper", "alphaHint").await;
|
||||
|
||||
// Emptied lists reach the server too: the symbols are offered again.
|
||||
set("autoImportFileExcludePatterns", "[]");
|
||||
set("autoImportFileExcludePatterns", "[]").await;
|
||||
let beta = typed("src/app/fourth.ts", "export const fourth", "betaW");
|
||||
smoke.auto_import(import(beta, "betaWidget", r#"from "./components""#)).await;
|
||||
set("autoImportSpecifierExcludeRegexes", "[]");
|
||||
set("autoImportSpecifierExcludeRegexes", "[]").await;
|
||||
let alpha = typed("src/app/fifth.ts", "export const fifth", "alphaH");
|
||||
smoke.auto_import(import(alpha, "alphaHelper", r#"from "../lib/alpha""#)).await;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
mod common;
|
||||
|
||||
use ide_core::{CancellationToken, ChangeSet, Diagnostic, IdeEvent, Pos, Range, Severity, TextChange};
|
||||
use ide_core::{
|
||||
CancellationToken, ChangeSet, Diagnostic, IdeEvent, Pos, Range, Severity, TextChange, event::McpUiRequest,
|
||||
};
|
||||
use ide_host::mcp::{BackgroundProjects, FileProblems, FocusedEditor, Registry};
|
||||
use ide_host::{Host, HostConfig};
|
||||
use ide_mcp::ToolRegistry;
|
||||
@@ -12,7 +14,8 @@ struct Harness {
|
||||
host: Arc<Host>,
|
||||
root: PathBuf,
|
||||
tmp: tempfile::TempDir,
|
||||
events: Arc<std::sync::Mutex<Vec<IdeEvent>>>,
|
||||
/// Every event, with the window whose sink it was emitted on.
|
||||
events: Arc<std::sync::Mutex<Vec<(String, IdeEvent)>>>,
|
||||
}
|
||||
impl Harness {
|
||||
fn new() -> Self {
|
||||
@@ -27,9 +30,9 @@ impl Harness {
|
||||
let events = Arc::new(std::sync::Mutex::new(Vec::new()));
|
||||
let sink = events.clone();
|
||||
let host = Arc::new(Host::new(HostConfig {
|
||||
sink_for: Box::new(move |_| {
|
||||
let events = sink.clone();
|
||||
Arc::new(move |e| events.lock().unwrap().push(e))
|
||||
sink_for: Box::new(move |window| {
|
||||
let (window, events) = (window.to_owned(), sink.clone());
|
||||
Arc::new(move |e| events.lock().unwrap().push((window.clone(), e)))
|
||||
}),
|
||||
local_data_dir: tmp.path().join("local"),
|
||||
..common::host_config(tmp.path())
|
||||
@@ -55,7 +58,7 @@ impl Harness {
|
||||
async fn request(&self) -> u32 {
|
||||
tokio::time::timeout(std::time::Duration::from_secs(10), async {
|
||||
loop {
|
||||
if let Some(id) = self.events.lock().unwrap().iter().rev().find_map(|e| match e {
|
||||
if let Some(id) = self.events.lock().unwrap().iter().rev().find_map(|(_, e)| match e {
|
||||
IdeEvent::McpRequest { id, .. } => Some(*id),
|
||||
_ => None,
|
||||
}) {
|
||||
@@ -67,6 +70,54 @@ impl Harness {
|
||||
.await
|
||||
.unwrap()
|
||||
}
|
||||
/// The requests `window` shows: asked there and not closed since.
|
||||
fn shown(&self, window: &str) -> Vec<(u32, McpUiRequest)> {
|
||||
let mut shown = Vec::new();
|
||||
for (_, event) in self.events.lock().unwrap().iter().filter(|(w, _)| w == window) {
|
||||
match event {
|
||||
IdeEvent::McpRequest { id, request } => shown.push((*id, request.clone())),
|
||||
IdeEvent::McpRequestClosed { id } => shown.retain(|(open, _)| open != id),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
shown
|
||||
}
|
||||
/// Waits until `window` shows `count` requests, and returns them.
|
||||
async fn shown_in(&self, window: &str, count: usize) -> Vec<(u32, McpUiRequest)> {
|
||||
tokio::time::timeout(std::time::Duration::from_secs(10), async {
|
||||
loop {
|
||||
let shown = self.shown(window);
|
||||
if shown.len() >= count {
|
||||
return shown;
|
||||
}
|
||||
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.unwrap_or_else(|_| panic!("{window} shows no {count} requests"))
|
||||
}
|
||||
/// The request `window` shows, once it shows one.
|
||||
async fn request_in(&self, window: &str) -> (u32, McpUiRequest) {
|
||||
self.shown_in(window, 1).await.pop().unwrap()
|
||||
}
|
||||
/// Whether `window` was told that request `id` closed.
|
||||
fn closed_in(&self, window: &str, id: u32) -> bool {
|
||||
let events = self.events.lock().unwrap();
|
||||
events
|
||||
.iter()
|
||||
.any(|(w, e)| w == window && matches!(e, IdeEvent::McpRequestClosed { id: closed } if *closed == id))
|
||||
}
|
||||
/// Reports `window` focused, as its frontend does when the user brings it to the front.
|
||||
fn focus(&self, window: &str) {
|
||||
self.host.mcp_reports.set_focused_editor(window, None, true);
|
||||
}
|
||||
/// Opens the window `second` on the folder `second` next to the open project.
|
||||
fn open_second(&self) -> PathBuf {
|
||||
let second = self.root.parent().unwrap().join("second");
|
||||
std::fs::create_dir_all(&second).unwrap();
|
||||
self.host.open_project("second", &second).unwrap();
|
||||
second
|
||||
}
|
||||
async fn call(&self, name: &str, args: Value) -> String {
|
||||
let (host, root, name) = (self.host.clone(), self.root.clone(), name.to_owned());
|
||||
tokio::task::spawn_blocking(move || {
|
||||
@@ -252,6 +303,10 @@ async fn restricted_projects_have_only_read_tools_and_remote_projects_explain_th
|
||||
assert!(!h.host.project("main").unwrap().is_trusted());
|
||||
let registry = Registry::new(h.host.clone());
|
||||
assert!(registry.tools(&h.root).unwrap().iter().all(|t| t.read_only && !t.destructive));
|
||||
// A tool that writes, called all the same, says why it can't run.
|
||||
let refused = h.error("create_new_file", json!({"pathInProject":"x.txt","text":"no"})).await;
|
||||
assert_eq!(refused, "Project is in Restricted Mode. Trust the project to enable execution.");
|
||||
assert!(!h.root.join("x.txt").exists());
|
||||
assert!(!h.host.global_settings.effective().mcp_server.enabled);
|
||||
h.host.mcp_reports.set_remote("remote", PathBuf::from("/remote/project"));
|
||||
assert_eq!(
|
||||
@@ -391,7 +446,11 @@ async fn mutations_preserve_unsaved_text_and_reject_metadata_and_escapes() {
|
||||
assert!(p.documents.is_dirty(doc.id).unwrap());
|
||||
assert_eq!(std::fs::read_to_string(&path).unwrap(), "old text\nneedle needle\n");
|
||||
assert!(
|
||||
h.events.lock().unwrap().iter().any(|e| matches!(e, IdeEvent::DocPatched { doc: id, .. } if *id == doc.id))
|
||||
h.events
|
||||
.lock()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.any(|(_, e)| matches!(e, IdeEvent::DocPatched { doc: id, .. } if *id == doc.id))
|
||||
);
|
||||
let edit_id = h
|
||||
.events
|
||||
@@ -399,7 +458,7 @@ async fn mutations_preserve_unsaved_text_and_reject_metadata_and_escapes() {
|
||||
.unwrap()
|
||||
.iter()
|
||||
.rev()
|
||||
.find_map(|event| match event {
|
||||
.find_map(|(_, event)| match event {
|
||||
// Undoable like a refactoring, but marked as the agent's, so it isn't announced as one.
|
||||
IdeEvent::WorkspaceEditApplied { id, by_agent, .. } => {
|
||||
assert!(*by_agent, "an MCP edit is the agent's");
|
||||
@@ -438,14 +497,16 @@ async fn execution_requires_a_window_and_denial_never_runs_a_build() {
|
||||
h.host.mcp_requests.set_ready("main", true);
|
||||
let denied = h.error("build_project", json!({}));
|
||||
let answer = async {
|
||||
let id = h.request().await;
|
||||
let (id, request) = h.request_in("main").await;
|
||||
// A window's own project is not a background one.
|
||||
assert!(matches!(request, McpUiRequest::Confirm { background: false, .. }), "{request:?}");
|
||||
assert!(h.host.mcp_requests.answer("other", id, true, None).is_err());
|
||||
h.host.mcp_requests.answer("main", id, false, None).unwrap();
|
||||
};
|
||||
let (error, ()) = tokio::join!(denied, answer);
|
||||
assert!(error.contains("denied by the user"), "{error}");
|
||||
assert!(h.host.processes.list().is_empty());
|
||||
assert!(h.events.lock().unwrap().iter().any(|e| matches!(e, IdeEvent::McpRequestClosed { .. })));
|
||||
assert!(h.events.lock().unwrap().iter().any(|(_, e)| matches!(e, IdeEvent::McpRequestClosed { .. })));
|
||||
h.events.lock().unwrap().clear();
|
||||
let closed = h.error("build_project", json!({}));
|
||||
let close = async {
|
||||
@@ -774,7 +835,7 @@ fn config_run_window(h: &Harness) -> Arc<std::sync::Mutex<Vec<ide_run::RunConfig
|
||||
tokio::spawn(async move {
|
||||
let mut handled = std::collections::HashSet::new();
|
||||
loop {
|
||||
let request = events.lock().unwrap().iter().find_map(|e| match e {
|
||||
let request = events.lock().unwrap().iter().find_map(|(_, e)| match e {
|
||||
IdeEvent::McpRequest { id, request: ide_core::event::McpUiRequest::RunConfiguration { config } }
|
||||
if !handled.contains(id) =>
|
||||
{
|
||||
@@ -847,11 +908,9 @@ async fn execute_reports_output_exit_code_and_requires_confirmation() {
|
||||
assert_eq!(tabs[0].name, "MCP test");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_project_without_a_window_runs_a_configuration_on_its_own() {
|
||||
let h = Harness::new();
|
||||
h.trust().await;
|
||||
let config = ide_run::RunConfig {
|
||||
/// A shell configuration named `MCP test` that prints `windowless` and exits with 3.
|
||||
fn windowless_config() -> ide_run::RunConfig {
|
||||
ide_run::RunConfig {
|
||||
id: "test".into(),
|
||||
name: "MCP test".into(),
|
||||
kind: "shell".into(),
|
||||
@@ -864,8 +923,14 @@ async fn a_project_without_a_window_runs_a_configuration_on_its_own() {
|
||||
debug_adapter: None,
|
||||
allow_parallel: false,
|
||||
extras: Default::default(),
|
||||
};
|
||||
ide_run::save_user_configs(&h.root, &[config]).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_project_without_a_window_runs_a_configuration_on_its_own() {
|
||||
let h = Harness::new();
|
||||
h.trust().await;
|
||||
ide_run::save_user_configs(&h.root, &[windowless_config()]).unwrap();
|
||||
h.host
|
||||
.global_settings
|
||||
.set(ide_workspace::SettingsScope::Global, "mcpServer.runWithoutConfirmation", json!(true))
|
||||
@@ -873,7 +938,7 @@ async fn a_project_without_a_window_runs_a_configuration_on_its_own() {
|
||||
let result = h.json("execute_run_configuration", json!({"configurationName":"MCP test","timeout":10000})).await;
|
||||
assert_eq!(result["exitCode"], 3, "{result}");
|
||||
assert!(result["output"].as_str().unwrap().contains("windowless"));
|
||||
assert!(!h.events.lock().unwrap().iter().any(|e| matches!(e, IdeEvent::McpRequest { .. })), "nothing asked");
|
||||
assert!(!h.events.lock().unwrap().iter().any(|(_, e)| matches!(e, IdeEvent::McpRequest { .. })), "nothing asked");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
@@ -1020,7 +1085,7 @@ async fn brave_mode_runs_tools_without_asking_only_from_the_global_settings() {
|
||||
.expect("ran without waiting for an answer")
|
||||
.unwrap();
|
||||
assert!(!format!("{result:?}").contains("denied"), "{result:?}");
|
||||
assert!(!h.events.lock().unwrap().iter().any(|e| matches!(e, IdeEvent::McpRequest { .. })), "nothing asked");
|
||||
assert!(!h.events.lock().unwrap().iter().any(|(_, e)| matches!(e, IdeEvent::McpRequest { .. })), "nothing asked");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
@@ -1052,7 +1117,7 @@ fn run_tool_window(h: &Harness) -> Arc<std::sync::Mutex<Vec<ide_run::RunConfig>>
|
||||
tokio::spawn(async move {
|
||||
let mut handled = std::collections::HashSet::new();
|
||||
loop {
|
||||
let request = events.lock().unwrap().iter().find_map(|e| match e {
|
||||
let request = events.lock().unwrap().iter().find_map(|(_, e)| match e {
|
||||
IdeEvent::McpRequest {
|
||||
id,
|
||||
request: ide_core::event::McpUiRequest::AgentRun { name, command, cwd, env },
|
||||
@@ -1546,22 +1611,91 @@ async fn a_folder_without_a_window_is_opened_by_its_first_tool_call() {
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn with_background_projects_off_a_folder_outside_the_open_projects_is_refused() {
|
||||
async fn with_background_projects_off_a_folder_outside_the_open_projects_lists_tools_and_refuses_calls() {
|
||||
let h = Harness::new();
|
||||
let inventory = h.root.parent().unwrap().join("inventory");
|
||||
std::fs::create_dir_all(&inventory).unwrap();
|
||||
let (_server, discovery) = h.server();
|
||||
let list = rpc(1, "tools/list", json!({}));
|
||||
let read = rpc(2, "tools/call", json!({"name":"read_file","arguments":{"file_path":"a.txt"}}));
|
||||
for reply in bridged(&discovery, &inventory, &[list, read]).await {
|
||||
assert_eq!(reply["error"]["code"], -32001, "{reply}");
|
||||
let message = reply["error"]["message"].as_str().unwrap();
|
||||
assert!(message.contains("isn't served in the background"), "{message}");
|
||||
}
|
||||
let replies = bridged(&discovery, &inventory, &[list, read]).await;
|
||||
let tools = replies[0]["result"]["tools"].as_array().unwrap();
|
||||
assert!(tools.iter().any(|t| t["name"] == "create_new_file" && t["annotations"]["readOnlyHint"] == false));
|
||||
assert_eq!(replies[1]["error"]["code"], -32001, "{}", replies[1]);
|
||||
let message = replies[1]["error"]["message"].as_str().unwrap();
|
||||
assert!(message.contains("isn't served in the background"), "{message}");
|
||||
assert!(h.background().is_empty());
|
||||
assert_eq!(h.host.projects().len(), 1);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_connection_in_a_folder_no_project_serves_lists_the_tools_and_each_call_names_its_project() {
|
||||
let h = Harness::new();
|
||||
// A folder that only holds repositories: one trusted, one not.
|
||||
let work = h.root.parent().unwrap().join("work");
|
||||
let (inventory, ledger) = (work.join("inventory"), work.join("ledger"));
|
||||
for project in [&inventory, &ledger] {
|
||||
std::fs::create_dir_all(project.join("src")).unwrap();
|
||||
}
|
||||
std::fs::write(inventory.join("src/stock.txt"), "forty crates\n").unwrap();
|
||||
h.set("enabled", json!(true));
|
||||
h.set("backgroundProjects", json!("listed"));
|
||||
h.set("backgroundProjectPaths", json!([inventory, ledger]));
|
||||
h.host.set_project_trust(&inventory, true, false).await.unwrap();
|
||||
let (_server, discovery) = h.server();
|
||||
|
||||
let requests =
|
||||
[rpc(1, "initialize", json!({})), rpc(2, "tools/list", json!({})), rpc(3, "openidea/servesFolder", json!({}))];
|
||||
let replies = bridged(&discovery, &work, &requests).await;
|
||||
let instructions = replies[0]["result"]["instructions"].as_str().unwrap();
|
||||
assert!(instructions.contains("no project of its own: pass `projectPath`"), "{instructions}");
|
||||
let tools = replies[1]["result"]["tools"].as_array().unwrap();
|
||||
assert!(tools.iter().any(|t| t["name"] == "create_new_file" && t["annotations"]["readOnlyHint"] == false));
|
||||
assert_eq!(replies[2]["result"], json!({ "root": null }), "{}", replies[2]);
|
||||
assert!(h.background().is_empty(), "initialize, tools/list and servesFolder open nothing");
|
||||
|
||||
// A tool that writes is refused for the untrusted project before it loads; a call that
|
||||
// names no project is refused too.
|
||||
let create = rpc(
|
||||
4,
|
||||
"tools/call",
|
||||
json!({"name":"create_new_file","arguments":{
|
||||
"projectPath":ledger,"pathInProject":"notes.txt","text":"no"}}),
|
||||
);
|
||||
let unnamed = rpc(5, "tools/call", json!({"name":"read_file","arguments":{"file_path":"src/stock.txt"}}));
|
||||
let replies = bridged(&discovery, &work, &[create, unnamed]).await;
|
||||
assert_eq!(replies[0]["result"]["isError"], true, "{}", replies[0]);
|
||||
let refused = replies[0]["result"]["content"][0]["text"].as_str().unwrap();
|
||||
assert!(refused.contains("Restricted Mode"), "{refused}");
|
||||
assert!(!ledger.join("notes.txt").exists());
|
||||
assert_eq!(replies[1]["error"]["code"], -32001, "{}", replies[1]);
|
||||
assert!(h.background().is_empty(), "refusals open nothing");
|
||||
|
||||
// Inside a served project, servesFolder names it, and loads nothing either.
|
||||
let serves = [rpc(7, "openidea/servesFolder", json!({}))];
|
||||
let replies = bridged(&discovery, &inventory.join("src"), &serves).await;
|
||||
assert_eq!(replies[0]["result"], json!({ "root": inventory }), "{}", replies[0]);
|
||||
assert!(h.background().is_empty());
|
||||
|
||||
let read = rpc(
|
||||
6,
|
||||
"tools/call",
|
||||
json!({"name":"read_file","arguments":{
|
||||
"projectPath":inventory,"file_path":"src/stock.txt"}}),
|
||||
);
|
||||
let replies = bridged(&discovery, &work, &[read]).await;
|
||||
assert_eq!(replies[0]["result"]["content"][0]["text"], "L1: forty crates\nL2: ", "{replies:?}");
|
||||
assert_eq!(h.background(), std::slice::from_ref(&inventory));
|
||||
|
||||
// A remote window's root is that host's to serve.
|
||||
let remote = work.join("remote");
|
||||
std::fs::create_dir_all(&remote).unwrap();
|
||||
h.host.mcp_reports.set_remote("remote", remote.clone());
|
||||
let replies = bridged(&discovery, &remote, &serves).await;
|
||||
assert_eq!(replies[0]["result"], json!({ "root": null }), "{}", replies[0]);
|
||||
h.host.close_project_detached("remote");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn the_tools_of_a_background_project_are_the_same_before_and_after_it_opens() {
|
||||
let h = Harness::new();
|
||||
@@ -1720,31 +1854,215 @@ async fn tools_fed_by_a_window_say_that_a_background_project_has_none() {
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn tools_that_ask_the_user_fail_closed_in_a_background_project() {
|
||||
async fn tools_that_need_a_window_refuse_in_a_background_project_before_asking() {
|
||||
let h = Harness::new();
|
||||
h.trust().await;
|
||||
h.host.mcp_requests.set_ready("main", true);
|
||||
let inventory = h.serve_inventory();
|
||||
h.host.trust.decide(&inventory, true, false).unwrap();
|
||||
for (tool, args) in [
|
||||
("build_project", json!({})),
|
||||
("run_command", json!({"name":"check","command":"true"})),
|
||||
("open_file_in_editor", json!({"filePath":"src/stock.txt"})),
|
||||
] {
|
||||
let error = h.call_at(&inventory, tool, args).await.unwrap_err();
|
||||
assert!(error.contains("no project window"), "{tool}: {error}");
|
||||
let root = inventory.display();
|
||||
// Running without confirmation does not give them a window either.
|
||||
for brave in [false, true] {
|
||||
h.set("runWithoutConfirmation", json!(brave));
|
||||
for (tool, args) in [
|
||||
("run_command", json!({"name":"check","command":"true"})),
|
||||
("open_file_in_editor", json!({"filePath":"src/stock.txt"})),
|
||||
("xdebug_start_debugger_session", json!({"filePath":"src/stock.txt","line":1})),
|
||||
("xdebug_set_breakpoint", json!({"filePath":"src/stock.txt","line":1})),
|
||||
("xdebug_remove_breakpoint", json!({})),
|
||||
("xdebug_list_breakpoints", json!({})),
|
||||
] {
|
||||
let error = h.call_at(&inventory, tool, args).await.unwrap_err();
|
||||
assert_eq!(
|
||||
error,
|
||||
format!("{tool} needs the project open in a window: {root} is served in the background.")
|
||||
);
|
||||
}
|
||||
}
|
||||
assert!(!h.events.lock().unwrap().iter().any(|(_, e)| matches!(e, IdeEvent::McpRequest { .. })), "nothing asked");
|
||||
assert!(h.host.processes.list().is_empty());
|
||||
// Running without confirmation does not give `run_command` or the editor a window.
|
||||
h.set("runWithoutConfirmation", json!(true));
|
||||
for (tool, args) in [
|
||||
("run_command", json!({"name":"check","command":"true"})),
|
||||
("open_file_in_editor", json!({"filePath":"src/stock.txt"})),
|
||||
] {
|
||||
let error = h.call_at(&inventory, tool, args).await.unwrap_err();
|
||||
assert!(error.contains("no project window"), "{tool}: {error}");
|
||||
}
|
||||
assert_eq!(h.background(), [inventory]);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_background_project_asks_in_the_most_recently_focused_project_window() {
|
||||
let h = Harness::new();
|
||||
h.trust().await;
|
||||
let second = h.open_second();
|
||||
h.host.set_project_trust(&second, true, false).await.unwrap();
|
||||
let inventory = h.serve_inventory();
|
||||
h.host.trust.decide(&inventory, true, false).unwrap();
|
||||
let error = h.call_at(&inventory, "build_project", json!({})).await.unwrap_err();
|
||||
assert!(error.contains("no project window is available"), "{error}");
|
||||
for window in ["main", "second"] {
|
||||
h.host.mcp_requests.set_ready(window, true);
|
||||
}
|
||||
h.focus("second");
|
||||
h.focus("main");
|
||||
let denied = h.call_at(&inventory, "build_project", json!({}));
|
||||
let deny = async {
|
||||
let (id, request) = h.request_in("main").await;
|
||||
let McpUiRequest::Confirm { background, project, .. } = request else { panic!("{request:?}") };
|
||||
assert!(background);
|
||||
assert_eq!(project, ide_core::ipc_path::to_ipc(&inventory));
|
||||
assert!(h.shown("second").is_empty());
|
||||
assert!(h.host.mcp_requests.answer("second", id, true, None).is_err());
|
||||
h.host.mcp_requests.answer("main", id, false, None).unwrap();
|
||||
};
|
||||
let (error, ()) = tokio::join!(denied, deny);
|
||||
assert!(error.unwrap_err().contains("denied by the user"));
|
||||
assert!(h.host.processes.list().is_empty());
|
||||
|
||||
// Allowed there, a configuration runs on its own, as without a window under brave mode.
|
||||
ide_run::save_user_configs(&inventory, &[windowless_config()]).unwrap();
|
||||
let run =
|
||||
h.call_at(&inventory, "execute_run_configuration", json!({"configurationName":"MCP test","timeout":10000}));
|
||||
let allow = async {
|
||||
let (id, request) = h.request_in("main").await;
|
||||
assert!(matches!(request, McpUiRequest::Confirm { background: true, .. }), "{request:?}");
|
||||
h.host.mcp_requests.answer("main", id, true, None).unwrap();
|
||||
};
|
||||
let (result, ()) = tokio::join!(run, allow);
|
||||
let result: Value = serde_json::from_str(&result.unwrap()).unwrap();
|
||||
assert_eq!(result["exitCode"], 3, "{result}");
|
||||
assert!(result["output"].as_str().unwrap().contains("windowless"));
|
||||
|
||||
std::fs::write(inventory.join("api.http"), "### Health\nGET http://127.0.0.1:9/health\n").unwrap();
|
||||
let denied = h.call_at(&inventory, "http_run_request", json!({"path":"api.http","index":0}));
|
||||
let deny = async {
|
||||
let (id, request) = h.request_in("main").await;
|
||||
assert!(matches!(request, McpUiRequest::Confirm { background: true, .. }), "{request:?}");
|
||||
h.host.mcp_requests.answer("main", id, false, None).unwrap();
|
||||
};
|
||||
let (error, ()) = tokio::join!(denied, deny);
|
||||
assert!(error.unwrap_err().contains("denied by the user"));
|
||||
assert!(h.shown("second").is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn requests_for_two_background_projects_queue_in_one_window() {
|
||||
let h = Harness::new();
|
||||
h.trust().await;
|
||||
h.host.mcp_requests.set_ready("main", true);
|
||||
let inventory = h.serve_inventory();
|
||||
let ledger = h.root.parent().unwrap().join("ledger");
|
||||
std::fs::create_dir_all(&ledger).unwrap();
|
||||
h.set("backgroundProjectPaths", json!([inventory, ledger]));
|
||||
for root in [&inventory, &ledger] {
|
||||
h.host.trust.decide(root, true, false).unwrap();
|
||||
}
|
||||
let first = h.call_at(&inventory, "build_project", json!({}));
|
||||
let second = h.call_at(&ledger, "build_project", json!({}));
|
||||
let deny = async {
|
||||
let shown = h.shown_in("main", 2).await;
|
||||
let mut projects: Vec<_> = shown
|
||||
.iter()
|
||||
.map(|(_, request)| match request {
|
||||
McpUiRequest::Confirm { project, background: true, .. } => PathBuf::from(project),
|
||||
other => panic!("{other:?}"),
|
||||
})
|
||||
.collect();
|
||||
projects.sort();
|
||||
assert_eq!(projects, [inventory.clone(), ledger.clone()]);
|
||||
for (id, _) in shown {
|
||||
h.host.mcp_requests.answer("main", id, false, None).unwrap();
|
||||
}
|
||||
};
|
||||
let (first, second, ()) = tokio::join!(first, second, deny);
|
||||
for error in [first.unwrap_err(), second.unwrap_err()] {
|
||||
assert!(error.contains("denied by the user"), "{error}");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_request_moves_when_its_window_closes_and_fails_when_none_is_left() {
|
||||
let h = Harness::new();
|
||||
h.trust().await;
|
||||
let second = h.open_second();
|
||||
h.host.set_project_trust(&second, true, false).await.unwrap();
|
||||
let inventory = h.serve_inventory();
|
||||
h.host.trust.decide(&inventory, true, false).unwrap();
|
||||
for window in ["second", "main"] {
|
||||
h.host.mcp_requests.set_ready(window, true);
|
||||
h.focus(window);
|
||||
}
|
||||
let denied = h.call_at(&inventory, "build_project", json!({}));
|
||||
let moves = async {
|
||||
let (id, _) = h.request_in("main").await;
|
||||
h.host.close_project_detached("main");
|
||||
let (moved, _) = h.request_in("second").await;
|
||||
assert_eq!(moved, id);
|
||||
assert!(h.closed_in("main", id));
|
||||
h.host.mcp_requests.answer("second", id, false, None).unwrap();
|
||||
};
|
||||
let (error, ()) = tokio::join!(denied, moves);
|
||||
assert!(error.unwrap_err().contains("denied by the user"));
|
||||
|
||||
let closed = h.call_at(&inventory, "build_project", json!({}));
|
||||
let close = async {
|
||||
let (id, _) = h.request_in("second").await;
|
||||
h.host.close_project_detached("second");
|
||||
id
|
||||
};
|
||||
let (error, id) = tokio::join!(closed, close);
|
||||
assert!(error.unwrap_err().contains("project window closed"));
|
||||
assert!(h.closed_in("second", id));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_request_leaves_the_window_when_its_project_unloads_or_the_call_is_cancelled() {
|
||||
let h = Harness::new();
|
||||
h.trust().await;
|
||||
h.host.mcp_requests.set_ready("main", true);
|
||||
let inventory = h.serve_inventory();
|
||||
h.host.trust.decide(&inventory, true, false).unwrap();
|
||||
let unloaded = h.call_at(&inventory, "build_project", json!({}));
|
||||
let unload = async {
|
||||
let (id, _) = h.request_in("main").await;
|
||||
assert!(h.host.mcp_background.detach(&h.host, &inventory, None));
|
||||
id
|
||||
};
|
||||
let (error, id) = tokio::join!(unloaded, unload);
|
||||
assert!(error.unwrap_err().contains("project window closed"));
|
||||
assert!(h.closed_in("main", id));
|
||||
|
||||
let (host, root, cancel) = (h.host.clone(), inventory.clone(), CancellationToken::new());
|
||||
let token = cancel.clone();
|
||||
let cancelled = tokio::task::spawn_blocking(move || Registry::new(host).call(&root, "build_project", "{}", token));
|
||||
let (id, _) = h.request_in("main").await;
|
||||
cancel.cancel();
|
||||
assert!(cancelled.await.unwrap().is_err());
|
||||
assert!(h.closed_in("main", id));
|
||||
assert!(h.shown("main").is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn an_untrusted_window_never_shows_a_background_request() {
|
||||
let h = Harness::new();
|
||||
h.trust().await;
|
||||
let second = h.open_second();
|
||||
let inventory = h.serve_inventory();
|
||||
h.host.trust.decide(&inventory, true, false).unwrap();
|
||||
// `second` is untrusted and focused last; its ready mark is a stale one.
|
||||
for window in ["main", "second"] {
|
||||
h.host.mcp_requests.set_ready(window, true);
|
||||
h.focus(window);
|
||||
}
|
||||
let call = h.call_at(&inventory, "build_project", json!({}));
|
||||
let moves = async {
|
||||
let (id, _) = h.request_in("main").await;
|
||||
assert!(h.shown("second").is_empty());
|
||||
h.host.set_project_trust(&second, true, false).await.unwrap();
|
||||
h.host.set_project_trust(&h.root, false, false).await.unwrap();
|
||||
let (moved, _) = h.request_in("second").await;
|
||||
assert_eq!(moved, id);
|
||||
assert!(h.closed_in("main", id));
|
||||
h.host.set_project_trust(&second, false, false).await.unwrap();
|
||||
};
|
||||
let (error, ()) = tokio::join!(call, moves);
|
||||
assert!(error.unwrap_err().contains("project window closed"));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_cancelled_or_failed_call_leaves_nothing_holding_the_project() {
|
||||
let h = Harness::new();
|
||||
@@ -1850,7 +2168,7 @@ fn debugger_window(h: &Harness) {
|
||||
tokio::spawn(async move {
|
||||
let mut handled = std::collections::HashSet::new();
|
||||
loop {
|
||||
let request = events.lock().unwrap().iter().find_map(|e| match e {
|
||||
let request = events.lock().unwrap().iter().find_map(|(_, e)| match e {
|
||||
IdeEvent::McpRequest { id, request }
|
||||
if !handled.contains(id)
|
||||
&& matches!(
|
||||
|
||||
@@ -70,6 +70,20 @@ impl Harness {
|
||||
fn run(&self, id: &str, arg: Option<&str>) -> ide_core::IdeResult<Option<String>> {
|
||||
self.plugins.run_command(ID, id, arg, self.invocation())
|
||||
}
|
||||
/// The folder `inventory` next to the project, listed to be served without a window.
|
||||
fn serve_inventory(&self) -> PathBuf {
|
||||
let inventory = self.root.parent().unwrap().join("inventory");
|
||||
std::fs::create_dir(&inventory).unwrap();
|
||||
for (key, value) in [
|
||||
("enabled", serde_json::json!(true)),
|
||||
("backgroundProjects", serde_json::json!("listed")),
|
||||
("backgroundProjectPaths", serde_json::json!([inventory])),
|
||||
] {
|
||||
let key = format!("mcpServer.{key}");
|
||||
self.host.global_settings.set(ide_workspace::SettingsScope::Global, &key, value).unwrap();
|
||||
}
|
||||
inventory
|
||||
}
|
||||
fn source(&self) -> String {
|
||||
serde_json::json!({"id":"local","name":"Example","driver":"sqlite","database":self.root.join("db.sqlite").to_string_lossy(),"options":[]}).to_string()
|
||||
}
|
||||
@@ -189,21 +203,66 @@ async fn mcp_listing_dispatch_confirmation_and_lifecycle_use_plugin_authority()
|
||||
assert!(spin.await.unwrap().is_err(), "command budget interrupts wasm");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_destructive_plugin_tool_of_a_background_project_asks_in_a_project_window() {
|
||||
let f = Harness::with_timeout(Duration::from_secs(10));
|
||||
f.host.set_project_trust(&f.root, true, false).await.unwrap();
|
||||
let inventory = f.serve_inventory();
|
||||
f.host.trust.decide(&inventory, true, false).unwrap();
|
||||
f.host.mcp_requests.set_ready("main", true);
|
||||
let (registry, root) = (Registry::new(f.host.clone()), inventory.clone());
|
||||
let call = tokio::task::spawn_blocking(move || {
|
||||
registry.call(&root, "test_data_tools__erase", "{}", CancellationToken::new())
|
||||
});
|
||||
let (window, id, background) = tokio::time::timeout(Duration::from_secs(5), async {
|
||||
loop {
|
||||
if let Some(found) = f.events.lock().unwrap().iter().find_map(|(w, e)| match e {
|
||||
IdeEvent::McpRequest { id, request: McpUiRequest::Confirm { background, .. } } => {
|
||||
Some((w.clone(), *id, *background))
|
||||
}
|
||||
_ => None,
|
||||
}) {
|
||||
break found;
|
||||
}
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!((window.as_str(), background), ("main", true));
|
||||
f.host.mcp_requests.answer("main", id, false, None).unwrap();
|
||||
let denied = call.await.unwrap().unwrap_err();
|
||||
assert!(format!("{denied:?}").contains("denied by the user"), "{denied:?}");
|
||||
f.host.close_project(&ide_host::mcp::BackgroundProjects::key(&inventory));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn plugin_tools_take_the_project_path_and_refuse_an_untrusted_project_before_it_loads() {
|
||||
let f = Harness::with_timeout(Duration::from_secs(10));
|
||||
f.host.set_project_trust(&f.root, true, false).await.unwrap();
|
||||
let inventory = f.serve_inventory();
|
||||
let registry = Registry::new(f.host.clone());
|
||||
// A connection without a project of its own lists the tool with `projectPath`, which its
|
||||
// calls have to pass, and the plugin's strict schema still takes the call.
|
||||
let listed = registry.tools_without_project();
|
||||
let echo = listed.iter().find(|t| t.name == "test_data_tools__echo").unwrap();
|
||||
assert!(echo.input_schema["properties"]["projectPath"].is_object(), "{}", echo.input_schema);
|
||||
let arguments = serde_json::json!({ "text": "hello", "projectPath": f.root }).to_string();
|
||||
let result = registry.call(&f.root, "test_data_tools__echo", &arguments, CancellationToken::new()).unwrap();
|
||||
assert!(result.contains("hello"), "{result}");
|
||||
// A tool that writes refuses the untrusted folder, and nothing loads.
|
||||
let refused = registry.call(&inventory, "test_data_tools__write", "{}", CancellationToken::new()).unwrap_err();
|
||||
let restricted = "Project is in Restricted Mode. Trust the project to enable execution.";
|
||||
assert_eq!(refused, ToolCallError::Failed(restricted.into()));
|
||||
assert!(f.host.mcp_background.snapshot(&f.host, std::time::Instant::now()).is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_plugin_tool_call_holds_its_background_project_until_it_ends() {
|
||||
use ide_host::mcp::{BackgroundProjects, McpBackgroundHold};
|
||||
// The fixture's `spin` runs until it is cancelled or its budget ends.
|
||||
let f = Harness::with_timeout(Duration::from_secs(10));
|
||||
let inventory = f.root.parent().unwrap().join("inventory");
|
||||
std::fs::create_dir(&inventory).unwrap();
|
||||
for (key, value) in [
|
||||
("enabled", serde_json::json!(true)),
|
||||
("backgroundProjects", serde_json::json!("listed")),
|
||||
("backgroundProjectPaths", serde_json::json!([inventory])),
|
||||
] {
|
||||
let key = format!("mcpServer.{key}");
|
||||
f.host.global_settings.set(ide_workspace::SettingsScope::Global, &key, value).unwrap();
|
||||
}
|
||||
let inventory = f.serve_inventory();
|
||||
let held_by = || {
|
||||
let loaded = f.host.mcp_background.snapshot(&f.host, std::time::Instant::now());
|
||||
loaded.into_iter().next().map(|project| project.kept_open_by)
|
||||
|
||||
@@ -8170,3 +8170,20 @@ fn contributes_skills_needs_api_1_15_and_warns_without_failing_plugin_on_bad_ent
|
||||
assert_eq!(dirs.len(), 1);
|
||||
assert!(dirs[0].ends_with("skills/good-skill"), "{dirs:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn restricting_a_project_without_its_plugins_announces_nothing() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let events: Events = Arc::default();
|
||||
let sink = {
|
||||
let events = events.clone();
|
||||
move |client: Option<&str>, e: PluginEvent| events.lock().push((client.map(str::to_owned), e))
|
||||
};
|
||||
let host = PluginHost::new(tmp.path().join("plugins"), Arc::new(sink), Limits::default()).unwrap();
|
||||
host.load_all();
|
||||
events.lock().clear();
|
||||
// A restricted window lists the plugins, which restricts its project again each time.
|
||||
host.restrict_project(tmp.path());
|
||||
host.restrict_project(tmp.path());
|
||||
assert!(!events.lock().iter().any(|(_, e)| matches!(e, PluginEvent::CommandsChanged)));
|
||||
}
|
||||
@@ -572,3 +572,60 @@ async fn a_repository_created_in_the_project_is_known_when_init_returns() {
|
||||
let roots: Vec<_> = project.repos().all().iter().map(|r| r.root().to_path_buf()).collect();
|
||||
assert_eq!(roots, [project_root]);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn vcs_roots_reports_unavailable_root_until_it_returns() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(temp.path()).unwrap();
|
||||
let project_root = base.join("project");
|
||||
let external_main = base.join("external-main");
|
||||
let wt = project_root.join("wt");
|
||||
let healthy = project_root.join("healthy");
|
||||
for root in [&external_main, &healthy] {
|
||||
std::fs::create_dir_all(root).unwrap();
|
||||
git(root, &["init", "-b", "main"]);
|
||||
git(root, &["config", "user.name", "Test"]);
|
||||
git(root, &["config", "user.email", "[email protected]"]);
|
||||
std::fs::write(root.join("file.txt"), "hello\n").unwrap();
|
||||
git(root, &["add", "."]);
|
||||
git(root, &["commit", "-m", "initial"]);
|
||||
}
|
||||
git(&external_main, &["worktree", "add", "-b", "wt-branch", wt.to_str().unwrap()]);
|
||||
|
||||
let host = Host::new(common::host_config(&base));
|
||||
host.trust.decide(&project_root, true, false).unwrap();
|
||||
let project = host.open_project("main", &project_root).unwrap();
|
||||
for _ in 0..500 {
|
||||
if project.repos().all().len() == 2 {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
assert_eq!(project.repos().all().len(), 2);
|
||||
|
||||
// Move the linked worktree's metadata dir (outside project_root) aside so the project FileWatcher never races.
|
||||
let wt_git_dir = external_main.join(".git/worktrees/wt");
|
||||
let parked_git_dir = base.join("parked-wt-git");
|
||||
std::fs::rename(&wt_git_dir, &parked_git_dir).unwrap();
|
||||
|
||||
let roots = vcs::vcs_roots(&host, "main").await.unwrap();
|
||||
let wt_root = roots.iter().find(|r| r.root.0 == wt).unwrap();
|
||||
let healthy_root = roots.iter().find(|r| r.root.0 == healthy).unwrap();
|
||||
assert!(wt_root.unavailable);
|
||||
assert!(wt_root.head.is_none());
|
||||
assert!(wt_root.head_commit.is_none());
|
||||
assert!(wt_root.operation.is_none());
|
||||
assert!(wt_root.has_remotes.is_none());
|
||||
assert_eq!(wt_root.branch_root.0, wt);
|
||||
assert!(!healthy_root.unavailable);
|
||||
assert_eq!(healthy_root.head.as_deref(), Some("main"));
|
||||
|
||||
std::fs::rename(&parked_git_dir, &wt_git_dir).unwrap();
|
||||
let restored = vcs::vcs_roots(&host, "main").await.unwrap();
|
||||
let wt_restored = restored.iter().find(|r| r.root.0 == wt).unwrap();
|
||||
let healthy_restored = restored.iter().find(|r| r.root.0 == healthy).unwrap();
|
||||
assert!(!wt_restored.unavailable);
|
||||
assert_eq!(wt_restored.head.as_deref(), Some("wt-branch"));
|
||||
assert!(!healthy_restored.unavailable);
|
||||
host.close_project("main");
|
||||
}
|
||||
@@ -28,6 +28,10 @@ struct Fixture {
|
||||
|
||||
impl Fixture {
|
||||
async fn new() -> Self {
|
||||
Self::with_sink(Arc::new(ide_core::NullSink)).await
|
||||
}
|
||||
|
||||
async fn with_sink(sink: ide_core::SharedSink) -> Self {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(temp.path()).unwrap();
|
||||
let root = base.join("project");
|
||||
@@ -40,7 +44,8 @@ impl Fixture {
|
||||
std::fs::write(root.join("file.txt"), "original\n").unwrap();
|
||||
git(&root, &["add", "."]);
|
||||
git(&root, &["commit", "-m", "original"]);
|
||||
let host = Host::new(common::host_config(&base));
|
||||
let host =
|
||||
Host::new(ide_host::HostConfig { sink_for: Box::new(move |_| sink.clone()), ..common::host_config(&base) });
|
||||
host.trust.decide(&root, true, false).unwrap();
|
||||
let project = host.open_project("main", &root).unwrap();
|
||||
wait_for_repos(&project, 1).await;
|
||||
@@ -278,6 +283,50 @@ async fn watcher_picks_up_a_worktree_added_below_the_project() {
|
||||
assert!(roots.contains(&linked), "watcher did not discover the worktree added below the project: {roots:?}");
|
||||
}
|
||||
|
||||
/// `git worktree add` writes the worktree's gitfile before its gitdir's `commondir` and `HEAD`; a
|
||||
/// slow git lets the watcher rescan in between and find no repository there yet.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn watcher_picks_up_a_worktree_whose_head_is_written_after_a_rescan() {
|
||||
let changes = Arc::new(std::sync::atomic::AtomicUsize::new(0));
|
||||
let counter = changes.clone();
|
||||
let sink: ide_core::SharedSink = Arc::new(move |event: ide_core::IdeEvent| {
|
||||
if matches!(event, ide_core::IdeEvent::VcsChanged { .. }) {
|
||||
counter.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
|
||||
}
|
||||
});
|
||||
let f = Fixture::with_sink(sink).await;
|
||||
// The watcher reports a batch that rescans only once the rescan is done.
|
||||
let next_change = || {
|
||||
let (changes, seen) = (changes.clone(), changes.load(std::sync::atomic::Ordering::SeqCst));
|
||||
async move {
|
||||
for _ in 0..200 {
|
||||
if changes.load(std::sync::atomic::Ordering::SeqCst) > seen {
|
||||
return;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
}
|
||||
panic!("the watcher reported no change");
|
||||
}
|
||||
};
|
||||
let linked = f.root.join("watched");
|
||||
let gitdir = f.root.join(".git/worktrees/watched");
|
||||
let registered = next_change();
|
||||
std::fs::create_dir_all(&gitdir).unwrap();
|
||||
std::fs::write(gitdir.join("gitdir"), format!("{}\n", linked.join(".git").display())).unwrap();
|
||||
registered.await;
|
||||
let rescanned = next_change();
|
||||
std::fs::create_dir_all(&linked).unwrap();
|
||||
std::fs::write(linked.join(".git"), format!("gitdir: {}\n", gitdir.display())).unwrap();
|
||||
rescanned.await;
|
||||
assert_eq!(f.project.repos().all().len(), 1, "a gitfile without its gitdir's HEAD is no repository yet");
|
||||
std::fs::write(gitdir.join("commondir"), "../..\n").unwrap();
|
||||
// As git does: through a lock file.
|
||||
std::fs::write(gitdir.join("HEAD.lock"), "ref: refs/heads/main\n").unwrap();
|
||||
std::fs::rename(gitdir.join("HEAD.lock"), gitdir.join("HEAD")).unwrap();
|
||||
wait_for_repos(&f.project, 2).await;
|
||||
assert!(f.project.repos().roots().contains(&linked));
|
||||
}
|
||||
|
||||
impl Fixture {
|
||||
async fn open(&self, root: &std::path::Path) {
|
||||
self.host.trust.decide(root, true, false).unwrap();
|
||||
|
||||
@@ -227,6 +227,10 @@ pub struct LanguageServerConfig {
|
||||
/// it parses a document.
|
||||
#[serde(default)]
|
||||
pub resync_on_configuration: bool,
|
||||
/// Server-created work-done tokens to ignore, including slash-delimited suffixes.
|
||||
/// Client-created request tokens are handled independently.
|
||||
#[serde(default)]
|
||||
pub ignored_progress_token_prefixes: Vec<String>,
|
||||
/// Set by the settings hook: what the user sees as the server when another program serves
|
||||
/// in its place (TypeScript 7's own `tsc --lsp` for vtsls).
|
||||
#[serde(skip)]
|
||||
|
||||
@@ -727,6 +727,21 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn java_analyzer_does_not_fill_empty_files() {
|
||||
let reg = reg();
|
||||
let java = reg.get(&LanguageId::new("java")).unwrap();
|
||||
let analyzer = java.language_servers.iter().find(|s| s.name == "java-analyzer").unwrap();
|
||||
assert_eq!(
|
||||
analyzer
|
||||
.initialization_options
|
||||
.as_ref()
|
||||
.and_then(|v| v.get("newFileTemplate"))
|
||||
.and_then(toml::Value::as_bool),
|
||||
Some(false)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn angular_server_joins_typescript_and_html_in_angular_projects() {
|
||||
let reg = reg();
|
||||
@@ -909,7 +924,10 @@ mod tests {
|
||||
let cfg = reg.get(&LanguageId::new("php")).unwrap();
|
||||
let names: Vec<&str> = cfg.language_servers.iter().map(|s| s.name.as_str()).collect();
|
||||
// After the fallback: hover, rename and symbols stay with Intelephense.
|
||||
assert_eq!(names, ["intelephense", "phpactor", "phoxite", "devsense-php-ls", "laravel-lsp"]);
|
||||
assert_eq!(names, ["intelephense", "phpantom", "phpactor", "phoxite", "devsense-php-ls", "laravel-lsp"]);
|
||||
let phpantom = &cfg.language_servers[1];
|
||||
assert!(phpantom.fallback && phpantom.args.is_empty());
|
||||
assert_eq!(phpantom.command, "phpantom_lsp");
|
||||
// Phoxite answers the Laravel strings itself.
|
||||
let phoxite = cfg.language_servers.iter().find(|s| s.name == "phoxite").unwrap();
|
||||
assert!(phoxite.fallback && phoxite.replaces == ["laravel-lsp"]);
|
||||
|
||||
@@ -73,6 +73,7 @@ fn server_config() -> LanguageServerConfig {
|
||||
tsserver_project: false,
|
||||
tsserver_project_extras: Default::default(),
|
||||
resync_on_configuration: false,
|
||||
ignored_progress_token_prefixes: vec![],
|
||||
display_name: None,
|
||||
pinned: None,
|
||||
}
|
||||
|
||||
@@ -151,6 +151,23 @@ impl ClientHandler {
|
||||
}
|
||||
|
||||
fn progress(&self, mgr: &LspManager, params: Value) {
|
||||
if let Some(token) = params["token"].as_str() {
|
||||
if let Some(id) = token.strip_prefix(crate::server::REQUEST_PROGRESS_PREFIX) {
|
||||
if let (Ok(id), Ok(update)) = (id.parse::<u32>(), serde_json::from_value(params["value"].clone())) {
|
||||
self.server.request_progress(mgr.sink(), TaskId(id), update);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if self
|
||||
.server
|
||||
.config
|
||||
.ignored_progress_token_prefixes
|
||||
.iter()
|
||||
.any(|prefix| token.strip_prefix(prefix).is_some_and(|rest| rest.is_empty() || rest.starts_with('/')))
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
let token = progress_key(¶ms["token"]);
|
||||
let value = ¶ms["value"];
|
||||
let kind = value.get("kind").and_then(Value::as_str);
|
||||
|
||||
@@ -503,12 +503,30 @@ impl LaunchScope {
|
||||
}
|
||||
}
|
||||
|
||||
/// m2e can run package-phase mojos such as `dependency:copy-dependencies` during
|
||||
/// `java/buildWorkspace`. In an incremental IDE build the reactor jars are not
|
||||
/// packaged, so the plugin fails with MDEP-187 (copy) or MDEP-98 (unpack). That is
|
||||
/// not a Java compile error, and a main-class launch does not need the copied jars.
|
||||
/// Debug uses this workspace build (so java-debug can HotSwap the classes jdtls
|
||||
/// compiled); Run uses the IDE's Java build and never hits the mojo. Ignoring the
|
||||
/// marker keeps the two consistent when the Java sources compiled.
|
||||
fn is_reactor_packaging_mojo_error(message: &str) -> bool {
|
||||
let lower = message.to_ascii_lowercase();
|
||||
lower.contains("has not been packaged yet") && lower.contains("executed after packaging")
|
||||
}
|
||||
|
||||
/// JDTLS reports all imported projects; report errors for the launch and its dependencies.
|
||||
fn launch_compile_errors(
|
||||
scope: &LaunchScope,
|
||||
diagnostics: Vec<(PathBuf, lsp_types::Diagnostic)>,
|
||||
) -> (Vec<JavaCompileError>, u32) {
|
||||
compile_errors(diagnostics.into_iter().filter(|(path, _)| scope.includes(path)).collect(), MAX_LAUNCH_ERRORS)
|
||||
compile_errors(
|
||||
diagnostics
|
||||
.into_iter()
|
||||
.filter(|(path, d)| scope.includes(path) && !is_reactor_packaging_mojo_error(&d.message))
|
||||
.collect(),
|
||||
MAX_LAUNCH_ERRORS,
|
||||
)
|
||||
}
|
||||
|
||||
/// `java.project.getClasspaths` result.
|
||||
@@ -1759,6 +1777,43 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn debug_launch_ignores_mdep_reactor_packaging_errors() {
|
||||
let cp = JavaClasspath {
|
||||
class_paths: vec!["/p/app/target/classes".into(), "/p/library/target/classes".into()],
|
||||
..Default::default()
|
||||
};
|
||||
let scope = LaunchScope::new(Path::new("/p/app"), false, Some(&cp));
|
||||
let diagnostic = |message: &str| lsp_types::Diagnostic {
|
||||
severity: Some(lsp_types::DiagnosticSeverity::ERROR),
|
||||
message: message.into(),
|
||||
range: lsp_types::Range::new(lsp_types::Position::new(299, 21), lsp_types::Position::new(299, 31)),
|
||||
..Default::default()
|
||||
};
|
||||
// m2e's BuildProblemInfo: the CoreException message, then the execution key,
|
||||
// then the stack whose cause is the plugin's MDEP-187 / MDEP-98 text.
|
||||
let copy = "Failed to execute mojo org.apache.maven.plugins:maven-dependency-plugin:3.6.1:copy-dependencies {execution: copy-dependencies} (org.apache.maven.plugins:maven-dependency-plugin:3.6.1:copy-dependencies:copy-dependencies:package)\n\norg.eclipse.core.runtime.CoreException: Failed to execute mojo org.apache.maven.plugins:maven-dependency-plugin:3.6.1:copy-dependencies {execution: copy-dependencies}\n\t at org.eclipse.m2e.core.project.configurator.MojoExecutionBuildParticipant.build(MojoExecutionBuildParticipant.java:57)\nCaused by: org.apache.maven.plugin.MojoExecutionException:\nArtifact has not been packaged yet. When used on reactor artifact, copy should be executed after packaging: see MDEP-187.";
|
||||
let unpack = "Failed to execute mojo org.apache.maven.plugins:maven-dependency-plugin:3.6.1:unpack-dependencies {execution: unpack-dependencies}\nCaused by: org.apache.maven.plugin.MojoExecutionException: Artifact has not been packaged yet. When used on reactor artifact, unpack should be executed after packaging: see MDEP-98.";
|
||||
let other_mojo = "Failed to execute mojo org.apache.maven.plugins:maven-compiler-plugin:3.13.0:compile {execution: default-compile}";
|
||||
let (errors, count) = launch_compile_errors(
|
||||
&scope,
|
||||
vec![
|
||||
(PathBuf::from("/p/app/pom.xml"), diagnostic(copy)),
|
||||
(PathBuf::from("/p/app/pom.xml"), diagnostic(unpack)),
|
||||
(PathBuf::from("/p/app/src/main/java/App.java"), diagnostic("App cannot be resolved to a type")),
|
||||
(PathBuf::from("/p/app/pom.xml"), diagnostic(other_mojo)),
|
||||
],
|
||||
);
|
||||
assert_eq!(count, 2);
|
||||
assert_eq!(&*errors[0].path, Path::new("/p/app/pom.xml"));
|
||||
assert_eq!(errors[0].message, other_mojo);
|
||||
assert_eq!(&*errors[1].path, Path::new("/p/app/src/main/java/App.java"));
|
||||
assert_eq!(errors[1].message, "App cannot be resolved to a type");
|
||||
let (_, only_packaging) =
|
||||
launch_compile_errors(&scope, vec![(PathBuf::from("/p/app/pom.xml"), diagnostic(copy))]);
|
||||
assert_eq!(only_packaging, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unresolved_classpaths_retain_all_errors() {
|
||||
for cp in [
|
||||
|
||||
@@ -1598,10 +1598,20 @@ impl LspManager {
|
||||
cancel: Option<&CancellationToken>,
|
||||
timeout: Duration,
|
||||
) -> IdeResult<R> {
|
||||
let params = serde_json::to_value(params).map_err(|e| IdeError::internal(e.to_string()))?;
|
||||
let mut params = serde_json::to_value(params).map_err(|e| IdeError::internal(e.to_string()))?;
|
||||
// ImplementationParams accepts an optional client work-done token. Servers
|
||||
// may report on it even when implementationProvider is advertised as `true`.
|
||||
let progress = (method == "textDocument/implementation")
|
||||
.then(|| t.server.track_request_progress(t.run.generation, self.sink(), cancel));
|
||||
let cancel = if let Some(progress) = &progress {
|
||||
params["workDoneToken"] = json!(progress.wire_token());
|
||||
Some(progress.cancel.clone())
|
||||
} else {
|
||||
cancel.cloned()
|
||||
};
|
||||
let stamp = self.injected_request_stamp(¶ms);
|
||||
let fut = async {
|
||||
let mut value = t.run.peer.request::<Value, Value>(method, params, cancel.cloned()).await?;
|
||||
let mut value = t.run.peer.request::<Value, Value>(method, params, cancel).await?;
|
||||
virtual_doc::normalize_uris(&mut value);
|
||||
serde_json::from_value(value).map_err(|e| RpcError::Protocol(format!("{method}: {e}")))
|
||||
};
|
||||
@@ -3395,10 +3405,17 @@ impl LspManager {
|
||||
if changes.is_empty() {
|
||||
continue;
|
||||
}
|
||||
// jdtls rebuilds a source file that changed on disk but keeps the diagnostics of the
|
||||
// open files it checked before: a reference to a class another tool adds after
|
||||
// rewriting the open file stays "cannot be resolved" until the file is reopened.
|
||||
// Sending the open files again makes it check them against the new sources.
|
||||
let recheck_open = jdtls && changes.iter().any(|(p, _)| p.extension().is_some_and(|e| e == "java"));
|
||||
let changes: Vec<Value> =
|
||||
changes.iter().map(|(p, c)| json!({ "uri": uri::path_to_uri(p), "type": *c as u8 })).collect();
|
||||
if let Err(e) = run.peer.notify("workspace/didChangeWatchedFiles", json!({ "changes": changes })) {
|
||||
tracing::debug!("{}: didChangeWatchedFiles: {e}", s.name);
|
||||
} else if recheck_open {
|
||||
self.resync_documents(&s, run.generation);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -53,10 +53,58 @@ struct State {
|
||||
generation: u64,
|
||||
conn: Conn,
|
||||
restarting: bool,
|
||||
request_progress: HashMap<TaskId, RequestProgressState>,
|
||||
events: VecDeque<IdeEvent>,
|
||||
publishing: bool,
|
||||
}
|
||||
|
||||
pub(crate) const REQUEST_PROGRESS_PREFIX: &str = "openidea/request/";
|
||||
|
||||
struct RequestProgressState {
|
||||
title: Option<String>,
|
||||
message: Option<String>,
|
||||
fraction: Option<f32>,
|
||||
_cancel: ide_core::task::CancelHandle,
|
||||
}
|
||||
|
||||
impl RequestProgressState {
|
||||
fn event(&self, id: TaskId, done: bool) -> Option<IdeEvent> {
|
||||
Some(IdeEvent::Task {
|
||||
id,
|
||||
title: self.title.clone()?,
|
||||
message: self.message.clone(),
|
||||
fraction: self.fraction,
|
||||
done,
|
||||
cancellable: !done,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Progress provided to an LSP request. Dropping the request always retires its token.
|
||||
pub(crate) struct RequestProgress<'a> {
|
||||
id: TaskId,
|
||||
server: &'a Server,
|
||||
sink: &'a SharedSink,
|
||||
pub(crate) cancel: CancellationToken,
|
||||
}
|
||||
|
||||
impl RequestProgress<'_> {
|
||||
pub(crate) fn wire_token(&self) -> String {
|
||||
format!("{REQUEST_PROGRESS_PREFIX}{}", self.id.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for RequestProgress<'_> {
|
||||
fn drop(&mut self) {
|
||||
let mut st = self.server.state.lock();
|
||||
if let Some(progress) = st.request_progress.remove(&self.id) {
|
||||
st.events.extend(progress.event(self.id, true));
|
||||
}
|
||||
drop(st);
|
||||
self.server.publish(self.sink);
|
||||
}
|
||||
}
|
||||
|
||||
/// A file opened on the server by the client itself (not by the user) for the
|
||||
/// duration of a request, e.g. to widen a references search.
|
||||
struct Transient {
|
||||
@@ -172,6 +220,7 @@ impl Server {
|
||||
generation: 0,
|
||||
conn: Conn::Idle,
|
||||
restarting: false,
|
||||
request_progress: HashMap::new(),
|
||||
events: VecDeque::new(),
|
||||
publishing: false,
|
||||
}),
|
||||
@@ -552,6 +601,9 @@ impl Server {
|
||||
|
||||
fn queue_cleanup(&self, st: &mut State) {
|
||||
*self.initializing.lock() = None;
|
||||
for (id, progress) in st.request_progress.drain() {
|
||||
st.events.extend(progress.event(id, true));
|
||||
}
|
||||
for (id, title) in self.take_progress() {
|
||||
st.events.push_back(IdeEvent::Task {
|
||||
id,
|
||||
@@ -572,6 +624,61 @@ impl Server {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn track_request_progress<'a>(
|
||||
&'a self,
|
||||
generation: u64,
|
||||
sink: &'a SharedSink,
|
||||
parent_cancel: Option<&CancellationToken>,
|
||||
) -> RequestProgress<'a> {
|
||||
let id = TaskId::next();
|
||||
let cancel = parent_cancel.map(CancellationToken::child_token).unwrap_or_default();
|
||||
let mut st = self.state.lock();
|
||||
if st.generation == generation && matches!(st.conn, Conn::Ready(_)) {
|
||||
let token = cancel.clone();
|
||||
st.request_progress.insert(
|
||||
id,
|
||||
RequestProgressState {
|
||||
title: None,
|
||||
message: None,
|
||||
fraction: None,
|
||||
_cancel: ide_core::task::on_cancel(id, move || token.cancel()),
|
||||
},
|
||||
);
|
||||
}
|
||||
RequestProgress { id, server: self, sink, cancel }
|
||||
}
|
||||
|
||||
pub(crate) fn request_progress(&self, sink: &SharedSink, id: TaskId, update: lsp::WorkDoneProgress) {
|
||||
let mut st = self.state.lock();
|
||||
let Some(progress) = st.request_progress.get_mut(&id) else { return };
|
||||
let fraction = |p: u32| p.min(100) as f32 / 100.0;
|
||||
let event = match update {
|
||||
lsp::WorkDoneProgress::Begin(begin) => {
|
||||
progress.title = Some(begin.title);
|
||||
progress.message = begin.message;
|
||||
progress.fraction = begin.percentage.map(fraction);
|
||||
progress.event(id, false)
|
||||
}
|
||||
lsp::WorkDoneProgress::Report(report) => {
|
||||
progress.message = report.message.or_else(|| progress.message.take());
|
||||
progress.fraction = report.percentage.map(fraction).or(progress.fraction);
|
||||
progress.event(id, false)
|
||||
}
|
||||
lsp::WorkDoneProgress::End(end) => {
|
||||
progress.message = end.message.or_else(|| progress.message.take());
|
||||
progress.fraction = Some(1.0);
|
||||
let event = progress.event(id, true);
|
||||
st.request_progress.remove(&id);
|
||||
event
|
||||
}
|
||||
};
|
||||
// Queue under the state lock so a reply or cancellation can't publish `done`
|
||||
// before a concurrent progress update and leave a stale row.
|
||||
st.events.extend(event);
|
||||
drop(st);
|
||||
self.publish(sink);
|
||||
}
|
||||
|
||||
pub fn emit(&self, sink: &SharedSink, event: IdeEvent) {
|
||||
self.state.lock().events.push_back(event);
|
||||
self.publish(sink);
|
||||
|
||||
@@ -277,6 +277,7 @@ fn server_cfg(name: &str) -> LanguageServerConfig {
|
||||
tsserver_project: false,
|
||||
tsserver_project_extras: Default::default(),
|
||||
resync_on_configuration: false,
|
||||
ignored_progress_token_prefixes: vec![],
|
||||
display_name: None,
|
||||
pinned: None,
|
||||
}
|
||||
@@ -481,6 +482,31 @@ async fn dart_file_watching_requires_an_explicit_registration() {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn java_sources_changed_on_disk_send_the_open_files_to_jdtls_again() {
|
||||
let h = harness_for("java", "java", &[("jdtls", incremental_caps())], &[]);
|
||||
let (_, main) = h.open("Main.java", "class Main { String s = Helper.greet(); }");
|
||||
h.wait_status("jdtls", ServerStatus::Ready).await;
|
||||
let s = h.launcher.state("jdtls");
|
||||
let resent = || {
|
||||
s.notified("textDocument/didChange")
|
||||
.iter()
|
||||
.filter(|v| v["textDocument"]["uri"] == uri_of(&main) && v["contentChanges"][0]["text"].is_string())
|
||||
.count()
|
||||
};
|
||||
// Another tool adds the class the open file refers to.
|
||||
let helper = h.root.join("Helper.java");
|
||||
h.mgr.watched_files_changed(std::slice::from_ref(&helper), &[], &[], &[]);
|
||||
eventually(|| s.notified("workspace/didChangeWatchedFiles").len() == 1).await;
|
||||
eventually(|| resent() == 1).await;
|
||||
// Files that are not Java sources leave the open files alone.
|
||||
h.mgr.watched_files_changed(&[], &[h.root.join("notes.txt")], &[], &[]);
|
||||
h.mgr.watched_files_changed(&[], &[h.root.join("pom.xml")], &[], &[]);
|
||||
tokio::time::sleep(Duration::from_millis(200)).await;
|
||||
assert_eq!(resent(), 1);
|
||||
h.mgr.shutdown_all().await;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ tests
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
@@ -2225,6 +2251,54 @@ async fn a_progress_token_begun_again_ends_the_task_it_replaces() {
|
||||
h.wait_status("mock", ServerStatus::Ready).await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn toml_progress_quirk_ignores_server_tokens_left_open_after_cancel() {
|
||||
let registry = LanguageRegistry::load(None).unwrap();
|
||||
let php = registry.get(&LanguageId::new("php")).unwrap();
|
||||
let quirk = &php.language_servers.iter().find(|s| s.name == "phpantom").unwrap().ignored_progress_token_prefixes;
|
||||
let h = harness_configured("php", "php", &[("mock", incremental_caps())], |cfg| {
|
||||
cfg.ignored_progress_token_prefixes = quirk.clone();
|
||||
});
|
||||
let (doc, path) = h.open("a.php", "<?php target();");
|
||||
h.wait_status("mock", ServerStatus::Ready).await;
|
||||
let server = h.launcher.state("mock");
|
||||
let peer = server.peer();
|
||||
let progress = |token, kind, title| {
|
||||
peer.notify("$/progress", json!({ "token": token, "value": { "kind": kind, "title": title } })).unwrap();
|
||||
};
|
||||
let method = "textDocument/references";
|
||||
let search = || h.mgr.references_streaming(doc, Pos::new(0, 7), true, false, true, Default::default(), None);
|
||||
|
||||
progress("find_references/1", "begin", "Find References");
|
||||
progress("find_references", "begin", "Find References");
|
||||
progress("goto_implementation/1", "begin", "Go to Implementation");
|
||||
progress("find_references_index/1", "begin", "Indexing");
|
||||
h.wait_status("mock", ServerStatus::Busy).await;
|
||||
server.errors.lock().insert(method.into(), (-32800, "Canceled".into()));
|
||||
assert_eq!(search().await.unwrap_err().kind, ide_core::error::ErrorKind::Cancelled);
|
||||
|
||||
server.errors.lock().remove(method);
|
||||
server.respond(
|
||||
method,
|
||||
json!([{
|
||||
"uri": uri_of(&path),
|
||||
"range": { "start": { "line": 0, "character": 6 }, "end": { "line": 0, "character": 12 } }
|
||||
}]),
|
||||
);
|
||||
progress("find_references/2", "begin", "Find References");
|
||||
assert_eq!(search().await.unwrap().locations.len(), 1);
|
||||
progress("find_references/2", "end", "Find References");
|
||||
progress("find_references_index/1", "end", "Indexing");
|
||||
h.wait_status("mock", ServerStatus::Ready).await;
|
||||
|
||||
let events = h.events.lock();
|
||||
assert!(!events.iter().any(
|
||||
|e| matches!(e, IdeEvent::Task { title, .. } if title == "Find References" || title == "Go to Implementation")
|
||||
));
|
||||
assert!(events.iter().any(|e| matches!(e, IdeEvent::Task { title, done: false, .. } if title == "Indexing")));
|
||||
assert!(events.iter().any(|e| matches!(e, IdeEvent::Task { title, done: true, .. } if title == "Indexing")));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn replacing_progress_keeps_cancellation_reports_and_indexing_on_the_new_task() {
|
||||
let h = harness(&[("mock", incremental_caps())]);
|
||||
@@ -4239,6 +4313,118 @@ async fn implementations_per_position() {
|
||||
assert_eq!(err.kind, ide_core::error::ErrorKind::Cancelled);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn implementation_progress_ends_on_cancel_without_server_end() {
|
||||
implementation_progress_ends_with_request(false).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn implementation_progress_ends_on_timeout_without_server_end() {
|
||||
implementation_progress_ends_with_request(true).await;
|
||||
}
|
||||
|
||||
async fn implementation_progress_ends_with_request(timeout: bool) {
|
||||
let caps = json!({ "textDocumentSync": 1, "implementationProvider": true });
|
||||
let h = harness_for("php", "php", &[("mock", caps)], &[]);
|
||||
let (doc, path) = h.open("a.php", "<?php\ninterface A {}\nclass B implements A {}\n");
|
||||
h.wait_status("mock", ServerStatus::Ready).await;
|
||||
let server = h.launcher.state("mock");
|
||||
let method = "textDocument/implementation";
|
||||
let gate = Arc::new(Gate::default());
|
||||
let uri = uri_of(&path);
|
||||
*server.responder.lock() =
|
||||
Some(Arc::new({
|
||||
let gate = gate.clone();
|
||||
move |server, requested, params| {
|
||||
if requested != method {
|
||||
return None;
|
||||
}
|
||||
let token = ¶ms["workDoneToken"];
|
||||
let peer = server.peer();
|
||||
peer.notify("$/progress", json!({
|
||||
"token": token, "value": { "kind": "begin", "title": "Go to Implementation", "cancellable": false }
|
||||
})).unwrap();
|
||||
if params["position"]["character"] == 10 {
|
||||
peer.notify(
|
||||
"$/progress",
|
||||
json!({
|
||||
"token": token, "value": { "kind": "report", "percentage": 88 }
|
||||
}),
|
||||
)
|
||||
.unwrap();
|
||||
gate.hold();
|
||||
}
|
||||
// The mock answers without sending `end`.
|
||||
Some(json!([{
|
||||
"uri": uri,
|
||||
"range": { "start": { "line": 2, "character": 6 }, "end": { "line": 2, "character": 7 } }
|
||||
}]))
|
||||
}
|
||||
}));
|
||||
|
||||
let mgr = h.mgr.clone();
|
||||
let batch = tokio::spawn(async move {
|
||||
mgr.implementations(doc, &[Pos::new(1, 10), Pos::new(2, 6)], Default::default()).await.unwrap()
|
||||
});
|
||||
let task_events = || {
|
||||
h.events
|
||||
.lock()
|
||||
.iter()
|
||||
.filter_map(|e| match e {
|
||||
IdeEvent::Task { id, title, done, fraction, cancellable, .. } if title == "Go to Implementation" => {
|
||||
Some((*id, *done, *fraction, *cancellable))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
eventually(|| {
|
||||
let events = task_events();
|
||||
gate.entered() && events.iter().any(|e| e.2 == Some(0.88)) && events.iter().any(|(_, done, _, _)| *done)
|
||||
})
|
||||
.await;
|
||||
let scanning = task_events().into_iter().find(|e| e.2 == Some(0.88)).expect("scan reported 88%");
|
||||
let (task, _, _, cancellable) = scanning;
|
||||
assert!(cancellable);
|
||||
assert!(!task_events().iter().any(|(id, done, _, _)| *id == task && *done));
|
||||
let requests = server.requested(method);
|
||||
assert_eq!(requests.len(), 2);
|
||||
assert_ne!(requests[0]["workDoneToken"], requests[1]["workDoneToken"]);
|
||||
|
||||
if timeout {
|
||||
tokio::time::pause();
|
||||
tokio::time::advance(Duration::from_secs(31)).await;
|
||||
tokio::time::resume();
|
||||
} else {
|
||||
assert!(ide_core::task::cancel(task));
|
||||
}
|
||||
let found = batch.await.unwrap();
|
||||
gate.open();
|
||||
eventually(|| !server.notified("$/cancelRequest").is_empty()).await;
|
||||
assert!(found[0].is_empty());
|
||||
assert_eq!(found[1][0].range.start.line, 2);
|
||||
assert!(!ide_core::task::cancel(task));
|
||||
assert_eq!(task_events().iter().filter(|(id, done, _, _)| *id == task && *done).count(), 1);
|
||||
|
||||
// Late progress for either retired token must not bring back its task.
|
||||
let before = task_events();
|
||||
let peer = server.peer();
|
||||
for request in requests {
|
||||
peer.notify(
|
||||
"$/progress",
|
||||
json!({
|
||||
"token": request["workDoneToken"], "value": { "kind": "begin", "title": "Go to Implementation" }
|
||||
}),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
peer.notify("$/progress", json!({ "token": "index", "value": { "kind": "begin", "title": "Indexing" } })).unwrap();
|
||||
h.wait_status("mock", ServerStatus::Busy).await;
|
||||
assert_eq!(task_events(), before);
|
||||
peer.notify("$/progress", json!({ "token": "index", "value": { "kind": "end" } })).unwrap();
|
||||
h.wait_status("mock", ServerStatus::Ready).await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn java_implementations_come_from_sources_first() {
|
||||
let caps = json!({
|
||||
|
||||
@@ -428,6 +428,7 @@ async fn missing_binary_is_reported_with_install_hint() {
|
||||
tsserver_project: false,
|
||||
tsserver_project_extras: Default::default(),
|
||||
resync_on_configuration: false,
|
||||
ignored_progress_token_prefixes: vec![],
|
||||
display_name: None,
|
||||
pinned: None,
|
||||
};
|
||||
@@ -721,6 +722,7 @@ async fn typescript_language_server_end_to_end() {
|
||||
tsserver_project: false,
|
||||
tsserver_project_extras: Default::default(),
|
||||
resync_on_configuration: false,
|
||||
ignored_progress_token_prefixes: vec![],
|
||||
display_name: None,
|
||||
pinned: None,
|
||||
};
|
||||
@@ -775,6 +777,7 @@ fn npm_server(tools: &Path, name: &str, bin: &str, init: Option<serde_json::Valu
|
||||
tsserver_project: false,
|
||||
tsserver_project_extras: Default::default(),
|
||||
resync_on_configuration: false,
|
||||
ignored_progress_token_prefixes: vec![],
|
||||
display_name: None,
|
||||
pinned: None,
|
||||
}
|
||||
|
||||
@@ -9,7 +9,11 @@
|
||||
//! `Origin` or `Host` are refused (DNS rebinding).
|
||||
//! - **Projects:** the `X-OpenIDEA-Project` header or the `?project=` query
|
||||
//! names a folder; the server picks the open project containing it, or the
|
||||
//! project the IDE serves it from without a window.
|
||||
//! project the IDE serves it from without a window. A connection whose
|
||||
//! folder no project serves lists the tools a trusted project gets, and each
|
||||
//! call names its project with `projectPath`. `openidea/servesFolder`
|
||||
//! answers which project serves the connection's folder (`{"root": null}`
|
||||
//! for none).
|
||||
//! - **Discovery:** `<app-data>/mcp/server.json` (`address`, `port`, `token`,
|
||||
//! `pid`, `version`; readable only by the user) while the server runs.
|
||||
//! - **Stdio:** `<app exe> --mcp-stdio [--project <path>]` reads the discovery
|
||||
@@ -76,6 +80,12 @@ pub trait ToolRegistry: Send + Sync + 'static {
|
||||
/// The tools callable for `project` (one of [`Self::projects`] or a root
|
||||
/// [`Self::resolve`] gave). `Err` says why there are none (an unsupported project).
|
||||
fn tools(&self, project: &Path) -> Result<Vec<Tool>, String>;
|
||||
/// The tools listed on a connection whose project doesn't resolve (a folder no project
|
||||
/// serves, or no folder and not exactly one window): those a trusted project gets. Each
|
||||
/// call still resolves its project and refuses by that project's trust.
|
||||
fn tools_without_project(&self) -> Vec<Tool> {
|
||||
Vec::new()
|
||||
}
|
||||
fn call_with_client(
|
||||
&self,
|
||||
project: &Path,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! MCP over JSON-RPC 2.0: `initialize`, `ping`, `tools/list`, `tools/call`
|
||||
//! and notifications, for one POST body (a message or a batch). Blocking: the
|
||||
//! server runs it on a blocking thread.
|
||||
//! MCP over JSON-RPC 2.0: `initialize`, `ping`, `tools/list`, `tools/call`,
|
||||
//! our own `openidea/servesFolder` and notifications, for one POST body (a
|
||||
//! message or a batch). Blocking: the server runs it on a blocking thread.
|
||||
|
||||
use crate::{CancellationToken, Tool, ToolCallError, ToolRegistry};
|
||||
use serde_json::{Value, json};
|
||||
@@ -26,16 +26,22 @@ impl Drop for InFlight<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// How long a cancellation that arrived before its call is kept.
|
||||
const EARLY_CANCELLATION: std::time::Duration = std::time::Duration::from_secs(60);
|
||||
|
||||
/// The protocol version answered when the client asks for one this server doesn't know.
|
||||
pub(crate) const LATEST: &str = "2025-06-18";
|
||||
pub(crate) const SUPPORTED: [&str; 3] = ["2025-06-18", "2025-03-26", "2024-11-05"];
|
||||
|
||||
const PARSE_ERROR: i64 = -32700;
|
||||
const INVALID_REQUEST: i64 = -32600;
|
||||
const METHOD_NOT_FOUND: i64 = -32601;
|
||||
pub(crate) const METHOD_NOT_FOUND: i64 = -32601;
|
||||
const INVALID_PARAMS: i64 = -32602;
|
||||
/// The requested folder isn't in a project the IDE serves (or has no tools there).
|
||||
pub(crate) const NOT_OPEN: i64 = -32001;
|
||||
/// Which project serves the connection's folder: `{"root": "<path>"}`, or `{"root": null}`
|
||||
/// for none. The stdio bridge asks it to pick the IDE process for its folder.
|
||||
pub(crate) const SERVES_FOLDER: &str = "openidea/servesFolder";
|
||||
|
||||
pub(crate) struct RpcError {
|
||||
code: i64,
|
||||
@@ -105,7 +111,12 @@ impl Session<'_> {
|
||||
let mut state = self.requests.0.lock().unwrap();
|
||||
if let Some(cancel) = state.running.get(&key) {
|
||||
cancel.cancel();
|
||||
} else if state.early.len() < 1024 {
|
||||
return None;
|
||||
}
|
||||
// The stdio bridge sends a cancellation to every server, so one that runs few
|
||||
// calls drops the stale ones here as well.
|
||||
state.early.retain(|_, at| at.elapsed() < EARLY_CANCELLATION);
|
||||
if state.early.len() < 1024 {
|
||||
state.early.insert(key, std::time::Instant::now());
|
||||
}
|
||||
}
|
||||
@@ -116,7 +127,7 @@ impl Session<'_> {
|
||||
let cancel = self.cancel.child_token();
|
||||
{
|
||||
let mut requests = self.requests.0.lock().unwrap();
|
||||
requests.early.retain(|_, at| at.elapsed() < std::time::Duration::from_secs(60));
|
||||
requests.early.retain(|_, at| at.elapsed() < EARLY_CANCELLATION);
|
||||
if requests.running.contains_key(&key) {
|
||||
return Some(error_response(id, INVALID_REQUEST, "request id already in flight"));
|
||||
}
|
||||
@@ -139,11 +150,18 @@ impl Session<'_> {
|
||||
"initialize" => Ok(self.initialize(¶ms)),
|
||||
"ping" => Ok(json!({})),
|
||||
"tools/list" => {
|
||||
let project = self.project()?;
|
||||
let tools = self.registry.tools(&project).map_err(|e| RpcError::new(NOT_OPEN, e))?;
|
||||
let tools = match self.project() {
|
||||
Ok(project) => self.registry.tools(&project).map_err(|e| RpcError::new(NOT_OPEN, e))?,
|
||||
Err(_) => self.registry.tools_without_project(),
|
||||
};
|
||||
Ok(json!({ "tools": tools.iter().map(tool_json).collect::<Vec<_>>() }))
|
||||
}
|
||||
"tools/call" => self.call(params, cancel),
|
||||
SERVES_FOLDER => {
|
||||
// A root without tools here (a remote window's) is another server's to serve.
|
||||
let root = self.project().ok().filter(|root| self.registry.tools(root).is_ok());
|
||||
Ok(json!({ "root": root.map(|root| root.display().to_string()) }))
|
||||
}
|
||||
_ => Err(RpcError::new(METHOD_NOT_FOUND, format!("no method {method:?}"))),
|
||||
}
|
||||
}
|
||||
@@ -157,9 +175,13 @@ impl Session<'_> {
|
||||
}
|
||||
let asked = params.get("protocolVersion").and_then(Value::as_str).unwrap_or(LATEST);
|
||||
let version = if SUPPORTED.contains(&asked) { asked } else { LATEST };
|
||||
let about = match self.project() {
|
||||
Ok(root) => format!("the project OpenIDEA serves at {}", root.display()),
|
||||
Err(_) => "a project open in OpenIDEA or served in the background".to_owned(),
|
||||
let (about, without_project) = match self.project() {
|
||||
Ok(root) => (format!("the project OpenIDEA serves at {}", root.display()), ""),
|
||||
Err(_) => (
|
||||
"a project open in OpenIDEA or served in the background".to_owned(),
|
||||
" This connection has no project of its own: pass `projectPath`, a folder inside a project \
|
||||
OpenIDEA serves, in every call, `get_workspace_roots` included.",
|
||||
),
|
||||
};
|
||||
json!({
|
||||
"protocolVersion": version,
|
||||
@@ -174,7 +196,7 @@ impl Session<'_> {
|
||||
its `roots` are every project in the IDE workspace. That is the scope to search and read, \
|
||||
not a list of projects to change; it doesn't change your working directory or \
|
||||
permissions. Pass another root as `projectPath` to reach that project. Call it again \
|
||||
when the user switches projects or attaches one."
|
||||
when the user switches projects or attaches one.{without_project}"
|
||||
),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
//! running IDE's server, found through the discovery file.
|
||||
|
||||
use crate::discovery::Discovery;
|
||||
use crate::protocol::{NOT_OPEN, error_response};
|
||||
use crate::protocol::{METHOD_NOT_FOUND, NOT_OPEN, SERVES_FOLDER, error_response};
|
||||
use bytes::Bytes;
|
||||
use http_body_util::{BodyExt, Full};
|
||||
use hyper::{Request, StatusCode, header};
|
||||
@@ -17,7 +17,11 @@ use tokio::io::{AsyncBufRead, AsyncBufReadExt, AsyncWrite, AsyncWriteExt};
|
||||
|
||||
#[derive(Default)]
|
||||
struct BridgeState {
|
||||
preferred: Option<SocketAddr>,
|
||||
/// The server that serves the connection's folder, or the first one when none does. A
|
||||
/// server restarted on its port is another one: its entry names another process or token.
|
||||
preferred: Option<Discovery>,
|
||||
/// The servers there were when `preferred` was picked: one started since may serve the folder.
|
||||
picked_among: Vec<Discovery>,
|
||||
init_message: Option<Value>,
|
||||
initialized_on: HashSet<SocketAddr>,
|
||||
}
|
||||
@@ -171,18 +175,28 @@ async fn post(
|
||||
if candidates.is_empty() {
|
||||
return Err(not_running());
|
||||
}
|
||||
if let Some(preferred) = state.lock().unwrap().preferred
|
||||
&& let Some(pos) = candidates.iter().position(|c| SocketAddr::new(c.address, c.port) == preferred)
|
||||
{
|
||||
if message.get("method").and_then(Value::as_str) == Some("notifications/cancelled") {
|
||||
return cancel_everywhere(candidates, project, message, scope, sent).await.ok_or_else(not_running);
|
||||
}
|
||||
let preferred = state.lock().unwrap().preferred.clone();
|
||||
if let Some(pos) = preferred.and_then(|preferred| candidates.iter().position(|c| *c == preferred)) {
|
||||
let chosen = candidates.remove(pos);
|
||||
candidates.insert(0, chosen);
|
||||
}
|
||||
// `initialize` picks the server that serves the connection's folder, and later messages
|
||||
// keep it: a call whose `projectPath` another server serves doesn't move `tools/list`
|
||||
// there. A message after that server stopped, or after another one started, picks again.
|
||||
let initializing = is_initialize(message);
|
||||
let mut fallback: Option<(SocketAddr, Answer)> = None;
|
||||
if !initializing {
|
||||
pick_again(&mut candidates, project, scope, state).await;
|
||||
}
|
||||
let listed = candidates.clone();
|
||||
let mut answered = None;
|
||||
let mut fallback: Option<(Discovery, Answer)> = None;
|
||||
let mut last_error: Option<String> = None;
|
||||
let total = candidates.len();
|
||||
for (idx, info) in candidates.into_iter().enumerate() {
|
||||
let at = SocketAddr::new(info.address, info.port);
|
||||
let at = address(&info);
|
||||
if !initializing {
|
||||
let init = {
|
||||
let guard = state.lock().unwrap();
|
||||
@@ -190,7 +204,7 @@ async fn post(
|
||||
};
|
||||
if let Some(mut init_msg) = init {
|
||||
if let Some(obj) = init_msg.as_object_mut() {
|
||||
obj.insert("id".into(), Value::String(format!("__openidea_init_{idx}__")));
|
||||
obj.insert("id".into(), Value::String(own_id("init")));
|
||||
}
|
||||
if post_one(&info, project, &init_msg, scope, sent).await.is_ok() {
|
||||
state.lock().unwrap().initialized_on.insert(at);
|
||||
@@ -202,34 +216,120 @@ async fn post(
|
||||
if initializing {
|
||||
state.lock().unwrap().initialized_on.insert(at);
|
||||
if total > 1 && !serves_project(&info, project, scope).await {
|
||||
fallback.get_or_insert((at, answer));
|
||||
fallback.get_or_insert((info, answer));
|
||||
continue;
|
||||
}
|
||||
} else if idx + 1 < total && is_not_open_reply(&answer) {
|
||||
fallback = Some((at, answer));
|
||||
fallback = Some((info, answer));
|
||||
continue;
|
||||
}
|
||||
state.lock().unwrap().preferred = Some(at);
|
||||
return Ok(answer);
|
||||
answered = Some((info, answer));
|
||||
break;
|
||||
}
|
||||
Err(err) => last_error = Some(err),
|
||||
}
|
||||
}
|
||||
if let Some((at, answer)) = fallback {
|
||||
state.lock().unwrap().preferred = Some(at);
|
||||
return Ok(answer);
|
||||
let Some((info, answer)) = answered.or(fallback) else {
|
||||
return Err(last_error.unwrap_or_else(not_running));
|
||||
};
|
||||
if initializing {
|
||||
let mut state = state.lock().unwrap();
|
||||
state.preferred = Some(info);
|
||||
state.picked_among = listed;
|
||||
}
|
||||
Err(last_error.unwrap_or_else(not_running))
|
||||
Ok(answer)
|
||||
}
|
||||
|
||||
/// Whether the server of `info` has `project` open: its `tools/list` doesn't answer "not open".
|
||||
async fn serves_project(info: &Discovery, project: &Path, scope: &str) -> bool {
|
||||
let probe = serde_json::json!({ "jsonrpc": "2.0", "id": "__openidea_probe__", "method": "tools/list" });
|
||||
let (discard, _) = tokio::sync::mpsc::unbounded_channel();
|
||||
match post_one(info, project, &probe, scope, &discard).await {
|
||||
Ok(answer @ Answer::Body(StatusCode::OK, _)) => !is_not_open_reply(&answer),
|
||||
_ => false,
|
||||
fn address(info: &Discovery) -> SocketAddr {
|
||||
SocketAddr::new(info.address, info.port)
|
||||
}
|
||||
|
||||
/// An id of the bridge's own for a request it makes: concurrent messages can make one to the
|
||||
/// same server at once, and a server refuses an id that is already in flight.
|
||||
fn own_id(kind: &str) -> String {
|
||||
static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
||||
format!("__openidea_{kind}_{}__", NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed))
|
||||
}
|
||||
|
||||
/// How long a server has to answer a probe or take a cancellation.
|
||||
const PROBE_WAIT: std::time::Duration = std::time::Duration::from_secs(2);
|
||||
|
||||
/// Sends a cancellation to every server at once, since the call may run in any of them (its
|
||||
/// `projectPath` picks one); the answer of one that took it. A server that doesn't run the call
|
||||
/// keeps the id for a while, in case the call reaches it later. One that doesn't answer in
|
||||
/// time holds up neither the others nor the bridge.
|
||||
async fn cancel_everywhere(
|
||||
candidates: Vec<Discovery>,
|
||||
project: &Path,
|
||||
message: &Value,
|
||||
scope: &str,
|
||||
sent: &tokio::sync::mpsc::UnboundedSender<Value>,
|
||||
) -> Option<Answer> {
|
||||
let mut posts = tokio::task::JoinSet::new();
|
||||
for info in candidates {
|
||||
let (project, message, scope, sent) = (project.to_owned(), message.clone(), scope.to_owned(), sent.clone());
|
||||
posts.spawn(async move {
|
||||
tokio::time::timeout(PROBE_WAIT, post_one(&info, &project, &message, &scope, &sent)).await
|
||||
});
|
||||
}
|
||||
let mut accepted = None;
|
||||
while let Some(posted) = posts.join_next().await {
|
||||
if let Ok(Ok(Ok(answer))) = posted {
|
||||
accepted.get_or_insert(answer);
|
||||
}
|
||||
}
|
||||
accepted
|
||||
}
|
||||
|
||||
/// Picks the server for the connection's folder again when the one picked is gone or another
|
||||
/// server started since, as `initialize` picks it: the first of `candidates` (the one picked
|
||||
/// before leads) that serves the folder, else the first. Puts it first.
|
||||
async fn pick_again(candidates: &mut Vec<Discovery>, project: &Path, scope: &str, state: &Mutex<BridgeState>) {
|
||||
{
|
||||
let state = state.lock().unwrap();
|
||||
let kept = state.preferred.as_ref().is_some_and(|preferred| candidates.contains(preferred));
|
||||
if kept && candidates.iter().all(|c| state.picked_among.contains(c)) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
let mut chosen = 0;
|
||||
if candidates.len() > 1 {
|
||||
for (pos, info) in candidates.iter().enumerate() {
|
||||
if serves_project(info, project, scope).await {
|
||||
chosen = pos;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
let picked = candidates.remove(chosen);
|
||||
candidates.insert(0, picked);
|
||||
let mut state = state.lock().unwrap();
|
||||
state.preferred = Some(candidates[0].clone());
|
||||
state.picked_among = candidates.clone();
|
||||
}
|
||||
|
||||
/// Whether the server of `info` serves `project`: its `openidea/servesFolder` names a root.
|
||||
/// An IDE older than that method answers "method not found"; its `tools/list` answers "not
|
||||
/// open" for a folder it doesn't serve, so that answers instead. A server that doesn't answer
|
||||
/// in time doesn't serve it.
|
||||
async fn serves_project(info: &Discovery, project: &Path, scope: &str) -> bool {
|
||||
let probe = |method| serde_json::json!({ "jsonrpc": "2.0", "id": own_id("probe"), "method": method });
|
||||
let (discard, _) = tokio::sync::mpsc::unbounded_channel();
|
||||
let ask = async {
|
||||
let reply = match post_one(info, project, &probe(SERVES_FOLDER), scope, &discard).await {
|
||||
Ok(Answer::Body(StatusCode::OK, body)) => serde_json::from_slice::<Value>(&body).ok(),
|
||||
_ => None,
|
||||
};
|
||||
let Some(reply) = reply else { return false };
|
||||
if reply.pointer("/error/code").and_then(Value::as_i64) == Some(METHOD_NOT_FOUND) {
|
||||
return match post_one(info, project, &probe("tools/list"), scope, &discard).await {
|
||||
Ok(answer @ Answer::Body(StatusCode::OK, _)) => !is_not_open_reply(&answer),
|
||||
_ => false,
|
||||
};
|
||||
}
|
||||
reply.pointer("/result/root").is_some_and(Value::is_string)
|
||||
};
|
||||
tokio::time::timeout(PROBE_WAIT, ask).await.unwrap_or(false)
|
||||
}
|
||||
|
||||
fn is_not_open_reply(answer: &Answer) -> bool {
|
||||
@@ -253,7 +353,7 @@ async fn post_one(
|
||||
project.display()
|
||||
)
|
||||
};
|
||||
let at = SocketAddr::new(info.address, info.port);
|
||||
let at = address(info);
|
||||
let stream = tokio::net::TcpStream::connect(at).await.map_err(|_| not_running())?;
|
||||
let (mut sender, conn) = hyper::client::conn::http1::handshake(hyper_util::rt::TokioIo::new(stream))
|
||||
.await
|
||||
|
||||
@@ -5,7 +5,7 @@ use ide_mcp::{Discovery, McpServer, ServerOptions, Tool, ToolCallError, ToolRegi
|
||||
use serde_json::{Value, json};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt};
|
||||
|
||||
struct Registry {
|
||||
project: PathBuf,
|
||||
@@ -28,6 +28,10 @@ impl ToolRegistry for Registry {
|
||||
}])
|
||||
}
|
||||
|
||||
fn tools_without_project(&self) -> Vec<Tool> {
|
||||
vec![named("everything")]
|
||||
}
|
||||
|
||||
fn call(
|
||||
&self,
|
||||
project: &Path,
|
||||
@@ -48,6 +52,18 @@ impl ToolRegistry for Registry {
|
||||
}
|
||||
}
|
||||
|
||||
/// A read-only tool with no arguments.
|
||||
fn named(name: &str) -> Tool {
|
||||
Tool {
|
||||
name: name.into(),
|
||||
description: format!("The tool {name}"),
|
||||
input_schema: json!({ "type": "object" }),
|
||||
read_only: true,
|
||||
destructive: false,
|
||||
output_schema: None,
|
||||
}
|
||||
}
|
||||
|
||||
struct Setup {
|
||||
_tmp: tempfile::TempDir,
|
||||
project: PathBuf,
|
||||
@@ -215,25 +231,30 @@ async fn requests_without_the_token_or_from_web_pages_are_refused() {
|
||||
async fn folders_that_are_not_open_are_named_in_the_error() {
|
||||
let s = setup();
|
||||
let elsewhere = s.project.parent().unwrap().join("elsewhere");
|
||||
let header = format!("X-OpenIDEA-Project: {}", elsewhere.display());
|
||||
let (status, body) =
|
||||
post(&s, "/mcp", &[&bearer(&s), &header], &json!({"jsonrpc":"2.0","id":3,"method":"tools/list"})).await;
|
||||
assert_eq!(status, 200);
|
||||
let reply: Value = serde_json::from_str(&body).unwrap();
|
||||
assert!(reply["error"]["message"].as_str().unwrap().contains("isn't open in OpenIDEA"));
|
||||
// The connection's folder isn't open: the list is the one without a project, and a call
|
||||
// that names no project of its own is refused with the folder named.
|
||||
let list = rpc_for(&s, &elsewhere, "tools/list", json!({})).await;
|
||||
assert_eq!(list["result"]["tools"][0]["name"], "everything", "{list}");
|
||||
let call = rpc_for(&s, &elsewhere, "tools/call", json!({ "name": "echo" })).await;
|
||||
assert_eq!(call["error"]["code"], -32001, "{call}");
|
||||
let message = call["error"]["message"].as_str().unwrap();
|
||||
assert!(message.contains("isn't open in OpenIDEA") && message.contains(elsewhere.to_str().unwrap()), "{message}");
|
||||
// No folder named and one window: that window's project lists its tools.
|
||||
let (_, body) = post(&s, "/mcp", &[&bearer(&s)], &json!({"jsonrpc":"2.0","id":3,"method":"tools/list"})).await;
|
||||
assert!(serde_json::from_str::<Value>(&body).unwrap()["result"]["tools"].is_array());
|
||||
assert_eq!(serde_json::from_str::<Value>(&body).unwrap()["result"]["tools"][0]["name"], "echo");
|
||||
}
|
||||
|
||||
/// One project open in a window and the folders served without a window.
|
||||
/// One project open in a window, the folders served without a window and, optionally, the
|
||||
/// root of a window on a remote host (which has no tools here).
|
||||
struct WithBackground {
|
||||
open: PathBuf,
|
||||
background: Vec<PathBuf>,
|
||||
remote: Option<PathBuf>,
|
||||
}
|
||||
|
||||
impl ToolRegistry for WithBackground {
|
||||
fn projects(&self) -> Vec<PathBuf> {
|
||||
vec![self.open.clone()]
|
||||
std::iter::once(self.open.clone()).chain(self.remote.clone()).collect()
|
||||
}
|
||||
/// The innermost served folder containing `path`, strictly inside `within`, as the
|
||||
/// background policy answers.
|
||||
@@ -242,7 +263,13 @@ impl ToolRegistry for WithBackground {
|
||||
let served = self.background.iter().filter(|root| path.starts_with(root)).filter(inside);
|
||||
served.max_by_key(|root| root.components().count()).cloned()
|
||||
}
|
||||
fn tools_without_project(&self) -> Vec<Tool> {
|
||||
vec![named("anything")]
|
||||
}
|
||||
fn tools(&self, project: &Path) -> Result<Vec<Tool>, String> {
|
||||
if self.remote.as_deref() == Some(project) {
|
||||
return Err("project is on a remote host".into());
|
||||
}
|
||||
Ok(vec![Tool {
|
||||
name: "where".into(),
|
||||
description: format!("Names {}", project.display()),
|
||||
@@ -257,20 +284,23 @@ impl ToolRegistry for WithBackground {
|
||||
}
|
||||
}
|
||||
|
||||
/// Stops the server of `s` and serves `registry` in its place.
|
||||
fn restart(s: &mut Setup, registry: impl ToolRegistry) {
|
||||
s.server.take().unwrap().stop();
|
||||
let runtime = tokio::runtime::Handle::current();
|
||||
s.server = Some(McpServer::start_with(Arc::new(registry), None, &runtime, ServerOptions::default()).unwrap());
|
||||
}
|
||||
|
||||
/// The server over [`WithBackground`] serving the `served` folders, relative to the folder
|
||||
/// that holds the open project; the folder `inventory` next to the open project.
|
||||
fn setup_with_background(served: &[&str]) -> (Setup, PathBuf) {
|
||||
let mut s = setup();
|
||||
s.server.take().unwrap().stop();
|
||||
let base = s.project.parent().unwrap().to_path_buf();
|
||||
let inventory = base.join("inventory");
|
||||
std::fs::create_dir_all(inventory.join("src")).unwrap();
|
||||
let background = served.iter().map(|folder| base.join(folder).components().collect()).collect();
|
||||
let registry = WithBackground { open: s.project.clone(), background };
|
||||
s.server = Some(
|
||||
McpServer::start_with(Arc::new(registry), None, &tokio::runtime::Handle::current(), ServerOptions::default())
|
||||
.unwrap(),
|
||||
);
|
||||
let registry = WithBackground { open: s.project.clone(), background, remote: None };
|
||||
restart(&mut s, registry);
|
||||
(s, inventory)
|
||||
}
|
||||
|
||||
@@ -291,6 +321,7 @@ async fn a_folder_served_in_the_background_answers_initialize_list_and_call() {
|
||||
assert!(instructions.contains(inventory.to_str().unwrap()), "{instructions}");
|
||||
// Clients that load tool descriptions lazily still learn to establish the workspace first (#5751).
|
||||
assert!(instructions.contains("first project-related operation in a session, call `get_workspace_roots`"));
|
||||
assert!(!instructions.contains("no project of its own"), "{instructions}");
|
||||
let list = rpc_for(&s, &inside, "tools/list", json!({})).await;
|
||||
assert_eq!(list["result"]["tools"][0]["description"], format!("Names {}", inventory.display()), "{list}");
|
||||
let call = rpc_for(&s, &inside, "tools/call", json!({ "name": "where" })).await;
|
||||
@@ -334,16 +365,41 @@ async fn the_innermost_project_answers_whether_a_window_has_it_open_or_it_is_ser
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_folder_that_is_neither_open_nor_served_in_the_background_says_where_to_turn_it_on() {
|
||||
let (s, inventory) = setup_with_background(&[]);
|
||||
for (method, params) in [("tools/list", json!({})), ("tools/call", json!({ "name": "where" }))] {
|
||||
let reply = rpc_for(&s, &inventory, method, params).await;
|
||||
assert_eq!(reply["error"]["code"], -32001, "{method}: {reply}");
|
||||
let message = reply["error"]["message"].as_str().unwrap();
|
||||
assert!(message.contains("isn't open in OpenIDEA and isn't served in the background"), "{message}");
|
||||
assert!(message.contains("Settings › Agents › IDE MCP Server"), "{message}");
|
||||
assert!(message.contains(inventory.to_str().unwrap()) && message.contains(s.project.to_str().unwrap()));
|
||||
}
|
||||
let list = rpc_for(&s, &inventory, "tools/list", json!({})).await;
|
||||
assert_eq!(list["result"]["tools"][0]["name"], "anything", "{list}");
|
||||
let reply = rpc_for(&s, &inventory, "tools/call", json!({ "name": "where" })).await;
|
||||
assert_eq!(reply["error"]["code"], -32001, "{reply}");
|
||||
let message = reply["error"]["message"].as_str().unwrap();
|
||||
assert!(message.contains("isn't open in OpenIDEA and isn't served in the background"), "{message}");
|
||||
assert!(message.contains("Settings › Agents › IDE MCP Server"), "{message}");
|
||||
assert!(message.contains(inventory.to_str().unwrap()) && message.contains(s.project.to_str().unwrap()));
|
||||
let init = rpc_for(&s, &inventory, "initialize", json!({})).await;
|
||||
assert!(init["result"]["instructions"].is_string(), "initialize answers without a project: {init}");
|
||||
let instructions = init["result"]["instructions"].as_str().unwrap();
|
||||
assert!(
|
||||
instructions.contains("pass `projectPath`, a folder inside a project OpenIDEA serves, in every call"),
|
||||
"{instructions}"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn serves_folder_names_the_project_that_answers_for_the_connection_folder() {
|
||||
let (mut s, inventory) = setup_with_background(&[]);
|
||||
let base = s.project.parent().unwrap().to_owned();
|
||||
let remote = base.join("remote");
|
||||
let registry =
|
||||
WithBackground { open: s.project.clone(), background: vec![inventory.clone()], remote: Some(remote.clone()) };
|
||||
restart(&mut s, registry);
|
||||
let cases = [
|
||||
(s.project.join("src"), json!(s.project)),
|
||||
(inventory.join("src"), json!(inventory)),
|
||||
(base.join("elsewhere"), Value::Null),
|
||||
// A remote window's root is that host's to serve.
|
||||
(remote, Value::Null),
|
||||
];
|
||||
for (folder, root) in cases {
|
||||
let reply = rpc_for(&s, &folder, "openidea/servesFolder", json!({})).await;
|
||||
assert_eq!(reply["result"], json!({ "root": root }), "{}: {reply}", folder.display());
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
@@ -413,6 +469,9 @@ async fn routing_an_argument_overrides_the_header_and_ambiguity_lists_projects()
|
||||
fn tools(&self, _: &Path) -> Result<Vec<Tool>, String> {
|
||||
Ok(Vec::new())
|
||||
}
|
||||
fn tools_without_project(&self) -> Vec<Tool> {
|
||||
vec![named("anywhere")]
|
||||
}
|
||||
fn call(
|
||||
&self,
|
||||
project: &Path,
|
||||
@@ -436,8 +495,14 @@ async fn routing_an_argument_overrides_the_header_and_ambiguity_lists_projects()
|
||||
)
|
||||
.unwrap(),
|
||||
);
|
||||
// No folder named and two windows: the list without a project, and a call has to name one.
|
||||
let (_, body) = post(&s, "/mcp", &[&bearer(&s)], &json!({"jsonrpc":"2.0","id":1,"method":"tools/list"})).await;
|
||||
let list: Value = serde_json::from_str(&body).unwrap();
|
||||
assert_eq!(list["result"]["tools"][0]["name"], "anywhere", "{list}");
|
||||
let call = json!({"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"where"}});
|
||||
let (_, body) = post(&s, "/mcp", &[&bearer(&s)], &call).await;
|
||||
let reply: Value = serde_json::from_str(&body).unwrap();
|
||||
assert_eq!(reply["error"]["code"], -32602, "{reply}");
|
||||
let message = reply["error"]["message"].as_str().unwrap();
|
||||
assert!(message.contains(s.project.to_str().unwrap()) && message.contains(second.to_str().unwrap()));
|
||||
let result = rpc(&s, "tools/call", json!({"name":"where","arguments":{"projectPath":second.join("nested")}})).await;
|
||||
@@ -624,3 +689,370 @@ async fn multiple_servers_sharing_app_data_route_by_project_and_survive_one_clos
|
||||
server_a.stop();
|
||||
assert!(!discovery.exists());
|
||||
}
|
||||
|
||||
/// The stdio bridge started in `folder`, driven as MCP clients drive it: each request goes
|
||||
/// out once the answer to the one before has come back.
|
||||
struct Client {
|
||||
input: tokio::io::DuplexStream,
|
||||
output: tokio::io::Lines<tokio::io::BufReader<tokio::io::DuplexStream>>,
|
||||
bridge: tokio::task::JoinHandle<std::io::Result<()>>,
|
||||
id: u64,
|
||||
}
|
||||
|
||||
impl Client {
|
||||
fn start(discovery: &Path, folder: &Path) -> Self {
|
||||
let (input, bridge_input) = tokio::io::duplex(1 << 16);
|
||||
let (bridge_output, output) = tokio::io::duplex(1 << 16);
|
||||
let (discovery, folder) = (discovery.to_owned(), folder.to_owned());
|
||||
let bridge = tokio::spawn(async move {
|
||||
stdio::bridge(&discovery, &folder, tokio::io::BufReader::new(bridge_input), bridge_output).await
|
||||
});
|
||||
Self { input, output: tokio::io::BufReader::new(output).lines(), bridge, id: 0 }
|
||||
}
|
||||
|
||||
/// Sends a request without waiting for its answer; its id.
|
||||
async fn send(&mut self, method: &str, params: Value) -> u64 {
|
||||
self.id += 1;
|
||||
self.notify(json!({ "jsonrpc": "2.0", "id": self.id, "method": method, "params": params })).await;
|
||||
self.id
|
||||
}
|
||||
|
||||
async fn notify(&mut self, message: Value) {
|
||||
self.input.write_all(format!("{message}\n").as_bytes()).await.unwrap();
|
||||
}
|
||||
|
||||
async fn answer(&mut self, id: u64) -> Value {
|
||||
let answer = async {
|
||||
loop {
|
||||
let line = self.output.next_line().await.unwrap().expect("the bridge answers");
|
||||
let reply: Value = serde_json::from_str(&line).unwrap();
|
||||
if reply["id"] == id {
|
||||
return reply;
|
||||
}
|
||||
}
|
||||
};
|
||||
tokio::time::timeout(std::time::Duration::from_secs(10), answer).await.expect("an answer in time")
|
||||
}
|
||||
|
||||
async fn ask(&mut self, method: &str, params: Value) -> Value {
|
||||
let id = self.send(method, params).await;
|
||||
self.answer(id).await
|
||||
}
|
||||
|
||||
async fn close(self) {
|
||||
let Self { input, output, bridge, .. } = self;
|
||||
drop(input);
|
||||
bridge.await.unwrap().unwrap();
|
||||
drop(output);
|
||||
}
|
||||
}
|
||||
|
||||
fn start_in(discovery: &Path, registry: impl ToolRegistry) -> McpServer {
|
||||
let runtime = tokio::runtime::Handle::current();
|
||||
McpServer::start_with(Arc::new(registry), Some(discovery.to_owned()), &runtime, ServerOptions::default()).unwrap()
|
||||
}
|
||||
|
||||
/// A temporary folder holding `folders` (each with a `src`), and the discovery file of the
|
||||
/// servers that share its data directory.
|
||||
fn layout(folders: &[&str]) -> (tempfile::TempDir, PathBuf, PathBuf) {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(tmp.path()).unwrap();
|
||||
for folder in folders {
|
||||
std::fs::create_dir_all(base.join(folder).join("src")).unwrap();
|
||||
}
|
||||
let discovery = discovery_path(&base.join("app-data"));
|
||||
(tmp, base, discovery)
|
||||
}
|
||||
|
||||
impl WithBackground {
|
||||
/// A window on `open` and `background` served without one.
|
||||
fn serving(open: &Path, background: &Path) -> Self {
|
||||
Self { open: open.to_owned(), background: vec![background.to_owned()], remote: None }
|
||||
}
|
||||
}
|
||||
|
||||
/// What an MCP client started in a folder of `proj-b` gets when two servers share the
|
||||
/// discovery directory: A has `proj-a` in a window, B serves `proj-b` in the background.
|
||||
/// Each order makes the other server the one in `server.json`.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn the_bridge_sends_a_folder_to_the_process_that_serves_it_in_either_order() {
|
||||
for b_first in [false, true] {
|
||||
let (_tmp, base, discovery) = layout(&["proj-a", "proj-b", "proj-c"]);
|
||||
let (proj_a, proj_b, proj_c) = (base.join("proj-a"), base.join("proj-b"), base.join("proj-c"));
|
||||
let a = || Registry { project: proj_a.clone() };
|
||||
let b = || WithBackground::serving(&proj_c, &proj_b);
|
||||
let servers = if b_first {
|
||||
[start_in(&discovery, b()), start_in(&discovery, a())]
|
||||
} else {
|
||||
[start_in(&discovery, a()), start_in(&discovery, b())]
|
||||
};
|
||||
|
||||
let mut client = Client::start(&discovery, &proj_b.join("src"));
|
||||
let init = client.ask("initialize", json!({ "protocolVersion": "2025-06-18" })).await;
|
||||
let instructions = init["result"]["instructions"].as_str().unwrap();
|
||||
assert!(instructions.contains(proj_b.to_str().unwrap()), "b_first {b_first}: {instructions}");
|
||||
let list = client.ask("tools/list", json!({})).await;
|
||||
assert_eq!(list["result"]["tools"][0]["description"], format!("Names {}", proj_b.display()), "{list}");
|
||||
let call = client.ask("tools/call", json!({ "name": "where" })).await;
|
||||
assert_eq!(call["result"]["structuredContent"]["project"], json!(proj_b), "{call}");
|
||||
client.close().await;
|
||||
for server in servers {
|
||||
server.stop();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A client started in `work`, a folder neither server serves: the tools of the server
|
||||
/// `initialize` picked, and each call goes where its `projectPath` is served.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_bridge_in_a_folder_no_process_serves_lists_tools_and_routes_each_call_by_project_path() {
|
||||
for b_first in [false, true] {
|
||||
let (_tmp, base, discovery) = layout(&["proj-a", "proj-c", "work/repo"]);
|
||||
let (proj_a, proj_c, work) = (base.join("proj-a"), base.join("proj-c"), base.join("work"));
|
||||
let repo = work.join("repo");
|
||||
let a = || Registry { project: proj_a.clone() };
|
||||
let b = || WithBackground::serving(&proj_c, &repo);
|
||||
// The server started last is in `server.json`; with neither serving the folder,
|
||||
// `initialize` settles on it.
|
||||
let (servers, listed) = if b_first {
|
||||
([start_in(&discovery, b()), start_in(&discovery, a())], "everything")
|
||||
} else {
|
||||
([start_in(&discovery, a()), start_in(&discovery, b())], "anything")
|
||||
};
|
||||
|
||||
let mut client = Client::start(&discovery, &work);
|
||||
let init = client.ask("initialize", json!({ "protocolVersion": "2025-06-18" })).await;
|
||||
let instructions = init["result"]["instructions"].as_str().unwrap();
|
||||
assert!(instructions.contains("no project of its own"), "{instructions}");
|
||||
let list = client.ask("tools/list", json!({})).await;
|
||||
assert_eq!(list["result"]["tools"][0]["name"], listed, "b_first {b_first}: {list}");
|
||||
|
||||
let in_repo = json!({ "name": "echo", "arguments": { "text": "x", "projectPath": repo.join("src") } });
|
||||
let call = client.ask("tools/call", in_repo).await;
|
||||
assert_eq!(call["result"]["structuredContent"]["project"], json!(repo), "{call}");
|
||||
let in_a = json!({ "name": "echo", "arguments": { "text": "x", "projectPath": proj_a } });
|
||||
let call = client.ask("tools/call", in_a).await;
|
||||
assert_eq!(call["result"]["content"][0]["text"], format!("x in {}", proj_a.display()), "{call}");
|
||||
let unnamed = client.ask("tools/call", json!({ "name": "echo", "arguments": { "text": "x" } })).await;
|
||||
assert_eq!(unnamed["error"]["code"], -32001, "{unnamed}");
|
||||
// A call sent to the other server doesn't move the connection there.
|
||||
let list = client.ask("tools/list", json!({})).await;
|
||||
assert_eq!(list["result"]["tools"][0]["name"], listed, "b_first {b_first}: {list}");
|
||||
client.close().await;
|
||||
for server in servers {
|
||||
server.stop();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The server `initialize` picked stops, or one that serves the folder starts later: the
|
||||
/// next message picks again, as `initialize` does.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn the_bridge_picks_the_server_again_when_the_servers_change() {
|
||||
let (_tmp, base, discovery) = layout(&["proj-a", "proj-b", "proj-c"]);
|
||||
let (proj_a, proj_b, proj_c) = (base.join("proj-a"), base.join("proj-b"), base.join("proj-c"));
|
||||
let a = || Registry { project: proj_a.clone() };
|
||||
let b = || WithBackground::serving(&proj_c, &proj_b);
|
||||
let serving_b = format!("Names {}", proj_b.display());
|
||||
|
||||
// Only A runs at `initialize`; B starts afterwards.
|
||||
let server_a = start_in(&discovery, a());
|
||||
let mut client = Client::start(&discovery, &proj_b.join("src"));
|
||||
client.ask("initialize", json!({ "protocolVersion": "2025-06-18" })).await;
|
||||
let server_b = start_in(&discovery, b());
|
||||
let list = client.ask("tools/list", json!({})).await;
|
||||
assert_eq!(list["result"]["tools"][0]["description"], serving_b, "a server started later: {list}");
|
||||
|
||||
// B restarts, and A restarts after it, so A is first in the discovery file.
|
||||
server_b.stop();
|
||||
let server_b = start_in(&discovery, b());
|
||||
server_a.stop();
|
||||
let server_a = start_in(&discovery, a());
|
||||
let list = client.ask("tools/list", json!({})).await;
|
||||
assert_eq!(list["result"]["tools"][0]["description"], serving_b, "the picked server restarted: {list}");
|
||||
client.close().await;
|
||||
server_a.stop();
|
||||
server_b.stop();
|
||||
}
|
||||
|
||||
/// A server restarted on the port it had (a fixed port in the settings) is another server: one
|
||||
/// that didn't serve the folder may serve it now.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn the_bridge_picks_the_server_again_after_a_restart_on_the_same_port() {
|
||||
let (_tmp, base, discovery) = layout(&["proj-a", "proj-b", "proj-c"]);
|
||||
let (proj_a, proj_b, proj_c) = (base.join("proj-a"), base.join("proj-b"), base.join("proj-c"));
|
||||
// Neither serves `proj-b` at `initialize`, which settles on A, the server started last.
|
||||
let server_b = start_in(&discovery, WithBackground { open: proj_c.clone(), background: Vec::new(), remote: None });
|
||||
let port = server_b.port();
|
||||
let server_a = start_in(&discovery, Registry { project: proj_a.clone() });
|
||||
let mut client = Client::start(&discovery, &proj_b.join("src"));
|
||||
client.ask("initialize", json!({ "protocolVersion": "2025-06-18" })).await;
|
||||
let list = client.ask("tools/list", json!({})).await;
|
||||
assert_eq!(list["result"]["tools"][0]["name"], "everything", "{list}");
|
||||
|
||||
server_b.stop();
|
||||
// stop signals the accept task; the listener is closed asynchronously. Wait for
|
||||
// the old port to be released, as the IDE does before restarting its server.
|
||||
tokio::time::timeout(std::time::Duration::from_secs(5), async {
|
||||
while std::net::TcpListener::bind(("127.0.0.1", port)).is_err() {
|
||||
tokio::time::sleep(std::time::Duration::from_millis(20)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("the stopped server should release its port");
|
||||
let server_b = McpServer::start_with(
|
||||
Arc::new(WithBackground::serving(&proj_c, &proj_b)),
|
||||
Some(discovery.clone()),
|
||||
&tokio::runtime::Handle::current(),
|
||||
ServerOptions { port: Some(port), ..Default::default() },
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(server_b.port(), port, "{:?}", server_b.port_unavailable());
|
||||
let list = client.ask("tools/list", json!({})).await;
|
||||
assert_eq!(list["result"]["tools"][0]["description"], format!("Names {}", proj_b.display()), "{list}");
|
||||
client.close().await;
|
||||
server_a.stop();
|
||||
server_b.stop();
|
||||
}
|
||||
|
||||
/// Holds every call until it is cancelled: a window on `open`, `background` served without one.
|
||||
struct Holding {
|
||||
open: PathBuf,
|
||||
background: PathBuf,
|
||||
}
|
||||
|
||||
impl ToolRegistry for Holding {
|
||||
fn projects(&self) -> Vec<PathBuf> {
|
||||
vec![self.open.clone()]
|
||||
}
|
||||
fn resolve(&self, path: &Path, _: Option<&Path>) -> Option<PathBuf> {
|
||||
path.starts_with(&self.background).then(|| self.background.clone())
|
||||
}
|
||||
fn tools(&self, _: &Path) -> Result<Vec<Tool>, String> {
|
||||
Ok(vec![named("hold")])
|
||||
}
|
||||
fn call(&self, _: &Path, _: &str, _: &str, cancel: ide_mcp::CancellationToken) -> Result<String, ToolCallError> {
|
||||
tokio::runtime::Handle::current().block_on(cancel.cancelled());
|
||||
Err(ToolCallError::Failed("cancelled".into()))
|
||||
}
|
||||
}
|
||||
|
||||
/// The connection is A's, and a call whose `projectPath` B serves runs in B: its
|
||||
/// cancellation reaches B.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_cancellation_reaches_the_server_that_runs_the_call() {
|
||||
let (_tmp, base, discovery) = layout(&["proj-a", "proj-b", "proj-c"]);
|
||||
let (proj_a, proj_b, proj_c) = (base.join("proj-a"), base.join("proj-b"), base.join("proj-c"));
|
||||
let server_b = start_in(&discovery, Holding { open: proj_c, background: proj_b.clone() });
|
||||
let server_a = start_in(&discovery, Registry { project: proj_a.clone() });
|
||||
|
||||
let mut client = Client::start(&discovery, &proj_a);
|
||||
let init = client.ask("initialize", json!({ "protocolVersion": "2025-06-18" })).await;
|
||||
assert!(init["result"]["instructions"].as_str().unwrap().contains(proj_a.to_str().unwrap()), "{init}");
|
||||
let call = client.send("tools/call", json!({ "name": "hold", "arguments": { "projectPath": proj_b } })).await;
|
||||
client
|
||||
.notify(json!({ "jsonrpc": "2.0", "method": "notifications/cancelled", "params": { "requestId": call } }))
|
||||
.await;
|
||||
let answer = client.answer(call).await;
|
||||
assert_eq!(answer["result"]["isError"], true, "{answer}");
|
||||
client.close().await;
|
||||
server_a.stop();
|
||||
server_b.stop();
|
||||
}
|
||||
|
||||
/// An OpenIDEA older than `openidea/servesFolder`, registered in `discovery`: it answers
|
||||
/// "method not found" to that, and "not open" to `tools/list` and `tools/call` for a folder
|
||||
/// outside `serves`.
|
||||
async fn fake_older_ide(discovery: &Path, serves: Option<PathBuf>) -> tokio::task::JoinHandle<()> {
|
||||
use http_body_util::{BodyExt, Full};
|
||||
let listener = tokio::net::TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
let server = tokio::spawn(async move {
|
||||
while let Ok((stream, _)) = listener.accept().await {
|
||||
let serves = serves.clone();
|
||||
let service = hyper::service::service_fn(move |request: hyper::Request<hyper::body::Incoming>| {
|
||||
let serves = serves.clone();
|
||||
async move {
|
||||
let query = request.uri().query().unwrap_or_default().to_owned();
|
||||
let folder = query.strip_prefix("project=").unwrap_or_default();
|
||||
let folder =
|
||||
PathBuf::from(percent_encoding::percent_decode_str(folder).decode_utf8_lossy().as_ref());
|
||||
let body = request.into_body().collect().await.unwrap().to_bytes();
|
||||
let message: Value = serde_json::from_slice(&body).unwrap();
|
||||
let served = serves.as_ref().is_some_and(|root| folder.starts_with(root));
|
||||
let id = message["id"].clone();
|
||||
let reply = match message["method"].as_str().unwrap_or_default() {
|
||||
_ if id.is_null() => None,
|
||||
"initialize" => Some(json!({ "jsonrpc": "2.0", "id": id, "result": {
|
||||
"protocolVersion": "2025-06-18", "capabilities": { "tools": {} },
|
||||
"serverInfo": { "name": "OpenIDEA", "version": "0.1.0" },
|
||||
"instructions": "an older OpenIDEA" } })),
|
||||
"tools/list" if served => {
|
||||
Some(json!({ "jsonrpc": "2.0", "id": id, "result": { "tools": [] } }))
|
||||
}
|
||||
"tools/call" if served => Some(json!({ "jsonrpc": "2.0", "id": id, "result": {
|
||||
"content": [{ "type": "text", "text": "older" }], "isError": false } })),
|
||||
"tools/list" | "tools/call" => Some(
|
||||
json!({ "jsonrpc": "2.0", "id": id, "error": { "code": -32001, "message": "not open" } }),
|
||||
),
|
||||
_ => Some(
|
||||
json!({ "jsonrpc": "2.0", "id": id, "error": { "code": -32601, "message": "no method" } }),
|
||||
),
|
||||
};
|
||||
let response = match reply {
|
||||
Some(reply) => hyper::Response::builder()
|
||||
.header("content-type", "application/json")
|
||||
.body(Full::new(bytes::Bytes::from(reply.to_string()))),
|
||||
None => hyper::Response::builder().status(202).body(Full::new(bytes::Bytes::new())),
|
||||
};
|
||||
Ok::<_, std::convert::Infallible>(response.unwrap())
|
||||
}
|
||||
});
|
||||
tokio::spawn(async move {
|
||||
let io = hyper_util::rt::TokioIo::new(stream);
|
||||
let _ = hyper::server::conn::http1::Builder::new().serve_connection(io, service).await;
|
||||
});
|
||||
}
|
||||
});
|
||||
// Written once it listens, so the stale-entry sweep of the next server keeps it.
|
||||
let info = Discovery {
|
||||
address: std::net::Ipv4Addr::LOCALHOST.into(),
|
||||
port,
|
||||
token: "test-token-older".into(),
|
||||
pid: std::process::id(),
|
||||
version: "0.1.0".into(),
|
||||
};
|
||||
info.write(discovery).unwrap();
|
||||
server
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn an_older_ide_without_serves_folder_is_probed_with_tools_list() {
|
||||
for older_serves in [false, true] {
|
||||
let (_tmp, base, discovery) = layout(&["proj-c", "inventory"]);
|
||||
let (proj_c, folder) = (base.join("proj-c"), base.join("inventory"));
|
||||
// Either way the server that doesn't serve the folder is in `server.json`.
|
||||
let (older, real) = if older_serves {
|
||||
let older = fake_older_ide(&discovery, Some(folder.clone())).await;
|
||||
(older, start_in(&discovery, Registry { project: proj_c.clone() }))
|
||||
} else {
|
||||
let real = start_in(&discovery, WithBackground::serving(&proj_c, &folder));
|
||||
(fake_older_ide(&discovery, None).await, real)
|
||||
};
|
||||
|
||||
let mut client = Client::start(&discovery, &folder.join("src"));
|
||||
let init = client.ask("initialize", json!({ "protocolVersion": "2025-06-18" })).await;
|
||||
let instructions = init["result"]["instructions"].as_str().unwrap();
|
||||
let expected = if older_serves { "an older OpenIDEA".to_owned() } else { folder.display().to_string() };
|
||||
assert!(instructions.contains(&expected), "older_serves {older_serves}: {instructions}");
|
||||
let call = client.ask("tools/call", json!({ "name": "where" })).await;
|
||||
let answered = match older_serves {
|
||||
true => call["result"]["content"][0]["text"] == "older",
|
||||
false => call["result"]["structuredContent"]["project"] == json!(folder),
|
||||
};
|
||||
assert!(answered, "older_serves {older_serves}: {call}");
|
||||
client.close().await;
|
||||
real.stop();
|
||||
older.abort();
|
||||
}
|
||||
}
|
||||
@@ -225,7 +225,9 @@ pub fn container_config(config: &RunConfig, run: &ContainerRun) -> IdeResult<Run
|
||||
args.push("--no-TTY".into());
|
||||
}
|
||||
}
|
||||
RunTargetKind::Ssh => return Err(IdeError::internal("an SSH target does not run in a container")),
|
||||
RunTargetKind::Ssh | RunTargetKind::Wsl => {
|
||||
return Err(IdeError::internal("this run target does not run in a container"));
|
||||
}
|
||||
}
|
||||
args.extend(["--name".into(), run.name.to_owned(), "--label".into(), format!("openidea.run={}", config.id)]);
|
||||
args.extend(["--workdir".into(), command.cwd.clone()]);
|
||||
@@ -341,7 +343,7 @@ pub fn python_probe_args(target: &RunTarget, root: &Path, name: &str, code: &str
|
||||
}
|
||||
args.extend(["run", "--no-deps", "--no-TTY"].map(String::from));
|
||||
}
|
||||
RunTargetKind::Ssh => {
|
||||
RunTargetKind::Ssh | RunTargetKind::Wsl => {
|
||||
return Err(IdeError::invalid(format!("Run target '{}' is not a container", target.name)));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! Remote work over SSH: SFTP deployment ([`deploy`], [`mapping`]) and run
|
||||
//! configurations on run targets ([`target`]; Docker and Compose ones in [`docker`]).
|
||||
//! configurations on run targets ([`target`]; Docker and Compose ones in [`docker`], WSL
|
||||
//! ones in [`wsl`]).
|
||||
|
||||
pub mod container_tunnel;
|
||||
pub mod deploy;
|
||||
@@ -10,6 +11,7 @@ pub mod mapping;
|
||||
pub mod service;
|
||||
pub mod target;
|
||||
pub mod upload;
|
||||
pub mod wsl;
|
||||
|
||||
pub use deploy::{
|
||||
Deployment, DeploymentCoverage, SyncAction, SyncEntry, SyncStatus, SyncStep, TransferReport, coverage,
|
||||
|
||||
@@ -438,7 +438,7 @@ impl RemoteService {
|
||||
let target_id = config.extras.target.as_deref().unwrap_or_default();
|
||||
let target = run_target(settings, target_id)?;
|
||||
if target.kind != ide_core::remote_settings::RunTargetKind::Ssh {
|
||||
return Err(IdeError::internal("container run targets start as local runs of the docker CLI"));
|
||||
return Err(IdeError::internal("container and WSL run targets start as local runs"));
|
||||
}
|
||||
let session = self.ssh.session(&target.ssh_config).await?;
|
||||
let fs = RemoteFs::new(session.sftp().await?).with_shell(session.clone());
|
||||
|
||||
@@ -72,7 +72,8 @@ fn replace_root(s: &str, root: &str, remote: &str) -> String {
|
||||
out.push_str(remote);
|
||||
if root.contains('\\') {
|
||||
let end = after
|
||||
.find(|c: char| c.is_whitespace() || matches!(c, ';' | ',' | '"' | '\''))
|
||||
// `:` too: past the drive letter, it only separates a POSIX path list.
|
||||
.find(|c: char| c.is_whitespace() || matches!(c, ';' | ':' | ',' | '"' | '\''))
|
||||
.unwrap_or(after.len());
|
||||
out.push_str(&after[..end].replace('\\', "/"));
|
||||
after = &after[end..];
|
||||
@@ -191,7 +192,7 @@ pub fn debugpy_probe(debug: &RemoteCommand, bootstrap: &str) -> String {
|
||||
/// `java` flags whose value is a path list that may point outside the project
|
||||
/// (`~/.m2` jars, `--module-path` entries): deployment sync only uploads the
|
||||
/// project root, so these entries need their own sync + rewrite (#2641).
|
||||
const PATH_LIST_FLAGS: [&str; 6] =
|
||||
pub(crate) const PATH_LIST_FLAGS: [&str; 6] =
|
||||
["-cp", "-classpath", "--class-path", "-p", "--module-path", "--upgrade-module-path"];
|
||||
|
||||
/// The separator of a `-cp` value on this (client) machine.
|
||||
@@ -635,6 +636,11 @@ mod tests {
|
||||
assert_eq!(replace_root("/work/proj2/x:/work/proj/y", "/work/proj", "/srv"), "/work/proj2/x:/srv/y");
|
||||
assert_eq!(replace_root("/work/proj", "/work/proj", "/srv"), "/srv");
|
||||
assert_eq!(replace_root(r"C:\p\src/a.py C:\p2", r"C:\p", "/srv"), r"/srv/src/a.py C:\p2");
|
||||
assert_eq!(
|
||||
replace_root(r"C:\work\proj:C:\work\proj\src", r"C:\work\proj", "/mnt/c/work/proj"),
|
||||
"/mnt/c/work/proj:/mnt/c/work/proj/src",
|
||||
"each root of a PYTHONPATH list"
|
||||
);
|
||||
}
|
||||
|
||||
/// Unix/Windows spellings of the same layout: one inside-root entry, one
|
||||
|
||||
@@ -0,0 +1,426 @@
|
||||
//! Run configurations on WSL run targets: rewritten into a local run of
|
||||
//! `wsl.exe -d <distro> --cd <dir> --exec <program> <args>`, with the project's paths
|
||||
//! and interpreters swapped for their Linux counterparts. The console, stdin, Stop and
|
||||
//! test parsers then work as for any local run.
|
||||
|
||||
use crate::target::remote_command;
|
||||
use ide_core::remote_settings::RunTarget;
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use ide_run::RunConfig;
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// Where the project is inside the target's distribution.
|
||||
pub fn project_root(target: &RunTarget, root: &Path) -> IdeResult<String> {
|
||||
match target.project_root.trim().trim_end_matches('/') {
|
||||
"" if target.project_root.trim().starts_with('/') => Ok("/".into()),
|
||||
"" => ide_core::wsl::linux_path(root, target.distro.trim()).ok_or_else(|| {
|
||||
IdeError::invalid(format!(
|
||||
"Run target '{}' can't reach {} from WSL: set the project's Linux path in Settings › Run Targets",
|
||||
target.name,
|
||||
root.display()
|
||||
))
|
||||
}),
|
||||
folder => Ok(folder.to_owned()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The file on this machine of a path a run in the target's distribution printed (a
|
||||
/// traceback line): in the project, on a drive under `/mnt/<drive>`, else in the
|
||||
/// distribution's own file system (`\\wsl.localhost\<distro>`).
|
||||
pub fn local_file(path: &str, target: &RunTarget, root: &Path) -> Option<PathBuf> {
|
||||
if !path.starts_with('/') {
|
||||
return None;
|
||||
}
|
||||
if let Ok(linux_root) = project_root(target, root) {
|
||||
let linux_root = linux_root.trim_end_matches('/');
|
||||
if let Some(rest) =
|
||||
path.strip_prefix(linux_root).filter(|r| r.is_empty() || r.starts_with('/') || linux_root.is_empty())
|
||||
{
|
||||
return Some(ide_core::wsl::path_parts(rest).into_iter().fold(root.to_path_buf(), |p, c| p.join(c)));
|
||||
}
|
||||
}
|
||||
Some(ide_core::wsl::windows_path(path, target.distro.trim()))
|
||||
}
|
||||
|
||||
fn is_java(command: &str) -> bool {
|
||||
let name = command.trim().rsplit(['/', '\\']).next().unwrap_or("");
|
||||
name.to_ascii_lowercase().trim_end_matches(".exe") == "java"
|
||||
}
|
||||
|
||||
/// The `-cp` / `--module-path` values of `java` arguments as the distribution reads them:
|
||||
/// each absolute entry outside the project through its `/mnt` path, joined with `:`.
|
||||
/// Entries in the project stay as they are: `remote_command` maps them onto its folder there.
|
||||
fn linux_path_lists(args: &[String], root: &Path, distro: &str) -> Vec<String> {
|
||||
let mut out = args.to_vec();
|
||||
for i in 1..out.len() {
|
||||
if !crate::target::PATH_LIST_FLAGS.contains(&out[i - 1].as_str()) || out[i].contains("${") {
|
||||
continue;
|
||||
}
|
||||
let entries: Vec<String> = out[i]
|
||||
.split(crate::target::classpath_separator())
|
||||
.filter(|e| !e.is_empty())
|
||||
.map(|e| {
|
||||
let path = Path::new(e);
|
||||
if path.starts_with(root) {
|
||||
return e.to_owned();
|
||||
}
|
||||
match path.is_absolute().then(|| ide_core::wsl::linux_path(path, distro)).flatten() {
|
||||
Some(linux) => linux,
|
||||
None => e.replace('\\', "/"),
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
out[i] = entries.join(":");
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The target's Python: its own, or `python3` on the distribution's `PATH`.
|
||||
pub fn python(target: &RunTarget) -> &str {
|
||||
match target.python.trim() {
|
||||
"" => "python3",
|
||||
python => python,
|
||||
}
|
||||
}
|
||||
|
||||
/// Run with `sh -c` in a distribution, the project's Linux folder as `$1`: prints the
|
||||
/// Pythons found there, one path a line.
|
||||
pub const FIND_PYTHONS: &str = r#"for p in "$(command -v python3)" "$(command -v python)" /usr/bin/python3* /usr/local/bin/python3* "$HOME"/.pyenv/versions/*/bin/python "$1/.venv/bin/python" "$1/venv/bin/python"; do case "$p" in *-config) continue ;; esac; [ -f "$p" ] && [ -x "$p" ] && echo "$p"; done; true"#;
|
||||
|
||||
/// The paths [`FIND_PYTHONS`] printed, without repeats and without the tools named after
|
||||
/// Python (`python3-pytest`, `python3.12-config`).
|
||||
pub fn parse_pythons(out: &str) -> Vec<String> {
|
||||
let interpreter = |path: &str| {
|
||||
let name = path.rsplit('/').next().unwrap_or("");
|
||||
let version = name.strip_prefix("python").unwrap_or("-");
|
||||
version.chars().all(|c| c.is_ascii_digit() || c == '.')
|
||||
};
|
||||
let mut found: Vec<String> = Vec::new();
|
||||
for line in out.lines().map(str::trim).filter(|l| l.starts_with('/') && interpreter(l)) {
|
||||
if !found.iter().any(|f| f == line) {
|
||||
found.push(line.to_owned());
|
||||
}
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
/// `config` as a local run of `wsl_exe` that runs it in the target's distribution.
|
||||
/// `file_env` holds the variables of the configuration's `.env` files, already read;
|
||||
/// `inherited_wslenv` is this machine's `WSLENV`, kept for the distribution.
|
||||
pub fn wsl_config(
|
||||
config: &RunConfig,
|
||||
target: &RunTarget,
|
||||
root: &Path,
|
||||
linux_root: &str,
|
||||
wsl_exe: &str,
|
||||
file_env: &BTreeMap<String, String>,
|
||||
inherited_wslenv: Option<&str>,
|
||||
) -> IdeResult<RunConfig> {
|
||||
let distro = target.distro.trim();
|
||||
if !ide_core::wsl::is_valid_distro(distro) {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"Run target '{}' has no WSL distribution; choose one in Settings › Run Targets",
|
||||
target.name
|
||||
)));
|
||||
}
|
||||
let mut command = if is_java(&config.command) {
|
||||
let mut java = config.clone();
|
||||
java.args = linux_path_lists(&config.args, root, distro);
|
||||
remote_command(&java, target, root, linux_root)
|
||||
} else {
|
||||
remote_command(config, target, root, linux_root)
|
||||
};
|
||||
// Outside the project `remote_command` falls back to the project folder: a folder of
|
||||
// this machine is reached through its own `/mnt` path instead.
|
||||
if let Some(dir) = config.cwd.as_ref().map(|d| d.to_path_buf()).filter(|d| d.is_absolute() && !d.starts_with(root))
|
||||
{
|
||||
command.cwd = ide_core::wsl::linux_path(&dir, distro).ok_or_else(|| {
|
||||
IdeError::invalid(format!(
|
||||
"Run target '{}' can't reach the working folder {} from WSL",
|
||||
target.name,
|
||||
dir.display()
|
||||
))
|
||||
})?;
|
||||
}
|
||||
let mut env = file_env.clone();
|
||||
if ide_run::is_python_kind(&config.kind) && !command.env.contains_key("PYTHONUNBUFFERED") {
|
||||
env.insert("PYTHONUNBUFFERED".into(), "1".into());
|
||||
}
|
||||
env.extend(command.env.clone());
|
||||
// The distribution keeps its own `PATH`: a value here is this machine's, or a `.env`
|
||||
// `PATH=$PATH:…` already expanded against it.
|
||||
env.remove("PATH");
|
||||
let mut args: Vec<String> = ["-d", distro, "--cd", &command.cwd, "--exec"].map(String::from).to_vec();
|
||||
// A Python run finds the console scripts next to the target's interpreter (a virtualenv's
|
||||
// `pytest`) first, as a local run with the project interpreter does.
|
||||
let scripts = (ide_run::is_python_kind(&config.kind) && target.python.trim().starts_with('/'))
|
||||
.then(|| target.python.trim().rsplit_once('/').map(|(dir, _)| dir.to_owned()))
|
||||
.flatten()
|
||||
.filter(|dir| !dir.is_empty());
|
||||
match (command.shell_line, scripts) {
|
||||
(Some(line), None) => args.extend(["sh".into(), "-c".into(), line]),
|
||||
(Some(line), Some(dir)) => args.extend(["sh".into(), "-c".into(), format!("PATH=\"$0:$PATH\"; {line}"), dir]),
|
||||
(None, None) => {
|
||||
args.push(command.program);
|
||||
args.extend(command.args);
|
||||
}
|
||||
(None, Some(dir)) => {
|
||||
args.extend(["sh".into(), "-c".into(), r#"PATH="$0:$PATH" exec "$@""#.into(), dir, command.program]);
|
||||
args.extend(command.args);
|
||||
}
|
||||
}
|
||||
// Values cross into the distribution through the environment (`WSLENV` lists the
|
||||
// names), so they stay out of the command line echoed in the console. The configuration's
|
||||
// own `WSLENV` entries (`FOO/p`) are kept with their flags.
|
||||
let own = env.remove("WSLENV");
|
||||
let mut wslenv: Vec<&str> = inherited_wslenv
|
||||
.into_iter()
|
||||
.chain(own.as_deref())
|
||||
.flat_map(|v| v.split(':'))
|
||||
.filter(|n| !n.is_empty())
|
||||
.collect();
|
||||
let listed = |name: &str, list: &[&str]| list.iter().any(|n| n.split('/').next() == Some(name));
|
||||
for name in env.keys() {
|
||||
if !listed(name, &wslenv) {
|
||||
wslenv.push(name);
|
||||
}
|
||||
}
|
||||
let wslenv = wslenv.join(":");
|
||||
if !wslenv.is_empty() {
|
||||
env.insert("WSLENV".into(), wslenv);
|
||||
}
|
||||
let mut out = config.clone();
|
||||
out.command = wsl_exe.to_owned();
|
||||
out.args = args;
|
||||
out.cwd = Some(root.to_path_buf().into());
|
||||
out.env = env;
|
||||
let extras = &mut out.extras;
|
||||
extras.target = None;
|
||||
extras.env_files.clear();
|
||||
// `wsl.exe` needs this machine's environment; the distribution gets only `WSLENV`'s names.
|
||||
extras.include_system_env = true;
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use ide_core::remote_settings::RunTargetKind;
|
||||
|
||||
fn target() -> RunTarget {
|
||||
RunTarget { kind: RunTargetKind::Wsl, name: "wsl".into(), distro: "Ubuntu-24.04".into(), ..Default::default() }
|
||||
}
|
||||
|
||||
fn config(command: &str, args: &[&str]) -> RunConfig {
|
||||
RunConfig {
|
||||
id: "app".into(),
|
||||
name: "app".into(),
|
||||
kind: "python".into(),
|
||||
command: command.into(),
|
||||
args: args.iter().map(|a| (*a).to_owned()).collect(),
|
||||
cwd: None,
|
||||
env: BTreeMap::new(),
|
||||
detected: false,
|
||||
is_test: false,
|
||||
debug_adapter: None,
|
||||
allow_parallel: false,
|
||||
extras: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_project_root_is_the_targets_or_its_mnt_path() {
|
||||
let t = target();
|
||||
assert_eq!(project_root(&t, Path::new(r"C:\work\proj")).unwrap(), "/mnt/c/work/proj");
|
||||
assert_eq!(project_root(&t, Path::new(r"\\wsl.localhost\Ubuntu-24.04\home\me\p")).unwrap(), "/home/me/p");
|
||||
let err = project_root(&t, Path::new(r"\\server\share\p")).unwrap_err();
|
||||
assert!(err.message.contains("set the project's Linux path"), "{}", err.message);
|
||||
let custom = RunTarget { project_root: " /c/work/proj/ ".into(), ..t.clone() };
|
||||
assert_eq!(project_root(&custom, Path::new(r"\\server\share\p")).unwrap(), "/c/work/proj");
|
||||
let slash = RunTarget { project_root: "/".into(), ..t };
|
||||
assert_eq!(project_root(&slash, Path::new("x")).unwrap(), "/");
|
||||
}
|
||||
|
||||
// Unix paths are not absolute on Windows; `windows_paths_are_mapped` covers Windows.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_program_runs_through_wsl_exe_with_its_variables_by_name() {
|
||||
let mut c = config("/work/proj/.venv/bin/python", &["-u", "/work/proj/main.py", "a b"]);
|
||||
c.cwd = Some(Path::new("/work/proj/src").to_path_buf().into());
|
||||
c.env.insert("DATA".into(), "/work/proj/data".into());
|
||||
c.extras.target = Some("t".into());
|
||||
c.extras.env_files = vec![".env".into()];
|
||||
let files = BTreeMap::from([("SECRET".to_owned(), "s3".to_owned())]);
|
||||
let out =
|
||||
wsl_config(&c, &target(), Path::new("/work/proj"), "/mnt/c/proj", "wsl.exe", &files, Some("USERPROFILE/p"))
|
||||
.unwrap();
|
||||
assert_eq!(out.command, "wsl.exe");
|
||||
assert_eq!(
|
||||
out.args,
|
||||
["-d", "Ubuntu-24.04", "--cd", "/mnt/c/proj/src", "--exec", "python3", "-u", "/mnt/c/proj/main.py", "a b"]
|
||||
);
|
||||
assert_eq!(out.env["DATA"], "/mnt/c/proj/data");
|
||||
assert_eq!(out.env["SECRET"], "s3");
|
||||
assert_eq!(out.env["PYTHONUNBUFFERED"], "1");
|
||||
assert_eq!(out.env["WSLENV"], "USERPROFILE/p:DATA:PYTHONUNBUFFERED:SECRET");
|
||||
assert_eq!(out.cwd.as_ref().map(|p| p.to_path_buf()), Some(Path::new("/work/proj").to_path_buf()));
|
||||
assert_eq!(out.extras.target, None);
|
||||
assert!(out.extras.env_files.is_empty());
|
||||
assert!(out.extras.include_system_env);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_shell_line_runs_in_sh_and_the_targets_interpreter_is_used() {
|
||||
let mut shell = config("npm run dev", &[]);
|
||||
shell.kind = "shell".into();
|
||||
let out =
|
||||
wsl_config(&shell, &target(), Path::new("proj"), "/mnt/c/proj", "wsl.exe", &BTreeMap::new(), None).unwrap();
|
||||
assert_eq!(out.args, ["-d", "Ubuntu-24.04", "--cd", "/mnt/c/proj", "--exec", "sh", "-c", "npm run dev"]);
|
||||
assert!(!out.env.contains_key("WSLENV"));
|
||||
|
||||
let t = RunTarget { python: "/home/me/.venv/bin/python".into(), ..target() };
|
||||
let out =
|
||||
wsl_config(&config("python.exe", &["-V"]), &t, Path::new("proj"), "/p", "wsl.exe", &BTreeMap::new(), None)
|
||||
.unwrap();
|
||||
let path_first = r#"PATH="$0:$PATH" exec "$@""#;
|
||||
assert_eq!(
|
||||
&out.args[4..],
|
||||
["--exec", "sh", "-c", path_first, "/home/me/.venv/bin", "/home/me/.venv/bin/python", "-V"],
|
||||
"the virtualenv's scripts come first on PATH"
|
||||
);
|
||||
let mut pytest = config("pytest", &["tests"]);
|
||||
pytest.kind = "pytest".into();
|
||||
let out = wsl_config(&pytest, &t, Path::new("proj"), "/p", "wsl.exe", &BTreeMap::new(), None).unwrap();
|
||||
assert_eq!(&out.args[9..], ["pytest", "tests"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_configurations_wslenv_keeps_its_flags_and_an_outside_folder_is_refused() {
|
||||
let mut c = config("python", &[]);
|
||||
c.env.insert("WSLENV".into(), "DATA/p".into());
|
||||
c.env.insert("DATA".into(), "x".into());
|
||||
let out = wsl_config(&c, &target(), Path::new("proj"), "/p", "wsl.exe", &BTreeMap::new(), Some("A/u")).unwrap();
|
||||
assert_eq!(out.env["WSLENV"], "A/u:DATA/p:PYTHONUNBUFFERED");
|
||||
c.env.insert("PATH".into(), "/here/bin:/usr/bin".into());
|
||||
let out = wsl_config(&c, &target(), Path::new("proj"), "/p", "wsl.exe", &BTreeMap::new(), None).unwrap();
|
||||
assert!(!out.env.contains_key("PATH") && !out.env["WSLENV"].contains("PATH"), "{:?}", out.env);
|
||||
// An absolute folder of this machine outside the project (`/elsewhere` has no `/mnt` path).
|
||||
let outside = if cfg!(windows) { r"\\server\share\x" } else { "/elsewhere" };
|
||||
c.cwd = Some(Path::new(outside).to_path_buf().into());
|
||||
let root = if cfg!(windows) { r"C:\proj" } else { "/proj" };
|
||||
let err = wsl_config(&c, &target(), Path::new(root), "/p", "wsl.exe", &BTreeMap::new(), None).unwrap_err();
|
||||
assert!(err.message.contains("can't reach the working folder"), "{}", err.message);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn java_path_lists_are_joined_with_colons() {
|
||||
let args: Vec<String> = ["-cp", "out:lib/*", "-p", "/opt/mods", "Main"].map(String::from).to_vec();
|
||||
assert_eq!(linux_path_lists(&args, Path::new("/p"), "Ubuntu"), ["-cp", "out:lib/*", "-p", "/opt/mods", "Main"]);
|
||||
assert!(is_java("/usr/lib/jvm/bin/java") && is_java(r"C:\jdk\bin\JAVA.EXE") && !is_java("javac"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn printed_paths_lead_back_to_files_here() {
|
||||
let t = RunTarget { project_root: "/mnt/c/work/proj".into(), ..target() };
|
||||
let root = Path::new("proj-here");
|
||||
assert_eq!(local_file("/mnt/c/work/proj/app/main.py", &t, root), Some(root.join("app").join("main.py")));
|
||||
assert_eq!(
|
||||
local_file("/mnt/d/lib/x.py", &t, root),
|
||||
Some(PathBuf::from("D:\\").join("lib").join("x.py")),
|
||||
"another drive"
|
||||
);
|
||||
assert_eq!(
|
||||
local_file("/usr/lib/python3/dist-packages/a.py", &t, root),
|
||||
Some(
|
||||
ide_core::wsl::share_root("Ubuntu-24.04")
|
||||
.join("usr")
|
||||
.join("lib")
|
||||
.join("python3")
|
||||
.join("dist-packages")
|
||||
.join("a.py")
|
||||
)
|
||||
);
|
||||
assert_eq!(
|
||||
local_file("/mnt/c/work/proj2/a.py", &t, root),
|
||||
Some(PathBuf::from("C:\\").join("work").join("proj2").join("a.py"))
|
||||
);
|
||||
assert_eq!(local_file("main.py", &t, root), None);
|
||||
assert_eq!(local_file("/mnt/c/work/proj/app/../lib/a.py", &t, root), Some(root.join("lib").join("a.py")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pythons_are_listed_once_and_python3_is_the_default() {
|
||||
let out = "/usr/bin/python3\n\n/usr/bin/python3\n/usr/bin/python3.12\nsh: 1: bad\n/usr/bin/python3-pytest\n\
|
||||
/usr/bin/python3.12-config\n/mnt/c/p/.venv/bin/python\r\n";
|
||||
assert_eq!(parse_pythons(out), ["/usr/bin/python3", "/usr/bin/python3.12", "/mnt/c/p/.venv/bin/python"]);
|
||||
assert_eq!(python(&target()), "python3");
|
||||
assert_eq!(python(&RunTarget { python: " /opt/py/bin/python ".into(), ..target() }), "/opt/py/bin/python");
|
||||
}
|
||||
|
||||
// The script itself, in this machine's `sh`.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn the_python_finder_lists_a_venv_of_the_project() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let bin = dir.path().join(".venv/bin");
|
||||
std::fs::create_dir_all(&bin).unwrap();
|
||||
let python = bin.join("python");
|
||||
std::fs::write(&python, "#!/bin/sh\n").unwrap();
|
||||
std::fs::set_permissions(&python, std::os::unix::fs::PermissionsExt::from_mode(0o755)).unwrap();
|
||||
let out = std::process::Command::new("sh").args(["-c", FIND_PYTHONS, "sh"]).arg(dir.path()).output().unwrap();
|
||||
assert!(out.status.success());
|
||||
let found = parse_pythons(&String::from_utf8_lossy(&out.stdout));
|
||||
assert!(found.contains(&python.to_string_lossy().into_owned()), "{found:?}");
|
||||
assert!(found.iter().all(|p| !p.ends_with("-config")), "{found:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_target_without_a_valid_distribution_is_refused() {
|
||||
for distro in ["", " ", "-u root", "a;b"] {
|
||||
let t = RunTarget { distro: distro.into(), ..target() };
|
||||
let err = wsl_config(&config("python", &[]), &t, Path::new("p"), "/p", "wsl.exe", &BTreeMap::new(), None)
|
||||
.unwrap_err();
|
||||
assert!(err.message.contains("no WSL distribution"), "{distro}: {}", err.message);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn windows_paths_are_mapped() {
|
||||
let root = Path::new(r"C:\work\proj");
|
||||
let linux = project_root(&target(), root).unwrap();
|
||||
let mut c = config(r"C:\work\proj\.venv\Scripts\python.exe", &[r"C:\work\proj\app\main.py"]);
|
||||
c.cwd = Some(Path::new(r"C:\work\proj\app").to_path_buf().into());
|
||||
let out = wsl_config(&c, &target(), root, &linux, "wsl.exe", &BTreeMap::new(), None).unwrap();
|
||||
assert_eq!(
|
||||
out.args,
|
||||
["-d", "Ubuntu-24.04", "--cd", "/mnt/c/work/proj/app", "--exec", "python3", "/mnt/c/work/proj/app/main.py"]
|
||||
);
|
||||
let java = config(
|
||||
r"C:\jdk\bin\java.exe",
|
||||
&["-cp", r"C:\work\proj\out;D:\m2\a.jar;lib\*", "--module-path", r"C:\work\proj\mods", "app.Main"],
|
||||
);
|
||||
let out = wsl_config(&java, &target(), root, &linux, "wsl.exe", &BTreeMap::new(), None).unwrap();
|
||||
assert_eq!(
|
||||
&out.args[4..],
|
||||
[
|
||||
"--exec",
|
||||
"java",
|
||||
"-cp",
|
||||
"/mnt/c/work/proj/out:/mnt/d/m2/a.jar:lib/*",
|
||||
"--module-path",
|
||||
"/mnt/c/work/proj/mods",
|
||||
"app.Main"
|
||||
]
|
||||
);
|
||||
let custom = RunTarget { project_root: "/home/me/proj".into(), ..target() };
|
||||
let java = config(r"C:\jdk\bin\java.exe", &["-cp", r"C:\work\proj\out;D:\m2\a.jar", "app.Main"]);
|
||||
let out = wsl_config(&java, &custom, root, "/home/me/proj", "wsl.exe", &BTreeMap::new(), None).unwrap();
|
||||
assert_eq!(out.args[7], "/home/me/proj/out:/mnt/d/m2/a.jar", "project entries go to its folder there");
|
||||
c.cwd = Some(Path::new(r"D:\data").to_path_buf().into());
|
||||
let out = wsl_config(&c, &target(), root, &linux, "wsl.exe", &BTreeMap::new(), None).unwrap();
|
||||
assert_eq!(out.args[3], "/mnt/d/data", "a folder outside the project, through its /mnt path");
|
||||
}
|
||||
}
|
||||
@@ -636,23 +636,24 @@ impl ProcessManager {
|
||||
let mut cmd = CommandBuilder::new(&inv.program);
|
||||
cmd.args(&inv.args);
|
||||
cmd.cwd(cwd);
|
||||
if env.clear {
|
||||
cmd.env_clear();
|
||||
} else {
|
||||
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();
|
||||
if !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.env("COLORTERM", "truecolor");
|
||||
for (k, v) in &env.vars {
|
||||
cmd.env(k, v);
|
||||
if ide_core::process::is_spawnable_env_pair(std::ffi::OsStr::new(k), std::ffi::OsStr::new(v)) {
|
||||
cmd.env(k, v);
|
||||
}
|
||||
}
|
||||
#[cfg(unix)]
|
||||
let wait_writable = ide_core::input::nonblocking(
|
||||
|
||||
@@ -1811,6 +1811,7 @@ fn custom_server(name: &str, ls: &LanguageServerSettings) -> LanguageServerConfi
|
||||
tsserver_project: false,
|
||||
tsserver_project_extras: Default::default(),
|
||||
resync_on_configuration: false,
|
||||
ignored_progress_token_prefixes: vec![],
|
||||
display_name: None,
|
||||
pinned: None,
|
||||
}
|
||||
|
||||
@@ -81,7 +81,11 @@ pub fn folders_to_copy(probe: &Probe, container_root: &str) -> Vec<String> {
|
||||
|
||||
/// Where a snapshot in `dir` keeps its copy of the container folder `container`.
|
||||
pub fn local_folder(dir: &Path, container: &str) -> PathBuf {
|
||||
container.split('/').filter(|c| !c.is_empty() && *c != "." && *c != "..").fold(dir.join("fs"), |p, c| p.join(c))
|
||||
below(dir.join("fs"), container)
|
||||
}
|
||||
|
||||
fn below(base: PathBuf, path: &str) -> PathBuf {
|
||||
path.split('/').filter(|c| !c.is_empty() && *c != "." && *c != "..").fold(base, |p, c| p.join(c))
|
||||
}
|
||||
|
||||
/// Where a snapshot in `dir` keeps the file `container_path` of its container (a
|
||||
@@ -91,7 +95,7 @@ pub fn snapshot_file(dir: &Path, snapshot: &Snapshot, container_path: &str) -> O
|
||||
.folders
|
||||
.iter()
|
||||
.any(|f| container_path.strip_prefix(f.trim_end_matches('/')).is_some_and(|rest| rest.starts_with('/')));
|
||||
(copied && !container_path.split('/').any(|c| c == "..")).then(|| local_folder(dir, container_path))
|
||||
(copied && !container_path.split('/').any(|c| c == "..")).then(|| snapshot.local(dir, container_path))
|
||||
}
|
||||
|
||||
/// `snapshot.json` of a snapshot folder.
|
||||
@@ -105,6 +109,21 @@ pub struct Snapshot {
|
||||
pub folders: Vec<String>,
|
||||
/// The neutral interpreter given to the language server; `None` without a local Python.
|
||||
pub neutral_python: Option<PathBuf>,
|
||||
/// A WSL interpreter's distribution. Its folders are read in place, not copied: on their
|
||||
/// drive under `/mnt/<drive>`, the rest through `\\wsl.localhost\<distro>`.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub distro: Option<String>,
|
||||
}
|
||||
|
||||
impl Snapshot {
|
||||
/// Where this machine reads the interpreter's folder or file `path`.
|
||||
pub fn local(&self, dir: &Path, path: &str) -> PathBuf {
|
||||
match &self.distro {
|
||||
// `..` never climbs above the drive or the distribution's share.
|
||||
Some(distro) => ide_core::wsl::windows_path(path, distro),
|
||||
None => local_folder(dir, path),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const SNAPSHOT_FILE: &str = "snapshot.json";
|
||||
@@ -160,8 +179,11 @@ pub fn make_current(target_dir: &Path, image: &str) -> IdeResult<()> {
|
||||
}
|
||||
|
||||
/// The local folders of a snapshot that exist.
|
||||
/// A WSL snapshot's folders are taken as they were probed: checking them would read the
|
||||
/// distribution's file system, which may be slow or still starting.
|
||||
pub fn local_folders(dir: &Path, snapshot: &Snapshot) -> Vec<PathBuf> {
|
||||
snapshot.folders.iter().map(|f| local_folder(dir, f)).filter(|p| p.is_dir()).collect()
|
||||
let folders = snapshot.folders.iter().map(|f| snapshot.local(dir, f));
|
||||
if snapshot.distro.is_some() { folders.collect() } else { folders.filter(|p| p.is_dir()).collect() }
|
||||
}
|
||||
|
||||
/// basedpyright / pyright: the neutral interpreter and the snapshot's folders as
|
||||
@@ -189,8 +211,8 @@ pub fn library_group(target_name: &str, dir: &Path, snapshot: &Snapshot) -> Opti
|
||||
let roots: Vec<LibraryRoot> = snapshot
|
||||
.folders
|
||||
.iter()
|
||||
.map(|f| (f, local_folder(dir, f)))
|
||||
.filter(|(_, p)| p.is_dir())
|
||||
.map(|f| (f, snapshot.local(dir, f)))
|
||||
.filter(|(_, p)| snapshot.distro.is_some() || p.is_dir())
|
||||
.map(|(f, p)| LibraryRoot { name: f.rsplit('/').next().unwrap_or(f).to_owned(), path: p.into() })
|
||||
.collect();
|
||||
(!roots.is_empty()).then(|| LibraryGroup {
|
||||
@@ -318,6 +340,17 @@ mod tests {
|
||||
local_folder(dir, "/usr/local/lib/../site-packages"),
|
||||
Path::new("snap").join("fs").join("usr").join("local").join("lib").join("site-packages")
|
||||
);
|
||||
let wsl = Snapshot { distro: Some("U".into()), ..Snapshot::default() };
|
||||
assert_eq!(
|
||||
wsl.local(dir, "/usr/lib/python3/dist-packages"),
|
||||
ide_core::wsl::share_root("U").join("usr").join("lib").join("python3").join("dist-packages"),
|
||||
"a WSL snapshot reads the distribution in place"
|
||||
);
|
||||
assert_eq!(
|
||||
wsl.local(dir, "/mnt/c/p/.venv/lib"),
|
||||
PathBuf::from("C:\\").join("p").join(".venv").join("lib"),
|
||||
"a drive directly"
|
||||
);
|
||||
assert_eq!(dir_name("sha256:0123456789abcdef0123"), "0123456789abcdef");
|
||||
assert_eq!(dir_name("target/../x y"), "target____x_y");
|
||||
}
|
||||
@@ -344,6 +377,7 @@ mod tests {
|
||||
probe: probe(),
|
||||
folders: vec!["/usr/local/lib/python3.12/site-packages".into(), "/gone".into()],
|
||||
neutral_python: neutral,
|
||||
distro: None,
|
||||
};
|
||||
let site = local_folder(dir, &snapshot.folders[0]);
|
||||
std::fs::create_dir_all(site.join("Django-5.1.3.dist-info")).unwrap();
|
||||
|
||||
@@ -46,6 +46,7 @@ pub(crate) fn server(name: &str) -> LanguageServerConfig {
|
||||
tsserver_project: false,
|
||||
tsserver_project_extras: Default::default(),
|
||||
resync_on_configuration: false,
|
||||
ignored_progress_token_prefixes: vec![],
|
||||
display_name: None,
|
||||
pinned: None,
|
||||
}
|
||||
|
||||
@@ -344,15 +344,18 @@ impl TerminalManager {
|
||||
resolve_cwd(&options.cwd)
|
||||
};
|
||||
cmd.cwd(&cwd);
|
||||
// In a project folder: the project's environment (its direnv `.envrc`) too.
|
||||
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),
|
||||
}
|
||||
// portable-pty starts from a base env that re-reads HKCU\Environment on
|
||||
// Windows. A REG_MULTI_SZ value's interior NULs split the environment
|
||||
// block and CreateProcessW fails with os error 87 (#6806). Build the
|
||||
// child's environment from sanitized host vars instead.
|
||||
cmd.env_clear();
|
||||
for (k, v) in ide_core::process::spawnable_host_vars_in(&cwd) {
|
||||
cmd.env(k, v);
|
||||
}
|
||||
for (k, v) in env {
|
||||
cmd.env(k, v);
|
||||
if ide_core::process::is_spawnable_env_pair(std::ffi::OsStr::new(&k), std::ffi::OsStr::new(&v)) {
|
||||
cmd.env(k, v);
|
||||
}
|
||||
}
|
||||
apply_powershell_env(&shell, &mut cmd);
|
||||
|
||||
|
||||
@@ -81,7 +81,7 @@ impl LineEnding {
|
||||
}
|
||||
|
||||
/// How long [`Document::diff`] may look for separate regions, so a reload never stalls on a huge file.
|
||||
const DIFF_BUDGET: Duration = Duration::from_millis(50);
|
||||
pub const DIFF_BUDGET: Duration = Duration::from_millis(50);
|
||||
|
||||
type LineRange = std::ops::Range<usize>;
|
||||
|
||||
@@ -741,6 +741,12 @@ mod tests {
|
||||
assert_eq!(doc.text(), "😀x😀");
|
||||
}
|
||||
|
||||
/// `diff` without its time budget: a loaded machine can spend 50 ms before the first deadline
|
||||
/// check, and the coarser result is right too, just not what these tests pin down.
|
||||
fn unhurried_diff(doc: &Document, text: &str) -> ChangeSet {
|
||||
doc.diff_until(text, std::time::Instant::now() + std::time::Duration::from_secs(3600))
|
||||
}
|
||||
|
||||
fn numbered_lines(n: usize) -> String {
|
||||
(0..n).map(|i| format!("line {i}\n")).collect()
|
||||
}
|
||||
@@ -750,7 +756,7 @@ mod tests {
|
||||
let old = numbered_lines(400);
|
||||
let new = old.replace("line 20\n", "line 20x\n").replace("line 299\n", "line 299x\n");
|
||||
let at = |line: &str| (old.find(line).unwrap() + line.len() - 1) as u32;
|
||||
let set = Document::new(&old).diff(&new);
|
||||
let set = unhurried_diff(&Document::new(&old), &new);
|
||||
assert_eq!(
|
||||
set.changes,
|
||||
vec![tc(at("line 20\n"), at("line 20\n"), "x"), tc(at("line 299\n"), at("line 299\n"), "x")]
|
||||
@@ -760,14 +766,14 @@ mod tests {
|
||||
#[test]
|
||||
fn diff_handles_added_and_removed_lines() {
|
||||
let old = "a\nb\nc\nd\ne\nf\n";
|
||||
let set = Document::new(old).diff("a\nnew\nb\nc\ne\nf\n");
|
||||
let set = unhurried_diff(&Document::new(old), "a\nnew\nb\nc\ne\nf\n");
|
||||
assert_eq!(set.changes, vec![tc(2, 2, "new\n"), tc(5, 7, "")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn diff_counts_utf16_past_astral_text() {
|
||||
let old = "😀 one\nsame\n😀 two\n";
|
||||
let set = Document::new(old).diff("😀 ONE\nsame\n😀 TWO\n");
|
||||
let set = unhurried_diff(&Document::new(old), "😀 ONE\nsame\n😀 TWO\n");
|
||||
assert_eq!(set.changes, vec![tc(3, 6, "ONE"), tc(15, 18, "TWO")]);
|
||||
}
|
||||
|
||||
|
||||
@@ -171,6 +171,14 @@ fn bin_dirs_in(root: &Path, platform: Platform) -> Vec<PathBuf> {
|
||||
dirs
|
||||
}
|
||||
|
||||
/// How [`Method::DotnetTool`] installs a package.
|
||||
#[derive(Clone, Copy)]
|
||||
struct DotnetToolOptions {
|
||||
package: &'static str,
|
||||
prerelease: bool,
|
||||
min_sdk: u32,
|
||||
}
|
||||
|
||||
fn managed_bin_dir(root: &Path, spec: &ToolSpec, platform: Platform) -> Option<PathBuf> {
|
||||
match spec.fallback.unwrap_or(spec.method) {
|
||||
Method::Npm { .. } => Some(root.join("node_modules").join(".bin")),
|
||||
@@ -1049,7 +1057,10 @@ impl Tools {
|
||||
Method::Go { module } => self.install_go(spec, module, cancel, emit)?,
|
||||
Method::Gem { gem } => self.install_gem(spec, gem, cancel, emit)?,
|
||||
Method::GemActive { gem } => self.install_gem_active(gem, cancel, emit)?,
|
||||
Method::DotnetTool { package } => self.install_dotnet_tool(spec, package, cancel, emit)?,
|
||||
Method::DotnetTool { package, prerelease, min_sdk } => {
|
||||
let options = DotnetToolOptions { package, prerelease, min_sdk };
|
||||
self.install_dotnet_tool(spec, options, langs, cancel, emit)?
|
||||
}
|
||||
Method::PipVenv { package } => self.install_venv(spec, package, cancel, emit)?,
|
||||
Method::PipUser { package, .. } => self.install_pip_user(package, cancel, emit)?,
|
||||
Method::PipTarget { package, .. } => self.install_pip_target(spec, package, cancel, emit)?,
|
||||
@@ -1220,20 +1231,28 @@ impl Tools {
|
||||
fn install_dotnet_tool(
|
||||
&self,
|
||||
spec: &ToolSpec,
|
||||
package: &str,
|
||||
options: DotnetToolOptions,
|
||||
langs: &[LanguageConfig],
|
||||
cancel: &CancellationToken,
|
||||
emit: Emit,
|
||||
) -> IdeResult<()> {
|
||||
let DotnetToolOptions { package, prerelease, .. } = options;
|
||||
let dir = self.root.join(spec.name);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let tool = dir.join("tool");
|
||||
std::fs::create_dir_all(&tool)?;
|
||||
let dotnet = self.which("dotnet").expect("checked");
|
||||
let version = self.dotnet_tool_version(spec, package, &dotnet, cancel, emit)?;
|
||||
let version = self.dotnet_tool_version(spec, options, langs, &dotnet, cancel, emit)?;
|
||||
let mut c = self.command(&dotnet);
|
||||
c.args(["tool", "install", package, "--tool-path"]).arg(&tool).args(["--verbosity", "normal"]);
|
||||
if let Some(version) = &version {
|
||||
c.args(["--version", version]);
|
||||
match &version {
|
||||
Some(version) => {
|
||||
c.args(["--version", version]);
|
||||
}
|
||||
None if prerelease => {
|
||||
c.arg("--prerelease");
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
let result = run_streamed_picking(c, cancel, emit, dotnet::nuget_errors).and_then(|_| {
|
||||
// The tool's apphost looks for .NET in the default location only; a
|
||||
@@ -1268,17 +1287,20 @@ impl Tools {
|
||||
}
|
||||
|
||||
/// The `--version` to install `package` with: `None` for the latest, or the newest version
|
||||
/// the installed SDK supports. Fails when there is no SDK, or no version runs on it.
|
||||
/// the installed SDK supports. Fails when there is no SDK, it is older than `min_sdk`, or no
|
||||
/// version runs on it.
|
||||
fn dotnet_tool_version(
|
||||
&self,
|
||||
spec: &ToolSpec,
|
||||
package: &str,
|
||||
options: DotnetToolOptions,
|
||||
langs: &[LanguageConfig],
|
||||
dotnet: &Path,
|
||||
cancel: &CancellationToken,
|
||||
emit: Emit,
|
||||
) -> IdeResult<Option<String>> {
|
||||
let mut c = self.command(dotnet);
|
||||
c.arg("--list-sdks");
|
||||
let DotnetToolOptions { package, prerelease, min_sdk } = options;
|
||||
let Some((true, out)) = run_quiet(c, Duration::from_secs(20)) else { return Ok(None) };
|
||||
let Some(sdk) = dotnet::newest_sdk(&out) else {
|
||||
return Err(IdeError::unavailable(format!(
|
||||
@@ -1287,6 +1309,29 @@ impl Tools {
|
||||
dotnet::SDK_DOWNLOAD_URL
|
||||
)));
|
||||
};
|
||||
if sdk.major < min_sdk {
|
||||
// An alternative server for the same files that this SDK can install.
|
||||
let instead = usages(langs)
|
||||
.get(spec.name)
|
||||
.into_iter()
|
||||
.flat_map(|u| u.alternatives.iter())
|
||||
.filter(|name| *name != spec.name)
|
||||
.filter_map(|name| registry::find(name))
|
||||
.find(|alt| matches!(alt.method, Method::DotnetTool { min_sdk, .. } if min_sdk <= sdk.major))
|
||||
.map(|alt| format!(", or install {}, which runs on it", alt.display))
|
||||
.unwrap_or_default();
|
||||
return Err(IdeError::unavailable(format!(
|
||||
"{} needs the .NET {min_sdk} SDK or newer; found {}. Install it from {}{instead}",
|
||||
spec.display,
|
||||
sdk.version,
|
||||
dotnet::SDK_DOWNLOAD_URL
|
||||
)));
|
||||
}
|
||||
// nuget.org's version index used below lists SemVer 1 versions only, which leaves out
|
||||
// most prereleases: let `--prerelease` pick the newest one.
|
||||
if prerelease {
|
||||
return Ok(None);
|
||||
}
|
||||
let pick = self
|
||||
.http()
|
||||
.and_then(|http| dotnet::pick_tool_version(package, sdk.major, |url| http.get_text(url, cancel)));
|
||||
|
||||
@@ -61,8 +61,10 @@ pub enum Method {
|
||||
/// (`~/Library/Application Support`: Bundler `exec`s a lone path string, and Ruby splits it).
|
||||
GemActive { gem: &'static str },
|
||||
/// `dotnet tool install --tool-path <tools>/<name>/tool <package>`, launched
|
||||
/// through `DOTNET_ROOT` wrappers in `bin/`.
|
||||
DotnetTool { package: &'static str },
|
||||
/// through `DOTNET_ROOT` wrappers in `bin/`. `prerelease` installs the newest version,
|
||||
/// prerelease or not, for packages that publish no stable one; `min_sdk` is the lowest
|
||||
/// .NET SDK major that can install the package (0: any).
|
||||
DotnetTool { package: &'static str, prerelease: bool, min_sdk: u32 },
|
||||
/// Platform archive download into `<tools>/<name>/`.
|
||||
Release { source: ReleaseSource, assets: &'static [AssetRule], locate: &'static [&'static str] },
|
||||
}
|
||||
@@ -681,6 +683,28 @@ pub static TOOLS: &[ToolSpec] = &[
|
||||
homepage: "https://github.com/laravel/lsp",
|
||||
needs: &[],
|
||||
},
|
||||
ToolSpec {
|
||||
name: "phpantom",
|
||||
display: "PHPantom",
|
||||
kind: LanguageServer,
|
||||
commands: &["phpantom_lsp"],
|
||||
method: Method::Release {
|
||||
source: ReleaseSource::GitHub { repo: "PHPantom-dev/phpantom_lsp" },
|
||||
assets: &[
|
||||
rule(Mac, Arm64, "phpantom_lsp-aarch64-apple-darwin.tar.gz"),
|
||||
rule(Mac, X64, "phpantom_lsp-x86_64-apple-darwin.tar.gz"),
|
||||
rule(Linux, Arm64, "phpantom_lsp-aarch64-unknown-linux-gnu.tar.gz"),
|
||||
rule(Linux, X64, "phpantom_lsp-x86_64-unknown-linux-gnu.tar.gz"),
|
||||
rule(Windows, Arm64, "phpantom_lsp-aarch64-pc-windows-msvc.zip"),
|
||||
rule(Windows, X64, "phpantom_lsp-x86_64-pc-windows-msvc.zip"),
|
||||
],
|
||||
locate: &["phpantom_lsp"],
|
||||
},
|
||||
fallback: None,
|
||||
version: ver("phpantom_lsp"),
|
||||
homepage: "https://github.com/PHPantom-dev/phpantom_lsp",
|
||||
needs: &[],
|
||||
},
|
||||
ToolSpec {
|
||||
name: "phoxite",
|
||||
display: "Phoxite",
|
||||
@@ -1404,12 +1428,24 @@ pub static TOOLS: &[ToolSpec] = &[
|
||||
homepage: "https://solargraph.org",
|
||||
needs: &[],
|
||||
},
|
||||
ToolSpec {
|
||||
name: "roslyn-language-server",
|
||||
display: "Roslyn (C#)",
|
||||
kind: LanguageServer,
|
||||
commands: &["roslyn-language-server"],
|
||||
// Prerelease builds only, as platform-specific tool packages: the .NET 10 SDK installs them.
|
||||
method: Method::DotnetTool { package: "roslyn-language-server", prerelease: true, min_sdk: 10 },
|
||||
fallback: None,
|
||||
version: V,
|
||||
homepage: "https://github.com/dotnet/roslyn",
|
||||
needs: &[],
|
||||
},
|
||||
ToolSpec {
|
||||
name: "csharp-ls",
|
||||
display: "csharp-ls",
|
||||
kind: LanguageServer,
|
||||
commands: &["csharp-ls"],
|
||||
method: Method::DotnetTool { package: "csharp-ls" },
|
||||
method: Method::DotnetTool { package: "csharp-ls", prerelease: false, min_sdk: 0 },
|
||||
fallback: None,
|
||||
version: V,
|
||||
homepage: "https://github.com/razzmatazz/csharp-language-server",
|
||||
@@ -1420,7 +1456,7 @@ pub static TOOLS: &[ToolSpec] = &[
|
||||
display: "FsAutoComplete (F#)",
|
||||
kind: LanguageServer,
|
||||
commands: &["fsautocomplete"],
|
||||
method: Method::DotnetTool { package: "fsautocomplete" },
|
||||
method: Method::DotnetTool { package: "fsautocomplete", prerelease: false, min_sdk: 0 },
|
||||
fallback: None,
|
||||
version: V,
|
||||
homepage: "https://github.com/ionide/FsAutoComplete",
|
||||
|
||||
@@ -190,6 +190,7 @@ fn everything_missing_on_an_empty_system() {
|
||||
#[test]
|
||||
fn interchangeable_servers_list_their_alternatives() {
|
||||
let env = Env::new();
|
||||
env.script(&env.sys, "curl", "exit 1");
|
||||
let list = env.tools().list(&langs());
|
||||
let python = ["basedpyright", "pyright", "ty", "pyrefly"];
|
||||
for name in python {
|
||||
@@ -203,6 +204,13 @@ fn interchangeable_servers_list_their_alternatives() {
|
||||
for name in ["kotlin-lsp", "kotlin-language-server"] {
|
||||
assert_eq!(find(&list, name).alternatives, ["kotlin-lsp", "kotlin-language-server", "kmp-lsp"]);
|
||||
}
|
||||
let php = ["intelephense", "phpantom", "phpactor", "phoxite", "devsense-php-ls"];
|
||||
for name in php {
|
||||
assert_eq!(find(&list, name).alternatives, php);
|
||||
}
|
||||
let phpantom = find(&list, "phpantom");
|
||||
assert!(phpantom.can_install, "{:?}", phpantom.unavailable_reason);
|
||||
assert!(find(&list, "laravel-lsp").alternatives.is_empty());
|
||||
// A regular server after a fallback starts no group with it.
|
||||
assert!(find(&list, "angular-language-server").alternatives.is_empty());
|
||||
assert!(find(&list, "ruff").alternatives.is_empty());
|
||||
@@ -830,7 +838,7 @@ esac"#,
|
||||
assert!(!env.root.join("ruby-lsp").exists());
|
||||
}
|
||||
|
||||
/// Installs of one tool name share a slot, so parallel csharp-ls tests would join each other's install.
|
||||
/// Installs of one tool name share a slot, so parallel .NET tool tests would join each other's install.
|
||||
#[cfg(unix)]
|
||||
static CSHARP_LS_INSTALL: parking_lot::Mutex<()> = parking_lot::Mutex::new(());
|
||||
|
||||
@@ -1012,6 +1020,37 @@ exit 1"#,
|
||||
assert!(skipped);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn prerelease_dotnet_tool_installs_with_prerelease_on_a_new_enough_sdk() {
|
||||
let _serial = CSHARP_LS_INSTALL.lock();
|
||||
let env = Env::new();
|
||||
let calls = dotnet_with_nuget(
|
||||
&env,
|
||||
"10.0.404",
|
||||
r#"/bin/mkdir -p "$5"; printf '#!/bin/sh\n' > "$5/roslyn-language-server"; /bin/chmod +x "$5/roslyn-language-server""#,
|
||||
);
|
||||
let info = env.tools().install("roslyn-language-server", &langs(), &CancellationToken::new(), &|_| {}).unwrap();
|
||||
assert_eq!(info.status, ToolStatus::Installed);
|
||||
let call = fs::read_to_string(&calls).unwrap();
|
||||
assert!(call.trim_end().ends_with("--verbosity normal --prerelease"), "{call}");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn dotnet_tool_on_an_older_sdk_names_the_sdk_and_an_alternative_that_runs_on_it() {
|
||||
let _serial = CSHARP_LS_INSTALL.lock();
|
||||
let env = Env::new();
|
||||
let calls = dotnet_with_nuget(&env, "8.0.416", FAKE_TOOL_INSTALL);
|
||||
let err = env.tools().install("roslyn-language-server", &langs(), &CancellationToken::new(), &|_| {}).unwrap_err();
|
||||
assert_eq!(err.kind, ErrorKind::Unavailable);
|
||||
assert_eq!(
|
||||
err.message,
|
||||
"Roslyn (C#) needs the .NET 10 SDK or newer; found 8.0.416. Install it from https://dotnet.microsoft.com/download, or install csharp-ls, which runs on it"
|
||||
);
|
||||
assert!(!calls.exists(), "dotnet tool install ran");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn kotlin_debugger_uses_existing_release_recipe_and_language_definition() {
|
||||
let spec = registry::find("kotlin-debug-adapter").unwrap();
|
||||
|
||||
@@ -16,17 +16,17 @@ struct CommitMeta {
|
||||
/// Parses `git blame --porcelain` output into one entry per final line.
|
||||
pub(crate) fn parse_porcelain(out: &str, root: &Path, relative_path: &str) -> Vec<BlameLine> {
|
||||
let mut metas: HashMap<String, CommitMeta> = HashMap::new();
|
||||
let mut lines: Vec<(u32, String, Option<IpcPath>)> = Vec::new();
|
||||
let mut current: Option<(u32, String)> = None;
|
||||
let mut lines: Vec<(u32, String, Option<IpcPath>, Option<u32>)> = Vec::new();
|
||||
let mut current: Option<(u32, String, Option<u32>)> = None;
|
||||
for line in out.split('\n') {
|
||||
if line.starts_with('\t') {
|
||||
if let Some((number, id)) = current.take() {
|
||||
if let Some((number, id, origin_line)) = current.take() {
|
||||
let origin = metas.get(&id).and_then(|m| m.origin_path.clone());
|
||||
lines.push((number, id, origin));
|
||||
lines.push((number, id, origin, origin_line));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if let Some((_, id)) = current.as_ref() {
|
||||
if let Some((_, id, _)) = current.as_ref() {
|
||||
let meta = metas.entry(id.clone()).or_default();
|
||||
if let Some(v) = line.strip_prefix("author ") {
|
||||
meta.author = v.to_string();
|
||||
@@ -48,7 +48,7 @@ pub(crate) fn parse_porcelain(out: &str, root: &Path, relative_path: &str) -> Ve
|
||||
}
|
||||
// Header: <sha> <orig-line> <final-line> [<group-count>]
|
||||
let mut parts = line.split(' ');
|
||||
let (Some(sha), Some(_orig), Some(final_line)) = (parts.next(), parts.next(), parts.next()) else {
|
||||
let (Some(sha), Some(orig_line), Some(final_line)) = (parts.next(), parts.next(), parts.next()) else {
|
||||
continue;
|
||||
};
|
||||
if sha.len() < 40 || !sha.bytes().all(|b| b.is_ascii_hexdigit()) {
|
||||
@@ -56,14 +56,23 @@ pub(crate) fn parse_porcelain(out: &str, root: &Path, relative_path: &str) -> Ve
|
||||
}
|
||||
let Ok(final_line) = final_line.parse::<u32>() else { continue };
|
||||
metas.entry(sha.to_string()).or_default();
|
||||
current = Some((final_line, sha.to_string()));
|
||||
// 1-based in the porcelain header.
|
||||
let origin_line = orig_line.parse::<u32>().ok().and_then(|n| n.checked_sub(1));
|
||||
current = Some((final_line, sha.to_string(), origin_line));
|
||||
}
|
||||
lines.sort_by_key(|(n, ..)| *n);
|
||||
lines
|
||||
.into_iter()
|
||||
.map(|(_, sha, origin_path)| {
|
||||
.map(|(_, sha, origin_path, origin_line)| {
|
||||
let meta = metas.get(&sha).cloned().unwrap_or_default();
|
||||
BlameLine { commit: sha, author: meta.author, time_ms: meta.time_ms, summary: meta.summary, origin_path }
|
||||
BlameLine {
|
||||
commit: sha,
|
||||
author: meta.author,
|
||||
time_ms: meta.time_ms,
|
||||
summary: meta.summary,
|
||||
origin_path,
|
||||
origin_line,
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -77,14 +86,16 @@ mod tests {
|
||||
let sha_a = "a".repeat(40);
|
||||
let sha_z = "0".repeat(40);
|
||||
let out = format!(
|
||||
"{sha_a} 1 1 2\nauthor Ann\nauthor-mail <a@x>\nauthor-time 100\nauthor-tz +0000\nsummary first\nfilename f\n\tl1\n\
|
||||
{sha_a} 2 2\n\tl2\n\
|
||||
{sha_z} 3 3 1\nauthor Not Committed Yet\nauthor-time 200\nsummary Version of f from f\nfilename f\n\tl3\n"
|
||||
"{sha_a} 11 17 2\nauthor Ann\nauthor-mail <a@x>\nauthor-time 100\nauthor-tz +0000\nsummary first\nfilename f\n\tl1\n\
|
||||
{sha_a} 12 18\n\tl2\n\
|
||||
{sha_z} 19 19 1\nauthor Not Committed Yet\nauthor-time 200\nsummary Version of f from f\nfilename f\n\tl3\n"
|
||||
);
|
||||
let lines = parse_porcelain(&out, Path::new("root"), "f");
|
||||
assert_eq!(lines.len(), 3);
|
||||
assert_eq!(lines[1].author, "Ann");
|
||||
assert_eq!(lines[1].time_ms, 100_000.0);
|
||||
assert_eq!(lines[2].author, "Not Committed Yet");
|
||||
// Where each line is in the attributed commit's file, 0-based: Show Diff opens there.
|
||||
assert_eq!(lines.iter().map(|l| l.origin_line).collect::<Vec<_>>(), [Some(10), Some(11), Some(18)]);
|
||||
}
|
||||
}
|
||||
@@ -920,6 +920,7 @@ fn log_indexed_rows(
|
||||
text,
|
||||
matches: HashMap::new(),
|
||||
projected: HashMap::new(),
|
||||
pruned: HashMap::new(),
|
||||
cancel,
|
||||
index,
|
||||
table: table.as_ref(),
|
||||
@@ -1010,6 +1011,7 @@ fn sort_subset(
|
||||
let mut children = vec![0usize; ids.len()];
|
||||
let mut times = Vec::with_capacity(ids.len());
|
||||
let mut projected: HashMap<ObjectId, Vec<usize>> = HashMap::new();
|
||||
let mut pruned: HashMap<ObjectId, Vec<ObjectId>> = HashMap::new();
|
||||
for id in &ids {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
@@ -1071,11 +1073,27 @@ fn sort_subset(
|
||||
.collect()
|
||||
};
|
||||
if !expanded {
|
||||
let ancestors = without_redundant_parents(ancestors, cancel, |id| {
|
||||
if let Some((ps, time)) = nodes.get(&id) {
|
||||
return Ok(Some((
|
||||
if shallow.contains(&id) { Vec::new() } else { ps.clone() },
|
||||
*time,
|
||||
)));
|
||||
}
|
||||
let Ok(commit) = repo.find_commit(id) else { return Ok(None) };
|
||||
let parents = if shallow.contains(&id) {
|
||||
Vec::new()
|
||||
} else {
|
||||
commit.parent_ids().map(|p| p.detach()).collect()
|
||||
};
|
||||
Ok(Some((parents, commit.time().map(|t| t.seconds).unwrap_or(0))))
|
||||
})?;
|
||||
stack.push((curr, true));
|
||||
stack.extend(ancestors.iter().rev().map(|&p| (p, false)));
|
||||
pruned.insert(curr, ancestors);
|
||||
} else {
|
||||
let mut combined = Vec::new();
|
||||
for a in ancestors {
|
||||
for a in pruned.remove(&curr).unwrap_or(ancestors) {
|
||||
for &p in projected.get(&a).into_iter().flatten() {
|
||||
if !combined.contains(&p) {
|
||||
combined.push(p);
|
||||
@@ -1177,6 +1195,70 @@ fn sort_subset(
|
||||
/// Visibility and graph projection share exactly the same predicates. Revision parents
|
||||
/// remain immutable; only graph parents skip hidden commits. Memoisation avoids walking
|
||||
/// the same hidden ancestry for each visible child, without a truncation limit.
|
||||
/// How many commits one ancestry check of [`without_redundant_parents`] may walk.
|
||||
const REDUNDANT_PARENT_WALK: usize = 2_000;
|
||||
|
||||
/// `parents` of a commit the graph hides, without those that are ancestors of another of them:
|
||||
/// whatever such a parent leads to is reached through the other one too. Without this, hiding the
|
||||
/// merges of a pull-request history (`M_k = merge(M_k-1, F_k)`) projects every merge onto all older
|
||||
/// features, so the projection grows with each merge and a long history never finishes.
|
||||
/// `lookup` gives a commit's parents and time (`None`: not available). Each check walks back from
|
||||
/// the other parent, skipping commits older than the candidate, for at most
|
||||
/// [`REDUNDANT_PARENT_WALK`] commits; when unsure the parent is kept.
|
||||
fn without_redundant_parents(
|
||||
mut parents: Vec<ObjectId>,
|
||||
cancel: &CancellationToken,
|
||||
mut lookup: impl FnMut(ObjectId) -> IdeResult<Option<(Vec<ObjectId>, i64)>>,
|
||||
) -> IdeResult<Vec<ObjectId>> {
|
||||
let mut seen = HashSet::new();
|
||||
parents.retain(|p| seen.insert(*p));
|
||||
if parents.len() < 2 {
|
||||
return Ok(parents);
|
||||
}
|
||||
let mut times = Vec::with_capacity(parents.len());
|
||||
for p in &parents {
|
||||
times.push(lookup(*p)?.map(|(_, t)| t));
|
||||
}
|
||||
let mut keep = vec![true; parents.len()];
|
||||
for i in 0..parents.len() {
|
||||
let Some(target_time) = times[i] else { continue };
|
||||
for j in 0..parents.len() {
|
||||
if i == j || !keep[j] || times[j].is_some_and(|t| t < target_time) {
|
||||
continue;
|
||||
}
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
let (mut stack, mut visited) = (vec![parents[j]], HashSet::new());
|
||||
let mut found = false;
|
||||
while let Some(id) = stack.pop() {
|
||||
if visited.len() >= REDUNDANT_PARENT_WALK {
|
||||
break;
|
||||
}
|
||||
if !visited.insert(id) {
|
||||
continue;
|
||||
}
|
||||
let Some((ps, time)) = lookup(id)? else { continue };
|
||||
if id != parents[j] && time < target_time {
|
||||
continue;
|
||||
}
|
||||
if ps.contains(&parents[i]) {
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
stack.extend(ps);
|
||||
}
|
||||
if found {
|
||||
keep[i] = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut keep = keep.into_iter();
|
||||
parents.retain(|_| keep.next().unwrap_or(true));
|
||||
Ok(parents)
|
||||
}
|
||||
|
||||
struct Visibility<'a> {
|
||||
speed_refs: &'a HashMap<ObjectId, Vec<String>>,
|
||||
query: &'a LogQuery,
|
||||
@@ -1186,6 +1268,8 @@ struct Visibility<'a> {
|
||||
text: Option<TextFilter>,
|
||||
matches: HashMap<ObjectId, bool>,
|
||||
projected: HashMap<ObjectId, Vec<ObjectId>>,
|
||||
/// The parents a hidden commit projects through, between its two visits.
|
||||
pruned: HashMap<ObjectId, Vec<ObjectId>>,
|
||||
cancel: &'a CancellationToken,
|
||||
index: &'a mut crate::log_index::LogIndex,
|
||||
table: Option<&'a redb::ReadOnlyTable<&'static str, &'static [u8]>>,
|
||||
@@ -1272,6 +1356,26 @@ impl Visibility<'_> {
|
||||
Ok(shown)
|
||||
}
|
||||
|
||||
/// `parents` of a hidden commit without those reachable through another of them.
|
||||
fn prune(&mut self, repo: &gix::Repository, parents: Vec<ObjectId>) -> IdeResult<Vec<ObjectId>> {
|
||||
let (index, table, shallow) = (&mut *self.index, self.table, &self.shallow);
|
||||
without_redundant_parents(parents, self.cancel, |id| {
|
||||
if let Some((ps, time)) = index.nodes.get(&id) {
|
||||
return Ok(Some((if shallow.contains(&id) { Vec::new() } else { ps.clone() }, *time)));
|
||||
}
|
||||
if !index.has_cached(&id) && !repo.has_object(id) {
|
||||
return Ok(None);
|
||||
}
|
||||
let commit = index.get_with_table(repo, id, table)?;
|
||||
let parents = if shallow.contains(&id) {
|
||||
Vec::new()
|
||||
} else {
|
||||
commit.parents.iter().map(|p| ObjectId::from_hex(p.as_bytes()).map_err(gx)).collect::<IdeResult<_>>()?
|
||||
};
|
||||
Ok(Some((parents, (commit.commit_time_ms / 1000.0) as i64)))
|
||||
})
|
||||
}
|
||||
|
||||
fn parents(&mut self, repo: &gix::Repository, parents: &[ObjectId]) -> IdeResult<Vec<ObjectId>> {
|
||||
let parents = if self.query.first_parent { &parents[..parents.len().min(1)] } else { parents };
|
||||
let mut out = Vec::new();
|
||||
@@ -1301,11 +1405,13 @@ impl Visibility<'_> {
|
||||
.collect::<IdeResult<Vec<_>>>()?
|
||||
};
|
||||
if !expanded {
|
||||
let ancestors = self.prune(repo, ancestors)?;
|
||||
stack.push((id, true));
|
||||
stack.extend(ancestors.iter().rev().map(|p| (*p, false)));
|
||||
self.pruned.insert(id, ancestors);
|
||||
} else {
|
||||
let mut nearest = Vec::new();
|
||||
for p in ancestors {
|
||||
for p in self.pruned.remove(&id).unwrap_or(ancestors) {
|
||||
for ancestor in self.projected.get(&p).into_iter().flatten() {
|
||||
if !nearest.contains(ancestor) {
|
||||
nearest.push(*ancestor);
|
||||
|
||||
@@ -131,6 +131,10 @@ pub struct BlameLine {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub origin_path: Option<ide_core::IpcPath>,
|
||||
/// The line's 0-based number in the attributed commit's version of the file.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub origin_line: Option<u32>,
|
||||
}
|
||||
|
||||
/// History for Selection: the commits that changed a block of lines, newest first.
|
||||
|
||||
@@ -105,16 +105,26 @@ fn pack_stamp(pack_dir: &Path) -> Option<SystemTime> {
|
||||
|
||||
pub(crate) fn discover(path: &Path) -> IdeResult<Option<Repo>> {
|
||||
let start = if path.is_file() { path.parent().unwrap_or(path) } else { path };
|
||||
if let Err(e) = gix::discover::upwards(start) {
|
||||
use gix::discover::upwards::Error as E;
|
||||
return match e.downcast_any_ref::<E>() {
|
||||
Some(
|
||||
E::NoGitRepository { .. } | E::NoGitRepositoryWithinCeiling { .. } | E::NoGitRepositoryWithinFs { .. },
|
||||
) => Ok(None),
|
||||
_ => Err(gx(e)),
|
||||
};
|
||||
}
|
||||
let ts = gix::ThreadSafeRepository::discover(start).map_err(gx)?;
|
||||
let found = match gix::discover::upwards(start) {
|
||||
Ok((found, _trust)) => found,
|
||||
Err(e) => {
|
||||
use gix::discover::upwards::Error as E;
|
||||
return match e.downcast_any_ref::<E>() {
|
||||
Some(
|
||||
E::NoGitRepository { .. }
|
||||
| E::NoGitRepositoryWithinCeiling { .. }
|
||||
| E::NoGitRepositoryWithinFs { .. },
|
||||
) => Ok(None),
|
||||
_ => Err(gx(e)),
|
||||
};
|
||||
}
|
||||
};
|
||||
// Opened like `gix()` reopens it, not with `ThreadSafeRepository::discover`: that picks the
|
||||
// options for the folder owner's trust, and for a repository another user owns (reduced trust)
|
||||
// they cap the object database at 32 pack indices. A repository with more packs then fails to
|
||||
// read any object, so `HEAD` doesn't resolve (#7138). Trust is still decided per repository.
|
||||
let (git_dir, worktree) = found.into_repository_and_work_tree_directories();
|
||||
let ts = gix::ThreadSafeRepository::open(worktree.unwrap_or(git_dir)).map_err(gx)?;
|
||||
let repo = ts.to_thread_local();
|
||||
let Some(workdir) = repo.workdir() else {
|
||||
// Bare repositories have no worktree to show changes for.
|
||||
@@ -178,7 +188,7 @@ impl Repo {
|
||||
/// Verifies that the worktree root and its git directory exist on disk. A missing one marks
|
||||
/// the repository stale and is logged once; when both are back (a drive reconnected, `git
|
||||
/// worktree repair`), the mark is cleared, so a stale repository costs two `stat`s per check.
|
||||
pub(crate) fn check_valid(&self) -> IdeResult<()> {
|
||||
pub fn check_valid(&self) -> IdeResult<()> {
|
||||
use std::sync::atomic::Ordering;
|
||||
if self.root.is_dir() && self.git_dir.is_dir() {
|
||||
if self.stale.swap(false, Ordering::AcqRel) {
|
||||
@@ -658,6 +668,53 @@ mod tests {
|
||||
assert!(cmd.status().unwrap().success(), "{cmd:?}");
|
||||
}
|
||||
|
||||
/// More pack indices than the 32 slots `gix` gives a repository another user owns (#7138). The
|
||||
/// owner can't be changed in a test, so this pins that discovery opens with slots sized by the
|
||||
/// pack directory: objects in every pack stay readable through the cached handle.
|
||||
#[test]
|
||||
fn a_repository_with_many_packs_reads_objects_from_all_of_them() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path().join("repo");
|
||||
run(Command::new("git").args(["init", "-q", "-b", "main"]).arg(&root));
|
||||
let git = |args: &[&str]| {
|
||||
let out = Command::new("git").current_dir(&root).args(args).output().unwrap();
|
||||
assert!(out.status.success(), "{args:?}");
|
||||
String::from_utf8(out.stdout).unwrap().trim().to_owned()
|
||||
};
|
||||
git(&["config", "gc.auto", "0"]);
|
||||
git(&["config", "maintenance.auto", "false"]);
|
||||
let mut oids = Vec::new();
|
||||
for i in 0..40 {
|
||||
std::fs::write(root.join(format!("f{i}.txt")), format!("{i}\n")).unwrap();
|
||||
git(&["add", "."]);
|
||||
git(&["-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "-m", &format!("c{i}")]);
|
||||
oids.push(git(&["rev-parse", "HEAD"]));
|
||||
let mut pack = Command::new("git")
|
||||
.current_dir(&root)
|
||||
.args(["pack-objects", "-q", "--revs", ".git/objects/pack/pack"])
|
||||
.stdin(std::process::Stdio::piped())
|
||||
.stdout(std::process::Stdio::null())
|
||||
.spawn()
|
||||
.unwrap();
|
||||
use std::io::Write;
|
||||
let range = if i == 0 { "HEAD\n" } else { "HEAD\n^HEAD~1\n" };
|
||||
pack.stdin.take().unwrap().write_all(range.as_bytes()).unwrap();
|
||||
assert!(pack.wait().unwrap().success());
|
||||
git(&["prune-packed"]);
|
||||
}
|
||||
let packs = std::fs::read_dir(root.join(".git/objects/pack"))
|
||||
.unwrap()
|
||||
.filter(|e| e.as_ref().unwrap().path().extension().is_some_and(|x| x == "idx"))
|
||||
.count();
|
||||
assert!(packs > 32, "{packs} pack indices");
|
||||
let repo = discover(&root).unwrap().unwrap();
|
||||
let gix = repo.gix().unwrap();
|
||||
assert_eq!(gix.head_id().unwrap().to_string(), *oids.last().unwrap());
|
||||
for oid in &oids {
|
||||
gix.find_commit(gix::ObjectId::from_hex(oid.as_bytes()).unwrap()).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
/// What a remounted volume looks like: every path and modification time is the same, but
|
||||
/// the files that the old handle mapped are gone. `tests/volume_loss.rs` does it for real.
|
||||
#[test]
|
||||
|
||||
@@ -15,6 +15,12 @@ const MAX_DEPTH: usize = 4;
|
||||
/// Folders never searched for nested repositories (dependencies, build output).
|
||||
const SKIPPED: &[&str] = &["node_modules", "target", "build", "dist", "out", "vendor", "venv", "__pycache__"];
|
||||
|
||||
/// A folder the nested-repository search neither looks at nor descends into.
|
||||
fn not_searched(path: &Path, skip: &dyn Fn(&Path) -> bool) -> bool {
|
||||
let name = path.file_name().map(|n| n.to_string_lossy()).unwrap_or_default();
|
||||
name.starts_with('.') || SKIPPED.contains(&name.as_ref()) || skip(path)
|
||||
}
|
||||
|
||||
/// The repositories of a project, sorted by root; lookups pick the innermost one.
|
||||
#[derive(Clone, Default)]
|
||||
pub struct Repos {
|
||||
@@ -46,6 +52,18 @@ impl Repos {
|
||||
Ok(Self { repos, primary })
|
||||
}
|
||||
|
||||
/// Whether [`Self::discover`] from `project_root` looks for a repository at `dir`, below it.
|
||||
pub fn searched(project_root: &Path, dir: &Path, skip: &dyn Fn(&Path) -> bool) -> bool {
|
||||
let Ok(rel) = dir.strip_prefix(project_root) else { return false };
|
||||
let depth = rel.components().count();
|
||||
let mut path = project_root.to_path_buf();
|
||||
(1..=MAX_DEPTH).contains(&depth)
|
||||
&& rel.components().all(|c| {
|
||||
path.push(c);
|
||||
!not_searched(&path, skip)
|
||||
})
|
||||
}
|
||||
|
||||
/// The repository containing `project_root` and every repository whose worktree
|
||||
/// root lies below it (up to [`MAX_DEPTH`] levels; hidden and dependency folders and
|
||||
/// folders `skip` rejects are not searched).
|
||||
@@ -61,10 +79,8 @@ impl Repos {
|
||||
if !entry.file_type().is_ok_and(|t| t.is_dir()) {
|
||||
continue;
|
||||
}
|
||||
let name = entry.file_name();
|
||||
let name = name.to_string_lossy();
|
||||
let path = entry.path();
|
||||
if name.starts_with('.') || SKIPPED.contains(&name.as_ref()) || skip(&path) {
|
||||
if not_searched(&path, skip) {
|
||||
continue;
|
||||
}
|
||||
if path.join(".git").exists()
|
||||
@@ -350,6 +366,24 @@ mod tests {
|
||||
assert!(ok, "git {args:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn searched_matches_what_discover_finds() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap();
|
||||
git_init(&root);
|
||||
let dirs = ["a", "a/b/c/d", "a/b/c/d/e", ".hidden/x", "vendor/x", "skipped/x", "a/skipped/x"];
|
||||
for dir in dirs {
|
||||
git_init(&root.join(dir));
|
||||
}
|
||||
let skip = |p: &Path| p.file_name().is_some_and(|n| n == "skipped");
|
||||
let found = Repos::discover(&root, &skip).unwrap().roots();
|
||||
for dir in dirs {
|
||||
let dir = root.join(dir);
|
||||
assert_eq!(Repos::searched(&root, &dir, &skip), found.contains(&dir), "{}", dir.display());
|
||||
}
|
||||
assert!(!Repos::searched(&root, &root, &skip), "the project root itself is no nested repository");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ignored_files_use_git_rules_without_listing_other_repositories_twice() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -287,6 +287,7 @@ fn uncommitted_lines(n: usize) -> Vec<BlameLine> {
|
||||
time_ms: now,
|
||||
summary: String::new(),
|
||||
origin_path: None,
|
||||
origin_line: None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
@@ -267,3 +267,57 @@ fn a_user_filter_links_shown_commits_past_hidden_ones() {
|
||||
assert_eq!(next.iter().map(|c| c.id.clone()).collect::<Vec<_>>(), std::slice::from_ref(&m1));
|
||||
let _ = m3;
|
||||
}
|
||||
|
||||
/// A pull-request history: each feature commit `F_k` branches from merge `M_k-1` and is merged
|
||||
/// back as `M_k = merge(M_k-1, F_k)`, written with `git fast-import`. Returns the feature commits
|
||||
/// newest first.
|
||||
fn pull_request_history(dir: &Path, merges: usize) -> Vec<String> {
|
||||
git(dir, &["init", "-q"], None);
|
||||
let mut stream =
|
||||
String::from("commit refs/heads/main\nmark :1\ncommitter T <[email protected]> 1000 +0000\ndata 4\nroot\n");
|
||||
let mut prev = 1;
|
||||
let mut mark = 1;
|
||||
for k in 0..merges {
|
||||
let t = 1001 + 2 * k as i64;
|
||||
let feature = mark + 1;
|
||||
let merge = mark + 2;
|
||||
stream += &format!(
|
||||
"commit refs/heads/main\nmark :{feature}\ncommitter T <[email protected]> {t} +0000\ndata 1\nf\nfrom :{prev}\n\
|
||||
commit refs/heads/main\nmark :{merge}\ncommitter T <t@example.com> {} +0000\ndata 1\nm\nfrom :{prev}\nmerge :{feature}\n",
|
||||
t + 1
|
||||
);
|
||||
prev = merge;
|
||||
mark = merge;
|
||||
}
|
||||
let mut child = Command::new("git")
|
||||
.current_dir(dir)
|
||||
.args(["fast-import", "--quiet", "--export-marks=marks"])
|
||||
.stdin(std::process::Stdio::piped())
|
||||
.spawn()
|
||||
.unwrap();
|
||||
std::io::Write::write_all(child.stdin.as_mut().unwrap(), stream.as_bytes()).unwrap();
|
||||
assert!(child.wait().unwrap().success());
|
||||
let marks: std::collections::HashMap<usize, String> = std::fs::read_to_string(dir.join("marks"))
|
||||
.unwrap()
|
||||
.lines()
|
||||
.filter_map(|l| l.strip_prefix(':')?.split_once(' ').map(|(m, id)| (m.parse().unwrap(), id.to_string())))
|
||||
.collect();
|
||||
(0..merges).rev().map(|k| marks[&(2 + 2 * k)].clone()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_merges_on_a_long_pull_request_history_links_each_feature_to_the_previous_one() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let features = pull_request_history(tmp.path(), 3000);
|
||||
let repo = Repo::discover(tmp.path()).unwrap().unwrap();
|
||||
let started = std::time::Instant::now();
|
||||
let out = repo
|
||||
.log(&LogQuery { branches: vec!["main".into()], no_merges: true, limit: 100, ..Default::default() })
|
||||
.unwrap();
|
||||
let elapsed = started.elapsed();
|
||||
assert_eq!(ids(&out)[..3], features[..3]);
|
||||
// Every older feature is reachable through the previous one, so it is the only graph parent.
|
||||
assert_eq!(parents_of(&out, &features[0]), vec![features[1].clone()]);
|
||||
assert_eq!(parents_of(&out, &features[1]), vec![features[2].clone()]);
|
||||
assert!(elapsed < std::time::Duration::from_secs(10), "took {elapsed:?}");
|
||||
}
|
||||
@@ -276,11 +276,11 @@ fn expand_jetbrains_path(raw: &str, home: Option<&Path>, config: &Path) -> Optio
|
||||
return None;
|
||||
}
|
||||
let rest = if cfg!(windows) { rest.replace('/', "\\") } else { rest.to_owned() };
|
||||
let path = match base {
|
||||
Some(base) => base.join(rest.trim_start_matches(['/', '\\'])),
|
||||
None => PathBuf::from(rest),
|
||||
};
|
||||
path.is_absolute().then_some(path)
|
||||
// `home` and `config` are absolute already; only a path without a variable is checked.
|
||||
match base {
|
||||
Some(base) => Some(base.join(rest.trim_start_matches(['/', '\\']))),
|
||||
None => Some(PathBuf::from(rest)).filter(|p| p.is_absolute()),
|
||||
}
|
||||
}
|
||||
|
||||
impl RecentProjects {
|
||||
|
||||
@@ -604,7 +604,9 @@ fn external_change_in_two_places_patches_each() {
|
||||
std::thread::sleep(std::time::Duration::from_millis(10));
|
||||
let new = old.replace("line 20\n", "line 20x\n").replace("line 299\n", "line 299x\n");
|
||||
fs::write(&path, &new).unwrap();
|
||||
let started = std::time::Instant::now();
|
||||
f.docs.on_disk_changed(std::slice::from_ref(&path));
|
||||
let in_budget = started.elapsed() < ide_text::DIFF_BUDGET;
|
||||
|
||||
assert_eq!(f.docs.snapshot(id).unwrap().text, new);
|
||||
let events = f.events.lock();
|
||||
@@ -612,7 +614,18 @@ fn external_change_in_two_places_patches_each() {
|
||||
IdeEvent::DocPatched { changes, .. } => Some(changes),
|
||||
_ => None,
|
||||
});
|
||||
assert_eq!(changes.map(Vec::len), Some(2));
|
||||
let changes = changes.expect("a patch");
|
||||
let mut replayed = ide_text::Document::new(&old);
|
||||
replayed.apply(0, &ChangeSet { changes: changes.clone() }).unwrap();
|
||||
assert_eq!(replayed.text(), new);
|
||||
// Merged or not, the patch stays between the two edited lines.
|
||||
let first = old.find("line 20\n").unwrap() as u32;
|
||||
let last = (old.find("line 299\n").unwrap() + "line 299\n".len()) as u32;
|
||||
assert!(changes[0].from >= first && changes[changes.len() - 1].to <= last, "{changes:?}");
|
||||
// Past the diff budget (a loaded machine) the two regions may come as one, still correctly.
|
||||
if in_budget {
|
||||
assert_eq!(changes.len(), 2);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -488,7 +488,7 @@
|
||||
"footer": {
|
||||
"socials": {
|
||||
"github": "https://github.com/l0ng-ai/openidea",
|
||||
"discord": "https://discord.gg/2Zy4yn7gP"
|
||||
"discord": "https://discord.gg/AsZqMgxZm"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -79,6 +79,8 @@ Use the executable path from **Copy Stdio Config**; the macOS path above is only
|
||||
|
||||
OpenIDEA must be running for the tools to work, and the project must be open in a window or served as a [background project](#background-projects). A client may name any folder inside such a project, and the server picks the innermost project that contains it, whether a window has it open or it is served in the background. A project served in the background inside a project open in a window answers for its own folders, so relative paths in a call are relative to its root. For example, with **Trusted projects** a repository inside a trusted location, a Git submodule among them, loads as a background project of its own when a call names its folder, even while a window has the project around it open. HTTP clients name it with the `X-OpenIDEA-Project` header or the `?project=` query.
|
||||
|
||||
A client started in a folder outside every project, such as a folder that only holds repositories, still gets the tools. Each call then names its project with `projectPath`, and the server refuses a call without one.
|
||||
|
||||
While the server runs, OpenIDEA writes its port and token to `mcp/server.json` in its application data directory (readable only by you); the stdio bridge reads it from there.
|
||||
|
||||
## Tools
|
||||
@@ -121,7 +123,7 @@ Notes on what they do:
|
||||
|
||||
`run_command` runs a shell command line in a tab of the Run tool window, with the shell of **Settings › Tools › Terminal**. The agent names the tab and OpenIDEA shows it as `_agent_<name>`, so you see the output as it comes and can type into the command, rerun it or stop it like any run.
|
||||
|
||||
Run configurations an agent starts with `execute_run_configuration` open a tab in the Run tool window too, as when you press Run: the console shows their output and Stop ends them. In a background project without a window (brave mode) they run without a tab.
|
||||
Run configurations an agent starts with `execute_run_configuration` open a tab in the Run tool window too, as when you press Run: the console shows their output and Stop ends them. In a background project without a window they run without a tab, after you allow them in a project window or under brave mode.
|
||||
|
||||
As JetBrains IDEs do, the command runs on pipes, not a terminal: programs print plain lines instead of progress bars and redraws. The agent gets that output cleaned of escape sequences and cut to 2000 lines (`maxLinesCount`); beyond that the end stays, or the start or both ends with `truncateMode`. The tab's raw output log stays complete.
|
||||
|
||||
@@ -168,15 +170,15 @@ What trust decides: a trusted project works as one open in a window, with its la
|
||||
|
||||
A background project has no window, so some tools differ:
|
||||
|
||||
- `run_command` and `open_file_in_editor` need a window.
|
||||
- `run_command`, `open_file_in_editor`, `xdebug_start_debugger_session` and the breakpoint tools (`xdebug_set_breakpoint`, `xdebug_remove_breakpoint`, `xdebug_list_breakpoints`) need a window. They refuse before they ask.
|
||||
- `get_file_problems` and `get_project_problems` report what a window shows. In a background project they answer with an error that points to `check_files`.
|
||||
- `get_current_file` and `get_all_open_file_paths` also describe a window. In a background project they answer with an error that says the project needs a window.
|
||||
- `execute_run_configuration` and `build_project` work in a background project when **Run tools without confirmation (brave mode)** is on.
|
||||
- `execute_run_configuration`, `build_project`, `http_run_request` and destructive plugin tools ask in the project window you used last. The dialog has a line `Background project <folder name>` with the full path under it, and requests queue there. The dialog does not take keyboard focus: answer it with a click, or click into it first and then use the keys. If that window closes or loses trust, the request moves to another open project window. With no project window open, the call fails with "no project window is available". Brave mode runs these tools without asking, with or without a window.
|
||||
|
||||
## Safety
|
||||
|
||||
- **Untrusted projects** expose only the read-only tools. Tools that write files, rename, reformat, build or run need a project you have trusted.
|
||||
- **Running and building ask first.** `execute_run_configuration`, `build_project`, `run_command` and `http_run_request` show a dialog in OpenIDEA naming the client, the project, the tool and what will run. Choose **Allow** or **Deny**; several requests queue up.
|
||||
- **Untrusted projects** expose only the read-only tools. Tools that write files, rename, reformat, build or run need a project you have trusted. A client started outside every project sees every tool, and so does one that names no project while no window or several windows are open. A tool that writes or runs still refuses a project you have not trusted.
|
||||
- **Running and building ask first.** `execute_run_configuration`, `build_project`, `run_command` and `http_run_request` show a dialog in OpenIDEA naming the client, the project, the tool and what will run. Choose **Allow** or **Deny**; several requests queue up. In a background project, all of them but `run_command` ask in the project window you used last, and the dialog names the project.
|
||||
- Tools that write refuse paths outside the project.
|
||||
- **Background projects.** Anyone with the token can make the IDE load a project that **Serve without a window** serves, so the setting and the token decide who can open folders on this computer. Listed folders you have not trusted open in Restricted Mode and get only the read-only tools. Keep the list to folders you want agents to reach.
|
||||
|
||||
|
||||
@@ -145,6 +145,17 @@ The **Ports** tool window is available in a WSL window too. Because the distribu
|
||||
`localhost`, a forwarded port is reachable here on the same port; the window lists, opens and remembers ports as it
|
||||
does for SSH.
|
||||
|
||||
### Run a Windows project in WSL
|
||||
|
||||
A project on the Windows file system can keep its local window and run its configurations in a distribution: in
|
||||
**Settings › Build, Execution, Deployment › Run Targets**, add a target of **Type** **WSL** (offered when a
|
||||
distribution is installed) and pick the **WSL distribution**. A configuration with that target under **Run on** runs as
|
||||
`wsl.exe -d <distribution> --cd <folder> --exec <program> <arguments>`. Project paths become their `/mnt/<drive>`
|
||||
paths (`C:\work\app` is `/mnt/c/work/app`); set **Project folder in WSL** when the distribution mounts drives
|
||||
elsewhere. Interpreters left empty are looked up on the distribution's `PATH` (`python3`, `node`, `java`). Environment
|
||||
variables reach the distribution through `WSLENV`. Debugging, coverage and profiling are not available on a WSL
|
||||
target.
|
||||
|
||||
## Other uses of SSH configurations
|
||||
|
||||
- **Run targets** (**Settings › Build, Execution, Deployment › Run Targets**) run a configuration on an SSH host. See
|
||||
|
||||
@@ -79,26 +79,27 @@ With **Shell integration** on, zsh, bash and fish report the current directory a
|
||||
|
||||
**Settings › Tools › Terminal**:
|
||||
|
||||
| Setting | Default | Notes |
|
||||
| ---------------------------------------- | ------------ | --------------------------------------------------------------------------------------------------------------------- |
|
||||
| **Start directory** | Project root | Relative paths resolve against the project root. **Open in Terminal** still opens the chosen folder. Project setting. |
|
||||
| **Environment variables** | none | Added to new sessions. Project setting. |
|
||||
| **Shell path** | login shell | A command line, e.g. `/bin/zsh --login`. **Installed Shells** lists what was found. |
|
||||
| **Default Tab name** | `Local` | |
|
||||
| **Audible bell** | on | |
|
||||
| **Close session when it ends** | on | |
|
||||
| **Mouse reporting** | on | Off: programs can't capture the mouse. |
|
||||
| **Copy to clipboard on selection** | off | |
|
||||
| **Paste on middle mouse button click** | on | |
|
||||
| **Paste on right click** | off | On: right-click pastes; Ctrl or Shift + right-click opens the context menu. |
|
||||
| **Move focus to the Editor with Escape** | off | Otherwise `Esc` goes to the shell. |
|
||||
| **Override IDE shortcuts** | on | See above. |
|
||||
| **Shell integration** | on | |
|
||||
| **Highlight hyperlinks** | on | |
|
||||
| **Use Option as Meta key** | off | macOS only. |
|
||||
| **Cursor shape** | Block | Block, Underline or Vertical. |
|
||||
| **Blinking cursor** | on | |
|
||||
| **Use editor font** | on | Off: set **Font**, **Size** (6–72), **Line height**, **Fallback font** and **Column width**. |
|
||||
| Setting | Default | Notes |
|
||||
| ----------------------------------------------- | ------------ | ------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| **Start directory** | Project root | Relative paths resolve against the project root. **Open in Terminal** still opens the chosen folder. Project setting. |
|
||||
| **Environment variables** | none | Added to new sessions. Project setting. |
|
||||
| **Shell path** | login shell | A command line, e.g. `/bin/zsh --login`. **Installed Shells** lists what was found. |
|
||||
| **Default Tab name** | `Local` | |
|
||||
| **Audible bell** | on | |
|
||||
| **Close session when it ends** | on | |
|
||||
| **Mouse reporting** | on | Off: programs can't capture the mouse. |
|
||||
| **Copy to clipboard on selection** | off | |
|
||||
| **Let programs copy to the clipboard (OSC 52)** | on | tmux (`set-clipboard on`), Neovim and other programs set the clipboard, also over SSH. They can't read it; payloads over 1 MiB are ignored. |
|
||||
| **Paste on middle mouse button click** | on | |
|
||||
| **Paste on right click** | off | On: right-click pastes; Ctrl or Shift + right-click opens the context menu. |
|
||||
| **Move focus to the Editor with Escape** | off | Otherwise `Esc` goes to the shell. |
|
||||
| **Override IDE shortcuts** | on | See above. |
|
||||
| **Shell integration** | on | |
|
||||
| **Highlight hyperlinks** | on | |
|
||||
| **Use Option as Meta key** | off | macOS only. |
|
||||
| **Cursor shape** | Block | Block, Underline or Vertical. |
|
||||
| **Blinking cursor** | on | |
|
||||
| **Use editor font** | on | Off: set **Font**, **Size** (6–72), **Line height**, **Fallback font** and **Column width**. |
|
||||
|
||||
Changes apply to open sessions right away. Colours follow the IDE theme.
|
||||
|
||||
|
||||
@@ -278,7 +278,7 @@ Retention is set in the **Local History** section of **Settings › Appearance &
|
||||
| ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| **Commit** | Non-modal commit interface, clearing the message after commit, message inspections (blank line after subject, subject and body length, right margin), default commit checks. |
|
||||
| **Confirmation** | What to do when files are created or deleted, **Show options before Update**, confirm before dropping commits, highlight modified folders in the Project view, history row limit. |
|
||||
| **Directory Mappings** | Add and remove Git repository mappings and exclude auto-detected repositories from Git integration. |
|
||||
| **Directory Mappings** | Add and remove Git repository mappings and exclude auto-detected repositories from Git integration. Unreachable mapped repositories are marked unavailable while other repositories keep working. |
|
||||
| **Issue Navigation** | Regex patterns that turn issue IDs in commit messages into links (presets for JIRA, YouTrack and GitHub). |
|
||||
| **Log** | Reference and time display, visible columns. |
|
||||
| **Shelf** | Remove applied files from the shelf. |
|
||||
|
||||
@@ -1,20 +1,22 @@
|
||||
---
|
||||
title: "C# and .NET"
|
||||
description: "C# with csharp-ls, F# with FsAutoComplete, the .NET tool window for builds, NuGet packages and tests, and debugging with netcoredbg."
|
||||
description: "C# with the Roslyn language server or csharp-ls, F# with FsAutoComplete, the .NET tool window for builds, NuGet packages and tests, and debugging with netcoredbg."
|
||||
---
|
||||
|
||||
OpenIDEA supports C# (`.cs`, `.csx`) through [csharp-ls](https://github.com/razzmatazz/csharp-language-server) and F# (`.fs`, `.fsi`, `.fsx`) through [FsAutoComplete](https://github.com/ionide/FsAutoComplete). Both are installed as .NET tools, and both debug with [netcoredbg](https://github.com/Samsung/netcoredbg). Builds, NuGet packages and tests go through the `dotnet` CLI. For other languages, see the [support matrix](/en/languages/index).
|
||||
OpenIDEA supports C# (`.cs`, `.csx`) through Microsoft's [Roslyn language server](https://github.com/dotnet/roslyn) or [csharp-ls](https://github.com/razzmatazz/csharp-language-server), and F# (`.fs`, `.fsi`, `.fsx`) through [FsAutoComplete](https://github.com/ionide/FsAutoComplete). All of them are installed as .NET tools, and both languages debug with [netcoredbg](https://github.com/Samsung/netcoredbg). Builds, NuGet packages and tests go through the `dotnet` CLI. For other languages, see the [support matrix](/en/languages/index).
|
||||
|
||||
## Language server
|
||||
|
||||
| Language | Server | Workspace root markers |
|
||||
| -------- | -------------- | ----------------------------------------------------------------------------------------------------------- |
|
||||
| C# | csharp-ls | `*.sln`, `*.slnx`, `*.csproj`, `global.json`, `Directory.Build.props`, `ProjectSettings/ProjectVersion.txt` |
|
||||
| F# | fsautocomplete | `*.sln`, `*.fsproj`, `global.json` |
|
||||
| Language | Server | Workspace root markers |
|
||||
| -------- | ----------------------------------- | ----------------------------------------------------------------------------------------------------------- |
|
||||
| C# | roslyn-language-server or csharp-ls | `*.sln`, `*.slnx`, `*.csproj`, `global.json`, `Directory.Build.props`, `ProjectSettings/ProjectVersion.txt` |
|
||||
| F# | fsautocomplete | `*.sln`, `*.fsproj`, `global.json` |
|
||||
|
||||
For C#, the IDE uses the Roslyn language server when it is installed and csharp-ls otherwise. Roslyn is the server of the VS Code C# extension. It needs the .NET 10 SDK or newer; csharp-ls also runs on older SDKs. With Roslyn, completion also lists types from namespaces the file doesn't import yet (shown with their namespace), and accepting one adds the `using` directive. Roslyn starts with `--autoLoadProjects`, so it finds and opens the solution or projects itself. On macOS and Linux it loads SDK-style projects only: .NET Framework projects need Mono MSBuild, which it doesn't use. Unity's Visual Studio Editor package generates SDK-style `.csproj` files.
|
||||
|
||||
The server loads the solution or project it finds from these markers. FsAutoComplete starts with `AutomaticWorkspaceInit` on, so it loads the projects without waiting for the editor to ask.
|
||||
|
||||
When you go to the definition of a library type, csharp-ls returns decompiled source. It opens as a read-only document, and so does source-generated code.
|
||||
When you go to the definition of a library type, the server returns decompiled source. It opens as a read-only document, and so does source-generated code.
|
||||
|
||||
`ProjectSettings/ProjectVersion.txt` is there so that Unity projects work too. See [Unity](/en/languages/unity) for using OpenIDEA as Unity's external editor.
|
||||
|
||||
@@ -22,17 +24,18 @@ When you go to the definition of a library type, csharp-ls returns decompiled so
|
||||
|
||||
You need the [.NET SDK](https://dotnet.microsoft.com/download) with `dotnet` on your `PATH`. The IDE runs every build, test and package command through it, and installs the language servers with it.
|
||||
|
||||
When a server is missing, opening a C# or F# file shows a "csharp-ls is not installed" (or FsAutoComplete) notification with **Install**. You can also install the tools from **Settings › Languages & Frameworks › Language Servers**.
|
||||
When no server is installed, opening a C# or F# file shows a "Roslyn (C#) is not installed" (or FsAutoComplete) notification with **Install**. If your SDK is older than .NET 10, the install says so and suggests csharp-ls instead. You can also install the tools from **Settings › Languages & Frameworks › Language Servers**.
|
||||
|
||||
| Tool | How it is installed |
|
||||
| -------------- | ------------------------------------------------------------------------------------------------------------------------- |
|
||||
| Roslyn (C#) | `dotnet tool install --prerelease --tool-path` into the IDE's tools folder; nuget.org has only prerelease builds of it |
|
||||
| csharp-ls | `dotnet tool install --tool-path` into the IDE's tools folder (not a global tool) |
|
||||
| FsAutoComplete | `dotnet tool install --tool-path` into the IDE's tools folder |
|
||||
| netcoredbg | Downloaded from the `Samsung/netcoredbg` GitHub releases. Prebuilt for macOS arm64, Linux x64 and arm64, and Windows x64. |
|
||||
|
||||
Before it installs csharp-ls or FsAutoComplete, the IDE compares the newest SDK in `dotnet --list-sdks` with the .NET version the tool's latest release on nuget.org targets. When the SDK is older, it installs the newest release that runs on it, or tells you which SDK to install.
|
||||
|
||||
A `csharp-ls`, `fsautocomplete` or `netcoredbg` already on your `PATH` (for example a global `dotnet tool install --global csharp-ls`) is used as is.
|
||||
A `roslyn-language-server`, `csharp-ls`, `fsautocomplete` or `netcoredbg` already on your `PATH` (for example a global `dotnet tool install --global csharp-ls`) is used as is.
|
||||
|
||||
## The .NET tool window
|
||||
|
||||
|
||||
@@ -65,7 +65,7 @@ The IDE never needs `sudo`. It installs tools into its own tools folder in the l
|
||||
| `go install` | gopls, Delve, sqls. Needs Go. |
|
||||
| `rustup component add` | rust-analyzer (falls back to a download from Open VSX). |
|
||||
| `gem install` | Solargraph into its own gem home; Ruby LSP into the project's Ruby. |
|
||||
| `dotnet tool install` | csharp-ls, FsAutoComplete. Needs the .NET SDK. |
|
||||
| `dotnet tool install` | Roslyn (C#), csharp-ls, FsAutoComplete. Needs the .NET SDK. |
|
||||
| Release download | clangd, CodeLLDB, vscode-js-debug, JDT LS, java-debug, Kotlin LSP, Lua, Marksman, Taplo, ZLS, terraform-ls and others, from GitHub, Open VSX, Maven Central, the Eclipse download site or HashiCorp. |
|
||||
| Bundled | The Lombok agent for JDT LS ships with the app. |
|
||||
|
||||
@@ -99,7 +99,7 @@ The table lists every built-in language definition. Server and debugger names in
|
||||
| Astro | `astro` | `.astro` | Yes | — | **astro-ls** + **oxlint** | — |
|
||||
| Batch | `bat` | `.bat`, `.cmd` | Yes | — | — | — |
|
||||
| C | `c` | `.c`, `.h` | Yes | Yes | **clangd** | lldb-dap |
|
||||
| C# | `csharp` | `.cs`, `.csx` | Yes | Yes | **csharp-ls** | **netcoredbg** |
|
||||
| C# | `csharp` | `.cs`, `.csx` | Yes | Yes | **roslyn-language-server** → **csharp-ls** | **netcoredbg** |
|
||||
| C++ | `cpp` | `.cpp`, `.cc`, `.cxx`, `.c++`, `.hpp`, … | Yes | Yes | **clangd** | lldb-dap |
|
||||
| Clojure | `clojure` | `.clj`, `.cljs`, `.cljc`, `.cljd`, `.edn`, … | Yes | — | **clojure-lsp** | — |
|
||||
| CMake | `cmake` | `.cmake` | Yes | Yes | **neocmakelsp** → cmake-language-server | — |
|
||||
|
||||
@@ -68,6 +68,14 @@ When the project's dependencies are installed only in an image, choose a Docker
|
||||
|
||||
A `pyrightconfig.json` or a `[tool.basedpyright]` / `[tool.pyright]` section with its own `extraPaths` replaces the copied paths. The interpreter's Python version is the empty virtualenv's, from a local Python of the same version when there is one.
|
||||
|
||||
### A Python in WSL as the interpreter
|
||||
|
||||
On Windows with WSL, **Add Python Interpreter** has a **WSL** entry: pick the **Distribution** and the **Python interpreter** (the ones found on its `PATH`, in `/usr/bin` and `/usr/local/bin`, pyenv's, and the project's `.venv` / `venv`; another path can be typed). **OK** adds a WSL [run target](/en/guide/remote/ssh#run-a-windows-project-in-wsl) with that Python and makes it the project interpreter.
|
||||
|
||||
- **Editor.** The IDE runs that Python once in the distribution to read its `sys.path`. basedpyright and Pyright read those folders in place through `\\wsl.localhost\<distribution>` (nothing is copied), with an empty local virtualenv as their interpreter, as for a Docker target. They are shown under **External Libraries**.
|
||||
- **Run.** Python run configurations without a run target of their own run in the distribution.
|
||||
- **Packages.** The list is read-only: install packages in WSL, then reload it.
|
||||
|
||||
### Creating an environment
|
||||
|
||||
On **Settings › Languages & Frameworks › Python Interpreter**, choose **Add Python Interpreter** and pick the **Interpreter type**:
|
||||
|
||||
@@ -76,9 +76,9 @@ When Git asks whether to add a new file you created in the IDE, the `.meta` file
|
||||
|
||||
## Code intelligence
|
||||
|
||||
C# in a Unity project uses the same language server as any other C# project, csharp-ls; see [C# and .NET](/en/languages/csharp) for installation. A Unity project is a workspace root for it even before a solution exists.
|
||||
C# in a Unity project uses the same language server as any other C# project (Roslyn, or csharp-ls); see [C# and .NET](/en/languages/csharp) for installation. A Unity project is a workspace root for it even before a solution exists.
|
||||
|
||||
csharp-ls reads the `.sln` and `.csproj` files that Unity generates. When they are missing, the Unity pane shows:
|
||||
The server reads the `.sln` and `.csproj` files that Unity generates. When they are missing, the Unity pane shows:
|
||||
|
||||
> C# project files are missing. In Unity, select an external script editor in Preferences > External Tools, then regenerate project files.
|
||||
|
||||
|
||||
Loaded 100 of 371 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Заблокувати користувача