дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-01 06:42:54 +02:00
Порівняти коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
07456e8efe | ||
|
|
b2d03ac5f0 | ||
|
|
4e735eadcb | ||
|
|
50ba6b5c56 | ||
|
|
36910712d1 | ||
|
|
5b99b8b5ab | ||
|
|
f3874b9b2e | ||
|
|
18b87b066b | ||
|
|
41a76ca0d7 | ||
|
|
1bf29ab3d7 | ||
|
|
49b52a8bfa | ||
|
|
77342b8e71 | ||
|
|
369ff7cec8 | ||
|
|
4016c410db | ||
|
|
3c3d02d7be | ||
|
|
2f66eb0503 | ||
|
|
63db10a688 | ||
|
|
1dd3d64781 | ||
|
|
8ac194cf50 | ||
|
|
3b488a7824 | ||
|
|
b5e89aace0 |
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",
|
||||
|
||||
Створено
@@ -4166,6 +4166,7 @@ dependencies = [
|
||||
"ide-tools",
|
||||
"ide-vcs",
|
||||
"ide-vfs",
|
||||
"libsqlite3-sys",
|
||||
"parking_lot 0.12.5",
|
||||
"rustix",
|
||||
"semver",
|
||||
|
||||
@@ -115,6 +115,7 @@ reqwest = { version = "0.13", default-features = false, features = ["rustls-no-p
|
||||
rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12", "logging"] }
|
||||
rustls-platform-verifier = "0.7"
|
||||
# Until SQLx releases its libsqlite3-sys 0.39 update (RUSTSEC-2026-0459).
|
||||
libsqlite3-sys = { version = "0.39", features = ["bundled"] }
|
||||
sqlx = { version = "0.9", git = "https://github.com/l0ng-ai/sqlx", rev = "9894985a1babc7e6bc0437da4fd43e3143184073", default-features = false, features = ["runtime-tokio", "tls-rustls-ring-webpki", "sqlite", "postgres", "mysql"] }
|
||||
tiberius = { version = "0.13", default-features = false, features = ["tds73", "rustls", "sql-browser-tokio"] }
|
||||
# Pure-Rust thin Oracle driver; pinned to the beta until it stabilizes.
|
||||
|
||||
@@ -15,6 +15,7 @@ ide-mcp.workspace = true
|
||||
ide-jsonrpc.workspace = true
|
||||
ide-vcs.workspace = true
|
||||
ide-tools = { path = "../ide-tools" }
|
||||
libsqlite3-sys.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
specta.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,
|
||||
@@ -246,6 +247,311 @@ 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)
|
||||
})
|
||||
}
|
||||
|
||||
struct SqliteDb(*mut libsqlite3_sys::sqlite3);
|
||||
|
||||
impl SqliteDb {
|
||||
fn open_readonly(path: &Path) -> Option<Self> {
|
||||
if !path.is_file() {
|
||||
return None;
|
||||
}
|
||||
let c_path = std::ffi::CString::new(path.to_str()?).ok()?;
|
||||
let mut raw: *mut libsqlite3_sys::sqlite3 = std::ptr::null_mut();
|
||||
let flags = libsqlite3_sys::SQLITE_OPEN_READONLY | libsqlite3_sys::SQLITE_OPEN_NOMUTEX;
|
||||
let rc = unsafe { libsqlite3_sys::sqlite3_open_v2(c_path.as_ptr(), &mut raw, flags, std::ptr::null()) };
|
||||
let guard = Self(raw);
|
||||
if rc != libsqlite3_sys::SQLITE_OK || raw.is_null() {
|
||||
return None;
|
||||
}
|
||||
unsafe {
|
||||
libsqlite3_sys::sqlite3_busy_timeout(raw, 200);
|
||||
}
|
||||
Some(guard)
|
||||
}
|
||||
|
||||
fn prepare(&self, sql: &str) -> Option<SqliteStmt> {
|
||||
let c_sql = std::ffi::CString::new(sql).ok()?;
|
||||
let mut stmt: *mut libsqlite3_sys::sqlite3_stmt = std::ptr::null_mut();
|
||||
let rc =
|
||||
unsafe { libsqlite3_sys::sqlite3_prepare_v2(self.0, c_sql.as_ptr(), -1, &mut stmt, std::ptr::null_mut()) };
|
||||
let guard = SqliteStmt(stmt);
|
||||
(rc == libsqlite3_sys::SQLITE_OK && !stmt.is_null()).then_some(guard)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for SqliteDb {
|
||||
fn drop(&mut self) {
|
||||
if !self.0.is_null() {
|
||||
unsafe {
|
||||
libsqlite3_sys::sqlite3_close(self.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct SqliteStmt(*mut libsqlite3_sys::sqlite3_stmt);
|
||||
|
||||
impl SqliteStmt {
|
||||
fn step(&self) -> bool {
|
||||
unsafe { libsqlite3_sys::sqlite3_step(self.0) == libsqlite3_sys::SQLITE_ROW }
|
||||
}
|
||||
|
||||
fn text(&self, col: std::ffi::c_int) -> Option<String> {
|
||||
unsafe {
|
||||
let ptr = libsqlite3_sys::sqlite3_column_text(self.0, col);
|
||||
if ptr.is_null() {
|
||||
return None;
|
||||
}
|
||||
let len = libsqlite3_sys::sqlite3_column_bytes(self.0, col);
|
||||
if len <= 0 {
|
||||
return None;
|
||||
}
|
||||
let bytes = std::slice::from_raw_parts(ptr, len as usize);
|
||||
std::str::from_utf8(bytes).ok().map(str::to_owned)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for SqliteStmt {
|
||||
fn drop(&mut self) {
|
||||
if !self.0.is_null() {
|
||||
unsafe {
|
||||
libsqlite3_sys::sqlite3_finalize(self.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 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
|
||||
}
|
||||
|
||||
/// Session titles VS Code's Agent Host (`vscode-agent-host`) assigns to backing Copilot CLI
|
||||
/// sessions (`sdkSessionId` → summary or user rename), read from `agent-host.db` without writing.
|
||||
fn vscode_copilot_titles(home: Option<&Path>) -> HashMap<String, String> {
|
||||
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 Some(home) = home else { return HashMap::new() };
|
||||
let mut titles = HashMap::new();
|
||||
for path in vscode_agent_host_dbs(home) {
|
||||
let Some(db) = SqliteDb::open_readonly(&path) else { continue };
|
||||
let Some(stmt) = db.prepare(FULL_QUERY).or_else(|| db.prepare(FALLBACK_QUERY)) else { continue };
|
||||
while stmt.step() {
|
||||
let Some(pdata) = stmt.text(0) 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;
|
||||
};
|
||||
let scs_title = stmt.text(1);
|
||||
let scs_source = stmt.text(2);
|
||||
let metadata = stmt.text(3);
|
||||
let payload = stmt.text(4);
|
||||
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
|
||||
}
|
||||
|
||||
/// 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)]));
|
||||
Some((
|
||||
ExternalSession { provider: "copilot".to_owned(), session_id, title, cwd, updated_ms: mtime(&events) },
|
||||
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 +650,116 @@ 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: &str) {
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
let c_path = std::ffi::CString::new(path.to_str().unwrap()).unwrap();
|
||||
let c_sql = std::ffi::CString::new(sql).unwrap();
|
||||
unsafe {
|
||||
let mut db: *mut libsqlite3_sys::sqlite3 = std::ptr::null_mut();
|
||||
assert_eq!(
|
||||
libsqlite3_sys::sqlite3_open_v2(
|
||||
c_path.as_ptr(),
|
||||
&mut db,
|
||||
libsqlite3_sys::SQLITE_OPEN_READWRITE | libsqlite3_sys::SQLITE_OPEN_CREATE,
|
||||
std::ptr::null(),
|
||||
),
|
||||
libsqlite3_sys::SQLITE_OK
|
||||
);
|
||||
assert_eq!(
|
||||
libsqlite3_sys::sqlite3_exec(db, c_sql.as_ptr(), None, std::ptr::null_mut(), std::ptr::null_mut()),
|
||||
libsqlite3_sys::SQLITE_OK
|
||||
);
|
||||
libsqlite3_sys::sqlite3_close(db);
|
||||
}
|
||||
}
|
||||
|
||||
#[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();
|
||||
|
||||
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_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");
|
||||
assert_eq!(by_id.remove("copilot-2").unwrap().title, "add a regression test");
|
||||
}
|
||||
|
||||
#[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,
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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,204 @@
|
||||
//! 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;
|
||||
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),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -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))),
|
||||
}
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -1063,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).
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -3405,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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -482,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")]
|
||||
|
||||
@@ -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,360 @@ 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"));
|
||||
let port = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap().local_addr().unwrap().port();
|
||||
let fixed = ServerOptions { port: Some(port), ..Default::default() };
|
||||
let runtime = tokio::runtime::Handle::current();
|
||||
let start_b = |registry: WithBackground| {
|
||||
McpServer::start_with(Arc::new(registry), Some(discovery.clone()), &runtime, fixed.clone()).unwrap()
|
||||
};
|
||||
// Neither serves `proj-b` at `initialize`, which settles on A, the server started last.
|
||||
let server_b = start_b(WithBackground { open: proj_c.clone(), background: Vec::new(), remote: None });
|
||||
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();
|
||||
let server_b = start_b(WithBackground::serving(&proj_c, &proj_b));
|
||||
assert_eq!(server_b.port(), port);
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -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(
|
||||
|
||||
@@ -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);
|
||||
|
||||
|
||||
@@ -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.
|
||||
|
||||
|
||||
@@ -35,7 +35,7 @@ optional = ["net:127.0.0.1", "clipboard.read"]
|
||||
"clipboard.read" = "Imports a log you copied, on the Log to SQL tab only."
|
||||
```
|
||||
|
||||
The dialog and the plugin's details in **Settings › Plugins** show it below the IDE's description, marked as the plugin's own words; it never replaces that description. Keys must be capabilities listed under `required` or `optional`, and each reason is 1 to 500 characters. Translate it like the plugin's other strings, with the English text as the key in `locales/<tag>.json`.
|
||||
The dialog and the plugin's details in **Settings › Plugins** show it below the IDE's description, marked as the plugin's own words; it never replaces that description. Keys must be capabilities listed under `required` or `optional`, or ones a contribution brings (`java.agent` from `[[contributes.javaAgents]]`, `project.read` from `[[contributes.documentIndexers]]`), and each reason is 1 to 500 characters. Translate it like the plugin's other strings, with the English text as the key in `locales/<tag>.json`.
|
||||
|
||||
When code finds an optional capability refused, `host::open_permissions()` opens **Settings › Plugins** at the plugin's permissions, so a notice can offer a button that goes straight there (from a command or event only).
|
||||
|
||||
@@ -49,33 +49,33 @@ Later:
|
||||
|
||||
## Capability reference
|
||||
|
||||
| Capability | Risk | Unlocks | API |
|
||||
| ------------------- | ------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------- |
|
||||
| `project.read` | Low | `Project::root`, `read_file`, `find_files`, `symbols`, `search_text`, `host::projects`, publishing diagnostics, `problems`, opening editors, decorations | 1.0 |
|
||||
| `project.write` | High | `Project::write_file`: creates and replaces text files inside the open projects, never git's own files (`.git`) | 1.3 |
|
||||
| `editor.read` | Low | `TextEditor::document`, `selections`, `host::open_editors` | 1.0 |
|
||||
| `editor.write` | Medium | `TextEditor::apply_edits` | 1.0 |
|
||||
| `vcs.read` | Low | `vcs_status`, `vcs_remotes`, `vcs_log`, `vcs_blame`, `vcs_diff`, the pending commit, before-commit checks | 1.0 |
|
||||
| `vcs.write` | Medium | `vcs_fetch` (trusted projects only), `host::set_commit_message` | 1.0 |
|
||||
| `build.read` | Low | `build_dependencies`: the Maven / Gradle dependency graph the IDE resolved; trusted projects only | 1.10 |
|
||||
| `storage` | Low | `host::storage`, 64 MiB per plugin | 1.0 |
|
||||
| `events` | Low | File opened, closed and saved, files changed, editor focused, repository changed, settings changed | 1.0 |
|
||||
| `events.input` | Medium | `action-performed` and `input-mode-changed` events (keystrokes and editor input) | 1.0 |
|
||||
| `clipboard` | Medium | `host::copy_to_clipboard` and the clipboard API in the plugin's web views | 1.0 |
|
||||
| `clipboard.read` | Medium | `host::read_clipboard`: the clipboard's text and image, only in commands and view actions the user ran (event handlers and other unattended calls are denied) | 1.11 |
|
||||
| `agents` | Medium | `host::fork_agent_session`: fork a recorded native agent session (`claude` or `codex`) into a new task in the invoking window's project; trusted projects only | 1.18 |
|
||||
| `secrets` | Medium | `{{secret:<name>}}` in request headers, `secret_is_set`, `secret_set`, `secret_delete` | 1.0 |
|
||||
| `net:<host>` | Medium | `host::fetch` / `host::fetch_stream` over HTTPS (and loopback HTTP) to that host; `*.example.com` matches subdomains | 1.0 |
|
||||
| `net:ask` | Medium | Ask the user at the first request to an HTTPS host that isn't declared | 1.5 |
|
||||
| `net.http:<host>` | Medium | Unencrypted HTTP to that host | 1.4 |
|
||||
| `database.sources` | Medium | Manage only the plugin's own project database sources and write their credentials; trusted projects only | 1.4 |
|
||||
| `fs.read:<path>` | High | `host::fs` reads outside the projects, under that path | 1.0 (the `fs` interface: 1.3) |
|
||||
| `fs.write:<path>` | High | `host::fs` writes outside the projects, under that path; does not imply reading | 1.3 |
|
||||
| `process:<program>` | High | Run that program: `run_process`, `run_command`, `start`, terminals, language servers, debug adapters, runs | 1.0 |
|
||||
| `lsp:<server>` | High | Send that running language server its own requests (`language_server_request`); trusted projects only | 1.9 |
|
||||
| `java.agent` | High | Run the plugin's Java agent inside the Java applications you start (see [Java agents](#java-agents)) | 1.10 |
|
||||
| `ipc:<path>` | High | Local Unix sockets or Windows named pipes on the project machine | 1.4 |
|
||||
| `ide.commands` | High | Run any IDE action or another plugin's command as if the user chose it, including running programs, committing and pushing. The plugin's own commands are exempt. | 1.4 |
|
||||
| Capability | Risk | Unlocks | API |
|
||||
| ------------------- | ------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------- |
|
||||
| `project.read` | Low | `Project::root`, `read_file`, `find_files`, `symbols`, `search_text`, `host::projects`, publishing diagnostics, `problems`, opening editors, decorations | 1.0 |
|
||||
| `project.write` | High | `Project::write_file`: creates and replaces text files inside the open projects, never git's own files (`.git`) | 1.3 |
|
||||
| `editor.read` | Low | `TextEditor::document`, `selections`, `host::open_editors` | 1.0 |
|
||||
| `editor.write` | Medium | `TextEditor::apply_edits` | 1.0 |
|
||||
| `vcs.read` | Low | `vcs_status`, `vcs_remotes`, `vcs_log`, `vcs_blame`, `vcs_diff`, the pending commit, before-commit checks | 1.0 |
|
||||
| `vcs.write` | Medium | `vcs_fetch` (trusted projects only), `host::set_commit_message` | 1.0 |
|
||||
| `build.read` | Low | `build_dependencies`: the Maven / Gradle dependency graph the IDE resolved; trusted projects only | 1.10 |
|
||||
| `storage` | Low | `host::storage`, 64 MiB per plugin | 1.0 |
|
||||
| `events` | Low | File opened, closed and saved, files changed, editor focused, repository changed, settings changed | 1.0 |
|
||||
| `events.input` | Medium | `action-performed` and `input-mode-changed` events (keystrokes and editor input) | 1.0 |
|
||||
| `clipboard` | Medium | `host::copy_to_clipboard` and the clipboard API in the plugin's web views | 1.0 |
|
||||
| `clipboard.read` | Medium | `host::read_clipboard`: the clipboard's text and image, only in commands and view actions the user ran (event handlers and other unattended calls are denied) | 1.11 |
|
||||
| `agents` | Medium | `host::fork_agent_session`: fork a recorded native agent session (`claude`, `codex`, or `copilot`) into a new task in the invoking window's project; trusted projects only | 1.18 |
|
||||
| `secrets` | Medium | `{{secret:<name>}}` in request headers, `secret_is_set`, `secret_set`, `secret_delete` | 1.0 |
|
||||
| `net:<host>` | Medium | `host::fetch` / `host::fetch_stream` over HTTPS (and loopback HTTP) to that host; `*.example.com` matches subdomains | 1.0 |
|
||||
| `net:ask` | Medium | Ask the user at the first request to an HTTPS host that isn't declared | 1.5 |
|
||||
| `net.http:<host>` | Medium | Unencrypted HTTP to that host | 1.4 |
|
||||
| `database.sources` | Medium | Manage only the plugin's own project database sources and write their credentials; trusted projects only | 1.4 |
|
||||
| `fs.read:<path>` | High | `host::fs` reads outside the projects, under that path | 1.0 (the `fs` interface: 1.3) |
|
||||
| `fs.write:<path>` | High | `host::fs` writes outside the projects, under that path; does not imply reading | 1.3 |
|
||||
| `process:<program>` | High | Run that program: `run_process`, `run_command`, `start`, terminals, language servers, debug adapters, runs | 1.0 |
|
||||
| `lsp:<server>` | High | Send that running language server its own requests (`language_server_request`); trusted projects only | 1.9 |
|
||||
| `java.agent` | High | Run the plugin's Java agent inside the Java applications you start (see [Java agents](#java-agents)) | 1.10 |
|
||||
| `ipc:<path>` | High | Local Unix sockets or Windows named pipes on the project machine | 1.4 |
|
||||
| `ide.commands` | High | Run any IDE action or another plugin's command as if the user chose it, including running programs, committing and pushing. The plugin's own commands are exempt. | 1.4 |
|
||||
|
||||
The **API** column is the oldest plugin API the manifest may admit when it declares the capability. For example, a manifest with `net.http:` must require `engines.openidea = "^1.4"` or later; installing and `openidea-plugin check` refuse it otherwise.
|
||||
|
||||
|
||||
@@ -12,28 +12,28 @@ The plugin API has one version number: the version of the WIT package in [`wit/`
|
||||
|
||||
## Versions
|
||||
|
||||
| API | Shipped with | Highlights |
|
||||
| ------ | ------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| 1.0.0 | OpenIDEA 0.1.36 | The base API: commands, events, storage, tasks, project and editor access, VCS, diagnostics, network and secrets, processes, declarative views and custom editors, settings, editor providers, syntax provider |
|
||||
| 1.1.0 | OpenIDEA 0.1.37 | `vcs.remotes`, `ui.copy-to-clipboard`, `ui.open-url`, opening a project file at a line from a view |
|
||||
| 1.2.0 | OpenIDEA 0.1.38 | Background document indexers, pickers, input boxes and confirmations, plugin context keys for `when` clauses, the files selected in the Project view, a manifest `icon`, the `viewItem.context` menu |
|
||||
| 1.3.0 | OpenIDEA 0.1.39 | Commit message and before-commit checks, Services detail panes, diagnostics while typing, hover, inlay hints, semantic tokens, file-changing code actions, HTTP endpoints, files outside the project (`fs.read`/`fs.write`, `project.write`, private plugin directory), batched `files-changed` events and path filters, workspace symbols, long-running processes, notifications with buttons, translations, multi-page settings, file template variables, web view PTYs, log tabs and content tabs |
|
||||
| 1.4.0 | OpenIDEA 0.1.40 | `net.http:`, `ipc:`, `ide.commands` and `database.sources` capabilities; editor and project snapshots, decorations, text search, Problems, Git log/blame/diff; output channels; OAuth loopback; runs, terminal sessions, run configurations, test result parsing and run targets; formatting and other language features; embedded languages; snippets; more menu locations; database sources; MCP tools |
|
||||
| 1.5.0 | OpenIDEA 0.1.41 | `Project::notify` (a notification in one project's window), the `net:ask` capability, run target validation, per-command run target working-directory arguments |
|
||||
| 1.6.0 | OpenIDEA 0.1.43 | Bounded, project-bound background WebSockets for event-stream plugins |
|
||||
| 1.7.0 | OpenIDEA 0.1.44 | `views.open-diff`: two texts in the diff viewer, such as a review's file before and after |
|
||||
| 1.8.0 | OpenIDEA 0.1.45 | The `problems-changed` workbench event: the host keeps every producer's diagnostics per file, so an annotation follows the file rather than the invoking window |
|
||||
| 1.9.0 | OpenIDEA 0.1.46 | Run configurations with an environment and a debugger, requests to a running language server (`lsp:<server>`), server commands routed to plugins, editor panels |
|
||||
| 1.10.0 | OpenIDEA 0.1.47 | `build.dependencies`: the Maven / Gradle dependency graph the IDE resolved (`build.read`) |
|
||||
| 1.11.0 | In development on `main` | `ui.read-clipboard`: the clipboard's text and image in commands the user ran (`clipboard.read`) |
|
||||
| 1.12.0 | In development on `main` | `ui.set-console-rules`: highlight rules (regex, palette colours, styles) for Run and Debug console output |
|
||||
| 1.13.0 | OpenIDEA 0.1.49 | Optional `search-provider` export and `searchCategories`: custom Search Everywhere tabs with cancellable queries |
|
||||
| 1.14.0 | In development on `main` | Optional `hover-actions` export: left-edge line actions revealed by line-edge hover, with an anchor line and inclusive trigger range; `[[contributes.javaAgents]]` `vmOptions` / `jdk`: JVM flags (optionally JetBrains Runtime–only) before `-javaagent:`; `ui.set-status-item-menu` / `set-window-status-item-menu`: a menu on a status bar item |
|
||||
| 1.15.0 | In development on `main` | `caret-moved` event; declarative `[[contributes.skills]]` (`path = "skills/<name>/SKILL.md"`) for bundling agent skills in plugins |
|
||||
| 1.16.0 | OpenIDEA 0.1.52 | Optional `completion-list-provider` export: completion marked incomplete is asked again while typing on, without re-asking the language server or other plugins; `decorations.set-markdown`: line-end decorations whose hover is a Markdown card |
|
||||
| 1.17.0 | OpenIDEA 0.1.53 | `decorations.set-styled`: editor decorations with their own `#rrggbb` / `#rrggbbaa` foreground and background, for colors outside the theme palette |
|
||||
| 1.18.0 | OpenIDEA 0.1.54 | `[[contributes.overlays]]`: a package web page floating over the workbench that never takes the keyboard focus, placed and resized through `openidea.overlay`; `[[contributes.dialogs]]`: a package web page in a modal, resizable IDE dialog opened with `views.reveal`, with a `closed` view event and `openidea.dialog.close()`; `events.subscribe-paths-with-options` (`debounce-ms`), `workspace.project.generation` and `FilesChanged` project/generation fields, stale run target/configuration rejection, and the `project-closed` lifecycle event; `execution-configurations`, `run.start-with-options` and `runDetectors.outputMode`: `pipes` or `pty` console output for plugin run configurations; `[[contributes.runAnything]]` with the `run-anything-provider` export: Run Anything lines starting with the plugin's prefix; `views.open-terminal-session-in`: a keyed terminal in a project directory; `workspace.invoking-project`: the project of the window a call serves, also in `gutter-actions` and `hover-actions`; `events.watch-paths` and the `watched-files-changed` event: files and directories outside the project, within `fs.read` grants; the `run-configuration-completion` export: completion in the Arguments field of the plugin's own run configurations; `services.context` and `services.toolbar` menus on the IDE's own Services nodes, with the selected services as the command argument; `executor` on `[[contributes.javaAgents]]`: "Run/Debug '<name>' with <title>" beside Run and Debug, the only launches that get that agent, also startable from the plugin's own commands with a configuration id; grant-scoped `agents.fork-session`: fork a recorded native agent session (`claude` or `codex`) into a new task in the invoking window's project (`agents` capability), with the host validating the session and building the fork invocation itself |
|
||||
| 1.19.0 | In development on `main` | `[capabilities.reasons]`: the plugin's own sentence on why it asks for a capability, shown below the host's description in the permission dialog and Settings › Plugins; `settings.open` / `settings.open-permissions`: open Settings at one of the plugin's own pages or at its permissions; `net.fetch-stream`: a response whose body is read as it arrives (server-sent events, streamed model replies), with the SDK's `host::fetch_stream` and `sse` parser; `editor.open-as-text`: open a file in the built-in text editor even when a custom editor claims it (the SDK's `host::open_editor_as_text`); the `openIn` menu: the **Open In** submenu of the editor, its tab and the Project view |
|
||||
| API | Shipped with | Highlights |
|
||||
| ------ | ------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| 1.0.0 | OpenIDEA 0.1.36 | The base API: commands, events, storage, tasks, project and editor access, VCS, diagnostics, network and secrets, processes, declarative views and custom editors, settings, editor providers, syntax provider |
|
||||
| 1.1.0 | OpenIDEA 0.1.37 | `vcs.remotes`, `ui.copy-to-clipboard`, `ui.open-url`, opening a project file at a line from a view |
|
||||
| 1.2.0 | OpenIDEA 0.1.38 | Background document indexers, pickers, input boxes and confirmations, plugin context keys for `when` clauses, the files selected in the Project view, a manifest `icon`, the `viewItem.context` menu |
|
||||
| 1.3.0 | OpenIDEA 0.1.39 | Commit message and before-commit checks, Services detail panes, diagnostics while typing, hover, inlay hints, semantic tokens, file-changing code actions, HTTP endpoints, files outside the project (`fs.read`/`fs.write`, `project.write`, private plugin directory), batched `files-changed` events and path filters, workspace symbols, long-running processes, notifications with buttons, translations, multi-page settings, file template variables, web view PTYs, log tabs and content tabs |
|
||||
| 1.4.0 | OpenIDEA 0.1.40 | `net.http:`, `ipc:`, `ide.commands` and `database.sources` capabilities; editor and project snapshots, decorations, text search, Problems, Git log/blame/diff; output channels; OAuth loopback; runs, terminal sessions, run configurations, test result parsing and run targets; formatting and other language features; embedded languages; snippets; more menu locations; database sources; MCP tools |
|
||||
| 1.5.0 | OpenIDEA 0.1.41 | `Project::notify` (a notification in one project's window), the `net:ask` capability, run target validation, per-command run target working-directory arguments |
|
||||
| 1.6.0 | OpenIDEA 0.1.43 | Bounded, project-bound background WebSockets for event-stream plugins |
|
||||
| 1.7.0 | OpenIDEA 0.1.44 | `views.open-diff`: two texts in the diff viewer, such as a review's file before and after |
|
||||
| 1.8.0 | OpenIDEA 0.1.45 | The `problems-changed` workbench event: the host keeps every producer's diagnostics per file, so an annotation follows the file rather than the invoking window |
|
||||
| 1.9.0 | OpenIDEA 0.1.46 | Run configurations with an environment and a debugger, requests to a running language server (`lsp:<server>`), server commands routed to plugins, editor panels |
|
||||
| 1.10.0 | OpenIDEA 0.1.47 | `build.dependencies`: the Maven / Gradle dependency graph the IDE resolved (`build.read`) |
|
||||
| 1.11.0 | In development on `main` | `ui.read-clipboard`: the clipboard's text and image in commands the user ran (`clipboard.read`) |
|
||||
| 1.12.0 | In development on `main` | `ui.set-console-rules`: highlight rules (regex, palette colours, styles) for Run and Debug console output |
|
||||
| 1.13.0 | OpenIDEA 0.1.49 | Optional `search-provider` export and `searchCategories`: custom Search Everywhere tabs with cancellable queries |
|
||||
| 1.14.0 | In development on `main` | Optional `hover-actions` export: left-edge line actions revealed by line-edge hover, with an anchor line and inclusive trigger range; `[[contributes.javaAgents]]` `vmOptions` / `jdk`: JVM flags (optionally JetBrains Runtime–only) before `-javaagent:`; `ui.set-status-item-menu` / `set-window-status-item-menu`: a menu on a status bar item |
|
||||
| 1.15.0 | In development on `main` | `caret-moved` event; declarative `[[contributes.skills]]` (`path = "skills/<name>/SKILL.md"`) for bundling agent skills in plugins |
|
||||
| 1.16.0 | OpenIDEA 0.1.52 | Optional `completion-list-provider` export: completion marked incomplete is asked again while typing on, without re-asking the language server or other plugins; `decorations.set-markdown`: line-end decorations whose hover is a Markdown card |
|
||||
| 1.17.0 | OpenIDEA 0.1.53 | `decorations.set-styled`: editor decorations with their own `#rrggbb` / `#rrggbbaa` foreground and background, for colors outside the theme palette |
|
||||
| 1.18.0 | OpenIDEA 0.1.54 | `[[contributes.overlays]]`: a package web page floating over the workbench that never takes the keyboard focus, placed and resized through `openidea.overlay`; `[[contributes.dialogs]]`: a package web page in a modal, resizable IDE dialog opened with `views.reveal`, with a `closed` view event and `openidea.dialog.close()`; `events.subscribe-paths-with-options` (`debounce-ms`), `workspace.project.generation` and `FilesChanged` project/generation fields, stale run target/configuration rejection, and the `project-closed` lifecycle event; `execution-configurations`, `run.start-with-options` and `runDetectors.outputMode`: `pipes` or `pty` console output for plugin run configurations; `[[contributes.runAnything]]` with the `run-anything-provider` export: Run Anything lines starting with the plugin's prefix; `views.open-terminal-session-in`: a keyed terminal in a project directory; `workspace.invoking-project`: the project of the window a call serves, also in `gutter-actions` and `hover-actions`; `events.watch-paths` and the `watched-files-changed` event: files and directories outside the project, within `fs.read` grants; the `run-configuration-completion` export: completion in the Arguments field of the plugin's own run configurations; `services.context` and `services.toolbar` menus on the IDE's own Services nodes, with the selected services as the command argument; `executor` on `[[contributes.javaAgents]]`: "Run/Debug '<name>' with <title>" beside Run and Debug, the only launches that get that agent, also startable from the plugin's own commands with a configuration id; grant-scoped `agents.fork-session`: fork a recorded native agent session (`claude`, `codex`, or `copilot`) into a new task in the invoking window's project (`agents` capability), with the host validating the session and building the fork invocation itself |
|
||||
| 1.19.0 | In development on `main` | `[capabilities.reasons]`: the plugin's own sentence on why it asks for a capability, shown below the host's description in the permission dialog and Settings › Plugins; `settings.open` / `settings.open-permissions`: open Settings at one of the plugin's own pages or at its permissions; `net.fetch-stream`: a response whose body is read as it arrives (server-sent events, streamed model replies), with the SDK's `host::fetch_stream` and `sse` parser; `editor.open-as-text`: open a file in the built-in text editor even when a custom editor claims it (the SDK's `host::open_editor_as_text`); the `openIn` menu: the **Open In** submenu of the editor, its tab and the Project view |
|
||||
|
||||
The full list of what each version added is in [`plugins/README.md`](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md).
|
||||
|
||||
|
||||
@@ -78,6 +78,8 @@ stdio 配置大致如下(路径以你机器上的为准):
|
||||
|
||||
工具只在 OpenIDEA 运行,且项目已在窗口中打开或作为[后台项目](#后台项目)提供服务时可用。客户端可以指定这类项目中的任意目录,服务器会选出包含它的最内层项目,无论该项目在窗口中打开还是作为后台项目提供服务。位于窗口项目之内的后台项目负责它自己的目录,调用中的相对路径以它的根目录为准。例如在 **受信任的项目** 模式下,受信任位置中的仓库(包括 Git 子模块)在调用指定它的目录时会作为单独的后台项目加载,即使外层项目已在窗口中打开。HTTP 客户端通过 `X-OpenIDEA-Project` 请求头或 `?project=` 查询参数指定项目。
|
||||
|
||||
如果客户端在所有项目之外的目录中启动,例如只存放仓库的目录,它仍能拿到工具。此时每次调用都要用 `projectPath` 指定项目,服务器会拒绝没有指定项目的调用。
|
||||
|
||||
服务器运行期间,OpenIDEA 会把端口和令牌写入应用数据目录下的 `mcp/server.json`(只有你自己可读),stdio 转发程序从这里读取。
|
||||
|
||||
## 工具
|
||||
@@ -120,7 +122,7 @@ stdio 配置大致如下(路径以你机器上的为准):
|
||||
|
||||
`run_command` 在运行工具窗口的一个标签页中,用 **设置 › 工具 › 终端** 中配置的 shell 执行一条命令行。标签名由智能体指定,OpenIDEA 显示为 `_agent_<名称>`。输出实时可见,你也可以像对待其他运行一样向命令输入、重新运行或停止它。
|
||||
|
||||
智能体用 `execute_run_configuration` 启动的运行配置同样会在运行工具窗口中打开一个标签页,和你点击运行时一样:控制台显示输出,停止按钮可以结束它。没有窗口的后台项目(勇敢模式)中则不打开标签页。
|
||||
智能体用 `execute_run_configuration` 启动的运行配置同样会在运行工具窗口中打开一个标签页,和你点击运行时一样:控制台显示输出,停止按钮可以结束它。没有窗口的后台项目中则不打开标签页,前提是你已在项目窗口中允许它们,或开启了勇敢模式。
|
||||
|
||||
和 JetBrains 的 IDE 一样,命令通过管道运行,而不是在终端里运行:程序输出的是普通文本行,不会有进度条和屏幕重绘。智能体拿到的输出会去掉控制字符,并截断到 2000 行(`maxLinesCount`);超出部分默认保留结尾,也可以用 `truncateMode` 改为保留开头或两头。标签页的原始输出日志保持完整。
|
||||
|
||||
@@ -167,15 +169,15 @@ stdio 配置大致如下(路径以你机器上的为准):
|
||||
|
||||
后台项目没有窗口,所以有些工具不同:
|
||||
|
||||
- `run_command` 和 `open_file_in_editor` 需要窗口。
|
||||
- `run_command`、`open_file_in_editor`、`xdebug_start_debugger_session` 和断点工具(`xdebug_set_breakpoint`、`xdebug_remove_breakpoint`、`xdebug_list_breakpoints`)需要窗口,它们会在询问之前直接拒绝。
|
||||
- `get_file_problems` 和 `get_project_problems` 报告的是窗口中显示的内容。在后台项目中,它们会返回一个错误,指向 `check_files`。
|
||||
- `get_current_file` 和 `get_all_open_file_paths` 描述的同样是窗口。在后台项目中,它们会返回一个错误,说明该项目需要窗口。
|
||||
- 打开 **运行工具时不再确认(勇敢模式)** 后,`execute_run_configuration` 和 `build_project` 可以在后台项目中使用。
|
||||
- `execute_run_configuration`、`build_project`、`http_run_request` 和带破坏性标记的插件工具会在你最后使用的项目窗口中询问。对话框中有一行 `后台项目 <文件夹名>`,下面是完整路径,请求在这里排队。对话框不会获得键盘焦点:用鼠标点击它,或先点进对话框再用键盘操作。该窗口关闭或失去信任时,请求会转到另一个打开的项目窗口。没有打开任何项目窗口时,调用会失败,返回 `no project window is available`。勇敢模式下,这些工具无需询问即可运行,有没有窗口都一样。
|
||||
|
||||
## 安全
|
||||
|
||||
- **未受信任的项目** 只开放只读工具。写文件、重命名、重新格式化、构建或运行的工具都要求项目已被信任。
|
||||
- **运行和构建会先询问。** `execute_run_configuration`、`build_project`、`run_command` 和 `http_run_request` 会在 OpenIDEA 中弹出对话框,说明是哪个客户端、哪个项目、哪个工具以及要运行什么,选择 **允许** 或 **拒绝**;多个请求会排队。
|
||||
- **未受信任的项目** 只开放只读工具。写文件、重命名、重新格式化、构建或运行的工具都要求项目已被信任。在所有项目之外启动的客户端能看到全部工具;没有打开窗口或打开了多个窗口时,未指定项目的客户端也是如此。会写入或运行的工具仍会拒绝你没有信任的项目。
|
||||
- **运行和构建会先询问。** `execute_run_configuration`、`build_project`、`run_command` 和 `http_run_request` 会在 OpenIDEA 中弹出对话框,说明是哪个客户端、哪个项目、哪个工具以及要运行什么,选择 **允许** 或 **拒绝**;多个请求会排队。在后台项目中,除 `run_command` 外,这些工具都会在你最后使用的项目窗口中询问,对话框会写明该项目。
|
||||
- 会写入的工具拒绝项目之外的路径。
|
||||
- **后台项目。** 任何持有令牌的人都能让 IDE 加载 **无窗口时提供服务** 所提供的项目,所以这项设置和令牌共同决定谁能在这台电脑上打开文件夹。你没有信任的列出文件夹会以受限模式打开,只开放只读工具。列表里只放你愿意让智能体访问的文件夹。
|
||||
|
||||
|
||||
@@ -35,7 +35,7 @@ optional = ["net:127.0.0.1", "clipboard.read"]
|
||||
"clipboard.read" = "Imports a log you copied, on the Log to SQL tab only."
|
||||
```
|
||||
|
||||
授权对话框和 **设置 › 插件** 的插件详情会把这句话显示在 IDE 说明的下方,并标明是插件自己的说法;它不会替换 IDE 的说明。键必须是 `required` 或 `optional` 里列出的能力,每条 1 到 500 个字符。翻译方式与插件的其他字符串相同:在 `locales/<tag>.json` 里以英文原文为键。
|
||||
授权对话框和 **设置 › 插件** 的插件详情会把这句话显示在 IDE 说明的下方,并标明是插件自己的说法;它不会替换 IDE 的说明。键必须是 `required` 或 `optional` 里列出的能力,或者由贡献点带来的能力(`[[contributes.javaAgents]]` 带来的 `java.agent`、`[[contributes.documentIndexers]]` 带来的 `project.read`),每条 1 到 500 个字符。翻译方式与插件的其他字符串相同:在 `locales/<tag>.json` 里以英文原文为键。
|
||||
|
||||
代码发现某个 optional 能力被拒绝时,可以调用 `host::open_permissions()` 打开 **设置 › 插件** 并定位到本插件的权限,这样通知里可以放一个直接跳过去的按钮(仅限命令或事件中调用)。
|
||||
|
||||
@@ -49,33 +49,33 @@ optional = ["net:127.0.0.1", "clipboard.read"]
|
||||
|
||||
## 能力一览
|
||||
|
||||
| 能力 | 风险 | 解锁 | API |
|
||||
| ------------------- | ---- | ------------------------------------------------------------------------------------------------------------------------------ | -------------------------- |
|
||||
| `project.read` | 低 | `Project::root`、`read_file`、`find_files`、`symbols`、`search_text`、`host::projects`、发布诊断、`problems`、打开编辑器、装饰 | 1.0 |
|
||||
| `project.write` | 高 | `Project::write_file`:在打开的项目中创建和替换文本文件,但不能写 git 自己的文件(`.git`) | 1.3 |
|
||||
| `editor.read` | 低 | `TextEditor::document`、`selections`、`host::open_editors` | 1.0 |
|
||||
| `editor.write` | 中 | `TextEditor::apply_edits` | 1.0 |
|
||||
| `vcs.read` | 低 | `vcs_status`、`vcs_remotes`、`vcs_log`、`vcs_blame`、`vcs_diff`、待提交的内容、提交前检查 | 1.0 |
|
||||
| `vcs.write` | 中 | `vcs_fetch`(仅受信任项目)、`host::set_commit_message` | 1.0 |
|
||||
| `build.read` | 低 | `build_dependencies`:IDE 已解析的 Maven / Gradle 依赖图;仅限受信任的项目 | 1.10 |
|
||||
| `storage` | 低 | `host::storage`,每个插件 64 MiB | 1.0 |
|
||||
| `events` | 低 | 文件打开、关闭、保存,文件变化,编辑器焦点变化,仓库变化,设置变化 | 1.0 |
|
||||
| `events.input` | 中 | `action-performed` 和 `input-mode-changed` 事件(按键和编辑器输入) | 1.0 |
|
||||
| `clipboard` | 中 | `host::copy_to_clipboard`,以及插件 Web 视图中的剪贴板 API | 1.0 |
|
||||
| `clipboard.read` | 中 | `host::read_clipboard`:读取剪贴板的文本和图片,仅限用户运行的命令和视图操作(事件处理器等无人值守的调用会被拒绝) | 1.11 |
|
||||
| `agents` | 中 | `host::fork_agent_session`:把录制的原生 agent 会话(`claude` 或 `codex`)派生为当前窗口项目中的新任务;仅限受信任项目 | 1.18 |
|
||||
| `secrets` | 中 | 请求头中的 `{{secret:<name>}}`、`secret_is_set`、`secret_set`、`secret_delete` | 1.0 |
|
||||
| `net:<host>` | 中 | `host::fetch` / `host::fetch_stream` 通过 HTTPS(以及回环地址的 HTTP)访问该主机;`*.example.com` 匹配子域名 | 1.0 |
|
||||
| `net:ask` | 中 | 第一次请求未声明的 HTTPS 主机时询问用户 | 1.5 |
|
||||
| `net.http:<host>` | 中 | 通过未加密的 HTTP 访问该主机 | 1.4 |
|
||||
| `database.sources` | 中 | 只管理插件自己的项目数据源并写入其凭据;仅限受信任项目 | 1.4 |
|
||||
| `fs.read:<path>` | 高 | 通过 `host::fs` 读取项目外、该路径下的文件 | 1.0(`fs` interface:1.3) |
|
||||
| `fs.write:<path>` | 高 | 通过 `host::fs` 写入项目外、该路径下的文件;不包含读权限 | 1.3 |
|
||||
| `process:<program>` | 高 | 运行该程序:`run_process`、`run_command`、`start`、终端、语言服务器、调试适配器、运行配置 | 1.0 |
|
||||
| `lsp:<server>` | 高 | 向正在运行的该语言服务器发送它自己的请求(`language_server_request`);仅限受信任的项目 | 1.9 |
|
||||
| `java.agent` | 高 | 在你启动的 Java 应用中运行插件的 Java 代理(见下文“Java 代理”) | 1.10 |
|
||||
| `ipc:<path>` | 高 | 项目所在机器上的本地 Unix 套接字或 Windows 命名管道 | 1.4 |
|
||||
| `ide.commands` | 高 | 像用户亲自选择一样运行任意 IDE 操作或其他插件的命令,包括运行程序、提交和推送。插件自己的命令不受此限制。 | 1.4 |
|
||||
| 能力 | 风险 | 解锁 | API |
|
||||
| ------------------- | ---- | --------------------------------------------------------------------------------------------------------------------------------- | -------------------------- |
|
||||
| `project.read` | 低 | `Project::root`、`read_file`、`find_files`、`symbols`、`search_text`、`host::projects`、发布诊断、`problems`、打开编辑器、装饰 | 1.0 |
|
||||
| `project.write` | 高 | `Project::write_file`:在打开的项目中创建和替换文本文件,但不能写 git 自己的文件(`.git`) | 1.3 |
|
||||
| `editor.read` | 低 | `TextEditor::document`、`selections`、`host::open_editors` | 1.0 |
|
||||
| `editor.write` | 中 | `TextEditor::apply_edits` | 1.0 |
|
||||
| `vcs.read` | 低 | `vcs_status`、`vcs_remotes`、`vcs_log`、`vcs_blame`、`vcs_diff`、待提交的内容、提交前检查 | 1.0 |
|
||||
| `vcs.write` | 中 | `vcs_fetch`(仅受信任项目)、`host::set_commit_message` | 1.0 |
|
||||
| `build.read` | 低 | `build_dependencies`:IDE 已解析的 Maven / Gradle 依赖图;仅限受信任的项目 | 1.10 |
|
||||
| `storage` | 低 | `host::storage`,每个插件 64 MiB | 1.0 |
|
||||
| `events` | 低 | 文件打开、关闭、保存,文件变化,编辑器焦点变化,仓库变化,设置变化 | 1.0 |
|
||||
| `events.input` | 中 | `action-performed` 和 `input-mode-changed` 事件(按键和编辑器输入) | 1.0 |
|
||||
| `clipboard` | 中 | `host::copy_to_clipboard`,以及插件 Web 视图中的剪贴板 API | 1.0 |
|
||||
| `clipboard.read` | 中 | `host::read_clipboard`:读取剪贴板的文本和图片,仅限用户运行的命令和视图操作(事件处理器等无人值守的调用会被拒绝) | 1.11 |
|
||||
| `agents` | 中 | `host::fork_agent_session`:把录制的原生 agent 会话(`claude`、`codex` 或 `copilot`)派生为当前窗口项目中的新任务;仅限受信任项目 | 1.18 |
|
||||
| `secrets` | 中 | 请求头中的 `{{secret:<name>}}`、`secret_is_set`、`secret_set`、`secret_delete` | 1.0 |
|
||||
| `net:<host>` | 中 | `host::fetch` / `host::fetch_stream` 通过 HTTPS(以及回环地址的 HTTP)访问该主机;`*.example.com` 匹配子域名 | 1.0 |
|
||||
| `net:ask` | 中 | 第一次请求未声明的 HTTPS 主机时询问用户 | 1.5 |
|
||||
| `net.http:<host>` | 中 | 通过未加密的 HTTP 访问该主机 | 1.4 |
|
||||
| `database.sources` | 中 | 只管理插件自己的项目数据源并写入其凭据;仅限受信任项目 | 1.4 |
|
||||
| `fs.read:<path>` | 高 | 通过 `host::fs` 读取项目外、该路径下的文件 | 1.0(`fs` interface:1.3) |
|
||||
| `fs.write:<path>` | 高 | 通过 `host::fs` 写入项目外、该路径下的文件;不包含读权限 | 1.3 |
|
||||
| `process:<program>` | 高 | 运行该程序:`run_process`、`run_command`、`start`、终端、语言服务器、调试适配器、运行配置 | 1.0 |
|
||||
| `lsp:<server>` | 高 | 向正在运行的该语言服务器发送它自己的请求(`language_server_request`);仅限受信任的项目 | 1.9 |
|
||||
| `java.agent` | 高 | 在你启动的 Java 应用中运行插件的 Java 代理(见下文“Java 代理”) | 1.10 |
|
||||
| `ipc:<path>` | 高 | 项目所在机器上的本地 Unix 套接字或 Windows 命名管道 | 1.4 |
|
||||
| `ide.commands` | 高 | 像用户亲自选择一样运行任意 IDE 操作或其他插件的命令,包括运行程序、提交和推送。插件自己的命令不受此限制。 | 1.4 |
|
||||
|
||||
**API** 一列是声明该能力时清单最低可以兼容的插件 API。例如声明了 `net.http:` 的清单必须要求 `engines.openidea = "^1.4"` 或更高,否则安装和 `openidea-plugin check` 都会拒绝。
|
||||
|
||||
|
||||
@@ -9,28 +9,28 @@ description: "engines.openidea、插件 API 从 1.0 到 1.19 的各个版本,
|
||||
|
||||
## 版本历史
|
||||
|
||||
| API | 随哪个版本发布 | 主要内容 |
|
||||
| ------ | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| 1.0.0 | OpenIDEA 0.1.36 | 基础 API:命令、事件、存储、任务、项目和编辑器访问、VCS、诊断、网络与密钥、进程、声明式视图和自定义编辑器、设置、编辑器 provider、syntax provider |
|
||||
| 1.1.0 | OpenIDEA 0.1.37 | `vcs.remotes`、`ui.copy-to-clipboard`、`ui.open-url`,从视图中打开项目文件的指定行 |
|
||||
| 1.2.0 | OpenIDEA 0.1.38 | 后台文档索引器;选择器、输入框和确认框;插件自定义的 `when` 上下文键;项目视图中选中的文件;清单 `icon`;`viewItem.context` 菜单 |
|
||||
| 1.3.0 | OpenIDEA 0.1.39 | 提交信息和提交前检查、Services 详情面板、输入时诊断、悬停、内嵌提示、语义 token、改动文件的代码操作、HTTP 端点、项目外文件(`fs.read`/`fs.write`、`project.write`、插件私有目录)、批量 `files-changed` 事件和路径过滤、工作区符号、长时间运行的进程、带按钮的通知、翻译、多页设置、文件模板变量、Web 视图 PTY、日志标签页和内容标签页 |
|
||||
| 1.4.0 | OpenIDEA 0.1.40 | `net.http:`、`ipc:`、`ide.commands` 和 `database.sources` 能力;编辑器与项目快照、装饰、文本搜索、问题视图、Git log/blame/diff;输出通道;OAuth 回环;运行、终端会话、运行配置、测试结果解析和运行目标;格式化等语言功能;嵌入语言;代码片段;更多菜单位置;数据库数据源;MCP 工具 |
|
||||
| 1.5.0 | OpenIDEA 0.1.41 | `Project::notify`(只在某个项目的窗口中显示通知)、`net:ask` 能力、运行目标启动前校验、运行目标按命令设置工作目录参数 |
|
||||
| 1.6.0 | OpenIDEA 0.1.43 | 面向事件流插件、受容量限制且绑定项目的后台 WebSocket |
|
||||
| 1.7.0 | OpenIDEA 0.1.44 | `views.open-diff`:在差异查看器中对比两段文本,例如评审中某个文件的修改前后 |
|
||||
| 1.8.0 | OpenIDEA 0.1.45 | `problems-changed` 工作台事件:宿主按文件保存每个生产者的诊断,注解跟着文件走,而不是跟着调用它的窗口 |
|
||||
| 1.9.0 | OpenIDEA 0.1.46 | 带环境变量和调试器的运行配置、向正在运行的语言服务器发送请求(`lsp:<server>`)、交给插件处理的服务器命令、编辑器面板 |
|
||||
| 1.10.0 | OpenIDEA 0.1.47 | `build.dependencies`:IDE 已解析的 Maven / Gradle 依赖图(`build.read`) |
|
||||
| 1.11.0 | `main` 上开发中 | `ui.read-clipboard`:在用户运行的命令中读取剪贴板的文本和图片(`clipboard.read`) |
|
||||
| 1.12.0 | `main` 上开发中 | `ui.set-console-rules`:Run/Debug 控制台输出的高亮规则(正则、调色板颜色、文本样式) |
|
||||
| 1.13.0 | OpenIDEA 0.1.49 | 新增 `search-provider` 导出和 `searchCategories` 贡献点:可取消查询的全局搜索自定义分类 |
|
||||
| 1.14.0 | `main` 上开发中 | 可选 `hover-actions` 导出:行内侧 hover 显示的左侧操作,带锚定行和包含式触发行范围; `[[contributes.javaAgents]]` 的 `vmOptions` / `jdk`:在 `-javaagent:` 之前注入 JVM 参数(可选仅 JetBrains Runtime);`ui.set-status-item-menu` / `set-window-status-item-menu`:状态栏项菜单 |
|
||||
| 1.15.0 | `main` 上开发中 | `caret-moved` 事件;声明式 `[[contributes.skills]]`(`path = "skills/<name>/SKILL.md"`),在插件包中打包代理技能 |
|
||||
| 1.16.0 | OpenIDEA 0.1.52 | 可选 `completion-list-provider` 导出:标记为不完整的补全在继续输入时再次询问,不会重新询问语言服务器和其他插件;`decorations.set-markdown`:悬停显示 Markdown 卡片的行尾装饰 |
|
||||
| 1.17.0 | OpenIDEA 0.1.53 | `decorations.set-styled`:自带 `#rrggbb` / `#rrggbbaa` 前景色和背景色的编辑器装饰,用于主题调色板之外的颜色 |
|
||||
| 1.18.0 | OpenIDEA 0.1.54 | `[[contributes.overlays]]`:悬浮在工作台上方、从不抢占键盘焦点的插件网页,可通过 `openidea.overlay` 移动和调整大小;`[[contributes.dialogs]]`:插件网页显示在可调整大小的模态对话框中,用 `views.reveal` 打开,关闭时发 `closed` 视图事件,页面可调用 `openidea.dialog.close()`;`events.subscribe-paths-with-options`(`debounce-ms`)、`workspace.project.generation` 与 `FilesChanged` 的 `project`/`generation` 字段、过期运行目标/配置拒绝以及 `project-closed` 生命周期事件;`execution-configurations`、`run.start-with-options` 与 `runDetectors.outputMode`:插件运行配置的控制台输出方式(`pipes` 或 `pty`);`[[contributes.runAnything]]` 与 `run-anything-provider` 导出:以插件前缀开头的 Run Anything 行;`views.open-terminal-session-in`:在项目子目录中打开带 key 的终端;`workspace.invoking-project`:本次调用所服务窗口的项目,`gutter-actions` 和 `hover-actions` 中也可用;`events.watch-paths` 与 `watched-files-changed` 事件:监听项目之外、`fs.read` 授权范围内的文件和目录;`run-configuration-completion` 导出:补全插件自己运行配置的“实参”字段;`services.context` 和 `services.toolbar` 菜单:作用于 IDE 自带的 Services 节点,命令参数是选中的服务;`[[contributes.javaAgents]]` 的 `executor`:运行和调试旁边的“使用 <title> 运行/调试 '<name>'”,只有经它启动时才加载该代理,插件自己的命令也可用配置 id 经它启动;需授权的 `agents.fork-session`:把录制的原生 agent 会话(`claude` 或 `codex`)派生为调用窗口项目中的新任务(`agents` 能力),宿主自行校验会话并构造 fork 调用 |
|
||||
| 1.19.0 | `main` 上开发中 | `[capabilities.reasons]`:插件用一句话说明为什么需要某个能力,显示在授权对话框和 设置 › 插件 中宿主说明的下方;`settings.open` / `settings.open-permissions`:打开设置并定位到插件自己的页面或它的权限;`net.fetch-stream`:边到达边读取响应体(服务器推送事件 SSE、模型的流式回复),SDK 提供 `host::fetch_stream` 和 `sse` 解析器;`editor.open-as-text`:即使文件被自定义编辑器认领,也用内置文本编辑器打开(SDK 的 `host::open_editor_as_text`);菜单点 `openIn`:编辑器、标签页和项目视图的 **打开方式** 子菜单 |
|
||||
| API | 随哪个版本发布 | 主要内容 |
|
||||
| ------ | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
||||
| 1.0.0 | OpenIDEA 0.1.36 | 基础 API:命令、事件、存储、任务、项目和编辑器访问、VCS、诊断、网络与密钥、进程、声明式视图和自定义编辑器、设置、编辑器 provider、syntax provider |
|
||||
| 1.1.0 | OpenIDEA 0.1.37 | `vcs.remotes`、`ui.copy-to-clipboard`、`ui.open-url`,从视图中打开项目文件的指定行 |
|
||||
| 1.2.0 | OpenIDEA 0.1.38 | 后台文档索引器;选择器、输入框和确认框;插件自定义的 `when` 上下文键;项目视图中选中的文件;清单 `icon`;`viewItem.context` 菜单 |
|
||||
| 1.3.0 | OpenIDEA 0.1.39 | 提交信息和提交前检查、Services 详情面板、输入时诊断、悬停、内嵌提示、语义 token、改动文件的代码操作、HTTP 端点、项目外文件(`fs.read`/`fs.write`、`project.write`、插件私有目录)、批量 `files-changed` 事件和路径过滤、工作区符号、长时间运行的进程、带按钮的通知、翻译、多页设置、文件模板变量、Web 视图 PTY、日志标签页和内容标签页 |
|
||||
| 1.4.0 | OpenIDEA 0.1.40 | `net.http:`、`ipc:`、`ide.commands` 和 `database.sources` 能力;编辑器与项目快照、装饰、文本搜索、问题视图、Git log/blame/diff;输出通道;OAuth 回环;运行、终端会话、运行配置、测试结果解析和运行目标;格式化等语言功能;嵌入语言;代码片段;更多菜单位置;数据库数据源;MCP 工具 |
|
||||
| 1.5.0 | OpenIDEA 0.1.41 | `Project::notify`(只在某个项目的窗口中显示通知)、`net:ask` 能力、运行目标启动前校验、运行目标按命令设置工作目录参数 |
|
||||
| 1.6.0 | OpenIDEA 0.1.43 | 面向事件流插件、受容量限制且绑定项目的后台 WebSocket |
|
||||
| 1.7.0 | OpenIDEA 0.1.44 | `views.open-diff`:在差异查看器中对比两段文本,例如评审中某个文件的修改前后 |
|
||||
| 1.8.0 | OpenIDEA 0.1.45 | `problems-changed` 工作台事件:宿主按文件保存每个生产者的诊断,注解跟着文件走,而不是跟着调用它的窗口 |
|
||||
| 1.9.0 | OpenIDEA 0.1.46 | 带环境变量和调试器的运行配置、向正在运行的语言服务器发送请求(`lsp:<server>`)、交给插件处理的服务器命令、编辑器面板 |
|
||||
| 1.10.0 | OpenIDEA 0.1.47 | `build.dependencies`:IDE 已解析的 Maven / Gradle 依赖图(`build.read`) |
|
||||
| 1.11.0 | `main` 上开发中 | `ui.read-clipboard`:在用户运行的命令中读取剪贴板的文本和图片(`clipboard.read`) |
|
||||
| 1.12.0 | `main` 上开发中 | `ui.set-console-rules`:Run/Debug 控制台输出的高亮规则(正则、调色板颜色、文本样式) |
|
||||
| 1.13.0 | OpenIDEA 0.1.49 | 新增 `search-provider` 导出和 `searchCategories` 贡献点:可取消查询的全局搜索自定义分类 |
|
||||
| 1.14.0 | `main` 上开发中 | 可选 `hover-actions` 导出:行内侧 hover 显示的左侧操作,带锚定行和包含式触发行范围; `[[contributes.javaAgents]]` 的 `vmOptions` / `jdk`:在 `-javaagent:` 之前注入 JVM 参数(可选仅 JetBrains Runtime);`ui.set-status-item-menu` / `set-window-status-item-menu`:状态栏项菜单 |
|
||||
| 1.15.0 | `main` 上开发中 | `caret-moved` 事件;声明式 `[[contributes.skills]]`(`path = "skills/<name>/SKILL.md"`),在插件包中打包代理技能 |
|
||||
| 1.16.0 | OpenIDEA 0.1.52 | 可选 `completion-list-provider` 导出:标记为不完整的补全在继续输入时再次询问,不会重新询问语言服务器和其他插件;`decorations.set-markdown`:悬停显示 Markdown 卡片的行尾装饰 |
|
||||
| 1.17.0 | OpenIDEA 0.1.53 | `decorations.set-styled`:自带 `#rrggbb` / `#rrggbbaa` 前景色和背景色的编辑器装饰,用于主题调色板之外的颜色 |
|
||||
| 1.18.0 | OpenIDEA 0.1.54 | `[[contributes.overlays]]`:悬浮在工作台上方、从不抢占键盘焦点的插件网页,可通过 `openidea.overlay` 移动和调整大小;`[[contributes.dialogs]]`:插件网页显示在可调整大小的模态对话框中,用 `views.reveal` 打开,关闭时发 `closed` 视图事件,页面可调用 `openidea.dialog.close()`;`events.subscribe-paths-with-options`(`debounce-ms`)、`workspace.project.generation` 与 `FilesChanged` 的 `project`/`generation` 字段、过期运行目标/配置拒绝以及 `project-closed` 生命周期事件;`execution-configurations`、`run.start-with-options` 与 `runDetectors.outputMode`:插件运行配置的控制台输出方式(`pipes` 或 `pty`);`[[contributes.runAnything]]` 与 `run-anything-provider` 导出:以插件前缀开头的 Run Anything 行;`views.open-terminal-session-in`:在项目子目录中打开带 key 的终端;`workspace.invoking-project`:本次调用所服务窗口的项目,`gutter-actions` 和 `hover-actions` 中也可用;`events.watch-paths` 与 `watched-files-changed` 事件:监听项目之外、`fs.read` 授权范围内的文件和目录;`run-configuration-completion` 导出:补全插件自己运行配置的“实参”字段;`services.context` 和 `services.toolbar` 菜单:作用于 IDE 自带的 Services 节点,命令参数是选中的服务;`[[contributes.javaAgents]]` 的 `executor`:运行和调试旁边的“使用 <title> 运行/调试 '<name>'”,只有经它启动时才加载该代理,插件自己的命令也可用配置 id 经它启动;需授权的 `agents.fork-session`:把录制的原生 agent 会话(`claude`、`codex` 或 `copilot`)派生为调用窗口项目中的新任务(`agents` 能力),宿主自行校验会话并构造 fork 调用 |
|
||||
| 1.19.0 | `main` 上开发中 | `[capabilities.reasons]`:插件用一句话说明为什么需要某个能力,显示在授权对话框和 设置 › 插件 中宿主说明的下方;`settings.open` / `settings.open-permissions`:打开设置并定位到插件自己的页面或它的权限;`net.fetch-stream`:边到达边读取响应体(服务器推送事件 SSE、模型的流式回复),SDK 提供 `host::fetch_stream` 和 `sse` 解析器;`editor.open-as-text`:即使文件被自定义编辑器认领,也用内置文本编辑器打开(SDK 的 `host::open_editor_as_text`);菜单点 `openIn`:编辑器、标签页和项目视图的 **打开方式** 子菜单 |
|
||||
|
||||
每个版本新增内容的完整列表见 [`plugins/README.md`](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md)。
|
||||
|
||||
|
||||
@@ -59,3 +59,32 @@ test("line bookmarks keep their code or description readable in the dock", async
|
||||
)
|
||||
.toEqual({ path, line: 27 });
|
||||
});
|
||||
|
||||
test("selecting a bookmark shows its code in the preview below the side-docked Bookmarks tree", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
const path = "/dev/acme-api/PreviewBookmark.ts";
|
||||
await page.evaluate(async (path) => {
|
||||
const backend = "/src/editor/core/backend.ts";
|
||||
const { docBackend } = await import(/* @vite-ignore */ backend);
|
||||
docBackend().files.set(path, "const previewBookmark = true;");
|
||||
const store = "/src/features/search/bookmarks/store.ts";
|
||||
const { updateBookmarks, toggleBookmark } = await import(/* @vite-ignore */ store);
|
||||
updateBookmarks((items: unknown[]) => toggleBookmark(items, path, 0, "const previewBookmark = true;"));
|
||||
const actions = "/src/platform/actions.ts";
|
||||
await (await import(/* @vite-ignore */ actions)).executeAction("toolwindow.bookmarks");
|
||||
}, path);
|
||||
|
||||
const previewButton = page.getByRole("button", { name: "Editor Preview" });
|
||||
if ((await previewButton.getAttribute("aria-pressed")) !== "true") await previewButton.click();
|
||||
const tree = page.getByRole("tree", { name: "Bookmarks" });
|
||||
await tree.getByRole("treeitem", { name: /const previewBookmark/ }).click();
|
||||
const preview = page.locator("#bookmarks-preview");
|
||||
await expect(preview).toBeVisible();
|
||||
const treeBounds = await tree.boundingBox();
|
||||
const previewBounds = await preview.boundingBox();
|
||||
expect(treeBounds).not.toBeNull();
|
||||
expect(previewBounds).not.toBeNull();
|
||||
expect(previewBounds!.y).toBeGreaterThanOrEqual(treeBounds!.y + treeBounds!.height);
|
||||
await expect(preview.locator(".cm-content")).toContainText("const previewBookmark = true;");
|
||||
});
|
||||
@@ -0,0 +1,90 @@
|
||||
/**
|
||||
* Git log row colors: User, Date and Hash use the normal text color on a regular
|
||||
* commit, and are dimmed together with the subject on a merge commit.
|
||||
*/
|
||||
import { expect, stubDesktop, test } from "./fixtures";
|
||||
|
||||
test("dims the metadata columns only on merge commits", async ({ workbench: page }) => {
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(async () => {
|
||||
const root = "/dev/acme-api";
|
||||
const id = (i: number) => i.toString(16).padStart(40, "0");
|
||||
const commit = (i: number, parents: number[], summary: string) => ({
|
||||
id: id(i),
|
||||
shortId: id(i).slice(-8),
|
||||
parents: parents.map(id),
|
||||
refs: i === 0 ? ["HEAD", "main"] : [],
|
||||
author: `Author ${i}`,
|
||||
email: "[email protected]",
|
||||
timeMs: 1_700_000_000_000 - i * 60_000,
|
||||
summary,
|
||||
message: summary,
|
||||
});
|
||||
const commits = [
|
||||
commit(0, [1, 2], "Merge branch 'feature'"),
|
||||
commit(1, [3], "Regular change"),
|
||||
commit(2, [3], "Feature change"),
|
||||
commit(3, [], "Initial"),
|
||||
];
|
||||
const h = window.__ipc.handlers;
|
||||
h.vcs_log = ({ query }) => {
|
||||
const { skip, limit, range } = query as { skip: number; limit: number; range?: string };
|
||||
return range ? [] : commits.slice(skip, limit ? skip + limit : undefined);
|
||||
};
|
||||
h.vcs_log_refs = () => ({});
|
||||
h.vcs_branches = () => [];
|
||||
h.vcs_branch_info = () => ({
|
||||
head: "main",
|
||||
headCommit: id(0),
|
||||
upstream: null,
|
||||
ahead: 0,
|
||||
behind: 0,
|
||||
operation: null,
|
||||
});
|
||||
h.vcs_config_get = () => null;
|
||||
h.vcs_commit_files = () => [];
|
||||
h.vcs_log_details_batch = ({ revisions }) =>
|
||||
(revisions as string[]).map(() => ({
|
||||
message: "",
|
||||
containingBranches: [],
|
||||
signature: "N",
|
||||
signer: "",
|
||||
key: "",
|
||||
fingerprint: "",
|
||||
}));
|
||||
const storeModule = "/src/features/vcs/store.ts";
|
||||
const { useVcs } = await import(/* @vite-ignore */ storeModule);
|
||||
useVcs.setState({ available: true, root, repo: root, roots: [root], branchesLoaded: true });
|
||||
const contextModule = "/src/platform/context.ts";
|
||||
const { setContext } = await import(/* @vite-ignore */ contextModule);
|
||||
setContext("vcsAvailable", true);
|
||||
const optionsModule = "/src/features/vcs/logOptions.ts";
|
||||
const { useLogOptions } = await import(/* @vite-ignore */ optionsModule);
|
||||
useLogOptions.setState({ showHash: true, highlightMerges: true });
|
||||
const actionsModule = "/src/platform/actions.ts";
|
||||
const { executeAction } = await import(/* @vite-ignore */ actionsModule);
|
||||
await executeAction("vcs.showLog");
|
||||
});
|
||||
const list = page.getByRole("listbox", { name: "Commits" });
|
||||
await expect(list.getByRole("option")).toHaveCount(4);
|
||||
|
||||
const colors = (summary: string) =>
|
||||
list
|
||||
.getByRole("option")
|
||||
.filter({ hasText: summary })
|
||||
.evaluate((row) => {
|
||||
const color = (el: Element | null) => (el ? getComputedStyle(el).color : null);
|
||||
const subject = row.querySelector("[class*=subjectText]");
|
||||
const author = row.querySelector('[title^="Author "]');
|
||||
const hash = [...row.querySelectorAll("span")].find((s) => /^0+[0-9a-f]$/.test(s.textContent ?? ""));
|
||||
return { subject: color(subject), author: color(author), hash: color(hash ?? null) };
|
||||
});
|
||||
|
||||
const regular = await colors("Regular change");
|
||||
const merge = await colors("Merge branch 'feature'");
|
||||
expect(regular.author).toBe(regular.subject);
|
||||
expect(regular.hash).toBe(regular.subject);
|
||||
expect(merge.author).toBe(merge.subject);
|
||||
expect(merge.hash).toBe(merge.subject);
|
||||
expect(merge.author).not.toBe(regular.author);
|
||||
});
|
||||
@@ -0,0 +1,158 @@
|
||||
import { expect, stubDesktop, test } from "./fixtures";
|
||||
import { expect as baseExpect, test as baseTest } from "@playwright/test";
|
||||
|
||||
// Inline marks (lint ranges, Usages preview matches, ⌘-hover links) paint only their font box.
|
||||
// With the default 13 px font on a taller line the box leaves gaps above and below the text, so
|
||||
// background fills look clipped and the pointer cursor stops where the font box stops (#7105,
|
||||
// #7106, #7107). A fill covers the whole row: the mark grows to the row (padding) and the fill
|
||||
// is a gradient centred in that box capped at 1lh, so it paints exactly the row, never bleeding.
|
||||
|
||||
test("a warning's background fill covers the whole row", async ({ workbench: page }, info) => {
|
||||
const path = "/dev/acme-api/src/Settlement.ts";
|
||||
await page.evaluate(
|
||||
async ({ path }) => {
|
||||
const backend = "/src/editor/core/backend.ts";
|
||||
(await import(/* @vite-ignore */ backend)).docBackend().files.set(path, "const settlement = total;\n");
|
||||
const service = "/src/workbench/contributions.ts";
|
||||
await (await import(/* @vite-ignore */ service)).editorService().openFile(path);
|
||||
},
|
||||
{ path },
|
||||
);
|
||||
await expect(page.locator(".cm-content")).toContainText("settlement");
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(
|
||||
async ({ path }) => {
|
||||
const diagnostic = "/src/editor/lsp/diagnostics.ts";
|
||||
(await import(/* @vite-ignore */ diagnostic)).setFileDiagnostics(path, "settlement-lint", [
|
||||
{
|
||||
severity: "warning",
|
||||
message: "Review the reported total.",
|
||||
range: { start: { line: 0, col: 6 }, end: { line: 0, col: 16 } },
|
||||
source: "settlement-lint",
|
||||
code: "review",
|
||||
},
|
||||
]);
|
||||
},
|
||||
{ path },
|
||||
);
|
||||
const warning = page.locator(".cm-content .cm-lintRange-warning");
|
||||
await expect(warning).toHaveText("settlement");
|
||||
const fill = await warning.evaluate((el) => {
|
||||
const row = (el.closest(".cm-line") as HTMLElement).getBoundingClientRect();
|
||||
const box = el.getBoundingClientRect();
|
||||
// The gradient paints min(box, 1lh) centred in the box; the line's height is 1lh.
|
||||
const paintHeight = Math.min(box.height, row.height);
|
||||
const paintTop = box.top + (box.height - paintHeight) / 2;
|
||||
return {
|
||||
paintHeight,
|
||||
paintTop,
|
||||
rowHeight: row.height,
|
||||
rowTop: row.top,
|
||||
image: getComputedStyle(el).backgroundImage,
|
||||
};
|
||||
});
|
||||
expect(fill.image, "the fill is a capped gradient, not a flat box colour").toContain("linear-gradient");
|
||||
expect(fill.paintHeight, "the fill is as tall as the row").toBeCloseTo(fill.rowHeight, 0);
|
||||
expect(Math.abs(fill.paintTop - fill.rowTop), "the fill starts at the row's top").toBeLessThanOrEqual(1);
|
||||
await page.screenshot({ path: info.outputPath("warning-row-fill.png"), animations: "disabled" });
|
||||
});
|
||||
|
||||
test("the Usages preview match covers the whole row", async ({ workbench: page }, info) => {
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(async () => {
|
||||
const modulePath = "/src/features/code-insight/usages.ts";
|
||||
const { useUsagesPopup } = await import(modulePath);
|
||||
const path = "/dev/acme-api/src/SettlementService.ts";
|
||||
const lines = ["const current = settlement;", "settlement = next;"];
|
||||
window.__ipc.handlers.fs_read_text = () => lines.join("\n");
|
||||
useUsagesPopup.setState({
|
||||
open: true,
|
||||
anchor: { x: 100, y: 150 },
|
||||
symbol: "settlement",
|
||||
loading: false,
|
||||
scope: "project",
|
||||
groups: [
|
||||
{
|
||||
path,
|
||||
usages: lines.map((text, line) => ({
|
||||
path,
|
||||
line,
|
||||
col: text.indexOf("settlement"),
|
||||
endCol: text.indexOf("settlement") + "settlement".length,
|
||||
text,
|
||||
access: line === 0 ? "read" : "write",
|
||||
})),
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
const popup = page.getByRole("dialog", { name: "Usages", exact: true });
|
||||
await expect(popup.getByRole("option")).toHaveCount(2);
|
||||
await popup.getByRole("button", { name: /Open in Find Window/ }).click();
|
||||
const view = page.getByRole("region", { name: "Find Usages", exact: true });
|
||||
const mark = view.locator("mark").first();
|
||||
await expect(mark).toHaveText("settlement");
|
||||
const fill = await mark.evaluate((el) => {
|
||||
const row = (el.parentElement as HTMLElement).getBoundingClientRect();
|
||||
const box = el.getBoundingClientRect();
|
||||
const paintHeight = Math.min(box.height, row.height);
|
||||
const paintTop = box.top + (box.height - paintHeight) / 2;
|
||||
return {
|
||||
paintHeight,
|
||||
paintTop,
|
||||
rowHeight: row.height,
|
||||
rowTop: row.top,
|
||||
image: getComputedStyle(el).backgroundImage,
|
||||
};
|
||||
});
|
||||
expect(fill.image, "the fill is a capped gradient, not a flat box colour").toContain("linear-gradient");
|
||||
expect(fill.paintHeight, "the match is as tall as its preview row").toBeCloseTo(fill.rowHeight, 0);
|
||||
expect(fill.paintTop, "the match starts at the row's top").toBeCloseTo(fill.rowTop, 0);
|
||||
await page.screenshot({ path: info.outputPath("usages-match-row-fill.png"), animations: "disabled" });
|
||||
});
|
||||
|
||||
// The navigation path needs a resolving target, which the configurationNavigation fixture
|
||||
// provides (a stubbed `lspGoto` behind a real CodeMirror editor).
|
||||
baseTest("the navigation cursor covers the row's gap above and below the font", async ({ page }) => {
|
||||
await page.addInitScript(() => Object.defineProperty(Navigator.prototype, "platform", { get: () => "MacIntel" }));
|
||||
await page.goto("/e2e/configurationNavigation.html");
|
||||
await expect(page.locator("#config .cm-content")).toContainText("driver-class-name");
|
||||
// The same ⌘-hover word, on a line tall enough to have gaps around the font box.
|
||||
await page.addStyleTag({ content: "#config .cm-editor { --lh-code: 34px; }" });
|
||||
const glyph = await page.evaluate(() => {
|
||||
const lines = document.querySelectorAll("#config .cm-content .cm-line");
|
||||
for (const line of lines) {
|
||||
const walker = document.createTreeWalker(line, NodeFilter.SHOW_TEXT);
|
||||
let node: Text | null = null;
|
||||
let at = -1;
|
||||
while ((node = walker.nextNode() as Text | null)) {
|
||||
at = node.data.indexOf("driver-class-name");
|
||||
if (at >= 0) break;
|
||||
}
|
||||
if (!node || at < 0) continue;
|
||||
const range = document.createRange();
|
||||
range.setStart(node, at);
|
||||
range.setEnd(node, at + "driver-class-name".length);
|
||||
const box = range.getBoundingClientRect();
|
||||
return { x: box.x + box.width / 2, top: box.top, bottom: box.bottom };
|
||||
}
|
||||
throw new Error("key text node not found");
|
||||
});
|
||||
await page.keyboard.down("Meta");
|
||||
await page.mouse.move(glyph.x, (glyph.top + glyph.bottom) / 2);
|
||||
await expect(page.locator("#config .cm-lsp-link")).toHaveText("driver-class-name");
|
||||
// A point in the key's own row's gap, above the glyph box but inside the same line.
|
||||
const rowTop = await page.evaluate(
|
||||
() =>
|
||||
(document.querySelector("#config .cm-lsp-link") as HTMLElement).closest(".cm-line")!.getBoundingClientRect().top,
|
||||
);
|
||||
const gap = { x: glyph.x, y: rowTop + 1 };
|
||||
await page.mouse.move(gap.x, gap.y);
|
||||
const cursor = await page.evaluate(({ x, y }) => {
|
||||
const el = document.elementFromPoint(x, y) as Element | null;
|
||||
const link = el?.closest(".cm-lsp-link") as HTMLElement | null;
|
||||
return link ? getComputedStyle(link).cursor : null;
|
||||
}, gap);
|
||||
baseExpect(cursor, "hovering the row's gap inside the word is the link, pointer cursor and all").toBe("pointer");
|
||||
await page.keyboard.up("Meta");
|
||||
});
|
||||
@@ -110,6 +110,132 @@ test("follows explicit Markdown anchors before generated heading IDs", async ({
|
||||
await expect(heading).toBeInViewport();
|
||||
});
|
||||
|
||||
test("keeps unchanged preview blocks mounted while their source lines move", async ({ workbench: page }) => {
|
||||
const path = "/dev/acme-api/incremental-markdown.md";
|
||||
const workerCounts = await page.evaluateHandle(() => {
|
||||
const counts = { started: 0, stopped: 0 };
|
||||
const BrowserWorker = window.Worker;
|
||||
window.Worker = class extends BrowserWorker {
|
||||
private readonly tracksPreview: boolean;
|
||||
|
||||
constructor(url: string | URL, options?: WorkerOptions) {
|
||||
super(url, options);
|
||||
this.tracksPreview = String(url).includes("/preview.worker.ts");
|
||||
if (this.tracksPreview) counts.started++;
|
||||
}
|
||||
|
||||
terminate() {
|
||||
if (this.tracksPreview) counts.stopped++;
|
||||
super.terminate();
|
||||
}
|
||||
};
|
||||
return counts;
|
||||
});
|
||||
await page.evaluate(async (path) => {
|
||||
const backendPath = "/src/editor/core/backend.ts";
|
||||
const servicePath = "/src/workbench/contributions.ts";
|
||||
const { docBackend } = await import(backendPath);
|
||||
const { editorService } = await import(servicePath);
|
||||
docBackend().files.set(path, "Edit this paragraph.\n\nKeep this paragraph.\n");
|
||||
await editorService().openFile(path);
|
||||
}, path);
|
||||
|
||||
const preview = page.getByRole("document", { name: "Markdown preview" });
|
||||
const unchanged = preview.getByText("Keep this paragraph.", { exact: true });
|
||||
await expect(unchanged).toBeVisible();
|
||||
await expect(preview).toHaveAttribute("style", /--markdown-block-width:/);
|
||||
const widthChanges = await preview.evaluateHandle((el) => {
|
||||
const records: MutationRecord[] = [];
|
||||
const observer = new MutationObserver((changes) => records.push(...changes));
|
||||
observer.observe(el, { attributes: true, attributeFilter: ["style"], attributeOldValue: true });
|
||||
return { observer, records };
|
||||
});
|
||||
const previous = await unchanged.elementHandle();
|
||||
expect(await previous.evaluate((el) => el.parentElement?.getAttribute("data-line"))).toBe("2");
|
||||
|
||||
await page.evaluate(async (path) => {
|
||||
const editorApi = "/src/editor/api.ts";
|
||||
const { editorsFor } = await import(editorApi);
|
||||
const { view } = editorsFor(path)[0];
|
||||
view.dispatch({ changes: { from: 0, to: 20, insert: "The edited paragraph.\n\nA new paragraph." } });
|
||||
}, path);
|
||||
|
||||
await expect(preview.getByText("The edited paragraph.", { exact: true })).toBeVisible();
|
||||
const inserted = preview.getByText("A new paragraph.", { exact: true });
|
||||
await expect(inserted).toBeVisible();
|
||||
await expect(inserted.locator("..")).toHaveAttribute("data-in-viewport", "");
|
||||
expect(await unchanged.evaluate((el, previous) => el === previous, previous)).toBe(true);
|
||||
expect(await previous.evaluate((el) => el.parentElement?.getAttribute("data-line"))).toBe("4");
|
||||
const lostWidth = await widthChanges.evaluate(({ observer, records }) => {
|
||||
const changes = [...records, ...observer.takeRecords()];
|
||||
observer.disconnect();
|
||||
return changes.some((record) => !record.oldValue?.includes("--markdown-block-width:"));
|
||||
});
|
||||
expect(lostWidth).toBe(false);
|
||||
expect(await workerCounts.jsonValue()).toEqual({ started: 1, stopped: 0 });
|
||||
|
||||
await openFromTree(page, "App.tsx");
|
||||
await expect.poll(() => workerCounts.jsonValue()).toEqual({ started: 1, stopped: 1 });
|
||||
await page.getByRole("tab", { name: /incremental-markdown\.md/ }).click();
|
||||
await expect(unchanged).toBeVisible();
|
||||
expect(await unchanged.evaluate((el, previous) => el === previous, previous)).toBe(true);
|
||||
expect(await workerCounts.jsonValue()).toEqual({ started: 1, stopped: 1 });
|
||||
});
|
||||
|
||||
test("defers Mermaid while editing prose after leaving its fence", async ({ workbench: page }) => {
|
||||
const path = "/dev/acme-api/diagram.md";
|
||||
await page.evaluate(async (path) => {
|
||||
const backendPath = "/src/editor/core/backend.ts";
|
||||
const servicePath = "/src/workbench/contributions.ts";
|
||||
const { docBackend } = await import(backendPath);
|
||||
const { editorService } = await import(servicePath);
|
||||
docBackend().files.set(
|
||||
path,
|
||||
"# Diagram\n\n~~~mermaid\nflowchart TD\nA[Start] --> B[Finish]\n~~~\n\nAfter the diagram.\n",
|
||||
);
|
||||
await editorService().openFile(path);
|
||||
}, path);
|
||||
|
||||
const preview = page.getByRole("document", { name: "Markdown preview" });
|
||||
const drawing = preview.locator(".mermaid-output svg");
|
||||
await expect(drawing).toContainText("Finish");
|
||||
const originalDrawing = await drawing.elementHandle();
|
||||
|
||||
await page.evaluate(async (path) => {
|
||||
const api = "/src/editor/api.ts";
|
||||
const { editorsFor } = await import(api);
|
||||
const { view } = editorsFor(path)[0];
|
||||
const line = view.state.doc.line(5);
|
||||
const from = line.from + line.text.indexOf("Finish");
|
||||
view.focus();
|
||||
view.dispatch({
|
||||
changes: { from, to: from + "Finish".length, insert: "Revised end" },
|
||||
selection: { anchor: from + "Revised end".length },
|
||||
});
|
||||
}, path);
|
||||
await page.waitForFunction(async (path) => {
|
||||
const liveModule = "/src/features/viewers/markdown/live.ts";
|
||||
const { useLiveMarkdown } = await import(liveModule);
|
||||
return useLiveMarkdown.getState()[path]?.text.line(5).text.includes("Revised end");
|
||||
}, path);
|
||||
await expect(preview.locator("[data-mermaid] pre code")).toContainText("Finish");
|
||||
expect(await drawing.evaluate((svg, original) => svg === original, originalDrawing)).toBe(true);
|
||||
|
||||
await page.evaluate(async (path) => {
|
||||
const api = "/src/editor/api.ts";
|
||||
const { editorsFor } = await import(api);
|
||||
const { view } = editorsFor(path)[0];
|
||||
const line = view.state.doc.line(8);
|
||||
view.dispatch({ selection: { anchor: line.from } });
|
||||
view.dispatch({ changes: { from: line.from + "After ".length, insert: "editing " } });
|
||||
}, path);
|
||||
await expect(preview.getByText("After editing the diagram.", { exact: true })).toBeVisible();
|
||||
await expect(drawing).toContainText("Finish");
|
||||
|
||||
await preview.focus();
|
||||
await expect(drawing).toContainText("Revised end");
|
||||
});
|
||||
|
||||
test("copies fenced Markdown code with hover or keyboard in both preview layouts", async ({
|
||||
workbench: page,
|
||||
context,
|
||||
|
||||
@@ -68,7 +68,10 @@ for (const { theme, scheme } of themes) {
|
||||
return channels[0]! * 0.2126 + channels[1]! * 0.7152 + channels[2]! * 0.0722;
|
||||
};
|
||||
return marks.flatMap((mark) => {
|
||||
const background = luminance(getComputedStyle(mark).backgroundColor);
|
||||
// The match is filled by a gradient of one colour, capped at the row (inlineBg).
|
||||
const style = getComputedStyle(mark);
|
||||
const fill = /rgba?\([^)]*\)/.exec(style.backgroundImage)?.[0] ?? style.backgroundColor;
|
||||
const background = luminance(fill);
|
||||
return [mark, ...mark.querySelectorAll("*")].map((node) => {
|
||||
const foreground = luminance(getComputedStyle(node).color);
|
||||
return (Math.max(background, foreground) + 0.05) / (Math.min(background, foreground) + 0.05);
|
||||
|
||||
@@ -51,7 +51,8 @@ with tempfile.TemporaryDirectory() as scratch:
|
||||
"##teamcity[testFailed name='fails' className='sample.SampleTest' message='org.opentest4j.AssertionFailedError: it|'s wrong ==> expected: <1> but was: <2>'",
|
||||
"##teamcity[testIgnored name='disabled' className='sample.SampleTest'",
|
||||
"##teamcity[testIgnored name='aborted' className='sample.SampleTest']",
|
||||
"##teamcity[testFailed name='parameterized' className='sample.SampleTest'",
|
||||
"##teamcity[testStarted name='parameterized' className='sample.SampleTest' invocation='|[1|] 1']",
|
||||
"##teamcity[testFailed name='parameterized' className='sample.SampleTest' invocation='|[2|] 2'",
|
||||
"##teamcity[testFinished name='nested' className='sample.SampleTest$Inner' duration=",
|
||||
"7 tests completed, 2 failed, 2 skipped",
|
||||
]
|
||||
|
||||
Бінарний файл не відображається.
@@ -153,18 +153,25 @@ final class PlatformRunner implements TestExecutionListener {
|
||||
for (Output o : outputs) o.flushLines(true);
|
||||
}
|
||||
|
||||
/** `name='method' className='a.B$Nested'`, the method and class of the test or its closest source. */
|
||||
/**
|
||||
* `name='method' className='a.B$Nested'`, the method and class of the test or its closest source;
|
||||
* an invocation of a parameterized, repeated or dynamic test adds `invocation='[1] a'`, its display name.
|
||||
*/
|
||||
private String id(TestIdentifier id) {
|
||||
// The outermost method of the chain: the test itself, or the method container of its invocations.
|
||||
TestIdentifier method = null;
|
||||
for (TestIdentifier at = id; at != null; at = plan.getParent(at).orElse(null)) {
|
||||
TestSource source = at.getSource().orElse(null);
|
||||
if (source instanceof MethodSource) {
|
||||
MethodSource m = (MethodSource) source;
|
||||
return Reporter.attr("name", m.getMethodName()) + Reporter.attr("className", m.getClassName());
|
||||
}
|
||||
if (source instanceof ClassSource)
|
||||
if (source instanceof MethodSource) method = at;
|
||||
else if (method != null) break;
|
||||
else if (source instanceof ClassSource)
|
||||
return Reporter.attr("name", id.getLegacyReportingName()) + Reporter.attr("className", ((ClassSource) source).getClassName());
|
||||
}
|
||||
return Reporter.attr("name", id.getLegacyReportingName()) + Reporter.attr("className", id.getDisplayName());
|
||||
if (method == null)
|
||||
return Reporter.attr("name", id.getLegacyReportingName()) + Reporter.attr("className", id.getDisplayName());
|
||||
MethodSource m = (MethodSource) method.getSource().get();
|
||||
String own = Reporter.attr("name", m.getMethodName()) + Reporter.attr("className", m.getClassName());
|
||||
return method == id ? own : own + Reporter.attr("invocation", id.getDisplayName());
|
||||
}
|
||||
|
||||
private Optional<String> className(TestIdentifier id) {
|
||||
|
||||
@@ -10,6 +10,7 @@ const config: KnipConfig = {
|
||||
"!src/editor/core/cm/jsp/parser.terms.ts",
|
||||
"!src/editor/core/cm/astro/parser.terms.ts",
|
||||
"!src/editor/core/cm/django/parser.terms.ts",
|
||||
"!src/editor/core/cm/freemarker/parser.terms.ts",
|
||||
"scripts/**/*.ts",
|
||||
"perf/**/*.ts",
|
||||
"evals/**/*.ts",
|
||||
|
||||
@@ -23,6 +23,7 @@
|
||||
"gen:angular-grammar": "lezer-generator src/editor/core/cm/angular/angular.grammar --typeScript -o src/editor/core/cm/angular/parser.ts",
|
||||
"gen:jsp-grammar": "lezer-generator src/editor/core/cm/jsp/jsp.grammar --typeScript -o src/editor/core/cm/jsp/parser.ts",
|
||||
"gen:django-grammar": "lezer-generator src/editor/core/cm/django/django.grammar --typeScript -o src/editor/core/cm/django/parser.ts",
|
||||
"gen:freemarker-grammar": "lezer-generator src/editor/core/cm/freemarker/freemarker.grammar --typeScript -o src/editor/core/cm/freemarker/parser.ts",
|
||||
"gen:astro-grammar": "lezer-generator src/editor/core/cm/astro/astro.grammar --typeScript -o src/editor/core/cm/astro/parser.ts",
|
||||
"gen:theme-docs": "node scripts/theme/gen-docs.ts",
|
||||
"gen:plugin-catalog": "node scripts/gen-plugin-catalog.ts",
|
||||
|
||||
+92
-92
@@ -582,7 +582,7 @@ matching SDK. Plugins for 1.14 and earlier keep working. New in 1.15:
|
||||
rather than failing the plugin.
|
||||
- [Forking agent sessions](#forking-agent-sessions-api-115):
|
||||
`host::fork_agent_session` (`agents.fork-session`) continues a recorded native
|
||||
agent session (`claude` or `codex`) as a new task in the invoking window's
|
||||
agent session (`claude`, `codex`, or `copilot`) as a new task in the invoking window's
|
||||
project, returning the task id. Requires the `agents` capability; the host
|
||||
validates the session and builds the fork invocation itself.
|
||||
|
||||
@@ -920,95 +920,95 @@ then run `openidea-plugin check`.
|
||||
|
||||
### The API
|
||||
|
||||
| Rust SDK | WIT | Notes |
|
||||
| -------------------------------------------------------------------------------------------------------------- | -------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
||||
| `Plugin::run_command(id, ctx, arg)` | export `commands.run` | `ctx` is the window: `ctx.project()`, `ctx.editor()`. An error shows _"<title> failed: …"_; the plugin keeps running. `"msg".into()` is `Error::Failed`; `Cancelled` and `Denied` don't count as the plugin failing. |
|
||||
| `Plugin::handle_events(events, ctx)` | export `event-handler.handle` | Batches of subscribed events, oldest first, per window. |
|
||||
| `Plugin::activate` / `deactivate` | export `lifecycle` | Per instance: after a crash or idle reclaim a new one is activated. |
|
||||
| `TextEditor::document()` → `{version, text}` | `editor.text-editor.document` | `selections()` are those when the command ran (0-based lines, UTF-16 columns). |
|
||||
| `Project::document`, `apply_document_edits` | `editor.{document,apply-edits}-at` | API 1.6: versioned access to an explicitly named open project document from background events. Requires `project.read` and `editor.read`/`editor.write`; stale edits change nothing. |
|
||||
| `WebSocket::{connect,send,drain,close}` | `net.websocket-*` | API 1.6: project-bound, bounded host-owned WSS transport with secret-filled headers, close state and event-driven wakeups. |
|
||||
| `Project::{upsert_data_source,remove_data_source,data_sources,set_data_source_credential,connect_data_source}` | `database` | API 1.4: owned project sources; requires `database.sources` and trust. See _Database sources_. |
|
||||
| `host::mcp_stdio_command()` | `mcp.stdio-command` | API 1.4: invoking project bridge argv, `None` while off. No URL/token. |
|
||||
| `McpProvider::call(tool, arguments, ctx)` | export `mcp-provider.call` | API 1.4: declared tools under plugin grants and command budget. See _Plugin MCP tools_. |
|
||||
| `host::open_editors()` | `editor.open-editors` | API 1.4: invoking window's path/language/dirty/active snapshots; requires `editor.read`. Commands/events of a window only. |
|
||||
| `host::open_editor(path, selection)` | `editor.open` | API 1.4: open/select a project file (`project.read`), plugin-dir file, or install-directory file (read-only); same path rules as `views.open-location`. Commands/events of a window only. |
|
||||
| `TextEditor::set_selections(ranges)`, `reveal(range)` | `editor.text-editor` | API 1.4: selections or scrolling in this window's already open editor; no capability. Commands/events only, UTF-16 coordinates. |
|
||||
| `host::set_decorations`, `clear_decorations` | `decorations.{set,clear}` | API 1.4: project-scoped editor annotations cleared on plugin stop. Requires `project.read`. |
|
||||
| `host::set_markdown_decorations` | `decorations.set-markdown` | API 1.16: the same sets with `markdown_hover` cards; shares set ids and limits with `set_decorations`. Requires `project.read`. |
|
||||
| `host::set_styled_decorations` | `decorations.set-styled` | API 1.17: those items with their own `#rrggbb` / `#rrggbbaa` `colors`; `style` may be empty when colors are set; shares set ids and limits with `set_decorations`. Requires `project.read`. |
|
||||
| `host::set_file_decoration`, `clear_file_decorations` | `decorations.{set-file,clear-file}` | API 1.4: project-tree badges/styles. Requires `project.read`. |
|
||||
| `host::set_file_note` | `decorations.set-file-note` | API 1.7: a note after the name in the project tree (one line, at most 200 characters). Requires `project.read`. |
|
||||
| `host::set_file_icon`, `set_file_icons` | `decorations.{set-file-icon,set-file-icons}` | API 1.8: assign one of the plugin's declared `[[contributes.fileIcons]]` icons to a file or plain folder by path (individually or up to 10,000 entries per set). Requires `project.read`. |
|
||||
| `Project::search_text(query, limit)` | `workspace.project.search-text` | API 1.4: cancellable Find in Files with unsaved documents and project excludes, at most 10,000 matches. Requires `project.read`. |
|
||||
| `host::problems(path)` | `diagnostics.problems` | API 1.4: project Problems reports grouped by file/source, optional file filter. Requires `project.read` and an invoking window. Empty for remote projects. |
|
||||
| `Project::vcs_log(path, limit)` | `vcs.log` | API 1.4: newest first, at most 1000 commits, optional file history. Requires `vcs.read` and trust. |
|
||||
| `Project::vcs_blame(path)` | `vcs.blame` | API 1.4: attribution including unsaved editor text. Requires `vcs.read` and trust. |
|
||||
| `Project::build_dependencies(module)` | `build.dependencies` | API 1.10: the Maven / Gradle dependency graph the IDE resolved, flat, each module a root; nothing is resolved for the call. Requires `build.read` and trust. |
|
||||
| `Project::vcs_diff(path, against)` | `vcs.diff` | API 1.4: disk working tree against HEAD/revision, optionally one file. None outside Git; fails above 4 MiB. Requires `vcs.read` and trust. |
|
||||
| `TextEditor::apply_edits(version, edits)` | `editor.text-editor.apply-edits` | One undoable change, only if the document is still at `version` — else `Error::Stale` and nothing changes. `transform_selections` retries once. |
|
||||
| `Project::root()`, `read_file(path)` | `workspace.project` | Absolute or project-relative; `..`/symlinks escaping the root are rejected; UTF-8 only, ≤ 16 MiB; unsaved editor contents win; a missing path is `Error::NotFound`. |
|
||||
| `Project::read_bytes(path)` | `workspace.project.read-bytes` | API 1.5: the exact bytes of a file inside the project (binary content is the point), at most 16 MiB, the file on disk. Same paths and `Error::NotFound` as `read_file`. |
|
||||
| `Project::exists(path)`, `stat(path)` | `workspace.project` | `exists` covers files and directories, hidden and ignored included, without reading content; `stat` gives kind, size and modified time (`Error::NotFound` for a missing path). |
|
||||
| `host::projects()` | `workspace.projects` | Every open project (for scheduled work without a window). |
|
||||
| `Project::vcs_status()`, `vcs_remotes()`, `vcs_fetch()` | `vcs` | `vcs_remotes` returns `(name, url)` pairs; fetch runs git, so only in trusted projects (call it inside a task). |
|
||||
| `host::pending_commit()`, `host::set_commit_message(revision, text)` | `commit` | The commit being prepared in the calling window and its message; see _Commits_. |
|
||||
| `host::subscribe(kind)` | `events.subscribe` | For the session, across idle reclaim (an event activates the plugin). Or declare `on-event:<kind>`. |
|
||||
| `host::begin_task(title, cancellable)` → `Task` | `tasks.begin` | Shown with the background tasks; `report`, `is_cancelled`; the call may run 60 s instead of 5 s while it is open; dropping it ends it. |
|
||||
| `host::storage::{get, set, delete, keys}` | `storage` | Survives restarts; the instance's memory does not. Deleted on uninstall. |
|
||||
| `host::set_status_item(id, item)`, `remove_status_item` | `ui` | `text`, `tooltip`, `command` (one of yours, run on click); at most 8; kept while the plugin is idle. |
|
||||
| `host::set_window_status_item(id, item)`, `remove_window_status_item(id)` | `ui.{set,remove}-window-status-item` | API 1.4: window-only override; removed on window close or plugin stop; removing falls back to the global item. Click runs its command in that window. |
|
||||
| `host::set_status_item_menu(id, item, menu)`, `set_window_status_item_menu` | `ui.set-{,window-}status-item-menu` | API 1.14: the item with a menu that a click opens instead of running its command; actions run declared commands with their argument. |
|
||||
| `host::execute_command(id, arg)` → `Option<String>` | `command-runner.execute` | API 1.4: requires high-risk `ide.commands` for IDE actions and other plugins; this plugin's own commands are exempt. Stable IDE action or `plugin.<plugin-id>.<command-id>` in the invoking window. IDE actions return none; plugin commands return their result. Unknown ids are not-found; at most 8 nested calls, no re-entry into a waiting instance. |
|
||||
| `host::ipc_connect(name)` → `Connection` | `ipc.connect` | API 1.4: `write(bytes)`, `read(max_bytes, timeout_ms)`, `close()`; requires `ipc:<path>`, at most 8 connections, closed on drop or plugin stop. Runs on the project server in remote projects. |
|
||||
| `host::secret_set(name, value)`, `secret_delete(name)` | `secrets.{set,delete}` | API 1.4: requires `secrets` and a declared name. Never returns the value. |
|
||||
| `host::begin_loopback(path)` → `Loopback` | `auth.begin-loopback` | API 1.4: `redirect_uri()`, `wait(timeout_ms)` → raw query or none on timeout. Desktop-only, even for remote projects; no capability. At most 2 listeners; one-shot, closed on timeout, drop or stop. Waiting excludes the call budget. |
|
||||
| `host::output_append(channel, text)`, `output_clear`, `output_reveal` | `output.{append,clear,reveal}` | API 1.4: read-only Output tabs; 32 named channels per plugin, each a 1 MiB UTF-8 ring buffer. Reveal requires the invoking window. |
|
||||
| `host::set_context(key, value)`, `remove_context` | `ui.{set,remove}-context` | Sets `plugin.<id>.<key>` for `when` clauses in the window the call came from (`true`, `3.5`, `"text"`; `ContextValue`). Key 1–64 of `A-Za-z0-9_-`, 100 per plugin; gone when the plugin stops. |
|
||||
| `host::set_console_rules(rules)` | `ui.set-console-rules` | API 1.12: replaces the plugin's highlight rules for Run and Debug console output (regex, palette colours, styles, whole line or match); no capability. See _Console highlight rules_. |
|
||||
| `host::notify(level, title, body)` | `ui.show-notification` | Balloon in the window the command or events came from (every window otherwise). |
|
||||
| `Project::notify(level, title, body, actions)` | `ui.notify-project` | API 1.5: balloon only in a window of that project (the most recently focused one), with or without an invoking window; see _Notifications with commands_. |
|
||||
| `host::copy_to_clipboard(text)` | `ui.copy-to-clipboard` | Copies `text` to the system clipboard. Needs `clipboard`. |
|
||||
| `host::read_clipboard()` → `ClipboardContent` | `ui.read-clipboard` | API 1.11: the clipboard's `text` and `image` (PNG bytes), `None` for what it doesn't hold. Needs `clipboard.read`; only in a command the user ran or a view action, else `denied`. See _Reading the clipboard_. |
|
||||
| `host::open_url(url)` | `ui.open-url` | Opens an `http://` or `https://` URL in the user's default browser. |
|
||||
| `host::pick(title, items)`, `pick_many` | `ui.pick`, `ui.pick-many` | Picks key(s) from `PickItem`s, or `None` when dismissed. From a command/event or code-action resolution in its editor window (else `invalid`); waiting is excluded from the budget. |
|
||||
| `host::input(prompt, value)` | `ui.input` | A one-line text box pre-filled with `value`; `None` when dismissed. Same rules as `pick`. |
|
||||
| `host::input_multiline(prompt, value)` | `ui.input-multiline` | A multi-line text box pre-filled with `value`; `None` when dismissed; Cmd/Ctrl+Enter confirms. Only from a command or event of a window. |
|
||||
| `host::confirm(title, body)` | `ui.confirm` | OK / Cancel; `true` on OK. Same rules as `pick`. |
|
||||
| `host::locale()` | `ui.locale` | The IDE's UI language as a BCP 47 tag (`en`, `fr`, `zh-CN`); no capability. See _Translations_. |
|
||||
| `host::log(level, msg)` | `log` | IDE log, tagged with the plugin id. `eprintln!` output is logged too and shown when the plugin crashes. |
|
||||
| `Project::find_files(glob, limit)` | `workspace.project.find-files` | Project-relative glob (`**/*Mapper.xml`); honours `.gitignore`; at most `limit` paths. |
|
||||
| `Project::symbols(query, limit)` | `workspace.symbols` | New in 1.3; `project.read`. Fuzzy in-memory search (no LSP): name, camelCase kind, container and UTF-16 location. Queries ≤ 256 UTF-8 bytes; limits capped at 1000. Snapshot notes below. |
|
||||
| `host::publish_diagnostics(path, items)` | `diagnostics.publish` | Replaces this plugin's problems for the file (editor squiggles and the Problems view); an empty list clears them. |
|
||||
| `host::fetch(request)` → `{status, headers, body}` | `net.fetch` | See _Network_. |
|
||||
| `Project::run_process(program, args, stdin)` → `{code, stdout, stderr}` | `process.run` | Only the pinned program of a `process:` grant; runs in the project root of a trusted project; up to 16 MiB of stdout (fails if exceeded); killed when the call is cancelled or times out. |
|
||||
| `host::run_command(cmd, project, stdin)` → `{code, stdout, stderr}` | `process.run-command` | API 1.3: same limits as `run_process`, with append-only environment variables; needs the pinned `process:<program>` grant. |
|
||||
| `host::start(cmd, project)` → `Child` | `process.start` | API 1.3: `poll(max_bytes)`, `write(text)`, `close_stdin()`, `wait(timeout_ms)`, `kill()`; at most 8 handles; dropping one kills its process. |
|
||||
| `host::refresh_view(view)` | `views.refresh` | The view (or custom editors) render again; call it when the content changed. |
|
||||
| `host::reveal_view(view)` | `views.reveal` | Brings one of your declared `[[contributes.views]]` to the front in the calling window. |
|
||||
| `host::post_view_message(view, text)` | `views.post-message` | To the script of the view's `html` body. |
|
||||
| `host::open_terminal(title, program, args)` | `views.open-terminal` | A terminal tab in the invoking window running the approved `process:<program>` in the project root: output that keeps coming, interactive sessions. |
|
||||
| `host::register_run_target(project, target)` | `run-targets.register` | API 1.4: project-scoped, read-only argv wrapper; requires its process grant, executable pin and project trust; remote projects run on the server. |
|
||||
| `host::unregister_run_target(project, id)` | `run-targets.unregister` | Withdraw this plugin's target; remembered prompt answers remain. |
|
||||
| `host::start_run(config, args, debug)` | `run.start` | API 1.4: start an owned configuration in this window's Run tool window; returns an id, followed by `run-exited`. Approved `process:` program; commands/events only. |
|
||||
| `host::start_run_with_options(config, args, options)` | `run.start-with-options` | API 1.18: start an owned configuration with `RunStartOptions` (`debug` and optional per-launch `output_mode`); user-saved override wins over `options.output_mode`, which wins over plugin default. |
|
||||
| `host::open_terminal_session(key, title, cmd)` | `views.open-terminal-session` | API 1.4: keyed, pinned terminal in this window, append-only env; returns its operation id and later `terminal-exited`. |
|
||||
| `host::open_terminal_session_in(key, title, cmd, cwd)` | `views.open-terminal-session-in` | API 1.18: the same, started in `cwd`, a directory of the project relative to its root. |
|
||||
| `host::write_terminal(key, text)` | `views.write-terminal` | API 1.4: write only to this plugin's still-running terminal in this window; trusted project, commands/events only. |
|
||||
| `host::open_content_tab(tab)` | `views.open-content-tab` | API 1.4: the shared content editor protocol, without a web view; actions arrive as `content-tab-action`. |
|
||||
| `host::reply_content_tab(request_id, reply)` | `views.reply-content-tab` | API 1.4: reply to an owned action in the originating window. No capability; commands/events only. |
|
||||
| `host::open_diff(diff, file_name)` | `views.open-diff` | API 1.7: two texts in the invoking window's diff viewer; `file_name` (at most 256 characters) picks the highlighting. Commands/events only; each side at most 8 MiB (earlier hosts: 1 MiB), a larger side fails with `Invalid("diff too large: …")`. |
|
||||
| `host::open_file_diff(diff, file_name)` | `views.open-file-diff` | API 1.10: `open_diff` where a side may be `None` (the file doesn't exist there: added or deleted); the viewer shows the other side alone. Both `None` fails with `Invalid`. |
|
||||
| `RunConfigurations::configurations(root)` | export `run-configurations.configurations` | API 1.4: optional `plugin-run-configurations` world; SDK registration `run_configurations`. Full project list, refreshed on configuration listing. |
|
||||
| `LaunchConfigurations::launch_configurations(root)` | export `launch-configurations` | API 1.9: optional `plugin-launch-configurations` world; SDK registration `launch_configurations`. The same list with `env` and `debugger`; preferred over `run-configurations`. |
|
||||
| `ExecutionConfigurations::execution_configurations(root)` | export `execution-configurations` | API 1.18: optional `plugin-execution-configurations` world; SDK registration `execution_configurations`. Adds a default `output_mode` (`Pipes` or `Pty`); preferred over `launch-configurations` and `run-configurations`. |
|
||||
| `RunConfigurationCompletion::complete(project, config, field, text, caret)` | export `run-configuration-completion` | API 1.18: optional `plugin-run-configuration-completion` world; SDK registration `run_configuration_completion`. Completes the Arguments field (`field = "arguments"`) of the plugin's own configurations; items replace a UTF-16 range; 200 items, 300 ms. |
|
||||
| `TestResults::parse(config, chunk)` | export `test-results.parse` | API 1.4: optional `plugin-test-results` world; SDK registration `test_results`. Bounded output batches for `framework = "plugin"`; failures use built-in parsers. |
|
||||
| `TestResults::select_tests(config, tests)` | export `test-results.select-tests` | API 1.4: full replacement argv for test-tree name paths, or `None` when unsupported (the SDK default). Enables rerunning failed tests and running tree selections. |
|
||||
| `host::open_location(path, line, column)` | `views.open-location` | Opens a file inside the project in an editor of the invoking window, the caret at `line`/`column` (0-based, UTF-16): a view's links to code. Needs `project.read`. |
|
||||
| `host::setting(key)`, `setting_bool`, `setting_string`, `setting_number` | `settings.get` | The user's value (project over global) or the schema's default. |
|
||||
| `host::open_settings(page)`, `open_permissions()` | `settings.open`, `settings.open-permissions` | API 1.19: Settings at the plugin's node (`None`) or one of its pages; at its permissions in Settings › Plugins. Commands and events only. |
|
||||
| `host::fork_agent_session(agent, session_id, cwd)` → `String` | `agents.fork-session` | API 1.18: fork a recorded native agent session (`claude` or `codex`) into a new task in the invoking window's project, returning the new task id. Requires the `agents` capability and project trust; the session must belong to the project and have been recorded in `cwd`. The host builds the fork invocation; claude forks under a host-chosen id, codex assigns its own. See _Forking agent sessions_. |
|
||||
| Rust SDK | WIT | Notes |
|
||||
| -------------------------------------------------------------------------------------------------------------- | -------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `Plugin::run_command(id, ctx, arg)` | export `commands.run` | `ctx` is the window: `ctx.project()`, `ctx.editor()`. An error shows _"<title> failed: …"_; the plugin keeps running. `"msg".into()` is `Error::Failed`; `Cancelled` and `Denied` don't count as the plugin failing. |
|
||||
| `Plugin::handle_events(events, ctx)` | export `event-handler.handle` | Batches of subscribed events, oldest first, per window. |
|
||||
| `Plugin::activate` / `deactivate` | export `lifecycle` | Per instance: after a crash or idle reclaim a new one is activated. |
|
||||
| `TextEditor::document()` → `{version, text}` | `editor.text-editor.document` | `selections()` are those when the command ran (0-based lines, UTF-16 columns). |
|
||||
| `Project::document`, `apply_document_edits` | `editor.{document,apply-edits}-at` | API 1.6: versioned access to an explicitly named open project document from background events. Requires `project.read` and `editor.read`/`editor.write`; stale edits change nothing. |
|
||||
| `WebSocket::{connect,send,drain,close}` | `net.websocket-*` | API 1.6: project-bound, bounded host-owned WSS transport with secret-filled headers, close state and event-driven wakeups. |
|
||||
| `Project::{upsert_data_source,remove_data_source,data_sources,set_data_source_credential,connect_data_source}` | `database` | API 1.4: owned project sources; requires `database.sources` and trust. See _Database sources_. |
|
||||
| `host::mcp_stdio_command()` | `mcp.stdio-command` | API 1.4: invoking project bridge argv, `None` while off. No URL/token. |
|
||||
| `McpProvider::call(tool, arguments, ctx)` | export `mcp-provider.call` | API 1.4: declared tools under plugin grants and command budget. See _Plugin MCP tools_. |
|
||||
| `host::open_editors()` | `editor.open-editors` | API 1.4: invoking window's path/language/dirty/active snapshots; requires `editor.read`. Commands/events of a window only. |
|
||||
| `host::open_editor(path, selection)` | `editor.open` | API 1.4: open/select a project file (`project.read`), plugin-dir file, or install-directory file (read-only); same path rules as `views.open-location`. Commands/events of a window only. |
|
||||
| `TextEditor::set_selections(ranges)`, `reveal(range)` | `editor.text-editor` | API 1.4: selections or scrolling in this window's already open editor; no capability. Commands/events only, UTF-16 coordinates. |
|
||||
| `host::set_decorations`, `clear_decorations` | `decorations.{set,clear}` | API 1.4: project-scoped editor annotations cleared on plugin stop. Requires `project.read`. |
|
||||
| `host::set_markdown_decorations` | `decorations.set-markdown` | API 1.16: the same sets with `markdown_hover` cards; shares set ids and limits with `set_decorations`. Requires `project.read`. |
|
||||
| `host::set_styled_decorations` | `decorations.set-styled` | API 1.17: those items with their own `#rrggbb` / `#rrggbbaa` `colors`; `style` may be empty when colors are set; shares set ids and limits with `set_decorations`. Requires `project.read`. |
|
||||
| `host::set_file_decoration`, `clear_file_decorations` | `decorations.{set-file,clear-file}` | API 1.4: project-tree badges/styles. Requires `project.read`. |
|
||||
| `host::set_file_note` | `decorations.set-file-note` | API 1.7: a note after the name in the project tree (one line, at most 200 characters). Requires `project.read`. |
|
||||
| `host::set_file_icon`, `set_file_icons` | `decorations.{set-file-icon,set-file-icons}` | API 1.8: assign one of the plugin's declared `[[contributes.fileIcons]]` icons to a file or plain folder by path (individually or up to 10,000 entries per set). Requires `project.read`. |
|
||||
| `Project::search_text(query, limit)` | `workspace.project.search-text` | API 1.4: cancellable Find in Files with unsaved documents and project excludes, at most 10,000 matches. Requires `project.read`. |
|
||||
| `host::problems(path)` | `diagnostics.problems` | API 1.4: project Problems reports grouped by file/source, optional file filter. Requires `project.read` and an invoking window. Empty for remote projects. |
|
||||
| `Project::vcs_log(path, limit)` | `vcs.log` | API 1.4: newest first, at most 1000 commits, optional file history. Requires `vcs.read` and trust. |
|
||||
| `Project::vcs_blame(path)` | `vcs.blame` | API 1.4: attribution including unsaved editor text. Requires `vcs.read` and trust. |
|
||||
| `Project::build_dependencies(module)` | `build.dependencies` | API 1.10: the Maven / Gradle dependency graph the IDE resolved, flat, each module a root; nothing is resolved for the call. Requires `build.read` and trust. |
|
||||
| `Project::vcs_diff(path, against)` | `vcs.diff` | API 1.4: disk working tree against HEAD/revision, optionally one file. None outside Git; fails above 4 MiB. Requires `vcs.read` and trust. |
|
||||
| `TextEditor::apply_edits(version, edits)` | `editor.text-editor.apply-edits` | One undoable change, only if the document is still at `version` — else `Error::Stale` and nothing changes. `transform_selections` retries once. |
|
||||
| `Project::root()`, `read_file(path)` | `workspace.project` | Absolute or project-relative; `..`/symlinks escaping the root are rejected; UTF-8 only, ≤ 16 MiB; unsaved editor contents win; a missing path is `Error::NotFound`. |
|
||||
| `Project::read_bytes(path)` | `workspace.project.read-bytes` | API 1.5: the exact bytes of a file inside the project (binary content is the point), at most 16 MiB, the file on disk. Same paths and `Error::NotFound` as `read_file`. |
|
||||
| `Project::exists(path)`, `stat(path)` | `workspace.project` | `exists` covers files and directories, hidden and ignored included, without reading content; `stat` gives kind, size and modified time (`Error::NotFound` for a missing path). |
|
||||
| `host::projects()` | `workspace.projects` | Every open project (for scheduled work without a window). |
|
||||
| `Project::vcs_status()`, `vcs_remotes()`, `vcs_fetch()` | `vcs` | `vcs_remotes` returns `(name, url)` pairs; fetch runs git, so only in trusted projects (call it inside a task). |
|
||||
| `host::pending_commit()`, `host::set_commit_message(revision, text)` | `commit` | The commit being prepared in the calling window and its message; see _Commits_. |
|
||||
| `host::subscribe(kind)` | `events.subscribe` | For the session, across idle reclaim (an event activates the plugin). Or declare `on-event:<kind>`. |
|
||||
| `host::begin_task(title, cancellable)` → `Task` | `tasks.begin` | Shown with the background tasks; `report`, `is_cancelled`; the call may run 60 s instead of 5 s while it is open; dropping it ends it. |
|
||||
| `host::storage::{get, set, delete, keys}` | `storage` | Survives restarts; the instance's memory does not. Deleted on uninstall. |
|
||||
| `host::set_status_item(id, item)`, `remove_status_item` | `ui` | `text`, `tooltip`, `command` (one of yours, run on click); at most 8; kept while the plugin is idle. |
|
||||
| `host::set_window_status_item(id, item)`, `remove_window_status_item(id)` | `ui.{set,remove}-window-status-item` | API 1.4: window-only override; removed on window close or plugin stop; removing falls back to the global item. Click runs its command in that window. |
|
||||
| `host::set_status_item_menu(id, item, menu)`, `set_window_status_item_menu` | `ui.set-{,window-}status-item-menu` | API 1.14: the item with a menu that a click opens instead of running its command; actions run declared commands with their argument. |
|
||||
| `host::execute_command(id, arg)` → `Option<String>` | `command-runner.execute` | API 1.4: requires high-risk `ide.commands` for IDE actions and other plugins; this plugin's own commands are exempt. Stable IDE action or `plugin.<plugin-id>.<command-id>` in the invoking window. IDE actions return none; plugin commands return their result. Unknown ids are not-found; at most 8 nested calls, no re-entry into a waiting instance. |
|
||||
| `host::ipc_connect(name)` → `Connection` | `ipc.connect` | API 1.4: `write(bytes)`, `read(max_bytes, timeout_ms)`, `close()`; requires `ipc:<path>`, at most 8 connections, closed on drop or plugin stop. Runs on the project server in remote projects. |
|
||||
| `host::secret_set(name, value)`, `secret_delete(name)` | `secrets.{set,delete}` | API 1.4: requires `secrets` and a declared name. Never returns the value. |
|
||||
| `host::begin_loopback(path)` → `Loopback` | `auth.begin-loopback` | API 1.4: `redirect_uri()`, `wait(timeout_ms)` → raw query or none on timeout. Desktop-only, even for remote projects; no capability. At most 2 listeners; one-shot, closed on timeout, drop or stop. Waiting excludes the call budget. |
|
||||
| `host::output_append(channel, text)`, `output_clear`, `output_reveal` | `output.{append,clear,reveal}` | API 1.4: read-only Output tabs; 32 named channels per plugin, each a 1 MiB UTF-8 ring buffer. Reveal requires the invoking window. |
|
||||
| `host::set_context(key, value)`, `remove_context` | `ui.{set,remove}-context` | Sets `plugin.<id>.<key>` for `when` clauses in the window the call came from (`true`, `3.5`, `"text"`; `ContextValue`). Key 1–64 of `A-Za-z0-9_-`, 100 per plugin; gone when the plugin stops. |
|
||||
| `host::set_console_rules(rules)` | `ui.set-console-rules` | API 1.12: replaces the plugin's highlight rules for Run and Debug console output (regex, palette colours, styles, whole line or match); no capability. See _Console highlight rules_. |
|
||||
| `host::notify(level, title, body)` | `ui.show-notification` | Balloon in the window the command or events came from (every window otherwise). |
|
||||
| `Project::notify(level, title, body, actions)` | `ui.notify-project` | API 1.5: balloon only in a window of that project (the most recently focused one), with or without an invoking window; see _Notifications with commands_. |
|
||||
| `host::copy_to_clipboard(text)` | `ui.copy-to-clipboard` | Copies `text` to the system clipboard. Needs `clipboard`. |
|
||||
| `host::read_clipboard()` → `ClipboardContent` | `ui.read-clipboard` | API 1.11: the clipboard's `text` and `image` (PNG bytes), `None` for what it doesn't hold. Needs `clipboard.read`; only in a command the user ran or a view action, else `denied`. See _Reading the clipboard_. |
|
||||
| `host::open_url(url)` | `ui.open-url` | Opens an `http://` or `https://` URL in the user's default browser. |
|
||||
| `host::pick(title, items)`, `pick_many` | `ui.pick`, `ui.pick-many` | Picks key(s) from `PickItem`s, or `None` when dismissed. From a command/event or code-action resolution in its editor window (else `invalid`); waiting is excluded from the budget. |
|
||||
| `host::input(prompt, value)` | `ui.input` | A one-line text box pre-filled with `value`; `None` when dismissed. Same rules as `pick`. |
|
||||
| `host::input_multiline(prompt, value)` | `ui.input-multiline` | A multi-line text box pre-filled with `value`; `None` when dismissed; Cmd/Ctrl+Enter confirms. Only from a command or event of a window. |
|
||||
| `host::confirm(title, body)` | `ui.confirm` | OK / Cancel; `true` on OK. Same rules as `pick`. |
|
||||
| `host::locale()` | `ui.locale` | The IDE's UI language as a BCP 47 tag (`en`, `fr`, `zh-CN`); no capability. See _Translations_. |
|
||||
| `host::log(level, msg)` | `log` | IDE log, tagged with the plugin id. `eprintln!` output is logged too and shown when the plugin crashes. |
|
||||
| `Project::find_files(glob, limit)` | `workspace.project.find-files` | Project-relative glob (`**/*Mapper.xml`); honours `.gitignore`; at most `limit` paths. |
|
||||
| `Project::symbols(query, limit)` | `workspace.symbols` | New in 1.3; `project.read`. Fuzzy in-memory search (no LSP): name, camelCase kind, container and UTF-16 location. Queries ≤ 256 UTF-8 bytes; limits capped at 1000. Snapshot notes below. |
|
||||
| `host::publish_diagnostics(path, items)` | `diagnostics.publish` | Replaces this plugin's problems for the file (editor squiggles and the Problems view); an empty list clears them. |
|
||||
| `host::fetch(request)` → `{status, headers, body}` | `net.fetch` | See _Network_. |
|
||||
| `Project::run_process(program, args, stdin)` → `{code, stdout, stderr}` | `process.run` | Only the pinned program of a `process:` grant; runs in the project root of a trusted project; up to 16 MiB of stdout (fails if exceeded); killed when the call is cancelled or times out. |
|
||||
| `host::run_command(cmd, project, stdin)` → `{code, stdout, stderr}` | `process.run-command` | API 1.3: same limits as `run_process`, with append-only environment variables; needs the pinned `process:<program>` grant. |
|
||||
| `host::start(cmd, project)` → `Child` | `process.start` | API 1.3: `poll(max_bytes)`, `write(text)`, `close_stdin()`, `wait(timeout_ms)`, `kill()`; at most 8 handles; dropping one kills its process. |
|
||||
| `host::refresh_view(view)` | `views.refresh` | The view (or custom editors) render again; call it when the content changed. |
|
||||
| `host::reveal_view(view)` | `views.reveal` | Brings one of your declared `[[contributes.views]]` to the front in the calling window. |
|
||||
| `host::post_view_message(view, text)` | `views.post-message` | To the script of the view's `html` body. |
|
||||
| `host::open_terminal(title, program, args)` | `views.open-terminal` | A terminal tab in the invoking window running the approved `process:<program>` in the project root: output that keeps coming, interactive sessions. |
|
||||
| `host::register_run_target(project, target)` | `run-targets.register` | API 1.4: project-scoped, read-only argv wrapper; requires its process grant, executable pin and project trust; remote projects run on the server. |
|
||||
| `host::unregister_run_target(project, id)` | `run-targets.unregister` | Withdraw this plugin's target; remembered prompt answers remain. |
|
||||
| `host::start_run(config, args, debug)` | `run.start` | API 1.4: start an owned configuration in this window's Run tool window; returns an id, followed by `run-exited`. Approved `process:` program; commands/events only. |
|
||||
| `host::start_run_with_options(config, args, options)` | `run.start-with-options` | API 1.18: start an owned configuration with `RunStartOptions` (`debug` and optional per-launch `output_mode`); user-saved override wins over `options.output_mode`, which wins over plugin default. |
|
||||
| `host::open_terminal_session(key, title, cmd)` | `views.open-terminal-session` | API 1.4: keyed, pinned terminal in this window, append-only env; returns its operation id and later `terminal-exited`. |
|
||||
| `host::open_terminal_session_in(key, title, cmd, cwd)` | `views.open-terminal-session-in` | API 1.18: the same, started in `cwd`, a directory of the project relative to its root. |
|
||||
| `host::write_terminal(key, text)` | `views.write-terminal` | API 1.4: write only to this plugin's still-running terminal in this window; trusted project, commands/events only. |
|
||||
| `host::open_content_tab(tab)` | `views.open-content-tab` | API 1.4: the shared content editor protocol, without a web view; actions arrive as `content-tab-action`. |
|
||||
| `host::reply_content_tab(request_id, reply)` | `views.reply-content-tab` | API 1.4: reply to an owned action in the originating window. No capability; commands/events only. |
|
||||
| `host::open_diff(diff, file_name)` | `views.open-diff` | API 1.7: two texts in the invoking window's diff viewer; `file_name` (at most 256 characters) picks the highlighting. Commands/events only; each side at most 8 MiB (earlier hosts: 1 MiB), a larger side fails with `Invalid("diff too large: …")`. |
|
||||
| `host::open_file_diff(diff, file_name)` | `views.open-file-diff` | API 1.10: `open_diff` where a side may be `None` (the file doesn't exist there: added or deleted); the viewer shows the other side alone. Both `None` fails with `Invalid`. |
|
||||
| `RunConfigurations::configurations(root)` | export `run-configurations.configurations` | API 1.4: optional `plugin-run-configurations` world; SDK registration `run_configurations`. Full project list, refreshed on configuration listing. |
|
||||
| `LaunchConfigurations::launch_configurations(root)` | export `launch-configurations` | API 1.9: optional `plugin-launch-configurations` world; SDK registration `launch_configurations`. The same list with `env` and `debugger`; preferred over `run-configurations`. |
|
||||
| `ExecutionConfigurations::execution_configurations(root)` | export `execution-configurations` | API 1.18: optional `plugin-execution-configurations` world; SDK registration `execution_configurations`. Adds a default `output_mode` (`Pipes` or `Pty`); preferred over `launch-configurations` and `run-configurations`. |
|
||||
| `RunConfigurationCompletion::complete(project, config, field, text, caret)` | export `run-configuration-completion` | API 1.18: optional `plugin-run-configuration-completion` world; SDK registration `run_configuration_completion`. Completes the Arguments field (`field = "arguments"`) of the plugin's own configurations; items replace a UTF-16 range; 200 items, 300 ms. |
|
||||
| `TestResults::parse(config, chunk)` | export `test-results.parse` | API 1.4: optional `plugin-test-results` world; SDK registration `test_results`. Bounded output batches for `framework = "plugin"`; failures use built-in parsers. |
|
||||
| `TestResults::select_tests(config, tests)` | export `test-results.select-tests` | API 1.4: full replacement argv for test-tree name paths, or `None` when unsupported (the SDK default). Enables rerunning failed tests and running tree selections. |
|
||||
| `host::open_location(path, line, column)` | `views.open-location` | Opens a file inside the project in an editor of the invoking window, the caret at `line`/`column` (0-based, UTF-16): a view's links to code. Needs `project.read`. |
|
||||
| `host::setting(key)`, `setting_bool`, `setting_string`, `setting_number` | `settings.get` | The user's value (project over global) or the schema's default. |
|
||||
| `host::open_settings(page)`, `open_permissions()` | `settings.open`, `settings.open-permissions` | API 1.19: Settings at the plugin's node (`None`) or one of its pages; at its permissions in Settings › Plugins. Commands and events only. |
|
||||
| `host::fork_agent_session(agent, session_id, cwd)` → `String` | `agents.fork-session` | API 1.18: fork a recorded native agent session (`claude`, `codex`, or `copilot`) into a new task in the invoking window's project, returning the new task id. Requires the `agents` capability and project trust; the session must belong to the project and have been recorded in `cwd`. The host builds the fork invocation; Claude forks under a host-chosen id, while Codex and Copilot assign their own. See _Forking agent sessions_. |
|
||||
|
||||
`Project::symbols` reads the current in-memory index: results may be partial
|
||||
while indexing, and locations can lag unsaved edits. Normal saves and filesystem
|
||||
@@ -1280,11 +1280,11 @@ the count and pattern length only, not the complexity.
|
||||
|
||||
`host::fork_agent_session(agent, session_id, cwd)` (`agents.fork-session`) continues a
|
||||
recorded native agent session as a new task in the invoking window's project, returning
|
||||
the task id. `agent` is a native provider (`claude` or `codex`); `session_id` is the
|
||||
the task id. `agent` is a native provider (`claude`, `codex`, or `copilot`); `session_id` is the
|
||||
recorded session's canonical UUID; `cwd` must be the directory the session was recorded
|
||||
in. The host validates all three against its own session discovery (the same list Import
|
||||
Sessions shows) and builds the agent's fork invocation itself, naming the fork's session id
|
||||
for claude while codex assigns its own — a plugin never supplies CLI arguments. The new task
|
||||
for Claude while Codex and Copilot assign their own - a plugin never supplies CLI arguments. The new task
|
||||
starts ready; its first turn continues the recording as the agent's own fork, leaving the
|
||||
original session unchanged.
|
||||
|
||||
|
||||
@@ -72,6 +72,10 @@ ide-android = { path = "../crates/ide-android" }
|
||||
[dev-dependencies]
|
||||
tempfile.workspace = true
|
||||
|
||||
[[test]]
|
||||
name = "background_tab_appkit"
|
||||
harness = false
|
||||
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
block2 = "0.6"
|
||||
# Plugin secrets in the login keychain.
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
disallowed-methods = [
|
||||
{ path = "tauri::webview::WebviewWindow::with_webview", reason = "panics on a detached background tab on macOS; use macos::with_web_view" },
|
||||
{ path = "tauri::webview::Webview::with_webview", reason = "panics on a detached background tab on macOS; use macos::with_web_view" },
|
||||
]
|
||||
@@ -0,0 +1,71 @@
|
||||
//! AppKit side of a background tab's detached web view; no tauri types, so a test can include it.
|
||||
use objc2::{
|
||||
Message,
|
||||
rc::Retained,
|
||||
runtime::{AnyClass, ProtocolObject},
|
||||
};
|
||||
use objc2_app_kit::{
|
||||
NSView, NSWindow, NSWindowDidBecomeKeyNotification, NSWindowDidChangeOcclusionStateNotification,
|
||||
NSWindowOcclusionState, NSWindowOrderingMode,
|
||||
};
|
||||
use objc2_foundation::{NSNotificationCenter, NSObjectProtocol};
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Return {
|
||||
Key,
|
||||
Visible,
|
||||
}
|
||||
|
||||
pub fn web_view(native: &NSWindow) -> Option<Retained<NSView>> {
|
||||
let class = AnyClass::get(c"WKWebView")?;
|
||||
native.contentView()?.subviews().iter().find(|v| v.isKindOfClass(class))
|
||||
}
|
||||
|
||||
/// At the bottom so the title bar views stay above it.
|
||||
pub fn put_back(native: &NSWindow, view: &NSView) {
|
||||
let Some(content) = native.contentView() else { return };
|
||||
view.setFrame(content.bounds());
|
||||
content.addSubview_positioned_relativeTo(view, NSWindowOrderingMode::Below, None);
|
||||
native.makeFirstResponder(Some(view));
|
||||
}
|
||||
|
||||
/// Calls `f` when the window becomes key, or visible (AppKit can bring a window back by itself,
|
||||
/// e.g. when a tab it closes next to leaves the group). The observers have no queue, so `f` runs
|
||||
/// synchronously inside the post. For the key notification that is inside `makeKeyWindow`, before the
|
||||
/// window's first display; occlusion arrives when the window is already on screen.
|
||||
pub fn on_return(
|
||||
native: &NSWindow,
|
||||
f: impl Fn(Return) + 'static,
|
||||
) -> Vec<Retained<ProtocolObject<dyn NSObjectProtocol>>> {
|
||||
let f = std::rc::Rc::new(f);
|
||||
let center = NSNotificationCenter::defaultCenter();
|
||||
let key = {
|
||||
let f = f.clone();
|
||||
let block = block2::RcBlock::new(move |_| f(Return::Key));
|
||||
unsafe {
|
||||
center.addObserverForName_object_queue_usingBlock(
|
||||
Some(NSWindowDidBecomeKeyNotification),
|
||||
Some(native),
|
||||
None,
|
||||
&block,
|
||||
)
|
||||
}
|
||||
};
|
||||
let visible = {
|
||||
let window: Retained<NSWindow> = native.retain();
|
||||
let block = block2::RcBlock::new(move |_| {
|
||||
if window.occlusionState().contains(NSWindowOcclusionState::Visible) {
|
||||
f(Return::Visible);
|
||||
}
|
||||
});
|
||||
unsafe {
|
||||
center.addObserverForName_object_queue_usingBlock(
|
||||
Some(NSWindowDidChangeOcclusionStateNotification),
|
||||
Some(native),
|
||||
None,
|
||||
&block,
|
||||
)
|
||||
}
|
||||
};
|
||||
vec![key, visible]
|
||||
}
|
||||
@@ -170,9 +170,9 @@ async fn webview_processes(app: &AppHandle, state: &AppState) -> Vec<MemoryRoot>
|
||||
let mut pending = Vec::new();
|
||||
for (label, w) in app.webview_windows() {
|
||||
let (tx, rx) = tokio::sync::oneshot::channel();
|
||||
let sent = w.with_webview(move |pv| {
|
||||
// SAFETY: `with_webview` runs on the main thread with the live WKWebView.
|
||||
let _ = tx.send(unsafe { memory::webkit_process_ids(pv.inner()) });
|
||||
let sent = crate::macos::with_web_view(&w, move |view| {
|
||||
// SAFETY: runs on the main thread with the live WKWebView, detached or not.
|
||||
let _ = tx.send(unsafe { memory::webkit_process_ids(view) });
|
||||
});
|
||||
if sent.is_ok() {
|
||||
pending.push((label, rx));
|
||||
|
||||
@@ -233,6 +233,7 @@ pub fn window_flash_taskbar(window: WebviewWindow, flash: bool) -> IdeResult<()>
|
||||
#[specta::specta]
|
||||
pub fn window_set_smooth_scrolling(window: WebviewWindow, enabled: bool) -> IdeResult<()> {
|
||||
#[cfg(target_os = "linux")]
|
||||
#[allow(clippy::disallowed_methods)]
|
||||
window
|
||||
.with_webview(move |platform| crate::linux_webkit::set_smooth_scrolling(&platform, enabled))
|
||||
.map_err(|e| IdeError::internal(e.to_string()))?;
|
||||
|
||||
@@ -139,10 +139,10 @@ pub fn coalescing_sink(sink: SharedSink, runtime: tokio::runtime::Handle) -> Sha
|
||||
})
|
||||
}
|
||||
|
||||
/// A debug session stopped on a breakpoint: bounce/flash the taskbar icon
|
||||
/// (IDEA) unless the user is already looking at an OpenIDEA window. The focus
|
||||
/// check and the request both touch the windowing system, so they run on the
|
||||
/// main thread; `emit` itself can come from any debug worker thread.
|
||||
/// A debug session stopped on a breakpoint, or a background project asks for confirmation:
|
||||
/// bounce/flash the taskbar icon (IDEA) unless the user is already looking at an OpenIDEA window.
|
||||
/// The focus check and the request both touch the windowing system, so they run on the main
|
||||
/// thread; `emit` itself can come from any worker thread.
|
||||
fn flash_taskbar_unless_focused(app: &AppHandle, owner: Option<&str>) {
|
||||
let handle = app.clone();
|
||||
let owner = owner.map(str::to_owned);
|
||||
@@ -189,19 +189,25 @@ impl EventSink for TauriSink {
|
||||
) {
|
||||
flash_taskbar_unless_focused(&self.app, self.window.as_deref());
|
||||
}
|
||||
// A confirmation waits for the user: bring the window up. Other requests (an agent's
|
||||
// run, opening a file) need nothing from the user and leave the focus where it is.
|
||||
if matches!(&event, IdeEvent::McpRequest { request: ide_core::event::McpUiRequest::Confirm { .. }, .. })
|
||||
// A confirmation waits for the user: bring the window up. One for a background project
|
||||
// shows in a window the user may be typing in, so it only asks for attention. Other
|
||||
// requests (an agent's run, opening a file) need nothing from the user and leave the
|
||||
// focus where it is.
|
||||
if let IdeEvent::McpRequest { request: ide_core::event::McpUiRequest::Confirm { background, .. }, .. } = &event
|
||||
&& let Some(label) = self.window.clone()
|
||||
{
|
||||
let app = self.app.clone();
|
||||
let _ = self.app.run_on_main_thread(move || {
|
||||
if let Some(window) = app.get_webview_window(&label) {
|
||||
let _ = window.unminimize();
|
||||
let _ = window.show();
|
||||
let _ = window.set_focus();
|
||||
}
|
||||
});
|
||||
if *background {
|
||||
flash_taskbar_unless_focused(&self.app, Some(&label));
|
||||
} else {
|
||||
let app = self.app.clone();
|
||||
let _ = self.app.run_on_main_thread(move || {
|
||||
if let Some(window) = app.get_webview_window(&label) {
|
||||
let _ = window.unminimize();
|
||||
let _ = window.show();
|
||||
let _ = window.set_focus();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
let result = match &self.window {
|
||||
Some(label) => {
|
||||
|
||||
@@ -7,6 +7,8 @@
|
||||
#![recursion_limit = "512"]
|
||||
|
||||
mod application_focus;
|
||||
#[cfg(target_os = "macos")]
|
||||
mod background_tab;
|
||||
mod cli;
|
||||
mod commands;
|
||||
#[cfg(debug_assertions)]
|
||||
@@ -308,6 +310,7 @@ pub fn run() {
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
page_swipe::forget(window.label());
|
||||
macos::forget_background(window.label());
|
||||
titlebar::forget(window);
|
||||
}
|
||||
if windows::auxiliary_parent(window.label()).is_none() {
|
||||
|
||||
@@ -91,6 +91,7 @@ pub fn smooth_scrolling_plugin() -> tauri::plugin::TauriPlugin<tauri::Wry> {
|
||||
let enabled = webview
|
||||
.try_state::<crate::state::AppState>()
|
||||
.is_some_and(|s| s.global_settings.effective().appearance.smooth_scrolling);
|
||||
#[allow(clippy::disallowed_methods)]
|
||||
let _ = webview.with_webview(move |platform| set_smooth_scrolling(&platform, enabled));
|
||||
})
|
||||
.build()
|
||||
|
||||
@@ -1,15 +1,101 @@
|
||||
//! macOS project tabs: native window tab groups behind the page's own tab bar.
|
||||
use crate::background_tab::{self, Return};
|
||||
use crate::windows::{Launch, WindowsState};
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use ide_workspace::window_groups::{TabbingPreference, should_group_new_project};
|
||||
use objc2::{
|
||||
MainThreadMarker,
|
||||
rc::Retained,
|
||||
runtime::{AnyClass, AnyObject, Imp, Sel},
|
||||
runtime::{AnyClass, AnyObject, Imp, ProtocolObject, Sel},
|
||||
};
|
||||
use objc2_app_kit::{
|
||||
NSApplication, NSView, NSWindow, NSWindowOcclusionState, NSWindowOrderingMode, NSWindowStyleMask,
|
||||
NSWindowUserTabbingPreference,
|
||||
};
|
||||
use objc2_foundation::{NSNotificationCenter, NSObjectProtocol, NSOperationQueue};
|
||||
use std::{
|
||||
cell::{Cell, RefCell},
|
||||
collections::HashMap,
|
||||
ffi::c_void,
|
||||
time::Duration,
|
||||
};
|
||||
use objc2_app_kit::{NSWindow, NSWindowUserTabbingPreference};
|
||||
use tauri::{AppHandle, Manager, WebviewWindow};
|
||||
|
||||
/// WebKit frees a page's graphics 10 s and its caches 2 min after the page leaves its window.
|
||||
const DETACH_BACKGROUND_TAB_AFTER: Duration = Duration::from_secs(30);
|
||||
|
||||
enum Background<V> {
|
||||
Pending(u64),
|
||||
Detached(V),
|
||||
}
|
||||
|
||||
struct BackgroundTabs<V> {
|
||||
next: u64,
|
||||
tabs: HashMap<String, Background<V>>,
|
||||
}
|
||||
|
||||
impl<V> Default for BackgroundTabs<V> {
|
||||
fn default() -> Self {
|
||||
Self { next: 0, tabs: HashMap::new() }
|
||||
}
|
||||
}
|
||||
|
||||
impl<V> BackgroundTabs<V> {
|
||||
/// None when the label already has an entry: a repeated select must not restart the clock.
|
||||
fn schedule(&mut self, label: &str) -> Option<u64> {
|
||||
if self.tabs.contains_key(label) {
|
||||
return None;
|
||||
}
|
||||
self.next += 1;
|
||||
self.tabs.insert(label.to_string(), Background::Pending(self.next));
|
||||
Some(self.next)
|
||||
}
|
||||
|
||||
fn due(&self, label: &str, generation: u64) -> bool {
|
||||
matches!(self.tabs.get(label), Some(Background::Pending(g)) if *g == generation)
|
||||
}
|
||||
|
||||
fn detached(&mut self, label: &str, view: V) {
|
||||
self.tabs.insert(label.to_string(), Background::Detached(view));
|
||||
}
|
||||
|
||||
fn cancel(&mut self, label: &str) {
|
||||
self.tabs.remove(label);
|
||||
}
|
||||
|
||||
fn view(&self, label: &str) -> Option<&V> {
|
||||
match self.tabs.get(label) {
|
||||
Some(Background::Detached(view)) => Some(view),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Also cancels a pending detach.
|
||||
fn attach(&mut self, label: &str) -> Option<V> {
|
||||
match self.tabs.remove(label) {
|
||||
Some(Background::Detached(view)) => Some(view),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct DetachedView {
|
||||
view: Retained<NSView>,
|
||||
observers: Vec<Retained<ProtocolObject<dyn NSObjectProtocol>>>,
|
||||
}
|
||||
|
||||
impl Drop for DetachedView {
|
||||
fn drop(&mut self) {
|
||||
for observer in &self.observers {
|
||||
unsafe { NSNotificationCenter::defaultCenter().removeObserver(observer.as_ref()) };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
static BACKGROUND: RefCell<BackgroundTabs<DetachedView>> = RefCell::new(BackgroundTabs::default());
|
||||
}
|
||||
|
||||
fn tabbing_preference(app: &AppHandle) -> IdeResult<TabbingPreference> {
|
||||
fn read(mtm: MainThreadMarker) -> TabbingPreference {
|
||||
match NSWindow::userTabbingPreference(mtm) {
|
||||
@@ -83,6 +169,101 @@ fn same_group(a: &NSWindow, b: &NSWindow) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
fn schedule_detach(window: &WebviewWindow) {
|
||||
// The debug-only MCP bridge calls `with_webview` directly, which panics on a detached view.
|
||||
if cfg!(debug_assertions) {
|
||||
return;
|
||||
}
|
||||
let Some(generation) = BACKGROUND.with_borrow_mut(|tabs| tabs.schedule(window.label())) else { return };
|
||||
let target = window.clone();
|
||||
tauri::async_runtime::spawn(async move {
|
||||
tokio::time::sleep(DETACH_BACKGROUND_TAB_AFTER).await;
|
||||
let window = target.clone();
|
||||
let _ = window.run_on_main_thread(move || detach_if_background(&target, generation));
|
||||
});
|
||||
}
|
||||
|
||||
fn detach_if_background(window: &WebviewWindow, generation: u64) {
|
||||
if !BACKGROUND.with_borrow(|tabs| tabs.due(window.label(), generation)) {
|
||||
return;
|
||||
}
|
||||
let Some(native) = native(window) else { return };
|
||||
// A visible window is never a background tab.
|
||||
if native.occlusionState().contains(NSWindowOcclusionState::Visible) {
|
||||
BACKGROUND.with_borrow_mut(|tabs| tabs.cancel(window.label()));
|
||||
return;
|
||||
}
|
||||
// An inactive app's full-screen group can be mid-transition, where AppKit has crashed (#6937): wait for activation.
|
||||
let inactive = MainThreadMarker::new().is_some_and(|mtm| !NSApplication::sharedApplication(mtm).isActive());
|
||||
if inactive && native.styleMask().contains(NSWindowStyleMask::FullScreen) {
|
||||
BACKGROUND.with_borrow_mut(|tabs| tabs.cancel(window.label()));
|
||||
schedule_detach(window);
|
||||
return;
|
||||
}
|
||||
let view = (|| {
|
||||
let group = native.tabGroup()?;
|
||||
let selected = group.selectedWindow()?;
|
||||
let background = group.windows().count() > 1
|
||||
&& !std::ptr::eq(Retained::as_ptr(&selected), native)
|
||||
&& native.attachedSheet().is_none();
|
||||
background.then(|| background_tab::web_view(native)).flatten()
|
||||
})();
|
||||
let Some(view) = view else {
|
||||
BACKGROUND.with_borrow_mut(|tabs| tabs.cancel(window.label()));
|
||||
return;
|
||||
};
|
||||
view.removeFromSuperview();
|
||||
let target = window.clone();
|
||||
let observers = background_tab::on_return(native, move |why| {
|
||||
attach_for(&target, if why == Return::Key { "key" } else { "visible" }, true)
|
||||
});
|
||||
BACKGROUND.with_borrow_mut(|tabs| tabs.detached(window.label(), DetachedView { view, observers }));
|
||||
}
|
||||
|
||||
/// Puts a detached web view back and cancels a pending detach.
|
||||
pub fn attach(window: &WebviewWindow) {
|
||||
attach_for(window, "select", false);
|
||||
}
|
||||
|
||||
fn attach_for(window: &WebviewWindow, reason: &str, from_observer: bool) {
|
||||
let Some(detached) = BACKGROUND.with_borrow_mut(|tabs| tabs.attach(window.label())) else {
|
||||
return;
|
||||
};
|
||||
if let Some(native) = native(window) {
|
||||
background_tab::put_back(native, &detached.view);
|
||||
tracing::debug!(label = window.label(), reason, "re-attached background tab web view");
|
||||
}
|
||||
if from_observer {
|
||||
// Dropping removes the observer whose block is running; wait until the post returns.
|
||||
let detached = Cell::new(Some(detached));
|
||||
let block = block2::RcBlock::new(move || drop(detached.take()));
|
||||
unsafe { NSOperationQueue::mainQueue().addOperationWithBlock(&block) };
|
||||
}
|
||||
}
|
||||
|
||||
/// Calls `f` on the main thread with the window's `WKWebView`, attached or not.
|
||||
/// tauri's webview size/position APIs (`core:webview:default` grants `webview_size`/`webview_position`) unwrap
|
||||
/// `superview()` in wry and are not safe while a tab is detached.
|
||||
pub fn with_web_view(window: &WebviewWindow, f: impl FnOnce(*mut c_void) + Send + 'static) -> tauri::Result<()> {
|
||||
let target = window.clone();
|
||||
window.run_on_main_thread(move || {
|
||||
// On the main thread tauri handles with_webview synchronously, so the tab cannot be detached between
|
||||
// the check and the call; wry's with_webview panics on a windowless view.
|
||||
let detached = BACKGROUND.with_borrow(|tabs| tabs.view(target.label()).map(|d| Retained::as_ptr(&d.view)));
|
||||
match detached {
|
||||
Some(view) => f(view as *mut c_void),
|
||||
None => {
|
||||
#[allow(clippy::disallowed_methods)]
|
||||
let _ = target.with_webview(move |w| f(w.inner()));
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
pub fn forget_background(label: &str) {
|
||||
BACKGROUND.with_borrow_mut(|tabs| tabs.cancel(label));
|
||||
}
|
||||
|
||||
/// Adds `members` to the existing anchor's native tab group and shows `selected`.
|
||||
pub fn sync_tab_group(
|
||||
members: Vec<WebviewWindow>,
|
||||
@@ -99,14 +280,18 @@ pub fn sync_tab_group(
|
||||
if let Some(window) = native(member)
|
||||
&& !same_group(anchor_window, window)
|
||||
{
|
||||
anchor_window.addTabbedWindow_ordered(window, objc2_app_kit::NSWindowOrderingMode::Above);
|
||||
anchor_window.addTabbedWindow_ordered(window, NSWindowOrderingMode::Above);
|
||||
}
|
||||
}
|
||||
attach(&target);
|
||||
if let Some(group) = shown.tabGroup() {
|
||||
group.setSelectedWindow(Some(shown));
|
||||
}
|
||||
shown.makeKeyAndOrderFront(None);
|
||||
for member in &members {
|
||||
if member.label() != target.label() {
|
||||
schedule_detach(member);
|
||||
}
|
||||
if let Some(window) = native(member) {
|
||||
hide_tab_bar(window);
|
||||
}
|
||||
@@ -129,6 +314,7 @@ pub fn move_tab_to_new_window(window: &WebviewWindow) -> tauri::Result<()> {
|
||||
let target = window.clone();
|
||||
on_main(window, move || {
|
||||
let Some(native) = native(&target) else { return };
|
||||
attach(&target);
|
||||
if native.tabbedWindows().is_some_and(|tabs| tabs.count() > 1) {
|
||||
native.moveTabToNewWindow(None);
|
||||
}
|
||||
@@ -226,3 +412,56 @@ pub fn native_modal_open() -> bool {
|
||||
let application = objc2_app_kit::NSApplication::sharedApplication(mtm);
|
||||
application.modalWindow().is_some() || application.windows().iter().any(|window| window.attachedSheet().is_some())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::BackgroundTabs;
|
||||
|
||||
#[test]
|
||||
fn repeated_schedule_keeps_the_first_generation() {
|
||||
let mut tabs = BackgroundTabs::<u32>::default();
|
||||
let first = tabs.schedule("a").unwrap();
|
||||
assert_eq!(tabs.schedule("a"), None);
|
||||
assert!(tabs.due("a", first));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn attach_cancels_a_pending_detach() {
|
||||
let mut tabs = BackgroundTabs::<u32>::default();
|
||||
let generation = tabs.schedule("a").unwrap();
|
||||
assert_eq!(tabs.attach("a"), None);
|
||||
assert!(!tabs.due("a", generation));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stale_generation_is_not_due_after_reschedule() {
|
||||
let mut tabs = BackgroundTabs::<u32>::default();
|
||||
let stale = tabs.schedule("a").unwrap();
|
||||
tabs.attach("a");
|
||||
let fresh = tabs.schedule("a").unwrap();
|
||||
assert_ne!(stale, fresh);
|
||||
assert!(!tabs.due("a", stale));
|
||||
assert!(tabs.due("a", fresh));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn view_is_only_there_while_detached() {
|
||||
let mut tabs = BackgroundTabs::<&'static str>::default();
|
||||
tabs.schedule("a").unwrap();
|
||||
assert_eq!(tabs.view("a"), None);
|
||||
tabs.detached("a", "view");
|
||||
assert_eq!(tabs.view("a"), Some(&"view"));
|
||||
tabs.attach("a");
|
||||
assert_eq!(tabs.view("a"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn attach_returns_the_detached_view_once() {
|
||||
let mut tabs = BackgroundTabs::<&'static str>::default();
|
||||
let generation = tabs.schedule("a").unwrap();
|
||||
tabs.detached("a", "view");
|
||||
assert!(!tabs.due("a", generation));
|
||||
assert_eq!(tabs.attach("a"), Some("view"));
|
||||
assert_eq!(tabs.attach("a"), None);
|
||||
}
|
||||
}
|
||||
@@ -33,9 +33,10 @@ fn stroke(window: &WebviewWindow, right: bool) {
|
||||
|
||||
pub fn install(window: &WebviewWindow) {
|
||||
let target = window.clone();
|
||||
let _ = window.with_webview(move |webview| {
|
||||
let view = unsafe { Retained::retain(webview.inner().cast::<NSView>()).unwrap() };
|
||||
let native = webview.ns_window() as usize;
|
||||
let _ = crate::macos::with_web_view(window, move |webview| {
|
||||
let view = unsafe { Retained::retain(webview.cast::<NSView>()).unwrap() };
|
||||
let Ok(native) = target.ns_window() else { return };
|
||||
let native = native as usize;
|
||||
let window = target.clone();
|
||||
let block = block2::RcBlock::new(move |event: NonNull<NSEvent>| {
|
||||
let event = unsafe { event.as_ref() };
|
||||
|
||||
@@ -458,10 +458,12 @@ fn track(window: &NSWindow, app: &tauri::AppHandle) -> Tracked {
|
||||
pub fn set_height(window: &tauri::WebviewWindow, height: f64) -> tauri::Result<()> {
|
||||
let label = window.label().to_owned();
|
||||
let app = window.app_handle().clone();
|
||||
// with_webview runs on the AppKit thread.
|
||||
window.with_webview(move |webview| unsafe {
|
||||
let target = window.clone();
|
||||
// The window's own handle works while a background tab's web view is detached.
|
||||
window.run_on_main_thread(move || unsafe {
|
||||
let Some(mtm) = MainThreadMarker::new() else { return };
|
||||
let native = &*webview.ns_window().cast::<NSWindow>();
|
||||
let Ok(native) = target.ns_window() else { return };
|
||||
let native = &*native.cast::<NSWindow>();
|
||||
let (state, buttons, strip) = WINDOWS.with_borrow_mut(|windows| {
|
||||
let tracked = windows.entry(label).or_insert_with(|| track(native, &app));
|
||||
tracked.height.set(height);
|
||||
|
||||
@@ -2764,8 +2764,8 @@ fn disable_macos_text_input_selection_updates(preferences: &objc2_web_kit::WKPre
|
||||
/// suppresses the affordance even if `NSTextInputContext` queries the view directly.
|
||||
#[cfg(target_os = "macos")]
|
||||
fn suppress_window_writing_tools_affordance(window: &WebviewWindow) {
|
||||
let _ = window.with_webview(|webview| unsafe {
|
||||
let ptr = webview.inner().cast::<objc2::runtime::AnyObject>();
|
||||
let _ = crate::macos::with_web_view(window, |webview| unsafe {
|
||||
let ptr = webview.cast::<objc2::runtime::AnyObject>();
|
||||
if !ptr.is_null() {
|
||||
let cls = (*ptr).class();
|
||||
suppress_webview_class_writing_tools_affordance(cls);
|
||||
|
||||
@@ -11,6 +11,7 @@ pub fn init() -> plugin::TauriPlugin<Wry> {
|
||||
plugin::Builder::new("webview-keys").on_webview_ready(disable_browser_keys).build()
|
||||
}
|
||||
|
||||
#[allow(clippy::disallowed_methods)]
|
||||
fn disable_browser_keys(webview: Webview) {
|
||||
let label = webview.label().to_owned();
|
||||
if let Err(error) = webview.with_webview(move |platform| {
|
||||
|
||||
@@ -50,6 +50,7 @@ pub fn init() -> plugin::TauriPlugin<Wry> {
|
||||
.build()
|
||||
}
|
||||
|
||||
#[allow(clippy::disallowed_methods)]
|
||||
fn install(webview: Webview) {
|
||||
let app = webview.app_handle().clone();
|
||||
let label = webview.label().to_owned();
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
fn main() {}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
#[path = "../src/background_tab.rs"]
|
||||
mod background_tab;
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
#[link(name = "WebKit", kind = "framework")]
|
||||
unsafe extern "C" {}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
fn main() {
|
||||
// nextest runs a harness-less binary as `--list --format terse [--ignored]`, then `<name> --exact --nocapture`.
|
||||
let args: Vec<String> = std::env::args().collect();
|
||||
if args.iter().any(|a| a == "--list") {
|
||||
if !args.iter().any(|a| a == "--ignored") {
|
||||
println!("background_tab_appkit: test");
|
||||
}
|
||||
return;
|
||||
}
|
||||
use background_tab::Return;
|
||||
use objc2::{MainThreadMarker, msg_send, rc::Retained, runtime::AnyClass};
|
||||
use objc2_app_kit::{
|
||||
NSApplication, NSBackingStoreType, NSView, NSWindow, NSWindowDidBecomeKeyNotification, NSWindowStyleMask,
|
||||
};
|
||||
use objc2_foundation::{NSNotificationCenter, NSPoint, NSRect, NSSize};
|
||||
use std::{cell::Cell, rc::Rc};
|
||||
|
||||
let mtm = MainThreadMarker::new().expect("main thread");
|
||||
let _app = NSApplication::sharedApplication(mtm);
|
||||
let rect = NSRect::new(NSPoint::new(0.0, 0.0), NSSize::new(400.0, 300.0));
|
||||
let window = unsafe {
|
||||
NSWindow::initWithContentRect_styleMask_backing_defer(
|
||||
mtm.alloc(),
|
||||
rect,
|
||||
NSWindowStyleMask::Titled,
|
||||
NSBackingStoreType::Buffered,
|
||||
false,
|
||||
)
|
||||
};
|
||||
let class = AnyClass::get(c"WKWebView").expect("WebKit is linked");
|
||||
let web: Retained<NSView> = unsafe { msg_send![msg_send![class, alloc], initWithFrame: rect] };
|
||||
window.contentView().unwrap().addSubview(&web);
|
||||
|
||||
let view = background_tab::web_view(&window).expect("web view in content view");
|
||||
view.removeFromSuperview();
|
||||
assert!(view.window().is_none());
|
||||
// Not asked for its process ids: on a web view that never loaded a page, WebKit asserts in
|
||||
// `_networkProcessIdentifier` (macOS 15), which a real tab never is.
|
||||
|
||||
let reason = Rc::new(Cell::new(None));
|
||||
let observers = {
|
||||
let (reason, window, view) = (reason.clone(), window.clone(), view.clone());
|
||||
background_tab::on_return(&window.clone(), move |why| {
|
||||
background_tab::put_back(&window, &view);
|
||||
reason.set(Some(why));
|
||||
})
|
||||
};
|
||||
unsafe {
|
||||
NSNotificationCenter::defaultCenter()
|
||||
.postNotificationName_object(NSWindowDidBecomeKeyNotification, Some(&window));
|
||||
}
|
||||
assert_eq!(reason.get(), Some(Return::Key));
|
||||
assert!(view.window().is_some_and(|w| Retained::as_ptr(&w) == Retained::as_ptr(&window)));
|
||||
for observer in &observers {
|
||||
unsafe { NSNotificationCenter::defaultCenter().removeObserver(observer.as_ref()) };
|
||||
}
|
||||
println!("ok: re-attached synchronously inside the key notification");
|
||||
}
|
||||
@@ -8162,7 +8162,7 @@ export type ExternalFormatterSettings = {
|
||||
|
||||
/** A session on this machine that no task holds yet. */
|
||||
export type ExternalSession = {
|
||||
/** The [`crate::AgentProvider`] id that owns it (`claude`, `codex`). */
|
||||
/** The [`crate::AgentProvider`] id that owns it (`claude`, `codex`, `copilot`). */
|
||||
provider: string,
|
||||
/** The id resuming it names (`--resume`, `thread/resume`). */
|
||||
sessionId: string,
|
||||
@@ -11614,7 +11614,12 @@ export type McpTransport = "stdio" | "http" | "sse";
|
||||
* the window's own Debug action builds the launch. `Breakpoints` replaces the window's
|
||||
* breakpoints, which the editor owns, persists and mirrors to the backend.
|
||||
*/
|
||||
export type McpUiRequest = { type: "confirm"; client: string; tool: string; subject: string; project: string; detail: string | null } | { type: "openFile"; path: IpcPath; line: number | null; column: number | null } | { type: "agentRun"; name: string; command: string; cwd: IpcPath; env: { [key in string]: string } } | { type: "runConfiguration"; config: unknown } |
|
||||
export type McpUiRequest = { type: "confirm"; client: string; tool: string; subject: string; project: string; detail: string | null;
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
background?: boolean } | { type: "openFile"; path: IpcPath; line: number | null; column: number | null } | { type: "agentRun"; name: string; command: string; cwd: IpcPath; env: { [key in string]: string } } | { type: "runConfiguration"; config: unknown } |
|
||||
/** Start a run configuration in Debug mode as the IDE's Debug action would. */
|
||||
{ type: "debugConfiguration"; config: unknown } |
|
||||
/**
|
||||
|
||||
@@ -1,154 +0,0 @@
|
||||
/**
|
||||
* FreeMarker editor mode: HTML outside the template syntax, FreeMarker inside
|
||||
* directives (`<#if …>`, `<@macro …/>`), interpolations (`${…}`) and comments.
|
||||
* The first directive fixes the tag syntax, angle (`<#if>`) or square (`[#if]`),
|
||||
* as FreeMarker itself does; `[=…]` interpolations count only in square syntax.
|
||||
*/
|
||||
import { LanguageSupport, StreamLanguage, StringStream, type StreamParser } from "@codemirror/language";
|
||||
import { tags } from "@lezer/highlight";
|
||||
|
||||
type State<H> = {
|
||||
html: H;
|
||||
mode: "comment" | "directive" | "interpolation" | null;
|
||||
/** Tag syntax: `null` until the first directive, then square or not. */
|
||||
square: boolean | null;
|
||||
/** What ends the current comment, directive or interpolation. */
|
||||
close: string;
|
||||
/** Brackets open inside the expression; the closer counts only at 0. */
|
||||
depth: number;
|
||||
/** The directive's name comes next. */
|
||||
name: "#" | "@" | null;
|
||||
};
|
||||
|
||||
// `(?=…)` lookahead only: WebKit lacks lookbehind.
|
||||
const OPENER = /<#--|\[#--|<\/?[#@](?=[A-Za-z_])|\[\/?[#@](?=[A-Za-z_])|\$\{|\[=/g;
|
||||
const KEYWORDS = new Set(["as", "in", "using", "gt", "gte", "lt", "lte"]);
|
||||
|
||||
function nextOpener(line: string, from: number, square: boolean | null): RegExpExecArray | null {
|
||||
OPENER.lastIndex = from;
|
||||
for (let m = OPENER.exec(line); m; m = OPENER.exec(line)) {
|
||||
const text = m[0];
|
||||
if (text === "${") return m;
|
||||
if (text === "[=" ? square === true : square === null || square === (text[0] === "[")) return m;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function tokenComment<H>(stream: StringStream, state: State<H>): string {
|
||||
const end = stream.string.indexOf(state.close, stream.pos);
|
||||
stream.pos = end < 0 ? stream.string.length : end + state.close.length;
|
||||
if (end >= 0) state.mode = null;
|
||||
return "comment";
|
||||
}
|
||||
|
||||
function tokenExpression<H>(stream: StringStream, state: State<H>): string | null {
|
||||
if (stream.eatSpace()) return null;
|
||||
if (state.depth === 0 && stream.match(state.close)) {
|
||||
state.mode = null;
|
||||
return "ftlDelimiter";
|
||||
}
|
||||
if (state.depth === 0 && state.mode === "directive" && stream.match("/" + state.close)) {
|
||||
state.mode = null;
|
||||
return "ftlDelimiter";
|
||||
}
|
||||
if (stream.match(/^r?"(?:[^"\\]|\\.)*"?/) || stream.match(/^r?'(?:[^'\\]|\\.)*'?/)) return "string";
|
||||
if (stream.match(/^\d+(?:\.\d+)?/)) return "number";
|
||||
if (stream.match("??")) return "operator";
|
||||
if (stream.match(/^\?[A-Za-z_]\w*/)) return "ftlBuiltin";
|
||||
if (stream.match(/^\.[A-Za-z_]\w*/)) return "propertyName";
|
||||
if (stream.match(/^[A-Za-z_$][\w$]*/)) {
|
||||
const word = stream.current();
|
||||
if (word === "true" || word === "false") return "bool";
|
||||
return KEYWORDS.has(word) ? "keyword" : "variableName";
|
||||
}
|
||||
const ch = stream.next()!;
|
||||
if ("([{".includes(ch)) {
|
||||
state.depth++;
|
||||
return "bracket";
|
||||
}
|
||||
if (")]}".includes(ch)) {
|
||||
state.depth = Math.max(0, state.depth - 1);
|
||||
return "bracket";
|
||||
}
|
||||
if (ch === "." && stream.match(/^\.[<!*]?/)) return "operator";
|
||||
return "+-*/%!=<>&|:,;.".includes(ch) ? "operator" : null;
|
||||
}
|
||||
|
||||
function freemarkerParser<H>(html: StreamParser<H>): StreamParser<State<H>> {
|
||||
const copy = (state: H): H =>
|
||||
html.copyState
|
||||
? html.copyState(state)
|
||||
: (Object.fromEntries(
|
||||
Object.entries(state as object).map(([k, v]) => [k, Array.isArray(v) ? v.slice() : v]),
|
||||
) as H);
|
||||
|
||||
/** Runs the HTML mode on `stream` cut at `end`, then advances `stream` to where it stopped. */
|
||||
const tokenHtml = (stream: StringStream, end: number, state: H): string | null => {
|
||||
const sub = new StringStream(stream.string.slice(0, end), 4, stream.indentUnit);
|
||||
sub.pos = stream.pos;
|
||||
sub.start = stream.start;
|
||||
const style = html.token(sub, state);
|
||||
stream.pos = Math.max(sub.pos, stream.pos + (sub.pos === stream.pos ? 1 : 0));
|
||||
return style;
|
||||
};
|
||||
|
||||
return {
|
||||
name: "freemarker",
|
||||
languageData: { ...html.languageData, commentTokens: { block: { open: "<#--", close: "-->" } } },
|
||||
tokenTable: {
|
||||
...html.tokenTable,
|
||||
ftlDelimiter: tags.special(tags.brace),
|
||||
ftlBuiltin: tags.standard(tags.function(tags.variableName)),
|
||||
ftlMacro: tags.function(tags.variableName),
|
||||
},
|
||||
startState: (indentUnit) => ({
|
||||
html: html.startState!(indentUnit),
|
||||
mode: null,
|
||||
square: null,
|
||||
close: "",
|
||||
depth: 0,
|
||||
name: null,
|
||||
}),
|
||||
copyState: (s) => ({ ...s, html: copy(s.html) }),
|
||||
blankLine: (s, unit) => (s.mode ? undefined : html.blankLine?.(s.html, unit)),
|
||||
indent: (s, text, cx) => (s.mode ? null : (html.indent?.(s.html, text, cx) ?? null)),
|
||||
token(stream, state) {
|
||||
if (state.mode === "comment") return tokenComment(stream, state);
|
||||
if (state.name) {
|
||||
const sigil = state.name;
|
||||
state.name = null;
|
||||
if (stream.match(/^[A-Za-z_][\w.:-]*/)) return sigil === "#" ? "keyword" : "ftlMacro";
|
||||
}
|
||||
if (state.mode) return tokenExpression(stream, state);
|
||||
|
||||
const open = nextOpener(stream.string, stream.pos, state.square);
|
||||
if (open?.index !== stream.pos) {
|
||||
return tokenHtml(stream, open ? open.index : stream.string.length, state.html);
|
||||
}
|
||||
const text = open[0];
|
||||
stream.pos += text.length;
|
||||
const square = text[0] === "[";
|
||||
state.depth = 0;
|
||||
if (text.endsWith("--")) {
|
||||
state.mode = "comment";
|
||||
state.close = square ? "--]" : "-->";
|
||||
return tokenComment(stream, state);
|
||||
}
|
||||
if (text === "${" || text === "[=") {
|
||||
state.mode = "interpolation";
|
||||
state.close = text === "${" ? "}" : "]";
|
||||
return "ftlDelimiter";
|
||||
}
|
||||
state.square ??= square;
|
||||
state.mode = "directive";
|
||||
state.close = square ? "]" : ">";
|
||||
state.name = text.endsWith("@") ? "@" : "#";
|
||||
return "ftlDelimiter";
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export async function freemarker(): Promise<LanguageSupport> {
|
||||
const { html } = await import("@codemirror/legacy-modes/mode/xml");
|
||||
return new LanguageSupport(StreamLanguage.define(freemarkerParser(html)));
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
// FreeMarker templates: the template layer. Directives (`<#if …>`), user-defined
|
||||
// directive calls (`<@badge …/>`), interpolations (`${…}`) and comments are parsed
|
||||
// here; the text between them is HTML, mounted by `./index.ts`. The first directive
|
||||
// fixes the tag syntax, angle (`<#if>`) or square (`[#if]`), as FreeMarker does.
|
||||
// Block directives nest (`<#if>…<#elseif>…<#else>…</#if>`); others stand alone.
|
||||
// Regenerate with `pnpm gen:freemarker-grammar`.
|
||||
|
||||
@context blocks from "./tokens"
|
||||
|
||||
@top Template { node* }
|
||||
|
||||
node {
|
||||
Text |
|
||||
Comment |
|
||||
Interpolation |
|
||||
Tag |
|
||||
Element |
|
||||
RawElement |
|
||||
StrayEndTag
|
||||
}
|
||||
|
||||
// A block directive or user-defined directive call, its middle tags
|
||||
// (`elseif`, `else`, `recover`, `case`…) and its end tag.
|
||||
Element { OpenTag node* (MidTag node*)* EndTag }
|
||||
|
||||
// `<#noparse>…</#noparse>`, `<#comment>…</#comment>`: the content is not parsed.
|
||||
RawElement { RawTag RawBody? EndTag }
|
||||
|
||||
@skip { space } {
|
||||
OpenTag { OpenTagStart tagName argument* TagEnd }
|
||||
RawTag { RawTagStart tagName argument* TagEnd }
|
||||
MidTag { MidTagStart tagName argument* (TagEnd | SelfCloseEnd) }
|
||||
EndTag { EndTagStart tagName? TagEnd }
|
||||
// An end tag without its start tag, or of a directive that may or may not be a block (`</#sep>`).
|
||||
StrayEndTag { StrayEndTagStart tagName? TagEnd }
|
||||
Tag { TagStart tagName argument* (TagEnd | SelfCloseEnd) }
|
||||
|
||||
Interpolation { InterpolationStart argument* InterpolationEnd }
|
||||
|
||||
argument {
|
||||
VariableName |
|
||||
Member { "." PropertyName } |
|
||||
BuiltIn { "?" BuiltInName } |
|
||||
String |
|
||||
Number |
|
||||
Operator |
|
||||
CompareOp |
|
||||
kw<"as"> | kw<"in"> | kw<"using"> |
|
||||
kw<"gt"> | kw<"gte"> | kw<"lt"> | kw<"lte"> |
|
||||
@specialize[@name=BooleanLiteral]<identifier, "true" | "false"> |
|
||||
ParenGroup { "(" argument* ")" } |
|
||||
BracketGroup { "[" argument* "]" } |
|
||||
HashGroup { "{" argument* "}" }
|
||||
}
|
||||
}
|
||||
|
||||
tagName { DirectiveName | MacroName }
|
||||
|
||||
VariableName { identifier }
|
||||
|
||||
PropertyName { identifier }
|
||||
|
||||
BuiltInName { identifier }
|
||||
|
||||
kw<term> { @specialize[@name={term}]<identifier, term> }
|
||||
|
||||
// Tried in this order, before the tokens below.
|
||||
@external tokens comment from "./tokens" { Comment }
|
||||
@external tokens rawBody from "./tokens" { RawBody }
|
||||
@external tokens text from "./tokens" { Text }
|
||||
@external tokens tagStart from "./tokens" {
|
||||
OpenTagStart, RawTagStart, MidTagStart, EndTagStart, StrayEndTagStart, TagStart, InterpolationStart
|
||||
}
|
||||
@external tokens tagName from "./tokens" { DirectiveName, MacroName }
|
||||
@external tokens tagEnd from "./tokens" { TagEnd, SelfCloseEnd, InterpolationEnd }
|
||||
|
||||
@tokens {
|
||||
space { $[ \t\n\r]+ }
|
||||
|
||||
identifier { $[a-zA-Z_$\u{a1}-\u{10ffff}] $[a-zA-Z0-9_$\u{a1}-\u{10ffff}]* }
|
||||
|
||||
Number { @digit+ ("." @digit+)? }
|
||||
|
||||
String {
|
||||
"r"? '"' (!["\\] | "\\" _)* '"'? |
|
||||
"r"? "'" (!['\\] | "\\" _)* "'"?
|
||||
}
|
||||
|
||||
Operator {
|
||||
"+" | "-" | "*" | "/" | "%" | "!" | "=" | "+=" | "-=" | "*=" | "/=" | "%=" | "++" | "--" |
|
||||
"&&" | "||" | "&" | "|" | "??" | ".." | "..<" | "..!" | "..*" | "," | ":" | ";" | "->"
|
||||
}
|
||||
|
||||
CompareOp { "==" | "!=" | "<" | "<=" | ">=" | ">" }
|
||||
|
||||
@precedence { String, identifier }
|
||||
|
||||
"." "?" "(" ")" "[" "]" "{" "}"
|
||||
}
|
||||
|
||||
@detectDelim
|
||||
@@ -0,0 +1,202 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { resolve } from "node:path";
|
||||
import { EditorSelection, EditorState } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { CompletionContext, type CompletionResult, type CompletionSource } from "@codemirror/autocomplete";
|
||||
import { foldable, getIndentation, indentUnit, matchBrackets } from "@codemirror/language";
|
||||
import { buildParserFile } from "@lezer/generator";
|
||||
import { highlightTree, tagHighlighter, tags as t } from "@lezer/highlight";
|
||||
import { completedSyntaxState, completedSyntaxTree } from "@/test/syntax";
|
||||
import { commentBlock } from "../comments";
|
||||
import { freemarker, freemarkerLanguage } from "./index";
|
||||
|
||||
const highlighter = tagHighlighter([
|
||||
{ tag: t.special(t.brace), class: "delim" },
|
||||
{ tag: t.blockComment, class: "comment" },
|
||||
{ tag: t.keyword, class: "keyword" },
|
||||
{ tag: t.variableName, class: "var" },
|
||||
{ tag: t.propertyName, class: "prop" },
|
||||
{ tag: t.attributeName, class: "attr" },
|
||||
{ tag: t.string, class: "str" },
|
||||
{ tag: t.tagName, class: "tag" },
|
||||
]);
|
||||
|
||||
function state(doc: string, selection?: number): EditorState {
|
||||
return completedSyntaxState(
|
||||
EditorState.create({
|
||||
doc,
|
||||
selection: selection == undefined ? undefined : EditorSelection.cursor(selection),
|
||||
extensions: [freemarker(), indentUnit.of(" ")],
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
/** `text:class` of the styled tokens of `doc`, HTML and embedded languages included. */
|
||||
function tokens(doc: string): string[] {
|
||||
const out: string[] = [];
|
||||
highlightTree(completedSyntaxTree(state(doc)), highlighter, (from, to, cls) =>
|
||||
out.push(`${doc.slice(from, to)}:${cls}`),
|
||||
);
|
||||
return out;
|
||||
}
|
||||
|
||||
/** The error nodes of `doc`'s template layer, with the text they start. */
|
||||
function errors(doc: string): string[] {
|
||||
const out: string[] = [];
|
||||
freemarkerLanguage.parser.parse(doc).iterate({
|
||||
enter: (node) => void (node.type.isError && out.push(doc.slice(node.from, node.from + 12))),
|
||||
});
|
||||
return out;
|
||||
}
|
||||
|
||||
const outline = (doc: string) => freemarkerLanguage.parser.parse(doc).toString();
|
||||
|
||||
/** A view on `doc` with `|` marking the caret. */
|
||||
function view(marked: string): EditorView {
|
||||
const at = marked.indexOf("|");
|
||||
return new EditorView({ state: state(marked.slice(0, at) + marked.slice(at + 1), at) });
|
||||
}
|
||||
|
||||
/** Types `text` at the caret through the input handlers, like a keystroke. */
|
||||
function type(v: EditorView, text: string): string {
|
||||
const { from, to } = v.state.selection.main;
|
||||
const handled = v.state.facet(EditorView.inputHandler).some((h) => h(v, from, to, text, () => v.state.update({})));
|
||||
if (!handled)
|
||||
v.dispatch({ changes: { from, to, insert: text }, selection: EditorSelection.cursor(from + text.length) });
|
||||
const head = v.state.selection.main.head;
|
||||
return v.state.sliceDoc(0, head) + "|" + v.state.sliceDoc(head);
|
||||
}
|
||||
|
||||
/** The labels completion offers at the end of `doc`. */
|
||||
function complete(doc: string): string[] | undefined {
|
||||
const s = state(doc);
|
||||
const sources = s.languageDataAt<CompletionSource>("autocomplete", doc.length);
|
||||
const result = sources.map((src) => src(new CompletionContext(s, doc.length, true))).find(Boolean) as
|
||||
| CompletionResult
|
||||
| undefined;
|
||||
return result?.options.map((o) => o.label);
|
||||
}
|
||||
|
||||
describe("FreeMarker template layer", () => {
|
||||
it("nests block directives with their middle tags and leaves other directives alone", () => {
|
||||
expect(outline("<#if a>x<#elseif b>y<#else>z</#if><#assign n = 1>")).toBe(
|
||||
"Template(Element(OpenTag(OpenTagStart,DirectiveName,VariableName,TagEnd),Text," +
|
||||
"MidTag(MidTagStart,DirectiveName,VariableName,TagEnd),Text,MidTag(MidTagStart,DirectiveName,TagEnd),Text," +
|
||||
"EndTag(EndTagStart,DirectiveName,TagEnd)),Tag(TagStart,DirectiveName,VariableName,Operator,Number,TagEnd))",
|
||||
);
|
||||
// `assign` without `=` captures its content; a call with content is a block, one without isn't.
|
||||
expect(outline("<#assign x>v</#assign><@m/><@m>c</@m>")).toMatch(
|
||||
/^Template\(Element\(.*\),Tag\(.*SelfCloseEnd\),Element\(.*\)\)$/,
|
||||
);
|
||||
});
|
||||
|
||||
it("doesn't parse the content of noparse and comment", () => {
|
||||
expect(outline("<#noparse><#if>${x}</#noparse>")).toBe(
|
||||
"Template(RawElement(RawTag(RawTagStart,DirectiveName,TagEnd),RawBody,EndTag(EndTagStart,DirectiveName,TagEnd)))",
|
||||
);
|
||||
});
|
||||
|
||||
it("parses common templates without errors", () => {
|
||||
const doc = [
|
||||
'<#ftl output_format="HTML">',
|
||||
'<#import "/lib/ui.ftl" as ui>',
|
||||
"<#macro row item><tr><td>${item.name}</td></tr></#macro>",
|
||||
"<#function total xs><#local s = 0><#list xs as x><#local s += x.price></#list><#return s></#function>",
|
||||
"<#list orders?filter(o -> o.paid) as order><@row item=order/><#sep>, </#sep><#else>none</#list>",
|
||||
'<#switch kind><#case "a">A<#break><#default>B</#switch>',
|
||||
"<#attempt>${risky}<#recover>failed</#attempt>",
|
||||
"<#if (a > 1) && b?? && c?has_content>${a..<5}</#if>",
|
||||
'<@ui.card title="x" items=[1, 2] opts={"k": true}>c</@ui.card>',
|
||||
"<#list map as k, v>${k}=${v}</#list>",
|
||||
].join("\n");
|
||||
expect(errors(doc)).toEqual([]);
|
||||
});
|
||||
|
||||
it("highlights script and style content as JavaScript and CSS", () => {
|
||||
const out = tokens('<script>let a = "${x}";</script><style>p { color: red }</style>');
|
||||
expect(out).toContain("let:keyword");
|
||||
expect(out).toContain("x:var");
|
||||
expect(out).toContain("color:prop");
|
||||
});
|
||||
|
||||
it("nests markup across directives", () => {
|
||||
const out = tokens('<#if a><div class="x"></#if><#if a></div></#if>');
|
||||
expect(out.filter((t) => t == "div:tag")).toHaveLength(2);
|
||||
expect(out).toContain("class:attr");
|
||||
});
|
||||
|
||||
it("is generated from freemarker.grammar", () => {
|
||||
const dir = import.meta.dirname;
|
||||
const { parser, terms } = buildParserFile(readFileSync(resolve(dir, "freemarker.grammar"), "utf8"), {
|
||||
fileName: "src/editor/core/cm/freemarker/freemarker.grammar",
|
||||
moduleStyle: "es",
|
||||
typeScript: true,
|
||||
});
|
||||
const lf = (s: string) => s.replace(/\r\n/g, "\n");
|
||||
expect(lf(parser)).toBe(lf(readFileSync(resolve(dir, "parser.ts"), "utf8")));
|
||||
expect(lf(terms)).toBe(lf(readFileSync(resolve(dir, "parser.terms.ts"), "utf8")));
|
||||
});
|
||||
});
|
||||
|
||||
describe("FreeMarker template editing", () => {
|
||||
it("folds blocks", () => {
|
||||
const doc = "<#list xs as x>\n <p>${x}</p>\n</#list>\n";
|
||||
expect(foldable(state(doc), 0, doc.indexOf("\n"))).toEqual({ from: doc.indexOf(">") + 1, to: doc.indexOf("</#") });
|
||||
});
|
||||
|
||||
it("indents a block's content and puts its middle and end tags back", () => {
|
||||
const s = state("<#if a>\nx\n<#else>\ny\n</#if>");
|
||||
const lineStart = (n: number) => s.doc.line(n).from;
|
||||
expect(getIndentation(s, lineStart(2))).toBe(2);
|
||||
expect(getIndentation(s, lineStart(3))).toBe(0);
|
||||
expect(getIndentation(s, lineStart(4))).toBe(2);
|
||||
expect(getIndentation(s, lineStart(5))).toBe(0);
|
||||
});
|
||||
|
||||
it("matches a block directive with its end tag", () => {
|
||||
const doc = "<#list xs as x>${x}</#list>";
|
||||
const match = matchBrackets(state(doc), 3, 1);
|
||||
expect(match?.matched).toBe(true);
|
||||
expect(doc.slice(match!.end!.from, match!.end!.to)).toBe("list");
|
||||
});
|
||||
|
||||
it("adds the end tag of a block directive when its > is typed", () => {
|
||||
expect(type(view("<#if a|"), ">")).toBe("<#if a>|</#if>");
|
||||
expect(type(view("<@card title=t|"), ">")).toBe("<@card title=t>|</@card>");
|
||||
expect(type(view("[#ftl][#list xs as x|"), "]")).toBe("[#ftl][#list xs as x]|[/#list]");
|
||||
// It has one already.
|
||||
expect(type(view("<#if a|\n</#if>"), ">")).toBe("<#if a>|\n</#if>");
|
||||
// Not a block, or closed by `/>`.
|
||||
expect(type(view("<#include 'a.ftl'|"), ">")).toBe("<#include 'a.ftl'>|");
|
||||
expect(type(view("<@card /|"), ">")).toBe("<@card />|");
|
||||
// A capturing assign only without `=`.
|
||||
expect(type(view("<#assign x|"), ">")).toBe("<#assign x>|</#assign>");
|
||||
// Not in a script.
|
||||
expect(type(view("<script>if (a <#b|</script>"), ">")).toBe("<script>if (a <#b>|</script>");
|
||||
});
|
||||
|
||||
it("completes directives, the open blocks' end tags and built-ins", () => {
|
||||
expect(complete("<p><#")).toContain("list");
|
||||
expect(complete("<#list xs as x><@card><#if a></")).toEqual(["#if", "@card", "#list"]);
|
||||
expect(complete("<#list xs as x><@card><#if a></#")).toEqual(["#if", "@card", "#list"]);
|
||||
expect(complete("${name?")).toContain("upper_case");
|
||||
expect(complete("<p>Why?")).not.toContain("upper_case");
|
||||
});
|
||||
|
||||
it("comments with <#-- -->", () => {
|
||||
const v = view("|<p>a</p>");
|
||||
v.dispatch({ selection: EditorSelection.range(0, v.state.doc.length) });
|
||||
commentBlock(v);
|
||||
expect(v.state.doc.toString()).toBe("<#-- <p>a</p> -->");
|
||||
const square = view("[#ftl]\n|<p>a</p>");
|
||||
square.dispatch({ selection: EditorSelection.range(7, square.state.doc.length) });
|
||||
commentBlock(square);
|
||||
expect(square.state.doc.toString()).toBe("[#ftl]\n[#-- <p>a</p> --]");
|
||||
// JavaScript keeps its own.
|
||||
const script = view("<script>|a()</script>");
|
||||
script.dispatch({ selection: EditorSelection.range(8, 11) });
|
||||
commentBlock(script);
|
||||
expect(script.state.doc.toString()).toBe("<script>/* a() */</script>");
|
||||
});
|
||||
});
|
||||
+14
-4
@@ -2,7 +2,7 @@ import { describe, expect, it } from "vitest";
|
||||
import { EditorState } from "@codemirror/state";
|
||||
import { completedSyntaxTree } from "@/test/syntax";
|
||||
import { highlightTree, tagHighlighter, tags as t } from "@lezer/highlight";
|
||||
import { findLanguageDescription, loadSupport } from "./languages";
|
||||
import { findLanguageDescription, loadSupport } from "../languages";
|
||||
|
||||
const highlighter = tagHighlighter([
|
||||
{ tag: t.keyword, class: "keyword" },
|
||||
@@ -25,9 +25,19 @@ async function tokens(source: string) {
|
||||
const support = await loadSupport(desc);
|
||||
const state = EditorState.create({ doc: source, extensions: [support!] });
|
||||
const result: { text: string; style: string }[] = [];
|
||||
highlightTree(completedSyntaxTree(state), highlighter, (from, to, style) =>
|
||||
result.push({ text: source.slice(from, to), style }),
|
||||
);
|
||||
let last = { to: -1, style: "" };
|
||||
// One span per run of a style on a line, as the editor draws it.
|
||||
highlightTree(completedSyntaxTree(state), highlighter, (from, to, style) => {
|
||||
source
|
||||
.slice(from, to)
|
||||
.split("\n")
|
||||
.forEach((text, i) => {
|
||||
const prev = result.at(-1);
|
||||
if (i == 0 && prev && last.to == from && last.style == style) prev.text += text;
|
||||
else result.push({ text, style });
|
||||
});
|
||||
last = { to, style };
|
||||
});
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,320 @@
|
||||
/**
|
||||
* FreeMarker templates: `freemarker.grammar` parses the template layer (directives,
|
||||
* user-defined directive calls, interpolations, comments), and the text between its
|
||||
* elements is one HTML document, an overlay as in Django and JSP templates, so markup
|
||||
* split by a directive still nests, `href="${url}"` is an attribute with a hole, and
|
||||
* `<script>` / `<style>` get JavaScript and CSS. Block directives fold, indent their
|
||||
* content and match their end tags; finishing a block directive adds its end tag.
|
||||
* Completion offers directives after `<#`, the open blocks' end tags after `</` and
|
||||
* built-ins after `?`.
|
||||
*/
|
||||
import {
|
||||
LRLanguage,
|
||||
LanguageSupport,
|
||||
bracketMatchingHandle,
|
||||
foldNodeProp,
|
||||
indentNodeProp,
|
||||
syntaxTree,
|
||||
type TreeIndentContext,
|
||||
} from "@codemirror/language";
|
||||
import { html } from "@codemirror/lang-html";
|
||||
import type { Completion, CompletionContext, CompletionResult } from "@codemirror/autocomplete";
|
||||
import { EditorSelection, EditorState, Prec, type Text } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { styleTags, tags as t } from "@lezer/highlight";
|
||||
import { NodeProp, parseMixed, type SyntaxNode, type SyntaxNodeRef } from "@lezer/common";
|
||||
import { VERSIONED_SCRIPT_TYPES } from "../htmlScripts";
|
||||
import { parser } from "./parser";
|
||||
import { BLOCK_DIRECTIVES, CAPTURING, DIRECTIVES, RAW_DIRECTIVES } from "./tokens";
|
||||
|
||||
const baseHTML = html({ selfClosingTags: true, nestedLanguages: VERSIONED_SCRIPT_TYPES });
|
||||
|
||||
const FTL_COMMENT = { block: { open: "<#--", close: "-->" } };
|
||||
const SQUARE_COMMENT = { block: { open: "[#--", close: "--]" } };
|
||||
|
||||
const OPENERS = ["OpenTag", "RawTag"];
|
||||
|
||||
const startTagOf = (element: SyntaxNode) => element.firstChild;
|
||||
const endTagOf = (element: SyntaxNode) => (element.lastChild?.name == "EndTag" ? element.lastChild : null);
|
||||
const tagNameOf = (node: SyntaxNode) => node.getChild("DirectiveName") ?? node.getChild("MacroName");
|
||||
|
||||
/** The content of a block: from the end of its start tag to its end tag (or the end of the block). */
|
||||
function foldBlock(element: SyntaxNode, state: EditorState) {
|
||||
const start = startTagOf(element);
|
||||
const end = endTagOf(element);
|
||||
if (!start) return null;
|
||||
// An end tag the parser inserted to recover is empty.
|
||||
const to = end && end.to > end.from ? end.from : element.to;
|
||||
return start.to < to && state.doc.lineAt(start.to).number < state.doc.lineAt(to).number
|
||||
? { from: start.to, to }
|
||||
: null;
|
||||
}
|
||||
|
||||
const MIDDLE = new Set([...BLOCK_DIRECTIVES.values()].flat());
|
||||
const CLOSING_LINE = /^\s*(?:<|\[)(?:\/[#@]|#([A-Za-z]+))/;
|
||||
|
||||
/** A block's content one unit in from its start tag's line; its middle and end tags at that line's indent. */
|
||||
function indentBlock(cx: TreeIndentContext) {
|
||||
const start = startTagOf(cx.node);
|
||||
if (!start) return null;
|
||||
const base = cx.lineIndent(start.from);
|
||||
const m = CLOSING_LINE.exec(cx.textAfter);
|
||||
return m && (!m[1] || MIDDLE.has(m[1])) ? base : base + cx.unit;
|
||||
}
|
||||
|
||||
const templateParser = parser.configure({
|
||||
props: [
|
||||
styleTags({
|
||||
"TagStart OpenTagStart RawTagStart MidTagStart EndTagStart StrayEndTagStart TagEnd SelfCloseEnd InterpolationStart InterpolationEnd":
|
||||
t.special(t.brace),
|
||||
DirectiveName: t.keyword,
|
||||
MacroName: t.function(t.variableName),
|
||||
"Comment RawBody": t.blockComment,
|
||||
VariableName: t.variableName,
|
||||
"PropertyName Member/.": t.propertyName,
|
||||
"BuiltInName BuiltIn/?": t.standard(t.function(t.variableName)),
|
||||
String: t.string,
|
||||
Number: t.number,
|
||||
BooleanLiteral: t.bool,
|
||||
"Operator CompareOp": t.operator,
|
||||
"as in using gt gte lt lte": t.keyword,
|
||||
"( ) [ ] { }": t.bracket,
|
||||
}),
|
||||
foldNodeProp.add({ "Element RawElement": foldBlock }),
|
||||
indentNodeProp.add({
|
||||
Element: indentBlock,
|
||||
// The raw content keeps its own indentation.
|
||||
RawElement: () => null,
|
||||
}),
|
||||
NodeProp.closedBy.add({ "OpenTag RawTag": ["EndTag"] }),
|
||||
NodeProp.openedBy.add({ EndTag: OPENERS }),
|
||||
bracketMatchingHandle.add({ "OpenTag RawTag EndTag": tagNameOf }),
|
||||
],
|
||||
});
|
||||
|
||||
// HTML's document gives no indentation past its last text; there the block around it does.
|
||||
const htmlBase = (baseHTML.language as LRLanguage).parser;
|
||||
const htmlDocumentIndent = htmlBase.nodeSet.types.find((type) => type.name == "Document")?.prop(indentNodeProp);
|
||||
const htmlParser = htmlBase.configure({
|
||||
props: [indentNodeProp.add({ Document: (cx) => htmlDocumentIndent?.(cx) ?? cx.continue() })],
|
||||
});
|
||||
|
||||
// The template text is one HTML document.
|
||||
const htmlMixed = { parser: htmlParser, overlay: (node: SyntaxNodeRef) => node.name == "Text" };
|
||||
|
||||
export const freemarkerLanguage = LRLanguage.define({
|
||||
name: "freemarker",
|
||||
parser: templateParser.configure({ wrap: parseMixed((node) => (node.type.isTop ? htmlMixed : null)) }),
|
||||
});
|
||||
|
||||
/** Where the template layer reaches: FreeMarker's own nodes, or the HTML outside `<script>` and `<style>`. */
|
||||
function inTemplate(state: EditorState, pos: number): boolean {
|
||||
return freemarkerLanguage.isActiveAt(state, pos, -1) || baseHTML.language.isActiveAt(state, pos, -1);
|
||||
}
|
||||
|
||||
const squareSyntaxOf = new WeakMap<Text, boolean>();
|
||||
|
||||
/** The square tag syntax, when the template's first directive uses it. */
|
||||
function squareSyntax(state: EditorState): boolean {
|
||||
let square = squareSyntaxOf.get(state.doc);
|
||||
if (square == undefined) {
|
||||
const head = state.sliceDoc(0, Math.min(state.doc.length, 20_000));
|
||||
square = /<\/?[#@][A-Za-z]|\[\/?[#@][A-Za-z]/.exec(head)?.[0][0] == "[";
|
||||
squareSyntaxOf.set(state.doc, square);
|
||||
}
|
||||
return square;
|
||||
}
|
||||
|
||||
/** The blocks open at `pos`, innermost first, as `#if` / `@badge`. */
|
||||
function openBlocks(state: EditorState, pos: number): string[] {
|
||||
const names: string[] = [];
|
||||
for (let node: SyntaxNode | null = syntaxTree(state).resolve(pos, -1); node; node = node.parent) {
|
||||
if (node.name != "Element" && node.name != "RawElement") continue;
|
||||
const start = startTagOf(node);
|
||||
const name = start && tagNameOf(start);
|
||||
if (start && name && start.to <= pos) {
|
||||
names.push(state.sliceDoc(start.from, name.from).replace(/^[<[]/, "") + state.sliceDoc(name.from, name.to));
|
||||
}
|
||||
}
|
||||
return names;
|
||||
}
|
||||
|
||||
/** Whether the block `name` opened before `pos` has no end tag after it, nested blocks counted. */
|
||||
function unclosed(state: EditorState, sigil: string, name: string, pos: number): boolean {
|
||||
const rest = state.sliceDoc(pos);
|
||||
const escaped = name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||
const re = new RegExp(`[<\\[](/)?${sigil}${escaped}(?![\\w.:-])`, "g");
|
||||
let depth = 0;
|
||||
for (let m; (m = re.exec(rest));) {
|
||||
if (!m[1]) depth++;
|
||||
else if (depth-- == 0) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
const TAG_BEFORE = /[<[]([#@])([A-Za-z_][\w.:-]*)(?:\s[^<>[\]]*)?$/;
|
||||
|
||||
/** Typing the `>` (`]`) of a block directive or a call with content adds its end tag after the caret. */
|
||||
const closeBlock = EditorView.inputHandler.of((view, from, to, text) => {
|
||||
const { state } = view;
|
||||
if ((text != ">" && text != "]") || from != to || state.selection.ranges.length > 1 || state.readOnly) return false;
|
||||
const square = squareSyntax(state);
|
||||
if ((text == "]") != square) return false;
|
||||
const line = state.doc.lineAt(from);
|
||||
const before = state.sliceDoc(line.from, from);
|
||||
const m = TAG_BEFORE.exec(before);
|
||||
if (!m || before.endsWith("/") || (m[0][0] == "[") != square) return false;
|
||||
const [, sigil, name] = m;
|
||||
// `<#assign x>…</#assign>` captures its content; `<#assign x = 1>` doesn't.
|
||||
const assigns = /(?:^|[^=!<>])=(?!=)/.test(before.slice(before.length - m[0].length + 2 + name!.length));
|
||||
const block = BLOCK_DIRECTIVES.has(name!) || RAW_DIRECTIVES.has(name!) || (CAPTURING.has(name!) && !assigns);
|
||||
if (sigil == "#" && !block) return false;
|
||||
if (!inTemplate(state, from - m[0].length)) return false;
|
||||
if (!unclosed(state, sigil!, name!, from)) return false;
|
||||
const close = square ? `[/${sigil}${name}]` : `</${sigil}${name}>`;
|
||||
view.dispatch({
|
||||
changes: { from, insert: text + close },
|
||||
selection: EditorSelection.cursor(from + 1),
|
||||
userEvent: "input.type",
|
||||
});
|
||||
return true;
|
||||
});
|
||||
|
||||
const DIRECTIVE_OPTIONS: Completion[] = DIRECTIVES.map((label) => ({ label, type: "keyword" }));
|
||||
|
||||
/** Built-ins most templates use, for completion after `?`. */
|
||||
const BUILT_INS = [
|
||||
"api",
|
||||
"boolean",
|
||||
"c",
|
||||
"c_lower_case",
|
||||
"cap_first",
|
||||
"capitalize",
|
||||
"chop_linebreaks",
|
||||
"chunk",
|
||||
"contains",
|
||||
"counter",
|
||||
"date",
|
||||
"datetime",
|
||||
"default",
|
||||
"drop_while",
|
||||
"ends_with",
|
||||
"ensure_ends_with",
|
||||
"ensure_starts_with",
|
||||
"eval",
|
||||
"eval_json",
|
||||
"filter",
|
||||
"first",
|
||||
"groups",
|
||||
"has_content",
|
||||
"has_next",
|
||||
"html",
|
||||
"if_exists",
|
||||
"index",
|
||||
"index_of",
|
||||
"interpret",
|
||||
"is_boolean",
|
||||
"is_date",
|
||||
"is_even_item",
|
||||
"is_first",
|
||||
"is_hash",
|
||||
"is_last",
|
||||
"is_number",
|
||||
"is_odd_item",
|
||||
"is_sequence",
|
||||
"is_string",
|
||||
"item_cycle",
|
||||
"item_parity",
|
||||
"j_string",
|
||||
"join",
|
||||
"js_string",
|
||||
"json_string",
|
||||
"keep_after",
|
||||
"keep_after_last",
|
||||
"keep_before",
|
||||
"keep_before_last",
|
||||
"keys",
|
||||
"last",
|
||||
"last_index_of",
|
||||
"left_pad",
|
||||
"length",
|
||||
"lower_case",
|
||||
"map",
|
||||
"matches",
|
||||
"max",
|
||||
"min",
|
||||
"no_esc",
|
||||
"number",
|
||||
"number_to_date",
|
||||
"number_to_datetime",
|
||||
"remove_beginning",
|
||||
"remove_ending",
|
||||
"replace",
|
||||
"reverse",
|
||||
"right_pad",
|
||||
"round",
|
||||
"seq_contains",
|
||||
"seq_index_of",
|
||||
"size",
|
||||
"sort",
|
||||
"sort_by",
|
||||
"split",
|
||||
"starts_with",
|
||||
"string",
|
||||
"substring",
|
||||
"switch",
|
||||
"take_while",
|
||||
"then",
|
||||
"time",
|
||||
"trim",
|
||||
"truncate",
|
||||
"uncap_first",
|
||||
"upper_case",
|
||||
"url",
|
||||
"values",
|
||||
"word_list",
|
||||
"xhtml",
|
||||
"xml",
|
||||
].map((label): Completion => ({ label, type: "function" }));
|
||||
|
||||
/** `<#…`, `</#…` and `?…` inside the template layer. */
|
||||
function templateCompletion(context: CompletionContext): CompletionResult | null {
|
||||
const { state } = context;
|
||||
const end = context.matchBefore(/[<[]\/(?:[#@][\w.:-]*)?$/);
|
||||
if (end) {
|
||||
const from = end.from + 2;
|
||||
const options = openBlocks(state, from).map((block, i) => ({ label: block, type: "keyword", boost: 99 - i }));
|
||||
return options.length ? { from, options, validFor: /^(?:[#@][\w.:-]*)?$/ } : null;
|
||||
}
|
||||
const directive = context.matchBefore(/[<[]#\w*$/);
|
||||
if (directive) {
|
||||
if ((directive.text[0] == "[") != squareSyntax(state)) return null;
|
||||
const name = /\w*$/.exec(directive.text)![0];
|
||||
return { from: directive.to - name.length, options: DIRECTIVE_OPTIONS, validFor: /^\w*$/ };
|
||||
}
|
||||
const builtIn = context.matchBefore(/\?\w*$/);
|
||||
// The `?` is a built-in's, not text or a string's.
|
||||
const mark = builtIn && syntaxTree(state).resolveInner(builtIn.from + 1, -1);
|
||||
if (builtIn && mark && (mark.name == "BuiltIn" || mark.parent?.name == "BuiltIn")) {
|
||||
return { from: builtIn.from + 1, options: BUILT_INS, validFor: /^\w*$/ };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function freemarker(): LanguageSupport {
|
||||
return new LanguageSupport(freemarkerLanguage, [
|
||||
// Before HTML's, so the template's completions come first.
|
||||
baseHTML.language.data.of({ autocomplete: templateCompletion }),
|
||||
baseHTML.support,
|
||||
// Markup is commented out with a template comment, which FreeMarker drops from the page.
|
||||
baseHTML.language.data.of({ commentTokens: FTL_COMMENT }),
|
||||
freemarkerLanguage.data.of({ autocomplete: templateCompletion, commentTokens: FTL_COMMENT }),
|
||||
// In the square syntax, `[#-- --]`.
|
||||
Prec.highest(
|
||||
EditorState.languageData.of((state, pos) =>
|
||||
squareSyntax(state) && inTemplate(state, pos) ? [{ commentTokens: SQUARE_COMMENT }] : [],
|
||||
),
|
||||
),
|
||||
Prec.high(closeBlock),
|
||||
]);
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
// This file was generated by lezer-generator. You probably shouldn't edit it.
|
||||
export const
|
||||
Comment = 1,
|
||||
RawBody = 2,
|
||||
Text = 3,
|
||||
OpenTagStart = 4,
|
||||
RawTagStart = 5,
|
||||
MidTagStart = 6,
|
||||
EndTagStart = 7,
|
||||
StrayEndTagStart = 8,
|
||||
TagStart = 9,
|
||||
InterpolationStart = 10,
|
||||
DirectiveName = 11,
|
||||
MacroName = 12,
|
||||
TagEnd = 13,
|
||||
SelfCloseEnd = 14,
|
||||
InterpolationEnd = 15,
|
||||
Template = 16,
|
||||
Interpolation = 17,
|
||||
VariableName = 18,
|
||||
PropertyName = 21,
|
||||
BuiltInName = 24,
|
||||
String = 25,
|
||||
Number = 26,
|
||||
Operator = 27,
|
||||
CompareOp = 28,
|
||||
as = 29,
|
||||
_in = 30,
|
||||
using = 31,
|
||||
gt = 32,
|
||||
gte = 33,
|
||||
lt = 34,
|
||||
lte = 35,
|
||||
BooleanLiteral = 36,
|
||||
Tag = 46,
|
||||
Element = 47,
|
||||
OpenTag = 48,
|
||||
MidTag = 49,
|
||||
EndTag = 50,
|
||||
RawElement = 51,
|
||||
RawTag = 52,
|
||||
StrayEndTag = 53
|
||||
@@ -0,0 +1,24 @@
|
||||
// This file was generated by lezer-generator. You probably shouldn't edit it.
|
||||
import {LRParser} from "@lezer/lr"
|
||||
import {comment, rawBody, text, tagStart, tagName, tagEnd, blocks} from "./tokens"
|
||||
const spec_identifier = {__proto__:null,as:58, in:60, using:62, gt:64, gte:66, lt:68, lte:70, true:72, false:72}
|
||||
export const parser = LRParser.deserialize({
|
||||
version: 14,
|
||||
states: "*nQVO]OOO!xQ#SO'#CmO#PQ!rO'#D[O#PQ!rO'#D^O#XO]O'#D]O#PQ!rO'#DbO#cOYO'#DaO#kQ#dO'#DcOOO]'#Dj'#DjOOO]'#Dd'#DdQVO]OOOOQp'#Cn'#CnO#vQ!bO'#CoO#{Q!bO'#CrO$QQ!bO'#DTO$XQ!bO'#DWO$`Q!bO'#DZOOQp'#Dk'#DkOOQp'#De'#DeO$gQ#SO,59XOOO],59X,59XOOQp'#Dm'#DmO$nQ#SO,59vO$xQ#SO,59xO#PQ!rO'#D_O%PO]O'#DfO%ZOWO,59wO%cQ#dO'#D`OOO],59w,59wO#XO]O,59wO%nQ#SO,59|OOO],59{,59{O#fOWO,59{OOO],59},59}O%uQ#SO,59}OOO]-E7b-E7bOOQp'#Cq'#CqOOQp,59Z,59ZOOQp'#Ct'#CtOOQp,59^,59^OOQp,59o,59oO%zQ!bO,59oOOQp,59r,59rO&RQ!bO,59rOOQp,59u,59uO&YQ!bO,59uOOQp-E7c-E7cOOO]1G.s1G.sO&aQ#SO1G/bOOO]1G/b1G/bO&kQ#SO1G/dOOO]1G/d1G/dO&rQ#SO,59yO&|O]O,5:QOOOW-E7d-E7dOOO]1G/c1G/cOOO],59z,59zO'WQ#SO,59zO%ZOWO1G/cO']Q#SO1G/hOOOY1G/h1G/hOOO]1G/g1G/gOOO]1G/i1G/iOOQp1G/Z1G/ZOOQp1G/^1G/^OOQp1G/a1G/aOOO]7+$|7+$|OOO]7+%O7+%OO'dQ#SO1G/eOOO]1G/e1G/eOOO]1G/f1G/fOOO]7+$}7+$}OOOY7+%S7+%SOOO]7+%P7+%P",
|
||||
stateData: "'q~O!]OS~OPWORWOSROTTOWVOXQOYPO~Od[Og]OiaOjaOkaOlaOmaOnaOoaOpaOqaOraOsaOtaOv^Oy_O|`O!`ZO~O_dO~PnOZeO[eO~OUhOVkO~PVOQpOVkO~OZeO[eO]qO~O!`tO~O!`vO~OuxO~PnOxzO~PnO{|O~PnO_!PO~PnO]!RO^!RO~PnO]!TO~PnOU!YXV!YX~PVOUhOVkO~OZeO[eO]!YO~O]!^O~PnO]!`O~Ou!aO~PnOx!bO~PnO{!cO~PnO]!dO^!dO~PnO]!eO~PnO]!gO^!gO~PnOU!YaV!Ya~PVO]!hO~O]!jO~PnO]!kO^!kO~PnOi!`~",
|
||||
goto: "&V!bPPPPPPPPPPPPPPPPP!c!k!kP!}!kP#QPPPPPPPPPPPPPP!kPP!kPP!k!c!c#T#]#c!c#s!c#{$Z$}PPP%X%aP%s]WOSYim!VqaP^_`cfgny{}!Q!S!U!]!fRu[Rw]]SOSYim!VXiSjm![QlSQoUS!XjmQ!_pR!i![]UOSYim!VQYOQmSUsYm!VR!ViQcPQy^Q{_Q}``!Ocy{}!Q!S!]!fQ!QfQ!SgQ!]nR!f!UQjSS!Wj![R![m]XOSYim!VqbP^_`cfgny{}!Q!S!U!]!fQfQQgRQnTQrVQ!UhR!Zk",
|
||||
nodeNames: "⚠ Comment RawBody Text OpenTagStart RawTagStart MidTagStart EndTagStart StrayEndTagStart TagStart InterpolationStart DirectiveName MacroName TagEnd SelfCloseEnd InterpolationEnd Template Interpolation VariableName Member . PropertyName BuiltIn ? BuiltInName String Number Operator CompareOp as in using gt gte lt lte BooleanLiteral ) ( ParenGroup ] [ BracketGroup } { HashGroup Tag Element OpenTag MidTag EndTag RawElement RawTag StrayEndTag",
|
||||
maxTerm: 63,
|
||||
context: blocks,
|
||||
nodeProps: [
|
||||
["openedBy", 37,"(",40,"[",43,"{"],
|
||||
["closedBy", 38,")",41,"]",44,"}"]
|
||||
],
|
||||
skippedNodes: [0],
|
||||
repeatNodeCount: 3,
|
||||
tokenData: ",X~RvXY#iYZ#i]^#ipq#iqr#zrs$Xtu%yuv&nvw&{wx'Txy(pyz(uz{&n{|(z|}&v}!O)V!O!P)e!P!Q&n!Q![){![!]&v!]!^&v!^!_*f!_!`#z!`!a*f!a!b*n!c!}%y!}#O*v#P#Q*{#R#S%y#T#f%y#f#g+Q#g#o%y#o#p+u#p#q+z#q#r,S$g;'S%y;'S;=`&h<%lO%y~#nS!]~XY#iYZ#i]^#ipq#i~$PPk~!_!`$S~$XOl~~$^Vi~Or$Xrs$ss#O$X#O#P$x#P;'S$X;'S;=`%s<%lO$X~$xOi~~${RO;'S$X;'S;=`%U;=`O$X~%ZWi~Or$Xrs$ss#O$X#O#P$x#P;'S$X;'S;=`%s;=`<%l$X<%lO$X~%vP;=`<%l$X~&OW!`~tu%y!Q![%y!c!}%y#R#S%y#T#o%y$g;'S%y;'S;=`&h<%lO%y~&kP;=`<%l%y~&sPk~!_!`&v~&{Ok~~'QPk~vw&v~'YVi~Ow'Twx$sx#O'T#O#P'o#P;'S'T;'S;=`(j<%lO'T~'rRO;'S'T;'S;=`'{;=`O'T~(QWi~Ow'Twx$sx#O'T#O#P'o#P;'S'T;'S;=`(j;=`<%l'T<%lO'T~(mP;=`<%l'T~(uOv~~(zOu~~)PQk~{|&v!_!`&v~)[Rk~}!O&v!_!`&v!`!a&v~)jPd~!O!P)m~)rRk~qr&vz{&v!^!_&v~*QQj~!O!P*W!Q![){~*ZP!Q![*^~*cPj~!Q![*^~*kPl~!_!`$S~*sPg~!a!b&v~*{Oy~~+QOx~~+VY!`~rs$Xtu%ywx'T!Q![%y!c!}%y#R#S%y#T#o%y$g;'S%y;'S;=`&h<%lO%y~+zO|~~,PPk~#p#q&v~,XO{~",
|
||||
tokenizers: [comment, rawBody, text, tagStart, tagName, tagEnd, 0],
|
||||
topRules: {"Template":[0,16]},
|
||||
specialized: [{term: 62, get: (value: keyof typeof spec_identifier) => spec_identifier[value] || -1}],
|
||||
tokenPrec: 306
|
||||
})
|
||||
@@ -0,0 +1,350 @@
|
||||
/**
|
||||
* External tokens of `freemarker.grammar`: the text between template elements, the
|
||||
* comments, the raw content of `noparse`, the start of each tag, classified by its name
|
||||
* against the blocks open around it, the tag's name and the delimiters that end tags
|
||||
* and interpolations, which depend on the tag syntax.
|
||||
*/
|
||||
import { ContextTracker, ExternalTokenizer, type InputStream, type Stack } from "@lezer/lr";
|
||||
import {
|
||||
Comment,
|
||||
DirectiveName,
|
||||
Element,
|
||||
EndTagStart,
|
||||
InterpolationEnd,
|
||||
InterpolationStart,
|
||||
MacroName,
|
||||
MidTagStart,
|
||||
OpenTagStart,
|
||||
RawBody,
|
||||
RawElement,
|
||||
RawTagStart,
|
||||
SelfCloseEnd,
|
||||
StrayEndTagStart,
|
||||
TagEnd,
|
||||
TagStart,
|
||||
Text,
|
||||
} from "./parser.terms";
|
||||
|
||||
const LT = 60,
|
||||
GT = 62,
|
||||
SLASH = 47,
|
||||
HASH = 35,
|
||||
AT = 64,
|
||||
DOLLAR = 36,
|
||||
EQ = 61,
|
||||
BRACE_L = 123,
|
||||
BRACE_R = 125,
|
||||
BRACKET_L = 91,
|
||||
BRACKET_R = 93,
|
||||
PAREN_L = 40,
|
||||
PAREN_R = 41,
|
||||
DASH = 45,
|
||||
QUOTE = 34,
|
||||
APOS = 39,
|
||||
BACKSLASH = 92,
|
||||
BANG = 33;
|
||||
|
||||
/** Block directives, with the middle tags each one allows. */
|
||||
export const BLOCK_DIRECTIVES: ReadonlyMap<string, readonly string[]> = new Map([
|
||||
["attempt", ["recover"]],
|
||||
["autoesc", []],
|
||||
["compress", []],
|
||||
["escape", []],
|
||||
["function", []],
|
||||
["if", ["elseif", "else"]],
|
||||
["items", []],
|
||||
["list", ["else"]],
|
||||
["macro", []],
|
||||
["noautoesc", []],
|
||||
["noescape", []],
|
||||
["outputformat", []],
|
||||
["switch", ["case", "default", "on"]],
|
||||
]);
|
||||
|
||||
/** `<#assign x>…</#assign>`: these capture their content when they have no `=`. */
|
||||
export const CAPTURING: ReadonlySet<string> = new Set(["assign", "global", "local"]);
|
||||
|
||||
/** Directives whose content FreeMarker doesn't parse. */
|
||||
export const RAW_DIRECTIVES: ReadonlySet<string> = new Set(["noparse", "comment"]);
|
||||
|
||||
/** Every built-in directive, for completion. */
|
||||
export const DIRECTIVES = [
|
||||
"assign",
|
||||
"attempt",
|
||||
"autoesc",
|
||||
"break",
|
||||
"case",
|
||||
"compress",
|
||||
"continue",
|
||||
"default",
|
||||
"else",
|
||||
"elseif",
|
||||
"escape",
|
||||
"fallback",
|
||||
"flush",
|
||||
"ftl",
|
||||
"function",
|
||||
"global",
|
||||
"if",
|
||||
"import",
|
||||
"include",
|
||||
"items",
|
||||
"list",
|
||||
"local",
|
||||
"lt",
|
||||
"macro",
|
||||
"nested",
|
||||
"noautoesc",
|
||||
"noescape",
|
||||
"noparse",
|
||||
"nt",
|
||||
"on",
|
||||
"outputformat",
|
||||
"recover",
|
||||
"recurse",
|
||||
"return",
|
||||
"rt",
|
||||
"sep",
|
||||
"setting",
|
||||
"stop",
|
||||
"switch",
|
||||
"t",
|
||||
"visit",
|
||||
];
|
||||
|
||||
/** The blocks open around a position, innermost first, and the tag syntax (`null`: not fixed yet). */
|
||||
class Context {
|
||||
readonly hash: number;
|
||||
constructor(
|
||||
/** `#if`, `@badge`. */
|
||||
readonly name: string | null,
|
||||
readonly parent: Context | null,
|
||||
readonly square: boolean | null,
|
||||
) {
|
||||
let hash = parent ? parent.hash : square === null ? 1 : square ? 2 : 3;
|
||||
for (let i = 0; name && i < name.length; i++) hash = ((hash << 5) - hash + name.charCodeAt(i)) | 0;
|
||||
this.hash = hash;
|
||||
}
|
||||
}
|
||||
|
||||
const TOP = new Context(null, null, null);
|
||||
|
||||
const isNameStart = (ch: number) => (ch >= 65 && ch <= 90) || (ch >= 97 && ch <= 122) || ch == 95;
|
||||
const isName = (ch: number) => isNameStart(ch) || (ch >= 48 && ch <= 57);
|
||||
/** User-defined directive names may be qualified (`lib.badge`) or carry `:` and `-`. */
|
||||
const isMacroName = (ch: number) => isName(ch) || ch == 46 || ch == 58 || ch == DASH;
|
||||
|
||||
/** A tag opening `offset` code units ahead: its kind, sigil and name. */
|
||||
interface TagHead {
|
||||
/** Code units up to the name. */
|
||||
length: number;
|
||||
end: boolean;
|
||||
sigil: "#" | "@";
|
||||
name: string;
|
||||
square: boolean;
|
||||
}
|
||||
|
||||
function tagHead(input: InputStream, offset: number, square: boolean | null): TagHead | null {
|
||||
const open = input.peek(offset);
|
||||
if (open == LT ? square === true : open == BRACKET_L ? square === false : true) return null;
|
||||
let i = offset + 1;
|
||||
const end = input.peek(i) == SLASH;
|
||||
if (end) i++;
|
||||
const sigil = input.peek(i);
|
||||
if (sigil != HASH && sigil != AT) return null;
|
||||
i++;
|
||||
let name = "";
|
||||
const accept = sigil == HASH ? isName : isMacroName;
|
||||
for (let ch; accept((ch = input.peek(i))); i++) {
|
||||
if (!name && !isNameStart(ch)) break;
|
||||
name += String.fromCharCode(ch);
|
||||
}
|
||||
// `<#--` is a comment, `</@>` ends the innermost call; anything else needs a name.
|
||||
if (!name && !(end && sigil == AT)) return null;
|
||||
return { length: i - offset - name.length, end, sigil: sigil == HASH ? "#" : "@", name, square: open == BRACKET_L };
|
||||
}
|
||||
|
||||
const commentAt = (input: InputStream, offset: number, square: boolean | null) => {
|
||||
const open = input.peek(offset);
|
||||
return (
|
||||
(open == LT ? square !== true : open == BRACKET_L && square !== false) &&
|
||||
input.peek(offset + 1) == HASH &&
|
||||
input.peek(offset + 2) == DASH &&
|
||||
input.peek(offset + 3) == DASH
|
||||
);
|
||||
};
|
||||
|
||||
const interpolationAt = (input: InputStream, offset: number, square: boolean | null) => {
|
||||
const ch = input.peek(offset);
|
||||
return (
|
||||
(ch == DOLLAR && input.peek(offset + 1) == BRACE_L) ||
|
||||
(square === true && ch == BRACKET_L && input.peek(offset + 1) == EQ)
|
||||
);
|
||||
};
|
||||
|
||||
/** Whether a comment, a tag or an interpolation starts `offset` code units ahead. */
|
||||
function elementStart(input: InputStream, offset: number, square: boolean | null): boolean {
|
||||
const ch = input.peek(offset);
|
||||
if (ch != LT && ch != BRACKET_L && ch != DOLLAR) return false;
|
||||
return interpolationAt(input, offset, square) || commentAt(input, offset, square) || !!tagHead(input, offset, square);
|
||||
}
|
||||
|
||||
/** How far a tag scan looks for the tag's end. */
|
||||
const MAX_TAG = 4000;
|
||||
|
||||
/**
|
||||
* The rest of a tag after its name: whether it ends with `/>` (`/]`) and whether it has an
|
||||
* assignment `=` outside brackets, skipping strings and brackets.
|
||||
*/
|
||||
function tagTail(input: InputStream, offset: number, square: boolean): { selfClosing: boolean; assigns: boolean } {
|
||||
const close = square ? BRACKET_R : GT;
|
||||
let depth = 0;
|
||||
let assigns = false;
|
||||
for (let i = offset; i < offset + MAX_TAG; i++) {
|
||||
const ch = input.peek(i);
|
||||
if (ch < 0) break;
|
||||
if (ch == QUOTE || ch == APOS) {
|
||||
for (i++; ; i++) {
|
||||
const c = input.peek(i);
|
||||
if (c < 0 || c == ch) break;
|
||||
if (c == BACKSLASH) i++;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (ch == PAREN_L || ch == BRACE_L || ch == BRACKET_L) {
|
||||
depth++;
|
||||
continue;
|
||||
}
|
||||
if (depth > 0 && (ch == PAREN_R || ch == BRACE_R || ch == BRACKET_R)) {
|
||||
depth--;
|
||||
continue;
|
||||
}
|
||||
if (depth == 0 && ch == close) return { selfClosing: input.peek(i - 1) == SLASH, assigns };
|
||||
if (depth == 0 && ch == EQ) {
|
||||
const before = input.peek(i - 1);
|
||||
const after = input.peek(i + 1);
|
||||
if (after != EQ && before != EQ && before != BANG && before != LT && before != GT) assigns = true;
|
||||
}
|
||||
}
|
||||
return { selfClosing: false, assigns };
|
||||
}
|
||||
|
||||
export const blocks = new ContextTracker<Context>({
|
||||
start: TOP,
|
||||
shift(context, term, _stack, input) {
|
||||
const opens = term == OpenTagStart || term == RawTagStart;
|
||||
const tag = opens || term == MidTagStart || term == EndTagStart || term == StrayEndTagStart || term == TagStart;
|
||||
if (!tag) return context;
|
||||
const square = context.square ?? input.next == BRACKET_L;
|
||||
if (!opens) return square === context.square ? context : fixSyntax(context, square);
|
||||
const head = tagHead(input, 0, square);
|
||||
const base = square === context.square ? context : fixSyntax(context, square);
|
||||
return new Context(head ? head.sigil + head.name : null, base, square);
|
||||
},
|
||||
reduce(context, term) {
|
||||
return (term == Element || term == RawElement) && context.parent ? context.parent : context;
|
||||
},
|
||||
hash: (context) => context.hash,
|
||||
strict: false,
|
||||
});
|
||||
|
||||
/** `context` with the tag syntax fixed, for the blocks around it too. */
|
||||
function fixSyntax(context: Context, square: boolean): Context {
|
||||
return context.parent
|
||||
? new Context(context.name, fixSyntax(context.parent, square), square)
|
||||
: new Context(null, null, square);
|
||||
}
|
||||
|
||||
/** `<#-- … -->` (`[#-- … --]`), to the end of the document when unterminated. */
|
||||
export const comment = new ExternalTokenizer((input, stack: Stack) => {
|
||||
const context: Context = stack.context;
|
||||
if (!commentAt(input, 0, context.square)) return;
|
||||
const close = input.next == BRACKET_L ? BRACKET_R : GT;
|
||||
input.advance(4);
|
||||
for (let ch; (ch = input.next) >= 0;) {
|
||||
if (ch == DASH && input.peek(1) == DASH && input.peek(2) == close) {
|
||||
input.advance(3);
|
||||
break;
|
||||
}
|
||||
input.advance();
|
||||
}
|
||||
input.acceptToken(Comment);
|
||||
});
|
||||
|
||||
/** Template text: up to a tag, an interpolation or a comment. */
|
||||
export const text = new ExternalTokenizer((input, stack: Stack) => {
|
||||
const square = (stack.context as Context).square;
|
||||
const start = input.pos;
|
||||
while (input.next >= 0 && !elementStart(input, 0, square)) input.advance();
|
||||
if (input.pos > start) input.acceptToken(Text);
|
||||
});
|
||||
|
||||
/** The opening delimiter of a tag or an interpolation, a token telling what it is in the blocks open around it. */
|
||||
export const tagStart = new ExternalTokenizer((input, stack: Stack) => {
|
||||
const context: Context = stack.context;
|
||||
if (interpolationAt(input, 0, context.square)) {
|
||||
if (stack.canShift(InterpolationStart)) input.acceptToken(InterpolationStart, 2);
|
||||
return;
|
||||
}
|
||||
const head = tagHead(input, 0, context.square);
|
||||
if (!head) return;
|
||||
const open = context.name;
|
||||
const name = head.sigil + head.name;
|
||||
let term = TagStart;
|
||||
if (head.end) {
|
||||
term =
|
||||
open && (name == open || (head.sigil == "@" && !head.name && open.startsWith("@")))
|
||||
? EndTagStart
|
||||
: StrayEndTagStart;
|
||||
} else if (head.sigil == "#" && RAW_DIRECTIVES.has(head.name)) {
|
||||
term = RawTagStart;
|
||||
} else if (open?.startsWith("#") && BLOCK_DIRECTIVES.get(open.slice(1))?.includes(head.name)) {
|
||||
term = MidTagStart;
|
||||
} else if (head.sigil == "@" || BLOCK_DIRECTIVES.has(head.name) || CAPTURING.has(head.name)) {
|
||||
const tail = tagTail(input, head.length + head.name.length, head.square);
|
||||
const block = !tail.selfClosing && (!CAPTURING.has(head.name) || !tail.assigns);
|
||||
if (block) term = OpenTagStart;
|
||||
}
|
||||
if (!stack.canShift(term)) term = term == EndTagStart ? StrayEndTagStart : TagStart;
|
||||
if (stack.canShift(term)) input.acceptToken(term, head.length);
|
||||
});
|
||||
|
||||
/** A tag's name: a directive's (`if`) or a user-defined directive's (`lib.badge`). */
|
||||
export const tagName = new ExternalTokenizer((input) => {
|
||||
const sigil = input.peek(-1);
|
||||
if (sigil != HASH && sigil != AT) return;
|
||||
const accept = sigil == HASH ? isName : isMacroName;
|
||||
if (!isNameStart(input.next)) return;
|
||||
while (accept(input.next)) input.advance();
|
||||
input.acceptToken(sigil == HASH ? DirectiveName : MacroName);
|
||||
});
|
||||
|
||||
/** `>` / `/>` (`]` / `/]`) ending a tag, `}` (`]`) ending an interpolation. */
|
||||
export const tagEnd = new ExternalTokenizer((input, stack: Stack) => {
|
||||
const square = (stack.context as Context).square === true;
|
||||
const close = square ? BRACKET_R : GT;
|
||||
if (input.next == SLASH && input.peek(1) == close) {
|
||||
if (stack.canShift(SelfCloseEnd)) input.acceptToken(SelfCloseEnd, 2);
|
||||
return;
|
||||
}
|
||||
if (input.next == close && stack.canShift(TagEnd)) {
|
||||
input.acceptToken(TagEnd, 1);
|
||||
return;
|
||||
}
|
||||
if ((input.next == BRACE_R || (square && input.next == BRACKET_R)) && stack.canShift(InterpolationEnd)) {
|
||||
input.acceptToken(InterpolationEnd, 1);
|
||||
}
|
||||
});
|
||||
|
||||
/** The content of `noparse` or `comment`: up to the end tag closing it. */
|
||||
export const rawBody = new ExternalTokenizer((input, stack: Stack) => {
|
||||
const context: Context = stack.context;
|
||||
const name = context.name;
|
||||
if (!name) return;
|
||||
const start = input.pos;
|
||||
for (; input.next >= 0; input.advance()) {
|
||||
const head = (input.next == LT || input.next == BRACKET_L) && tagHead(input, 0, context.square);
|
||||
if (head && head.end && head.sigil + head.name == name) break;
|
||||
}
|
||||
if (input.pos > start) input.acceptToken(RawBody);
|
||||
});
|
||||
@@ -5,7 +5,7 @@
|
||||
* a click (it picks the line by height first). A font taller than the line height makes the
|
||||
* value negative, which padding clamps to 0. Safari before 16.4 drops it (no `lh`).
|
||||
*/
|
||||
const FULL_ROW_PADDING = "calc((1lh - 1em) / 2)";
|
||||
export const FULL_ROW_PADDING = "calc((1lh - 1em) / 2)";
|
||||
|
||||
/** A background capped at `1lh` so a font taller than the line height does not bleed into the rows above and below. */
|
||||
function cappedBackground(color: string) {
|
||||
|
||||
@@ -43,6 +43,7 @@ import {
|
||||
useTextEditorWrappers,
|
||||
type EditorCloseSession,
|
||||
type EditorInput,
|
||||
type EditorKindContribution,
|
||||
type OpenOptions,
|
||||
type FileEditorResolution,
|
||||
type OpenEditorTab,
|
||||
@@ -310,6 +311,11 @@ function tabModified(tab: Tab): boolean {
|
||||
);
|
||||
}
|
||||
|
||||
/** Whether `input` opens in the preview tab when asked: always for kinds that reuse one, else per the setting. */
|
||||
function previewTabsFor(input: EditorInput, kinds: ReadonlyMap<string, EditorKindContribution>): boolean {
|
||||
return editorPrefs().tabs.previewTab || !!kinds.get(input.kind)?.reusesPreviewTab;
|
||||
}
|
||||
|
||||
export class EditorController implements SlotHost {
|
||||
manager: DocumentManager;
|
||||
readonly slots = new Map<string, EditorSlot>();
|
||||
@@ -1529,7 +1535,7 @@ export class EditorController implements SlotHost {
|
||||
const kinds = useContributions.getState().editorKinds;
|
||||
const lifecycle = documentLifecycle(input, kinds);
|
||||
const canPreview = !lifecycle || (lifecycle.allowPreview && !documentDirty({ input, lifecycle }));
|
||||
const preview = !!o.preview && editorPrefs().tabs.previewTab && canPreview;
|
||||
const preview = !!o.preview && previewTabsFor(input, kinds) && canPreview;
|
||||
if (!activate && preview) return;
|
||||
const kind = kinds.get(input.kind);
|
||||
let paneId = s.panes[generation.pane] ? generation.pane : activate ? s.activePane : null;
|
||||
@@ -2447,7 +2453,8 @@ export class EditorController implements SlotHost {
|
||||
|
||||
activeInput(options?: { previewOnly?: boolean }): EditorInput | null {
|
||||
const tab = this.activeTabOf();
|
||||
if (options?.previewOnly && (!tab?.preview || !editorPrefs().tabs.previewTab)) return null;
|
||||
const kinds = useContributions.getState().editorKinds;
|
||||
if (options?.previewOnly && (!tab?.preview || !previewTabsFor(tab.input, kinds))) return null;
|
||||
return tab?.input ?? null;
|
||||
}
|
||||
|
||||
|
||||
@@ -151,6 +151,36 @@ describe("file open order", () => {
|
||||
expect(activePath()).toBe("/p/b.ts");
|
||||
});
|
||||
|
||||
it("reuses one tab for kinds that ask for it while the preview tab is off", async () => {
|
||||
useProject.setState({ settings: { editor: { tabs: { previewTab: false } } } });
|
||||
dispose = registerEditorKind({
|
||||
kind: "test-diff",
|
||||
reusesPreviewTab: true,
|
||||
component: () => null,
|
||||
title: (input) => input.key,
|
||||
});
|
||||
const controller = setup();
|
||||
const diff = (key: string) => ({ kind: "test-diff", key });
|
||||
await controller.openInput(diff("one"), { preview: true, focus: false });
|
||||
await controller.openInput(diff("two"), { preview: true, focus: false });
|
||||
const tabs = () => Object.values(useTabs.getState().panes).flatMap((pane) => pane.tabs);
|
||||
expect(tabs().map((t) => [t.input.key, t.preview])).toEqual([["two", true]]);
|
||||
expect(controller.activeInput({ previewOnly: true })?.key).toBe("two");
|
||||
// Files still don't preview.
|
||||
await controller.openFile("/p/a.ts", { preview: true, focus: false });
|
||||
await controller.openFile("/p/b.ts", { preview: true, focus: false });
|
||||
expect(openFilePaths(useTabs.getState()).sort()).toEqual(["/p/a.ts", "/p/b.ts"]);
|
||||
// A kept diff tab stays.
|
||||
const pane = useTabs.getState().activePane;
|
||||
controller.keepTab(pane, tabs().find((t) => t.input.key == "two")!.id);
|
||||
await controller.openInput(diff("three"), { preview: true, focus: false });
|
||||
expect(
|
||||
tabs()
|
||||
.filter((t) => t.input.kind == "test-diff")
|
||||
.map((t) => t.input.key),
|
||||
).toEqual(["two", "three"]);
|
||||
});
|
||||
|
||||
it("keeps an earlier regular file without removing the newer preview", async () => {
|
||||
const { started, response } = delayProvider();
|
||||
const controller = setup();
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { CodeAction } from "@/bindings";
|
||||
import { unambiguousImport } from "./autoImport";
|
||||
|
||||
const action = (title: string, over: Partial<CodeAction> = {}): CodeAction => ({
|
||||
title,
|
||||
kind: "quickfix",
|
||||
isPreferred: false,
|
||||
disabledReason: null,
|
||||
edit: null,
|
||||
command: null,
|
||||
data: null,
|
||||
server: 1,
|
||||
...over,
|
||||
});
|
||||
|
||||
describe("unambiguousImport", () => {
|
||||
it("applies the one import fix among other quick fixes", () => {
|
||||
const fix = action("Import 'ArrayList' (java.util)");
|
||||
expect(unambiguousImport([action("Create class 'ArrayList'"), fix])).toBe(fix);
|
||||
});
|
||||
|
||||
it("recognizes C#'s add-using fix, titled with the directive", () => {
|
||||
// csharp-ls (Roslyn) for an unresolved `SceneManager`.
|
||||
const using = action("using UnityEngine.SceneManagement;", { isPreferred: true });
|
||||
const actions = [
|
||||
using,
|
||||
action("Generate field 'SceneManager' in 'Player'", { kind: null }),
|
||||
action("UnityEngine.SceneManagement.SceneManager", { kind: null }),
|
||||
action("Generate class 'SceneManager'", { kind: null }),
|
||||
];
|
||||
expect(unambiguousImport(actions)).toBe(using);
|
||||
expect(unambiguousImport([action("using static System.Math;")])?.title).toBe("using static System.Math;");
|
||||
});
|
||||
|
||||
it("leaves ambiguous, disabled and non-import fixes alone", () => {
|
||||
expect(unambiguousImport([action("using A.Scenes;"), action("using B.Scenes;")])).toBeNull();
|
||||
expect(
|
||||
unambiguousImport([action("using UnityEngine.SceneManagement;", { disabledReason: "unavailable" })]),
|
||||
).toBeNull();
|
||||
expect(unambiguousImport([action("using UnityEngine.SceneManagement;", { kind: "refactor" })])).toBeNull();
|
||||
expect(unambiguousImport([action("Remove unnecessary usings")])).toBeNull();
|
||||
expect(unambiguousImport([action("UnityEngine.SceneManagement.SceneManager")])).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -16,13 +16,21 @@ import { offsetsToRange, rangeToOffsets } from "./positions";
|
||||
import { featureBackoff } from "./availability";
|
||||
|
||||
const IDLE_MS = 1500;
|
||||
/**
|
||||
* C#'s add-import fix: Roslyn (csharp-ls) titles it with the directive itself,
|
||||
* `using UnityEngine.SceneManagement;`, never with the word "import".
|
||||
*/
|
||||
export const CSHARP_USING_FIX = /^using (?:static )?[\w.]+;$/;
|
||||
const IMPORT_TITLE = /\bimport\b/i;
|
||||
const importBackoff = featureBackoff();
|
||||
|
||||
/** The single import fix among `actions`, if exactly one exists. */
|
||||
export function unambiguousImport(actions: readonly CodeAction[]): CodeAction | null {
|
||||
const imports = actions.filter(
|
||||
(a) => !a.disabledReason && IMPORT_TITLE.test(a.title) && (!a.kind || a.kind.startsWith("quickfix")),
|
||||
(a) =>
|
||||
!a.disabledReason &&
|
||||
(IMPORT_TITLE.test(a.title) || CSHARP_USING_FIX.test(a.title)) &&
|
||||
(!a.kind || a.kind.startsWith("quickfix")),
|
||||
);
|
||||
return imports.length === 1 ? imports[0]! : null;
|
||||
}
|
||||
|
||||
@@ -165,4 +165,23 @@ describe("editor diagnostics in a view", () => {
|
||||
setFileDiagnostics(path, "phpstan", []);
|
||||
setFileDiagnostics(path, "intelephense", []);
|
||||
});
|
||||
|
||||
it("fills a warning's background mark to the full row height", async () => {
|
||||
const path = "/p/warn.ts";
|
||||
const view = new EditorView({
|
||||
state: EditorState.create({
|
||||
doc: "const x = 1;",
|
||||
extensions: [lspDoc.of({ doc: 1, path } as EditorDocContext), diagnosticsExtension()],
|
||||
}),
|
||||
parent: document.body,
|
||||
});
|
||||
setFileDiagnostics(path, "eslint", [d(0, 6, 7, "warning")]);
|
||||
await Promise.resolve();
|
||||
const warning = view.contentDOM.querySelector(".cm-lintRange-warning");
|
||||
expect(warning).not.toBeNull();
|
||||
// The fill needs a paint box as tall as the row: jsdom re-serializes the calc, same value.
|
||||
expect(getComputedStyle(warning as Element).paddingBlock).toBe("calc(0.5 * (1lh - 1em))");
|
||||
view.destroy();
|
||||
setFileDiagnostics(path, "eslint", []);
|
||||
});
|
||||
});
|
||||
@@ -13,6 +13,7 @@ import { commands, ideEventsReady, isTauri, onIdeEvent } from "@/platform/ipc";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { publishLocalDiagnostics } from "@/platform/localDiagnostics";
|
||||
import { intentionsChanged, isLibraryPath, scrollbarMarks, shownAgain, type ScrollbarMark } from "@/editor/api";
|
||||
import { inlineBackground } from "@/editor/core/cm/inlineBg";
|
||||
import { rangeToOffsets } from "./positions";
|
||||
import { lspDoc } from "./lsp";
|
||||
import { showHint } from "./hint";
|
||||
@@ -312,7 +313,7 @@ const diagnosticsSync = ViewPlugin.fromClass(
|
||||
// WebKit drops a `text-decoration` with a style or colour; `-webkit-text-decoration`, set after
|
||||
// it, takes the whole value there.
|
||||
const lintTheme = EditorView.theme({
|
||||
".cm-lintRange": { backgroundImage: "none", paddingBottom: "0" },
|
||||
".cm-lintRange": { backgroundImage: "none", paddingBlock: "0" },
|
||||
".cm-lintRange-error": {
|
||||
textDecoration: "var(--editor-error-decoration, underline wavy var(--danger))",
|
||||
WebkitTextDecoration: "var(--editor-error-decoration, underline wavy var(--danger))",
|
||||
@@ -326,7 +327,9 @@ const lintTheme = EditorView.theme({
|
||||
WebkitTextDecoration: "var(--editor-warning-decoration, underline wavy var(--warning))",
|
||||
fontWeight: "var(--wave-warning-bold, inherit)",
|
||||
fontStyle: "var(--wave-warning-italic, inherit)",
|
||||
backgroundColor: "var(--editor-warning-background, transparent)",
|
||||
// Light schemes paint the warning as a background: fill the whole row like the selection
|
||||
// (inlineBg grows the mark's box to the row and centres a 1lh-capped fill in it).
|
||||
...inlineBackground("var(--editor-warning-background, transparent)"),
|
||||
textDecorationSkipInk: "none",
|
||||
textUnderlineOffset: "3px",
|
||||
},
|
||||
@@ -348,7 +351,7 @@ const lintTheme = EditorView.theme({
|
||||
},
|
||||
".cm-lintRange.cm-lsp-unnecessary": {
|
||||
textDecoration: "none",
|
||||
backgroundColor: "transparent",
|
||||
background: "none",
|
||||
color: "var(--fg-unused, var(--fg-faint))",
|
||||
fontWeight: "var(--fg-unused-bold, inherit)",
|
||||
fontStyle: "var(--fg-unused-italic, inherit)",
|
||||
@@ -369,8 +372,9 @@ const lintTheme = EditorView.theme({
|
||||
textDecoration: "var(--editor-warning-decoration, underline wavy var(--warning))",
|
||||
WebkitTextDecoration: "var(--editor-warning-decoration, underline wavy var(--warning))",
|
||||
},
|
||||
// The active warning keeps its fill: it is an image now, which the transparent colour below
|
||||
// does not touch.
|
||||
".cm-lintRange-active": { backgroundColor: "transparent" },
|
||||
".cm-lintRange-warning.cm-lintRange-active": { backgroundColor: "var(--editor-warning-background, transparent)" },
|
||||
".cm-lintPoint:after": { display: "none" },
|
||||
});
|
||||
|
||||
|
||||
@@ -151,6 +151,8 @@ describe("paste import selection", () => {
|
||||
"Import `std::collections::HashMap`",
|
||||
'Add import: "fmt"',
|
||||
"Add 'useState' to existing import declaration from 'react'",
|
||||
"using UnityEngine.SceneManagement;",
|
||||
"using static System.Math;",
|
||||
])("recognizes the import quick fix %s", (title) => {
|
||||
expect(pastedImport([action({ title }), action({ title: "Create class ArrayList" })])?.title).toBe(title);
|
||||
});
|
||||
@@ -165,6 +167,8 @@ describe("paste import selection", () => {
|
||||
{ title: "Remove unused import" },
|
||||
{ title: "Import all missing names" },
|
||||
{ title: "Optimize imports" },
|
||||
{ title: "UnityEngine.SceneManagement.SceneManager" },
|
||||
{ title: "Remove unnecessary usings" },
|
||||
])
|
||||
expect(pastedImport([action(over)])).toBeNull();
|
||||
expect(pastedImport([action({ isPreferred: true }), action({ title: "Import 'ArrayList' (other)" })])).toBeNull();
|
||||
|
||||
@@ -11,6 +11,7 @@ import { docOf, lspRequest } from "./lsp";
|
||||
import { comparePos, rangeToOffsets } from "./positions";
|
||||
import { closePopup, openPopup, useLspPopup, type LspPopup } from "./popupStore";
|
||||
import { actionsForDiagnostic } from "./intentions";
|
||||
import { CSHARP_USING_FIX } from "./autoImport";
|
||||
|
||||
const WAIT_MS = 8000;
|
||||
const SETTLE_MS = 200;
|
||||
@@ -47,7 +48,7 @@ export function pastedImport(actions: readonly CodeAction[]): CodeAction | null
|
||||
(a) =>
|
||||
a.disabledReason == null &&
|
||||
(!a.kind || a.kind === "quickfix" || a.kind.startsWith("quickfix.")) &&
|
||||
IMPORT_FIX.test(a.title) &&
|
||||
(IMPORT_FIX.test(a.title) || CSHARP_USING_FIX.test(a.title)) &&
|
||||
!/^import (?:all|missing)\b/i.test(a.title),
|
||||
);
|
||||
return imports.length === 1 ? imports[0]! : null;
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { Marked } from "marked";
|
||||
import DOMPurify from "dompurify";
|
||||
import { mathExtension, renderMath } from "./markdownMath";
|
||||
import { mathExtension } from "./markdownMath";
|
||||
import { renderMath } from "./renderMarkdownMath";
|
||||
|
||||
const marked = new Marked({ gfm: true, breaks: false }).use(mathExtension());
|
||||
|
||||
|
||||
@@ -6,9 +6,6 @@
|
||||
* placeholders, which survive `DOMPurify` (with `data-math` allowed) and are
|
||||
* rendered synchronously into KaTeX DOM by `renderMath()` right after sanitization.
|
||||
*/
|
||||
import katex from "katex";
|
||||
import "katex/dist/katex.min.css";
|
||||
import "./markdownMath.css";
|
||||
import type { MarkedExtension, Tokens } from "marked";
|
||||
|
||||
interface MathToken extends Tokens.Generic {
|
||||
@@ -210,20 +207,3 @@ export function mathExtension(): MarkedExtension {
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
/** Renders every `[data-math]` placeholder inside `root` synchronously using KaTeX. */
|
||||
export function renderMath(root: ParentNode): void {
|
||||
root.querySelectorAll<HTMLElement>("[data-math]").forEach((el) => {
|
||||
const mode = el.getAttribute("data-math");
|
||||
el.removeAttribute("data-math");
|
||||
if (mode !== "inline" && mode !== "display") return;
|
||||
const tex = (el.textContent ?? "").trim();
|
||||
if (!tex) return;
|
||||
katex.render(tex, el, {
|
||||
displayMode: mode === "display",
|
||||
throwOnError: false,
|
||||
strict: false,
|
||||
trust: false,
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -1,7 +1,8 @@
|
||||
/** Markdown → sanitized HTML (marked + DOMPurify); loaded on demand by `markdown.ts`. */
|
||||
import { Marked } from "marked";
|
||||
import DOMPurify from "dompurify";
|
||||
import { mathExtension, renderMath } from "./markdownMath";
|
||||
import { mathExtension } from "./markdownMath";
|
||||
import { renderMath } from "./renderMarkdownMath";
|
||||
|
||||
/** DOMPurify's default link schemes plus `file:` and jdtls' `jdt:` (library classes). */
|
||||
const ALLOWED_URI = /^(?:(?:(?:f|ht)tps?|mailto|tel|file|jdt):|[^a-z]|[a-z+.-]+(?:[^a-z+.\-:]|$))/i;
|
||||
|
||||
@@ -25,3 +25,16 @@ it("draws the ⌘-hover info as a popup in a view without the editor theme", ()
|
||||
expect(style.borderRadius).toBe("var(--radius-popup-large)");
|
||||
expect(style.overflow).toBe("visible");
|
||||
});
|
||||
|
||||
it("fills the Ctrl-hover link's hover box to the full row height", () => {
|
||||
view = new EditorView({
|
||||
state: EditorState.create({ extensions: [lspTheme] }),
|
||||
parent: document.body,
|
||||
});
|
||||
const link = document.createElement("span");
|
||||
link.className = "cm-lsp-link";
|
||||
view.dom.appendChild(link);
|
||||
// The cursor is only over the mark's box, so the box has to reach the row's gap:
|
||||
// jsdom re-serializes the calc, same value.
|
||||
expect(getComputedStyle(link).paddingBlock).toBe("calc(0.5 * (1lh - 1em))");
|
||||
});
|
||||
@@ -0,0 +1,20 @@
|
||||
import katex from "katex";
|
||||
import "katex/dist/katex.min.css";
|
||||
import "./markdownMath.css";
|
||||
|
||||
/** Renders every `[data-math]` placeholder inside `root` synchronously using KaTeX. */
|
||||
export function renderMath(root: ParentNode): void {
|
||||
root.querySelectorAll<HTMLElement>("[data-math]").forEach((el) => {
|
||||
const mode = el.getAttribute("data-math");
|
||||
el.removeAttribute("data-math");
|
||||
if (mode !== "inline" && mode !== "display") return;
|
||||
const tex = (el.textContent ?? "").trim();
|
||||
if (!tex) return;
|
||||
katex.render(tex, el, {
|
||||
displayMode: mode === "display",
|
||||
throwOnError: false,
|
||||
strict: false,
|
||||
trust: false,
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
/** Editor-side styling for LSP features (CodeMirror theme; tokens only). */
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import {
|
||||
FULL_ROW_PADDING,
|
||||
inlineBackground,
|
||||
inlineFramedFallback,
|
||||
inlineFramedModern,
|
||||
@@ -428,6 +429,9 @@ export const lspTheme = EditorView.theme({
|
||||
WebkitTextFillColor: "currentcolor",
|
||||
textDecoration: "underline",
|
||||
textUnderlineOffset: "2px",
|
||||
// The pointer cursor only applies over the mark's box: grow the box to the row so the
|
||||
// gap above and below the font hovers (and clicks, via posAtCoords) as the link too.
|
||||
paddingBlock: FULL_ROW_PADDING,
|
||||
cursor: "pointer",
|
||||
},
|
||||
".cm-lsp-occurrence, .cm-lsp-occurrence-tail": {
|
||||
|
||||
@@ -754,7 +754,7 @@ export function AgentsView() {
|
||||
<div className={styles.empty}>{externalError}</div>
|
||||
) : (
|
||||
<div className={styles.external}>
|
||||
{external.map((s) => {
|
||||
{external.slice(0, 50).map((s) => {
|
||||
const key = externalKey(s.provider, s.sessionId);
|
||||
return (
|
||||
<div key={key} className={styles.row} title={s.cwd ?? s.sessionId}>
|
||||
|
||||
@@ -16,7 +16,7 @@ import {
|
||||
} from "./store";
|
||||
import styles from "./Agents.module.css";
|
||||
|
||||
/** The backend lists at most this many sessions, newest first. */
|
||||
/** At most this many matching sessions are shown at once, newest first. */
|
||||
const LISTED_MAX = 50;
|
||||
const ROW = 24;
|
||||
|
||||
@@ -74,7 +74,7 @@ function ImportSessionsDialog() {
|
||||
const [frozen, setFrozen] = useState<Row[] | null>(null);
|
||||
const abort = useRef<AbortController | null>(null);
|
||||
|
||||
const rows = useMemo<Row[]>(() => {
|
||||
const matched = useMemo<Row[]>(() => {
|
||||
const q = query.trim().toLowerCase();
|
||||
return external
|
||||
.map((s) => ({
|
||||
@@ -87,8 +87,15 @@ function ImportSessionsDialog() {
|
||||
updatedMs: s.updatedMs ?? 0,
|
||||
}))
|
||||
.filter((r) => !importing.has(r.key))
|
||||
.filter((r) => !q || r.title.toLowerCase().includes(q) || r.folder.toLowerCase().includes(q));
|
||||
.filter(
|
||||
(r) =>
|
||||
!q ||
|
||||
r.title.toLowerCase().includes(q) ||
|
||||
r.folder.toLowerCase().includes(q) ||
|
||||
r.sessionId.toLowerCase().includes(q),
|
||||
);
|
||||
}, [external, importing, query, root]);
|
||||
const rows = useMemo(() => matched.slice(0, LISTED_MAX), [matched]);
|
||||
const view = frozen ?? rows;
|
||||
|
||||
// The lead is drawn as selected: keep it on a selected row the list still shows, else on none.
|
||||
@@ -192,7 +199,7 @@ function ImportSessionsDialog() {
|
||||
? tx`Forking ${Math.min(progress.done + 1, progress.total)} of ${progress.total}…`
|
||||
: tx`Importing ${Math.min(progress.done + 1, progress.total)} of ${progress.total}…`}
|
||||
</span>
|
||||
) : shown && external.length >= LISTED_MAX ? (
|
||||
) : shown && matched.length > LISTED_MAX ? (
|
||||
<span className={styles.chooserHint}>
|
||||
<T>Only the 50 most recent sessions are shown.</T>
|
||||
</span>
|
||||
|
||||
Loaded 100 of 158 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Заблокувати користувача