Порівняти коміти

..
Автор SHA1 Повідомлення Дата
l0ng-ai c3e0b8bd58 fix(vcs): stop rescanning the file per hunk when opening large diffs
Opening a working-tree diff from the commit panel computes a key for
every hunk (hunkKeys). Each key called currentHunkText, which rebuilt the
line-start table of the whole file, so a file with many changes cost
hunks x file size: a 9.4 MB JSON with 17,931 changes kept the web view
busy for minutes and froze the window.

rollbackEdit and currentHunkText now take an optional precomputed
lineStarts table. hunkKeys builds it once. The other per-hunk loops pass
theirs too: line-level partial commits (commitSelection), the partial
commit projection, the commit-check rollback fallback, and stage/unstage
from the gutter.
2026-12-01 06:25:35 +08:00
218 змінених файлів з 834 додано та 7817 видалено

No files matched your search

+1 -2
Переглянути файл
@@ -34,7 +34,6 @@ 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"
@@ -110,7 +109,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|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$)'
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$)'
langs=""
while read -r f; do
case "$f" in
Створено
-1
Переглянути файл
@@ -4173,7 +4173,6 @@ dependencies = [
"serde_json",
"sha1 0.10.7",
"specta",
"sqlx",
"tempfile",
"tokio",
"toml 0.9.12+spec-1.1.0",
+1 -1
Переглянути файл
@@ -71,7 +71,7 @@ the [official plugins](plugins/official). The plugin API is still a preview.
## Community
- [Discord](https://discord.gg/AsZqMgxZm) — questions, feedback and release news.
- [Discord](https://discord.gg/2Zy4yn7gP) — questions, feedback and release news.
- WeChat group — scan to join:
<img src=".github/assets/wechat-group-4.png" alt="WeChat group QR code" width="200">
+1 -1
Переглянути файл
@@ -71,7 +71,7 @@ Eklentileri Ayarlar › Eklentiler (Settings › Plugins) bölümünden kur ya d
## Topluluk
- [Discord](https://discord.gg/AsZqMgxZm): sorular, geri bildirim ve sürüm haberleri.
- [Discord](https://discord.gg/2Zy4yn7gP): sorular, geri bildirim ve sürüm haberleri.
- WeChat grubu, katılmak için kodu okut:
<img src=".github/assets/wechat-group-4.png" alt="WeChat grubu QR kodu" width="200">
+1 -1
Переглянути файл
@@ -69,7 +69,7 @@ WebAssembly 组件运行;主题、图标主题和语言无需编写代码。
## 社区
- [Discord](https://discord.gg/AsZqMgxZm):提问、反馈和版本发布消息。
- [Discord](https://discord.gg/2Zy4yn7gP):提问、反馈和版本发布消息。
- 微信群,扫码加入:
<img src=".github/assets/wechat-group-4.png" alt="微信群二维码" width="200">
-1
Переглянути файл
@@ -18,7 +18,6 @@ ide-tools = { path = "../ide-tools" }
serde.workspace = true
serde_json.workspace = true
specta.workspace = true
sqlx.workspace = true
tokio.workspace = true
toml.workspace = true
tracing.workspace = true
+40 -306
Переглянути файл
@@ -27,9 +27,6 @@ pub struct ExternalSession {
pub cwd: Option<String>,
/// File modification time, ms since the epoch.
pub updated_ms: f64,
/// Another live process (VS Code, a terminal Copilot CLI) has it open: importing would let two
/// apps write the same session, so forking a copy is the safe choice.
pub in_use: bool,
}
/// Modification time of `path` in ms, else 0.
@@ -127,7 +124,6 @@ pub fn claude_sessions(config_dir: &Path, root: &Path) -> Vec<ExternalSession> {
title,
cwd,
updated_ms: mtime(&path),
in_use: false,
});
}
}
@@ -198,7 +194,6 @@ fn codex_file(path: &Path) -> Option<ExternalSession> {
session_id,
cwd,
updated_ms: mtime(path),
in_use: false,
})
}
@@ -252,71 +247,35 @@ 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('"') {
/// One scalar at the root of Copilot's `workspace.yaml`.
///
/// Copilot writes a flat mapping of scalar values. Most values are plain, while names can
/// be JSON-compatible double-quoted YAML strings (including `\n`).
fn yaml_scalar(line: &str) -> Option<(String, String)> {
let (key, raw) = line.split_once(':')?;
let key = key.trim();
let raw = raw.trim();
if key.is_empty() || raw.is_empty() || line.starts_with(char::is_whitespace) {
return None;
}
let value = 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()
}
};
Some((key.to_owned(), value))
}
/// 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));
}
}
let metadata = std::io::BufReader::new(file)
.lines()
.map_while(Result::ok)
.filter_map(|line| yaml_scalar(&line))
.collect::<HashMap<_, _>>();
(!metadata.is_empty()).then_some(metadata)
}
@@ -337,160 +296,11 @@ fn copilot_prompt(path: &Path) -> Option<String> {
})
}
/// Candidate VS Code Agent Host SQLite databases (`<user>/globalStorage/agent-host.db`),
/// ordered oldest-first so a newer database wins when two editions share a session.
fn vscode_agent_host_dbs(home: &Path) -> Vec<PathBuf> {
let mut bases = vec![home.join("Library/Application Support"), home.join(".config"), home.join("AppData/Roaming")];
let real_home = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE"));
if real_home.as_deref().is_some_and(|h| Path::new(h) == home) {
for var in ["XDG_CONFIG_HOME", "APPDATA"] {
if let Some(dir) = std::env::var_os(var).filter(|v| !v.is_empty()).map(PathBuf::from)
&& !bases.contains(&dir)
{
bases.push(dir);
}
}
}
let mut dbs = Vec::new();
for base in bases {
for app in ["Code", "Code - Insiders"] {
dbs.push(base.join(app).join("User/globalStorage/agent-host.db"));
}
}
for server in [".vscode-server", ".vscode-server-insiders"] {
dbs.push(home.join(server).join("data/User/globalStorage/agent-host.db"));
}
dbs.retain(|p| p.is_file());
dbs.sort_by(|a, b| mtime(a).total_cmp(&mtime(b)));
dbs
}
fn is_generic_vscode_placeholder(title: &str, source: Option<&str>) -> bool {
source != Some("user") && (title.eq_ignore_ascii_case("new session") || title.eq_ignore_ascii_case("new chat"))
}
fn pick_vscode_chat_title(
scs_title: Option<&str>,
scs_source: Option<&str>,
metadata_json: Option<&str>,
payload_json: Option<&str>,
) -> Option<String> {
if let Some(t) = scs_title.map(str::trim).filter(|t| !t.is_empty())
&& !is_generic_vscode_placeholder(t, scs_source)
{
return Some(t.to_owned());
}
for blob in [metadata_json, payload_json].into_iter().flatten() {
let Ok(v) = serde_json::from_str::<serde_json::Value>(blob) else { continue };
let summary = v.pointer("/data/summary").and_then(serde_json::Value::as_str).map(str::trim);
let source = v.pointer("/data/titleSource").and_then(serde_json::Value::as_str);
if let Some(t) = summary.filter(|t| !t.is_empty())
&& !is_generic_vscode_placeholder(t, source)
{
return Some(t.to_owned());
}
}
None
}
/// The rows of one `agent-host.db` that map a backing Copilot session (`sdkSessionId`) to its
/// title. Read through a read-only connection that sets no `journal_mode` or other write pragma,
/// so VS Code's database is never changed. An unknown schema (a newer VS Code) reads nothing.
async fn read_vscode_chat_rows(path: &Path) -> Vec<[Option<String>; 5]> {
use sqlx::{Connection, Row};
const FULL_QUERY: &str = "\
SELECT c.provider_data, scs.title, scs.title_source, c.metadata, s.payload \
FROM chats_v2 c \
LEFT JOIN session_chat_state scs \
ON scs.session_uri = c.owner_session_uri AND scs.chat_uri = c.chat_uri \
LEFT JOIN sessions_v2 s \
ON s.session_uri = c.owner_session_uri \
WHERE c.tombstoned = 0 \
ORDER BY COALESCE(s.modified_time, 0) ASC, COALESCE(c.chat_order, 0) ASC";
const FALLBACK_QUERY: &str = "SELECT provider_data, NULL, NULL, metadata, NULL FROM chats_v2 WHERE tombstoned = 0";
let options = sqlx::sqlite::SqliteConnectOptions::new()
.filename(path)
.read_only(true)
.create_if_missing(false)
.busy_timeout(std::time::Duration::from_millis(200));
let Ok(mut conn) = sqlx::SqliteConnection::connect_with(&options).await else { return Vec::new() };
let rows = match sqlx::query(FULL_QUERY).fetch_all(&mut conn).await {
Ok(rows) => rows,
Err(_) => sqlx::query(FALLBACK_QUERY).fetch_all(&mut conn).await.unwrap_or_default(),
};
let _ = conn.close().await;
rows.iter().map(|row| std::array::from_fn(|i| row.try_get::<Option<String>, _>(i).ok().flatten())).collect()
}
/// Session titles VS Code's Agent Host (`vscode-agent-host`) assigns to backing Copilot CLI
/// sessions (`sdkSessionId` → summary or user rename). VS Code keeps these in its own
/// `agent-host.db` rather than in Copilot's `workspace.yaml`, so without them a renamed chat
/// would be listed under its first prompt. Best-effort: any failure leaves the CLI titles.
fn vscode_copilot_titles(home: Option<&Path>) -> HashMap<String, String> {
let Some(home) = home else { return HashMap::new() };
let dbs = vscode_agent_host_dbs(home);
if dbs.is_empty() {
return HashMap::new();
}
// Callers are sync and may run on a runtime thread or none: a private runtime on its own
// thread works from either without blocking a runtime worker.
let rows: Vec<[Option<String>; 5]> = std::thread::scope(|scope| {
scope
.spawn(|| {
let Ok(rt) = tokio::runtime::Builder::new_current_thread().enable_all().build() else {
return Vec::new();
};
rt.block_on(async {
let mut all = Vec::new();
for path in &dbs {
all.extend(read_vscode_chat_rows(path).await);
}
all
})
})
.join()
.unwrap_or_default()
});
let mut titles = HashMap::new();
for [pdata, scs_title, scs_source, metadata, payload] in rows {
let Some(pdata) = pdata else { continue };
let Ok(pv) = serde_json::from_str::<serde_json::Value>(&pdata) else { continue };
let Some(sdk_id) = pv.get("sdkSessionId").and_then(serde_json::Value::as_str).filter(|s| !s.is_empty()) else {
continue;
};
if let Some(title) =
pick_vscode_chat_title(scs_title.as_deref(), scs_source.as_deref(), metadata.as_deref(), payload.as_deref())
{
titles.insert(sdk_id.to_owned(), title);
}
}
titles
}
/// Whether a live process holds the Copilot session in `dir`. Copilot writes `inuse.<pid>.lock`
/// while a CLI or SDK host (such as VS Code) has the session open; a crash leaves a stale one,
/// so only a lock whose process still runs counts.
fn copilot_session_in_use(dir: &Path) -> bool {
std::fs::read_dir(dir).into_iter().flatten().flatten().any(|entry| {
let name = entry.file_name();
let Some(pid) = name
.to_str()
.and_then(|n| n.strip_prefix("inuse."))
.and_then(|n| n.strip_suffix(".lock"))
.and_then(|n| n.parse::<u32>().ok())
else {
return false;
};
ide_core::process::process_alive(pid)
})
}
/// Copilot sessions of the project at `root`: `<config>/session-state/<id>`, titled by VS Code's
/// Agent Host summary/rename (when started from VS Code), their recorded CLI name, or first prompt.
/// Directories without an event log are unfinished sessions and are not listed.
pub fn copilot_sessions(copilot_home: &Path, home: Option<&Path>, root: &Path) -> Vec<ExternalSession> {
let mut pending: Vec<(ExternalSession, bool)> = std::fs::read_dir(copilot_home.join("session-state"))
/// Copilot sessions of the project at `root`: `<config>/session-state/<id>`, titled by
/// their recorded name or first prompt. Directories without an event log are unfinished
/// sessions and are not listed.
pub fn copilot_sessions(copilot_home: &Path, root: &Path) -> Vec<ExternalSession> {
std::fs::read_dir(copilot_home.join("session-state"))
.into_iter()
.flatten()
.flatten()
@@ -506,33 +316,17 @@ pub fn copilot_sessions(copilot_home: &Path, home: Option<&Path>, root: &Path) -
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
let title = metadata
.get("name")
.map(String::as_str)
.map(str::trim)
.filter(|name| !name.is_empty())
.map(short)
.or_else(|| copilot_prompt(&events))
.unwrap_or_else(|| format!("Copilot session {}", &session_id[..session_id.len().min(8)]));
let session = ExternalSession {
provider: "copilot".to_owned(),
session_id,
title,
cwd,
updated_ms: mtime(&events),
in_use: copilot_session_in_use(&dir),
};
Some((session, cli_user_named))
Some(ExternalSession { provider: "copilot".to_owned(), session_id, title, cwd, updated_ms: mtime(&events) })
})
.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()
.collect()
}
#[cfg(test)]
@@ -633,26 +427,13 @@ mod tests {
let tmp = tempfile::tempdir().unwrap();
assert!(claude_sessions(&tmp.path().join("nope"), Path::new("/work")).is_empty());
assert!(codex_sessions(&tmp.path().join("nope"), Path::new("/work")).is_empty());
assert!(copilot_sessions(&tmp.path().join("nope"), None, Path::new("/work")).is_empty());
}
fn exec_sqlite(path: &Path, sql: &'static str) {
use sqlx::Connection;
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
rt.block_on(async {
let options = sqlx::sqlite::SqliteConnectOptions::new().filename(path).create_if_missing(true);
let mut conn = sqlx::SqliteConnection::connect_with(&options).await.unwrap();
sqlx::raw_sql(sql).execute(&mut conn).await.unwrap();
conn.close().await.unwrap();
});
assert!(copilot_sessions(&tmp.path().join("nope"), Path::new("/work")).is_empty());
}
#[test]
fn lists_copilot_sessions_with_names_block_scalars_vscode_titles_and_prompt_fallbacks() {
fn lists_copilot_sessions_with_names_and_prompt_fallbacks() {
let tmp = tempfile::tempdir().unwrap();
let copilot_home = tmp.path().join(".copilot");
let session = copilot_home.join("session-state/copilot-1");
let session = tmp.path().join("session-state/copilot-1");
write(
&session.join("events.jsonl"),
&[
@@ -666,78 +447,31 @@ mod tests {
)
.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");
let unnamed = tmp.path().join("session-state/copilot-2");
write(
&unnamed.join("events.jsonl"),
&[json!({"type": "user.message", "data": {"content": "add a regression test"}})],
);
std::fs::write(unnamed.join("workspace.yaml"), "id: copilot-2\ncwd: /work/app\n").unwrap();
// A live holder marks the session in use; a lock left by a process that exited does not.
std::fs::write(session.join(format!("inuse.{}.lock", std::process::id())), "").unwrap();
std::fs::write(unnamed.join("inuse.2147483646.lock"), "").unwrap();
let empty = copilot_home.join("session-state/copilot-empty");
let empty = tmp.path().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");
let other = tmp.path().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 sessions = copilot_sessions(tmp.path(), Path::new("/work"));
assert_eq!(sessions.len(), 2);
let mut by_id: HashMap<_, _> = sessions.into_iter().map(|s| (s.session_id.clone(), s)).collect();
let named = by_id.remove("copilot-1").unwrap();
assert_eq!((named.provider.as_str(), named.title.as_str()), ("copilot", "Fix parser and tests"));
assert_eq!(named.cwd.as_deref(), Some("/work/app/api"));
assert!(named.in_use);
assert_eq!(by_id.remove("copilot-block").unwrap().title, "check why excalidraw font is not displayed");
assert_eq!(by_id.remove("copilot-vscode").unwrap().title, "Session");
assert_eq!(by_id.remove("copilot-placeholder").unwrap().title, "Greeting exchange");
let unnamed = by_id.remove("copilot-2").unwrap();
assert_eq!(unnamed.title, "add a regression test");
assert!(!unnamed.in_use);
assert_eq!(by_id.remove("copilot-2").unwrap().title, "add a regression test");
}
#[test]
+40 -76
Переглянути файл
@@ -1415,11 +1415,12 @@ impl AgentManager {
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));
out.extend(external::copilot_sessions(&dir, &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
}
@@ -2050,63 +2051,46 @@ impl AgentManager {
return Err(IdeError::invalid("wait until the agent is done"));
}
let epoch = self.shared.shutdown_epoch();
// A Codex fork must be opened by its own task: the creating app-server owns its writer.
// It can also fork a recorded thread whose writer is held by another process.
let codex_source = {
let s = source.state.lock();
(s.task.provider == "codex").then(|| s.session_id.clone()).flatten()
};
let live = if codex_source.is_none() {
Some(source.ensure_session(epoch).await.map_err(IdeError::internal)?)
} else {
None
};
let live = source.ensure_session(epoch).await.map_err(IdeError::internal)?;
let total = turn_starts(&source.state.lock().history.conversation.main.entries).len() as u32;
let keep = turns.unwrap_or(total).min(total);
let capabilities = live.as_ref().map(|l| l.capabilities).unwrap_or(source.state.lock().task.capabilities);
if !capabilities.fork || (keep < total && !capabilities.rollback) {
if !live.capabilities.fork || (keep < total && !live.capabilities.rollback) {
return Err(IdeError::invalid("this agent can't copy a conversation from there"));
}
let session = if let Some(live) = &live {
let (cwd, provider_id, mcp_overrides, project_root) = {
let s = source.state.lock();
let t = &s.task;
(t.cwd.0.clone(), t.provider.clone(), t.mcp_overrides.clone(), t.project_root.clone().map(|p| p.0))
};
let mcp_servers = source.shared.mcp_servers_for_session(&provider_id, &live.init, &mcp_overrides);
let roots = source.shared.additional_directories(&live.init, &cwd, project_root.as_deref());
let skills_delivery = source.stage_skills(stage_key(live.driver), &cwd).await;
let memory_delivery = source.stage_memory(&provider_id, &cwd).await;
let cwd_s = dunce::canonicalize(&cwd).unwrap_or(cwd).to_string_lossy().into_owned();
let reply: Value = live
.peer
.request(
"session/fork",
{
let mut params = session_params(
&cwd_s,
&mcp_servers,
skills_delivery.as_ref(),
memory_delivery.as_ref(),
&roots,
);
params["sessionId"] = json!(live.session);
params
},
None,
)
.await
.map_err(|e| IdeError::internal(source.describe(e)))?;
Some(
reply
.get("sessionId")
.and_then(Value::as_str)
.ok_or_else(|| IdeError::internal("the agent returned no session"))?
.to_owned(),
)
} else {
None
let (cwd, provider_id, mcp_overrides, project_root) = {
let s = source.state.lock();
let t = &s.task;
(t.cwd.0.clone(), t.provider.clone(), t.mcp_overrides.clone(), t.project_root.clone().map(|p| p.0))
};
let mcp_servers = source.shared.mcp_servers_for_session(&provider_id, &live.init, &mcp_overrides);
let roots = source.shared.additional_directories(&live.init, &cwd, project_root.as_deref());
let skills_delivery = source.stage_skills(stage_key(live.driver), &cwd).await;
let memory_delivery = source.stage_memory(&provider_id, &cwd).await;
let cwd_s = dunce::canonicalize(&cwd).unwrap_or(cwd).to_string_lossy().into_owned();
let reply: Value = live
.peer
.request(
"session/fork",
{
let mut params = session_params(
&cwd_s,
&mcp_servers,
skills_delivery.as_ref(),
memory_delivery.as_ref(),
&roots,
);
params["sessionId"] = json!(live.session);
params
},
None,
)
.await
.map_err(|e| IdeError::internal(source.describe(e)))?;
let session = reply
.get("sessionId")
.and_then(Value::as_str)
.ok_or_else(|| IdeError::internal("the agent returned no session"))?
.to_owned();
let file = {
let s = source.state.lock();
let mut entries = s.history.conversation.main.entries.clone();
@@ -2132,7 +2116,7 @@ impl AgentManager {
};
TaskFile {
task,
session_id: session,
session_id: Some(session),
entries,
wanted: s.wanted.clone(),
pending_model: None,
@@ -2147,19 +2131,12 @@ impl AgentManager {
pending_rollback: total - keep,
title_renamed: s.title_renamed,
ephemeral: s.ephemeral,
pending_native_fork: codex_source.map(|source| ForkStart { source, target: None }),
pending_native_fork: None,
}
};
// Copying may have started the source's agent: it stops again once idle.
if live.is_some() {
source.release_when_idle();
}
source.release_when_idle();
let task = Task::restore(file, self.shared.clone());
if live.is_none() {
// Establish the fork before returning so its snapshot cannot drift while the source continues.
task.ensure_session(epoch).await.map_err(IdeError::internal)?;
task.release_when_idle();
}
self.tasks.write().insert(task.id.clone(), task.clone());
task.persist();
task.emit_task();
@@ -4973,19 +4950,6 @@ impl Task {
if let Some(message) = self.sign_in_error(&e, Some(&sign_in_message)) {
return Err(SessionOpenError { message, allow_acp_fallback: false });
}
// A writer conflict is temporary: retrying must retain the original session ID.
if spec.driver == provider::Driver::Codex
&& matches!(&e, RpcError::Server { message, .. } if message.contains("already has an active writer"))
{
return Err(SessionOpenError {
message: format!(
"Couldn't reopen this conversation's {} session: {}",
spec.name,
self.describe(e)
),
allow_acp_fallback: false,
});
}
if pending_model.is_some() {
return Err(SessionOpenError {
message: format!(
+1 -1
Переглянути файл
@@ -730,7 +730,7 @@ impl CopilotShim {
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);
tracing::info!("copilot session {session_id}: could not load history: {}", error.message);
return;
}
};
-35
Переглянути файл
@@ -2191,41 +2191,6 @@ async fn a_session_that_fails_to_load_is_reported_and_replaced_only_when_sent_ag
assert_eq!(calls(&agent), ["session/load", "session/new", "session/prompt"]);
}
/// A locked Codex recording can be forked without resuming it or moving its writer between tasks.
#[tokio::test(flavor = "multi_thread")]
async fn codex_writer_conflict_can_retry_or_fork_on_a_new_connection() {
let tmp = tempfile::tempdir().unwrap();
let task = {
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
let task = mgr
.create(NewAgentTask { prompt: text("again"), provider: "codex".into(), ..Default::default() })
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
mgr.shutdown();
task
};
let agent = Arc::new(FakeAgent {
load_error: Some((codes::INVALID_PARAMS, "thread s1 already has an active writer".into())),
..Default::default()
});
let mgr = manager(tmp.path(), agent.clone());
for _ in 0..2 {
mgr.prompt(&task.id, text("again"), false).await.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Failed).await;
}
assert!(!agent.calls.lock().iter().any(|c| c == "session/new"));
let copy = mgr.fork(&task.id, None).await.unwrap();
assert_eq!(agent.forks.lock().last().unwrap()["sessionId"], "s1");
let copy_handle = mgr.task(&copy.id).unwrap();
assert_eq!(copy_handle.live.lock().as_ref().unwrap().session, "s2");
let loads = agent.calls.lock().iter().filter(|c| *c == "session/load").count();
mgr.prompt(&copy.id, text("again"), false).await.unwrap();
wait_for(&mgr, &copy.id, AgentStatus::Ready).await;
assert_eq!(agent.calls.lock().iter().filter(|c| *c == "session/load").count(), loads);
mgr.shutdown();
}
fn text(t: &str) -> AgentPrompt {
AgentPrompt { text: t.into(), ..AgentPrompt::default() }
}
-53
Переглянути файл
@@ -622,30 +622,6 @@ 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> {
@@ -1264,35 +1240,6 @@ 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(
-26
Переглянути файл
@@ -530,7 +530,6 @@ pub struct DebuggerSettings {
/// Java: whether to reload changed classes into running debug sessions after compilation.
pub hot_swap_after_compile: HotSwapPolicy,
pub python: PythonDebuggerSettings,
pub cpp: CppDebuggerSettings,
}
impl Default for DebuggerSettings {
@@ -553,7 +552,6 @@ impl Default for DebuggerSettings {
flutter_hot_reload_on_save: true,
hot_swap_after_compile: HotSwapPolicy::Ask,
python: PythonDebuggerSettings::default(),
cpp: CppDebuggerSettings::default(),
}
}
}
@@ -572,14 +570,6 @@ impl Default for PythonDebuggerSettings {
}
}
/// C/C++ debugger executables. Empty paths use automatic discovery.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct CppDebuggerSettings {
pub gdb_executable: String,
pub lldb_dap_executable: String,
}
/// Run/Debug configuration behaviour.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
@@ -626,8 +616,6 @@ pub struct TerminalSettings {
pub close_on_exit: bool,
pub mouse_reporting: bool,
pub copy_on_selection: bool,
/// Programs may set the clipboard with OSC 52 (tmux, Neovim, TUIs over SSH); never read it.
pub osc52_clipboard: bool,
pub paste_on_middle_click: bool,
/// Right-click pastes instead of opening the context menu (Ctrl or Shift + right-click still opens it).
pub right_click_paste: bool,
@@ -668,7 +656,6 @@ impl Default for TerminalSettings {
close_on_exit: true,
mouse_reporting: true,
copy_on_selection: false,
osc52_clipboard: true,
paste_on_middle_click: true,
right_click_paste: false,
override_ide_shortcuts: true,
@@ -813,17 +800,4 @@ mod tests {
assert_eq!(serialized["hotSwapAfterCompile"], raw);
}
}
#[test]
fn cpp_debugger_paths_default_to_empty_and_roundtrip() {
let missing: DebuggerSettings = serde_json::from_str("{}").unwrap();
assert!(missing.cpp.gdb_executable.is_empty());
assert!(missing.cpp.lldb_dap_executable.is_empty());
let cpp = serde_json::json!({"gdbExecutable": "tools/gdb-16", "lldbDapExecutable": "/opt/llvm/bin/lldb-dap"});
let settings: DebuggerSettings = serde_json::from_value(serde_json::json!({"cpp": cpp})).unwrap();
assert_eq!(settings.cpp.gdb_executable, "tools/gdb-16");
assert_eq!(settings.cpp.lldb_dap_executable, "/opt/llvm/bin/lldb-dap");
assert_eq!(serde_json::to_value(&settings).unwrap()["cpp"], cpp);
}
}
+10 -95
Переглянути файл
@@ -360,46 +360,9 @@ 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`. Elsewhere lldb-dap may carry its LLVM version.
/// lldb-dap without putting it on `PATH`.
pub fn resolve_binary(command: &str, cwd: &Path) -> Option<PathBuf> {
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)
find_binary(command, cwd).or_else(|| xcrun_tool(command, cwd))
}
/// `cwd`, inside a project, picks the project's Xcode (`DEVELOPER_DIR`).
@@ -509,7 +472,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".
pub(crate) const GDB_MIN_MAJOR: u32 = 14;
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
@@ -550,29 +513,24 @@ 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(env, cwd) {
if let Some(path) = adapter_path(&spec.env, &spec.cwd) {
probe.env("PATH", path);
}
probe.current_dir(cwd);
probe.current_dir(&spec.cwd);
ide_core::process::prepare(probe.as_std_mut());
let probe = probe
.arg("--version")
.envs(env.iter().cloned())
.envs(spec.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 None;
return Ok(None);
};
parse_gdb_version(&String::from_utf8_lossy(&out.stdout))
Ok(parse_gdb_version(&String::from_utf8_lossy(&out.stdout)))
}
/// Refuse old GDB versions and report whether launch must follow configurationDone.
@@ -585,9 +543,8 @@ async fn prepare_gdb(spec: &AdapterSpec, binary: &Path) -> IdeResult<bool> {
return Ok(major == 15);
}
let mut msg = format!(
"debugging with GDB needs GDB {GDB_MIN_MAJOR} or newer (found {major}.{minor} at {}): \
this one has no DAP interpreter (`gdb -i dap`)",
binary.display(),
"debugging with GDB needs GDB {GDB_MIN_MAJOR} or newer (found {major}.{minor}): \
this one has no DAP interpreter (`gdb -i dap`)"
);
if let Some(hint) = &spec.install_hint {
msg.push_str(". ");
@@ -1069,48 +1026,6 @@ mod tests {
assert!(builtin("nope").is_none());
}
#[cfg(unix)]
#[tokio::test]
async fn gdb_version_check_probes_the_adapter_command() {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().unwrap();
let binary = dir.path().join("custom gdb");
std::fs::write(&binary, "#!/bin/sh\n[ \"$1\" = --version ] && echo 'GNU gdb (GDB) 13.2'\n").unwrap();
std::fs::set_permissions(&binary, std::fs::Permissions::from_mode(0o755)).unwrap();
let mut spec = resolve(&builtin("gdb").unwrap(), dir.path().to_path_buf());
spec.command = binary.to_str().unwrap().to_owned();
let Err(error) = ProcessLauncher.launch(spec, None).await else {
panic!("GDB 13 was started as a DAP adapter");
};
assert_eq!(error.kind, ide_core::error::ErrorKind::Unavailable);
assert!(error.message.contains("needs GDB 14 or newer (found 13.2 at "), "{}", error.message);
assert!(error.message.contains(binary.to_str().unwrap()), "{}", error.message);
}
/// Debian/Ubuntu's versioned lldb-dap (and lldb-vscode before LLVM 18): the newest LLVM wins.
#[cfg(unix)]
#[test]
fn finds_versioned_lldb_dap() {
use std::os::unix::fs::PermissionsExt;
let tmp = tempfile::tempdir().unwrap();
let exe = |p: &Path| {
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
std::fs::write(p, "").unwrap();
std::fs::set_permissions(p, std::fs::Permissions::from_mode(0o755)).unwrap();
};
let (bin, lib) = (tmp.path().join("bin"), tmp.path().join("lib"));
exe(&bin.join("lldb-vscode-14"));
std::fs::write(bin.join("lldb-dap-99"), "").unwrap(); // not executable
assert_eq!(versioned_lldb_dap(std::slice::from_ref(&bin), &lib), Some(bin.join("lldb-vscode-14")));
exe(&lib.join("llvm-18/bin/lldb-dap"));
assert_eq!(versioned_lldb_dap(std::slice::from_ref(&bin), &lib), Some(lib.join("llvm-18/bin/lldb-dap")));
exe(&bin.join("lldb-dap-19"));
assert_eq!(versioned_lldb_dap(std::slice::from_ref(&bin), &lib), Some(bin.join("lldb-dap-19")));
assert_eq!(versioned_lldb_dap(&[], &tmp.path().join("none")), None);
}
/// The first version number of `gdb --version`'s first line, however the distro decorates it.
#[test]
fn parses_gdb_versions() {
-1
Переглянути файл
@@ -22,7 +22,6 @@ mod jvm_memory;
pub mod kotlin;
pub mod kotlin_lsp;
mod memory;
pub mod native;
mod session;
mod stream_trace;
mod swiftpm;
-206
Переглянути файл
@@ -1,206 +0,0 @@
//! C/C++ launches made for lldb-dap (CMake, Swift packages) fall back to CodeLLDB, then to
//! GDB 14 or newer, when the host has no lldb-dap: Linux hosts rarely put one on `PATH`, and
//! CodeLLDB is the debugger OpenIDEA can install itself.
use crate::LaunchConfig;
use crate::adapter::{GDB_MIN_MAJOR, probe_gdb_version};
use ide_core::{IdeError, IdeResult};
use serde_json::{Map, Value, json};
use std::path::{Path, PathBuf};
/// Prefix of the error when none of them is there; the UI offers to install CodeLLDB on it.
pub const NO_NATIVE_DEBUGGER: &str = "No C/C++ debugger found";
/// `config` for the first of lldb-dap, CodeLLDB and GDB 14+ that `lookup` finds (it resolves a
/// debugger command: a configured tool path, else the search path). Other launches pass through.
pub async fn choose(
mut config: LaunchConfig,
lookup: impl Fn(&str) -> Option<PathBuf> + Send + 'static,
) -> IdeResult<LaunchConfig> {
if config.adapter != "lldb-dap" || config.request != "launch" {
return Ok(config);
}
let found = tokio::task::spawn_blocking(move || {
if lookup("lldb-dap").is_some() {
return Found::LldbDap;
}
if lookup("codelldb").is_some() {
return Found::CodeLldb;
}
lookup("gdb").map_or(Found::Nothing, Found::Gdb)
})
.await
.map_err(|e| IdeError::internal(e.to_string()))?;
let cwd = config.cwd.clone().map(PathBuf::from).unwrap_or_else(|| PathBuf::from("/"));
match found {
Found::LldbDap => {}
Found::CodeLldb => convert(&mut config, "codelldb")?,
Found::Gdb(gdb) => match probe_gdb_version(&gdb, &cwd, &[]).await {
Some((major, minor)) if major < GDB_MIN_MAJOR => return Err(missing(Some((&gdb, major, minor)))),
// Unknown versions are left to GDB itself, as a GDB launch does.
_ => convert(&mut config, "gdb")?,
},
Found::Nothing => return Err(missing(None)),
}
Ok(config)
}
enum Found {
LldbDap,
CodeLldb,
Gdb(PathBuf),
Nothing,
}
fn missing(gdb: Option<(&Path, u32, u32)>) -> IdeError {
let found = match gdb {
Some((path, major, minor)) => format!(
"lldb-dap and CodeLLDB are not installed, and GDB {major}.{minor} at {} cannot debug through DAP \
(it needs GDB {GDB_MIN_MAJOR} or newer)",
path.display(),
),
None => "lldb-dap, CodeLLDB and GDB are not installed".to_owned(),
};
IdeError::unavailable(format!(
"{NO_NATIVE_DEBUGGER}: {found}. Install CodeLLDB, or install lldb-dap or GDB {GDB_MIN_MAJOR} or newer on this host"
))
}
/// Rewrites an lldb-dap launch for `to` (`codelldb` or `gdb`). lldb-dap takes the environment as
/// `KEY=VALUE` strings and the source map as pairs; the others take the run configuration's
/// environment map (`config.env`), CodeLLDB its source map as an object, GDB none.
fn convert(config: &mut LaunchConfig, to: &str) -> IdeResult<()> {
let mut extra = match config.extra_json.as_deref().filter(|e| !e.trim().is_empty()).map(serde_json::from_str) {
None => Map::new(),
Some(Ok(Value::Object(extra))) => extra,
Some(Ok(other)) => return Err(IdeError::invalid(format!("launch arguments are not an object: {other}"))),
Some(Err(e)) => return Err(IdeError::invalid(format!("invalid launch JSON: {e}"))),
};
extra.remove("env");
let source_map = extra.remove("sourceMap");
if to == "codelldb" {
if let Some(Value::Array(pairs)) = source_map {
let map: Map<String, Value> = pairs
.iter()
.filter_map(|pair| match pair.as_array().map(Vec::as_slice) {
Some([Value::String(from), to]) => Some((from.clone(), to.clone())),
_ => None,
})
.collect();
if !map.is_empty() {
extra.insert("sourceMap".into(), Value::Object(map));
}
}
// CodeLLDB evaluates as Rust unless told otherwise (ide-dap's default for it).
let language = if extra.contains_key("swiftpm") { "swift" } else { "cpp" };
extra.entry("sourceLanguages").or_insert_with(|| json!([language]));
}
config.adapter = to.to_owned();
config.extra_json = (!extra.is_empty()).then(|| Value::Object(extra).to_string());
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::BTreeMap;
fn cmake_launch() -> LaunchConfig {
LaunchConfig {
name: "hello".into(),
adapter: "lldb-dap".into(),
request: "launch".into(),
program: Some("/home/dev/hello/build/hello".into()),
args: vec![],
cwd: Some(std::path::PathBuf::from("/").into()),
env: BTreeMap::from([("A".into(), "1".into())]),
extra_json: Some(json!({"env": ["A=1"], "sourceMap": [["/src", "/real/src"]]}).to_string()),
}
}
fn extra(config: &LaunchConfig) -> Value {
config.extra_json.as_deref().map_or(Value::Null, |e| serde_json::from_str(e).unwrap())
}
fn only(names: &'static [&'static str]) -> impl Fn(&str) -> Option<PathBuf> + Send + 'static {
move |c| names.contains(&c).then(|| PathBuf::from(format!("/usr/bin/{c}")))
}
#[tokio::test]
async fn keeps_lldb_dap_when_it_is_there() {
let config = choose(cmake_launch(), only(&["lldb-dap", "codelldb", "gdb"])).await.unwrap();
assert_eq!(config.adapter, "lldb-dap");
assert_eq!(config.extra_json, cmake_launch().extra_json);
}
#[tokio::test]
async fn falls_back_to_codelldb_with_its_launch_shape() {
let config = choose(cmake_launch(), only(&["codelldb", "gdb"])).await.unwrap();
assert_eq!(config.adapter, "codelldb");
assert_eq!(config.env, cmake_launch().env, "the environment comes from the run configuration's map");
assert_eq!(
extra(&config),
json!({"sourceMap": {"/src": "/real/src"}, "sourceLanguages": ["cpp"]}),
"no KEY=VALUE env strings; the source map as an object; C++ evaluation"
);
}
#[tokio::test]
async fn a_swift_package_evaluates_swift_under_codelldb() {
let mut launch = cmake_launch();
launch.extra_json = Some(json!({"env": [], "swiftpm": {"product": "app", "buildArgs": []}}).to_string());
let config = choose(launch, only(&["codelldb"])).await.unwrap();
assert_eq!(extra(&config)["sourceLanguages"], json!(["swift"]));
assert_eq!(extra(&config)["swiftpm"]["product"], "app");
}
#[tokio::test]
async fn without_any_debugger_says_what_to_install() {
let e = choose(cmake_launch(), only(&[])).await.unwrap_err();
assert_eq!(e.kind, ide_core::error::ErrorKind::Unavailable);
assert!(e.message.starts_with(NO_NATIVE_DEBUGGER), "{}", e.message);
assert!(e.message.contains("Install CodeLLDB"), "{}", e.message);
}
#[tokio::test]
async fn other_launches_pass_through() {
let mut attach = cmake_launch();
attach.request = "attach".into();
assert_eq!(choose(attach, only(&[])).await.unwrap().adapter, "lldb-dap");
let mut rust = cmake_launch();
rust.adapter = "codelldb".into();
assert_eq!(choose(rust, only(&[])).await.unwrap().adapter, "codelldb");
}
#[cfg(unix)]
fn fake_gdb(dir: &Path, version: &str) -> PathBuf {
use std::os::unix::fs::PermissionsExt;
let gdb = dir.join("gdb");
std::fs::write(&gdb, format!("#!/bin/sh\necho '{version}'\n")).unwrap();
std::fs::set_permissions(&gdb, std::fs::Permissions::from_mode(0o755)).unwrap();
gdb
}
/// Ubuntu 22.04's GDB 12 has no DAP interpreter: the error names its version (#7001).
#[cfg(unix)]
#[tokio::test]
async fn an_old_gdb_is_named_in_the_error() {
let dir = tempfile::tempdir().unwrap();
let gdb = fake_gdb(dir.path(), "GNU gdb (Ubuntu 12.1-0ubuntu1~22.04.2) 12.1");
let path = gdb.clone();
let e = choose(cmake_launch(), move |c| (c == "gdb").then(|| path.clone())).await.unwrap_err();
assert!(e.message.starts_with(NO_NATIVE_DEBUGGER), "{}", e.message);
assert!(e.message.contains("GDB 12.1"), "{}", e.message);
assert!(e.message.contains(gdb.to_str().unwrap()), "{}", e.message);
}
#[cfg(unix)]
#[tokio::test]
async fn falls_back_to_a_gdb_with_dap() {
let dir = tempfile::tempdir().unwrap();
let gdb = fake_gdb(dir.path(), "GNU gdb (GDB) 14.2");
let config = choose(cmake_launch(), move |c| (c == "gdb").then(|| gdb.clone())).await.unwrap();
assert_eq!(config.adapter, "gdb");
assert_eq!(extra(&config), Value::Null, "GDB takes the environment map and has no source map");
}
}
+7 -13
Переглянути файл
@@ -1134,27 +1134,21 @@ 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);
// 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::host_env_fixes_in(cwd) {
match v {
Some(v) => cmd.env(k, v),
None => cmd.env_remove(k),
}
}
for (k, v) in ide_core::process::shell_env_in(cwd) {
if ide_core::process::is_spawnable_env_pair(&k, &v) {
cmd.env(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)
if ide_core::process::is_spawnable_env_pair(std::ffi::OsStr::new(k), std::ffi::OsStr::new(v)) =>
{
cmd.env(k, v)
}
Some(_) => {}
Some(v) => cmd.env(k, v),
None => cmd.env_remove(k),
};
}
+62 -134
Переглянути файл
@@ -447,15 +447,6 @@ fn read_table_properties(details: &mut TableDetails, row: Vec<Option<String>>) {
);
details.partitioning = next();
details.persistence = next().as_deref().and_then(DbPersistence::from_catalog);
// PostgreSQL's `table_properties` carries the comment as its last column, so reading it here
// saves the separate query `table_comment` would make on the same `pg_class` row.
if let Some(comment) = next() {
// `table_comment` this replaces yielded `NULL` or empty for no comment, so an empty
// comment must not become `Some("")` — the DDL would emit an empty `COMMENT ON`.
if !comment.is_empty() {
details.comment = Some(comment);
}
}
}
fn flag(v: &Option<String>) -> bool {
@@ -1393,61 +1384,8 @@ impl DbManager {
if driver == DbDriver::Jdbc {
return Ok(TableDetails { columns, ..Default::default() });
}
// Everything below describes the same table and none of it feeds the next, so it goes
// out together. Serialised, this is four round trips on the path that opens a table
// (`table_page_on` calls this for the primary key), which is what makes opening a table
// feel slow on a remote server. Five queries against a pool of four (`conn.rs`'s `MAX`),
// so one waits — still one round trip rather than five.
type Rows = Vec<Vec<Option<String>>>;
let keys = !matches!(driver, DbDriver::Clickhouse | DbDriver::Snowflake);
let (index_q, fk_q, trigger_q) = (
sql::indexes(driver, schema, table),
sql::table_foreign_keys(driver, schema, table),
sql::triggers(driver, schema, table),
);
let (index_rows, fk_rows, trigger_rows, comment_rows, property_rows) = futures::join!(
pool.rows(&index_q, MAX_META_ROWS),
async {
if !keys {
return Ok::<Rows, IdeError>(Vec::new());
}
match pool.rows(&fk_q, MAX_META_ROWS).await {
Ok(rows) => Ok(rows),
Err(e) => {
tracing::warn!("foreign keys: {}", e.message);
Ok(Vec::new())
}
}
},
async {
if !keys {
return Ok::<Rows, IdeError>(Vec::new());
}
match pool.rows(&trigger_q, MAX_META_ROWS).await {
Ok(rows) => Ok(rows),
Err(e) => {
tracing::warn!("triggers: {}", e.message);
Ok(Vec::new())
}
}
},
async {
// PostgreSQL reads it with the properties above; the engines without a
// `table_properties` query ask for it here.
match sql::table_comment(driver, schema, table) {
Some(q) if sql::table_properties(driver, schema, table).is_none() => pool.rows(&q, 1).await,
_ => Ok::<Rows, IdeError>(Vec::new()),
}
},
async {
match sql::table_properties(driver, schema, table) {
Some(q) => catalog_rows(pool, &q).await,
None => Ok::<Rows, IdeError>(Vec::new()),
}
},
);
let mut indexes: Vec<IndexInfo> = Vec::new();
for r in index_rows? {
for r in pool.rows(&sql::indexes(driver, schema, table), MAX_META_ROWS).await? {
let mut it = r.into_iter();
let (Some(name), unique, Some(col)) = (it.next().flatten(), it.next().flatten(), it.next().flatten())
else {
@@ -1463,7 +1401,11 @@ impl DbManager {
}),
}
}
let fk_rows = fk_rows?;
let fk_rows = if matches!(driver, DbDriver::Clickhouse | DbDriver::Snowflake) {
Vec::new()
} else {
pool.rows(&sql::table_foreign_keys(driver, schema, table), MAX_META_ROWS).await.unwrap_or_default()
};
let mut foreign_keys = group_foreign_keys(fk_rows, &[]);
// SQLite keys that reference the primary key implicitly: look it up.
for k in foreign_keys.iter_mut().filter(|k| k.ref_columns.is_empty()) {
@@ -1476,7 +1418,15 @@ impl DbManager {
.collect();
}
foreign_keys.retain(|k| k.columns.len() == k.ref_columns.len());
let triggers = trigger_rows?
let trigger_rows = if matches!(driver, DbDriver::Clickhouse | DbDriver::Snowflake) {
Vec::new()
} else {
pool.rows(&sql::triggers(driver, schema, table), MAX_META_ROWS).await.unwrap_or_else(|e| {
tracing::warn!("triggers: {}", e.message);
Vec::new()
})
};
let triggers = trigger_rows
.into_iter()
.filter_map(|r| {
let mut it = r.into_iter();
@@ -1489,21 +1439,26 @@ impl DbManager {
Some(TriggerInfo { name, timing, events })
})
.collect();
let comment = comment_rows.map_or_else(
|e| {
tracing::warn!("table comment: {}", e.message);
None
},
|rows| rows.into_iter().next().and_then(|r| r.into_iter().next().flatten()).filter(|c| !c.is_empty()),
);
let comment = match sql::table_comment(driver, schema, table) {
Some(q) => pool.rows(&q, 1).await.map_or_else(
|e| {
tracing::warn!("table comment: {}", e.message);
None
},
|rows| rows.into_iter().next().and_then(|r| r.into_iter().next().flatten()).filter(|c| !c.is_empty()),
),
None => None,
};
let mut details = TableDetails { comment, columns, indexes, foreign_keys, triggers, ..Default::default() };
match property_rows {
Ok(rows) => {
if let Some(row) = rows.into_iter().next() {
read_table_properties(&mut details, row);
if let Some(q) = sql::table_properties(driver, schema, table) {
match catalog_rows(pool, &q).await {
Ok(rows) => {
if let Some(row) = rows.into_iter().next() {
read_table_properties(&mut details, row);
}
}
Err(e) => tracing::warn!("table properties: {}", e.message),
}
Err(e) => tracing::warn!("table properties: {}", e.message),
}
Ok(details)
}
@@ -1714,16 +1669,16 @@ impl DbManager {
ddl.map(|d| format!("{};\n", d.trim_end().trim_end_matches(';'))).ok_or_else(missing)
}
DbDriver::Postgres => {
// Everything the script needs depends on the relation oid, so read that first and
// then the rest at once — five queries in flight against a pool of four, so one
// waits, but that is still two round trips instead of six.
let rel = catalog_rows(&pool, &sql::postgres_relation(schema, name)).await?.into_iter().next();
let Some([Some(oid), Some(kind), owner, comment, persistence, partition_key, parent @ ..]) =
rel.as_deref()
else {
return Err(missing());
let rel = pool.rows(&sql::postgres_relation(schema, name), 1).await?.into_iter().next();
let (oid, kind, owner, comment) = match rel.as_deref() {
Some([Some(oid), Some(kind), owner, comment]) => (
oid.parse::<u32>().map_err(|e| IdeError::invalid(e.to_string()))?,
kind.clone(),
owner.clone(),
comment.clone(),
),
_ => return Err(missing()),
};
let oid = oid.parse::<u32>().map_err(|e| IdeError::invalid(e.to_string()))?;
if kind == "v" || kind == "m" {
let def = cells(pool.rows(&format!("SELECT pg_get_viewdef({oid}, true)"), 1).await?, 0);
let what = if kind == "m" { "materialized view" } else { "view" };
@@ -1731,70 +1686,43 @@ impl DbManager {
let target = sql::qualified(driver, schema, name);
return Ok(format!("create {what} {target} as\n{};\n", body.trim_end().trim_end_matches(';')));
}
let partition = match parent {
[Some(parent_schema), Some(parent_table), Some(bound)] => Some(sql::DdlPartition {
parent_schema: parent_schema.clone(),
parent_table: parent_table.clone(),
bound: bound.clone(),
}),
_ => None,
};
let is_partition = partition.is_some();
let (cols_q, keys_q, grants_q, index_q, trigger_q) = (
sql::postgres_ddl_columns(oid, is_partition),
sql::postgres_ddl_constraints(oid, is_partition),
sql::postgres_ddl_grants(oid),
sql::postgres_ddl_indexes(oid, is_partition),
sql::postgres_ddl_triggers(oid, is_partition),
);
let (col_rows, key_rows, grant_rows, index_rows, trigger_rows) = futures::join!(
catalog_rows(&pool, &cols_q),
pool.rows(&keys_q, MAX_META_ROWS),
pool.rows(&grants_q, MAX_META_ROWS),
pool.rows(&index_q, MAX_META_ROWS),
catalog_rows(&pool, &trigger_q),
);
let columns = col_rows?
let columns = pool
.rows(&sql::postgres_ddl_columns(oid), MAX_META_ROWS)
.await?
.into_iter()
.filter_map(|r| {
let mut it = r.into_iter();
let name = it.next().flatten()?;
let data_type = it.next().flatten()?;
let not_null = flag(&it.next().flatten());
let expression = it.next().flatten();
let comment = it.next().flatten().filter(|c| !c.is_empty());
let identity = it.next().flatten();
let generated = it.next().flatten();
let value =
sql::DdlColumnValue::from_catalog(identity.as_deref(), generated.as_deref(), expression);
Some(sql::DdlColumn { name, data_type, not_null, value, comment })
Some(sql::DdlColumn {
name: it.next().flatten()?,
data_type: it.next().flatten().unwrap_or_default(),
not_null: flag(&it.next().flatten()),
default: it.next().flatten(),
comment: it.next().flatten(),
})
})
.collect::<Vec<_>>();
let constraints = key_rows?
let constraints = pool
.rows(&sql::postgres_ddl_constraints(oid), MAX_META_ROWS)
.await?
.into_iter()
.filter_map(|r| {
let mut it = r.into_iter();
Some((it.next().flatten()?, it.next().flatten()?))
})
.collect::<Vec<_>>();
let indexes =
index_rows?.into_iter().filter_map(|r| r.into_iter().next().flatten()).collect::<Vec<_>>();
let grants = grant_rows?
let indexes = cells(pool.rows(&sql::postgres_ddl_indexes(oid), MAX_META_ROWS).await?, 0);
let grants = pool
.rows(&sql::postgres_ddl_grants(oid), MAX_META_ROWS)
.await?
.into_iter()
.filter_map(|r| {
let mut it = r.into_iter();
Some((it.next().flatten()?, it.next().flatten()?, flag(&it.next().flatten())))
})
.collect::<Vec<_>>();
let triggers =
trigger_rows?.into_iter().filter_map(|r| r.into_iter().next().flatten()).collect::<Vec<_>>();
let options = sql::DdlTableOptions {
unlogged: persistence.as_deref() == Some("u"),
partition_key: partition_key.clone(),
partition,
};
let extras = sql::DdlExtras { comment: comment.clone(), owner: owner.clone(), grants, triggers };
Ok(sql::postgres_table_ddl(schema, name, &columns, &constraints, &indexes, &options, &extras))
.collect();
let triggers = cells(pool.rows(&sql::postgres_ddl_triggers(oid), MAX_META_ROWS).await?, 0);
let extras = sql::DdlExtras { comment, owner, grants, triggers };
Ok(sql::postgres_table_ddl(schema, name, &columns, &constraints, &indexes, &extras))
}
}
}
+24 -224
Переглянути файл
@@ -249,7 +249,7 @@ pub fn table_properties(driver: DbDriver, schema: &str, table: &str) -> Option<S
JOIN pg_tablespace dt ON dt.oid = d.dattablespace WHERE d.datname = current_database())), \
am.amname, array_to_string(array_cat(c.reloptions, \
(SELECT array_agg('toast.' || o) FROM unnest(tc.reloptions) o)), chr(10)), \
pg_get_partkeydef(c.oid), c.relpersistence, obj_description(c.oid, 'pg_class') \
pg_get_partkeydef(c.oid), c.relpersistence \
FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace \
LEFT JOIN pg_class tc ON tc.oid = c.reltoastrelid \
LEFT JOIN pg_tablespace ts ON ts.oid = c.reltablespace LEFT JOIN pg_am am ON am.oid = c.relam \
@@ -697,70 +697,40 @@ pub fn sqlite_ddl(schema: &str, name: &str) -> String {
)
}
/// Rows: `oid, relkind, owner, comment, persistence, partition key, parent schema, parent name, bound`.
/// Rows: `oid, relkind, owner, comment` of a PostgreSQL relation.
pub fn postgres_relation(schema: &str, name: &str) -> String {
format!(
"SELECT c.oid::text, c.relkind::text, pg_get_userbyid(c.relowner), obj_description(c.oid, 'pg_class'), \
c.relpersistence::text, pg_get_partkeydef(c.oid), pn.nspname, p.relname, pg_get_expr(c.relpartbound, c.oid) \
"SELECT c.oid::text, c.relkind::text, pg_get_userbyid(c.relowner), obj_description(c.oid, 'pg_class') \
FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace \
LEFT JOIN pg_inherits i ON i.inhrelid = c.oid AND c.relispartition \
LEFT JOIN pg_class p ON p.oid = i.inhparent LEFT JOIN pg_namespace pn ON pn.oid = p.relnamespace \
WHERE n.nspname = {} AND c.relname = {}",
quote_literal(DbDriver::Postgres, schema),
quote_literal(DbDriver::Postgres, name)
)
}
/// Rows: `name, type, not null (0/1), expression, comment, identity, generated` of relation `oid`.
/// On a partition, the not-null flag and expression describe overrides of the parent column.
///
/// Read from `pg_attribute` with `format_type` rather than from `information_schema.columns`:
/// that view reports `character varying` without the length, `numeric` without the precision,
/// `ARRAY` for every array and `USER-DEFINED` for an enum, so a script built from it would not
/// recreate the table. It also lists only the columns the current role holds privileges on.
pub fn postgres_ddl_columns(oid: u32, partition: bool) -> String {
// Generated clauses add their own parentheses. Keep the original deparser style for defaults.
let pretty = "(a.attgenerated::text = 's') IS TRUE";
let expression = format!("pg_get_expr(d.adbin, d.adrelid, {pretty})");
let (not_null, expression, identity, parent_join) = if partition {
let parent_expression = format!("pg_get_expr(pd.adbin, pd.adrelid, {pretty})");
(
"a.attnotnull AND NOT pa.attnotnull",
format!(
"CASE WHEN {expression} IS DISTINCT FROM {parent_expression} THEN COALESCE({expression}, 'NULL') END"
),
"NULL",
"JOIN pg_inherits i ON i.inhrelid = a.attrelid \
JOIN pg_attribute pa ON pa.attrelid = i.inhparent AND pa.attname = a.attname AND NOT pa.attisdropped \
LEFT JOIN pg_attrdef pd ON pd.adrelid = pa.attrelid AND pd.adnum = pa.attnum",
)
} else {
("a.attnotnull", expression, "a.attidentity::text", "")
};
/// Rows: `name, type, not null (0/1), default, comment` of relation `oid`.
pub fn postgres_ddl_columns(oid: u32) -> String {
format!(
"SELECT a.attname, format_type(a.atttypid, a.atttypmod), CASE WHEN {not_null} THEN 1 ELSE 0 END, \
{expression}, col_description(a.attrelid, a.attnum), {identity}, a.attgenerated::text FROM pg_attribute a \
LEFT JOIN pg_attrdef d ON d.adrelid = a.attrelid AND d.adnum = a.attnum {parent_join} \
"SELECT a.attname, format_type(a.atttypid, a.atttypmod), CASE WHEN a.attnotnull THEN 1 ELSE 0 END, \
pg_get_expr(d.adbin, d.adrelid), col_description(a.attrelid, a.attnum) FROM pg_attribute a \
LEFT JOIN pg_attrdef d ON d.adrelid = a.attrelid AND d.adnum = a.attnum \
WHERE a.attrelid = {oid} AND a.attnum > 0 AND NOT a.attisdropped ORDER BY a.attnum"
)
}
/// Rows: `name, definition` of the constraints of relation `oid` (primary key first).
pub fn postgres_ddl_constraints(oid: u32, partition: bool) -> String {
let local = if partition { " AND conislocal AND coninhcount = 0" } else { "" };
pub fn postgres_ddl_constraints(oid: u32) -> String {
format!(
"SELECT conname, pg_get_constraintdef(oid, true) FROM pg_constraint WHERE conrelid = {oid}{local} \
"SELECT conname, pg_get_constraintdef(oid, true) FROM pg_constraint WHERE conrelid = {oid} \
ORDER BY CASE contype WHEN 'p' THEN 0 WHEN 'u' THEN 1 WHEN 'c' THEN 2 WHEN 'f' THEN 3 ELSE 4 END, conname"
)
}
/// Rows: `CREATE INDEX …` of relation `oid`, except the indexes behind constraints.
pub fn postgres_ddl_indexes(oid: u32, partition: bool) -> String {
let local =
if partition { " AND NOT EXISTS (SELECT 1 FROM pg_inherits WHERE inhrelid = i.indexrelid)" } else { "" };
pub fn postgres_ddl_indexes(oid: u32) -> String {
format!(
"SELECT pg_get_indexdef(i.indexrelid) FROM pg_index i WHERE i.indrelid = {oid} \
AND NOT EXISTS (SELECT 1 FROM pg_constraint c WHERE c.conindid = i.indexrelid AND c.conrelid = i.indrelid){local} \
AND NOT EXISTS (SELECT 1 FROM pg_constraint c WHERE c.conindid = i.indexrelid AND c.conrelid = i.indrelid) \
ORDER BY 1"
)
}
@@ -779,10 +749,9 @@ pub fn postgres_ddl_grants(oid: u32) -> String {
}
/// Rows: `CREATE TRIGGER …` of the user triggers of relation `oid`.
pub fn postgres_ddl_triggers(oid: u32, partition: bool) -> String {
let local = if partition { " AND tgparentid = 0" } else { "" };
pub fn postgres_ddl_triggers(oid: u32) -> String {
format!(
"SELECT pg_get_triggerdef(oid, true) FROM pg_trigger t WHERE tgrelid = {oid} AND NOT tgisinternal{local} \
"SELECT pg_get_triggerdef(oid, true) FROM pg_trigger WHERE tgrelid = {oid} AND NOT tgisinternal \
ORDER BY tgname"
)
}
@@ -871,12 +840,6 @@ pub fn postgres_legacy(sql: &str) -> Option<String> {
.replace(" LEFT JOIN pg_am am ON am.oid = c.relam", "")
.replace("am.amname", "NULL")
.replace("pg_get_partkeydef(c.oid)", "NULL")
.replace("c.relispartition", "false")
.replace("pg_get_expr(c.relpartbound, c.oid)", "NULL")
// These flags entered the catalog in different releases. Keep whichever ones exist.
.replace("a.attidentity::text", "to_jsonb(a)->>'attidentity'")
.replace("a.attgenerated::text", "to_jsonb(a)->>'attgenerated'")
.replace("tgparentid = 0", "COALESCE(to_jsonb(t)->>'tgparentid', '0') = '0'")
.replace("c.relkind IN ('r', 'p')", "c.relkind = 'r'");
(legacy != sql).then_some(legacy)
}
@@ -1036,42 +999,10 @@ pub struct DdlColumn {
pub name: String,
pub data_type: String,
pub not_null: bool,
pub value: Option<DdlColumnValue>,
pub default: Option<String>,
pub comment: Option<String>,
}
pub enum DdlColumnValue {
Default(String),
IdentityByDefault,
IdentityAlways,
GeneratedStored(String),
}
impl DdlColumnValue {
pub fn from_catalog(identity: Option<&str>, generated: Option<&str>, expression: Option<String>) -> Option<Self> {
match (identity, generated) {
(Some("d"), _) => Some(Self::IdentityByDefault),
(Some("a"), _) => Some(Self::IdentityAlways),
(_, Some("s")) => expression.map(Self::GeneratedStored),
(_, None | Some("")) => expression.map(Self::Default),
_ => None,
}
}
}
#[derive(Default)]
pub struct DdlTableOptions {
pub unlogged: bool,
pub partition_key: Option<String>,
pub partition: Option<DdlPartition>,
}
pub struct DdlPartition {
pub parent_schema: String,
pub parent_table: String,
pub bound: String,
}
/// What [`postgres_table_ddl`] adds after `create table` so the script rebuilds the table.
#[derive(Default)]
pub struct DdlExtras {
@@ -1090,30 +1021,17 @@ pub fn postgres_table_ddl(
columns: &[DdlColumn],
constraints: &[(String, String)],
indexes: &[String],
options: &DdlTableOptions,
extras: &DdlExtras,
) -> String {
let d = DbDriver::Postgres;
let partition = options.partition.as_ref();
let mut items: Vec<String> = columns
.iter()
.filter(|c| partition.is_none() || c.not_null || c.value.is_some())
.map(|c| {
let mut s = format!(" {}", quote_ident(d, &c.name));
if partition.is_none() {
s.push(' ');
s.push_str(&c.data_type);
let mut s = format!(" {} {}", quote_ident(d, &c.name), c.data_type);
if let Some(v) = &c.default {
s.push_str(&format!(" default {v}"));
}
match &c.value {
Some(DdlColumnValue::Default(v)) => s.push_str(&format!(" default {v}")),
Some(DdlColumnValue::IdentityByDefault) => s.push_str(" generated by default as identity"),
Some(DdlColumnValue::IdentityAlways) => s.push_str(" generated always as identity"),
Some(DdlColumnValue::GeneratedStored(v)) => s.push_str(&format!(" generated always as ({v}) stored")),
None => {}
}
if c.not_null
&& !matches!(c.value, Some(DdlColumnValue::IdentityByDefault | DdlColumnValue::IdentityAlways))
{
if c.not_null {
s.push_str(" not null");
}
s
@@ -1121,35 +1039,7 @@ pub fn postgres_table_ddl(
.collect();
items.extend(constraints.iter().map(|(name, def)| format!(" constraint {} {def}", quote_ident(d, name))));
let target = qualified(d, schema, table);
let persistence = if options.unlogged { "unlogged " } else { "" };
let mut out = format!("create {persistence}table {target}");
if let Some(partition) = partition {
let parent = qualified(d, &partition.parent_schema, &partition.parent_table);
out.push_str(&format!(" partition of {parent}"));
}
if partition.is_none() || !items.is_empty() {
out.push_str(&format!("\n(\n{}\n)", items.join(",\n")));
}
if let Some(partition) = partition {
out.push_str("\n ");
// pg_get_expr deparses bounds as keywords and constants. Preserve quoted constants,
// including doubled quotes, while matching the casing of the generated DDL.
for (i, part) in partition.bound.split('\'').enumerate() {
if i != 0 {
out.push('\'');
}
if i % 2 == 0 {
out.push_str(&part.to_ascii_lowercase());
} else {
out.push_str(part);
}
}
}
if let Some(key) = &options.partition_key {
let (method, expression) = key.split_at(key.find(' ').unwrap_or(key.len()));
out.push_str(&format!("\n partition by {}{expression}", method.to_ascii_lowercase()));
}
out.push_str(";\n");
let mut out = format!("create table {target}\n(\n{}\n);\n", items.join(",\n"));
// The order a script runs in: comments, owner and privileges, then indexes and triggers.
if let Some(comment) = &extras.comment {
out.push_str(&format!("\ncomment on table {target} is {};\n", quote_literal(d, comment)));
@@ -1526,31 +1416,15 @@ mod tests {
assert_eq!(use_schema(DbDriver::Clickhouse, "default"), None);
}
#[test]
fn postgres_ddl_columns_reads_pg_attribute_not_information_schema() {
// `information_schema.columns.data_type` loses what a script needs to recreate the table:
// `character varying` without the length, `numeric` without the precision, `ARRAY` for
// every array and `USER-DEFINED` for an enum. It also lists only the columns the current
// role holds privileges on. The DDL must therefore read `pg_attribute` with
// `format_type(atttypid, atttypmod)`, which is what makes `varchar(255)`, `numeric(10,2)`,
// `text[]` and an enum name come out as written.
let q = postgres_ddl_columns(42, false);
assert!(q.contains("format_type(a.atttypid, a.atttypmod)"), "{q}");
assert!(q.contains("FROM pg_attribute a"), "{q}");
assert!(q.contains("left join pg_attrdef") || q.contains("LEFT JOIN pg_attrdef"), "{q}");
assert!(q.contains("attrelid = 42"), "{q}");
assert!(!q.contains("information_schema"), "{q}");
}
#[test]
fn postgres_ddl() {
let cols = [
DdlColumn { name: "id".into(), data_type: "integer".into(), not_null: true, value: None, comment: None },
DdlColumn { name: "id".into(), data_type: "integer".into(), not_null: true, default: None, comment: None },
DdlColumn {
name: "name".into(),
data_type: "character varying(40)".into(),
not_null: false,
value: Some(DdlColumnValue::Default("'x'::character varying".into())),
default: Some("'x'::character varying".into()),
comment: None,
},
];
@@ -1561,94 +1435,21 @@ mod tests {
&cols,
&[("t_pkey".into(), "PRIMARY KEY (id)".into())],
&["CREATE INDEX t_name ON public.t USING btree (name)".into()],
&DdlTableOptions::default(),
&DdlExtras::default(),
),
"create table \"public\".\"t\"\n(\n \"id\" integer not null,\n \"name\" character varying(40) default 'x'::character varying,\n constraint \"t_pkey\" PRIMARY KEY (id)\n);\n\nCREATE INDEX t_name ON public.t USING btree (name);\n"
);
}
#[test]
fn postgres_ddl_renders_identity_and_stored_columns() {
let columns = [
("id_default", "bigint", true, "d", "", Some("ignored()")),
("id_always", "bigint", true, "a", "", None),
("total", "integer", true, "", "s", Some("qty * price")),
]
.map(|(name, data_type, not_null, identity, generated, expression)| DdlColumn {
name: name.into(),
data_type: data_type.into(),
not_null,
value: DdlColumnValue::from_catalog(Some(identity), Some(generated), expression.map(Into::into)),
comment: None,
});
let ddl =
postgres_table_ddl("public", "t", &columns, &[], &[], &DdlTableOptions::default(), &DdlExtras::default());
assert_eq!(
ddl,
concat!(
"create table \"public\".\"t\"\n(\n",
" \"id_default\" bigint generated by default as identity,\n",
" \"id_always\" bigint generated always as identity,\n",
" \"total\" integer generated always as (qty * price) stored not null\n",
");\n",
)
);
}
#[test]
fn postgres_ddl_renders_unlogged_partitioned_parent() {
let columns =
[DdlColumn { name: "Day".into(), data_type: "date".into(), not_null: true, value: None, comment: None }];
let options =
DdlTableOptions { unlogged: true, partition_key: Some("RANGE (\"Day\")".into()), partition: None };
assert_eq!(
postgres_table_ddl("public", "events", &columns, &[], &[], &options, &DdlExtras::default()),
"create unlogged table \"public\".\"events\"\n(\n \"Day\" date not null\n)\n partition by range (\"Day\");\n"
);
}
#[test]
fn postgres_ddl_renders_partitions_and_preserves_bound_literals() {
let columns = [DdlColumn {
name: "region".into(),
data_type: "text".into(),
not_null: false,
value: None,
comment: None,
}];
for (bound, rendered) in [
("FOR VALUES FROM (MINVALUE) TO ('A) TO (B')", "for values from (minvalue) to ('A) TO (B')"),
("FOR VALUES IN ('East''s', 'SOUTH', NULL)", "for values in ('East''s', 'SOUTH', null)"),
("FOR VALUES WITH (modulus 2, remainder 0)", "for values with (modulus 2, remainder 0)"),
("DEFAULT", "default"),
] {
let options = DdlTableOptions {
partition: Some(DdlPartition {
parent_schema: "other".into(),
parent_table: "Parent\"Table".into(),
bound: bound.into(),
}),
..Default::default()
};
assert_eq!(
postgres_table_ddl("public", "child", &columns, &[], &[], &options, &DdlExtras::default()),
format!(
"create table \"public\".\"child\" partition of \"other\".\"Parent\"\"Table\"\n {rendered};\n"
)
);
}
}
#[test]
fn postgres_ddl_rebuilds_comments_owner_grants_and_triggers() {
let cols = [
DdlColumn { name: "id".into(), data_type: "integer".into(), not_null: true, value: None, comment: None },
DdlColumn { name: "id".into(), data_type: "integer".into(), not_null: true, default: None, comment: None },
DdlColumn {
name: "note".into(),
data_type: "text".into(),
not_null: false,
value: None,
default: None,
comment: Some("what's this".into()),
},
];
@@ -1667,7 +1468,6 @@ mod tests {
&cols,
&[],
&["CREATE INDEX t_note ON public.t USING btree (note)".into()],
&DdlTableOptions::default(),
&extras
),
"create table \"public\".\"t\"\n(\n \"id\" integer not null,\n \"note\" text\n);\n\
+8 -20
Переглянути файл
@@ -1601,21 +1601,15 @@ mod tests {
let text = "a\n b\nc\nd\n e\n";
let formatted = "a\nb\nc\nd\ne\n";
let whole = vec![TextEdit { range: Range::new(Pos::new(0, 0), Pos::new(5, 0)), new_text: formatted.into() }];
let started = std::time::Instant::now();
let edits = minimal_edits(text, whole);
// Past the diff budget (a loaded machine) the regions may merge, still correctly.
if started.elapsed() < ide_text::DIFF_BUDGET {
assert_eq!(
edits,
[
TextEdit { range: Range::new(Pos::new(1, 0), Pos::new(1, 2)), new_text: String::new() },
TextEdit { range: Range::new(Pos::new(4, 0), Pos::new(4, 2)), new_text: String::new() },
]
);
}
assert_eq!(
edits,
[
TextEdit { range: Range::new(Pos::new(1, 0), Pos::new(1, 2)), new_text: String::new() },
TextEdit { range: Range::new(Pos::new(4, 0), Pos::new(4, 2)), new_text: String::new() },
]
);
assert_eq!(after(text, &edits), formatted);
// Merged or not, the edits stay between the first and the last changed line.
assert!(edits[0].range.start >= Pos::new(1, 0) && edits[edits.len() - 1].range.end <= Pos::new(4, 2));
// Single-line edits are already minimal and pass through.
let small = vec![TextEdit { range: Range::new(Pos::new(1, 0), Pos::new(1, 2)), new_text: String::new() }];
assert_eq!(minimal_edits(text, small.clone()), small);
@@ -1666,17 +1660,11 @@ mod tests {
let text = "<?php\n$x = 1;\n$yyy = 2;\n$a = [\n 'a' => 1,\n 'bbb' => 2,\n];\n";
// PHP-CS-Fixer formats the whole file (here: adds a line at the top) whatever the selection.
let formatted = format!("<?php\n\ndeclare(strict_types=1);\n{}", &text["<?php\n".len()..]);
let started = std::time::Instant::now();
let edits = whole_file(text, &formatted);
// Lines 3..=6 select the array, up to the start of the line after it.
let range = Range::new(Pos::new(3, 0), Pos::new(7, 0));
let aligned = align_formatted(&syntax, &php, text, edits, Some(range), ALIGN).unwrap();
// Past the diff budget (a loaded machine) the regions may merge, still correctly.
if started.elapsed() < ide_text::DIFF_BUDGET {
assert_eq!(aligned.len(), 2, "one edit per changed region: {aligned:?}");
}
// Merged or not, the edits leave the unchanged first and last lines alone.
assert!(aligned[0].range.start >= Pos::new(1, 0) && aligned[aligned.len() - 1].range.end <= Pos::new(6, 0));
assert_eq!(aligned.len(), 2, "one edit per changed region: {aligned:?}");
assert_eq!(
after(text, &aligned),
"<?php\n\ndeclare(strict_types=1);\n$x = 1;\n$yyy = 2;\n$a = [\n 'a' => 1,\n 'bbb' => 2,\n];\n"
+5 -21
Переглянути файл
@@ -99,8 +99,8 @@ fn get_repositories() -> Tool {
"get_repositories",
"Retrieves the list of VCS roots in the project.
This is useful to detect all repositories in a multi-repository project.
In OpenIDEA each root also tells its current `branch` (absent when HEAD is detached or the repository is unavailable), \
`headCommit`, a merge, rebase or cherry-pick in progress (`operationInProgress`), and `unavailable` (`true` when the repository directory cannot be reached).",
In OpenIDEA each root also tells its current `branch` (absent when HEAD is detached), `headCommit` and a merge, \
rebase or cherry-pick in progress (`operationInProgress`).",
|call| async move {
let roots = crate::ops::vcs::vcs_roots(&call.host(), &call.window).await?;
let list: Vec<Value> = roots
@@ -117,9 +117,6 @@ In OpenIDEA each root also tells its current `branch` (absent when HEAD is detac
if let Some(op) = r.operation {
v["operationInProgress"] = op.into();
}
if r.unavailable {
v["unavailable"] = true.into();
}
v
})
.collect();
@@ -259,10 +256,10 @@ By default all Git repositories are returned.",
let include_ignored = call.flag("includeIgnored", false)?;
let page = Page::of(&call, STATUS_DEFAULT_LIMIT)?;
let host = call.host();
let repos: Vec<(PathBuf, (Option<String>, bool))> = crate::ops::vcs::vcs_roots(&host, &call.window)
let repos: Vec<(PathBuf, Option<String>)> = crate::ops::vcs::vcs_roots(&host, &call.window)
.await?
.into_iter()
.map(|r| (r.root.into_path_buf(), (r.head, r.unavailable)))
.map(|r| (r.root.into_path_buf(), r.head))
.collect();
let wanted = call.opt_str("repositoryPathRelativeToProject")?;
let paths = super::search::PathScope::of(&call)?;
@@ -274,25 +271,12 @@ By default all Git repositories are returned.",
};
let mut roots: Vec<(PathBuf, Option<String>)> = if targets.is_empty() {
repos
.into_iter()
.filter(|(_, (_, unavailable))| !unavailable)
.map(|(root, (head, _))| (root, head))
.collect()
} else {
let mut picked: Vec<(PathBuf, Option<String>)> = Vec::new();
for path in targets {
// The innermost repository containing the path.
let repo = match innermost_repo(repos.clone(), &path) {
Some((root, (_, true))) => {
if wanted.is_some() {
return Err(IdeError::unavailable(format!(
"Git repository '{}' is currently unavailable",
relative_to_project(&call, &root)
)));
}
continue;
}
Some((root, (head, false))) => (root, head),
Some(repo) => repo,
None => match find_git_root(call.root(), &path) {
Some(root) => {
// JetBrains reads the branch of any repository it reports.
+2 -30
Переглянути файл
@@ -1,15 +1,13 @@
mod kotlin;
#[cfg(test)]
mod kotlin_tests;
#[cfg(test)]
mod native_tests;
mod output;
use crate::Host;
use ide_command::command;
use ide_core::{DebugSessionId, IdeResult};
use ide_dap::*;
use std::path::{Path, PathBuf};
use std::path::PathBuf;
/// Starts a session owned by this window: its events (and those of child sessions) go here only.
#[command(trust = trusted)]
@@ -142,17 +140,6 @@ pub async fn debug_start(host: &Host, window: &str, config: LaunchConfig) -> Ide
config = add_java_source_paths(config, &roots);
}
let root = config.cwd.clone().map(PathBuf::from).unwrap_or_default();
// No lldb-dap on this host (most Linux hosts): CodeLLDB, else GDB 14+.
if config.adapter == "lldb-dap" {
let (root, settings) = (root.clone(), settings.clone());
let project_root = project.root.clone();
config = ide_dap::native::choose(config, move |command| {
native_debugger_command(&project_root, &settings.debugger.cpp, command)
.or_else(|| ide_sdk::apply::tool_command(&root, &settings, command))
.or_else(|| ide_dap::adapter::resolve_binary(command, &root))
})
.await?;
}
let mut ruby_tools = Vec::new();
if config.adapter == "rdbg" && config.request == "launch" {
let project_root = host.project(window).map(|p| p.root.clone()).unwrap_or_else(|_| root.clone());
@@ -165,13 +152,11 @@ pub async fn debug_start(host: &Host, window: &str, config: LaunchConfig) -> Ide
.await?;
}
let java_analyzer = java_analyzer_command(host, window, &config)?;
let native = native_debugger_command(&project.root, &settings.debugger.cpp, &config.adapter);
let custom = |command: &str| {
if let Some(binary) = java_analyzer {
return Some(binary.to_string_lossy().into_owned());
}
let path = native
.or_else(|| ide_sdk::apply::tool_command(&root, &settings, command))
let path = ide_sdk::apply::tool_command(&root, &settings, command)
.or_else(|| ruby_tools.into_iter().find(|(name, _)| *name == command).map(|(_, path)| path))?;
Some(path.to_string_lossy().into_owned())
};
@@ -203,19 +188,6 @@ pub async fn debug_start(host: &Host, window: &str, config: LaunchConfig) -> Ide
result
}
fn native_debugger_command(
root: &Path,
settings: &ide_core::settings::CppDebuggerSettings,
adapter: &str,
) -> Option<PathBuf> {
let path = match adapter {
"gdb" => &settings.gdb_executable,
"lldb-dap" => &settings.lldb_dap_executable,
_ => return None,
};
ide_sdk::apply::setting_path(root, path)
}
/// For java-analyzer's debugger, the executable of the java-analyzer serving the module
/// (`projectRoot`, else the working directory), so the session debugs with the server that
/// analyzes the code.
-63
Переглянути файл
@@ -1,63 +0,0 @@
use super::*;
use ide_core::IdeError;
use ide_dap::adapter::{AdapterLauncher, AdapterSpec, LaunchFuture};
use ide_workspace::SettingsScope;
use parking_lot::Mutex;
use std::sync::Arc;
#[derive(Default)]
struct CaptureAdapter(Mutex<Option<AdapterSpec>>);
impl AdapterLauncher for CaptureAdapter {
fn launch(&self, spec: AdapterSpec, _: Option<u16>) -> LaunchFuture {
*self.0.lock() = Some(spec);
Box::pin(async { Err(IdeError::cancelled()) })
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn cpp_debugger_paths_override_adapter_commands() {
let dir = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(dir.path()).unwrap();
let root = base.join("project");
let cwd = root.join("build");
std::fs::create_dir_all(&cwd).unwrap();
let capture = Arc::new(CaptureAdapter::default());
let mut host = Host::new(crate::HostConfig::for_test(&base));
host.debugger = DebugManager::with_launcher(host.languages.clone(), capture.clone());
host.open_project("main", &root).unwrap();
host.set_project_trust(&root, true, false).await.unwrap();
let project = host.project("main").unwrap();
for (adapter, key, configured) in [
("gdb", "gdbExecutable", root.join("custom gdb").to_str().unwrap().to_owned()),
("lldb-dap", "lldbDapExecutable", "tools/lldb-dap-custom".into()),
] {
let config = LaunchConfig {
name: "C++".into(),
adapter: adapter.into(),
request: "attach".into(),
program: None,
args: vec![],
cwd: Some(cwd.clone().into()),
env: Default::default(),
extra_json: Some(r#"{"pid":1}"#.into()),
};
let _ = debug_start(&host, "main", config.clone()).await.unwrap_err();
assert_eq!(capture.0.lock().take().unwrap().command, adapter);
project
.settings
.set(SettingsScope::Project, &format!("debugger.cpp.{key}"), serde_json::json!(configured))
.unwrap();
let mut config = config;
config.request = "launch".into();
config.program = Some(cwd.join("app").to_str().unwrap().to_owned());
config.extra_json = None;
let _ = debug_start(&host, "main", config).await.unwrap_err();
let spec = capture.0.lock().take().unwrap();
assert_eq!(spec.adapter, adapter);
assert_eq!(Path::new(&spec.command), root.join(configured));
assert_eq!(spec.cwd, cwd);
}
}
+10 -57
Переглянути файл
@@ -1,34 +1,19 @@
use crate::project::Project;
use ide_core::IdeResult;
use ide_dap::LaunchConfig;
use ide_workspace::roots::{RootKind, SourceFolder};
use std::collections::{BTreeMap, HashSet};
use ide_workspace::roots::RootKind;
use std::collections::BTreeMap;
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> {
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);
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);
}
}
}
paths
@@ -135,38 +120,6 @@ 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]
+6 -43
Переглянути файл
@@ -190,10 +190,6 @@ pub struct VcsRoot {
/// Conflicts staged during the current operation that can be reopened.
#[serde(default)]
pub resolved_conflicts: Vec<ide_core::IpcPath>,
/// The repository's worktree or git directory is missing or on an unmounted volume.
#[serde(default)]
#[specta(optional)]
pub unavailable: bool,
}
#[derive(Clone, Serialize, Deserialize, Type)]
@@ -535,23 +531,6 @@ pub async fn vcs_detected_roots(host: &Host, window: &str) -> IdeResult<Vec<Path
blocking(move || project.detected_repository_roots()).await
}
fn unavailable_vcs_root(root: &Path) -> VcsRoot {
VcsRoot {
root: root.into(),
branch_root: root.into(),
operation: None,
interactive_rebase: false,
head: None,
head_commit: None,
shallow: false,
lfs: false,
uninitialized_submodules: Vec::new(),
has_remotes: None,
resolved_conflicts: Vec::new(),
unavailable: true,
}
}
/// The project's repositories, the primary one first.
#[command(trust = always)]
pub async fn vcs_roots(host: &Host, window: &str) -> IdeResult<Vec<VcsRoot>> {
@@ -562,17 +541,10 @@ pub async fn vcs_roots(host: &Host, window: &str) -> IdeResult<Vec<VcsRoot>> {
let primary = repos.primary().map(|r| r.root().to_path_buf());
let mut all: Vec<_> = repos.all().iter().collect();
all.sort_by_key(|r| Some(r.root()) != primary.as_deref());
let roots: Vec<_> = all
.into_iter()
.map(|repo| {
let dirs = repo.check_valid().ok().and_then(|()| repo.metadata_dirs().ok());
let available = dirs.is_some() && !repo.is_stale();
(repo, available, dirs)
})
.collect();
let roots: Vec<_> = all.into_iter().map(|repo| (repo, repo.metadata_dirs().ok())).collect();
let mut branch_roots = std::collections::HashMap::new();
for (repo, available, dirs) in &roots {
if *available && let Some([git_dir, common_dir]) = dirs {
for (repo, dirs) in &roots {
if let Some([git_dir, common_dir]) = dirs {
let first = branch_roots.entry(common_dir).or_insert(repo.root());
if git_dir == common_dir {
*first = repo.root();
@@ -581,10 +553,7 @@ pub async fn vcs_roots(host: &Host, window: &str) -> IdeResult<Vec<VcsRoot>> {
}
Ok(roots
.iter()
.map(|(r, available, dirs)| {
if !available {
return unavailable_vcs_root(r.root());
}
.map(|(r, dirs)| {
let branch_root = dirs.as_ref().and_then(|[_, common_dir]| branch_roots.get(common_dir));
let (head, head_commit) = r.head().unwrap_or_default();
let operation = r.operation().ok().flatten();
@@ -596,11 +565,6 @@ pub async fn vcs_roots(host: &Host, window: &str) -> IdeResult<Vec<VcsRoot>> {
.into_iter()
.map(Into::into)
.collect();
let has_remotes = trusted.then(|| r.has_remotes().ok()).flatten();
let shallow = r.is_shallow().unwrap_or(false);
if r.is_stale() {
return unavailable_vcs_root(r.root());
}
VcsRoot {
root: r.root().into(),
branch_root: branch_root.copied().unwrap_or_else(|| r.root()).into(),
@@ -608,7 +572,7 @@ pub async fn vcs_roots(host: &Host, window: &str) -> IdeResult<Vec<VcsRoot>> {
interactive_rebase,
head,
head_commit,
shallow,
shallow: r.is_shallow().unwrap_or(false),
lfs: r.uses_lfs(),
uninitialized_submodules: r
.uninitialized_submodules()
@@ -616,9 +580,8 @@ pub async fn vcs_roots(host: &Host, window: &str) -> IdeResult<Vec<VcsRoot>> {
.iter()
.map(|path| ide_core::ipc_path::to_ipc(path))
.collect(),
has_remotes,
has_remotes: trusted.then(|| r.has_remotes().ok()).flatten(),
resolved_conflicts,
unavailable: false,
}
})
.collect())
+2 -6
Переглянути файл
@@ -386,12 +386,8 @@ impl Host {
}));
}
{
// Weak: `documents` keeps `lsp` alive through its observers, so a strong handle here would be
// a cycle that leaks every closed project's documents, registry and language manager.
let documents = Arc::downgrade(&documents);
lsp.set_apply_edit_hook(Box::new(move |edit| {
documents.upgrade().is_some_and(|documents| documents.apply_workspace_edit(&edit).is_ok())
}));
let documents = documents.clone();
lsp.set_apply_edit_hook(Box::new(move |edit| documents.apply_workspace_edit(&edit).is_ok()));
}
let syntax = Arc::new(SyntaxCache::new(self.syntax()));
documents.add_observer(Arc::new(SyntaxObserver(syntax.clone())));
-43
Переглянути файл
@@ -87,46 +87,3 @@ fn detached_close_returns_while_runtime_workers_wait_for_the_closing_thread() {
host.shutdown_notebooks_on_exit();
assert!(started.elapsed() < Duration::from_secs(5), "exit joined the finished close instead of timing out");
}
/// `Documents` keeps the language manager alive through its observers and the manager once held the
/// documents back, so a closed project's documents (and everything they reference) were never freed.
/// Checked for the synchronous close and for the detached close that a window uses.
#[test]
fn closing_a_project_frees_its_documents() {
for detached in [false, true] {
assert_close_frees_documents(detached);
}
}
fn assert_close_frees_documents(detached: bool) {
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap().join("project");
std::fs::create_dir_all(&root).unwrap();
let runtime = tokio::runtime::Builder::new_multi_thread().worker_threads(2).enable_all().build().unwrap();
let _guard = runtime.enter();
let host = Arc::new(Host::new(common::host_config(tmp.path())));
host.trust.decide(&root, true, false).unwrap();
host.open_project("main", &root).unwrap();
let (documents, languages) = {
let project = host.project("main").unwrap();
(Arc::downgrade(&project.documents), Arc::downgrade(&project.languages))
};
assert!(documents.upgrade().is_some(), "the open project owns its documents");
if detached {
host.close_project_detached("main");
} else {
host.close_project("main");
}
// The detached close drops the project on its own thread.
let deadline = Instant::now() + Duration::from_secs(5);
while documents.upgrade().is_some() && Instant::now() < deadline {
std::thread::sleep(Duration::from_millis(10));
}
assert!(documents.upgrade().is_none(), "detached={detached}: the documents of a closed project are still alive");
assert!(
languages.upgrade().is_none(),
"detached={detached}: the language registry of a closed project is still alive"
);
}
-57
Переглянути файл
@@ -572,60 +572,3 @@ async fn a_repository_created_in_the_project_is_known_when_init_returns() {
let roots: Vec<_> = project.repos().all().iter().map(|r| r.root().to_path_buf()).collect();
assert_eq!(roots, [project_root]);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn vcs_roots_reports_unavailable_root_until_it_returns() {
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
let project_root = base.join("project");
let external_main = base.join("external-main");
let wt = project_root.join("wt");
let healthy = project_root.join("healthy");
for root in [&external_main, &healthy] {
std::fs::create_dir_all(root).unwrap();
git(root, &["init", "-b", "main"]);
git(root, &["config", "user.name", "Test"]);
git(root, &["config", "user.email", "[email protected]"]);
std::fs::write(root.join("file.txt"), "hello\n").unwrap();
git(root, &["add", "."]);
git(root, &["commit", "-m", "initial"]);
}
git(&external_main, &["worktree", "add", "-b", "wt-branch", wt.to_str().unwrap()]);
let host = Host::new(common::host_config(&base));
host.trust.decide(&project_root, true, false).unwrap();
let project = host.open_project("main", &project_root).unwrap();
for _ in 0..500 {
if project.repos().all().len() == 2 {
break;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
assert_eq!(project.repos().all().len(), 2);
// Move the linked worktree's metadata dir (outside project_root) aside so the project FileWatcher never races.
let wt_git_dir = external_main.join(".git/worktrees/wt");
let parked_git_dir = base.join("parked-wt-git");
std::fs::rename(&wt_git_dir, &parked_git_dir).unwrap();
let roots = vcs::vcs_roots(&host, "main").await.unwrap();
let wt_root = roots.iter().find(|r| r.root.0 == wt).unwrap();
let healthy_root = roots.iter().find(|r| r.root.0 == healthy).unwrap();
assert!(wt_root.unavailable);
assert!(wt_root.head.is_none());
assert!(wt_root.head_commit.is_none());
assert!(wt_root.operation.is_none());
assert!(wt_root.has_remotes.is_none());
assert_eq!(wt_root.branch_root.0, wt);
assert!(!healthy_root.unavailable);
assert_eq!(healthy_root.head.as_deref(), Some("main"));
std::fs::rename(&parked_git_dir, &wt_git_dir).unwrap();
let restored = vcs::vcs_roots(&host, "main").await.unwrap();
let wt_restored = restored.iter().find(|r| r.root.0 == wt).unwrap();
let healthy_restored = restored.iter().find(|r| r.root.0 == healthy).unwrap();
assert!(!wt_restored.unavailable);
assert_eq!(wt_restored.head.as_deref(), Some("wt-branch"));
assert!(!healthy_restored.unavailable);
host.close_project("main");
}
-71
Переглянути файл
@@ -530,77 +530,6 @@ src/local/
assert!(listed[0].ignored);
}
#[test]
fn root_anchored_gitignore_is_honoured_and_does_not_match_nested_names() {
let dir = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(dir.path()).unwrap();
for f in ["src/a.rs", "build/gen.rs", "build/nested/out.rs", "packages/foo/build/x.rs", "tmp/scratch.rs"] {
touch(&root, f);
}
std::fs::write(
root.join(".gitignore"),
"# Flutter-style root build output
/build/
tmp/
",
)
.unwrap();
let filter = PathFilter::new(&root, &vec![].into(), &[]);
let mut found: Vec<(String, bool)> = filter
.walk(&root, &AtomicBool::new(false))
.iter()
.filter_map(|f| Some((filter.rel(&f.path)?, f.ignored)))
.collect();
found.sort();
// Root-anchored `/build/` ignores only the root `build/` tree. Unanchored
// `tmp/` is also filename-only. A nested directory named `build` is kept.
assert_eq!(
found,
[
(".gitignore", false),
("build/gen.rs", true),
("build/nested/out.rs", true),
("packages/foo/build/x.rs", false),
("src/a.rs", false),
("tmp/scratch.rs", true),
]
.map(|(p, i)| (p.to_owned(), i))
);
for rel in ["build/gen.rs", "build/nested/out.rs", "packages/foo/build/x.rs", "tmp/scratch.rs", "src/a.rs"] {
assert!(!filter.is_excluded(&root.join(rel)), "{rel}");
}
let mut listed: Vec<(String, bool)> = filter
.list_dir(&root.join("build"))
.iter()
.filter_map(|f| Some((filter.rel(&f.path)?, f.ignored)))
.collect();
listed.sort();
assert_eq!(listed, [("build/gen.rs", true)].map(|(p, i)| (p.to_owned(), i)));
}
#[test]
fn root_anchored_exclude_file_is_honoured() {
let dir = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(dir.path()).unwrap();
touch(&root, "src/a.rs");
touch(&root, "build/gen.rs");
std::fs::create_dir_all(root.join(".git/info")).unwrap();
std::fs::write(
root.join(".git/info/exclude"),
"/build/
",
)
.unwrap();
let filter = PathFilter::new(&root, &vec![].into(), &[]);
let mut found: Vec<(String, bool)> = filter
.walk(&root, &AtomicBool::new(false))
.iter()
.filter_map(|f| Some((filter.rel(&f.path)?, f.ignored)))
.collect();
found.sort();
assert_eq!(found, [("build/gen.rs", true), ("src/a.rs", false)].map(|(p, i)| (p.to_owned(), i)));
}
#[test]
fn a_nested_repository_is_not_hidden_by_the_outer_repositorys_gitignore() {
let dir = tempfile::tempdir().unwrap();
-4
Переглянути файл
@@ -390,10 +390,6 @@ impl Store {
})
}
pub(crate) fn snapshot_exists(&self) -> bool {
self.snapshot.is_file()
}
fn open_db(&self) -> Result<Database> {
let file = self.snapshot.with_file_name("index.redb");
let db = match Database::builder().set_cache_size(DB_CACHE_BYTES).create(&file) {
+8 -51
Переглянути файл
@@ -601,11 +601,8 @@ impl Shared {
d.remove(path);
}
}
let index_changed = !stale.is_empty() || !todo.is_empty();
let stale: Vec<String> = stale.iter().filter_map(|p| filter.store_key(p)).collect();
if !stale.is_empty() {
self.persist(&[], &stale, false);
}
self.persist(&[], &stale, false);
let total = todo.len();
if task.is_none() && total >= QUIET_SCAN_FILES {
@@ -677,31 +674,25 @@ impl Shared {
return None;
}
let durable_started = Instant::now();
if index_changed {
self.persist(&[], &[], true);
}
self.persist(&[], &[], true);
let durable = durable_started.elapsed();
let update_elapsed = update_started.elapsed();
let snapshot_started = Instant::now();
if let Some(store) = &self.store {
let recent: Vec<String> = self.recent.lock().iter().filter_map(|p| filter.recent_key(p)).collect();
// process() may already have applied the change and deleted the snapshot;
// a follow-up reconcile scan can have scheduled=0 and still need to write it.
if index_changed || !store.snapshot_exists() {
let d = self.data.read();
let snapshot_started = Instant::now();
if let Err(e) = store.save_snapshot(&d, &filter, guard) {
tracing::warn!("index snapshot: {e}");
}
tracing::info!("index snapshot: written in {:?}", snapshot_started.elapsed());
*self.snapshot_saved.lock() = Some(Instant::now());
let d = self.data.read();
let snapshot_started = Instant::now();
if let Err(e) = store.save_snapshot(&d, &filter, guard) {
tracing::warn!("index snapshot: {e}");
}
tracing::info!("index snapshot: written in {:?}", snapshot_started.elapsed());
if let Err(e) = store.save_recent_file(&recent) {
tracing::warn!("index recent snapshot: {e}");
}
}
let snapshot_elapsed = snapshot_started.elapsed();
*self.snapshot_due.lock() = None;
*self.snapshot_saved.lock() = Some(Instant::now());
if let Some(task) = task {
self.indexing.store(false, Ordering::SeqCst);
self.sink.emit(IdeEvent::Task {
@@ -1452,40 +1443,6 @@ mod metric_tests {
assert_eq!(shared.data.read().symbol_count, 1);
}
#[test]
fn no_change_scan_skips_snapshot_rewrite() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path().join("project");
std::fs::create_dir(&root).unwrap();
let root = dunce::canonicalize(root).unwrap();
std::fs::write(root.join("main.rs"), "fn main() {}\n").unwrap();
let cache = dir.path().join("cache");
let mut index = shared(&root);
index.store = Some(Store::open(&cache, &root, "metrics-test").unwrap());
// A guard after every write, so save_snapshot does not discard the file
// when a directory mtime lands on the same instant as the scan start.
let guard = || SystemTime::now() + std::time::Duration::from_secs(2);
let cold = index.scan(None, &[], None, guard()).unwrap();
assert_eq!(cold.scheduled, 1);
let snapshot = cache.join("index.snapshot");
assert!(snapshot.exists());
let before = std::fs::metadata(&snapshot).unwrap();
// A rewrite would bump mtime; give the filesystem a distinct timestamp.
std::thread::sleep(std::time::Duration::from_millis(20));
let hot = index.scan(None, &[], None, guard()).unwrap();
assert_eq!((hot.discovered, hot.metadata_reused, hot.scheduled), (1, 1, 0));
let after = std::fs::metadata(&snapshot).unwrap();
assert_eq!(after.len(), before.len(), "a no-change scan must not rewrite the snapshot");
assert_eq!(after.modified().unwrap(), before.modified().unwrap());
std::fs::write(root.join("main.rs"), "fn renamed() {}\n").unwrap();
std::thread::sleep(std::time::Duration::from_millis(20));
let changed = index.scan(None, &[], None, guard()).unwrap();
assert_eq!(changed.scheduled, 1);
let rewritten = std::fs::metadata(&snapshot).unwrap();
assert!(rewritten.modified().unwrap() > after.modified().unwrap(), "a changed scan must refresh the snapshot");
}
#[test]
fn extraction_outcomes_are_exclusive_and_forced_parsing_is_counted() {
let dir = tempfile::tempdir().unwrap();
-15
Переглянути файл
@@ -727,21 +727,6 @@ mod tests {
}
}
#[test]
fn java_analyzer_does_not_fill_empty_files() {
let reg = reg();
let java = reg.get(&LanguageId::new("java")).unwrap();
let analyzer = java.language_servers.iter().find(|s| s.name == "java-analyzer").unwrap();
assert_eq!(
analyzer
.initialization_options
.as_ref()
.and_then(|v| v.get("newFileTemplate"))
.and_then(toml::Value::as_bool),
Some(false)
);
}
#[test]
fn angular_server_joins_typescript_and_html_in_angular_projects() {
let reg = reg();
+1 -56
Переглянути файл
@@ -503,30 +503,12 @@ impl LaunchScope {
}
}
/// m2e can run package-phase mojos such as `dependency:copy-dependencies` during
/// `java/buildWorkspace`. In an incremental IDE build the reactor jars are not
/// packaged, so the plugin fails with MDEP-187 (copy) or MDEP-98 (unpack). That is
/// not a Java compile error, and a main-class launch does not need the copied jars.
/// Debug uses this workspace build (so java-debug can HotSwap the classes jdtls
/// compiled); Run uses the IDE's Java build and never hits the mojo. Ignoring the
/// marker keeps the two consistent when the Java sources compiled.
fn is_reactor_packaging_mojo_error(message: &str) -> bool {
let lower = message.to_ascii_lowercase();
lower.contains("has not been packaged yet") && lower.contains("executed after packaging")
}
/// JDTLS reports all imported projects; report errors for the launch and its dependencies.
fn launch_compile_errors(
scope: &LaunchScope,
diagnostics: Vec<(PathBuf, lsp_types::Diagnostic)>,
) -> (Vec<JavaCompileError>, u32) {
compile_errors(
diagnostics
.into_iter()
.filter(|(path, d)| scope.includes(path) && !is_reactor_packaging_mojo_error(&d.message))
.collect(),
MAX_LAUNCH_ERRORS,
)
compile_errors(diagnostics.into_iter().filter(|(path, _)| scope.includes(path)).collect(), MAX_LAUNCH_ERRORS)
}
/// `java.project.getClasspaths` result.
@@ -1777,43 +1759,6 @@ mod tests {
}
}
#[test]
fn debug_launch_ignores_mdep_reactor_packaging_errors() {
let cp = JavaClasspath {
class_paths: vec!["/p/app/target/classes".into(), "/p/library/target/classes".into()],
..Default::default()
};
let scope = LaunchScope::new(Path::new("/p/app"), false, Some(&cp));
let diagnostic = |message: &str| lsp_types::Diagnostic {
severity: Some(lsp_types::DiagnosticSeverity::ERROR),
message: message.into(),
range: lsp_types::Range::new(lsp_types::Position::new(299, 21), lsp_types::Position::new(299, 31)),
..Default::default()
};
// m2e's BuildProblemInfo: the CoreException message, then the execution key,
// then the stack whose cause is the plugin's MDEP-187 / MDEP-98 text.
let copy = "Failed to execute mojo org.apache.maven.plugins:maven-dependency-plugin:3.6.1:copy-dependencies {execution: copy-dependencies} (org.apache.maven.plugins:maven-dependency-plugin:3.6.1:copy-dependencies:copy-dependencies:package)\n\norg.eclipse.core.runtime.CoreException: Failed to execute mojo org.apache.maven.plugins:maven-dependency-plugin:3.6.1:copy-dependencies {execution: copy-dependencies}\n\t at org.eclipse.m2e.core.project.configurator.MojoExecutionBuildParticipant.build(MojoExecutionBuildParticipant.java:57)\nCaused by: org.apache.maven.plugin.MojoExecutionException:\nArtifact has not been packaged yet. When used on reactor artifact, copy should be executed after packaging: see MDEP-187.";
let unpack = "Failed to execute mojo org.apache.maven.plugins:maven-dependency-plugin:3.6.1:unpack-dependencies {execution: unpack-dependencies}\nCaused by: org.apache.maven.plugin.MojoExecutionException: Artifact has not been packaged yet. When used on reactor artifact, unpack should be executed after packaging: see MDEP-98.";
let other_mojo = "Failed to execute mojo org.apache.maven.plugins:maven-compiler-plugin:3.13.0:compile {execution: default-compile}";
let (errors, count) = launch_compile_errors(
&scope,
vec![
(PathBuf::from("/p/app/pom.xml"), diagnostic(copy)),
(PathBuf::from("/p/app/pom.xml"), diagnostic(unpack)),
(PathBuf::from("/p/app/src/main/java/App.java"), diagnostic("App cannot be resolved to a type")),
(PathBuf::from("/p/app/pom.xml"), diagnostic(other_mojo)),
],
);
assert_eq!(count, 2);
assert_eq!(&*errors[0].path, Path::new("/p/app/pom.xml"));
assert_eq!(errors[0].message, other_mojo);
assert_eq!(&*errors[1].path, Path::new("/p/app/src/main/java/App.java"));
assert_eq!(errors[1].message, "App cannot be resolved to a type");
let (_, only_packaging) =
launch_compile_errors(&scope, vec![(PathBuf::from("/p/app/pom.xml"), diagnostic(copy))]);
assert_eq!(only_packaging, 0);
}
#[test]
fn unresolved_classpaths_retain_all_errors() {
for cp in [
-7
Переглянути файл
@@ -3405,17 +3405,10 @@ 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);
}
}
}
-25
Переглянути файл
@@ -482,31 +482,6 @@ 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 -19
Переглянути файл
@@ -881,9 +881,14 @@ async fn the_bridge_picks_the_server_again_when_the_servers_change() {
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_in(&discovery, WithBackground { open: proj_c.clone(), background: Vec::new(), remote: None });
let port = server_b.port();
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;
@@ -891,23 +896,8 @@ async fn the_bridge_picks_the_server_again_after_a_restart_on_the_same_port() {
assert_eq!(list["result"]["tools"][0]["name"], "everything", "{list}");
server_b.stop();
// stop signals the accept task; the listener is closed asynchronously. Wait for
// the old port to be released, as the IDE does before restarting its server.
tokio::time::timeout(std::time::Duration::from_secs(5), async {
while std::net::TcpListener::bind(("127.0.0.1", port)).is_err() {
tokio::time::sleep(std::time::Duration::from_millis(20)).await;
}
})
.await
.expect("the stopped server should release its port");
let server_b = McpServer::start_with(
Arc::new(WithBackground::serving(&proj_c, &proj_b)),
Some(discovery.clone()),
&tokio::runtime::Handle::current(),
ServerOptions { port: Some(port), ..Default::default() },
)
.unwrap();
assert_eq!(server_b.port(), port, "{:?}", server_b.port_unavailable());
let 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;
+10 -11
Переглянути файл
@@ -636,24 +636,23 @@ impl ProcessManager {
let mut cmd = CommandBuilder::new(&inv.program);
cmd.args(&inv.args);
cmd.cwd(cwd);
// 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);
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),
}
}
for (k, v) in ide_core::process::shell_env_in(cwd) {
if ide_core::process::is_spawnable_env_pair(&k, &v) {
cmd.env(k, v);
}
cmd.env(k, v);
}
}
cmd.env("TERM", "xterm-256color");
cmd.env("COLORTERM", "truecolor");
for (k, v) in &env.vars {
if ide_core::process::is_spawnable_env_pair(std::ffi::OsStr::new(k), std::ffi::OsStr::new(v)) {
cmd.env(k, v);
}
cmd.env(k, v);
}
#[cfg(unix)]
let wait_writable = ide_core::input::nonblocking(
-16
Переглянути файл
@@ -62,22 +62,6 @@ fn round_trip() {
assert!(!loaded[0].detected);
}
#[test]
fn docker_detach_round_trips_in_project_params() {
let dir = tempfile::tempdir().unwrap();
let mut configs = sample();
for (config, (kind, detach)) in configs.iter_mut().zip([("docker-dockerfile", "true"), ("docker-image", "false")]) {
config.kind = kind.into();
config.extras.params.insert("detach".into(), detach.into());
}
save_user_configs(dir.path(), &configs).unwrap();
let project = fs::read_to_string(user_configs_path(dir.path())).unwrap();
assert!(project.contains("params = { detach = \"true\" }"), "{project}");
assert!(project.contains("params = { detach = \"false\" }"), "{project}");
assert_eq!(load_user_configs(dir.path()).unwrap(), configs);
}
#[test]
fn preserves_unrelated_content() {
let dir = tempfile::tempdir().unwrap();
+7 -10
Переглянути файл
@@ -344,18 +344,15 @@ impl TerminalManager {
resolve_cwd(&options.cwd)
};
cmd.cwd(&cwd);
// 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);
// 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),
}
}
for (k, v) in env {
if ide_core::process::is_spawnable_env_pair(std::ffi::OsStr::new(&k), std::ffi::OsStr::new(&v)) {
cmd.env(k, v);
}
cmd.env(k, v);
}
apply_powershell_env(&shell, &mut cmd);
+4 -10
Переглянути файл
@@ -81,7 +81,7 @@ impl LineEnding {
}
/// How long [`Document::diff`] may look for separate regions, so a reload never stalls on a huge file.
pub const DIFF_BUDGET: Duration = Duration::from_millis(50);
const DIFF_BUDGET: Duration = Duration::from_millis(50);
type LineRange = std::ops::Range<usize>;
@@ -741,12 +741,6 @@ mod tests {
assert_eq!(doc.text(), "😀x😀");
}
/// `diff` without its time budget: a loaded machine can spend 50 ms before the first deadline
/// check, and the coarser result is right too, just not what these tests pin down.
fn unhurried_diff(doc: &Document, text: &str) -> ChangeSet {
doc.diff_until(text, std::time::Instant::now() + std::time::Duration::from_secs(3600))
}
fn numbered_lines(n: usize) -> String {
(0..n).map(|i| format!("line {i}\n")).collect()
}
@@ -756,7 +750,7 @@ mod tests {
let old = numbered_lines(400);
let new = old.replace("line 20\n", "line 20x\n").replace("line 299\n", "line 299x\n");
let at = |line: &str| (old.find(line).unwrap() + line.len() - 1) as u32;
let set = unhurried_diff(&Document::new(&old), &new);
let set = Document::new(&old).diff(&new);
assert_eq!(
set.changes,
vec![tc(at("line 20\n"), at("line 20\n"), "x"), tc(at("line 299\n"), at("line 299\n"), "x")]
@@ -766,14 +760,14 @@ mod tests {
#[test]
fn diff_handles_added_and_removed_lines() {
let old = "a\nb\nc\nd\ne\nf\n";
let set = unhurried_diff(&Document::new(old), "a\nnew\nb\nc\ne\nf\n");
let set = Document::new(old).diff("a\nnew\nb\nc\ne\nf\n");
assert_eq!(set.changes, vec![tc(2, 2, "new\n"), tc(5, 7, "")]);
}
#[test]
fn diff_counts_utf16_past_astral_text() {
let old = "😀 one\nsame\n😀 two\n";
let set = unhurried_diff(&Document::new(old), "😀 ONE\nsame\n😀 TWO\n");
let set = Document::new(old).diff("😀 ONE\nsame\n😀 TWO\n");
assert_eq!(set.changes, vec![tc(3, 6, "ONE"), tc(15, 18, "TWO")]);
}
+7 -52
Переглянути файл
@@ -171,14 +171,6 @@ fn bin_dirs_in(root: &Path, platform: Platform) -> Vec<PathBuf> {
dirs
}
/// How [`Method::DotnetTool`] installs a package.
#[derive(Clone, Copy)]
struct DotnetToolOptions {
package: &'static str,
prerelease: bool,
min_sdk: u32,
}
fn managed_bin_dir(root: &Path, spec: &ToolSpec, platform: Platform) -> Option<PathBuf> {
match spec.fallback.unwrap_or(spec.method) {
Method::Npm { .. } => Some(root.join("node_modules").join(".bin")),
@@ -1057,10 +1049,7 @@ impl Tools {
Method::Go { module } => self.install_go(spec, module, cancel, emit)?,
Method::Gem { gem } => self.install_gem(spec, gem, cancel, emit)?,
Method::GemActive { gem } => self.install_gem_active(gem, cancel, emit)?,
Method::DotnetTool { package, prerelease, min_sdk } => {
let options = DotnetToolOptions { package, prerelease, min_sdk };
self.install_dotnet_tool(spec, options, langs, cancel, emit)?
}
Method::DotnetTool { package } => self.install_dotnet_tool(spec, package, cancel, emit)?,
Method::PipVenv { package } => self.install_venv(spec, package, cancel, emit)?,
Method::PipUser { package, .. } => self.install_pip_user(package, cancel, emit)?,
Method::PipTarget { package, .. } => self.install_pip_target(spec, package, cancel, emit)?,
@@ -1231,28 +1220,20 @@ impl Tools {
fn install_dotnet_tool(
&self,
spec: &ToolSpec,
options: DotnetToolOptions,
langs: &[LanguageConfig],
package: &str,
cancel: &CancellationToken,
emit: Emit,
) -> IdeResult<()> {
let DotnetToolOptions { package, prerelease, .. } = options;
let dir = self.root.join(spec.name);
let _ = std::fs::remove_dir_all(&dir);
let tool = dir.join("tool");
std::fs::create_dir_all(&tool)?;
let dotnet = self.which("dotnet").expect("checked");
let version = self.dotnet_tool_version(spec, options, langs, &dotnet, cancel, emit)?;
let version = self.dotnet_tool_version(spec, package, &dotnet, cancel, emit)?;
let mut c = self.command(&dotnet);
c.args(["tool", "install", package, "--tool-path"]).arg(&tool).args(["--verbosity", "normal"]);
match &version {
Some(version) => {
c.args(["--version", version]);
}
None if prerelease => {
c.arg("--prerelease");
}
None => {}
if let Some(version) = &version {
c.args(["--version", version]);
}
let result = run_streamed_picking(c, cancel, emit, dotnet::nuget_errors).and_then(|_| {
// The tool's apphost looks for .NET in the default location only; a
@@ -1287,20 +1268,17 @@ impl Tools {
}
/// The `--version` to install `package` with: `None` for the latest, or the newest version
/// the installed SDK supports. Fails when there is no SDK, it is older than `min_sdk`, or no
/// version runs on it.
/// the installed SDK supports. Fails when there is no SDK, or no version runs on it.
fn dotnet_tool_version(
&self,
spec: &ToolSpec,
options: DotnetToolOptions,
langs: &[LanguageConfig],
package: &str,
dotnet: &Path,
cancel: &CancellationToken,
emit: Emit,
) -> IdeResult<Option<String>> {
let mut c = self.command(dotnet);
c.arg("--list-sdks");
let DotnetToolOptions { package, prerelease, min_sdk } = options;
let Some((true, out)) = run_quiet(c, Duration::from_secs(20)) else { return Ok(None) };
let Some(sdk) = dotnet::newest_sdk(&out) else {
return Err(IdeError::unavailable(format!(
@@ -1309,29 +1287,6 @@ impl Tools {
dotnet::SDK_DOWNLOAD_URL
)));
};
if sdk.major < min_sdk {
// An alternative server for the same files that this SDK can install.
let instead = usages(langs)
.get(spec.name)
.into_iter()
.flat_map(|u| u.alternatives.iter())
.filter(|name| *name != spec.name)
.filter_map(|name| registry::find(name))
.find(|alt| matches!(alt.method, Method::DotnetTool { min_sdk, .. } if min_sdk <= sdk.major))
.map(|alt| format!(", or install {}, which runs on it", alt.display))
.unwrap_or_default();
return Err(IdeError::unavailable(format!(
"{} needs the .NET {min_sdk} SDK or newer; found {}. Install it from {}{instead}",
spec.display,
sdk.version,
dotnet::SDK_DOWNLOAD_URL
)));
}
// nuget.org's version index used below lists SemVer 1 versions only, which leaves out
// most prereleases: let `--prerelease` pick the newest one.
if prerelease {
return Ok(None);
}
let pick = self
.http()
.and_then(|http| dotnet::pick_tool_version(package, sdk.major, |url| http.get_text(url, cancel)));
+4 -18
Переглянути файл
@@ -61,10 +61,8 @@ pub enum Method {
/// (`~/Library/Application Support`: Bundler `exec`s a lone path string, and Ruby splits it).
GemActive { gem: &'static str },
/// `dotnet tool install --tool-path <tools>/<name>/tool <package>`, launched
/// through `DOTNET_ROOT` wrappers in `bin/`. `prerelease` installs the newest version,
/// prerelease or not, for packages that publish no stable one; `min_sdk` is the lowest
/// .NET SDK major that can install the package (0: any).
DotnetTool { package: &'static str, prerelease: bool, min_sdk: u32 },
/// through `DOTNET_ROOT` wrappers in `bin/`.
DotnetTool { package: &'static str },
/// Platform archive download into `<tools>/<name>/`.
Release { source: ReleaseSource, assets: &'static [AssetRule], locate: &'static [&'static str] },
}
@@ -1428,24 +1426,12 @@ pub static TOOLS: &[ToolSpec] = &[
homepage: "https://solargraph.org",
needs: &[],
},
ToolSpec {
name: "roslyn-language-server",
display: "Roslyn (C#)",
kind: LanguageServer,
commands: &["roslyn-language-server"],
// Prerelease builds only, as platform-specific tool packages: the .NET 10 SDK installs them.
method: Method::DotnetTool { package: "roslyn-language-server", prerelease: true, min_sdk: 10 },
fallback: None,
version: V,
homepage: "https://github.com/dotnet/roslyn",
needs: &[],
},
ToolSpec {
name: "csharp-ls",
display: "csharp-ls",
kind: LanguageServer,
commands: &["csharp-ls"],
method: Method::DotnetTool { package: "csharp-ls", prerelease: false, min_sdk: 0 },
method: Method::DotnetTool { package: "csharp-ls" },
fallback: None,
version: V,
homepage: "https://github.com/razzmatazz/csharp-language-server",
@@ -1456,7 +1442,7 @@ pub static TOOLS: &[ToolSpec] = &[
display: "FsAutoComplete (F#)",
kind: LanguageServer,
commands: &["fsautocomplete"],
method: Method::DotnetTool { package: "fsautocomplete", prerelease: false, min_sdk: 0 },
method: Method::DotnetTool { package: "fsautocomplete" },
fallback: None,
version: V,
homepage: "https://github.com/ionide/FsAutoComplete",
+1 -32
Переглянути файл
@@ -838,7 +838,7 @@ esac"#,
assert!(!env.root.join("ruby-lsp").exists());
}
/// Installs of one tool name share a slot, so parallel .NET tool tests would join each other's install.
/// Installs of one tool name share a slot, so parallel csharp-ls tests would join each other's install.
#[cfg(unix)]
static CSHARP_LS_INSTALL: parking_lot::Mutex<()> = parking_lot::Mutex::new(());
@@ -1020,37 +1020,6 @@ exit 1"#,
assert!(skipped);
}
#[cfg(unix)]
#[test]
fn prerelease_dotnet_tool_installs_with_prerelease_on_a_new_enough_sdk() {
let _serial = CSHARP_LS_INSTALL.lock();
let env = Env::new();
let calls = dotnet_with_nuget(
&env,
"10.0.404",
r#"/bin/mkdir -p "$5"; printf '#!/bin/sh\n' > "$5/roslyn-language-server"; /bin/chmod +x "$5/roslyn-language-server""#,
);
let info = env.tools().install("roslyn-language-server", &langs(), &CancellationToken::new(), &|_| {}).unwrap();
assert_eq!(info.status, ToolStatus::Installed);
let call = fs::read_to_string(&calls).unwrap();
assert!(call.trim_end().ends_with("--verbosity normal --prerelease"), "{call}");
}
#[cfg(unix)]
#[test]
fn dotnet_tool_on_an_older_sdk_names_the_sdk_and_an_alternative_that_runs_on_it() {
let _serial = CSHARP_LS_INSTALL.lock();
let env = Env::new();
let calls = dotnet_with_nuget(&env, "8.0.416", FAKE_TOOL_INSTALL);
let err = env.tools().install("roslyn-language-server", &langs(), &CancellationToken::new(), &|_| {}).unwrap_err();
assert_eq!(err.kind, ErrorKind::Unavailable);
assert_eq!(
err.message,
"Roslyn (C#) needs the .NET 10 SDK or newer; found 8.0.416. Install it from https://dotnet.microsoft.com/download, or install csharp-ls, which runs on it"
);
assert!(!calls.exists(), "dotnet tool install ran");
}
#[test]
fn kotlin_debugger_uses_existing_release_recipe_and_language_definition() {
let spec = registry::find("kotlin-debug-adapter").unwrap();
+12 -23
Переглянути файл
@@ -16,17 +16,17 @@ struct CommitMeta {
/// Parses `git blame --porcelain` output into one entry per final line.
pub(crate) fn parse_porcelain(out: &str, root: &Path, relative_path: &str) -> Vec<BlameLine> {
let mut metas: HashMap<String, CommitMeta> = HashMap::new();
let mut lines: Vec<(u32, String, Option<IpcPath>, Option<u32>)> = Vec::new();
let mut current: Option<(u32, String, Option<u32>)> = None;
let mut lines: Vec<(u32, String, Option<IpcPath>)> = Vec::new();
let mut current: Option<(u32, String)> = None;
for line in out.split('\n') {
if line.starts_with('\t') {
if let Some((number, id, origin_line)) = current.take() {
if let Some((number, id)) = current.take() {
let origin = metas.get(&id).and_then(|m| m.origin_path.clone());
lines.push((number, id, origin, origin_line));
lines.push((number, id, origin));
}
continue;
}
if let Some((_, id, _)) = current.as_ref() {
if let Some((_, id)) = current.as_ref() {
let meta = metas.entry(id.clone()).or_default();
if let Some(v) = line.strip_prefix("author ") {
meta.author = v.to_string();
@@ -48,7 +48,7 @@ pub(crate) fn parse_porcelain(out: &str, root: &Path, relative_path: &str) -> Ve
}
// Header: <sha> <orig-line> <final-line> [<group-count>]
let mut parts = line.split(' ');
let (Some(sha), Some(orig_line), Some(final_line)) = (parts.next(), parts.next(), parts.next()) else {
let (Some(sha), Some(_orig), Some(final_line)) = (parts.next(), parts.next(), parts.next()) else {
continue;
};
if sha.len() < 40 || !sha.bytes().all(|b| b.is_ascii_hexdigit()) {
@@ -56,23 +56,14 @@ pub(crate) fn parse_porcelain(out: &str, root: &Path, relative_path: &str) -> Ve
}
let Ok(final_line) = final_line.parse::<u32>() else { continue };
metas.entry(sha.to_string()).or_default();
// 1-based in the porcelain header.
let origin_line = orig_line.parse::<u32>().ok().and_then(|n| n.checked_sub(1));
current = Some((final_line, sha.to_string(), origin_line));
current = Some((final_line, sha.to_string()));
}
lines.sort_by_key(|(n, ..)| *n);
lines
.into_iter()
.map(|(_, sha, origin_path, origin_line)| {
.map(|(_, sha, origin_path)| {
let meta = metas.get(&sha).cloned().unwrap_or_default();
BlameLine {
commit: sha,
author: meta.author,
time_ms: meta.time_ms,
summary: meta.summary,
origin_path,
origin_line,
}
BlameLine { commit: sha, author: meta.author, time_ms: meta.time_ms, summary: meta.summary, origin_path }
})
.collect()
}
@@ -86,16 +77,14 @@ mod tests {
let sha_a = "a".repeat(40);
let sha_z = "0".repeat(40);
let out = format!(
"{sha_a} 11 17 2\nauthor Ann\nauthor-mail <a@x>\nauthor-time 100\nauthor-tz +0000\nsummary first\nfilename f\n\tl1\n\
{sha_a} 12 18\n\tl2\n\
{sha_z} 19 19 1\nauthor Not Committed Yet\nauthor-time 200\nsummary Version of f from f\nfilename f\n\tl3\n"
"{sha_a} 1 1 2\nauthor Ann\nauthor-mail <a@x>\nauthor-time 100\nauthor-tz +0000\nsummary first\nfilename f\n\tl1\n\
{sha_a} 2 2\n\tl2\n\
{sha_z} 3 3 1\nauthor Not Committed Yet\nauthor-time 200\nsummary Version of f from f\nfilename f\n\tl3\n"
);
let lines = parse_porcelain(&out, Path::new("root"), "f");
assert_eq!(lines.len(), 3);
assert_eq!(lines[1].author, "Ann");
assert_eq!(lines[1].time_ms, 100_000.0);
assert_eq!(lines[2].author, "Not Committed Yet");
// Where each line is in the attributed commit's file, 0-based: Show Diff opens there.
assert_eq!(lines.iter().map(|l| l.origin_line).collect::<Vec<_>>(), [Some(10), Some(11), Some(18)]);
}
}
-4
Переглянути файл
@@ -131,10 +131,6 @@ pub struct BlameLine {
#[serde(skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub origin_path: Option<ide_core::IpcPath>,
/// The line's 0-based number in the attributed commit's version of the file.
#[serde(skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub origin_line: Option<u32>,
}
/// History for Selection: the commits that changed a block of lines, newest first.
+11 -68
Переглянути файл
@@ -105,26 +105,16 @@ fn pack_stamp(pack_dir: &Path) -> Option<SystemTime> {
pub(crate) fn discover(path: &Path) -> IdeResult<Option<Repo>> {
let start = if path.is_file() { path.parent().unwrap_or(path) } else { path };
let found = match gix::discover::upwards(start) {
Ok((found, _trust)) => found,
Err(e) => {
use gix::discover::upwards::Error as E;
return match e.downcast_any_ref::<E>() {
Some(
E::NoGitRepository { .. }
| E::NoGitRepositoryWithinCeiling { .. }
| E::NoGitRepositoryWithinFs { .. },
) => Ok(None),
_ => Err(gx(e)),
};
}
};
// Opened like `gix()` reopens it, not with `ThreadSafeRepository::discover`: that picks the
// options for the folder owner's trust, and for a repository another user owns (reduced trust)
// they cap the object database at 32 pack indices. A repository with more packs then fails to
// read any object, so `HEAD` doesn't resolve (#7138). Trust is still decided per repository.
let (git_dir, worktree) = found.into_repository_and_work_tree_directories();
let ts = gix::ThreadSafeRepository::open(worktree.unwrap_or(git_dir)).map_err(gx)?;
if let Err(e) = gix::discover::upwards(start) {
use gix::discover::upwards::Error as E;
return match e.downcast_any_ref::<E>() {
Some(
E::NoGitRepository { .. } | E::NoGitRepositoryWithinCeiling { .. } | E::NoGitRepositoryWithinFs { .. },
) => Ok(None),
_ => Err(gx(e)),
};
}
let ts = gix::ThreadSafeRepository::discover(start).map_err(gx)?;
let repo = ts.to_thread_local();
let Some(workdir) = repo.workdir() else {
// Bare repositories have no worktree to show changes for.
@@ -188,7 +178,7 @@ impl Repo {
/// Verifies that the worktree root and its git directory exist on disk. A missing one marks
/// the repository stale and is logged once; when both are back (a drive reconnected, `git
/// worktree repair`), the mark is cleared, so a stale repository costs two `stat`s per check.
pub fn check_valid(&self) -> IdeResult<()> {
pub(crate) fn check_valid(&self) -> IdeResult<()> {
use std::sync::atomic::Ordering;
if self.root.is_dir() && self.git_dir.is_dir() {
if self.stale.swap(false, Ordering::AcqRel) {
@@ -668,53 +658,6 @@ mod tests {
assert!(cmd.status().unwrap().success(), "{cmd:?}");
}
/// More pack indices than the 32 slots `gix` gives a repository another user owns (#7138). The
/// owner can't be changed in a test, so this pins that discovery opens with slots sized by the
/// pack directory: objects in every pack stay readable through the cached handle.
#[test]
fn a_repository_with_many_packs_reads_objects_from_all_of_them() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().join("repo");
run(Command::new("git").args(["init", "-q", "-b", "main"]).arg(&root));
let git = |args: &[&str]| {
let out = Command::new("git").current_dir(&root).args(args).output().unwrap();
assert!(out.status.success(), "{args:?}");
String::from_utf8(out.stdout).unwrap().trim().to_owned()
};
git(&["config", "gc.auto", "0"]);
git(&["config", "maintenance.auto", "false"]);
let mut oids = Vec::new();
for i in 0..40 {
std::fs::write(root.join(format!("f{i}.txt")), format!("{i}\n")).unwrap();
git(&["add", "."]);
git(&["-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "-m", &format!("c{i}")]);
oids.push(git(&["rev-parse", "HEAD"]));
let mut pack = Command::new("git")
.current_dir(&root)
.args(["pack-objects", "-q", "--revs", ".git/objects/pack/pack"])
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::null())
.spawn()
.unwrap();
use std::io::Write;
let range = if i == 0 { "HEAD\n" } else { "HEAD\n^HEAD~1\n" };
pack.stdin.take().unwrap().write_all(range.as_bytes()).unwrap();
assert!(pack.wait().unwrap().success());
git(&["prune-packed"]);
}
let packs = std::fs::read_dir(root.join(".git/objects/pack"))
.unwrap()
.filter(|e| e.as_ref().unwrap().path().extension().is_some_and(|x| x == "idx"))
.count();
assert!(packs > 32, "{packs} pack indices");
let repo = discover(&root).unwrap().unwrap();
let gix = repo.gix().unwrap();
assert_eq!(gix.head_id().unwrap().to_string(), *oids.last().unwrap());
for oid in &oids {
gix.find_commit(gix::ObjectId::from_hex(oid.as_bytes()).unwrap()).unwrap();
}
}
/// What a remounted volume looks like: every path and modification time is the same, but
/// the files that the old handle mapped are gone. `tests/volume_loss.rs` does it for real.
#[test]
-1
Переглянути файл
@@ -287,7 +287,6 @@ fn uncommitted_lines(n: usize) -> Vec<BlameLine> {
time_ms: now,
summary: String::new(),
origin_path: None,
origin_line: None,
})
.collect()
}
+8 -32
Переглянути файл
@@ -215,20 +215,20 @@ impl GitignoreStack {
{
let mut nested = self.nested.lock();
let target = if dir.file_name().is_some_and(|n| n == ".git") { dir.parent().unwrap_or(dir) } else { dir };
// Always drop descendant keys. Requiring `target` itself to be a key
// misses a repository created after the watch started: lookups then
// stop at the new `.git`, so the filesystem root is never recorded,
// and `reload_ignore_rules` from that root would leave a stale
// "no rules" cache behind.
nested.by_dir.retain(|k, _| !k.starts_with(target));
nested.by_root.retain(|k, _| !k.starts_with(target));
if nested.by_dir.contains_key(target) || nested.by_root.contains_key(target) {
nested.by_dir.retain(|k, _| !k.starts_with(target));
nested.by_root.retain(|k, _| !k.starts_with(target));
}
for stack in nested.by_root.values() {
stack.invalidate_tree(dir);
}
}
let mut cache = self.cache.lock();
self.generation.fetch_add(1, Ordering::Relaxed);
cache.retain(|k, _| !k.starts_with(dir));
// Lookups always populate every ancestor, so no key below `dir` exists without `dir`.
if cache.contains_key(dir) {
cache.retain(|k, _| !k.starts_with(dir));
}
}
pub fn repo_root(&self) -> Option<&Path> {
@@ -545,28 +545,4 @@ mod tests {
stack.invalidate_tree(&workspace.join("sub/.git"));
assert!(stack.is_ignored(&workspace.join("sub/deep/a.tmp"), false));
}
#[test]
fn git_init_after_the_first_listing_is_picked_up_from_the_filesystem_root() {
// The project was opened before `git init`. A listing after the repository
// appears, but before any ignore file is written, caches a nested stack whose
// keys stop at the new `.git` and never include the filesystem root. Reloading
// from that root must still drop those stale "no rules" entries.
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap();
std::fs::write(root.join("shared.ignore-me"), "x").unwrap();
std::fs::write(root.join("private.ignore-me"), "x").unwrap();
let stack = GitignoreStack::new(&root);
assert_eq!(stack.repo_root(), None);
std::fs::create_dir_all(root.join(".git/info")).unwrap();
assert!(!stack.is_ignored(&root.join("shared.ignore-me"), false));
assert!(!stack.is_ignored(&root.join("private.ignore-me"), false));
std::fs::write(root.join(".gitignore"), "/shared.ignore-me\n").unwrap();
std::fs::write(root.join(".git/info/exclude"), "/private.ignore-me\n").unwrap();
stack.reload_repo_level();
let top = root.ancestors().last().unwrap();
stack.invalidate_tree(top);
assert!(stack.is_ignored(&root.join("shared.ignore-me"), false));
assert!(stack.is_ignored(&root.join("private.ignore-me"), false));
}
}
+1 -8
Переглянути файл
@@ -146,14 +146,7 @@ impl Watcher {
// `.git` that now exists (`git init`). `/` is no ancestor of `C:\…` on Windows, so take
// the watch root's own topmost ancestor.
let top = self.root.ancestors().last().unwrap_or(&self.root);
let origin = self.rules.repo_root().unwrap_or(top);
self.rules.invalidate_tree(origin);
// After `git init`, a listing may have cached a nested stack whose keys
// stop at the new `.git` and never include `top`. Drop the watched tree
// itself too, which also covers a Windows `C:\` vs `\\?\C:\` mismatch.
if origin != self.root.as_path() {
self.rules.invalidate_tree(&self.root);
}
self.rules.invalidate_tree(self.rules.repo_root().unwrap_or(top));
}
/// The watched directory (canonical).
-22
Переглянути файл
@@ -371,28 +371,6 @@ fn watcher_read_dir_sees_a_repository_made_after_it_started() {
assert_eq!(ignored, BTreeSet::from(["private.ignore-me".to_string(), "shared.ignore-me".to_string()]));
}
/// Same as above, but the first listing happens after `git init` and before the
/// ignore files exist. That caches a nested stack that never recorded the
/// filesystem root as a key — the case `reload_ignore_rules` hits when the
/// watcher has already seen the new `.git`.
#[test]
fn watcher_read_dir_sees_ignore_files_written_after_a_post_init_listing() {
let (_t, r) = root();
write(&r.join("shared.ignore-me"), "x");
write(&r.join("private.ignore-me"), "x");
let sink: SharedSink = Arc::new(|_| {});
let watcher = Watcher::start(&r, vec![], sink, Box::new(|_| {})).unwrap();
assert_eq!(watcher.repo_root(), None);
write(&r.join(".git/HEAD"), "ref: refs/heads/main\n");
assert!(watcher.read_dir(&r, &[]).unwrap().iter().all(|e| !e.ignored));
write(&r.join(".gitignore"), "/shared.ignore-me\n");
write(&r.join(".git/info/exclude"), "/private.ignore-me\n");
watcher.reload_ignore_rules();
let ignored: BTreeSet<String> =
watcher.read_dir(&r, &[]).unwrap().into_iter().filter(|e| e.ignored).map(|e| e.name).collect();
assert_eq!(ignored, BTreeSet::from(["private.ignore-me".to_string(), "shared.ignore-me".to_string()]));
}
#[test]
fn watcher_reports_changes() {
let (_t, r) = root();
+1 -14
Переглянути файл
@@ -604,9 +604,7 @@ fn external_change_in_two_places_patches_each() {
std::thread::sleep(std::time::Duration::from_millis(10));
let new = old.replace("line 20\n", "line 20x\n").replace("line 299\n", "line 299x\n");
fs::write(&path, &new).unwrap();
let started = std::time::Instant::now();
f.docs.on_disk_changed(std::slice::from_ref(&path));
let in_budget = started.elapsed() < ide_text::DIFF_BUDGET;
assert_eq!(f.docs.snapshot(id).unwrap().text, new);
let events = f.events.lock();
@@ -614,18 +612,7 @@ fn external_change_in_two_places_patches_each() {
IdeEvent::DocPatched { changes, .. } => Some(changes),
_ => None,
});
let changes = changes.expect("a patch");
let mut replayed = ide_text::Document::new(&old);
replayed.apply(0, &ChangeSet { changes: changes.clone() }).unwrap();
assert_eq!(replayed.text(), new);
// Merged or not, the patch stays between the two edited lines.
let first = old.find("line 20\n").unwrap() as u32;
let last = (old.find("line 299\n").unwrap() + "line 299\n".len()) as u32;
assert!(changes[0].from >= first && changes[changes.len() - 1].to <= last, "{changes:?}");
// Past the diff budget (a loaded machine) the two regions may come as one, still correctly.
if in_budget {
assert_eq!(changes.len(), 2);
}
assert_eq!(changes.map(Vec::len), Some(2));
}
#[test]
+1 -1
Переглянути файл
@@ -488,7 +488,7 @@
"footer": {
"socials": {
"github": "https://github.com/l0ng-ai/openidea",
"discord": "https://discord.gg/AsZqMgxZm"
"discord": "https://discord.gg/2Zy4yn7gP"
}
}
}
+20 -21
Переглянути файл
@@ -79,27 +79,26 @@ With **Shell integration** on, zsh, bash and fish report the current directory a
**Settings › Tools › Terminal**:
| Setting | Default | Notes |
| ----------------------------------------------- | ------------ | ------------------------------------------------------------------------------------------------------------------------------------------- |
| **Start directory** | Project root | Relative paths resolve against the project root. **Open in Terminal** still opens the chosen folder. Project setting. |
| **Environment variables** | none | Added to new sessions. Project setting. |
| **Shell path** | login shell | A command line, e.g. `/bin/zsh --login`. **Installed Shells** lists what was found. |
| **Default Tab name** | `Local` | |
| **Audible bell** | on | |
| **Close session when it ends** | on | |
| **Mouse reporting** | on | Off: programs can't capture the mouse. |
| **Copy to clipboard on selection** | off | |
| **Let programs copy to the clipboard (OSC 52)** | on | tmux (`set-clipboard on`), Neovim and other programs set the clipboard, also over SSH. They can't read it; payloads over 1 MiB are ignored. |
| **Paste on middle mouse button click** | on | |
| **Paste on right click** | off | On: right-click pastes; Ctrl or Shift + right-click opens the context menu. |
| **Move focus to the Editor with Escape** | off | Otherwise `Esc` goes to the shell. |
| **Override IDE shortcuts** | on | See above. |
| **Shell integration** | on | |
| **Highlight hyperlinks** | on | |
| **Use Option as Meta key** | off | macOS only. |
| **Cursor shape** | Block | Block, Underline or Vertical. |
| **Blinking cursor** | on | |
| **Use editor font** | on | Off: set **Font**, **Size** (6–72), **Line height**, **Fallback font** and **Column width**. |
| Setting | Default | Notes |
| ---------------------------------------- | ------------ | --------------------------------------------------------------------------------------------------------------------- |
| **Start directory** | Project root | Relative paths resolve against the project root. **Open in Terminal** still opens the chosen folder. Project setting. |
| **Environment variables** | none | Added to new sessions. Project setting. |
| **Shell path** | login shell | A command line, e.g. `/bin/zsh --login`. **Installed Shells** lists what was found. |
| **Default Tab name** | `Local` | |
| **Audible bell** | on | |
| **Close session when it ends** | on | |
| **Mouse reporting** | on | Off: programs can't capture the mouse. |
| **Copy to clipboard on selection** | off | |
| **Paste on middle mouse button click** | on | |
| **Paste on right click** | off | On: right-click pastes; Ctrl or Shift + right-click opens the context menu. |
| **Move focus to the Editor with Escape** | off | Otherwise `Esc` goes to the shell. |
| **Override IDE shortcuts** | on | See above. |
| **Shell integration** | on | |
| **Highlight hyperlinks** | on | |
| **Use Option as Meta key** | off | macOS only. |
| **Cursor shape** | Block | Block, Underline or Vertical. |
| **Blinking cursor** | on | |
| **Use editor font** | on | Off: set **Font**, **Size** (6–72), **Line height**, **Fallback font** and **Column width**. |
Changes apply to open sessions right away. Colours follow the IDE theme.
+1 -1
Переглянути файл
@@ -278,7 +278,7 @@ Retention is set in the **Local History** section of **Settings › Appearance &
| ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Commit** | Non-modal commit interface, clearing the message after commit, message inspections (blank line after subject, subject and body length, right margin), default commit checks. |
| **Confirmation** | What to do when files are created or deleted, **Show options before Update**, confirm before dropping commits, highlight modified folders in the Project view, history row limit. |
| **Directory Mappings** | Add and remove Git repository mappings and exclude auto-detected repositories from Git integration. Unreachable mapped repositories are marked unavailable while other repositories keep working. |
| **Directory Mappings** | Add and remove Git repository mappings and exclude auto-detected repositories from Git integration. |
| **Issue Navigation** | Regex patterns that turn issue IDs in commit messages into links (presets for JIRA, YouTrack and GitHub). |
| **Log** | Reference and time display, visible columns. |
| **Shelf** | Remove applied files from the shelf. |
+9 -12
Переглянути файл
@@ -1,22 +1,20 @@
---
title: "C# and .NET"
description: "C# with the Roslyn language server or csharp-ls, F# with FsAutoComplete, the .NET tool window for builds, NuGet packages and tests, and debugging with netcoredbg."
description: "C# with csharp-ls, F# with FsAutoComplete, the .NET tool window for builds, NuGet packages and tests, and debugging with netcoredbg."
---
OpenIDEA supports C# (`.cs`, `.csx`) through Microsoft's [Roslyn language server](https://github.com/dotnet/roslyn) or [csharp-ls](https://github.com/razzmatazz/csharp-language-server), and F# (`.fs`, `.fsi`, `.fsx`) through [FsAutoComplete](https://github.com/ionide/FsAutoComplete). All of them are installed as .NET tools, and both languages debug with [netcoredbg](https://github.com/Samsung/netcoredbg). Builds, NuGet packages and tests go through the `dotnet` CLI. For other languages, see the [support matrix](/en/languages/index).
OpenIDEA supports C# (`.cs`, `.csx`) through [csharp-ls](https://github.com/razzmatazz/csharp-language-server) and F# (`.fs`, `.fsi`, `.fsx`) through [FsAutoComplete](https://github.com/ionide/FsAutoComplete). Both are installed as .NET tools, and both debug with [netcoredbg](https://github.com/Samsung/netcoredbg). Builds, NuGet packages and tests go through the `dotnet` CLI. For other languages, see the [support matrix](/en/languages/index).
## Language server
| Language | Server | Workspace root markers |
| -------- | ----------------------------------- | ----------------------------------------------------------------------------------------------------------- |
| C# | roslyn-language-server or csharp-ls | `*.sln`, `*.slnx`, `*.csproj`, `global.json`, `Directory.Build.props`, `ProjectSettings/ProjectVersion.txt` |
| F# | fsautocomplete | `*.sln`, `*.fsproj`, `global.json` |
For C#, the IDE uses the Roslyn language server when it is installed and csharp-ls otherwise. Roslyn is the server of the VS Code C# extension. It needs the .NET 10 SDK or newer; csharp-ls also runs on older SDKs. With Roslyn, completion also lists types from namespaces the file doesn't import yet (shown with their namespace), and accepting one adds the `using` directive. Roslyn starts with `--autoLoadProjects`, so it finds and opens the solution or projects itself. On macOS and Linux it loads SDK-style projects only: .NET Framework projects need Mono MSBuild, which it doesn't use. Unity's Visual Studio Editor package generates SDK-style `.csproj` files.
| Language | Server | Workspace root markers |
| -------- | -------------- | ----------------------------------------------------------------------------------------------------------- |
| C# | csharp-ls | `*.sln`, `*.slnx`, `*.csproj`, `global.json`, `Directory.Build.props`, `ProjectSettings/ProjectVersion.txt` |
| F# | fsautocomplete | `*.sln`, `*.fsproj`, `global.json` |
The server loads the solution or project it finds from these markers. FsAutoComplete starts with `AutomaticWorkspaceInit` on, so it loads the projects without waiting for the editor to ask.
When you go to the definition of a library type, the server returns decompiled source. It opens as a read-only document, and so does source-generated code.
When you go to the definition of a library type, csharp-ls returns decompiled source. It opens as a read-only document, and so does source-generated code.
`ProjectSettings/ProjectVersion.txt` is there so that Unity projects work too. See [Unity](/en/languages/unity) for using OpenIDEA as Unity's external editor.
@@ -24,18 +22,17 @@ When you go to the definition of a library type, the server returns decompiled s
You need the [.NET SDK](https://dotnet.microsoft.com/download) with `dotnet` on your `PATH`. The IDE runs every build, test and package command through it, and installs the language servers with it.
When no server is installed, opening a C# or F# file shows a "Roslyn (C#) is not installed" (or FsAutoComplete) notification with **Install**. If your SDK is older than .NET 10, the install says so and suggests csharp-ls instead. You can also install the tools from **Settings › Languages & Frameworks › Language Servers**.
When a server is missing, opening a C# or F# file shows a "csharp-ls is not installed" (or FsAutoComplete) notification with **Install**. You can also install the tools from **Settings › Languages & Frameworks › Language Servers**.
| Tool | How it is installed |
| -------------- | ------------------------------------------------------------------------------------------------------------------------- |
| Roslyn (C#) | `dotnet tool install --prerelease --tool-path` into the IDE's tools folder; nuget.org has only prerelease builds of it |
| csharp-ls | `dotnet tool install --tool-path` into the IDE's tools folder (not a global tool) |
| FsAutoComplete | `dotnet tool install --tool-path` into the IDE's tools folder |
| netcoredbg | Downloaded from the `Samsung/netcoredbg` GitHub releases. Prebuilt for macOS arm64, Linux x64 and arm64, and Windows x64. |
Before it installs csharp-ls or FsAutoComplete, the IDE compares the newest SDK in `dotnet --list-sdks` with the .NET version the tool's latest release on nuget.org targets. When the SDK is older, it installs the newest release that runs on it, or tells you which SDK to install.
A `roslyn-language-server`, `csharp-ls`, `fsautocomplete` or `netcoredbg` already on your `PATH` (for example a global `dotnet tool install --global csharp-ls`) is used as is.
A `csharp-ls`, `fsautocomplete` or `netcoredbg` already on your `PATH` (for example a global `dotnet tool install --global csharp-ls`) is used as is.
## The .NET tool window
+2 -2
Переглянути файл
@@ -65,7 +65,7 @@ The IDE never needs `sudo`. It installs tools into its own tools folder in the l
| `go install` | gopls, Delve, sqls. Needs Go. |
| `rustup component add` | rust-analyzer (falls back to a download from Open VSX). |
| `gem install` | Solargraph into its own gem home; Ruby LSP into the project's Ruby. |
| `dotnet tool install` | Roslyn (C#), csharp-ls, FsAutoComplete. Needs the .NET SDK. |
| `dotnet tool install` | csharp-ls, FsAutoComplete. Needs the .NET SDK. |
| Release download | clangd, CodeLLDB, vscode-js-debug, JDT LS, java-debug, Kotlin LSP, Lua, Marksman, Taplo, ZLS, terraform-ls and others, from GitHub, Open VSX, Maven Central, the Eclipse download site or HashiCorp. |
| Bundled | The Lombok agent for JDT LS ships with the app. |
@@ -99,7 +99,7 @@ The table lists every built-in language definition. Server and debugger names in
| Astro | `astro` | `.astro` | Yes | — | **astro-ls** + **oxlint** | — |
| Batch | `bat` | `.bat`, `.cmd` | Yes | — | — | — |
| C | `c` | `.c`, `.h` | Yes | Yes | **clangd** | lldb-dap |
| C# | `csharp` | `.cs`, `.csx` | Yes | Yes | **roslyn-language-server** → **csharp-ls** | **netcoredbg** |
| C# | `csharp` | `.cs`, `.csx` | Yes | Yes | **csharp-ls** | **netcoredbg** |
| C++ | `cpp` | `.cpp`, `.cc`, `.cxx`, `.c++`, `.hpp`, … | Yes | Yes | **clangd** | lldb-dap |
| Clojure | `clojure` | `.clj`, `.cljs`, `.cljc`, `.cljd`, `.edn`, … | Yes | — | **clojure-lsp** | — |
| CMake | `cmake` | `.cmake` | Yes | Yes | **neocmakelsp** → cmake-language-server | — |
+2 -2
Переглянути файл
@@ -76,9 +76,9 @@ When Git asks whether to add a new file you created in the IDE, the `.meta` file
## Code intelligence
C# in a Unity project uses the same language server as any other C# project (Roslyn, or csharp-ls); see [C# and .NET](/en/languages/csharp) for installation. A Unity project is a workspace root for it even before a solution exists.
C# in a Unity project uses the same language server as any other C# project, csharp-ls; see [C# and .NET](/en/languages/csharp) for installation. A Unity project is a workspace root for it even before a solution exists.
The server reads the `.sln` and `.csproj` files that Unity generates. When they are missing, the Unity pane shows:
csharp-ls reads the `.sln` and `.csproj` files that Unity generates. When they are missing, the Unity pane shows:
> C# project files are missing. In Unity, select an external script editor in Preferences > External Tools, then regenerate project files.
+1 -1
Переглянути файл
@@ -80,4 +80,4 @@ If a `settings.toml` you edited by hand can't be parsed or has a value of the wr
2. Click **Report an Issue** (or go to [GitHub issues](https://github.com/l0ng-ai/openidea/issues/new/choose)) and describe the steps to reproduce.
3. Attach the relevant part of the log.
Questions and feedback are also welcome on [Discord](https://discord.gg/AsZqMgxZm).
Questions and feedback are also welcome on [Discord](https://discord.gg/2Zy4yn7gP).
+20 -21
Переглянути файл
@@ -79,27 +79,26 @@ OpenIDEA 会按项目记住终端标签页:各自的目录、自定义名称
**设置 › 工具 › 终端**:
| 设置 | 默认值 | 说明 |
| ---------------------------------- | ---------- | ---------------------------------------------------------------------------------------------------------------------- |
| **起始目录** | 项目根目录 | 相对路径按项目根目录解析。**在终端中打开** 仍会打开所选文件夹。项目级设置。 |
| **环境变量** | 无 | 添加到新会话的环境中。项目级设置。 |
| **Shell 路径** | 登录 Shell | 一条命令行,例如 `/bin/zsh --login`。**已安装的 Shell** 列出找到的 Shell。 |
| **默认标签页名称** | `Local` | |
| **响铃** | 开 | |
| **会话结束时关闭** | 开 | |
| **鼠标报告** | 开 | 关闭后程序无法捕获鼠标。 |
| **选择时复制到剪贴板** | 关 | |
| **允许程序复制到剪贴板(OSC 52)** | 开 | tmux(`set-clipboard on`)、Neovim 等程序可以设置剪贴板,SSH 中也有效。程序无法读取剪贴板;超过 1 MiB 的内容会被忽略。 |
| **点击鼠标中键时粘贴** | 开 | |
| **右键单击时粘贴** | 关 | 开启后右键单击直接粘贴;按住 Ctrl 或 Shift 右键单击仍打开上下文菜单。 |
| **按 Escape 将焦点移到编辑器** | 关 | 关闭时 `Esc` 发给 Shell。 |
| **覆盖 IDE 快捷键** | 开 | 见上文。 |
| **Shell 集成** | 开 | |
| **高亮超链接** | 开 | |
| **将 Option 用作 Meta 键** | 关 | 仅 macOS。 |
| **光标形状** | 块 | 块、下划线或竖线。 |
| **闪烁光标** | 开 | |
| **使用编辑器字体** | 开 | 关闭后可设置 **字体**、**大小**(6–72)、**行高**、**备用字体** 和 **列宽**。 |
| 设置 | 默认值 | 说明 |
| ------------------------------ | ---------- | ----------------------------------------------------------------------------- |
| **起始目录** | 项目根目录 | 相对路径按项目根目录解析。**在终端中打开** 仍会打开所选文件夹。项目级设置。 |
| **环境变量** | 无 | 添加到新会话的环境中。项目级设置。 |
| **Shell 路径** | 登录 Shell | 一条命令行,例如 `/bin/zsh --login`。**已安装的 Shell** 列出找到的 Shell。 |
| **默认标签页名称** | `Local` | |
| **响铃** | 开 | |
| **会话结束时关闭** | 开 | |
| **鼠标报告** | 开 | 关闭后程序无法捕获鼠标。 |
| **选择时复制到剪贴板** | 关 | |
| **点击鼠标中键时粘贴** | 开 | |
| **右键单击时粘贴** | 关 | 开启后右键单击直接粘贴;按住 Ctrl 或 Shift 右键单击仍打开上下文菜单。 |
| **按 Escape 将焦点移到编辑器** | 关 | 关闭时 `Esc` 发给 Shell。 |
| **覆盖 IDE 快捷键** | 开 | 见上文。 |
| **Shell 集成** | 开 | |
| **高亮超链接** | 开 | |
| **将 Option 用作 Meta 键** | 关 | 仅 macOS。 |
| **光标形状** | 块 | 块、下划线或竖线。 |
| **闪烁光标** | 开 | |
| **使用编辑器字体** | 开 | 关闭后可设置 **字体**、**大小**(6–72)、**行高**、**备用字体** 和 **列宽**。 |
修改会立即应用到已打开的会话。配色跟随 IDE 主题。
+1 -1
Переглянути файл
@@ -276,7 +276,7 @@ Git 工具窗口的 **日志** 标签页显示提交图。
| ------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **提交** | 非模态提交界面、提交后清空消息、提交消息检查(主题与正文之间空行、主题和正文长度、右边距)、默认提交检查。 |
| **确认** | 新建或删除文件时的处理方式、**更新前显示选项**、丢弃提交前确认、在项目视图中高亮包含修改的目录、历史记录行数上限。 |
| **目录映射** | 添加和移除 Git 仓库映射,或将自动检测到的仓库排除在 Git 集成之外。无法访问的已映射仓库会被标记为不可用,其余仓库仍可继续使用。 |
| **目录映射** | 添加和移除 Git 仓库映射,或将自动检测到的仓库排除在 Git 集成之外。 |
| **问题导航** | 把提交消息中的问题编号变成链接的正则规则(内置 JIRA、YouTrack 和 GitHub 预设)。 |
| **日志** | 引用和时间的显示方式、显示哪些列。 |
| **搁置** | 应用后从搁置中移除文件。 |
+9 -12
Переглянути файл
@@ -1,22 +1,20 @@
---
title: "C# 与 .NET"
description: "使用 Roslyn 语言服务器或 csharp-ls 的 C#、使用 FsAutoComplete 的 F#,用于构建、NuGet 包和测试的 .NET 工具窗口,以及基于 netcoredbg 的调试。"
description: "使用 csharp-ls 的 C#、使用 FsAutoComplete 的 F#,用于构建、NuGet 包和测试的 .NET 工具窗口,以及基于 netcoredbg 的调试。"
---
OpenIDEA 通过微软的 [Roslyn 语言服务器](https://github.com/dotnet/roslyn)或 [csharp-ls](https://github.com/razzmatazz/csharp-language-server) 支持 C#(`.cs`、`.csx`),通过 [FsAutoComplete](https://github.com/ionide/FsAutoComplete) 支持 F#(`.fs`、`.fsi`、`.fsx`)。它们都以 .NET 工具的形式安装,两种语言的调试都使用 [netcoredbg](https://github.com/Samsung/netcoredbg)。构建、NuGet 包和测试统一走 `dotnet` 命令行。其他语言见[语言支持总览](/zh/languages/index)。
OpenIDEA 通过 [csharp-ls](https://github.com/razzmatazz/csharp-language-server) 支持 C#(`.cs`、`.csx`),通过 [FsAutoComplete](https://github.com/ionide/FsAutoComplete) 支持 F#(`.fs`、`.fsi`、`.fsx`)。两者都以 .NET 工具的形式安装,调试都使用 [netcoredbg](https://github.com/Samsung/netcoredbg)。构建、NuGet 包和测试统一走 `dotnet` 命令行。其他语言见[语言支持总览](/zh/languages/index)。
## 语言服务器
| 语言 | 服务器 | 工作区根目录标记 |
| ---- | ----------------------------------- | ----------------------------------------------------------------------------------------------------------- |
| C# | roslyn-language-server 或 csharp-ls | `*.sln`、`*.slnx`、`*.csproj`、`global.json`、`Directory.Build.props`、`ProjectSettings/ProjectVersion.txt` |
| F# | fsautocomplete | `*.sln`、`*.fsproj`、`global.json` |
C# 在装了 Roslyn 语言服务器时用它,否则用 csharp-ls。Roslyn 是 VS Code C# 扩展使用的服务器,需要 .NET 10 或更新的 SDK;csharp-ls 在较旧的 SDK 上也能运行。用 Roslyn 时,补全还会列出当前文件尚未导入的命名空间里的类型(附带命名空间),选中后自动加上 `using` 指令。Roslyn 以 `--autoLoadProjects` 启动,会自己找到并打开解决方案或项目。在 macOS 和 Linux 上它只加载 SDK 风格的项目:.NET Framework 项目需要 Mono MSBuild,它不使用。Unity 的 Visual Studio Editor 包生成的就是 SDK 风格的 `.csproj`。
| 语言 | 服务器 | 工作区根目录标记 |
| ---- | -------------- | ----------------------------------------------------------------------------------------------------------- |
| C# | csharp-ls | `*.sln`、`*.slnx`、`*.csproj`、`global.json`、`Directory.Build.props`、`ProjectSettings/ProjectVersion.txt` |
| F# | fsautocomplete | `*.sln`、`*.fsproj`、`global.json` |
语言服务器会加载根据这些标记找到的解决方案或项目。FsAutoComplete 启动时开启了 `AutomaticWorkspaceInit`,无需等待编辑器请求就会自动加载项目。
跳转到类库类型的定义时,语言服务器返回反编译后的源码,以只读文档打开;源生成器生成的代码同样以只读方式打开。
跳转到类库类型的定义时,csharp-ls 返回反编译后的源码,以只读文档打开;源生成器生成的代码同样以只读方式打开。
`ProjectSettings/ProjectVersion.txt` 这个标记是为 Unity 项目准备的。把 OpenIDEA 设为 Unity 外部编辑器的方法见 [Unity](/zh/languages/unity)。
@@ -24,18 +22,17 @@ C# 在装了 Roslyn 语言服务器时用它,否则用 csharp-ls。Roslyn 是
需要安装 [.NET SDK](https://dotnet.microsoft.com/download),并确保 `dotnet` 在 `PATH` 上。IDE 的构建、测试和包管理命令都通过它执行,语言服务器也用它安装。
没有安装语言服务器时,打开 C# 或 F# 文件会弹出“Roslyn (C#) 未安装”(或 FsAutoComplete)的通知,点 **安装** 即可。SDK 低于 .NET 10 时,安装会说明这一点并建议改装 csharp-ls。也可以在 **设置 › 语言和框架 › 语言服务器** 中安装。
缺少语言服务器时,打开 C# 或 F# 文件会弹出“csharp-ls 未安装”(或 FsAutoComplete)的通知,点 **安装** 即可。也可以在 **设置 › 语言和框架 › 语言服务器** 中安装。
| 工具 | 安装方式 |
| -------------- | -------------------------------------------------------------------------------------------------------------- |
| Roslyn (C#) | `dotnet tool install --prerelease --tool-path` 安装到 IDE 自己的工具目录;nuget.org 上只有它的预发布版本 |
| csharp-ls | `dotnet tool install --tool-path` 安装到 IDE 自己的工具目录(不是全局工具) |
| FsAutoComplete | `dotnet tool install --tool-path` 安装到 IDE 自己的工具目录 |
| netcoredbg | 从 `Samsung/netcoredbg` 的 GitHub Release 下载。提供 macOS arm64、Linux x64 与 arm64、Windows x64 的预编译包。 |
安装 csharp-ls 或 FsAutoComplete 之前,IDE 会把 `dotnet --list-sdks` 中最新的 SDK 与该工具在 nuget.org 上最新版本的目标 .NET 版本进行比较。如果 SDK 较旧,会安装能在它上面运行的最新版本,或者提示需要安装哪个 SDK。
`PATH` 上已有的 `roslyn-language-server`、`csharp-ls`、`fsautocomplete` 或 `netcoredbg`(例如通过 `dotnet tool install --global csharp-ls` 安装的全局工具)会直接使用。
`PATH` 上已有的 `csharp-ls`、`fsautocomplete` 或 `netcoredbg`(例如通过 `dotnet tool install --global csharp-ls` 安装的全局工具)会直接使用。
## .NET 工具窗口
+2 -2
Переглянути файл
@@ -61,7 +61,7 @@ IDE 安装工具从不需要 `sudo`。工具装在本地数据目录下 IDE 自
| `go install` | gopls、Delve、sqls。需要 Go。 |
| `rustup component add` | rust-analyzer(不可用时改为从 Open VSX 下载)。 |
| `gem install` | Solargraph 装到独立的 gem 目录;Ruby LSP 装到项目使用的 Ruby 中。 |
| `dotnet tool install` | Roslyn(C#)、csharp-ls、FsAutoComplete。需要 .NET SDK。 |
| `dotnet tool install` | csharp-ls、FsAutoComplete。需要 .NET SDK。 |
| 下载发布包 | clangd、CodeLLDB、vscode-js-debug、JDT LS、java-debug、Kotlin LSP、Lua、Marksman、Taplo、ZLS、terraform-ls 等,来源包括 GitHub、Open VSX、Maven Central、Eclipse 下载站和 HashiCorp。 |
| 内置 | JDT LS 使用的 Lombok agent 随应用一起提供。 |
@@ -94,7 +94,7 @@ IDE 安装工具从不需要 `sudo`。工具装在本地数据目录下 IDE 自
| Astro | `astro` | `.astro` | 是 | — | **astro-ls** + **oxlint** | — |
| Batch | `bat` | `.bat`, `.cmd` | 是 | — | — | — |
| C | `c` | `.c`, `.h` | 是 | 是 | **clangd** | lldb-dap |
| C# | `csharp` | `.cs`, `.csx` | 是 | 是 | **roslyn-language-server** → **csharp-ls** | **netcoredbg** |
| C# | `csharp` | `.cs`, `.csx` | 是 | 是 | **csharp-ls** | **netcoredbg** |
| C++ | `cpp` | `.cpp`, `.cc`, `.cxx`, `.c++`, `.hpp`, … | 是 | 是 | **clangd** | lldb-dap |
| Clojure | `clojure` | `.clj`, `.cljs`, `.cljc`, `.cljd`, `.edn`, … | 是 | — | **clojure-lsp** | — |
| CMake | `cmake` | `.cmake` | 是 | 是 | **neocmakelsp** → cmake-language-server | — |
+2 -2
Переглянути файл
@@ -76,9 +76,9 @@ description: "把 OpenIDEA 设为 Unity 的外部脚本编辑器,浏览 Unity
## 代码智能
Unity 项目中的 C# 和普通 C# 项目使用同一个语言服务器(Roslyn 或 csharp-ls),安装方式见 [C# 与 .NET](/zh/languages/csharp)。即使还没有解决方案文件,Unity 项目也会被当作它的工作区根目录。
Unity 项目中的 C# 和普通 C# 项目使用同一个语言服务器 csharp-ls,安装方式见 [C# 与 .NET](/zh/languages/csharp)。即使还没有解决方案文件,Unity 项目也会被当作它的工作区根目录。
语言服务器读取 Unity 生成的 `.sln` 和 `.csproj` 文件。缺少这些文件时,**Unity 项目**视图会提示:
csharp-ls 读取 Unity 生成的 `.sln` 和 `.csproj` 文件。缺少这些文件时,**Unity 项目**视图会提示:
> 缺少 C# 项目文件。请在 Unity 的偏好设置 > 外部工具中选择外部脚本编辑器,然后重新生成项目文件。
+1 -1
Переглянути файл
@@ -80,4 +80,4 @@ WEBKIT_DISABLE_DMABUF_RENDERER=1 ./OpenIDEA_<version>_amd64.AppImage
2. 点击 **报告问题**(或直接前往 [GitHub Issues](https://github.com/l0ng-ai/openidea/issues/new/choose)),写明复现步骤。
3. 附上日志中相关的部分。
也欢迎在 [Discord](https://discord.gg/AsZqMgxZm) 提问和反馈;README 中还有微信群二维码。
也欢迎在 [Discord](https://discord.gg/2Zy4yn7gP) 提问和反馈;README 中还有微信群二维码。
-140
Переглянути файл
@@ -1,7 +1,5 @@
import { expect, test, type Page } from "@playwright/test";
import type { AgentEntry, AgentTask } from "../src/bindings";
import type * as AgentStore from "../src/features/agents/store";
import type * as Ipc from "../src/platform/ipc";
const task: AgentTask = {
id: "long-chat",
@@ -256,141 +254,3 @@ test("paints earlier turns past folded process runs longer than ENTRY_BATCH", as
await expect(stream.getByText("Split PR into three focused PRs")).toBeVisible();
await expect(stream.getByText("Interim status update")).toBeVisible();
});
test("keeps earlier messages visible and upward wheel scrolling working after a tall row collapses", async ({
page,
}) => {
await page.setViewportSize({ width: 980, height: 640 });
await page.goto("/");
await page.getByRole("tree", { name: "Project" }).waitFor();
await page.evaluate(async () => {
const storePath = "/src/features/agents/store.ts";
const themePath = "/src/workbench/theme.ts";
const ipcPath = "/src/platform/ipc.ts";
const store: typeof AgentStore = await import(storePath);
const { previewTheme } = await import(themePath);
const { commands }: typeof Ipc = await import(ipcPath);
previewTheme("light");
const taskId = "collapse-scroll";
commands.agentRespond = async (_id: string, permId: number, _answer: string | null) => {
const current = store.useAgents.getState().entries.get(taskId) ?? [];
store.useAgents.setState({
entries: new Map([
[
taskId,
[
...current.map((entry) =>
entry.type === "permission" && entry.id === permId
? { ...entry, chosen: "Layered architecture diagram" }
: entry,
),
{ type: "thought", text: "Planning the layered architecture diagram…", startedMs: Date.now() },
],
],
]),
});
return { status: "ok", data: null };
};
const priorTurns: AgentEntry[] = Array.from({ length: 8 }, (_, turn): AgentEntry[] => [
{ type: "user", text: `Earlier request ${turn}`, attachments: [], steered: false },
{ type: "agent", text: `Earlier reply ${turn} with context from the repository.` },
]).flat();
const history: AgentEntry[] = [
...priorTurns,
{
type: "user",
text: "Can you review the architecture design and convert Section 2.1 into a diagram?",
attachments: ["architecture_design.md"],
sentMs: Date.now() - 180_000,
steered: false,
},
{
type: "agent",
text: "I reviewed `architecture_design.md` against the codebase. Before generating the diagram, please confirm the layout preferences below.",
},
{
type: "permission",
id: 1,
title: "Choose diagram options",
command: null,
options: [
{ id: "submit", name: "Submit", kind: "allow_once" },
{ id: "cancel", name: "Cancel", kind: "reject_once" },
],
questions: [
{
header: "Style",
question: "Which visual style should Section 2.1 use?",
multiSelect: false,
options: Array.from({ length: 8 }, (_, i) => ({
label: i === 0 ? "Layered architecture diagram (Recommended)" : `Alternative layout style ${i + 1}`,
description:
"Horizontal pipeline tiers with a dedicated right-hand artifact rail so connectors never cross.",
preview: null,
})),
},
],
chosen: null,
},
];
store.useAgents.setState({
loaded: true,
error: null,
providers: [],
tasks: new Map([
[
taskId,
{
id: taskId,
title: "Can you review the architecture design",
status: "running",
isolation: "local",
provider: "copilot",
model: null,
cwd: "/dev/acme-api",
branch: null,
base: null,
baseCommit: null,
error: null,
createdMs: Date.now() - 180_000,
updatedMs: Date.now(),
config: [],
commands: [],
usage: null,
queue: [],
},
],
]),
entries: new Map([[taskId, history]]),
unread: new Set(),
docked: null,
});
store.openTaskInEditorLocation(taskId);
});
const stream = page.locator("[class*='_stream_']:visible");
const card = page.getByRole("form", { name: "Choose diagram options" });
await expect(card).toBeVisible();
// Scroll slightly away so the tall card's header sits above `.stream` while Submit stays in view, then submit.
await card.getByRole("radio", { name: /^Layered architecture diagram/ }).check();
await stream.hover();
await page.mouse.wheel(0, -10);
await stream.evaluate((el) => {
el.scrollTop = el.scrollHeight - el.clientHeight - 4;
el.dispatchEvent(new Event("scroll"));
});
await card.getByRole("button", { name: "Submit", exact: true }).click();
await expect(card).toHaveCount(0);
// Immediately after collapsing, the preceding reply stays visible in the viewport with no blank slack lockup.
await expect(stream.getByText("I reviewed")).toBeInViewport();
// Scrolling upward with the wheel reaches the earliest turns without snapping scrollTop back.
await stream.hover();
for (let i = 0; i < 12; i++) {
await page.mouse.wheel(0, -120);
await page.waitForTimeout(20);
}
await expect(stream.getByText("Earlier reply 0 with context from the repository.")).toBeInViewport();
});
-4
Переглянути файл
@@ -610,8 +610,6 @@ test("keeps diagrams and their math labels when editing or switching Markdown ta
].join("\n\n");
await page.keyboard.insertText(source);
const preview = page.getByRole("document", { name: "Markdown preview" });
// Mermaid rendering is deferred while editing the source.
await preview.focus();
const diagram = preview.locator(".mermaid-output .pan-zoom-content > svg");
await expect(diagram.locator("foreignObject math")).toHaveCount(1);
const original = await diagram.elementHandle();
@@ -625,7 +623,6 @@ test("keeps diagrams and their math labels when editing or switching Markdown ta
await content.press("Meta+a");
await page.keyboard.insertText(source.replace("$$x^2$$", () => "$$z^3$$"));
await preview.focus();
await expect(diagram.locator("foreignObject math mi")).toHaveText("z");
const edited = await diagram.elementHandle();
expect(await diagram.evaluate((svg, old) => svg === old, original)).toBe(false);
@@ -676,7 +673,6 @@ test("Markdown preview aligns Mermaid diagrams to their container align attribut
);
const preview = page.getByRole("document", { name: "Markdown preview" });
await preview.focus();
const outputs = preview.locator("[data-mermaid-state='ok'] .mermaid-output");
await expect(outputs).toHaveCount(4);
-90
Переглянути файл
@@ -1,90 +0,0 @@
/**
* 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);
});
-46
Переглянути файл
@@ -362,52 +362,6 @@ test("long Git Log filter values shorten inside their buttons", async ({ workben
await expect(clear).toBeHidden();
});
test("a click in the User filter shows only that user's commits, without check marks", async ({ workbench: page }) => {
const alice = "Alice <[email protected]>";
const bob = "Bob <[email protected]>";
await page.evaluate(
async ([alice, bob]) => {
const optionsModule = "/src/features/vcs/logOptions.ts";
const { setLogOptions } = await import(/* @vite-ignore */ optionsModule);
// Room for the User filter on the bar.
setLogOptions({ showBranches: false, showDetails: false });
const h = window.__ipc.handlers;
h.vcs_log_users = () => [alice, "Author <[email protected]>", bob];
const log = h.vcs_log!;
h.vcs_log = (args) => {
(window as { logAuthors?: unknown }).logAuthors = (args.query as { authors: string[] }).authors;
return log(args);
};
},
[alice, bob],
);
const toolbar = page.getByRole("toolbar", { name: "Log filters" });
const user = toolbar.getByRole("button", { name: /^User/ });
const item = (name: string) => page.getByRole("menuitem", { name, exact: true });
const logAuthors = () => page.evaluate(() => (window as { logAuthors?: unknown }).logAuthors);
// The menu opens with the users known so far and fetches the list in the background.
await user.click();
await page.keyboard.press("Escape");
await expect(async () => {
await user.click();
try {
await expect(item(alice)).toBeVisible({ timeout: 1000 });
} catch (e) {
await page.keyboard.press("Escape");
throw e;
}
}).toPass();
await item(alice).click();
await expect(user).toHaveText(`User: ${alice}`);
await expect.poll(logAuthors).toEqual([alice]);
await user.click();
await expect(page.getByRole("menuitemcheckbox", { name: alice, exact: true })).toHaveCount(0);
await item(bob).click();
await expect(user).toHaveText(`User: ${bob}`);
await expect.poll(logAuthors).toEqual([bob]);
});
test("Git Log puts affected changes on the changed-files toolbar and groups preview options", async ({
workbench: page,
}) => {
-126
Переглянути файл
@@ -110,132 +110,6 @@ 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,
+7 -6
Переглянути файл
@@ -8,7 +8,7 @@ async function openRecent(page: Page, kind: "recentFiles" | "recentLocations") {
}, kind);
}
test("Recent Files shows only names and keeps the selected path in the footer in a narrow window", async ({
test("Recent Files keeps directories beside names and leaves room for files in a narrow window", async ({
workbench: page,
}) => {
await stubDesktop(page);
@@ -20,19 +20,20 @@ test("Recent Files shows only names and keeps the selected path in the footer in
const files = dialog.getByRole("listbox", { name: "Recent files" });
const row = files.getByRole("option").first();
const name = row.getByText("InvoiceService.ts", { exact: true });
const footer = dialog.locator("footer");
const directory = row.getByText("src/orders", { exact: true });
await expect(name).toBeVisible();
await expect(row).not.toContainText("src/orders");
await expect(footer.locator("bdi")).toHaveText("/dev/acme-api/src/orders/InvoiceService.ts");
const nameRight = await name.evaluate((el) => el.getBoundingClientRect().right);
const dirLeft = (await directory.boundingBox())!.x;
expect(dirLeft - nameRight).toBeLessThanOrEqual(8);
await page.setViewportSize({ width: 400, height: 500 });
expect((await files.boundingBox())!.width).toBeGreaterThan(200);
expect((await dialog.getByRole("textbox", { name: "Filter recent files" }).boundingBox())!.width).toBeGreaterThan(
200,
);
await expect(row).not.toContainText("src/orders");
await expect(footer.locator("bdi")).toHaveText("/dev/acme-api/src/orders/InvoiceService.ts");
await expect.poll(() => directory.evaluate((el) => el.getBoundingClientRect().width)).toBeGreaterThan(20);
await expect(dialog.getByRole("button", { name: /Recent Locations/ })).toBeVisible();
const footer = dialog.locator("footer");
await expect(footer).toBeInViewport({ ratio: 1 });
expect(
await dialog.locator("[data-dialog-body]").evaluate((el) => el.scrollHeight - el.clientHeight),
+7 -15
Переглянути файл
@@ -69,11 +69,6 @@ test("sorts collapsed workspace roots by project type, shows their icons and ref
(path) => path.getAttribute("d"),
);
}, name);
// File-type logos sit as an 8px corner badge on the module folder; dedicated
// project glyphs (Flutter, Gradle, Maven, Vite) still replace the folder.
const folder = await shape("module");
const glyph = async (icon: string) =>
icon.startsWith("file-") ? [...folder, ...(await shape(icon))] : await shape(icon);
for (const [name, icon] of [
["z-web", "file-npm"],
["Go2", "file-go"],
@@ -88,13 +83,9 @@ test("sorts collapsed workspace roots by project type, shows their icons and ref
["notes", "module"],
]) {
const row = tree.locator(`[data-project-path="/work/${name}"]`);
const badged = icon!.startsWith("file-");
await expect(row).toHaveAttribute("data-project-icon", badged ? "module" : icon!);
if (badged) await expect(row).toHaveAttribute("data-project-type-badge", icon!);
else await expect(row).not.toHaveAttribute("data-project-type-badge");
await expect
.poll(() => row.locator("svg path").evaluateAll((paths) => paths.map((path) => path.getAttribute("d"))))
.toEqual(await glyph(icon!));
.toEqual(await shape(icon!));
await expect(row.locator("[data-project-path]")).toHaveCount(0);
}
await tree.locator('[data-project-path="/work/z-web"]').click();
@@ -122,12 +113,13 @@ test("sorts collapsed workspace roots by project type, shows their icons and ref
removed: ["/work/z-web/package.json"],
});
});
const zWeb = tree.locator('[data-project-path="/work/z-web"]');
await expect(zWeb).toHaveAttribute("data-project-icon", "module");
await expect(zWeb).toHaveAttribute("data-project-type-badge", "file-go");
await expect
.poll(() => zWeb.locator("svg path").evaluateAll((paths) => paths.map((path) => path.getAttribute("d"))))
.toEqual(await glyph("file-go"));
.poll(() =>
tree
.locator('[data-project-path="/work/z-web"] svg path')
.evaluateAll((paths) => paths.map((path) => path.getAttribute("d"))),
)
.toEqual(await shape("file-go"));
await expect(tree.locator("[data-project-path]")).toHaveText([
"rust/work/rust",
"dart/work/dart",
-13
Переглянути файл
@@ -7,21 +7,8 @@ indent = { tab-size = 4, insert-spaces = true }
ui-mode = "C#"
tree-sitter = "csharp"
[[language-servers]]
name = "roslyn-language-server"
command = "roslyn-language-server"
# --autoLoadProjects: the server finds and opens the solution or projects itself.
args = ["--stdio", "--autoLoadProjects", "--telemetryLevel", "off"]
root-markers = ["*.sln", "*.slnx", "*.csproj", "global.json", "Directory.Build.props", "ProjectSettings/ProjectVersion.txt"]
install-hint = "Install Roslyn (C#) in Settings › Languages & Frameworks › Language Servers (needs the .NET 10 SDK), or csharp-ls for older SDKs"
[language-servers.settings."csharp|completion"]
dotnet_show_completion_items_from_unimported_namespaces = true
[[language-servers]]
name = "csharp-ls"
# Alternative: used only when the server above is not installed.
fallback = true
command = "csharp-ls"
root-markers = ["*.sln", "*.slnx", "*.csproj", "global.json", "Directory.Build.props", "ProjectSettings/ProjectVersion.txt"]
install-hint = "dotnet tool install --global csharp-ls"
-5
Переглянути файл
@@ -81,11 +81,6 @@ command = "java-analyzer"
root-markers = ["java-analyzer.toml", "pom.xml", "build.gradle", "build.gradle.kts", "settings.gradle", "settings.gradle.kts", "build.xml", ".project"]
install-hint = "Install java-analyzer in Settings › Languages & Frameworks › Language Servers (https://github.com/l0ng-ai/java-analyzer)"
[language-servers.initialization-options]
# OpenIDEA owns New Java Class templates. Do not race the editor by inserting
# a second package and class through workspace/applyEdit when it opens an empty file.
newFileTemplate = false
[[language-servers]]
name = "kmp-lsp"
fallback = true
+1 -7
Переглянути файл
@@ -15,8 +15,6 @@ use tracing_subscriber::{EnvFilter, Layer};
const PREFIX: &str = "openidea";
const SUFFIX: &str = "log";
/// Lines waiting for the log writer thread before new ones are dropped.
const LOG_QUEUE_LINES: usize = 16_384;
static LOG_DIR: OnceLock<PathBuf> = OnceLock::new();
static GUARD: OnceLock<WorkerGuard> = OnceLock::new();
@@ -40,11 +38,7 @@ pub fn init(identifier: &str) {
.max_log_files(7)
.build(&dir)
.ok()?;
// The default queue holds 128 000 lines and is filled when it is created: 4 MB of memory for a
// backlog the writer thread never builds.
let (writer, guard) = tracing_appender::non_blocking::NonBlockingBuilder::default()
.buffered_lines_limit(LOG_QUEUE_LINES)
.finish(appender);
let (writer, guard) = tracing_appender::non_blocking(appender);
let _ = GUARD.set(guard);
log_panics(dir.clone());
let _ = LOG_DIR.set(dir);
-20
Переглянути файл
@@ -4638,8 +4638,6 @@ export type BlameLine_Deserialize = {
summary: string,
/** The file blamed for this line when it had another path in the attributed commit. */
originPath?: IpcPath | null,
/** The line's 0-based number in the attributed commit's version of the file. */
originLine?: number | null,
};
export type BlameLine_Serialize = {
@@ -4649,8 +4647,6 @@ export type BlameLine_Serialize = {
summary: string,
/** The file blamed for this line when it had another path in the attributed commit. */
originPath?: IpcPath | null,
/** The line's 0-based number in the attributed commit's version of the file. */
originLine?: number | null,
};
/** History for Selection: the commits that changed a block of lines, newest first. */
@@ -5914,12 +5910,6 @@ export type CoverageSuite = {
files: FileCoverage[],
};
/** C/C++ debugger executables. Empty paths use automatic discovery. */
export type CppDebuggerSettings = {
gdbExecutable?: string,
lldbDapExecutable?: string,
};
/** Payload for creating a new instruction or rule file. */
export type CreateAgentMemoryInput = {
scope: McpScope,
@@ -6929,7 +6919,6 @@ export type DebuggerSettings = {
/** Java: whether to reload changed classes into running debug sessions after compilation. */
hotSwapAfterCompile?: HotSwapPolicy,
python?: PythonDebuggerSettings,
cpp?: CppDebuggerSettings,
};
/** An editor decoration. */
@@ -8182,11 +8171,6 @@ export type ExternalSession = {
cwd: string | null,
/** File modification time, ms since the epoch. */
updatedMs: number | null,
/**
* Another live process (VS Code, a terminal Copilot CLI) has it open: importing would let two
* apps write the same session, so forking a copy is the safe choice.
*/
inUse: boolean,
};
/** Tools › External Tools entry. */
@@ -15732,8 +15716,6 @@ export type TerminalSettings = {
closeOnExit?: boolean,
mouseReporting?: boolean,
copyOnSelection?: boolean,
/** Programs may set the clipboard with OSC 52 (tmux, Neovim, TUIs over SSH); never read it. */
osc52Clipboard?: boolean,
pasteOnMiddleClick?: boolean,
/** Right-click pastes instead of opening the context menu (Ctrl or Shift + right-click still opens it). */
rightClickPaste?: boolean,
@@ -16329,8 +16311,6 @@ export type VcsRoot = {
hasRemotes?: boolean | null,
/** Conflicts staged during the current operation that can be reopened. */
resolvedConflicts?: IpcPath[],
/** The repository's worktree or git directory is missing or on an unmounted volume. */
unavailable?: boolean,
};
/** Version Control (main page) and its sub-pages. */
-44
Переглянути файл
@@ -1,44 +0,0 @@
import { EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { afterEach, describe, expect, it } from "vitest";
import { joinerKind, zeroWidthJoiners } from "../joiners";
const code = (s: string) => s.charCodeAt(0);
describe("zero-width joiners", () => {
it("splits a joiner off CJK text, where it joins nothing (#7019)", () => {
expect(joinerKind(code("是"), code("全"))).toBe("split");
expect(joinerKind(code("同"), code(":"))).toBe("split");
expect(joinerKind(undefined, code("位"))).toBe("split");
expect(joinerKind(code(";"), undefined)).toBe("split");
});
it("keeps a joiner that shapes its neighbours", () => {
// Persian ZWNJ, Devanagari, an emoji ZWJ sequence (high surrogate of 👩).
expect(joinerKind(code("ی"), code("ه"))).toBe("keep");
expect(joinerKind(code("क"), code("ष"))).toBe("keep");
expect(joinerKind(0xd83d, 0xd83d)).toBe("keep");
expect(joinerKind(code("a"), code("ی"))).toBe("keep");
});
it("shows a joiner between ASCII characters or alone on a line", () => {
expect(joinerKind(code("a"), code("b"))).toBe("show");
expect(joinerKind(undefined, undefined)).toBe("show");
});
let view: EditorView | null = null;
afterEach(() => view?.destroy());
it("draws the CJK character apart from the joiner and shows one between ASCII", () => {
view = new EditorView({
state: EditorState.create({ doc: "冒号是‌全角\na‌b\nسی‌هزار", extensions: zeroWidthJoiners }),
parent: document.body,
});
const lines = [...view.contentDOM.querySelectorAll(".cm-line")];
expect(lines[0]!.querySelectorAll(".cm-zeroWidthJoiner")).toHaveLength(1);
expect(lines[0]!.textContent).toBe("冒号是全角");
expect(lines[1]!.querySelector(".cm-specialChar")?.getAttribute("title")).toBe("\\u200c");
expect(lines[2]!.textContent).toBe("سی‌هزار");
expect(view.state.doc.line(1).text).toBe("冒号是‌全角");
});
});
-21
Переглянути файл
@@ -457,27 +457,6 @@ describe("overwrite mode", () => {
type("XYZ");
expect(show(v)).toBe("abXYZ|\nx");
});
it("overwrites a whole surrogate pair after the caret", () => {
for (const [text, typed, after] of [
["|😀b", "A", "A|b"],
["|ab😀c", "XYZ", "XYZ|c"],
["|是\u200D全角", "非", "非|\u200D全角"],
// A DOM change from 😀 to 🨀 arrives as the new high surrogate alone.
["|😀b", "\ud83e", "\ud83e|\ude00b"],
]) {
const v = make(text!, overwriteField);
toggleOverwrite(v);
v.state.facet(EditorView.inputHandler).some((h) => h(v, 0, 0, typed!, () => v.state.update({})));
expect(show(v)).toBe(after);
}
// A caret between the halves of a pair (Go to Line:Column can put it there) replaces nothing on its own.
const v = make("|😀b", overwriteField);
toggleOverwrite(v);
v.dispatch({ selection: { anchor: 1 } });
v.state.facet(EditorView.inputHandler).some((h) => h(v, 1, 1, "", () => v.state.update({})));
expect(v.state.doc.toString()).toBe("😀b");
});
});
describe("smooth caret", () => {
-112
Переглянути файл
@@ -1,112 +0,0 @@
/**
* Zero-width joiners (U+200C ZWNJ, U+200D ZWJ) in text pasted from web pages.
*
* Next to a CJK character they join nothing, but WebKitGTK looks up a glyph for the
* character and the joiner together and draws a box when its fallback font lacks the joiner
* (#7019). There the joiner is split off as an empty widget, so the character is drawn on its
* own. Between ASCII characters (or at a line edge) it is shown like the other invisible
* characters. Next to any other non-ASCII character (Arabic, Indic scripts, emoji sequences)
* it shapes its neighbours and stays as it is.
*/
import {
type EditorView,
Decoration,
type DecorationSet,
MatchDecorator,
ViewPlugin,
type ViewUpdate,
WidgetType,
} from "@codemirror/view";
const JOINER = /[‌‍]/g;
/** CJK ideographs, kana, Hangul, CJK and fullwidth punctuation (UTF-16 units; surrogates of the supplementary ideographs too). */
function isCjk(code: number): boolean {
return (
(code >= 0x2e80 && code <= 0x9fff) ||
(code >= 0xac00 && code <= 0xd7af) ||
(code >= 0xd840 && code <= 0xd87f) ||
(code >= 0xdc00 && code <= 0xdfff) ||
(code >= 0xf900 && code <= 0xfaff) ||
(code >= 0xfe30 && code <= 0xfe4f) ||
(code >= 0xff00 && code <= 0xffef)
);
}
/** A neighbour the joiner may shape: non-ASCII, not CJK, not another invisible format character. */
function shapes(code: number | undefined): boolean {
if (code == null || code < 0x80 || isCjk(code)) return false;
return !(code >= 0x200b && code <= 0x200f) && code !== 0xfeff;
}
export type JoinerKind = "keep" | "split" | "show";
/** How the joiner between `before` and `after` (UTF-16 code units; undefined at a line edge) is drawn. */
export function joinerKind(before: number | undefined, after: number | undefined): JoinerKind {
if (shapes(before) || shapes(after)) return "keep";
if ((before != null && isCjk(before)) || (after != null && isCjk(after))) return "split";
return "show";
}
class SplitWidget extends WidgetType {
override eq() {
return true;
}
toDOM() {
const span = document.createElement("span");
span.className = "cm-zeroWidthJoiner";
return span;
}
override ignoreEvent() {
return false;
}
}
class ShowWidget extends WidgetType {
constructor(readonly code: number) {
super();
}
override eq(other: ShowWidget) {
return other.code === this.code;
}
toDOM() {
const span = document.createElement("span");
span.className = "cm-specialChar";
span.textContent = "•";
span.title = `\\u${this.code.toString(16)}`;
span.setAttribute("aria-label", span.title);
return span;
}
override ignoreEvent() {
return false;
}
}
const split = Decoration.replace({ widget: new SplitWidget() });
const shown = new Map([0x200c, 0x200d].map((c) => [c, Decoration.replace({ widget: new ShowWidget(c) })]));
const decorator = new MatchDecorator({
regexp: JOINER,
decoration: (match, view, pos) => {
const line = view.state.doc.lineAt(pos);
const at = pos - line.from;
const before = at > 0 ? line.text.charCodeAt(at - 1) : undefined;
const after = at + 1 < line.length ? line.text.charCodeAt(at + 1) : undefined;
const kind = joinerKind(before, after);
if (kind === "keep") return null;
return kind === "split" ? split : (shown.get(match[0]!.charCodeAt(0)) ?? null);
},
});
export const zeroWidthJoiners = ViewPlugin.fromClass(
class {
decorations: DecorationSet;
constructor(view: EditorView) {
this.decorations = decorator.createDeco(view);
}
update(update: ViewUpdate) {
this.decorations = decorator.updateDeco(update, this.decorations);
}
},
{ decorations: (v) => v.decorations },
);
-4
Переглянути файл
@@ -24,10 +24,6 @@ const overwriteInput = EditorView.inputHandler.of((view, _from, _to, text) => {
if (r.empty) {
const line = state.doc.lineAt(r.head);
to = Math.min(line.to, r.head + text.length);
// A range that ends between the halves of a surrogate pair takes the low half too, unless the
// typed text ends with a high surrogate that pairs with it.
const pair = state.doc.sliceString(to - 1, to + 1);
if (to > r.head && /^[\ud800-\udbff][\udc00-\udfff]$/.test(pair) && !/[\ud800-\udbff]$/.test(text)) to++;
}
return { changes: { from: r.from, to, insert: text }, range: EditorSelection.cursor(r.from + text.length) };
});
-2
Переглянути файл
@@ -71,7 +71,6 @@ import { horizontalScrollHold } from "./horizontalScrollHold";
import { relativeLineNumbers } from "./relativeLineNumbers";
import { clipboardDocumentPath, clipboardFilesExtension } from "./clipboard";
import { primarySelectionYield } from "./primarySelection";
import { zeroWidthJoiners } from "./joiners";
import type { LanguageInfo } from "../backend";
import { tx } from "@/platform/i18n";
@@ -441,7 +440,6 @@ export function baseExtensions(o: SetupOptions): Extension {
compartments.folding.of(foldingFor(o.settings)),
highlightActiveLineGutter(),
highlightSpecialChars(),
zeroWidthJoiners,
history(),
compartments.caret.of(caretFor(o.settings)),
dropCursor(),
-20
Переглянути файл
@@ -98,26 +98,6 @@ describe("string clipboard", () => {
expect(view.state.doc.toString()).toBe('value = ""\\\n"');
});
it.each([
["JavaScript", "javascript", "https://example.test"],
["TypeScript", "typescript", "https://example.test"],
["Python", "python", "https:\\/\\/example.test"],
])("%s unescapes an escaped slash only where the language does", async (mode, language, expected) => {
const view = await make(mode, language, 'value = "«https:\\/\\/example.test»"');
expect(copiedText(view.state)).toBe(expected);
});
it("keeps an escaped slash in a string of a language embedded in JavaScript", async () => {
// The embedded mode loads lazily; load it first so the first parse mounts it.
await loadSupport(findLanguageDescription("SQL", "")!);
const views = await Promise.all(
["", "// filler\n".repeat(400)].map((before) =>
make("JavaScript", "javascript", before + "const q = sql`SELECT '«a\\/b»'`;"),
),
);
for (const view of views) expect(copiedText(view.state)).toBe("a\\/b");
});
it("disables both escaping and unescaping with the setting", async () => {
const settings = { smartKeys: { escapeOnPaste: false, reformatOnPaste: "none" } };
const view = await make("Java", "java", 'value = "«a\\nb»"', settings);
+6 -16
Переглянути файл
@@ -8,11 +8,9 @@ const JS = new Set(["javascript", "typescript"]);
interface PlainString {
quote: string;
language: string;
/** `\/` is an escape: a JavaScript string, not one of a language embedded in a template literal. */
slash: boolean;
}
function readEscape(text: string, at: number, language: string, slash = false): { end: number; value: string } {
function readEscape(text: string, at: number, language: string): { end: number; value: string } {
const rest = text.slice(at + 1);
const ch = rest[0];
const basic: Record<string, string> = { n: "\n", r: "\r", t: "\t", "\\": "\\", '"': '"', "'": "'" };
@@ -20,7 +18,6 @@ function readEscape(text: string, at: number, language: string, slash = false):
if (!["kotlin", "rust"].includes(language)) basic.f = "\f";
if (["python", "go", "c", "cpp"].includes(language)) basic.a = "\x07";
if (!["java", "kotlin", "rust"].includes(language)) basic.v = "\v";
if (slash) basic["/"] = "/";
if (language === "kotlin") basic.$ = "$";
if (language === "java") basic.s = " ";
if (language === "c" || language === "cpp") basic["?"] = "?";
@@ -88,9 +85,7 @@ function plainStringAt(state: EditorState, from: number, to: number, language: s
if ([from, to].some((pos) => pos > node.from + i && pos < node.from + end)) return null;
i = end - 1;
}
let embedded = false;
for (let n = node.parent; n; n = n.parent) if (n.type.isTop && n.parent) embedded = true;
return { quote, language, slash: JS.has(language) && !embedded };
return { quote, language };
}
if (!node.parent) return null;
node = node.parent;
@@ -114,12 +109,12 @@ function escapeText(text: string, literal: PlainString): string {
});
}
function unescapeText(text: string, literal: PlainString): string {
function unescapeText(text: string, language: string): string {
let out = "";
for (let i = 0; i < text.length; i++) {
if (text[i] !== "\\") out += text[i];
else {
const escape = readEscape(text, i, literal.language, literal.slash);
const escape = readEscape(text, i, language);
out += escape.value;
i = escape.end - 1;
}
@@ -156,15 +151,10 @@ export function stringClipboard(language: string | undefined): Extension {
),
EditorView.clipboardOutputFilter.of((text, state) => {
const ranges = state.selection.ranges;
const literals: PlainString[] = [];
for (const r of ranges) {
const literal = r.empty ? null : plainStringAt(state, r.from, r.to, language);
if (!literal) return text;
literals.push(literal);
}
if (ranges.some((r) => r.empty || !plainStringAt(state, r.from, r.to, language))) return text;
const selected = ranges.map((r) => state.sliceDoc(r.from, r.to));
if (text !== selected.join(state.lineBreak)) return text;
return selected.map((part, i) => unescapeText(part, literals[i]!)).join(state.lineBreak);
return selected.map((part) => unescapeText(part, language)).join(state.lineBreak);
}),
];
}
+3 -61
Переглянути файл
@@ -1,6 +1,6 @@
import { describe, expect, it, vi } from "vitest";
import type { CodeAction, WorkspaceEdit } from "@/bindings";
import { readyOrganizeImportsAction, unambiguousImport } from "./autoImport";
import { describe, expect, it } from "vitest";
import type { CodeAction } from "@/bindings";
import { unambiguousImport } from "./autoImport";
const action = (title: string, over: Partial<CodeAction> = {}): CodeAction => ({
title,
@@ -14,21 +14,6 @@ const action = (title: string, over: Partial<CodeAction> = {}): CodeAction => ({
...over,
});
const organizeEdit = (): WorkspaceEdit => ({
files: [
{
kind: "edit",
path: "/p/Sample.java",
edits: [
{
range: { start: { line: 3, col: 0 }, end: { line: 4, col: 0 } },
new_text: "",
},
],
},
],
});
describe("unambiguousImport", () => {
it("applies the one import fix among other quick fixes", () => {
const fix = action("Import 'ArrayList' (java.util)");
@@ -58,46 +43,3 @@ describe("unambiguousImport", () => {
expect(unambiguousImport([action("UnityEngine.SceneManagement.SceneManager")])).toBeNull();
});
});
describe("readyOrganizeImportsAction", () => {
const organize = (over: Partial<CodeAction> = {}) =>
action("Organize imports", { kind: "source.organizeImports", ...over });
it("resolves a lazy organize-imports action that has data but no edit", async () => {
const lazy = organize({ data: '{"id":"organize_imports"}' });
const resolved = { ...lazy, edit: organizeEdit() };
const resolve = vi.fn(async (a: CodeAction) => {
expect(a).toBe(lazy);
return resolved;
});
await expect(readyOrganizeImportsAction([lazy], resolve)).resolves.toBe(resolved);
expect(resolve).toHaveBeenCalledOnce();
});
it("uses an action that already has an edit without resolving", async () => {
const ready = organize({ edit: organizeEdit() });
const resolve = vi.fn(async (a: CodeAction) => a);
await expect(readyOrganizeImportsAction([ready], resolve)).resolves.toBe(ready);
expect(resolve).not.toHaveBeenCalled();
});
it("skips disabled actions and lazy actions that cannot be resolved to an edit", async () => {
const resolve = vi.fn(async (a: CodeAction) => a);
await expect(
readyOrganizeImportsAction(
[
organize({ disabledReason: "unavailable", edit: organizeEdit() }),
organize(),
action("Import 'HashMap' (java.util)", { data: "{}" }),
],
resolve,
),
).resolves.toBeUndefined();
expect(resolve).not.toHaveBeenCalled();
const lazy = organize({ data: '{"id":"organize_imports"}' });
const unresolved = vi.fn(async (a: CodeAction) => a);
await expect(readyOrganizeImportsAction([lazy], unresolved)).resolves.toBeUndefined();
expect(unresolved).toHaveBeenCalledOnce();
});
});
+1 -22
Переглянути файл
@@ -35,25 +35,6 @@ export function unambiguousImport(actions: readonly CodeAction[]): CodeAction |
return imports.length === 1 ? imports[0]! : null;
}
/**
* An organize-imports action the on-the-fly path can inspect.
* java-analyzer (and other servers) often return a lazy action with `data` and
* no `edit`; the workspace edit is only available after `codeAction/resolve`.
* Command-palette and optimize-on-save already resolve through
* `runInteractiveCodeAction` / `lspApplyCodeAction`.
*/
export async function readyOrganizeImportsAction(
actions: readonly CodeAction[],
resolve: (action: CodeAction) => Promise<CodeAction>,
): Promise<CodeAction | undefined> {
const action = actions.find((a) => a.kind?.startsWith("source.organizeImports") && !a.disabledReason);
if (!action) return undefined;
if (action.edit) return action;
if (action.data == null) return undefined;
const resolved = await resolve(action);
return resolved.edit && !resolved.disabledReason ? resolved : undefined;
}
/** Whether a workspace edit for `path` touches 0-based `line`. */
export function editTouchesLine(action: CodeAction, path: string, line: number): boolean {
for (const f of action.edit?.files ?? []) {
@@ -135,9 +116,7 @@ const autoImportPlugin = ViewPlugin.fromClass(
const doc = docOf(view)!;
const range = offsetsToRange(view.state.doc, 0, view.state.doc.length);
const actions = await lspRequest(() => commands.lspCodeActions(doc.doc, range, ["source.organizeImports"]));
const action = await readyOrganizeImportsAction(actions, (a) =>
lspRequest(() => commands.lspResolveCodeAction(doc.doc, a)),
);
const action = actions.find((a) => a.kind?.startsWith("source.organizeImports") && !a.disabledReason && a.edit);
if (!action || editTouchesLine(action, doc.path, caretLine)) return;
const edits = action.edit!.files.flatMap((f) => (f.kind === "edit" && f.path === doc.path ? f.edits : []));
const noop = edits.every((e) => {
+1 -149
Переглянути файл
@@ -39,7 +39,7 @@ vi.mock("@tauri-apps/api/core", async (orig) => ({
},
}));
const { lensTargets, skipInheritedLifecycleUsages, usagesLensExtension } = await import("./codeLens");
const { lensTargets, usagesLensExtension } = await import("./codeLens");
const { foregroundStarted } = await import("./foreground");
const { lspDoc } = await import("./lsp");
const { useProject } = await import("@/platform/project");
@@ -692,151 +692,3 @@ describe("file changes on disk", () => {
expect(ipc.lspReferences).toHaveBeenCalledTimes(80);
});
});
describe("inherited Dart lifecycle usages", () => {
const textOf = (src: string) => EditorState.create({ doc: src }).doc;
const src = [
"class _PageState extends State<Page> {",
" @override",
" void initState() { super.initState(); }",
"",
" @override",
" Widget build(BuildContext context) { return const SizedBox(); }",
"",
" @override",
" void dispose() { super.dispose(); }",
"",
" @override",
" void didUpdateWidget(Page oldWidget) { super.didUpdateWidget(oldWidget); }",
"",
" @override",
" void didChangeDependencies() { super.didChangeDependencies(); }",
"",
" Future<void> loadData() async {}",
"",
" Widget buildHelper() { return const SizedBox(); }",
"",
" @override Widget createState() => this;",
"",
" @override",
" String toString() => 'page';",
"",
" @override",
" int get hashCode => 1;",
"",
" @override",
" bool operator ==(Object other) => other is _PageState;",
"}",
].join("\n");
const doc = textOf(src);
const lineOf = (snippet: string) => src.split("\n").findIndex((l) => l.includes(snippet));
it("skips Flutter @override lifecycle methods, not other Dart names", () => {
expect(skipInheritedLifecycleUsages("dart", "initState", doc, lineOf("void initState"))).toBe(true);
expect(skipInheritedLifecycleUsages("dart", "build", doc, lineOf("Widget build(BuildContext"))).toBe(true);
expect(skipInheritedLifecycleUsages("dart", "dispose", doc, lineOf("void dispose"))).toBe(true);
expect(skipInheritedLifecycleUsages("dart", "didUpdateWidget", doc, lineOf("void didUpdateWidget"))).toBe(true);
expect(
skipInheritedLifecycleUsages("dart", "didChangeDependencies", doc, lineOf("void didChangeDependencies")),
).toBe(true);
expect(skipInheritedLifecycleUsages("dart", "createState", doc, lineOf("@override Widget createState"))).toBe(true);
expect(skipInheritedLifecycleUsages("dart", "toString", doc, lineOf("String toString"))).toBe(true);
expect(skipInheritedLifecycleUsages("dart", "hashCode", doc, lineOf("int get hashCode"))).toBe(true);
expect(skipInheritedLifecycleUsages("dart", "operator ==", doc, lineOf("bool operator"))).toBe(true);
expect(skipInheritedLifecycleUsages("dart", "==", doc, lineOf("bool operator"))).toBe(true);
expect(skipInheritedLifecycleUsages("dart", "loadData", doc, lineOf("Future<void> loadData"))).toBe(false);
expect(skipInheritedLifecycleUsages("dart", "buildHelper", doc, lineOf("Widget buildHelper"))).toBe(false);
expect(skipInheritedLifecycleUsages("dart", "_PageState", doc, 0)).toBe(false);
expect(skipInheritedLifecycleUsages("rust", "build", doc, lineOf("Widget build(BuildContext"))).toBe(false);
});
it("does not skip a lifecycle name that is not an override", () => {
const plain = textOf("void dispose() {}\nWidget build() { return const SizedBox(); }");
expect(skipInheritedLifecycleUsages("dart", "dispose", plain, 0)).toBe(false);
expect(skipInheritedLifecycleUsages("dart", "build", plain, 1)).toBe(false);
});
});
describe("Dart Code Vision references", () => {
const dart = { doc: 11, path: "/p/page.dart", language: "dart", uiMode: "Dart", readOnly: false };
const src = [
"class _PageState extends State<Page> {",
" @override",
" void initState() {}",
" @override",
" Widget build(BuildContext context) { return const SizedBox(); }",
" Future<void> loadData() async {}",
" void refresh() {}",
"}",
].join("\n");
it("does not query references for @override lifecycle methods", async () => {
ipc.docOutline.mockResolvedValue(
ok([
item("_PageState", "class", 0, [
item("initState", "method", 2),
item("build", "method", 4),
item("loadData", "method", 5),
item("refresh", "method", 6),
]),
]),
);
const view = new EditorView({
state: EditorState.create({
doc: src,
extensions: [lspDoc.of(dart), usagesLensExtension()],
}),
parent: document.body,
});
views.push(view);
await settle();
expect(ipc.lspReferences.mock.calls.map((c) => c[2])).toEqual([
{ line: 0, col: 0 },
{ line: 5, col: 0 },
{ line: 6, col: 0 },
]);
expect(titles(view)).toEqual(["2 usages", "2 usages", "2 usages"]);
});
it("asks Dart references one at a time", async () => {
const pending = deferred<ReturnType<typeof refs>>();
ipc.docOutline.mockResolvedValue(ok(Array.from({ length: 8 }, (_, i) => item(`f${i}`, "function", i))));
ipc.lspReferences.mockReturnValue(pending.promise);
const view = new EditorView({
state: EditorState.create({
doc: Array.from({ length: 8 }, (_, i) => `void f${i}() {}`).join("\n"),
extensions: [lspDoc.of(dart), usagesLensExtension()],
}),
parent: document.body,
});
views.push(view);
await settle();
expect(ipc.lspReferences).toHaveBeenCalledTimes(1);
pending.resolve(refs(1));
await settle();
expect(ipc.lspReferences).toHaveBeenCalledTimes(8);
});
it("does not start a new Dart references wave until a cancelled request has finished", async () => {
const first = deferred<ReturnType<typeof refs>>();
ipc.lspReferences.mockReturnValueOnce(first.promise).mockResolvedValue(refs(2));
ipc.docOutline.mockResolvedValue(ok([item("loadData", "function", 0)]));
const view = new EditorView({
state: EditorState.create({
doc: "void loadData() {}",
extensions: [lspDoc.of(dart), usagesLensExtension()],
}),
parent: document.body,
});
views.push(view);
await settle();
expect(ipc.lspReferences).toHaveBeenCalledTimes(1);
_emitEditorEvent({ type: "docChanged", doc: 9, path: "/p/b.dart", baseVersion: 1, version: 2, changes: [] });
await settle();
expect(ipc.lspReferences).toHaveBeenCalledTimes(1);
first.resolve(refs(1));
await settle();
expect(ipc.lspReferences).toHaveBeenCalledTimes(2);
expect(titles(view)).toEqual(["2 usages"]);
});
});
+4 -76
Переглянути файл
@@ -3,11 +3,7 @@
* construction: only declarations in (and near) the viewport are counted, one
* debounced pass after edits / scrolling, results cached per document text
* and symbol until the project's documents change, and at most a few reference
* requests in flight. Dart is the exception: inherited Flutter lifecycle methods
* (`@override build`, `initState`, …) resolve to the framework and a single
* isolate cannot cancel `textDocument/references` promptly, so those methods are
* skipped and remaining Dart counts run one at a time, never overlapping a
* request that has not finished. Counts run the same references query the Find Usages
* requests in flight. Counts run the same references query the Find Usages
* panel runs (including the plugin indexers' anchors), scoped to what the
* server analyses: opening candidate files or the libraries for every count
* would trigger expensive server analysis, so only an explicit Find Usages
@@ -58,8 +54,6 @@ const LENS_KINDS = new Set<SymbolKind>([
const MAX_PER_PASS = 40;
const CONCURRENCY = 4;
/** The Dart analyzer is a single isolate; overlapping references stall completion. */
const DART_CONCURRENCY = 1;
/** Lines above/below the viewport that are counted too, so scrolling feels instant. */
const MARGIN_LINES = 10;
/**
@@ -138,46 +132,6 @@ export function usagesLabel(n: number): string {
return n === 1 ? tx("1 usage") : tx`${n} usages`;
}
/**
* Flutter / Dart `@override` lifecycle and Object methods. A references query
* for any of them walks the framework (and the project) from the superclass.
*/
const DART_INHERITED_LIFECYCLE = new Set([
"build",
"createState",
"initState",
"dispose",
"didUpdateWidget",
"didChangeDependencies",
"deactivate",
"activate",
"reassemble",
"toString",
"hashCode",
"==",
]);
/** Outline names for `operator ==` (`==`, `operator ==`). */
function dartMethodName(name: string): string {
return name.replace(/^operator\s+/, "").trim();
}
/**
* Whether Code Vision should skip a usages query for this declaration: a Dart
* method whose name is a framework lifecycle / Object member, with `@override`
* on or just above the name. Exported for tests.
*/
export function skipInheritedLifecycleUsages(language: string, name: string, text: Text, line: number): boolean {
if (language !== "dart") return false;
if (!DART_INHERITED_LIFECYCLE.has(dartMethodName(name))) return false;
const from = Math.max(1, line + 1 - 4);
const to = Math.min(text.lines, line + 1);
for (let n = from; n <= to; n++) {
if (/@override\b/.test(text.line(n).text)) return true;
}
return false;
}
const setLenses = StateEffect.define<CodeLens[]>();
const lensField = StateField.define<CodeLens[]>({
@@ -232,11 +186,6 @@ class UsagesLensPlugin {
private skipped = false;
/** A pass was cut short or held back by a foreground request, and runs once it is done. */
private yielded = false;
/** Reference requests still running on the server, including ones already cancelled. */
private inflight = 0;
/** A Dart pass is waiting for `inflight` to reach 0 before asking again. */
private drain = false;
private closed = false;
constructor(private view: EditorView) {
this.refresh();
@@ -327,11 +276,6 @@ class UsagesLensPlugin {
this.yielded = true;
return;
}
// Dart's analyzer does not cancel promptly; a new wave on top of a cancelled one stalls it.
if (doc.language === "dart" && this.inflight > 0) {
this.drain = true;
return;
}
const gen = this.generation;
const usagesWanted = usagesEnabled() && !isLibrarySource(doc);
const usages = usagesWanted && !usagesBackoff.active(doc.doc);
@@ -363,30 +307,20 @@ class UsagesLensPlugin {
.filter((t) => t.line >= firstLine && t.line <= lastLine)
.slice(0, MAX_PER_PASS);
const key = (t: LensTarget) => `${t.line}:${t.col}:${t.name}`;
const todo = usages
? visible.filter(
(t) =>
!this.cache.has(key(t)) &&
!this.incomplete.has(key(t)) &&
!skipInheritedLifecycleUsages(doc.language, t.name, text, t.line),
)
: [];
const todo = usages ? visible.filter((t) => !this.cache.has(key(t)) && !this.incomplete.has(key(t))) : [];
let unavailable = false;
let retry = false;
// A base file is outlined once per pass, however many of its methods are overridden here.
const outlines: OutlineCache = new Map([[doc.path, Promise.resolve(this.outline.items)]]);
const concurrency = doc.language === "dart" ? DART_CONCURRENCY : CONCURRENCY;
for (let i = 0; i < todo.length && !unavailable; i += concurrency) {
for (let i = 0; i < todo.length && !unavailable; i += CONCURRENCY) {
if (inForeground()) {
this.yielded = true;
return;
}
if (!wanted()) return;
// oxlint-disable-next-line no-await-in-loop -- batched in groups of CONCURRENCY; a batch's flags decide whether the next batch runs
await Promise.all(
todo.slice(i, i + concurrency).map(async (t) => {
todo.slice(i, i + CONCURRENCY).map(async (t) => {
const request = nextRequestId();
this.inflight++;
try {
// Opening candidate files for each count triggers expensive server analysis.
// Only an explicit Find Usages should widen the server's scope.
@@ -417,11 +351,6 @@ class UsagesLensPlugin {
if (wanted() && isUnavailable(e)) unavailable = true;
} finally {
this.pending.delete(request);
this.inflight--;
if (this.inflight === 0 && this.drain && !this.closed) {
this.drain = false;
this.schedule();
}
}
}),
);
@@ -496,7 +425,6 @@ class UsagesLensPlugin {
}
destroy() {
this.closed = true;
this.schedule.cancel();
this.unsubscribe();
this.offReady();
-84
Переглянути файл
@@ -523,90 +523,6 @@ describe("applying completions", () => {
expect(a!.apply).not.toBe(b!.apply);
});
it("keeps same-name imports from different modules apart", () => {
const { req } = setup("@RequestBod|");
const packages = ["org.springframework.web.bind.annotation", "io.swagger.v3.oas.annotations.parameters"];
const [a, b] = packages.map((labelDescription) =>
makeCompletion(
item({ label: "RequestBody", kind: "interface", insertText: "RequestBody", labelDescription }),
req,
),
);
expect([a!.label, b!.label]).toEqual(["RequestBody", "RequestBody"]);
expect(a!.detail).toBeUndefined();
expect(b!.detail).toBeUndefined();
expect(typeColumnText(a!.lsp)).toBe(packages[0]);
expect(typeColumnText(b!.lsp)).toBe(packages[1]);
expect(a!.apply).not.toBe(b!.apply);
});
it("completes a keyword rather than a declaration snippet with the same name", async () => {
const { view } = setup("public interf| Demo {}");
setInvokeRoute((cmd) => {
if (cmd === "cancel_request") return Promise.resolve(null);
if (cmd === "lsp_completion") {
return Promise.resolve({
isIncomplete: false,
items: [
item({ label: "interface", kind: "keyword", insertText: "interface" }),
item({
label: "interface",
kind: "snippet",
insertText: "public interface ${1:Demo} {\n\t$0\n}",
isSnippet: true,
}),
],
});
}
return Promise.resolve(null);
});
try {
view.dispatch({
effects: StateEffect.appendConfig.of([
lspDoc.of({ doc: 7151, path: "/p/Demo.java", language: "java", uiMode: "Java", readOnly: false }),
completionExtension(),
]),
});
startCompletion(view);
await vi.waitFor(() => expect(currentCompletions(view.state)).toHaveLength(1));
expect((currentCompletions(view.state)[0] as unknown as { lsp: CompletionItem }).lsp.kind).toBe("keyword");
} finally {
setInvokeRoute(null);
}
});
it("lists same-name Java imports from different packages", async () => {
const { view } = setup("@RequestBod|");
const packages = ["org.springframework.web.bind.annotation", "io.swagger.v3.oas.annotations.parameters"];
setInvokeRoute((cmd) => {
if (cmd === "cancel_request") return Promise.resolve(null);
if (cmd === "lsp_completion") {
return Promise.resolve({
isIncomplete: false,
items: packages.map((labelDescription) =>
item({ label: "RequestBody", kind: "interface", insertText: "RequestBody", labelDescription }),
),
});
}
return Promise.resolve(null);
});
try {
view.dispatch({
effects: StateEffect.appendConfig.of([
lspDoc.of({ doc: 7144, path: "/p/Demo.java", language: "java", uiMode: "Java", readOnly: false }),
completionExtension(),
]),
});
startCompletion(view);
await vi.waitFor(() => expect(currentCompletions(view.state)).toHaveLength(2));
expect(
currentCompletions(view.state).map((c) => typeColumnText((c as unknown as { lsp: CompletionItem }).lsp)),
).toEqual(packages);
} finally {
setInvokeRoute(null);
}
});
it("replaces the rest of the identifier with ⇥", () => {
const { view, req } = setup("service.cr|Order()");
applyLspCompletion(view, makeCompletion(item({ insertText: "create" }), req), 8, 10, "replace");
+2 -14
Переглянути файл
@@ -749,17 +749,9 @@ export function makeCompletion(item: CompletionItem, req: RequestContext): LspCo
req,
// CodeMirror merges options with the same label, detail and `apply`: overloads
// sharing a filterText (`times(other: Int)`, `times(other: Long)`…) and the same
// name imported from different modules need their own. A Java type's package is
// shown in the type column (`labelDescription` / `detail`), not CodeMirror's
// `detail`, and JDT.LS often defers the import edit until resolve — without a
// distinct apply, only one of those candidates is listed.
// name imported from different modules need their own.
apply:
cm.displayLabel ||
(item.filterText && item.filterText !== item.label) ||
item.additionalEdits.length ||
item.labelDescription ||
item.detail ||
item.labelDetail
cm.displayLabel || (item.filterText && item.filterText !== item.label) || item.additionalEdits.length
? (...a: Parameters<typeof applyLsp>) => applyLsp(...a)
: applyLsp,
info: (c: Completion) => renderInfo(c as LspCompletion),
@@ -875,10 +867,6 @@ async function lspCompletionSource(ctx: CompletionContext): Promise<CompletionRe
if (inVarCall(ctx)) items = items.filter((it) => !it.label.startsWith("--"));
const pruned = pruneItems(items, typed);
items = [...pruned.items];
// A server snippet named like a keyword it also lists (jdtls `interface`, `class`, `enum` declaration
// skeletons) would replace one word with a whole declaration; IDEA completes the keyword.
const keywords = new Set(items.filter((it) => it.kind === "keyword").map((it) => it.label));
if (keywords.size) items = items.filter((it) => it.kind !== "snippet" || !keywords.has(it.label));
// A server snippet named like a live template (jdtls `sout`, `fori`) would be listed twice; the template wins.
if (items.some((it) => it.kind === "snippet")) {
const own = await contributedSource(ctx);
+1 -2
Переглянути файл
@@ -1,8 +1,7 @@
import { describe, expect, it } from "vitest";
import { Marked } from "marked";
import DOMPurify from "dompurify";
import { mathExtension } from "./markdownMath";
import { renderMath } from "./renderMarkdownMath";
import { mathExtension, renderMath } from "./markdownMath";
const marked = new Marked({ gfm: true, breaks: false }).use(mathExtension());
+20
Переглянути файл
@@ -6,6 +6,9 @@
* 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 {
@@ -207,3 +210,20 @@ 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 -2
Переглянути файл
@@ -1,8 +1,7 @@
/** Markdown → sanitized HTML (marked + DOMPurify); loaded on demand by `markdown.ts`. */
import { Marked } from "marked";
import DOMPurify from "dompurify";
import { mathExtension } from "./markdownMath";
import { renderMath } from "./renderMarkdownMath";
import { mathExtension, renderMath } from "./markdownMath";
/** 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;
-20
Переглянути файл
@@ -1,20 +0,0 @@
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,
});
});
}
-5
Переглянути файл
@@ -346,8 +346,3 @@
color: var(--fg-muted);
font-size: var(--fs-small);
}
.inUse {
flex: none;
color: var(--warning);
font-size: var(--fs-small);
}
+1 -6
Переглянути файл
@@ -754,17 +754,12 @@ export function AgentsView() {
<div className={styles.empty}>{externalError}</div>
) : (
<div className={styles.external}>
{external.slice(0, 50).map((s) => {
{external.map((s) => {
const key = externalKey(s.provider, s.sessionId);
return (
<div key={key} className={styles.row} title={s.cwd ?? s.sessionId}>
<Icon name={providerIcon(s.provider)} size={16} label={providerName(s.provider)} />
<span className={styles.title}>{s.title}</span>
{s.inUse && (
<span className={styles.inUse} title={tx("Open in another app")}>
<T>In use</T>
</span>
)}
<span className={styles.age}>{age(s.updatedMs ?? 0)}</span>
<button
type="button"
+1 -2
Переглянути файл
@@ -91,7 +91,6 @@ import { imageSrc } from "./imageActions";
import { useAgentSettings } from "./agentSettings";
import styles from "./Composer.module.css";
import { isImeKey } from "@/platform/ime";
import { ipcPath } from "@/platform/paths";
const MAX_ITEMS = 12;
const MAX_OPEN_EDITORS = 5;
@@ -1064,7 +1063,7 @@ export function Composer(props: ComposerProps) {
setFileOver(false);
if (p.type !== "drop" || !p.paths.length || !inBox(p.position)) return;
const paths: string[] = [];
for (const path of p.paths.map(ipcPath)) {
for (const path of p.paths) {
if (IMAGE_EXTENSIONS.test(path)) {
void invokeLocal<string>("fs_read_image", { path }).then(
(url) => {
+9 -41
Переглянути файл
@@ -16,7 +16,7 @@ import {
} from "./store";
import styles from "./Agents.module.css";
/** At most this many matching sessions are shown at once, newest first. */
/** The backend lists at most this many sessions, newest first. */
const LISTED_MAX = 50;
const ROW = 24;
@@ -28,8 +28,6 @@ interface Row {
cwd: string | null;
folder: string;
updatedMs: number;
/** Open in another app, which would keep writing to it too. */
inUse: boolean;
}
interface Selection {
@@ -76,7 +74,7 @@ function ImportSessionsDialog() {
const [frozen, setFrozen] = useState<Row[] | null>(null);
const abort = useRef<AbortController | null>(null);
const matched = useMemo<Row[]>(() => {
const rows = useMemo<Row[]>(() => {
const q = query.trim().toLowerCase();
return external
.map((s) => ({
@@ -87,18 +85,10 @@ function ImportSessionsDialog() {
cwd: s.cwd ?? null,
folder: folderOf(s.cwd ?? null, root),
updatedMs: s.updatedMs ?? 0,
inUse: s.inUse,
}))
.filter((r) => !importing.has(r.key))
.filter(
(r) =>
!q ||
r.title.toLowerCase().includes(q) ||
r.folder.toLowerCase().includes(q) ||
r.sessionId.toLowerCase().includes(q),
);
.filter((r) => !q || r.title.toLowerCase().includes(q) || r.folder.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.
@@ -109,8 +99,6 @@ function ImportSessionsDialog() {
const chosen = sel.keys ? view.filter((r) => sel.keys!.has(r.key)) : lead >= 0 ? [view[lead]!] : [];
const busy = progress !== null;
const shown = !loading && !externalError;
// Importing a session another app has open would let both write to it: a fork is a safe copy.
const forkByDefault = chosen.some((r) => r.inUse);
const select = (index: number, e?: KeyboardEvent | MouseEvent) => {
if (busy) return;
@@ -161,11 +149,10 @@ function ImportSessionsDialog() {
hideImportSessions();
};
const forkChosen = () => runChosen(true);
const runDefault = () => runChosen(forkByDefault);
const onFilterKey = (e: KeyboardEvent) => {
if (e.key === "Enter") {
e.preventDefault();
runDefault();
importChosen();
return;
}
// Home / End move the caret in the filter text.
@@ -178,7 +165,7 @@ function ImportSessionsDialog() {
const onListKey = (e: KeyboardEvent) => {
if (e.key === "Enter") {
e.preventDefault();
runDefault();
importChosen();
} else if (e.key.toLowerCase() === "a" && hasPrimaryModifier(e)) {
e.preventDefault();
selectAll();
@@ -205,11 +192,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 && forkByDefault ? (
<span className={styles.chooserHint}>
<T>Another app has this session open. Fork copies it so both can continue.</T>
</span>
) : shown && matched.length > LISTED_MAX ? (
) : shown && external.length >= LISTED_MAX ? (
<span className={styles.chooserHint}>
<T>Only the 50 most recent sessions are shown.</T>
</span>
@@ -218,18 +201,8 @@ function ImportSessionsDialog() {
}
buttons={[
{ label: "Cancel", role: "cancel" },
{
label: forkLabel,
role: forkByDefault ? "default" : undefined,
onClick: forkChosen,
disabled: busy || !shown || !chosen.length,
},
{
label: importLabel,
role: forkByDefault ? undefined : "default",
onClick: importChosen,
disabled: busy || !shown || !chosen.length,
},
{ label: forkLabel, onClick: forkChosen, disabled: busy || !shown || !chosen.length },
{ label: importLabel, role: "default", onClick: importChosen, disabled: busy || !shown || !chosen.length },
]}
>
<div className={styles.chooser}>
@@ -250,7 +223,7 @@ function ImportSessionsDialog() {
className={styles.chooserList}
onKeyDown={onListKey}
onDoubleClick={(e) => {
if ((e.target as Element).closest('[role="option"]')) runDefault();
if ((e.target as Element).closest('[role="option"]')) importChosen();
}}
>
{loading ? (
@@ -279,11 +252,6 @@ function ImportSessionsDialog() {
<Icon name={providerIcon(r.provider)} size={16} label={providerName(r.provider)} />
<span className={styles.title}>{r.title}</span>
{r.folder && <span className={styles.chooserFolder}>{r.folder}</span>}
{r.inUse && (
<span className={styles.inUse} title={tx("Open in another app")}>
<T>In use</T>
</span>
)}
<span className={styles.age}>{age(r.updatedMs)}</span>
</span>
)}
+1 -2
Переглянути файл
@@ -11,8 +11,7 @@ import { useEffect, useLayoutEffect, useRef, useSyncExternalStore } from "react"
import { Marked } from "marked";
import DOMPurify from "dompurify";
import { highlightInto } from "@/editor/lsp/markdown";
import { mathExtension } from "@/editor/lsp/markdownMath";
import { renderMath } from "@/editor/lsp/renderMarkdownMath";
import { mathExtension, renderMath } from "@/editor/lsp/markdownMath";
import { iconNode } from "@/ui/iconNode";
import { tx } from "@/platform/i18n";
import { openExternalUrl } from "@/platform/openUrl";
+1 -37
Переглянути файл
@@ -1,9 +1,5 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { EditorState, EditorSelection } from "@codemirror/state";
import { commands } from "@/bindings";
import * as editorApi from "@/editor/api";
import { executeAction, getAction, registerAction, registerActions } from "@/platform/actions";
import * as context from "@/platform/context";
import { registerAction, registerActions } from "@/platform/actions";
import { useProject } from "@/platform/project";
import * as contributions from "@/workbench/contributions";
import type { MenuItem } from "@/ui";
@@ -28,7 +24,6 @@ beforeEach(() => {
contributions.provideNotificationService({ notify });
vi.spyOn(contributions, "editorService").mockReturnValue({} as contributions.EditorService);
useProject.setState({ project: { root: "/w/api", workspace: { projects: ["/w/api", "/w/web"] } } as never });
context.setContext("projectOpen", true);
useAgents.setState({ draft: { ...useAgents.getState().draft, projectRoot: "/w/api" } });
disposers.push(
registerActions(copyAgentReferenceActions),
@@ -43,7 +38,6 @@ afterEach(() => {
.reverse()
.forEach((dispose) => dispose());
useProject.setState({ project: null });
context.clearContext("projectOpen");
vi.restoreAllMocks();
vi.unstubAllGlobals();
});
@@ -107,33 +101,3 @@ describe("Copy Path/Reference… › Agent Reference", () => {
expect(hint).not.toHaveBeenCalled();
});
});
describe("Copy Agent Reference without targets (shortcut, Find Action)", () => {
it("is listed for the keymap and Find Action", () => {
expect(getAction("agents.copyAgentReference")?.hidden).toBeFalsy();
});
it("copies the active editor's file with the selected lines", async () => {
const state = EditorState.create({
doc: "a\nb\nc\nd\n",
selection: EditorSelection.range(2, 6),
});
vi.spyOn(editorApi, "activeEditor").mockReturnValue({
view: { state },
ctx: { path: "/w/api/a.go" },
} as never);
await executeAction("agents.copyAgentReference");
await vi.waitFor(() => expect(writeText).toHaveBeenCalledExactlyOnceWith("@a.go:2-3"));
});
it("copies the focused Project view's selection, folders with a slash", async () => {
vi.spyOn(context, "getContext").mockReturnValue({ ...context.getContext(), projectViewFocus: true });
vi.spyOn(contributions, "projectViewSelection").mockReturnValue(["/w/api/src", "/w/api/main.go"]);
vi.spyOn(commands, "fsEntryKind").mockImplementation(async (path) => ({
status: "ok",
data: path.endsWith("src") ? "dir" : "file",
}));
await executeAction("agents.copyAgentReference");
await vi.waitFor(() => expect(writeText).toHaveBeenCalledExactlyOnceWith("@src/ @main.go"));
});
});
+5 -34
Переглянути файл
@@ -3,15 +3,11 @@
* writes into the composer, so a selection or a Project view file can be pasted into a terminal
* agent as `@src/app.ts` / `@src/app.ts:12-18`.
*/
import { commands } from "@/bindings";
import { activeEditor } from "@/editor/api";
import { executeAction, type Action } from "@/platform/actions";
import { writeClipboardText } from "@/platform/clipboard";
import { getContext } from "@/platform/context";
import { call } from "@/platform/ipc";
import { tx } from "@/platform/i18n";
import { isVirtualUri } from "@/platform/virtualDocs";
import { notifications, projectViewSelection, registerMenuGroup } from "@/workbench/contributions";
import { notifications, registerMenuGroup } from "@/workbench/contributions";
import { mentionOf, referenceOf } from "./composerModel";
import { composerReferenceContext, type ReferenceTarget } from "./store";
@@ -42,41 +38,16 @@ async function copy(text: string) {
}
}
/**
* What a run without targets (a shortcut, Find Action) copies: the Project view's selection while
* it has focus, folders with a trailing slash; otherwise the active editor's file with the selected
* lines, or the caret's line, as the editor's menu does.
*/
async function contextTargets(): Promise<ReferenceTarget[]> {
if (getContext().projectViewFocus) {
const paths = projectViewSelection();
const kinds = await Promise.all(paths.map((path) => call(commands.fsEntryKind(path)).catch(() => null)));
return paths.map((path, i) => ({ path: kinds[i] === "dir" ? `${path}/` : path }));
}
const handle = activeEditor();
if (!handle) return [];
const { doc, selection } = handle.view.state;
const { from, to } = selection.main;
const first = doc.lineAt(from).number;
// A selection ending at a line start does not include that line.
const last = Math.max(first, doc.lineAt(to).number - (to > from && doc.lineAt(to).from === to ? 1 : 0));
return [{ path: handle.ctx.path, lines: { from: first, to: last } }];
}
export const copyAgentReferenceActions: Action[] = [
{
id: "agents.copyAgentReference",
title: "Copy Agent Reference",
description:
"Copies the `@` reference of the Project view selection, or of the editor's file and selected lines, for pasting into a terminal agent.",
category: "Edit",
icon: "copy",
when: "projectOpen",
keywords: ["agent", "reference", "mention", "path", "clipboard"],
run: async ({ arg }) => {
const targets = Array.isArray(arg) ? (arg as ReferenceTarget[]) : await contextTargets();
const text = agentReferences(targets);
if (text) await copy(text);
hidden: true,
run: ({ arg }) => {
const text = Array.isArray(arg) ? agentReferences(arg as ReferenceTarget[]) : null;
if (text) void copy(text);
},
},
];
+30 -80
Переглянути файл
@@ -217,8 +217,8 @@ export function revealRowsAt(el: HTMLElement, top: number) {
}
}
/** The first row the view shows and its box in the view; the rows are laid out in order. */
function firstShownRow(el: HTMLElement): { row: Element; top: number; height: number } | null {
/** The first row the view shows and its top in the view; the rows are laid out in order. */
function firstShownRow(el: HTMLElement): { row: Element; top: number } | null {
const rows = el.querySelectorAll(`:scope > .${styles.conversationRow}`);
if (!rows.length) return null;
const view = el.getBoundingClientRect().top;
@@ -230,9 +230,7 @@ function firstShownRow(el: HTMLElement): { row: Element; top: number; height: nu
else lo = mid + 1;
}
const row = rows[lo]!;
const box = row.getBoundingClientRect();
if (box.bottom <= view) return null;
return { row, top: box.top - view, height: box.height };
return { row, top: row.getBoundingClientRect().top - view };
}
/** Images remain visible beside the work's folded summary, without duplicating them when it opens. */
@@ -292,14 +290,6 @@ function clampMultiClick(target: EventTarget) {
if (row) clampSelectionToRow(document.getSelection(), row);
}
/** Interactive controls inside a row handle clicks of their own, not a scrollbar or selection drag. */
function isInteractiveTarget(target: EventTarget | null): boolean {
return (
target instanceof Element &&
target.closest("button, input, textarea, select, label, summary, a, [role='button'], [contenteditable]") !== null
);
}
/** First entry index painted for a `shown` tail cap, keeping a leading process run intact. */
function historyStart(entries: readonly AgentEntry[], shown: number): number {
let start = Math.max(0, entries.length - shown);
@@ -413,7 +403,7 @@ export function Stream({
}, [loadEarlier]);
useEffect(() => {
const down = (event: PointerEvent) => {
if (!ref.current?.contains(event.target as Node) || isInteractiveTarget(event.target)) return;
if (!ref.current?.contains(event.target as Node)) return;
dragging.current = true;
if (loadTimer.current !== null) {
window.clearTimeout(loadTimer.current);
@@ -498,7 +488,6 @@ export function Stream({
const shownRow = useRef<{
row: Element;
top: number;
height: number;
scrollTop: number;
} | null>(null);
const holdShownRow = useCallback(() => {
@@ -507,35 +496,24 @@ export function Stream({
const held = shownRow.current;
shownRow.current = null;
if (position.current.stick || !latest.current.visible) return;
// Rows that grew back below take the room left for them.
trimSlack();
if (held?.row.isConnected && !dragging.current) {
// Content that got shorter below clamps the offset to the new end; check before `trimSlack`
// shrinks `scrollHeight` on an upward user scroll.
const preTrimMaxScroll = el.scrollHeight - el.clientHeight;
const clamped =
preTrimMaxScroll < held.scrollTop - 0.5 &&
el.scrollTop < held.scrollTop &&
el.scrollTop >= preTrimMaxScroll - 1;
// Content that got shorter below clamps the offset to the new end.
const clamped = el.scrollTop < held.scrollTop && el.scrollTop >= el.scrollHeight - el.clientHeight - 1;
if (el.scrollTop === held.scrollTop || clamped) {
const box = held.row.getBoundingClientRect();
const padTop = parseFloat(getComputedStyle(el).paddingTop) || 0;
const collapsedPastTop = held.top < 0 && box.height < held.height - 0.5 && held.top + box.height <= padTop;
const desiredTop = collapsedPastTop ? padTop : held.top;
const moved = box.top - el.getBoundingClientRect().top - desiredTop;
const moved = held.row.getBoundingClientRect().top - el.getBoundingClientRect().top - held.top;
if (Math.abs(moved) >= 1) {
const maxContentScroll = Math.max(0, el.scrollHeight - slack.current - el.clientHeight);
const rawTarget = Math.max(0, el.scrollTop + moved);
const target = collapsedPastTop ? Math.min(rawTarget, maxContentScroll) : rawTarget;
const target = Math.max(0, el.scrollTop + moved);
const short = Math.ceil(target + el.clientHeight - el.scrollHeight);
if (short > 0) setSlack(slack.current + short);
el.scrollTop = target;
position.current = { top: el.scrollTop, stick: false };
positions.set(key, position.current);
updateJumpVisibility(el);
}
}
}
// Rows that grew back below, or an upward scroll, take the room left for them.
trimSlack();
updateJumpVisibility(el);
const shown = firstShownRow(el);
shownRow.current = shown && { ...shown, scrollTop: el.scrollTop };
}, [key, positions, setSlack, trimSlack, updateJumpVisibility]);
@@ -548,10 +526,7 @@ export function Stream({
const onDiagramDrawn = useCallback(() => {
const el = ref.current;
if (!el) return;
if (position.current.stick && !dragging.current && slack.current === 0) {
scrollStreamTo(el, el.scrollHeight);
position.current = { top: el.scrollTop, stick: true };
}
if (position.current.stick && !dragging.current) scrollStreamTo(el, el.scrollHeight);
updateJumpVisibility(el);
}, [updateJumpVisibility]);
useLayoutEffect(() => {
@@ -561,43 +536,27 @@ export function Stream({
// A message the user just sent: back to the end, where it shows, wherever they had scrolled.
const sent = previousLength.current > 0 && entries.slice(previousLength.current).some((e) => e.type === "user");
previousLength.current = entries.length;
if (sent) {
if (sent && !position.current.stick) {
scrollingUp.current = false;
if (slack.current !== 0) setSlack(0);
if (!position.current.stick) {
position.current = { top: el.scrollTop, stick: true };
positions.set(key, position.current);
setAway(false);
}
position.current = { top: el.scrollTop, stick: true };
positions.set(key, position.current);
setAway(false);
return;
}
if ((truncated || entries.length === 0) && el.scrollHeight - el.scrollTop - el.clientHeight < 40) {
scrollingUp.current = false;
if (slack.current !== 0) setSlack(0);
position.current = { top: el.scrollTop, stick: true };
positions.set(key, position.current);
setAway(false);
}
}, [entries, visible, key, positions, setSlack]);
}, [entries, visible, key, positions]);
useLayoutEffect(() => {
const el = ref.current;
if (!el || entries === null || !visible) return;
trimSlack();
if (position.current.stick) {
if (!dragging.current) {
const content = el.scrollHeight - slack.current;
if (slack.current === 0 || content - el.clientHeight > el.scrollTop) {
if (slack.current !== 0) setSlack(0);
scrollStreamTo(el, el.scrollHeight);
position.current = { top: el.scrollTop, stick: true };
positions.set(key, position.current);
} else {
trimSlack();
}
}
} else {
trimSlack();
if (!restored.current) scrollStreamTo(el, position.current.top);
}
if (!dragging.current) scrollStreamTo(el, el.scrollHeight);
} else if (!restored.current) scrollStreamTo(el, position.current.top);
restored.current = true;
updateJumpVisibility(el);
});
@@ -637,10 +596,8 @@ export function Stream({
if (!el) return;
const observer = new ResizeObserver(() => {
trimSlack();
if (position.current.stick && !dragging.current && slack.current === 0) {
scrollStreamTo(el, el.scrollHeight);
position.current = { top: el.scrollTop, stick: true };
} else if (!position.current.stick && el.scrollHeight <= el.clientHeight && !dragging.current) loadWhenStill();
if (position.current.stick && !dragging.current) scrollStreamTo(el, el.scrollHeight);
else if (!position.current.stick && el.scrollHeight <= el.clientHeight && !dragging.current) loadWhenStill();
updateJumpVisibility(el);
});
observer.observe(el);
@@ -704,7 +661,6 @@ export function Stream({
position.current = { top: el.scrollTop, stick: false };
positions.set(key, position.current);
}
seenHeight.current = { content: el.scrollHeight - slack.current, view: el.clientHeight };
updateJumpVisibility(el);
takeShownRow();
},
@@ -715,15 +671,13 @@ export function Stream({
const el = ref.current;
if (!el) return;
scrollingUp.current = false;
if (slack.current !== 0) setSlack(0);
shownRow.current = null;
position.current = { top: el.scrollTop, stick: true };
revealRowsAt(el, el.scrollHeight);
if (typeof el.scrollTo === "function") el.scrollTo({ top: el.scrollHeight, behavior: "smooth" });
else el.scrollTop = el.scrollHeight;
setAway(false);
el.focus({ preventScroll: true });
}, [setSlack]);
}, []);
// Forks and undo apply to the task's own turns, not a subagent's conversation.
const turns = useMemo(() => (entries && !subagent ? turnNumbers(entries) : null), [entries, subagent]);
const replies = useMemo(() => (entries && !subagent ? replyTurns(entries) : null), [entries, subagent]);
@@ -852,8 +806,7 @@ export function Stream({
)
scrollingUp.current = false;
}}
onPointerDown={(e) => {
if (isInteractiveTarget(e.target)) return;
onPointerDown={() => {
markUserScroll();
scrollingUp.current = false;
}}
@@ -866,24 +819,21 @@ export function Stream({
}}
onScroll={(e) => {
const el = e.currentTarget;
const contentHeight = el.scrollHeight - slack.current;
trimSlack();
const atEnd = el.scrollHeight - el.scrollTop - el.clientHeight < 40;
const laidOut =
contentHeight !== seenHeight.current.content || el.clientHeight !== seenHeight.current.view;
el.scrollHeight !== seenHeight.current.content || el.clientHeight !== seenHeight.current.view;
seenHeight.current = {
content: contentHeight,
content: el.scrollHeight,
view: el.clientHeight,
};
const byUser = dragging.current || performance.now() - userScrolled.current < 500 || !laidOut;
const movedDown = el.scrollTop > position.current.top;
const stayedAtEnd = position.current.stick && el.scrollTop === position.current.top;
if (!position.current.stick) holdShownRow();
trimSlack();
const atEnd = el.scrollHeight - el.scrollTop - el.clientHeight < 40;
const stick =
(atEnd && !scrollingUp.current && (movedDown || stayedAtEnd)) || (position.current.stick && !byUser);
// Still following: back to the end the offset was moved away from.
if (stick && !atEnd && !dragging.current && slack.current === 0) scrollStreamTo(el, el.scrollHeight);
if (stick) shownRow.current = null;
if (stick && !atEnd && !dragging.current) scrollStreamTo(el, el.scrollHeight);
position.current = { top: el.scrollTop, stick };
positions.set(key, position.current);
updateJumpVisibility(el);
@@ -891,7 +841,7 @@ export function Stream({
// once the drag has settled.
if (loadTimer.current !== null) window.clearTimeout(loadTimer.current);
if (!position.current.stick && el.scrollTop < 120 && !dragging.current) loadWhenStill();
if (!position.current.stick && shownRow.current === null) takeShownRow();
holdShownRow();
}}
// Copy, plus Quote for a selection: replies to it in the composer.
onContextMenu={(e) => {
+14 -217
Переглянути файл
@@ -1,4 +1,4 @@
import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import { act, fireEvent, render, waitFor } from "@testing-library/react";
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import type { AgentEntry, AgentTask } from "@/bindings";
@@ -14,20 +14,6 @@ vi.mock("@/platform/ipc", async (original) => ({
status: "ok",
data: { uncommitted: [], commits: [] },
}),
agentRespond: async (_taskId: string, id: number, chosen: string | null) => {
const current = useAgents.getState().entries.get(task.id) ?? [];
useAgents.setState({
entries: new Map([
[
task.id,
current.map((entry) =>
entry.type === "permission" && entry.id === id ? { ...entry, chosen: chosen ?? "Cancelled" } : entry,
),
],
]),
});
return { status: "ok", data: null };
},
vcsBranchInfo: async () => ({ status: "ok", data: { head: "main" } }),
},
}));
@@ -65,58 +51,26 @@ const task: AgentTask = {
const agent = (text: string): AgentEntry => ({ type: "agent", text });
let scroller: HTMLElement | null = null;
/** Rows stack from the top of the stream: a row with a form or "tall" is 500px/300px, "compact" is 30px, any other 100px. */
const height = (row: Element) => {
if (row.querySelector("form")) return 500;
if (row.textContent?.includes("huge")) return 600;
if (row.textContent?.includes("tall")) return 300;
if (row.textContent?.includes("compact") || row.classList.contains(styles.working!)) return 30;
return 100;
};
/** Rows stack from the top of the stream: a row whose text says "tall" is 300px, any other 100px. */
const height = (row: Element) => (row.textContent?.includes("tall") ? 300 : 100);
const rowsOf = (el: HTMLElement) => [...el.querySelectorAll(`:scope > .${styles.conversationRow}`)];
const childrenOf = (el: HTMLElement) =>
[...el.children].filter(
(child) => child.classList.contains(styles.conversationRow!) || child.classList.contains(styles.working!),
);
const slackOf = (el: HTMLElement) => parseFloat(el.style.getPropertyValue("--stream-slack")) || 0;
const original = Element.prototype.getBoundingClientRect;
function attachScrollGeometry(el: HTMLElement, viewport = 400) {
scroller = el;
let top = el.scrollTop;
const totalHeight = () => childrenOf(el).reduce((sum, child) => sum + height(child), 0) + slackOf(el);
Object.defineProperty(el, "clientHeight", { value: viewport, configurable: true });
Object.defineProperty(el, "scrollHeight", {
get: totalHeight,
configurable: true,
});
Object.defineProperty(el, "scrollTop", {
get: () => Math.max(0, Math.min(top, Math.max(0, totalHeight() - viewport))),
set: (next: number) => {
top = Math.max(0, Math.min(next, Math.max(0, totalHeight() - viewport)));
},
configurable: true,
});
}
beforeEach(() => {
useAgents.setState({
loaded: true,
tasks: new Map([[task.id, task]]),
entries: new Map([
[task.id, [agent("tall one"), agent("two"), agent("three"), agent("four"), agent("five"), agent("six")]],
]),
entries: new Map([[task.id, [agent("tall one"), agent("two"), agent("three"), agent("four"), agent("five")]]]),
composers: new Map(),
scrollPositions: new Map(),
focus: null,
});
Element.prototype.getBoundingClientRect = function (this: Element) {
if (scroller && this === scroller) return new DOMRect(0, 0, 600, 400);
if (scroller && this.parentElement === scroller) {
let top = -scroller.scrollTop;
for (const child of childrenOf(scroller)) {
if (child === this) return new DOMRect(0, top, 600, height(child));
top += height(child);
for (const row of rowsOf(scroller)) {
if (row === this) return new DOMRect(0, top, 600, height(row));
top += height(row);
}
}
return original.call(this);
@@ -137,7 +91,12 @@ it("keeps the row at the top of the view in place when a row above it gets short
expect(found).toBeTruthy();
return found!;
});
attachScrollGeometry(el);
scroller = el;
Object.defineProperty(el, "clientHeight", { value: 400, configurable: true });
Object.defineProperty(el, "scrollHeight", {
get: () => rowsOf(el).reduce((sum, row) => sum + height(row), 0),
configurable: true,
});
// Scrolled up from the end: "two" is at the top of the view, 50px of it above.
fireEvent.wheel(el, { deltaY: -4 });
el.scrollTop = 350;
@@ -146,172 +105,10 @@ it("keeps the row at the top of the view in place when a row above it gets short
// The first row gets 200px shorter above the view.
act(() => {
useAgents.setState({
entries: new Map([
[task.id, [agent("one"), agent("two"), agent("three"), agent("four"), agent("five"), agent("six")]],
]),
entries: new Map([[task.id, [agent("one"), agent("two"), agent("three"), agent("four"), agent("five")]]]),
});
});
expect(el.scrollTop).toBe(150);
const two = rowsOf(el).find((row) => row.textContent?.includes("two"))!;
expect(two.getBoundingClientRect().top).toBe(-50);
});
it("lets upward scrolling consume --stream-slack without snapping scrollTop back", async () => {
useAgents.setState({
entries: new Map([[task.id, [agent("one"), agent("two"), agent("three"), agent("four"), agent("huge five")]]]),
});
const { container } = render(
<SessionEditor input={{ kind: "agent-session", key: task.id, data: { task: task.id } }} />,
);
const el = await waitFor(() => {
const found = container.querySelector<HTMLElement>(`.${styles.conversationRow}`)?.parentElement;
expect(found).toBeTruthy();
return found!;
});
attachScrollGeometry(el);
// Content is 400 + 600 = 1000px; scroll to 550 (away from the end).
el.scrollTop = 600;
fireEvent.scroll(el);
fireEvent.wheel(el, { deltaY: -50 });
el.scrollTop = 550;
fireEvent.scroll(el);
// Even a 1px upward trackpad step from the end is not swallowed as browser clamping.
el.scrollTop = 600;
fireEvent.wheel(el, { deltaY: 50 });
fireEvent.scroll(el);
fireEvent.wheel(el, { deltaY: -1 });
el.scrollTop = 599;
fireEvent.scroll(el);
expect(el.scrollTop).toBe(599);
// Scroll to 450 ("huge five" at -50px), then "huge five" shrinks from 600px to 100px below.
el.scrollTop = 450;
fireEvent.scroll(el);
act(() => {
useAgents.setState({
entries: new Map([[task.id, [agent("one"), agent("two"), agent("three"), agent("four"), agent("five")]]]),
});
});
expect(el.scrollTop).toBe(450);
expect(slackOf(el)).toBe(350);
// Scrolling back up consumes slack step by step instead of getting stuck at 450.
fireEvent.wheel(el, { deltaY: -60 });
el.scrollTop = 390;
fireEvent.scroll(el);
expect(el.scrollTop).toBe(390);
expect(slackOf(el)).toBe(290);
fireEvent.wheel(el, { deltaY: -300 });
el.scrollTop = 90;
fireEvent.scroll(el);
expect(el.scrollTop).toBe(90);
expect(slackOf(el)).toBe(0);
});
it("keeps a collapsing tall row in view instead of pushing all rows above WorkingRow", async () => {
useAgents.setState({
tasks: new Map([[task.id, { ...task, status: "running" }]]),
entries: new Map([[task.id, [agent("one"), agent("two"), agent("three"), agent("four"), agent("huge thought")]]]),
});
const { container } = render(
<SessionEditor input={{ kind: "agent-session", key: task.id, data: { task: task.id } }} />,
);
const el = await waitFor(() => {
const found = container.querySelector<HTMLElement>(`.${styles.conversationRow}`)?.parentElement;
expect(found).toBeTruthy();
return found!;
});
attachScrollGeometry(el);
// Content is 400 + 600 + 30 (WorkingRow) = 1030px. Scroll to 550 so "huge thought" starts at -150px.
el.scrollTop = 630;
fireEvent.scroll(el);
fireEvent.wheel(el, { deltaY: -80 });
el.scrollTop = 550;
fireEvent.scroll(el);
// "huge thought" (600px, top = -150px) collapses into "compact thought" (30px).
act(() => {
useAgents.setState({
entries: new Map([
[task.id, [agent("one"), agent("two"), agent("three"), agent("four"), agent("compact thought")]],
]),
});
});
const collapsed = rowsOf(el).at(-1)!;
expect(collapsed.getBoundingClientRect().bottom).toBeGreaterThan(0);
expect(collapsed.getBoundingClientRect().top).toBeGreaterThanOrEqual(0);
});
it("keeps following the end with zero slack after submitting an inline QuestionForm", async () => {
const entries: AgentEntry[] = [
agent("one"),
agent("two"),
agent("three"),
agent("four"),
{
type: "permission",
id: 1,
title: "Which visual style?",
command: null,
options: [
{ id: "submit", name: "Submit", kind: "allow_once" },
{ id: "cancel", name: "Cancel", kind: "reject_once" },
],
questions: [
{
header: "Question",
question: "Which visual style?",
multiSelect: false,
options: [
{ label: "Layered SVG (Recommended)", description: "Crisp vector layout", preview: null },
{ label: "Hand-drawn", description: "Sketchy strokes", preview: null },
],
},
],
chosen: null,
},
];
useAgents.setState({
tasks: new Map([[task.id, { ...task, status: "running" }]]),
entries: new Map([[task.id, entries]]),
});
const { container } = render(
<SessionEditor input={{ kind: "agent-session", key: task.id, data: { task: task.id } }} />,
);
const el = await waitFor(() => {
const found = container.querySelector<HTMLElement>(`.${styles.conversationRow}`)?.parentElement;
expect(found).toBeTruthy();
return found!;
});
attachScrollGeometry(el);
// At the bottom of the 400 + 500 + 30 = 930px stream (scrollTop = 530).
el.scrollTop = 530;
fireEvent.scroll(el);
const form = await screen.findByRole("form", { name: "Which visual style?" });
const radio = within(form).getByRole("radio", { name: /^Layered SVG/ });
fireEvent.pointerDown(radio);
fireEvent.click(radio);
fireEvent.pointerUp(window);
const submit = within(form).getByRole("button", { name: "Submit" });
fireEvent.pointerDown(submit);
await act(async () => {
fireEvent.click(submit);
});
fireEvent.pointerUp(window);
// Browser dispatches the clamped scroll event after the 500px form shrinks to a compact record.
fireEvent.scroll(el);
expect(slackOf(el)).toBe(0);
// Next streamed reply still follows the end automatically.
act(() => {
const current = useAgents.getState().entries.get(task.id)!;
useAgents.setState({
entries: new Map([[task.id, [...current, agent("huge follow-up reply")]]]),
});
});
expect(el.scrollTop).toBe(el.scrollHeight - el.clientHeight);
});
Loaded 100 of 218 files, more files were not shown because too many files have changed in this diff. Show more