дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-06 10:07:11 +02:00
Порівняти коміти
21
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
a9714d98ca | ||
|
|
dd8de05013 | ||
|
|
a547c8cdee | ||
|
|
a74d5b5dbb | ||
|
|
b895093f6b | ||
|
|
cbb9079577 | ||
|
|
44418411b8 | ||
|
|
5e23076766 | ||
|
|
689d3fd877 | ||
|
|
608ab44fca | ||
|
|
41545d38e5 | ||
|
|
4f86211dd6 | ||
|
|
203e4fbcb2 | ||
|
|
869e52f837 | ||
|
|
02e4c9c7a2 | ||
|
|
61be657209 | ||
|
|
52294c51c2 | ||
|
|
222d0b5ee3 | ||
|
|
cd8f29ea63 | ||
|
|
ba94abcb8b | ||
|
|
937eb0c3a0 |
No files matched your search
Створено
+1
-1
@@ -4166,7 +4166,6 @@ dependencies = [
|
||||
"ide-tools",
|
||||
"ide-vcs",
|
||||
"ide-vfs",
|
||||
"libsqlite3-sys",
|
||||
"parking_lot 0.12.5",
|
||||
"rustix",
|
||||
"semver",
|
||||
@@ -4174,6 +4173,7 @@ dependencies = [
|
||||
"serde_json",
|
||||
"sha1 0.10.7",
|
||||
"specta",
|
||||
"sqlx",
|
||||
"tempfile",
|
||||
"tokio",
|
||||
"toml 0.9.12+spec-1.1.0",
|
||||
|
||||
@@ -115,7 +115,6 @@ reqwest = { version = "0.13", default-features = false, features = ["rustls-no-p
|
||||
rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12", "logging"] }
|
||||
rustls-platform-verifier = "0.7"
|
||||
# Until SQLx releases its libsqlite3-sys 0.39 update (RUSTSEC-2026-0459).
|
||||
libsqlite3-sys = { version = "0.39", features = ["bundled"] }
|
||||
sqlx = { version = "0.9", git = "https://github.com/l0ng-ai/sqlx", rev = "9894985a1babc7e6bc0437da4fd43e3143184073", default-features = false, features = ["runtime-tokio", "tls-rustls-ring-webpki", "sqlite", "postgres", "mysql"] }
|
||||
tiberius = { version = "0.13", default-features = false, features = ["tds73", "rustls", "sql-browser-tokio"] }
|
||||
# Pure-Rust thin Oracle driver; pinned to the beta until it stabilizes.
|
||||
|
||||
+1
-1
@@ -71,7 +71,7 @@ the [official plugins](plugins/official). The plugin API is still a preview.
|
||||
|
||||
## Community
|
||||
|
||||
- [Discord](https://discord.gg/2Zy4yn7gP) — questions, feedback and release news.
|
||||
- [Discord](https://discord.gg/AsZqMgxZm) — questions, feedback and release news.
|
||||
- WeChat group — scan to join:
|
||||
|
||||
<img src=".github/assets/wechat-group-4.png" alt="WeChat group QR code" width="200">
|
||||
|
||||
+1
-1
@@ -71,7 +71,7 @@ Eklentileri Ayarlar › Eklentiler (Settings › Plugins) bölümünden kur ya d
|
||||
|
||||
## Topluluk
|
||||
|
||||
- [Discord](https://discord.gg/2Zy4yn7gP): sorular, geri bildirim ve sürüm haberleri.
|
||||
- [Discord](https://discord.gg/AsZqMgxZm): sorular, geri bildirim ve sürüm haberleri.
|
||||
- WeChat grubu, katılmak için kodu okut:
|
||||
|
||||
<img src=".github/assets/wechat-group-4.png" alt="WeChat grubu QR kodu" width="200">
|
||||
|
||||
@@ -69,7 +69,7 @@ WebAssembly 组件运行;主题、图标主题和语言无需编写代码。
|
||||
|
||||
## 社区
|
||||
|
||||
- [Discord](https://discord.gg/2Zy4yn7gP):提问、反馈和版本发布消息。
|
||||
- [Discord](https://discord.gg/AsZqMgxZm):提问、反馈和版本发布消息。
|
||||
- 微信群,扫码加入:
|
||||
|
||||
<img src=".github/assets/wechat-group-4.png" alt="微信群二维码" width="200">
|
||||
|
||||
@@ -15,10 +15,10 @@ ide-mcp.workspace = true
|
||||
ide-jsonrpc.workspace = true
|
||||
ide-vcs.workspace = true
|
||||
ide-tools = { path = "../ide-tools" }
|
||||
libsqlite3-sys.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
specta.workspace = true
|
||||
sqlx.workspace = true
|
||||
tokio.workspace = true
|
||||
toml.workspace = true
|
||||
tracing.workspace = true
|
||||
|
||||
@@ -27,6 +27,9 @@ pub struct ExternalSession {
|
||||
pub cwd: Option<String>,
|
||||
/// File modification time, ms since the epoch.
|
||||
pub updated_ms: f64,
|
||||
/// Another live process (VS Code, a terminal Copilot CLI) has it open: importing would let two
|
||||
/// apps write the same session, so forking a copy is the safe choice.
|
||||
pub in_use: bool,
|
||||
}
|
||||
|
||||
/// Modification time of `path` in ms, else 0.
|
||||
@@ -124,6 +127,7 @@ pub fn claude_sessions(config_dir: &Path, root: &Path) -> Vec<ExternalSession> {
|
||||
title,
|
||||
cwd,
|
||||
updated_ms: mtime(&path),
|
||||
in_use: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -194,6 +198,7 @@ fn codex_file(path: &Path) -> Option<ExternalSession> {
|
||||
session_id,
|
||||
cwd,
|
||||
updated_ms: mtime(path),
|
||||
in_use: false,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -332,80 +337,6 @@ fn copilot_prompt(path: &Path) -> Option<String> {
|
||||
})
|
||||
}
|
||||
|
||||
struct SqliteDb(*mut libsqlite3_sys::sqlite3);
|
||||
|
||||
impl SqliteDb {
|
||||
fn open_readonly(path: &Path) -> Option<Self> {
|
||||
if !path.is_file() {
|
||||
return None;
|
||||
}
|
||||
let c_path = std::ffi::CString::new(path.to_str()?).ok()?;
|
||||
let mut raw: *mut libsqlite3_sys::sqlite3 = std::ptr::null_mut();
|
||||
let flags = libsqlite3_sys::SQLITE_OPEN_READONLY | libsqlite3_sys::SQLITE_OPEN_NOMUTEX;
|
||||
let rc = unsafe { libsqlite3_sys::sqlite3_open_v2(c_path.as_ptr(), &mut raw, flags, std::ptr::null()) };
|
||||
let guard = Self(raw);
|
||||
if rc != libsqlite3_sys::SQLITE_OK || raw.is_null() {
|
||||
return None;
|
||||
}
|
||||
unsafe {
|
||||
libsqlite3_sys::sqlite3_busy_timeout(raw, 200);
|
||||
}
|
||||
Some(guard)
|
||||
}
|
||||
|
||||
fn prepare(&self, sql: &str) -> Option<SqliteStmt> {
|
||||
let c_sql = std::ffi::CString::new(sql).ok()?;
|
||||
let mut stmt: *mut libsqlite3_sys::sqlite3_stmt = std::ptr::null_mut();
|
||||
let rc =
|
||||
unsafe { libsqlite3_sys::sqlite3_prepare_v2(self.0, c_sql.as_ptr(), -1, &mut stmt, std::ptr::null_mut()) };
|
||||
let guard = SqliteStmt(stmt);
|
||||
(rc == libsqlite3_sys::SQLITE_OK && !stmt.is_null()).then_some(guard)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for SqliteDb {
|
||||
fn drop(&mut self) {
|
||||
if !self.0.is_null() {
|
||||
unsafe {
|
||||
libsqlite3_sys::sqlite3_close(self.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct SqliteStmt(*mut libsqlite3_sys::sqlite3_stmt);
|
||||
|
||||
impl SqliteStmt {
|
||||
fn step(&self) -> bool {
|
||||
unsafe { libsqlite3_sys::sqlite3_step(self.0) == libsqlite3_sys::SQLITE_ROW }
|
||||
}
|
||||
|
||||
fn text(&self, col: std::ffi::c_int) -> Option<String> {
|
||||
unsafe {
|
||||
let ptr = libsqlite3_sys::sqlite3_column_text(self.0, col);
|
||||
if ptr.is_null() {
|
||||
return None;
|
||||
}
|
||||
let len = libsqlite3_sys::sqlite3_column_bytes(self.0, col);
|
||||
if len <= 0 {
|
||||
return None;
|
||||
}
|
||||
let bytes = std::slice::from_raw_parts(ptr, len as usize);
|
||||
std::str::from_utf8(bytes).ok().map(str::to_owned)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for SqliteStmt {
|
||||
fn drop(&mut self) {
|
||||
if !self.0.is_null() {
|
||||
unsafe {
|
||||
libsqlite3_sys::sqlite3_finalize(self.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Candidate VS Code Agent Host SQLite databases (`<user>/globalStorage/agent-host.db`),
|
||||
/// ordered oldest-first so a newer database wins when two editions share a session.
|
||||
fn vscode_agent_host_dbs(home: &Path) -> Vec<PathBuf> {
|
||||
@@ -462,9 +393,11 @@ fn pick_vscode_chat_title(
|
||||
None
|
||||
}
|
||||
|
||||
/// Session titles VS Code's Agent Host (`vscode-agent-host`) assigns to backing Copilot CLI
|
||||
/// sessions (`sdkSessionId` → summary or user rename), read from `agent-host.db` without writing.
|
||||
fn vscode_copilot_titles(home: Option<&Path>) -> HashMap<String, String> {
|
||||
/// 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 \
|
||||
@@ -474,40 +407,85 @@ fn vscode_copilot_titles(home: Option<&Path>) -> HashMap<String, String> {
|
||||
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";
|
||||
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 path in vscode_agent_host_dbs(home) {
|
||||
let Some(db) = SqliteDb::open_readonly(&path) else { continue };
|
||||
let Some(stmt) = db.prepare(FULL_QUERY).or_else(|| db.prepare(FALLBACK_QUERY)) else { continue };
|
||||
while stmt.step() {
|
||||
let Some(pdata) = stmt.text(0) else { continue };
|
||||
let Ok(pv) = serde_json::from_str::<serde_json::Value>(&pdata) else { continue };
|
||||
let Some(sdk_id) = pv.get("sdkSessionId").and_then(serde_json::Value::as_str).filter(|s| !s.is_empty())
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let scs_title = stmt.text(1);
|
||||
let scs_source = stmt.text(2);
|
||||
let metadata = stmt.text(3);
|
||||
let payload = stmt.text(4);
|
||||
if let Some(title) = pick_vscode_chat_title(
|
||||
scs_title.as_deref(),
|
||||
scs_source.as_deref(),
|
||||
metadata.as_deref(),
|
||||
payload.as_deref(),
|
||||
) {
|
||||
titles.insert(sdk_id.to_owned(), title);
|
||||
}
|
||||
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.
|
||||
@@ -535,10 +513,15 @@ pub fn copilot_sessions(copilot_home: &Path, home: Option<&Path>, root: &Path) -
|
||||
.map(short)
|
||||
.or_else(|| copilot_prompt(&events))
|
||||
.unwrap_or_else(|| format!("Copilot session {}", &session_id[..session_id.len().min(8)]));
|
||||
Some((
|
||||
ExternalSession { provider: "copilot".to_owned(), session_id, title, cwd, updated_ms: mtime(&events) },
|
||||
cli_user_named,
|
||||
))
|
||||
let session = ExternalSession {
|
||||
provider: "copilot".to_owned(),
|
||||
session_id,
|
||||
title,
|
||||
cwd,
|
||||
updated_ms: mtime(&events),
|
||||
in_use: copilot_session_in_use(&dir),
|
||||
};
|
||||
Some((session, cli_user_named))
|
||||
})
|
||||
.collect();
|
||||
if !pending.is_empty() {
|
||||
@@ -653,27 +636,16 @@ mod tests {
|
||||
assert!(copilot_sessions(&tmp.path().join("nope"), None, Path::new("/work")).is_empty());
|
||||
}
|
||||
|
||||
fn exec_sqlite(path: &Path, sql: &str) {
|
||||
fn exec_sqlite(path: &Path, sql: &'static str) {
|
||||
use sqlx::Connection;
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
let c_path = std::ffi::CString::new(path.to_str().unwrap()).unwrap();
|
||||
let c_sql = std::ffi::CString::new(sql).unwrap();
|
||||
unsafe {
|
||||
let mut db: *mut libsqlite3_sys::sqlite3 = std::ptr::null_mut();
|
||||
assert_eq!(
|
||||
libsqlite3_sys::sqlite3_open_v2(
|
||||
c_path.as_ptr(),
|
||||
&mut db,
|
||||
libsqlite3_sys::SQLITE_OPEN_READWRITE | libsqlite3_sys::SQLITE_OPEN_CREATE,
|
||||
std::ptr::null(),
|
||||
),
|
||||
libsqlite3_sys::SQLITE_OK
|
||||
);
|
||||
assert_eq!(
|
||||
libsqlite3_sys::sqlite3_exec(db, c_sql.as_ptr(), None, std::ptr::null_mut(), std::ptr::null_mut()),
|
||||
libsqlite3_sys::SQLITE_OK
|
||||
);
|
||||
libsqlite3_sys::sqlite3_close(db);
|
||||
}
|
||||
let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
|
||||
rt.block_on(async {
|
||||
let options = sqlx::sqlite::SqliteConnectOptions::new().filename(path).create_if_missing(true);
|
||||
let mut conn = sqlx::SqliteConnection::connect_with(&options).await.unwrap();
|
||||
sqlx::raw_sql(sql).execute(&mut conn).await.unwrap();
|
||||
conn.close().await.unwrap();
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -727,6 +699,9 @@ mod tests {
|
||||
&[json!({"type": "user.message", "data": {"content": "add a regression test"}})],
|
||||
);
|
||||
std::fs::write(unnamed.join("workspace.yaml"), "id: copilot-2\ncwd: /work/app\n").unwrap();
|
||||
// A live holder marks the session in use; a lock left by a process that exited does not.
|
||||
std::fs::write(session.join(format!("inuse.{}.lock", std::process::id())), "").unwrap();
|
||||
std::fs::write(unnamed.join("inuse.2147483646.lock"), "").unwrap();
|
||||
|
||||
let empty = copilot_home.join("session-state/copilot-empty");
|
||||
std::fs::create_dir_all(&empty).unwrap();
|
||||
@@ -756,10 +731,13 @@ mod tests {
|
||||
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");
|
||||
assert_eq!(by_id.remove("copilot-2").unwrap().title, "add a regression test");
|
||||
let unnamed = by_id.remove("copilot-2").unwrap();
|
||||
assert_eq!(unnamed.title, "add a regression test");
|
||||
assert!(!unnamed.in_use);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -616,6 +616,8 @@ pub struct TerminalSettings {
|
||||
pub close_on_exit: bool,
|
||||
pub mouse_reporting: bool,
|
||||
pub copy_on_selection: bool,
|
||||
/// Programs may set the clipboard with OSC 52 (tmux, Neovim, TUIs over SSH); never read it.
|
||||
pub osc52_clipboard: bool,
|
||||
pub paste_on_middle_click: bool,
|
||||
/// Right-click pastes instead of opening the context menu (Ctrl or Shift + right-click still opens it).
|
||||
pub right_click_paste: bool,
|
||||
@@ -656,6 +658,7 @@ impl Default for TerminalSettings {
|
||||
close_on_exit: true,
|
||||
mouse_reporting: true,
|
||||
copy_on_selection: false,
|
||||
osc52_clipboard: true,
|
||||
paste_on_middle_click: true,
|
||||
right_click_paste: false,
|
||||
override_ide_shortcuts: true,
|
||||
|
||||
@@ -103,6 +103,7 @@ fn convert(config: &mut LaunchConfig, to: &str) -> IdeResult<()> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::collections::BTreeMap;
|
||||
#[cfg(unix)]
|
||||
use std::path::Path;
|
||||
|
||||
fn cmake_launch() -> LaunchConfig {
|
||||
|
||||
+105
-47
@@ -447,6 +447,15 @@ fn read_table_properties(details: &mut TableDetails, row: Vec<Option<String>>) {
|
||||
);
|
||||
details.partitioning = next();
|
||||
details.persistence = next().as_deref().and_then(DbPersistence::from_catalog);
|
||||
// PostgreSQL's `table_properties` carries the comment as its last column, so reading it here
|
||||
// saves the separate query `table_comment` would make on the same `pg_class` row.
|
||||
if let Some(comment) = next() {
|
||||
// `table_comment` this replaces yielded `NULL` or empty for no comment, so an empty
|
||||
// comment must not become `Some("")` — the DDL would emit an empty `COMMENT ON`.
|
||||
if !comment.is_empty() {
|
||||
details.comment = Some(comment);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn flag(v: &Option<String>) -> bool {
|
||||
@@ -1384,8 +1393,61 @@ impl DbManager {
|
||||
if driver == DbDriver::Jdbc {
|
||||
return Ok(TableDetails { columns, ..Default::default() });
|
||||
}
|
||||
// Everything below describes the same table and none of it feeds the next, so it goes
|
||||
// out together. Serialised, this is four round trips on the path that opens a table
|
||||
// (`table_page_on` calls this for the primary key), which is what makes opening a table
|
||||
// feel slow on a remote server. Five queries against a pool of four (`conn.rs`'s `MAX`),
|
||||
// so one waits — still one round trip rather than five.
|
||||
type Rows = Vec<Vec<Option<String>>>;
|
||||
let keys = !matches!(driver, DbDriver::Clickhouse | DbDriver::Snowflake);
|
||||
let (index_q, fk_q, trigger_q) = (
|
||||
sql::indexes(driver, schema, table),
|
||||
sql::table_foreign_keys(driver, schema, table),
|
||||
sql::triggers(driver, schema, table),
|
||||
);
|
||||
let (index_rows, fk_rows, trigger_rows, comment_rows, property_rows) = futures::join!(
|
||||
pool.rows(&index_q, MAX_META_ROWS),
|
||||
async {
|
||||
if !keys {
|
||||
return Ok::<Rows, IdeError>(Vec::new());
|
||||
}
|
||||
match pool.rows(&fk_q, MAX_META_ROWS).await {
|
||||
Ok(rows) => Ok(rows),
|
||||
Err(e) => {
|
||||
tracing::warn!("foreign keys: {}", e.message);
|
||||
Ok(Vec::new())
|
||||
}
|
||||
}
|
||||
},
|
||||
async {
|
||||
if !keys {
|
||||
return Ok::<Rows, IdeError>(Vec::new());
|
||||
}
|
||||
match pool.rows(&trigger_q, MAX_META_ROWS).await {
|
||||
Ok(rows) => Ok(rows),
|
||||
Err(e) => {
|
||||
tracing::warn!("triggers: {}", e.message);
|
||||
Ok(Vec::new())
|
||||
}
|
||||
}
|
||||
},
|
||||
async {
|
||||
// PostgreSQL reads it with the properties above; the engines without a
|
||||
// `table_properties` query ask for it here.
|
||||
match sql::table_comment(driver, schema, table) {
|
||||
Some(q) if sql::table_properties(driver, schema, table).is_none() => pool.rows(&q, 1).await,
|
||||
_ => Ok::<Rows, IdeError>(Vec::new()),
|
||||
}
|
||||
},
|
||||
async {
|
||||
match sql::table_properties(driver, schema, table) {
|
||||
Some(q) => catalog_rows(pool, &q).await,
|
||||
None => Ok::<Rows, IdeError>(Vec::new()),
|
||||
}
|
||||
},
|
||||
);
|
||||
let mut indexes: Vec<IndexInfo> = Vec::new();
|
||||
for r in pool.rows(&sql::indexes(driver, schema, table), MAX_META_ROWS).await? {
|
||||
for r in index_rows? {
|
||||
let mut it = r.into_iter();
|
||||
let (Some(name), unique, Some(col)) = (it.next().flatten(), it.next().flatten(), it.next().flatten())
|
||||
else {
|
||||
@@ -1401,11 +1463,7 @@ impl DbManager {
|
||||
}),
|
||||
}
|
||||
}
|
||||
let fk_rows = if matches!(driver, DbDriver::Clickhouse | DbDriver::Snowflake) {
|
||||
Vec::new()
|
||||
} else {
|
||||
pool.rows(&sql::table_foreign_keys(driver, schema, table), MAX_META_ROWS).await.unwrap_or_default()
|
||||
};
|
||||
let fk_rows = fk_rows?;
|
||||
let mut foreign_keys = group_foreign_keys(fk_rows, &[]);
|
||||
// SQLite keys that reference the primary key implicitly: look it up.
|
||||
for k in foreign_keys.iter_mut().filter(|k| k.ref_columns.is_empty()) {
|
||||
@@ -1418,15 +1476,7 @@ impl DbManager {
|
||||
.collect();
|
||||
}
|
||||
foreign_keys.retain(|k| k.columns.len() == k.ref_columns.len());
|
||||
let trigger_rows = if matches!(driver, DbDriver::Clickhouse | DbDriver::Snowflake) {
|
||||
Vec::new()
|
||||
} else {
|
||||
pool.rows(&sql::triggers(driver, schema, table), MAX_META_ROWS).await.unwrap_or_else(|e| {
|
||||
tracing::warn!("triggers: {}", e.message);
|
||||
Vec::new()
|
||||
})
|
||||
};
|
||||
let triggers = trigger_rows
|
||||
let triggers = trigger_rows?
|
||||
.into_iter()
|
||||
.filter_map(|r| {
|
||||
let mut it = r.into_iter();
|
||||
@@ -1439,26 +1489,21 @@ impl DbManager {
|
||||
Some(TriggerInfo { name, timing, events })
|
||||
})
|
||||
.collect();
|
||||
let comment = match sql::table_comment(driver, schema, table) {
|
||||
Some(q) => pool.rows(&q, 1).await.map_or_else(
|
||||
|e| {
|
||||
tracing::warn!("table comment: {}", e.message);
|
||||
None
|
||||
},
|
||||
|rows| rows.into_iter().next().and_then(|r| r.into_iter().next().flatten()).filter(|c| !c.is_empty()),
|
||||
),
|
||||
None => None,
|
||||
};
|
||||
let comment = comment_rows.map_or_else(
|
||||
|e| {
|
||||
tracing::warn!("table comment: {}", e.message);
|
||||
None
|
||||
},
|
||||
|rows| rows.into_iter().next().and_then(|r| r.into_iter().next().flatten()).filter(|c| !c.is_empty()),
|
||||
);
|
||||
let mut details = TableDetails { comment, columns, indexes, foreign_keys, triggers, ..Default::default() };
|
||||
if let Some(q) = sql::table_properties(driver, schema, table) {
|
||||
match catalog_rows(pool, &q).await {
|
||||
Ok(rows) => {
|
||||
if let Some(row) = rows.into_iter().next() {
|
||||
read_table_properties(&mut details, row);
|
||||
}
|
||||
match property_rows {
|
||||
Ok(rows) => {
|
||||
if let Some(row) = rows.into_iter().next() {
|
||||
read_table_properties(&mut details, row);
|
||||
}
|
||||
Err(e) => tracing::warn!("table properties: {}", e.message),
|
||||
}
|
||||
Err(e) => tracing::warn!("table properties: {}", e.message),
|
||||
}
|
||||
Ok(details)
|
||||
}
|
||||
@@ -1669,9 +1714,12 @@ impl DbManager {
|
||||
ddl.map(|d| format!("{};\n", d.trim_end().trim_end_matches(';'))).ok_or_else(missing)
|
||||
}
|
||||
DbDriver::Postgres => {
|
||||
// Everything the script needs depends on the relation oid, so read that first and
|
||||
// then the rest at once — five queries in flight against a pool of four, so one
|
||||
// waits, but that is still two round trips instead of six.
|
||||
let rel = pool.rows(&sql::postgres_relation(schema, name), 1).await?.into_iter().next();
|
||||
let (oid, kind, owner, comment) = match rel.as_deref() {
|
||||
Some([Some(oid), Some(kind), owner, comment]) => (
|
||||
Some([Some(oid), Some(kind), owner, comment, ..]) => (
|
||||
oid.parse::<u32>().map_err(|e| IdeError::invalid(e.to_string()))?,
|
||||
kind.clone(),
|
||||
owner.clone(),
|
||||
@@ -1686,41 +1734,51 @@ impl DbManager {
|
||||
let target = sql::qualified(driver, schema, name);
|
||||
return Ok(format!("create {what} {target} as\n{};\n", body.trim_end().trim_end_matches(';')));
|
||||
}
|
||||
let columns = pool
|
||||
.rows(&sql::postgres_ddl_columns(oid), MAX_META_ROWS)
|
||||
.await?
|
||||
let (cols_q, keys_q, grants_q, index_q, trigger_q) = (
|
||||
sql::postgres_ddl_columns(oid),
|
||||
sql::postgres_ddl_constraints(oid),
|
||||
sql::postgres_ddl_grants(oid),
|
||||
sql::postgres_ddl_indexes(oid),
|
||||
sql::postgres_ddl_triggers(oid),
|
||||
);
|
||||
let (col_rows, key_rows, grant_rows, index_rows, trigger_rows) = futures::join!(
|
||||
pool.rows(&cols_q, MAX_META_ROWS),
|
||||
pool.rows(&keys_q, MAX_META_ROWS),
|
||||
pool.rows(&grants_q, MAX_META_ROWS),
|
||||
pool.rows(&index_q, MAX_META_ROWS),
|
||||
pool.rows(&trigger_q, MAX_META_ROWS),
|
||||
);
|
||||
let columns = col_rows?
|
||||
.into_iter()
|
||||
.filter_map(|r| {
|
||||
let mut it = r.into_iter();
|
||||
Some(sql::DdlColumn {
|
||||
name: it.next().flatten()?,
|
||||
data_type: it.next().flatten().unwrap_or_default(),
|
||||
data_type: it.next().flatten()?,
|
||||
not_null: flag(&it.next().flatten()),
|
||||
default: it.next().flatten(),
|
||||
comment: it.next().flatten(),
|
||||
comment: it.next().flatten().filter(|c| !c.is_empty()),
|
||||
})
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let constraints = pool
|
||||
.rows(&sql::postgres_ddl_constraints(oid), MAX_META_ROWS)
|
||||
.await?
|
||||
let constraints = key_rows?
|
||||
.into_iter()
|
||||
.filter_map(|r| {
|
||||
let mut it = r.into_iter();
|
||||
Some((it.next().flatten()?, it.next().flatten()?))
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let indexes = cells(pool.rows(&sql::postgres_ddl_indexes(oid), MAX_META_ROWS).await?, 0);
|
||||
let grants = pool
|
||||
.rows(&sql::postgres_ddl_grants(oid), MAX_META_ROWS)
|
||||
.await?
|
||||
let indexes =
|
||||
index_rows?.into_iter().filter_map(|r| r.into_iter().next().flatten()).collect::<Vec<_>>();
|
||||
let grants = grant_rows?
|
||||
.into_iter()
|
||||
.filter_map(|r| {
|
||||
let mut it = r.into_iter();
|
||||
Some((it.next().flatten()?, it.next().flatten()?, flag(&it.next().flatten())))
|
||||
})
|
||||
.collect();
|
||||
let triggers = cells(pool.rows(&sql::postgres_ddl_triggers(oid), MAX_META_ROWS).await?, 0);
|
||||
.collect::<Vec<_>>();
|
||||
let triggers =
|
||||
trigger_rows?.into_iter().filter_map(|r| r.into_iter().next().flatten()).collect::<Vec<_>>();
|
||||
let extras = sql::DdlExtras { comment, owner, grants, triggers };
|
||||
Ok(sql::postgres_table_ddl(schema, name, &columns, &constraints, &indexes, &extras))
|
||||
}
|
||||
|
||||
@@ -249,7 +249,7 @@ pub fn table_properties(driver: DbDriver, schema: &str, table: &str) -> Option<S
|
||||
JOIN pg_tablespace dt ON dt.oid = d.dattablespace WHERE d.datname = current_database())), \
|
||||
am.amname, array_to_string(array_cat(c.reloptions, \
|
||||
(SELECT array_agg('toast.' || o) FROM unnest(tc.reloptions) o)), chr(10)), \
|
||||
pg_get_partkeydef(c.oid), c.relpersistence \
|
||||
pg_get_partkeydef(c.oid), c.relpersistence, obj_description(c.oid, 'pg_class') \
|
||||
FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace \
|
||||
LEFT JOIN pg_class tc ON tc.oid = c.reltoastrelid \
|
||||
LEFT JOIN pg_tablespace ts ON ts.oid = c.reltablespace LEFT JOIN pg_am am ON am.oid = c.relam \
|
||||
@@ -709,6 +709,11 @@ pub fn postgres_relation(schema: &str, name: &str) -> String {
|
||||
}
|
||||
|
||||
/// Rows: `name, type, not null (0/1), default, comment` of relation `oid`.
|
||||
///
|
||||
/// Read from `pg_attribute` with `format_type` rather than from `information_schema.columns`:
|
||||
/// that view reports `character varying` without the length, `numeric` without the precision,
|
||||
/// `ARRAY` for every array and `USER-DEFINED` for an enum, so a script built from it would not
|
||||
/// recreate the table. It also lists only the columns the current role holds privileges on.
|
||||
pub fn postgres_ddl_columns(oid: u32) -> String {
|
||||
format!(
|
||||
"SELECT a.attname, format_type(a.atttypid, a.atttypmod), CASE WHEN a.attnotnull THEN 1 ELSE 0 END, \
|
||||
@@ -1416,6 +1421,22 @@ mod tests {
|
||||
assert_eq!(use_schema(DbDriver::Clickhouse, "default"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn postgres_ddl_columns_reads_pg_attribute_not_information_schema() {
|
||||
// `information_schema.columns.data_type` loses what a script needs to recreate the table:
|
||||
// `character varying` without the length, `numeric` without the precision, `ARRAY` for
|
||||
// every array and `USER-DEFINED` for an enum. It also lists only the columns the current
|
||||
// role holds privileges on. The DDL must therefore read `pg_attribute` with
|
||||
// `format_type(atttypid, atttypmod)`, which is what makes `varchar(255)`, `numeric(10,2)`,
|
||||
// `text[]` and an enum name come out as written.
|
||||
let q = postgres_ddl_columns(42);
|
||||
assert!(q.contains("format_type(a.atttypid, a.atttypmod)"), "{q}");
|
||||
assert!(q.contains("FROM pg_attribute a"), "{q}");
|
||||
assert!(q.contains("left join pg_attrdef") || q.contains("LEFT JOIN pg_attrdef"), "{q}");
|
||||
assert!(q.contains("attrelid = 42"), "{q}");
|
||||
assert!(!q.contains("information_schema"), "{q}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn postgres_ddl() {
|
||||
let cols = [
|
||||
|
||||
@@ -1,19 +1,34 @@
|
||||
use crate::project::Project;
|
||||
use ide_core::IdeResult;
|
||||
use ide_dap::LaunchConfig;
|
||||
use ide_workspace::roots::RootKind;
|
||||
use std::collections::BTreeMap;
|
||||
use ide_workspace::roots::{RootKind, SourceFolder};
|
||||
use std::collections::{BTreeMap, HashSet};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// The project's import roots, put on `PYTHONPATH` by runs, debug sessions and consoles.
|
||||
pub(super) fn paths(project: &Project) -> Vec<PathBuf> {
|
||||
let mut paths = vec![project.root.clone()];
|
||||
paths.extend(project.content_roots());
|
||||
for root in project.roots().roots {
|
||||
if matches!(root.kind, RootKind::Source | RootKind::Test) {
|
||||
let path = project.root.join(root.path);
|
||||
if !paths.contains(&path) {
|
||||
paths.push(path);
|
||||
}
|
||||
import_roots(&project.root, project.content_roots(), &project.roots().roots)
|
||||
}
|
||||
|
||||
/// `root`, the content roots, then the Source and Test roots. A detected root that is itself a
|
||||
/// package (it holds `__init__.py`, like an Odoo addon or its `tests` folder) is left out:
|
||||
/// importing from it would give its modules a second top-level name, and a project with
|
||||
/// thousands of them made `PYTHONPATH` longer than a process environment can hold (#7083).
|
||||
/// Folders the user marked always count.
|
||||
fn import_roots(root: &Path, content_roots: Vec<PathBuf>, roots: &[SourceFolder]) -> Vec<PathBuf> {
|
||||
let mut paths = vec![root.to_path_buf()];
|
||||
paths.extend(content_roots);
|
||||
let mut seen: HashSet<PathBuf> = paths.iter().cloned().collect();
|
||||
for folder in roots {
|
||||
if !matches!(folder.kind, RootKind::Source | RootKind::Test) {
|
||||
continue;
|
||||
}
|
||||
let path = root.join(&folder.path);
|
||||
if folder.detected_from.is_some() && path.join("__init__.py").is_file() {
|
||||
continue;
|
||||
}
|
||||
if seen.insert(path.clone()) {
|
||||
paths.push(path);
|
||||
}
|
||||
}
|
||||
paths
|
||||
@@ -120,6 +135,38 @@ pub(super) fn prepare_debug(
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn detected_package_folders_are_not_import_roots() {
|
||||
use ide_workspace::roots::{RootKind, SourceFolder};
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
for file in ["src/pkg/__init__.py", "addon/__init__.py", "addon/tests/__init__.py", "marked/__init__.py"] {
|
||||
let path = root.join(file);
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
std::fs::write(path, "").unwrap();
|
||||
}
|
||||
std::fs::create_dir_all(root.join("tests")).unwrap();
|
||||
let folder = |path: &str, kind, detected: bool| SourceFolder {
|
||||
path: path.into(),
|
||||
kind,
|
||||
detected_from: detected.then(|| "pyproject.toml".into()),
|
||||
};
|
||||
let roots = [
|
||||
folder("src", RootKind::Source, true),
|
||||
folder("tests", RootKind::Test, true),
|
||||
folder("addon", RootKind::Source, true),
|
||||
folder("addon/tests", RootKind::Test, true),
|
||||
folder("marked", RootKind::Source, false),
|
||||
folder("build", RootKind::Excluded, true),
|
||||
folder("src", RootKind::Source, true),
|
||||
];
|
||||
assert_eq!(
|
||||
super::import_roots(root, vec![], &roots),
|
||||
[root.to_path_buf(), root.join("src"), root.join("tests"), root.join("marked")],
|
||||
"detected packages are left out, a folder the user marked stays, no duplicates"
|
||||
);
|
||||
}
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -727,6 +727,21 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn java_analyzer_does_not_fill_empty_files() {
|
||||
let reg = reg();
|
||||
let java = reg.get(&LanguageId::new("java")).unwrap();
|
||||
let analyzer = java.language_servers.iter().find(|s| s.name == "java-analyzer").unwrap();
|
||||
assert_eq!(
|
||||
analyzer
|
||||
.initialization_options
|
||||
.as_ref()
|
||||
.and_then(|v| v.get("newFileTemplate"))
|
||||
.and_then(toml::Value::as_bool),
|
||||
Some(false)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn angular_server_joins_typescript_and_html_in_angular_projects() {
|
||||
let reg = reg();
|
||||
|
||||
@@ -503,12 +503,30 @@ impl LaunchScope {
|
||||
}
|
||||
}
|
||||
|
||||
/// m2e can run package-phase mojos such as `dependency:copy-dependencies` during
|
||||
/// `java/buildWorkspace`. In an incremental IDE build the reactor jars are not
|
||||
/// packaged, so the plugin fails with MDEP-187 (copy) or MDEP-98 (unpack). That is
|
||||
/// not a Java compile error, and a main-class launch does not need the copied jars.
|
||||
/// Debug uses this workspace build (so java-debug can HotSwap the classes jdtls
|
||||
/// compiled); Run uses the IDE's Java build and never hits the mojo. Ignoring the
|
||||
/// marker keeps the two consistent when the Java sources compiled.
|
||||
fn is_reactor_packaging_mojo_error(message: &str) -> bool {
|
||||
let lower = message.to_ascii_lowercase();
|
||||
lower.contains("has not been packaged yet") && lower.contains("executed after packaging")
|
||||
}
|
||||
|
||||
/// JDTLS reports all imported projects; report errors for the launch and its dependencies.
|
||||
fn launch_compile_errors(
|
||||
scope: &LaunchScope,
|
||||
diagnostics: Vec<(PathBuf, lsp_types::Diagnostic)>,
|
||||
) -> (Vec<JavaCompileError>, u32) {
|
||||
compile_errors(diagnostics.into_iter().filter(|(path, _)| scope.includes(path)).collect(), MAX_LAUNCH_ERRORS)
|
||||
compile_errors(
|
||||
diagnostics
|
||||
.into_iter()
|
||||
.filter(|(path, d)| scope.includes(path) && !is_reactor_packaging_mojo_error(&d.message))
|
||||
.collect(),
|
||||
MAX_LAUNCH_ERRORS,
|
||||
)
|
||||
}
|
||||
|
||||
/// `java.project.getClasspaths` result.
|
||||
@@ -1759,6 +1777,43 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn debug_launch_ignores_mdep_reactor_packaging_errors() {
|
||||
let cp = JavaClasspath {
|
||||
class_paths: vec!["/p/app/target/classes".into(), "/p/library/target/classes".into()],
|
||||
..Default::default()
|
||||
};
|
||||
let scope = LaunchScope::new(Path::new("/p/app"), false, Some(&cp));
|
||||
let diagnostic = |message: &str| lsp_types::Diagnostic {
|
||||
severity: Some(lsp_types::DiagnosticSeverity::ERROR),
|
||||
message: message.into(),
|
||||
range: lsp_types::Range::new(lsp_types::Position::new(299, 21), lsp_types::Position::new(299, 31)),
|
||||
..Default::default()
|
||||
};
|
||||
// m2e's BuildProblemInfo: the CoreException message, then the execution key,
|
||||
// then the stack whose cause is the plugin's MDEP-187 / MDEP-98 text.
|
||||
let copy = "Failed to execute mojo org.apache.maven.plugins:maven-dependency-plugin:3.6.1:copy-dependencies {execution: copy-dependencies} (org.apache.maven.plugins:maven-dependency-plugin:3.6.1:copy-dependencies:copy-dependencies:package)\n\norg.eclipse.core.runtime.CoreException: Failed to execute mojo org.apache.maven.plugins:maven-dependency-plugin:3.6.1:copy-dependencies {execution: copy-dependencies}\n\t at org.eclipse.m2e.core.project.configurator.MojoExecutionBuildParticipant.build(MojoExecutionBuildParticipant.java:57)\nCaused by: org.apache.maven.plugin.MojoExecutionException:\nArtifact has not been packaged yet. When used on reactor artifact, copy should be executed after packaging: see MDEP-187.";
|
||||
let unpack = "Failed to execute mojo org.apache.maven.plugins:maven-dependency-plugin:3.6.1:unpack-dependencies {execution: unpack-dependencies}\nCaused by: org.apache.maven.plugin.MojoExecutionException: Artifact has not been packaged yet. When used on reactor artifact, unpack should be executed after packaging: see MDEP-98.";
|
||||
let other_mojo = "Failed to execute mojo org.apache.maven.plugins:maven-compiler-plugin:3.13.0:compile {execution: default-compile}";
|
||||
let (errors, count) = launch_compile_errors(
|
||||
&scope,
|
||||
vec![
|
||||
(PathBuf::from("/p/app/pom.xml"), diagnostic(copy)),
|
||||
(PathBuf::from("/p/app/pom.xml"), diagnostic(unpack)),
|
||||
(PathBuf::from("/p/app/src/main/java/App.java"), diagnostic("App cannot be resolved to a type")),
|
||||
(PathBuf::from("/p/app/pom.xml"), diagnostic(other_mojo)),
|
||||
],
|
||||
);
|
||||
assert_eq!(count, 2);
|
||||
assert_eq!(&*errors[0].path, Path::new("/p/app/pom.xml"));
|
||||
assert_eq!(errors[0].message, other_mojo);
|
||||
assert_eq!(&*errors[1].path, Path::new("/p/app/src/main/java/App.java"));
|
||||
assert_eq!(errors[1].message, "App cannot be resolved to a type");
|
||||
let (_, only_packaging) =
|
||||
launch_compile_errors(&scope, vec![(PathBuf::from("/p/app/pom.xml"), diagnostic(copy))]);
|
||||
assert_eq!(only_packaging, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unresolved_classpaths_retain_all_errors() {
|
||||
for cp in [
|
||||
|
||||
@@ -881,14 +881,9 @@ 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_b(WithBackground { open: proj_c.clone(), background: Vec::new(), remote: None });
|
||||
let server_b = start_in(&discovery, WithBackground { open: proj_c.clone(), background: Vec::new(), remote: None });
|
||||
let port = server_b.port();
|
||||
let server_a = start_in(&discovery, Registry { project: proj_a.clone() });
|
||||
let mut client = Client::start(&discovery, &proj_b.join("src"));
|
||||
client.ask("initialize", json!({ "protocolVersion": "2025-06-18" })).await;
|
||||
@@ -896,8 +891,23 @@ 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();
|
||||
let server_b = start_b(WithBackground::serving(&proj_c, &proj_b));
|
||||
assert_eq!(server_b.port(), port);
|
||||
// stop signals the accept task; the listener is closed asynchronously. Wait for
|
||||
// the old port to be released, as the IDE does before restarting its server.
|
||||
tokio::time::timeout(std::time::Duration::from_secs(5), async {
|
||||
while std::net::TcpListener::bind(("127.0.0.1", port)).is_err() {
|
||||
tokio::time::sleep(std::time::Duration::from_millis(20)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("the stopped server should release its port");
|
||||
let server_b = McpServer::start_with(
|
||||
Arc::new(WithBackground::serving(&proj_c, &proj_b)),
|
||||
Some(discovery.clone()),
|
||||
&tokio::runtime::Handle::current(),
|
||||
ServerOptions { port: Some(port), ..Default::default() },
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(server_b.port(), port, "{:?}", server_b.port_unavailable());
|
||||
let list = client.ask("tools/list", json!({})).await;
|
||||
assert_eq!(list["result"]["tools"][0]["description"], format!("Names {}", proj_b.display()), "{list}");
|
||||
client.close().await;
|
||||
|
||||
@@ -171,6 +171,14 @@ fn bin_dirs_in(root: &Path, platform: Platform) -> Vec<PathBuf> {
|
||||
dirs
|
||||
}
|
||||
|
||||
/// How [`Method::DotnetTool`] installs a package.
|
||||
#[derive(Clone, Copy)]
|
||||
struct DotnetToolOptions {
|
||||
package: &'static str,
|
||||
prerelease: bool,
|
||||
min_sdk: u32,
|
||||
}
|
||||
|
||||
fn managed_bin_dir(root: &Path, spec: &ToolSpec, platform: Platform) -> Option<PathBuf> {
|
||||
match spec.fallback.unwrap_or(spec.method) {
|
||||
Method::Npm { .. } => Some(root.join("node_modules").join(".bin")),
|
||||
@@ -1049,7 +1057,10 @@ impl Tools {
|
||||
Method::Go { module } => self.install_go(spec, module, cancel, emit)?,
|
||||
Method::Gem { gem } => self.install_gem(spec, gem, cancel, emit)?,
|
||||
Method::GemActive { gem } => self.install_gem_active(gem, cancel, emit)?,
|
||||
Method::DotnetTool { package } => self.install_dotnet_tool(spec, package, cancel, emit)?,
|
||||
Method::DotnetTool { package, prerelease, min_sdk } => {
|
||||
let options = DotnetToolOptions { package, prerelease, min_sdk };
|
||||
self.install_dotnet_tool(spec, options, langs, cancel, emit)?
|
||||
}
|
||||
Method::PipVenv { package } => self.install_venv(spec, package, cancel, emit)?,
|
||||
Method::PipUser { package, .. } => self.install_pip_user(package, cancel, emit)?,
|
||||
Method::PipTarget { package, .. } => self.install_pip_target(spec, package, cancel, emit)?,
|
||||
@@ -1220,20 +1231,28 @@ impl Tools {
|
||||
fn install_dotnet_tool(
|
||||
&self,
|
||||
spec: &ToolSpec,
|
||||
package: &str,
|
||||
options: DotnetToolOptions,
|
||||
langs: &[LanguageConfig],
|
||||
cancel: &CancellationToken,
|
||||
emit: Emit,
|
||||
) -> IdeResult<()> {
|
||||
let DotnetToolOptions { package, prerelease, .. } = options;
|
||||
let dir = self.root.join(spec.name);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let tool = dir.join("tool");
|
||||
std::fs::create_dir_all(&tool)?;
|
||||
let dotnet = self.which("dotnet").expect("checked");
|
||||
let version = self.dotnet_tool_version(spec, package, &dotnet, cancel, emit)?;
|
||||
let version = self.dotnet_tool_version(spec, options, langs, &dotnet, cancel, emit)?;
|
||||
let mut c = self.command(&dotnet);
|
||||
c.args(["tool", "install", package, "--tool-path"]).arg(&tool).args(["--verbosity", "normal"]);
|
||||
if let Some(version) = &version {
|
||||
c.args(["--version", version]);
|
||||
match &version {
|
||||
Some(version) => {
|
||||
c.args(["--version", version]);
|
||||
}
|
||||
None if prerelease => {
|
||||
c.arg("--prerelease");
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
let result = run_streamed_picking(c, cancel, emit, dotnet::nuget_errors).and_then(|_| {
|
||||
// The tool's apphost looks for .NET in the default location only; a
|
||||
@@ -1268,17 +1287,20 @@ impl Tools {
|
||||
}
|
||||
|
||||
/// The `--version` to install `package` with: `None` for the latest, or the newest version
|
||||
/// the installed SDK supports. Fails when there is no SDK, or no version runs on it.
|
||||
/// the installed SDK supports. Fails when there is no SDK, it is older than `min_sdk`, or no
|
||||
/// version runs on it.
|
||||
fn dotnet_tool_version(
|
||||
&self,
|
||||
spec: &ToolSpec,
|
||||
package: &str,
|
||||
options: DotnetToolOptions,
|
||||
langs: &[LanguageConfig],
|
||||
dotnet: &Path,
|
||||
cancel: &CancellationToken,
|
||||
emit: Emit,
|
||||
) -> IdeResult<Option<String>> {
|
||||
let mut c = self.command(dotnet);
|
||||
c.arg("--list-sdks");
|
||||
let DotnetToolOptions { package, prerelease, min_sdk } = options;
|
||||
let Some((true, out)) = run_quiet(c, Duration::from_secs(20)) else { return Ok(None) };
|
||||
let Some(sdk) = dotnet::newest_sdk(&out) else {
|
||||
return Err(IdeError::unavailable(format!(
|
||||
@@ -1287,6 +1309,29 @@ impl Tools {
|
||||
dotnet::SDK_DOWNLOAD_URL
|
||||
)));
|
||||
};
|
||||
if sdk.major < min_sdk {
|
||||
// An alternative server for the same files that this SDK can install.
|
||||
let instead = usages(langs)
|
||||
.get(spec.name)
|
||||
.into_iter()
|
||||
.flat_map(|u| u.alternatives.iter())
|
||||
.filter(|name| *name != spec.name)
|
||||
.filter_map(|name| registry::find(name))
|
||||
.find(|alt| matches!(alt.method, Method::DotnetTool { min_sdk, .. } if min_sdk <= sdk.major))
|
||||
.map(|alt| format!(", or install {}, which runs on it", alt.display))
|
||||
.unwrap_or_default();
|
||||
return Err(IdeError::unavailable(format!(
|
||||
"{} needs the .NET {min_sdk} SDK or newer; found {}. Install it from {}{instead}",
|
||||
spec.display,
|
||||
sdk.version,
|
||||
dotnet::SDK_DOWNLOAD_URL
|
||||
)));
|
||||
}
|
||||
// nuget.org's version index used below lists SemVer 1 versions only, which leaves out
|
||||
// most prereleases: let `--prerelease` pick the newest one.
|
||||
if prerelease {
|
||||
return Ok(None);
|
||||
}
|
||||
let pick = self
|
||||
.http()
|
||||
.and_then(|http| dotnet::pick_tool_version(package, sdk.major, |url| http.get_text(url, cancel)));
|
||||
|
||||
@@ -61,8 +61,10 @@ pub enum Method {
|
||||
/// (`~/Library/Application Support`: Bundler `exec`s a lone path string, and Ruby splits it).
|
||||
GemActive { gem: &'static str },
|
||||
/// `dotnet tool install --tool-path <tools>/<name>/tool <package>`, launched
|
||||
/// through `DOTNET_ROOT` wrappers in `bin/`.
|
||||
DotnetTool { package: &'static str },
|
||||
/// through `DOTNET_ROOT` wrappers in `bin/`. `prerelease` installs the newest version,
|
||||
/// prerelease or not, for packages that publish no stable one; `min_sdk` is the lowest
|
||||
/// .NET SDK major that can install the package (0: any).
|
||||
DotnetTool { package: &'static str, prerelease: bool, min_sdk: u32 },
|
||||
/// Platform archive download into `<tools>/<name>/`.
|
||||
Release { source: ReleaseSource, assets: &'static [AssetRule], locate: &'static [&'static str] },
|
||||
}
|
||||
@@ -1426,12 +1428,24 @@ pub static TOOLS: &[ToolSpec] = &[
|
||||
homepage: "https://solargraph.org",
|
||||
needs: &[],
|
||||
},
|
||||
ToolSpec {
|
||||
name: "roslyn-language-server",
|
||||
display: "Roslyn (C#)",
|
||||
kind: LanguageServer,
|
||||
commands: &["roslyn-language-server"],
|
||||
// Prerelease builds only, as platform-specific tool packages: the .NET 10 SDK installs them.
|
||||
method: Method::DotnetTool { package: "roslyn-language-server", prerelease: true, min_sdk: 10 },
|
||||
fallback: None,
|
||||
version: V,
|
||||
homepage: "https://github.com/dotnet/roslyn",
|
||||
needs: &[],
|
||||
},
|
||||
ToolSpec {
|
||||
name: "csharp-ls",
|
||||
display: "csharp-ls",
|
||||
kind: LanguageServer,
|
||||
commands: &["csharp-ls"],
|
||||
method: Method::DotnetTool { package: "csharp-ls" },
|
||||
method: Method::DotnetTool { package: "csharp-ls", prerelease: false, min_sdk: 0 },
|
||||
fallback: None,
|
||||
version: V,
|
||||
homepage: "https://github.com/razzmatazz/csharp-language-server",
|
||||
@@ -1442,7 +1456,7 @@ pub static TOOLS: &[ToolSpec] = &[
|
||||
display: "FsAutoComplete (F#)",
|
||||
kind: LanguageServer,
|
||||
commands: &["fsautocomplete"],
|
||||
method: Method::DotnetTool { package: "fsautocomplete" },
|
||||
method: Method::DotnetTool { package: "fsautocomplete", prerelease: false, min_sdk: 0 },
|
||||
fallback: None,
|
||||
version: V,
|
||||
homepage: "https://github.com/ionide/FsAutoComplete",
|
||||
|
||||
@@ -838,7 +838,7 @@ esac"#,
|
||||
assert!(!env.root.join("ruby-lsp").exists());
|
||||
}
|
||||
|
||||
/// Installs of one tool name share a slot, so parallel csharp-ls tests would join each other's install.
|
||||
/// Installs of one tool name share a slot, so parallel .NET tool tests would join each other's install.
|
||||
#[cfg(unix)]
|
||||
static CSHARP_LS_INSTALL: parking_lot::Mutex<()> = parking_lot::Mutex::new(());
|
||||
|
||||
@@ -1020,6 +1020,37 @@ exit 1"#,
|
||||
assert!(skipped);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn prerelease_dotnet_tool_installs_with_prerelease_on_a_new_enough_sdk() {
|
||||
let _serial = CSHARP_LS_INSTALL.lock();
|
||||
let env = Env::new();
|
||||
let calls = dotnet_with_nuget(
|
||||
&env,
|
||||
"10.0.404",
|
||||
r#"/bin/mkdir -p "$5"; printf '#!/bin/sh\n' > "$5/roslyn-language-server"; /bin/chmod +x "$5/roslyn-language-server""#,
|
||||
);
|
||||
let info = env.tools().install("roslyn-language-server", &langs(), &CancellationToken::new(), &|_| {}).unwrap();
|
||||
assert_eq!(info.status, ToolStatus::Installed);
|
||||
let call = fs::read_to_string(&calls).unwrap();
|
||||
assert!(call.trim_end().ends_with("--verbosity normal --prerelease"), "{call}");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn dotnet_tool_on_an_older_sdk_names_the_sdk_and_an_alternative_that_runs_on_it() {
|
||||
let _serial = CSHARP_LS_INSTALL.lock();
|
||||
let env = Env::new();
|
||||
let calls = dotnet_with_nuget(&env, "8.0.416", FAKE_TOOL_INSTALL);
|
||||
let err = env.tools().install("roslyn-language-server", &langs(), &CancellationToken::new(), &|_| {}).unwrap_err();
|
||||
assert_eq!(err.kind, ErrorKind::Unavailable);
|
||||
assert_eq!(
|
||||
err.message,
|
||||
"Roslyn (C#) needs the .NET 10 SDK or newer; found 8.0.416. Install it from https://dotnet.microsoft.com/download, or install csharp-ls, which runs on it"
|
||||
);
|
||||
assert!(!calls.exists(), "dotnet tool install ran");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn kotlin_debugger_uses_existing_release_recipe_and_language_definition() {
|
||||
let spec = registry::find("kotlin-debug-adapter").unwrap();
|
||||
|
||||
@@ -488,7 +488,7 @@
|
||||
"footer": {
|
||||
"socials": {
|
||||
"github": "https://github.com/l0ng-ai/openidea",
|
||||
"discord": "https://discord.gg/2Zy4yn7gP"
|
||||
"discord": "https://discord.gg/AsZqMgxZm"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -79,26 +79,27 @@ With **Shell integration** on, zsh, bash and fish report the current directory a
|
||||
|
||||
**Settings › Tools › Terminal**:
|
||||
|
||||
| Setting | Default | Notes |
|
||||
| ---------------------------------------- | ------------ | --------------------------------------------------------------------------------------------------------------------- |
|
||||
| **Start directory** | Project root | Relative paths resolve against the project root. **Open in Terminal** still opens the chosen folder. Project setting. |
|
||||
| **Environment variables** | none | Added to new sessions. Project setting. |
|
||||
| **Shell path** | login shell | A command line, e.g. `/bin/zsh --login`. **Installed Shells** lists what was found. |
|
||||
| **Default Tab name** | `Local` | |
|
||||
| **Audible bell** | on | |
|
||||
| **Close session when it ends** | on | |
|
||||
| **Mouse reporting** | on | Off: programs can't capture the mouse. |
|
||||
| **Copy to clipboard on selection** | off | |
|
||||
| **Paste on middle mouse button click** | on | |
|
||||
| **Paste on right click** | off | On: right-click pastes; Ctrl or Shift + right-click opens the context menu. |
|
||||
| **Move focus to the Editor with Escape** | off | Otherwise `Esc` goes to the shell. |
|
||||
| **Override IDE shortcuts** | on | See above. |
|
||||
| **Shell integration** | on | |
|
||||
| **Highlight hyperlinks** | on | |
|
||||
| **Use Option as Meta key** | off | macOS only. |
|
||||
| **Cursor shape** | Block | Block, Underline or Vertical. |
|
||||
| **Blinking cursor** | on | |
|
||||
| **Use editor font** | on | Off: set **Font**, **Size** (6–72), **Line height**, **Fallback font** and **Column width**. |
|
||||
| Setting | Default | Notes |
|
||||
| ----------------------------------------------- | ------------ | ------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| **Start directory** | Project root | Relative paths resolve against the project root. **Open in Terminal** still opens the chosen folder. Project setting. |
|
||||
| **Environment variables** | none | Added to new sessions. Project setting. |
|
||||
| **Shell path** | login shell | A command line, e.g. `/bin/zsh --login`. **Installed Shells** lists what was found. |
|
||||
| **Default Tab name** | `Local` | |
|
||||
| **Audible bell** | on | |
|
||||
| **Close session when it ends** | on | |
|
||||
| **Mouse reporting** | on | Off: programs can't capture the mouse. |
|
||||
| **Copy to clipboard on selection** | off | |
|
||||
| **Let programs copy to the clipboard (OSC 52)** | on | tmux (`set-clipboard on`), Neovim and other programs set the clipboard, also over SSH. They can't read it; payloads over 1 MiB are ignored. |
|
||||
| **Paste on middle mouse button click** | on | |
|
||||
| **Paste on right click** | off | On: right-click pastes; Ctrl or Shift + right-click opens the context menu. |
|
||||
| **Move focus to the Editor with Escape** | off | Otherwise `Esc` goes to the shell. |
|
||||
| **Override IDE shortcuts** | on | See above. |
|
||||
| **Shell integration** | on | |
|
||||
| **Highlight hyperlinks** | on | |
|
||||
| **Use Option as Meta key** | off | macOS only. |
|
||||
| **Cursor shape** | Block | Block, Underline or Vertical. |
|
||||
| **Blinking cursor** | on | |
|
||||
| **Use editor font** | on | Off: set **Font**, **Size** (6–72), **Line height**, **Fallback font** and **Column width**. |
|
||||
|
||||
Changes apply to open sessions right away. Colours follow the IDE theme.
|
||||
|
||||
|
||||
@@ -1,20 +1,22 @@
|
||||
---
|
||||
title: "C# and .NET"
|
||||
description: "C# with csharp-ls, F# with FsAutoComplete, the .NET tool window for builds, NuGet packages and tests, and debugging with netcoredbg."
|
||||
description: "C# with the Roslyn language server or csharp-ls, F# with FsAutoComplete, the .NET tool window for builds, NuGet packages and tests, and debugging with netcoredbg."
|
||||
---
|
||||
|
||||
OpenIDEA supports C# (`.cs`, `.csx`) through [csharp-ls](https://github.com/razzmatazz/csharp-language-server) and F# (`.fs`, `.fsi`, `.fsx`) through [FsAutoComplete](https://github.com/ionide/FsAutoComplete). Both are installed as .NET tools, and both debug with [netcoredbg](https://github.com/Samsung/netcoredbg). Builds, NuGet packages and tests go through the `dotnet` CLI. For other languages, see the [support matrix](/en/languages/index).
|
||||
OpenIDEA supports C# (`.cs`, `.csx`) through Microsoft's [Roslyn language server](https://github.com/dotnet/roslyn) or [csharp-ls](https://github.com/razzmatazz/csharp-language-server), and F# (`.fs`, `.fsi`, `.fsx`) through [FsAutoComplete](https://github.com/ionide/FsAutoComplete). All of them are installed as .NET tools, and both languages debug with [netcoredbg](https://github.com/Samsung/netcoredbg). Builds, NuGet packages and tests go through the `dotnet` CLI. For other languages, see the [support matrix](/en/languages/index).
|
||||
|
||||
## Language server
|
||||
|
||||
| Language | Server | Workspace root markers |
|
||||
| -------- | -------------- | ----------------------------------------------------------------------------------------------------------- |
|
||||
| C# | csharp-ls | `*.sln`, `*.slnx`, `*.csproj`, `global.json`, `Directory.Build.props`, `ProjectSettings/ProjectVersion.txt` |
|
||||
| F# | fsautocomplete | `*.sln`, `*.fsproj`, `global.json` |
|
||||
| Language | Server | Workspace root markers |
|
||||
| -------- | ----------------------------------- | ----------------------------------------------------------------------------------------------------------- |
|
||||
| C# | roslyn-language-server or csharp-ls | `*.sln`, `*.slnx`, `*.csproj`, `global.json`, `Directory.Build.props`, `ProjectSettings/ProjectVersion.txt` |
|
||||
| F# | fsautocomplete | `*.sln`, `*.fsproj`, `global.json` |
|
||||
|
||||
For C#, the IDE uses the Roslyn language server when it is installed and csharp-ls otherwise. Roslyn is the server of the VS Code C# extension. It needs the .NET 10 SDK or newer; csharp-ls also runs on older SDKs. With Roslyn, completion also lists types from namespaces the file doesn't import yet (shown with their namespace), and accepting one adds the `using` directive. Roslyn starts with `--autoLoadProjects`, so it finds and opens the solution or projects itself. On macOS and Linux it loads SDK-style projects only: .NET Framework projects need Mono MSBuild, which it doesn't use. Unity's Visual Studio Editor package generates SDK-style `.csproj` files.
|
||||
|
||||
The server loads the solution or project it finds from these markers. FsAutoComplete starts with `AutomaticWorkspaceInit` on, so it loads the projects without waiting for the editor to ask.
|
||||
|
||||
When you go to the definition of a library type, csharp-ls returns decompiled source. It opens as a read-only document, and so does source-generated code.
|
||||
When you go to the definition of a library type, the server returns decompiled source. It opens as a read-only document, and so does source-generated code.
|
||||
|
||||
`ProjectSettings/ProjectVersion.txt` is there so that Unity projects work too. See [Unity](/en/languages/unity) for using OpenIDEA as Unity's external editor.
|
||||
|
||||
@@ -22,17 +24,18 @@ When you go to the definition of a library type, csharp-ls returns decompiled so
|
||||
|
||||
You need the [.NET SDK](https://dotnet.microsoft.com/download) with `dotnet` on your `PATH`. The IDE runs every build, test and package command through it, and installs the language servers with it.
|
||||
|
||||
When a server is missing, opening a C# or F# file shows a "csharp-ls is not installed" (or FsAutoComplete) notification with **Install**. You can also install the tools from **Settings › Languages & Frameworks › Language Servers**.
|
||||
When no server is installed, opening a C# or F# file shows a "Roslyn (C#) is not installed" (or FsAutoComplete) notification with **Install**. If your SDK is older than .NET 10, the install says so and suggests csharp-ls instead. You can also install the tools from **Settings › Languages & Frameworks › Language Servers**.
|
||||
|
||||
| Tool | How it is installed |
|
||||
| -------------- | ------------------------------------------------------------------------------------------------------------------------- |
|
||||
| Roslyn (C#) | `dotnet tool install --prerelease --tool-path` into the IDE's tools folder; nuget.org has only prerelease builds of it |
|
||||
| csharp-ls | `dotnet tool install --tool-path` into the IDE's tools folder (not a global tool) |
|
||||
| FsAutoComplete | `dotnet tool install --tool-path` into the IDE's tools folder |
|
||||
| netcoredbg | Downloaded from the `Samsung/netcoredbg` GitHub releases. Prebuilt for macOS arm64, Linux x64 and arm64, and Windows x64. |
|
||||
|
||||
Before it installs csharp-ls or FsAutoComplete, the IDE compares the newest SDK in `dotnet --list-sdks` with the .NET version the tool's latest release on nuget.org targets. When the SDK is older, it installs the newest release that runs on it, or tells you which SDK to install.
|
||||
|
||||
A `csharp-ls`, `fsautocomplete` or `netcoredbg` already on your `PATH` (for example a global `dotnet tool install --global csharp-ls`) is used as is.
|
||||
A `roslyn-language-server`, `csharp-ls`, `fsautocomplete` or `netcoredbg` already on your `PATH` (for example a global `dotnet tool install --global csharp-ls`) is used as is.
|
||||
|
||||
## The .NET tool window
|
||||
|
||||
|
||||
@@ -65,7 +65,7 @@ The IDE never needs `sudo`. It installs tools into its own tools folder in the l
|
||||
| `go install` | gopls, Delve, sqls. Needs Go. |
|
||||
| `rustup component add` | rust-analyzer (falls back to a download from Open VSX). |
|
||||
| `gem install` | Solargraph into its own gem home; Ruby LSP into the project's Ruby. |
|
||||
| `dotnet tool install` | csharp-ls, FsAutoComplete. Needs the .NET SDK. |
|
||||
| `dotnet tool install` | Roslyn (C#), csharp-ls, FsAutoComplete. Needs the .NET SDK. |
|
||||
| Release download | clangd, CodeLLDB, vscode-js-debug, JDT LS, java-debug, Kotlin LSP, Lua, Marksman, Taplo, ZLS, terraform-ls and others, from GitHub, Open VSX, Maven Central, the Eclipse download site or HashiCorp. |
|
||||
| Bundled | The Lombok agent for JDT LS ships with the app. |
|
||||
|
||||
@@ -99,7 +99,7 @@ The table lists every built-in language definition. Server and debugger names in
|
||||
| Astro | `astro` | `.astro` | Yes | — | **astro-ls** + **oxlint** | — |
|
||||
| Batch | `bat` | `.bat`, `.cmd` | Yes | — | — | — |
|
||||
| C | `c` | `.c`, `.h` | Yes | Yes | **clangd** | lldb-dap |
|
||||
| C# | `csharp` | `.cs`, `.csx` | Yes | Yes | **csharp-ls** | **netcoredbg** |
|
||||
| C# | `csharp` | `.cs`, `.csx` | Yes | Yes | **roslyn-language-server** → **csharp-ls** | **netcoredbg** |
|
||||
| C++ | `cpp` | `.cpp`, `.cc`, `.cxx`, `.c++`, `.hpp`, … | Yes | Yes | **clangd** | lldb-dap |
|
||||
| Clojure | `clojure` | `.clj`, `.cljs`, `.cljc`, `.cljd`, `.edn`, … | Yes | — | **clojure-lsp** | — |
|
||||
| CMake | `cmake` | `.cmake` | Yes | Yes | **neocmakelsp** → cmake-language-server | — |
|
||||
|
||||
@@ -76,9 +76,9 @@ When Git asks whether to add a new file you created in the IDE, the `.meta` file
|
||||
|
||||
## Code intelligence
|
||||
|
||||
C# in a Unity project uses the same language server as any other C# project, csharp-ls; see [C# and .NET](/en/languages/csharp) for installation. A Unity project is a workspace root for it even before a solution exists.
|
||||
C# in a Unity project uses the same language server as any other C# project (Roslyn, or csharp-ls); see [C# and .NET](/en/languages/csharp) for installation. A Unity project is a workspace root for it even before a solution exists.
|
||||
|
||||
csharp-ls reads the `.sln` and `.csproj` files that Unity generates. When they are missing, the Unity pane shows:
|
||||
The server reads the `.sln` and `.csproj` files that Unity generates. When they are missing, the Unity pane shows:
|
||||
|
||||
> C# project files are missing. In Unity, select an external script editor in Preferences > External Tools, then regenerate project files.
|
||||
|
||||
|
||||
@@ -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/2Zy4yn7gP).
|
||||
Questions and feedback are also welcome on [Discord](https://discord.gg/AsZqMgxZm).
|
||||
@@ -79,26 +79,27 @@ OpenIDEA 会按项目记住终端标签页:各自的目录、自定义名称
|
||||
|
||||
**设置 › 工具 › 终端**:
|
||||
|
||||
| 设置 | 默认值 | 说明 |
|
||||
| ------------------------------ | ---------- | ----------------------------------------------------------------------------- |
|
||||
| **起始目录** | 项目根目录 | 相对路径按项目根目录解析。**在终端中打开** 仍会打开所选文件夹。项目级设置。 |
|
||||
| **环境变量** | 无 | 添加到新会话的环境中。项目级设置。 |
|
||||
| **Shell 路径** | 登录 Shell | 一条命令行,例如 `/bin/zsh --login`。**已安装的 Shell** 列出找到的 Shell。 |
|
||||
| **默认标签页名称** | `Local` | |
|
||||
| **响铃** | 开 | |
|
||||
| **会话结束时关闭** | 开 | |
|
||||
| **鼠标报告** | 开 | 关闭后程序无法捕获鼠标。 |
|
||||
| **选择时复制到剪贴板** | 关 | |
|
||||
| **点击鼠标中键时粘贴** | 开 | |
|
||||
| **右键单击时粘贴** | 关 | 开启后右键单击直接粘贴;按住 Ctrl 或 Shift 右键单击仍打开上下文菜单。 |
|
||||
| **按 Escape 将焦点移到编辑器** | 关 | 关闭时 `Esc` 发给 Shell。 |
|
||||
| **覆盖 IDE 快捷键** | 开 | 见上文。 |
|
||||
| **Shell 集成** | 开 | |
|
||||
| **高亮超链接** | 开 | |
|
||||
| **将 Option 用作 Meta 键** | 关 | 仅 macOS。 |
|
||||
| **光标形状** | 块 | 块、下划线或竖线。 |
|
||||
| **闪烁光标** | 开 | |
|
||||
| **使用编辑器字体** | 开 | 关闭后可设置 **字体**、**大小**(6–72)、**行高**、**备用字体** 和 **列宽**。 |
|
||||
| 设置 | 默认值 | 说明 |
|
||||
| ---------------------------------- | ---------- | ---------------------------------------------------------------------------------------------------------------------- |
|
||||
| **起始目录** | 项目根目录 | 相对路径按项目根目录解析。**在终端中打开** 仍会打开所选文件夹。项目级设置。 |
|
||||
| **环境变量** | 无 | 添加到新会话的环境中。项目级设置。 |
|
||||
| **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)、**行高**、**备用字体** 和 **列宽**。 |
|
||||
|
||||
修改会立即应用到已打开的会话。配色跟随 IDE 主题。
|
||||
|
||||
|
||||
@@ -1,20 +1,22 @@
|
||||
---
|
||||
title: "C# 与 .NET"
|
||||
description: "使用 csharp-ls 的 C#、使用 FsAutoComplete 的 F#,用于构建、NuGet 包和测试的 .NET 工具窗口,以及基于 netcoredbg 的调试。"
|
||||
description: "使用 Roslyn 语言服务器或 csharp-ls 的 C#、使用 FsAutoComplete 的 F#,用于构建、NuGet 包和测试的 .NET 工具窗口,以及基于 netcoredbg 的调试。"
|
||||
---
|
||||
|
||||
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)。
|
||||
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)。
|
||||
|
||||
## 语言服务器
|
||||
|
||||
| 语言 | 服务器 | 工作区根目录标记 |
|
||||
| ---- | -------------- | ----------------------------------------------------------------------------------------------------------- |
|
||||
| C# | csharp-ls | `*.sln`、`*.slnx`、`*.csproj`、`global.json`、`Directory.Build.props`、`ProjectSettings/ProjectVersion.txt` |
|
||||
| F# | fsautocomplete | `*.sln`、`*.fsproj`、`global.json` |
|
||||
| 语言 | 服务器 | 工作区根目录标记 |
|
||||
| ---- | ----------------------------------- | ----------------------------------------------------------------------------------------------------------- |
|
||||
| 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`。
|
||||
|
||||
语言服务器会加载根据这些标记找到的解决方案或项目。FsAutoComplete 启动时开启了 `AutomaticWorkspaceInit`,无需等待编辑器请求就会自动加载项目。
|
||||
|
||||
跳转到类库类型的定义时,csharp-ls 返回反编译后的源码,以只读文档打开;源生成器生成的代码同样以只读方式打开。
|
||||
跳转到类库类型的定义时,语言服务器返回反编译后的源码,以只读文档打开;源生成器生成的代码同样以只读方式打开。
|
||||
|
||||
`ProjectSettings/ProjectVersion.txt` 这个标记是为 Unity 项目准备的。把 OpenIDEA 设为 Unity 外部编辑器的方法见 [Unity](/zh/languages/unity)。
|
||||
|
||||
@@ -22,17 +24,18 @@ OpenIDEA 通过 [csharp-ls](https://github.com/razzmatazz/csharp-language-server
|
||||
|
||||
需要安装 [.NET SDK](https://dotnet.microsoft.com/download),并确保 `dotnet` 在 `PATH` 上。IDE 的构建、测试和包管理命令都通过它执行,语言服务器也用它安装。
|
||||
|
||||
缺少语言服务器时,打开 C# 或 F# 文件会弹出“csharp-ls 未安装”(或 FsAutoComplete)的通知,点 **安装** 即可。也可以在 **设置 › 语言和框架 › 语言服务器** 中安装。
|
||||
没有安装语言服务器时,打开 C# 或 F# 文件会弹出“Roslyn (C#) 未安装”(或 FsAutoComplete)的通知,点 **安装** 即可。SDK 低于 .NET 10 时,安装会说明这一点并建议改装 csharp-ls。也可以在 **设置 › 语言和框架 › 语言服务器** 中安装。
|
||||
|
||||
| 工具 | 安装方式 |
|
||||
| -------------- | -------------------------------------------------------------------------------------------------------------- |
|
||||
| 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` 上已有的 `csharp-ls`、`fsautocomplete` 或 `netcoredbg`(例如通过 `dotnet tool install --global csharp-ls` 安装的全局工具)会直接使用。
|
||||
`PATH` 上已有的 `roslyn-language-server`、`csharp-ls`、`fsautocomplete` 或 `netcoredbg`(例如通过 `dotnet tool install --global csharp-ls` 安装的全局工具)会直接使用。
|
||||
|
||||
## .NET 工具窗口
|
||||
|
||||
|
||||
@@ -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` | csharp-ls、FsAutoComplete。需要 .NET SDK。 |
|
||||
| `dotnet tool install` | Roslyn(C#)、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` | 是 | 是 | **csharp-ls** | **netcoredbg** |
|
||||
| C# | `csharp` | `.cs`, `.csx` | 是 | 是 | **roslyn-language-server** → **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 | — |
|
||||
|
||||
@@ -76,9 +76,9 @@ description: "把 OpenIDEA 设为 Unity 的外部脚本编辑器,浏览 Unity
|
||||
|
||||
## 代码智能
|
||||
|
||||
Unity 项目中的 C# 和普通 C# 项目使用同一个语言服务器 csharp-ls,安装方式见 [C# 与 .NET](/zh/languages/csharp)。即使还没有解决方案文件,Unity 项目也会被当作它的工作区根目录。
|
||||
Unity 项目中的 C# 和普通 C# 项目使用同一个语言服务器(Roslyn 或 csharp-ls),安装方式见 [C# 与 .NET](/zh/languages/csharp)。即使还没有解决方案文件,Unity 项目也会被当作它的工作区根目录。
|
||||
|
||||
csharp-ls 读取 Unity 生成的 `.sln` 和 `.csproj` 文件。缺少这些文件时,**Unity 项目**视图会提示:
|
||||
语言服务器读取 Unity 生成的 `.sln` 和 `.csproj` 文件。缺少这些文件时,**Unity 项目**视图会提示:
|
||||
|
||||
> 缺少 C# 项目文件。请在 Unity 的偏好设置 > 外部工具中选择外部脚本编辑器,然后重新生成项目文件。
|
||||
|
||||
|
||||
@@ -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/2Zy4yn7gP) 提问和反馈;README 中还有微信群二维码。
|
||||
也欢迎在 [Discord](https://discord.gg/AsZqMgxZm) 提问和反馈;README 中还有微信群二维码。
|
||||
@@ -1,5 +1,7 @@
|
||||
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",
|
||||
@@ -254,3 +256,141 @@ 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();
|
||||
});
|
||||
@@ -610,6 +610,8 @@ 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();
|
||||
@@ -623,6 +625,7 @@ 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);
|
||||
@@ -673,6 +676,7 @@ 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);
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ async function openRecent(page: Page, kind: "recentFiles" | "recentLocations") {
|
||||
}, kind);
|
||||
}
|
||||
|
||||
test("Recent Files keeps directories beside names and leaves room for files in a narrow window", async ({
|
||||
test("Recent Files shows only names and keeps the selected path in the footer in a narrow window", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await stubDesktop(page);
|
||||
@@ -20,20 +20,19 @@ test("Recent Files keeps directories beside names and leaves room for files in a
|
||||
const files = dialog.getByRole("listbox", { name: "Recent files" });
|
||||
const row = files.getByRole("option").first();
|
||||
const name = row.getByText("InvoiceService.ts", { exact: true });
|
||||
const directory = row.getByText("src/orders", { exact: true });
|
||||
const footer = dialog.locator("footer");
|
||||
await expect(name).toBeVisible();
|
||||
const nameRight = await name.evaluate((el) => el.getBoundingClientRect().right);
|
||||
const dirLeft = (await directory.boundingBox())!.x;
|
||||
expect(dirLeft - nameRight).toBeLessThanOrEqual(8);
|
||||
await expect(row).not.toContainText("src/orders");
|
||||
await expect(footer.locator("bdi")).toHaveText("/dev/acme-api/src/orders/InvoiceService.ts");
|
||||
|
||||
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.poll(() => directory.evaluate((el) => el.getBoundingClientRect().width)).toBeGreaterThan(20);
|
||||
await expect(row).not.toContainText("src/orders");
|
||||
await expect(footer.locator("bdi")).toHaveText("/dev/acme-api/src/orders/InvoiceService.ts");
|
||||
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),
|
||||
|
||||
@@ -69,6 +69,11 @@ 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"],
|
||||
@@ -83,9 +88,13 @@ 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 shape(icon!));
|
||||
.toEqual(await glyph(icon!));
|
||||
await expect(row.locator("[data-project-path]")).toHaveCount(0);
|
||||
}
|
||||
await tree.locator('[data-project-path="/work/z-web"]').click();
|
||||
@@ -113,13 +122,12 @@ 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(() =>
|
||||
tree
|
||||
.locator('[data-project-path="/work/z-web"] svg path')
|
||||
.evaluateAll((paths) => paths.map((path) => path.getAttribute("d"))),
|
||||
)
|
||||
.toEqual(await shape("file-go"));
|
||||
.poll(() => zWeb.locator("svg path").evaluateAll((paths) => paths.map((path) => path.getAttribute("d"))))
|
||||
.toEqual(await glyph("file-go"));
|
||||
await expect(tree.locator("[data-project-path]")).toHaveText([
|
||||
"rust/work/rust",
|
||||
"dart/work/dart",
|
||||
|
||||
@@ -7,8 +7,21 @@ 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"
|
||||
|
||||
@@ -81,6 +81,11 @@ 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
|
||||
|
||||
@@ -8171,6 +8171,11 @@ 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. */
|
||||
@@ -15716,6 +15721,8 @@ 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,
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
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: "冒号是全角\nab\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("冒号是全角");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,112 @@
|
||||
/**
|
||||
* 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 },
|
||||
);
|
||||
@@ -71,6 +71,7 @@ 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";
|
||||
|
||||
@@ -440,6 +441,7 @@ export function baseExtensions(o: SetupOptions): Extension {
|
||||
compartments.folding.of(foldingFor(o.settings)),
|
||||
highlightActiveLineGutter(),
|
||||
highlightSpecialChars(),
|
||||
zeroWidthJoiners,
|
||||
history(),
|
||||
compartments.caret.of(caretFor(o.settings)),
|
||||
dropCursor(),
|
||||
|
||||
@@ -523,6 +523,90 @@ 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");
|
||||
|
||||
@@ -749,9 +749,17 @@ 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.
|
||||
// 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.
|
||||
apply:
|
||||
cm.displayLabel || (item.filterText && item.filterText !== item.label) || item.additionalEdits.length
|
||||
cm.displayLabel ||
|
||||
(item.filterText && item.filterText !== item.label) ||
|
||||
item.additionalEdits.length ||
|
||||
item.labelDescription ||
|
||||
item.detail ||
|
||||
item.labelDetail
|
||||
? (...a: Parameters<typeof applyLsp>) => applyLsp(...a)
|
||||
: applyLsp,
|
||||
info: (c: Completion) => renderInfo(c as LspCompletion),
|
||||
@@ -867,6 +875,10 @@ 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);
|
||||
|
||||
@@ -346,3 +346,8 @@
|
||||
color: var(--fg-muted);
|
||||
font-size: var(--fs-small);
|
||||
}
|
||||
.inUse {
|
||||
flex: none;
|
||||
color: var(--warning);
|
||||
font-size: var(--fs-small);
|
||||
}
|
||||
@@ -760,6 +760,11 @@ export function AgentsView() {
|
||||
<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"
|
||||
|
||||
@@ -28,6 +28,8 @@ interface Row {
|
||||
cwd: string | null;
|
||||
folder: string;
|
||||
updatedMs: number;
|
||||
/** Open in another app, which would keep writing to it too. */
|
||||
inUse: boolean;
|
||||
}
|
||||
|
||||
interface Selection {
|
||||
@@ -85,6 +87,7 @@ 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(
|
||||
@@ -106,6 +109,8 @@ 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;
|
||||
@@ -156,10 +161,11 @@ function ImportSessionsDialog() {
|
||||
hideImportSessions();
|
||||
};
|
||||
const forkChosen = () => runChosen(true);
|
||||
const runDefault = () => runChosen(forkByDefault);
|
||||
const onFilterKey = (e: KeyboardEvent) => {
|
||||
if (e.key === "Enter") {
|
||||
e.preventDefault();
|
||||
importChosen();
|
||||
runDefault();
|
||||
return;
|
||||
}
|
||||
// Home / End move the caret in the filter text.
|
||||
@@ -172,7 +178,7 @@ function ImportSessionsDialog() {
|
||||
const onListKey = (e: KeyboardEvent) => {
|
||||
if (e.key === "Enter") {
|
||||
e.preventDefault();
|
||||
importChosen();
|
||||
runDefault();
|
||||
} else if (e.key.toLowerCase() === "a" && hasPrimaryModifier(e)) {
|
||||
e.preventDefault();
|
||||
selectAll();
|
||||
@@ -199,6 +205,10 @@ 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 ? (
|
||||
<span className={styles.chooserHint}>
|
||||
<T>Only the 50 most recent sessions are shown.</T>
|
||||
@@ -208,8 +218,18 @@ function ImportSessionsDialog() {
|
||||
}
|
||||
buttons={[
|
||||
{ label: "Cancel", role: "cancel" },
|
||||
{ label: forkLabel, onClick: forkChosen, disabled: busy || !shown || !chosen.length },
|
||||
{ label: importLabel, role: "default", onClick: importChosen, disabled: busy || !shown || !chosen.length },
|
||||
{
|
||||
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,
|
||||
},
|
||||
]}
|
||||
>
|
||||
<div className={styles.chooser}>
|
||||
@@ -230,7 +250,7 @@ function ImportSessionsDialog() {
|
||||
className={styles.chooserList}
|
||||
onKeyDown={onListKey}
|
||||
onDoubleClick={(e) => {
|
||||
if ((e.target as Element).closest('[role="option"]')) importChosen();
|
||||
if ((e.target as Element).closest('[role="option"]')) runDefault();
|
||||
}}
|
||||
>
|
||||
{loading ? (
|
||||
@@ -259,6 +279,11 @@ 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,5 +1,9 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { registerAction, registerActions } from "@/platform/actions";
|
||||
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 { useProject } from "@/platform/project";
|
||||
import * as contributions from "@/workbench/contributions";
|
||||
import type { MenuItem } from "@/ui";
|
||||
@@ -24,6 +28,7 @@ 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),
|
||||
@@ -38,6 +43,7 @@ afterEach(() => {
|
||||
.reverse()
|
||||
.forEach((dispose) => dispose());
|
||||
useProject.setState({ project: null });
|
||||
context.clearContext("projectOpen");
|
||||
vi.restoreAllMocks();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
@@ -101,3 +107,33 @@ 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"));
|
||||
});
|
||||
});
|
||||
@@ -3,11 +3,15 @@
|
||||
* 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, registerMenuGroup } from "@/workbench/contributions";
|
||||
import { notifications, projectViewSelection, registerMenuGroup } from "@/workbench/contributions";
|
||||
import { mentionOf, referenceOf } from "./composerModel";
|
||||
import { composerReferenceContext, type ReferenceTarget } from "./store";
|
||||
|
||||
@@ -38,16 +42,41 @@ 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",
|
||||
hidden: true,
|
||||
run: ({ arg }) => {
|
||||
const text = Array.isArray(arg) ? agentReferences(arg as ReferenceTarget[]) : null;
|
||||
if (text) void copy(text);
|
||||
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);
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
@@ -217,8 +217,8 @@ export function revealRowsAt(el: HTMLElement, top: number) {
|
||||
}
|
||||
}
|
||||
|
||||
/** 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 {
|
||||
/** 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 {
|
||||
const rows = el.querySelectorAll(`:scope > .${styles.conversationRow}`);
|
||||
if (!rows.length) return null;
|
||||
const view = el.getBoundingClientRect().top;
|
||||
@@ -230,7 +230,9 @@ function firstShownRow(el: HTMLElement): { row: Element; top: number } | null {
|
||||
else lo = mid + 1;
|
||||
}
|
||||
const row = rows[lo]!;
|
||||
return { row, top: row.getBoundingClientRect().top - view };
|
||||
const box = row.getBoundingClientRect();
|
||||
if (box.bottom <= view) return null;
|
||||
return { row, top: box.top - view, height: box.height };
|
||||
}
|
||||
|
||||
/** Images remain visible beside the work's folded summary, without duplicating them when it opens. */
|
||||
@@ -290,6 +292,14 @@ 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);
|
||||
@@ -403,7 +413,7 @@ export function Stream({
|
||||
}, [loadEarlier]);
|
||||
useEffect(() => {
|
||||
const down = (event: PointerEvent) => {
|
||||
if (!ref.current?.contains(event.target as Node)) return;
|
||||
if (!ref.current?.contains(event.target as Node) || isInteractiveTarget(event.target)) return;
|
||||
dragging.current = true;
|
||||
if (loadTimer.current !== null) {
|
||||
window.clearTimeout(loadTimer.current);
|
||||
@@ -488,6 +498,7 @@ export function Stream({
|
||||
const shownRow = useRef<{
|
||||
row: Element;
|
||||
top: number;
|
||||
height: number;
|
||||
scrollTop: number;
|
||||
} | null>(null);
|
||||
const holdShownRow = useCallback(() => {
|
||||
@@ -496,24 +507,35 @@ 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.
|
||||
const clamped = el.scrollTop < held.scrollTop && el.scrollTop >= el.scrollHeight - el.clientHeight - 1;
|
||||
// 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;
|
||||
if (el.scrollTop === held.scrollTop || clamped) {
|
||||
const moved = held.row.getBoundingClientRect().top - el.getBoundingClientRect().top - held.top;
|
||||
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;
|
||||
if (Math.abs(moved) >= 1) {
|
||||
const target = Math.max(0, el.scrollTop + moved);
|
||||
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 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]);
|
||||
@@ -526,7 +548,10 @@ export function Stream({
|
||||
const onDiagramDrawn = useCallback(() => {
|
||||
const el = ref.current;
|
||||
if (!el) return;
|
||||
if (position.current.stick && !dragging.current) scrollStreamTo(el, el.scrollHeight);
|
||||
if (position.current.stick && !dragging.current && slack.current === 0) {
|
||||
scrollStreamTo(el, el.scrollHeight);
|
||||
position.current = { top: el.scrollTop, stick: true };
|
||||
}
|
||||
updateJumpVisibility(el);
|
||||
}, [updateJumpVisibility]);
|
||||
useLayoutEffect(() => {
|
||||
@@ -536,27 +561,43 @@ 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 && !position.current.stick) {
|
||||
if (sent) {
|
||||
scrollingUp.current = false;
|
||||
position.current = { top: el.scrollTop, stick: true };
|
||||
positions.set(key, position.current);
|
||||
setAway(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);
|
||||
}
|
||||
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]);
|
||||
}, [entries, visible, key, positions, setSlack]);
|
||||
useLayoutEffect(() => {
|
||||
const el = ref.current;
|
||||
if (!el || entries === null || !visible) return;
|
||||
trimSlack();
|
||||
if (position.current.stick) {
|
||||
if (!dragging.current) scrollStreamTo(el, el.scrollHeight);
|
||||
} else if (!restored.current) scrollStreamTo(el, position.current.top);
|
||||
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);
|
||||
}
|
||||
restored.current = true;
|
||||
updateJumpVisibility(el);
|
||||
});
|
||||
@@ -596,8 +637,10 @@ export function Stream({
|
||||
if (!el) return;
|
||||
const observer = new ResizeObserver(() => {
|
||||
trimSlack();
|
||||
if (position.current.stick && !dragging.current) scrollStreamTo(el, el.scrollHeight);
|
||||
else if (!position.current.stick && el.scrollHeight <= el.clientHeight && !dragging.current) loadWhenStill();
|
||||
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();
|
||||
updateJumpVisibility(el);
|
||||
});
|
||||
observer.observe(el);
|
||||
@@ -661,6 +704,7 @@ 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();
|
||||
},
|
||||
@@ -671,13 +715,15 @@ 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]);
|
||||
@@ -806,7 +852,8 @@ export function Stream({
|
||||
)
|
||||
scrollingUp.current = false;
|
||||
}}
|
||||
onPointerDown={() => {
|
||||
onPointerDown={(e) => {
|
||||
if (isInteractiveTarget(e.target)) return;
|
||||
markUserScroll();
|
||||
scrollingUp.current = false;
|
||||
}}
|
||||
@@ -819,21 +866,24 @@ export function Stream({
|
||||
}}
|
||||
onScroll={(e) => {
|
||||
const el = e.currentTarget;
|
||||
trimSlack();
|
||||
const atEnd = el.scrollHeight - el.scrollTop - el.clientHeight < 40;
|
||||
const contentHeight = el.scrollHeight - slack.current;
|
||||
const laidOut =
|
||||
el.scrollHeight !== seenHeight.current.content || el.clientHeight !== seenHeight.current.view;
|
||||
contentHeight !== seenHeight.current.content || el.clientHeight !== seenHeight.current.view;
|
||||
seenHeight.current = {
|
||||
content: el.scrollHeight,
|
||||
content: contentHeight,
|
||||
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) scrollStreamTo(el, el.scrollHeight);
|
||||
if (stick && !atEnd && !dragging.current && slack.current === 0) scrollStreamTo(el, el.scrollHeight);
|
||||
if (stick) shownRow.current = null;
|
||||
position.current = { top: el.scrollTop, stick };
|
||||
positions.set(key, position.current);
|
||||
updateJumpVisibility(el);
|
||||
@@ -841,7 +891,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();
|
||||
holdShownRow();
|
||||
if (!position.current.stick && shownRow.current === null) takeShownRow();
|
||||
}}
|
||||
// Copy, plus Quote for a selection: replies to it in the composer.
|
||||
onContextMenu={(e) => {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { act, fireEvent, render, waitFor } from "@testing-library/react";
|
||||
import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
|
||||
import { afterEach, beforeEach, expect, it, vi } from "vitest";
|
||||
import type { AgentEntry, AgentTask } from "@/bindings";
|
||||
|
||||
@@ -14,6 +14,20 @@ 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" } }),
|
||||
},
|
||||
}));
|
||||
@@ -51,26 +65,58 @@ 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 whose text says "tall" is 300px, any other 100px. */
|
||||
const height = (row: Element) => (row.textContent?.includes("tall") ? 300 : 100);
|
||||
/** 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;
|
||||
};
|
||||
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")]]]),
|
||||
entries: new Map([
|
||||
[task.id, [agent("tall one"), agent("two"), agent("three"), agent("four"), agent("five"), agent("six")]],
|
||||
]),
|
||||
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 row of rowsOf(scroller)) {
|
||||
if (row === this) return new DOMRect(0, top, 600, height(row));
|
||||
top += height(row);
|
||||
for (const child of childrenOf(scroller)) {
|
||||
if (child === this) return new DOMRect(0, top, 600, height(child));
|
||||
top += height(child);
|
||||
}
|
||||
}
|
||||
return original.call(this);
|
||||
@@ -91,12 +137,7 @@ it("keeps the row at the top of the view in place when a row above it gets short
|
||||
expect(found).toBeTruthy();
|
||||
return found!;
|
||||
});
|
||||
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,
|
||||
});
|
||||
attachScrollGeometry(el);
|
||||
// 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;
|
||||
@@ -105,10 +146,172 @@ 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")]]]),
|
||||
entries: new Map([
|
||||
[task.id, [agent("one"), agent("two"), agent("three"), agent("four"), agent("five"), agent("six")]],
|
||||
]),
|
||||
});
|
||||
});
|
||||
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);
|
||||
});
|
||||
@@ -55,6 +55,7 @@ const backend = vi.hoisted(() => ({
|
||||
title: string;
|
||||
cwd: string | null;
|
||||
updatedMs: number;
|
||||
inUse?: boolean;
|
||||
}>,
|
||||
imported: [] as Array<[string, string]>,
|
||||
forked: [] as Array<[string, string, string]>,
|
||||
@@ -2695,6 +2696,7 @@ describe("batch import", () => {
|
||||
title,
|
||||
cwd: null,
|
||||
updatedMs: 0,
|
||||
inUse: false,
|
||||
});
|
||||
const a = session("a", "First");
|
||||
const b = session("b", "Second");
|
||||
@@ -2814,7 +2816,14 @@ describe("import sessions dialog", () => {
|
||||
{ provider: "claude", sessionId: "abc", title: "Login fix", cwd: "/work/app", updatedMs: 0 },
|
||||
{ provider: "codex", sessionId: "thread-1", title: "Add tests", cwd: null, updatedMs: 0 },
|
||||
];
|
||||
const third = { provider: "claude", sessionId: "c3", title: "Fix flaky test", cwd: "/work/api", updatedMs: 0 };
|
||||
const third = {
|
||||
provider: "claude",
|
||||
sessionId: "c3",
|
||||
title: "Fix flaky test",
|
||||
cwd: "/work/api",
|
||||
updatedMs: 0,
|
||||
inUse: false,
|
||||
};
|
||||
const open = () => {
|
||||
render(<ImportSessionsOverlay />);
|
||||
act(() => showImportSessions());
|
||||
@@ -3060,6 +3069,27 @@ describe("import sessions dialog", () => {
|
||||
await listed("Add tests");
|
||||
});
|
||||
|
||||
it("forks by default when another app has a chosen session open", async () => {
|
||||
backend.external = [...sessions, { ...third, inUse: true }];
|
||||
open();
|
||||
await listed("Fix flaky test");
|
||||
expect(row(/Login fix/)).not.toHaveTextContent("In use");
|
||||
expect(row(/Fix flaky test/)).toHaveTextContent("In use");
|
||||
expect(screen.getByRole("button", { name: "Import" })).toHaveAttribute("data-dialog-default");
|
||||
fireEvent.click(row(/Login fix/));
|
||||
fireEvent.click(row(/Fix flaky test/), primary);
|
||||
expect(screen.getByText(/Another app has this session open/)).toBeInTheDocument();
|
||||
expect(screen.getByRole("button", { name: "Fork 2" })).toHaveAttribute("data-dialog-default");
|
||||
await act(async () => {
|
||||
fireEvent.keyDown(screen.getByRole("listbox"), { key: "Enter" });
|
||||
});
|
||||
expect(backend.imported).toEqual([]);
|
||||
expect(backend.forked.map(([provider, id]) => [provider, id])).toEqual([
|
||||
["claude", "abc"],
|
||||
["claude", "c3"],
|
||||
]);
|
||||
});
|
||||
|
||||
it("shows the full title and folder as a row tooltip", async () => {
|
||||
backend.external = sessions;
|
||||
open();
|
||||
|
||||
@@ -290,7 +290,7 @@ export function TableEditor({ input }: { input: EditorInput }) {
|
||||
const showDdl = async () => {
|
||||
setDdlBusy(true);
|
||||
try {
|
||||
await openDdl(ref.id, ref.schema, ref.table);
|
||||
await openDdl(ref.id, ref.schema, ref.table, ref.catalog);
|
||||
} finally {
|
||||
setDdlBusy(false);
|
||||
}
|
||||
|
||||
@@ -86,6 +86,7 @@ import {
|
||||
tablesKey,
|
||||
setConsoleSchema,
|
||||
setManualCommit,
|
||||
reloadDdl,
|
||||
sourceById,
|
||||
useDatabase,
|
||||
} from "./store";
|
||||
@@ -421,6 +422,8 @@ function ConsoleBar({ path, view }: { path: string; view: EditorView }) {
|
||||
const bound = useDatabase(() => consoleSource(path));
|
||||
const running = useDatabase((s) => !!s.running[path]);
|
||||
const maxRows = useDatabase((s) => s.maxRows);
|
||||
// A file this feature generated (Go to DDL): its text is a snapshot, so it gets a Reload.
|
||||
const ddlTable = useDatabase((s) => s.ddlFiles[path]);
|
||||
const manual = useDatabase((s) => !!bound && consoleUsesManualCommit(s, bound, path));
|
||||
const pending = useDatabase((s) => !!bound && consoleHasPending(s, bound, path));
|
||||
const inEditor = useProject((s) => inEditorResults(s.settings));
|
||||
@@ -557,6 +560,7 @@ function ConsoleBar({ path, view }: { path: string; view: EditorView }) {
|
||||
options={ROW_LIMITS.map((v) => ({ value: v, label: tx`${Number(v).toLocaleString("en")} rows` }))}
|
||||
onChange={(v) => useDatabase.setState({ maxRows: Number(v) })}
|
||||
/>
|
||||
{ddlTable && <IconButton icon="refresh" title="Reload the DDL" onClick={() => void reloadDdl(path)} />}
|
||||
<span className={styles.spacer} />
|
||||
{bound && driver === "snowflake" && <SnowflakeSession target={bound} idle={!running} />}
|
||||
<Select
|
||||
|
||||
@@ -235,6 +235,12 @@ interface DatabaseState {
|
||||
objects: Record<string, DbSchemaObjects>;
|
||||
/** Console / SQL file path → data source id. */
|
||||
consoles: Record<string, string>;
|
||||
/**
|
||||
* DDL file path → the table it was generated for, so the editor's Reload can regenerate it.
|
||||
* The path itself is lossy (`openDdl` replaces characters outside `[\w.-]`), so the table is
|
||||
* recorded rather than parsed back out of the name.
|
||||
*/
|
||||
ddlFiles: Record<string, { id: string; schema: string; table: string; catalog?: string }>;
|
||||
/** Console path → its active schema (unqualified names resolve there; see `consoleSchema`). */
|
||||
consoleSchemas: Record<string, string>;
|
||||
separateProceduresAndFunctions: boolean;
|
||||
@@ -335,6 +341,7 @@ export const useDatabase = create<DatabaseState>(() => ({
|
||||
details: {},
|
||||
objects: {},
|
||||
consoles: readBindings(),
|
||||
ddlFiles: {},
|
||||
consoleSchemas: readConsoleSchemas(),
|
||||
...initialViewOptions,
|
||||
completion: {},
|
||||
@@ -2023,7 +2030,7 @@ export function readableDdl(text: string, driver: DbDriver | undefined): string
|
||||
}
|
||||
|
||||
/** Go to DDL: the definition of a table / view, in a SQL file next to the data source's console. */
|
||||
export async function openDdl(id: string, schema: string, name: string): Promise<void> {
|
||||
export async function openDdl(id: string, schema: string, name: string, catalog?: string): Promise<void> {
|
||||
try {
|
||||
const [text, console] = await Promise.all([
|
||||
withConnection(id, () => call(commands.dbDdl(id, schema, name))),
|
||||
@@ -2033,12 +2040,32 @@ export async function openDdl(id: string, schema: string, name: string): Promise
|
||||
const path = console.replace(/[^\\/]*$/, `${safe(schema)}.${safe(name)}.sql`);
|
||||
await call(commands.dbExportFile(path, readableDdl(text, sourceById(id)?.driver)));
|
||||
bindConsole(path, id);
|
||||
// Reload on the generated file needs the table it came from; the path cannot be parsed back
|
||||
// into one (`safe` above is lossy).
|
||||
useDatabase.setState((s) => ({ ddlFiles: { ...s.ddlFiles, [path]: { id, schema, table: name, catalog } } }));
|
||||
await editorService().openFile(path, { focus: true });
|
||||
} catch (e) {
|
||||
notifications().notify({ level: "error", title: `Cannot get the DDL of ${name}`, body: message(e) });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-reads the table's DDL into the file `openDdl` generated, replacing what it holds. Used by
|
||||
* the Reload in the generated file's tab: the text there is a snapshot of the catalog at the
|
||||
* time it was generated, so it goes stale as soon as anything changes on the server.
|
||||
*/
|
||||
export async function reloadDdl(path: string): Promise<void> {
|
||||
const target = useDatabase.getState().ddlFiles[path];
|
||||
if (!target) return;
|
||||
try {
|
||||
const text = await withConnection(target.id, () => call(commands.dbDdl(target.id, target.schema, target.table)));
|
||||
await call(commands.dbExportFile(path, readableDdl(text, sourceById(target.id)?.driver)));
|
||||
notifications().notify({ level: "info", title: `Reloaded the DDL of ${target.table}`, key: "db-ddl-reload" });
|
||||
} catch (e) {
|
||||
notifications().notify({ level: "error", title: `Cannot get the DDL of ${target.table}`, body: message(e) });
|
||||
}
|
||||
}
|
||||
|
||||
interface BoundStatements {
|
||||
/** The statements with their parameters' values in their text; `[]` when cancelled. */
|
||||
statements: SqlStatement[];
|
||||
|
||||
@@ -135,7 +135,7 @@ describe("table editor capabilities", () => {
|
||||
});
|
||||
const button = await screen.findByRole("button", { name: "DDL" });
|
||||
fireEvent.click(button);
|
||||
expect(backend.openDdl).toHaveBeenCalledWith("source", "public", "users");
|
||||
expect(backend.openDdl).toHaveBeenCalledWith("source", "public", "users", undefined);
|
||||
});
|
||||
|
||||
it("does not offer DDL where the source cannot report it", async () => {
|
||||
|
||||
@@ -10,6 +10,7 @@ import { focusedCellEditor } from "@/editor/api";
|
||||
import { getContext, useContextKeys } from "@/platform/context";
|
||||
import { CellEditor } from "./CellEditor";
|
||||
import { NotebookSession, notebookBackend } from "./session";
|
||||
import { lineCommentStyle, commentLine } from "@/editor/core/cm/comments";
|
||||
|
||||
type KernelEvent = Extract<IdeEvent, { type: "notebookKernel" }>;
|
||||
const kernelListeners = vi.hoisted(() => new Set<(event: KernelEvent) => void>());
|
||||
@@ -72,6 +73,27 @@ function makeSession(): NotebookSession {
|
||||
return new NotebookSession("/p/a.ipynb", backend, true);
|
||||
}
|
||||
|
||||
function withPythonCommentSpace(settings: Settings | null, addSpace: boolean): Settings {
|
||||
const current = settings ?? ({} as Settings);
|
||||
|
||||
return {
|
||||
...current,
|
||||
editor: {
|
||||
...current.editor,
|
||||
codeStyle: {
|
||||
...current.editor?.codeStyle,
|
||||
languages: {
|
||||
...current.editor?.codeStyle?.languages,
|
||||
python: {
|
||||
...current.editor?.codeStyle?.languages?.python,
|
||||
lineCommentAddSpace: addSpace,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
} as Settings;
|
||||
}
|
||||
|
||||
describe("cell editor focus", () => {
|
||||
it("tracks the focused cell so history can restore its caret", async () => {
|
||||
const session = makeSession();
|
||||
@@ -167,3 +189,75 @@ describe("cell editor indentation", () => {
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("cell editor comments", () => {
|
||||
it("follows the Python line comment style and updates it in place", async () => {
|
||||
const session = makeSession();
|
||||
await session.load();
|
||||
|
||||
const before = useProject.getState().settings;
|
||||
|
||||
// Initially disable adding a space.
|
||||
useProject.setState({
|
||||
settings: withPythonCommentSpace(before, false),
|
||||
});
|
||||
|
||||
try {
|
||||
const { container, unmount } = render(
|
||||
<CellEditor session={session} id="cell-a" source="typed text" type="code" frozen={false} />,
|
||||
);
|
||||
|
||||
const view = EditorView.findFromDOM(container.querySelector(".cm-editor")!)!;
|
||||
|
||||
// Wait until Python language support is loaded.
|
||||
await vi.waitFor(() => {
|
||||
expect(view.state.languageDataAt<{ line?: string }>("commentTokens", 0)[0]?.line).toBe("#");
|
||||
});
|
||||
|
||||
expect(view.state.facet(lineCommentStyle)).toEqual({
|
||||
atFirstColumn: false,
|
||||
addSpace: false,
|
||||
});
|
||||
|
||||
// #typed text
|
||||
act(() => {
|
||||
expect(commentLine(view)).toBe(true);
|
||||
});
|
||||
|
||||
expect(view.state.doc.toString()).toBe("#typed text");
|
||||
|
||||
// Enable adding a space without recreating the editor.
|
||||
act(() => {
|
||||
useProject.setState({
|
||||
settings: withPythonCommentSpace(before, true),
|
||||
});
|
||||
});
|
||||
|
||||
expect(EditorView.findFromDOM(container.querySelector(".cm-editor")!)).toBe(view);
|
||||
|
||||
expect(view.state.facet(lineCommentStyle)).toEqual({
|
||||
atFirstColumn: false,
|
||||
addSpace: true,
|
||||
});
|
||||
|
||||
// Uncomment.
|
||||
act(() => {
|
||||
commentLine(view);
|
||||
});
|
||||
|
||||
expect(view.state.doc.toString()).toBe("typed text");
|
||||
|
||||
// Comment again: # typed text
|
||||
act(() => {
|
||||
commentLine(view);
|
||||
});
|
||||
|
||||
expect(view.state.doc.toString()).toBe("# typed text");
|
||||
|
||||
unmount();
|
||||
} finally {
|
||||
useProject.setState({ settings: before });
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -27,6 +27,8 @@ import { seamlessSelection } from "@/editor/core/cm/selectionLayer";
|
||||
import { multiCaretMouse } from "@/editor/core/cm/multiCaret";
|
||||
import { findLanguageDescription, languageInfo, loadSupport } from "@/editor/core/cm/languages";
|
||||
import { effectiveIndent, indentExtension, tooltipBounds } from "@/editor/core/cm/setup";
|
||||
import { lineCommentStyle } from "@/editor/core/cm/comments";
|
||||
import { editorPrefs, lineCommentStyleFor } from "@/platform/editorSettings";
|
||||
import { useProject } from "@/platform/project";
|
||||
import type { EditorSettings } from "@/platform/ipc";
|
||||
import { tx } from "@/platform/i18n";
|
||||
@@ -75,6 +77,7 @@ export function CellEditor({
|
||||
const host = useRef<HTMLDivElement>(null);
|
||||
const view = useRef<EditorView | null>(null);
|
||||
const editorSettings = useProject((s) => s.settings?.editor);
|
||||
const comments = useRef(new Compartment());
|
||||
const indent = useRef(new Compartment());
|
||||
const readonly = useRef(new Compartment());
|
||||
const services = useRef(new Compartment());
|
||||
@@ -129,6 +132,14 @@ export function CellEditor({
|
||||
redo: () => void session.redo().catch((e) => session.report(e)),
|
||||
}),
|
||||
embeddedEditorExtensions(session.path),
|
||||
comments.current.of(
|
||||
lineCommentStyle.of(
|
||||
lineCommentStyleFor(
|
||||
editorPrefs({ editor: useProject.getState().settings?.editor }),
|
||||
type === "code" ? "python" : undefined,
|
||||
),
|
||||
),
|
||||
),
|
||||
language.of([]),
|
||||
services.current.of(languageServices(type, initialDoc.current)),
|
||||
readonly.current.of(EditorState.readOnly.of(session.getState().frozen)),
|
||||
@@ -217,6 +228,15 @@ export function CellEditor({
|
||||
}
|
||||
editor.focus();
|
||||
}, [reveal, id, session]);
|
||||
useLayoutEffect(() => {
|
||||
view.current?.dispatch({
|
||||
effects: comments.current.reconfigure(
|
||||
lineCommentStyle.of(
|
||||
lineCommentStyleFor(editorPrefs({ editor: editorSettings }), type === "code" ? "python" : undefined),
|
||||
),
|
||||
),
|
||||
});
|
||||
}, [editorSettings, type]);
|
||||
return <div ref={host} className={styles.cellEditor} />;
|
||||
}
|
||||
|
||||
|
||||
@@ -185,3 +185,11 @@
|
||||
inset: 0;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
/* Corner mark on the 16px stack. Inline width/height beat --oi-tree-icon-size. */
|
||||
.typeBadge {
|
||||
position: absolute;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
pointer-events: none;
|
||||
}
|
||||
@@ -19,6 +19,7 @@ import { MessagesHost } from "@/workbench/messages";
|
||||
import { FileRefactorDialogHost } from "./FileRefactorDialogs";
|
||||
import { setRefactorBackendForTests } from "./fileRefactor";
|
||||
import { ProjectView, formatFileDetails } from "./ProjectView";
|
||||
import styles from "./ProjectView.module.css";
|
||||
import { beginNew, beginRename, canPaste } from "./operations";
|
||||
import { initProjectTree, selectModel, setSelection, setViewOption, useProjectTree } from "./store";
|
||||
import type { OutlineItem } from "@/bindings";
|
||||
@@ -29,7 +30,7 @@ import { clearLineTokens } from "@/editor/lineTokens";
|
||||
import { ProjectHeaderActions, useProjectHeaderMenu } from "./HeaderActions";
|
||||
import { executeAction, getAction } from "@/platform/actions";
|
||||
import { useProject } from "@/platform/project";
|
||||
import type { MenuItem } from "@/ui";
|
||||
import { FILES_DRAG, registerDropTarget, type MenuItem } from "@/ui";
|
||||
import { loadOutline } from "./store";
|
||||
|
||||
const ipc = vi.hoisted(() => ({
|
||||
@@ -763,7 +764,127 @@ describe("ProjectView", () => {
|
||||
tree.scrollLeft = 600;
|
||||
fireEvent.scroll(tree);
|
||||
expect(tree.scrollLeft).toBe(0);
|
||||
expect(tree.style.overflowX).toBe("hidden");
|
||||
act(() => void window.dispatchEvent(new MouseEvent("pointerup", { bubbles: true })));
|
||||
expect(tree.style.overflowX).toBe("");
|
||||
});
|
||||
|
||||
it("keeps the horizontal overlay thumb still when a drag leaves the tree", async () => {
|
||||
const { tree, row, rows } = setup();
|
||||
await waitFor(() => expect(rows()).toContain("README.md"));
|
||||
let scrollLeft = 120;
|
||||
Object.defineProperties(tree, {
|
||||
clientWidth: { configurable: true, value: 200 },
|
||||
scrollWidth: { configurable: true, value: 800 },
|
||||
offsetLeft: { configurable: true, value: 0 },
|
||||
scrollLeft: {
|
||||
configurable: true,
|
||||
get: () => scrollLeft,
|
||||
set: (value: number) => void (scrollLeft = value),
|
||||
},
|
||||
});
|
||||
document.elementFromPoint = () => null;
|
||||
const flushFrame = () => act(() => new Promise<void>((resolve) => requestAnimationFrame(() => resolve())));
|
||||
fireEvent.scroll(tree);
|
||||
await flushFrame();
|
||||
const bar = document.querySelector<HTMLElement>("[data-horizontal-scrollbar]")!;
|
||||
const thumb = bar.firstElementChild as HTMLElement;
|
||||
const before = { active: bar.getAttribute("data-active"), transform: thumb.style.transform, left: tree.scrollLeft };
|
||||
expect(before.active).toBe("");
|
||||
fireEvent(
|
||||
row("README.md").querySelector("[data-project-path]")!,
|
||||
new MouseEvent("pointerdown", { bubbles: true, button: 0 }),
|
||||
);
|
||||
act(() => void window.dispatchEvent(new MouseEvent("pointermove", { buttons: 1, clientX: 40, clientY: 0 })));
|
||||
// WebKit's autoscroll toward a pointer heading for the terminal.
|
||||
tree.scrollLeft = 600;
|
||||
fireEvent.scroll(tree);
|
||||
await flushFrame();
|
||||
expect({
|
||||
active: bar.getAttribute("data-active"),
|
||||
transform: thumb.style.transform,
|
||||
left: tree.scrollLeft,
|
||||
overflowX: tree.style.overflowX,
|
||||
}).toEqual({ ...before, overflowX: "hidden" });
|
||||
act(() => void window.dispatchEvent(new MouseEvent("pointerup", { bubbles: true })));
|
||||
expect(tree.style.overflowX).toBe("");
|
||||
expect(tree.scrollLeft).toBe(before.left);
|
||||
});
|
||||
|
||||
it("drags an attached project root to a drop target outside the tree", async () => {
|
||||
fs = new MemoryFs({ "/w/acme/src/App.kt": "x", "/w/acme/README.md": "x", "/w/lib/Program.cs": "x" }, ROOT);
|
||||
setProjectFsForTests(fs, ROOT);
|
||||
initProjectTree(ROOT, "acme", [ROOT, "/w/lib"]);
|
||||
const { tree, row, rows } = setup();
|
||||
await waitFor(() => expect(rows().some((r) => r?.startsWith("lib"))).toBe(true));
|
||||
// The terminal, an editor or an agent composer: a target of the same kind, outside the tree.
|
||||
const outside = document.createElement("div");
|
||||
document.body.appendChild(outside);
|
||||
const dropped: string[] = [];
|
||||
const unregister = registerDropTarget(outside, {
|
||||
accepts: (type) => type === FILES_DRAG,
|
||||
over: () => {},
|
||||
leave: () => {},
|
||||
drop: (data) => dropped.push(data.payload),
|
||||
});
|
||||
document.elementFromPoint = () => outside;
|
||||
try {
|
||||
fireEvent(
|
||||
row("lib").querySelector("[data-project-path]")!,
|
||||
new MouseEvent("pointerdown", { bubbles: true, button: 0 }),
|
||||
);
|
||||
act(() => void window.dispatchEvent(new MouseEvent("pointermove", { buttons: 1, clientX: 400, clientY: 0 })));
|
||||
// WebKit's autoscroll of the pressed scroll container: a root drag holds the tree still too.
|
||||
tree.scrollLeft = 600;
|
||||
tree.scrollTop = 40;
|
||||
fireEvent.scroll(tree);
|
||||
act(() => void window.dispatchEvent(new MouseEvent("pointerup", { bubbles: true, clientX: 400, clientY: 0 })));
|
||||
// Folders carry the trailing slash `findDirs` reads; a drop target strips it.
|
||||
expect({ dropped, scrollLeft: tree.scrollLeft, scrollTop: tree.scrollTop }).toEqual({
|
||||
dropped: ["/w/lib/"],
|
||||
scrollLeft: 0,
|
||||
scrollTop: 0,
|
||||
});
|
||||
// Outside the window a root is still not a file set to hand to another app: copying a
|
||||
// whole project out on a drag is not something a drop on a terminal asks for.
|
||||
dragOut.canDragOut.mockReturnValue(true);
|
||||
fireEvent(
|
||||
row("lib").querySelector("[data-project-path]")!,
|
||||
new MouseEvent("pointerdown", { bubbles: true, button: 0 }),
|
||||
);
|
||||
act(
|
||||
() =>
|
||||
void window.dispatchEvent(
|
||||
new MouseEvent("pointermove", { buttons: 1, clientX: window.innerWidth + 5, clientY: 0 }),
|
||||
),
|
||||
);
|
||||
expect(dragOut.dragOut).not.toHaveBeenCalled();
|
||||
act(() => void window.dispatchEvent(new MouseEvent("pointerup", { bubbles: true })));
|
||||
} finally {
|
||||
dragOut.canDragOut.mockReturnValue(false);
|
||||
unregister();
|
||||
outside.remove();
|
||||
}
|
||||
});
|
||||
|
||||
it("does not offer to move an attached project root inside the tree", async () => {
|
||||
fs = new MemoryFs({ "/w/acme/src/App.kt": "x", "/w/lib/Program.cs": "x" }, ROOT);
|
||||
setProjectFsForTests(fs, ROOT);
|
||||
initProjectTree(ROOT, "acme", [ROOT, "/w/lib"]);
|
||||
const { row, rows } = setup();
|
||||
await waitFor(() => expect(rows().some((r) => r?.startsWith("lib"))).toBe(true));
|
||||
// A folder of the other project: not below the dragged root, so only the "roots are not
|
||||
// moved inside the tree" rule keeps this from being an in-tree drop.
|
||||
await waitFor(() => expect(rows().some((r) => r?.startsWith("src"))).toBe(true));
|
||||
const target = row("src").querySelector<HTMLElement>("[data-project-path]")!;
|
||||
document.elementFromPoint = () => target;
|
||||
fireEvent(
|
||||
row("lib").querySelector("[data-project-path]")!,
|
||||
new MouseEvent("pointerdown", { bubbles: true, button: 0 }),
|
||||
);
|
||||
act(() => void window.dispatchEvent(new MouseEvent("pointermove", { buttons: 1, clientX: 40, clientY: 10 })));
|
||||
expect(target.className).not.toContain(styles.dropTarget);
|
||||
act(() => void window.dispatchEvent(new MouseEvent("pointerup", { bubbles: true, clientX: 40, clientY: 10 })));
|
||||
});
|
||||
|
||||
it("hands the selected files to an OS drag once the pointer leaves the window", async () => {
|
||||
|
||||
@@ -76,7 +76,7 @@ import {
|
||||
} from "@/platform/projectPresentation";
|
||||
import { relativePath, useProject } from "@/platform/project";
|
||||
import { folderKind } from "./folderKind";
|
||||
import { PROJECT_TYPES } from "@/ui/projectType";
|
||||
import { PROJECT_TYPES, projectTypeFolderBadge } from "@/ui/projectType";
|
||||
import { useHomeDir } from "./home";
|
||||
import {
|
||||
compareNames,
|
||||
@@ -361,9 +361,10 @@ const Row = memo(function Row({
|
||||
? isConfiguredLibraryDirectory(node.path, root, validateProjectStructure(s.settings?.projectStructure).libraries)
|
||||
: false,
|
||||
);
|
||||
const typeBadge = !deco.icon && projectType ? projectTypeFolderBadge(projectType) : undefined;
|
||||
const icon =
|
||||
deco.icon ??
|
||||
(projectType
|
||||
(projectType && !typeBadge
|
||||
? PROJECT_TYPES[projectType].icon
|
||||
: node.dir || node.placeholder || node.icon
|
||||
? iconFor(node, roots, root, build, detected, expanded, holdsOpen, libraryDir)
|
||||
@@ -382,6 +383,7 @@ const Row = memo(function Row({
|
||||
data-project-path={node.placeholder ? undefined : node.path}
|
||||
data-project-key={node.key}
|
||||
data-project-icon={icon}
|
||||
data-project-type-badge={typeBadge}
|
||||
data-dir={node.dir || undefined}
|
||||
title={deco.tooltip ?? hint ?? undefined}
|
||||
onClick={(e) => onClick(node, e)}
|
||||
@@ -394,6 +396,15 @@ const Row = memo(function Row({
|
||||
size={16}
|
||||
className={clsx(styles.icon, node.dir && styles.folderIcon, dimIcon && styles.faded)}
|
||||
/>
|
||||
{typeBadge && projectType && (
|
||||
<Icon
|
||||
name={typeBadge}
|
||||
size={8}
|
||||
className={clsx(styles.typeBadge, dimIcon && styles.faded)}
|
||||
style={{ width: 8, height: 8 }}
|
||||
label={PROJECT_TYPES[projectType].name}
|
||||
/>
|
||||
)}
|
||||
{/* IDEA's symlink arrow, on file and folder links (the entry kind comes with the listing). */}
|
||||
{node.symlink && <Icon name="symlink-mark" size={16} className={styles.overlay} label="Symbolic link" />}
|
||||
{!!file?.runnable && icon !== "spring-boot" && icon !== "jvm-test" && (
|
||||
@@ -742,20 +753,14 @@ export function ProjectView() {
|
||||
|
||||
const onRowPointerDown = useCallback((node: ProjectNode, e: ReactPointerEvent) => {
|
||||
if (e.button === 0) dragged.current = false;
|
||||
if (
|
||||
e.button !== 0 ||
|
||||
node.member ||
|
||||
node.root ||
|
||||
node.placeholder ||
|
||||
node.readOnly ||
|
||||
useProjectTree.getState().editing
|
||||
)
|
||||
return;
|
||||
if (e.button !== 0 || node.member || node.placeholder || node.readOnly || useProjectTree.getState().editing) return;
|
||||
const before = useProjectTree.getState().selected;
|
||||
const lead = useProjectTree.getState().lead;
|
||||
const startX = e.clientX,
|
||||
startY = e.clientY;
|
||||
let active = false;
|
||||
// The rows the drag started on, roots included: they name the drag and fill its payload.
|
||||
let nodes: ProjectNode[] = [];
|
||||
let paths: string[] = [];
|
||||
// What an OS drag out of the window carries: groups ("External Libraries") have no folder.
|
||||
let outPaths: string[] = [];
|
||||
@@ -768,10 +773,18 @@ export function ProjectView() {
|
||||
// (IDEA's DnD autoscroll). Leaving the tree toward a drop target elsewhere (the terminal,
|
||||
// an editor) keeps it where it is: WebKit's own autoscroll of the pressed scroll container
|
||||
// would otherwise keep scrolling it toward the pointer. It never scrolls sideways: a pointer
|
||||
// right of the tree would scroll its long rows out of view.
|
||||
// right of the tree would scroll its long rows out of view, and the same autoscroll would
|
||||
// jump the horizontal overlay thumb back and forth as keep() snapped scrollLeft back.
|
||||
const scroller = containerRef.current?.querySelector<HTMLElement>('[role="tree"]') ?? null;
|
||||
let held = scroller?.scrollTop ?? 0;
|
||||
const heldLeft = scroller?.scrollLeft ?? 0;
|
||||
let overflowLocked = false;
|
||||
const setOverflowX = (value: string) => {
|
||||
if (!scroller) return;
|
||||
const left = scroller.scrollLeft;
|
||||
scroller.style.overflowX = value;
|
||||
scroller.scrollLeft = left;
|
||||
};
|
||||
let pointer: { x: number; y: number } | null = null;
|
||||
let frame = 0;
|
||||
const inside = (p: { x: number; y: number }) => {
|
||||
@@ -794,7 +807,11 @@ export function ProjectView() {
|
||||
held = scroller.scrollTop;
|
||||
if (held !== before) {
|
||||
const target = folderAt(containerRef.current, pointer.x, pointer.y);
|
||||
setDropTarget(target && !paths.some((p) => target.path === p || isInside(target.path, p)) ? target.key : null);
|
||||
setDropTarget(
|
||||
paths.length && target && !paths.some((p) => target.path === p || isInside(target.path, p))
|
||||
? target.key
|
||||
: null,
|
||||
);
|
||||
frame = requestAnimationFrame(edgeScroll);
|
||||
}
|
||||
};
|
||||
@@ -812,14 +829,23 @@ export function ProjectView() {
|
||||
const m = selectModel(useProjectTree.getState());
|
||||
const keys = before.has(node.key) ? [...before] : [node.key];
|
||||
if (before.has(node.key)) setSelection(before, lead);
|
||||
const nodes = keys.map((k) => m.byKey.get(k)).filter((n): n is ProjectNode => !!n && !n.root && !n.placeholder);
|
||||
paths = nodes.map((n) => n.path);
|
||||
outPaths = nodes.filter((n) => !n.group).map((n) => n.path);
|
||||
if (!paths.length) return cleanup();
|
||||
nodes = keys.map((k) => m.byKey.get(k)).filter((n): n is ProjectNode => !!n && !n.placeholder);
|
||||
// A project root is a folder to a target outside the tree (the terminal, an editor, an
|
||||
// agent composer), and PyCharm drags it the same way; moving one inside the tree is not a
|
||||
// move we make, so it stays out of what an in-tree drop moves and out of an OS drag.
|
||||
paths = nodes.filter((n) => !n.root).map((n) => n.path);
|
||||
outPaths = nodes.filter((n) => !n.group && !n.root).map((n) => n.path);
|
||||
if (!nodes.length) return cleanup();
|
||||
files = dragSession({
|
||||
type: FILES_DRAG,
|
||||
payload: nodes.map((n) => (n.dir ? `${n.path}/` : n.path)).join("\n"),
|
||||
});
|
||||
// WebKit will not autoscroll a hidden axis, so the overlay thumb stays put
|
||||
// instead of tracking the autoscroll/keep() fight (#7155).
|
||||
if (!overflowLocked) {
|
||||
overflowLocked = true;
|
||||
setOverflowX("hidden");
|
||||
}
|
||||
}
|
||||
// Leaving the window hands the files to an OS drag: the app they land on copies them.
|
||||
const viewport = { left: 0, top: 0, right: window.innerWidth, bottom: window.innerHeight };
|
||||
@@ -834,13 +860,13 @@ export function ProjectView() {
|
||||
keep();
|
||||
if (!frame) frame = requestAnimationFrame(edgeScroll);
|
||||
const target = folderAt(containerRef.current, ev.clientX, ev.clientY);
|
||||
const valid = target && !paths.some((p) => target.path === p || isInside(target.path, p));
|
||||
const valid = paths.length > 0 && target && !paths.some((p) => target.path === p || isInside(target.path, p));
|
||||
setDropTarget(valid ? target.key : null);
|
||||
if (target) files?.cancel();
|
||||
else files?.move(ev.clientX, ev.clientY);
|
||||
setDrag({
|
||||
paths,
|
||||
label: paths.length === 1 ? nameOf(paths[0]!) : tx`${paths.length} items`,
|
||||
label: nodes.length === 1 ? nameOf(nodes[0]!.path) : tx`${nodes.length} items`,
|
||||
x: ev.clientX,
|
||||
y: ev.clientY,
|
||||
copy: ev.altKey,
|
||||
@@ -867,6 +893,10 @@ export function ProjectView() {
|
||||
cancelAnimationFrame(frame);
|
||||
frame = 0;
|
||||
pointer = null;
|
||||
if (overflowLocked) {
|
||||
overflowLocked = false;
|
||||
setOverflowX("");
|
||||
}
|
||||
window.removeEventListener("pointermove", move);
|
||||
window.removeEventListener("pointerup", up);
|
||||
window.removeEventListener("pointercancel", cleanup);
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||
import { render, screen, waitFor, within } from "@testing-library/react";
|
||||
import { provideEditorService, type EditorService } from "@/workbench/contributions";
|
||||
import { activate } from "./index";
|
||||
import { MemoryFs, setProjectFsForTests } from "./fs";
|
||||
import { ProjectView } from "./ProjectView";
|
||||
import { initProjectTree, useProjectTree } from "./store";
|
||||
import type { ProjectType } from "@/ui/projectType";
|
||||
|
||||
const WORKSPACE = "/workspace";
|
||||
const APP = "/code/app";
|
||||
const PY = "/code/python-service";
|
||||
const MAVEN = "/code/auth";
|
||||
|
||||
let dispose: () => void = () => {};
|
||||
|
||||
beforeEach(() => {
|
||||
setProjectFsForTests(
|
||||
new MemoryFs(
|
||||
{
|
||||
[`${APP}/README.md`]: "x",
|
||||
[`${PY}/pyproject.toml`]: "[project]\nname = 'python-service'\n",
|
||||
[`${PY}/main.py`]: "x",
|
||||
[`${MAVEN}/pom.xml`]: "x",
|
||||
[`${WORKSPACE}/.openidea/workspace.json`]: "{}",
|
||||
},
|
||||
WORKSPACE,
|
||||
),
|
||||
WORKSPACE,
|
||||
);
|
||||
provideEditorService({ openFile: async () => {}, activePath: () => null } as unknown as EditorService);
|
||||
dispose = activate();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
dispose();
|
||||
setProjectFsForTests(null);
|
||||
});
|
||||
|
||||
const contentOf = (path: string) => document.querySelector(`[data-project-path="${path}"]`);
|
||||
const iconOf = (path: string) => contentOf(path)?.getAttribute("data-project-icon");
|
||||
const badgeOf = (path: string) => contentOf(path)?.getAttribute("data-project-type-badge");
|
||||
|
||||
function seedTypes(types: ReadonlyArray<readonly [string, ProjectType]>) {
|
||||
useProjectTree.setState({ projectTypes: new Map(types) });
|
||||
}
|
||||
|
||||
describe("attached project root icons", () => {
|
||||
it("keeps a folder icon and a small Python badge on an attached Python root", async () => {
|
||||
initProjectTree(WORKSPACE, "Workspace", [APP, PY]);
|
||||
seedTypes([
|
||||
[APP, "node"],
|
||||
[PY, "python"],
|
||||
]);
|
||||
render(<ProjectView />);
|
||||
const tree = screen.getByRole("tree", { name: "Project" });
|
||||
await waitFor(() => expect(contentOf(PY)).not.toBeNull());
|
||||
expect(within(tree).getByText("python-service")).toBeInTheDocument();
|
||||
|
||||
expect(iconOf(PY)).toBe("module");
|
||||
expect(badgeOf(PY)).toBe("file-python");
|
||||
const badge = contentOf(PY)?.querySelector('[aria-label="Python"]');
|
||||
expect(badge).not.toBeNull();
|
||||
expect(badge).toHaveAttribute("width", "8");
|
||||
expect(badge).toHaveAttribute("height", "8");
|
||||
|
||||
// Other file-type logos follow the same rule; they must not replace the folder.
|
||||
expect(iconOf(APP)).toBe("module");
|
||||
expect(badgeOf(APP)).toBe("file-npm");
|
||||
});
|
||||
|
||||
it("still uses a dedicated Maven project icon on an attached Maven root", async () => {
|
||||
initProjectTree(WORKSPACE, "Workspace", [APP, MAVEN, PY]);
|
||||
seedTypes([
|
||||
[APP, "node"],
|
||||
[MAVEN, "maven"],
|
||||
[PY, "python"],
|
||||
]);
|
||||
render(<ProjectView />);
|
||||
await waitFor(() => expect(contentOf(MAVEN)).not.toBeNull());
|
||||
expect(iconOf(MAVEN)).toBe("maven-project");
|
||||
expect(badgeOf(MAVEN)).toBeNull();
|
||||
expect(iconOf(PY)).toBe("module");
|
||||
expect(badgeOf(PY)).toBe("file-python");
|
||||
});
|
||||
|
||||
it("does not badge a standalone Python project root", async () => {
|
||||
setProjectFsForTests(new MemoryFs({ [`${PY}/pyproject.toml`]: "[project]\nname = 'python-service'\n" }, PY), PY);
|
||||
initProjectTree(PY, "python-service");
|
||||
seedTypes([[PY, "python"]]);
|
||||
render(<ProjectView />);
|
||||
await waitFor(() => expect(contentOf(PY)).not.toBeNull());
|
||||
expect(iconOf(PY)).toBe("module");
|
||||
expect(badgeOf(PY)).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -40,7 +40,7 @@ describe("buildModel", () => {
|
||||
const base: Listings = listings({
|
||||
"/r": [
|
||||
entry("/r/src", "dir"),
|
||||
entry("/r/build", "dir", { ignored: true }),
|
||||
entry("/r/build", "dir", { ignored: true, excluded: true }),
|
||||
entry("/r/.git", "dir", { hidden: true }),
|
||||
entry("/r/.gitignore"),
|
||||
entry("/r/README.md"),
|
||||
@@ -56,9 +56,16 @@ describe("buildModel", () => {
|
||||
expect(m.byKey.get("/r/build")?.ignored).toBe(true);
|
||||
});
|
||||
|
||||
it("filters IDE-hidden names and excluded entries by option", () => {
|
||||
it("filters IDE-hidden names and excluded entries by option, keeping git-ignored files", () => {
|
||||
const opts: TreeOptions = { ...DEFAULT_TREE_OPTIONS, showHidden: true, showExcluded: false };
|
||||
expect(labels(buildModel(ROOT, base, opts), "/r")).toEqual(["src", ".git", ".gitignore", "README.md"]);
|
||||
const withIgnored = listings({ "/r": [...base.get("/r")!, entry("/r/local.sqlite3", "file", { ignored: true })] });
|
||||
expect(labels(buildModel(ROOT, withIgnored, opts), "/r")).toEqual([
|
||||
"src",
|
||||
".git",
|
||||
".gitignore",
|
||||
"README.md",
|
||||
"local.sqlite3",
|
||||
]);
|
||||
});
|
||||
|
||||
it("sorts names naturally, optionally mixing folders and files", () => {
|
||||
|
||||
@@ -110,7 +110,8 @@ export function isVisible(entry: FileEntry, opts: TreeOptions): boolean {
|
||||
if (!unrealPathVisible(entry.path, opts)) return false;
|
||||
// Ignored names are also excluded on the backend; only "Show Hidden" brings them back.
|
||||
if (isIgnoredName(entry.name)) return opts.showHidden;
|
||||
if (!opts.showExcluded && entry.ignored) return false;
|
||||
// Git-ignored files stay visible (dimmed); the option hides only excluded ones.
|
||||
if (!opts.showExcluded && entry.excluded) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { hasIcon } from "@/ui/icons";
|
||||
import { detectProjectType, isProjectMarker, PROJECT_TYPES } from "@/ui/projectType";
|
||||
import { detectProjectType, isProjectMarker, PROJECT_TYPES, projectTypeFolderBadge } from "@/ui/projectType";
|
||||
|
||||
describe("project types", () => {
|
||||
it.each([
|
||||
@@ -67,6 +67,19 @@ describe("project types", () => {
|
||||
it("has an existing SVG for every project type", () => {
|
||||
for (const { icon } of Object.values(PROJECT_TYPES)) expect(hasIcon(icon), icon).toBe(true);
|
||||
});
|
||||
it("uses file-type logos as folder badges and keeps dedicated project icons", () => {
|
||||
const badges = (Object.keys(PROJECT_TYPES) as (keyof typeof PROJECT_TYPES)[]).filter((id) =>
|
||||
projectTypeFolderBadge(id),
|
||||
);
|
||||
const replacements = (Object.keys(PROJECT_TYPES) as (keyof typeof PROJECT_TYPES)[]).filter(
|
||||
(id) => !projectTypeFolderBadge(id),
|
||||
);
|
||||
expect(replacements).toEqual(["flutter", "vite", "gradle", "maven"]);
|
||||
expect(badges).toContain("python");
|
||||
for (const id of badges) expect(PROJECT_TYPES[id].icon.startsWith("file-")).toBe(true);
|
||||
for (const id of replacements) expect(PROJECT_TYPES[id].icon.startsWith("file-")).toBe(false);
|
||||
expect(projectTypeFolderBadge("python")).toBe("file-python");
|
||||
});
|
||||
it.each(Object.entries(PROJECT_TYPES))("derives %s detection and refresh from its registry entry", (id, type) => {
|
||||
const required = "requires" in type ? type.requires : [];
|
||||
for (const marker of required) expect(isProjectMarker(marker)).toBe(true);
|
||||
|
||||
@@ -525,12 +525,15 @@ it("keeps the primary first and sorts attachments by name", () => {
|
||||
});
|
||||
|
||||
describe("a file the view options hide", () => {
|
||||
const entry = (name: string, ignored = false) => ({ name, path: `/p/${name}`, isDir: true, ignored }) as never;
|
||||
const entry = (name: string, excluded = false) =>
|
||||
({ name, path: `/p/${name}`, isDir: true, ignored: excluded, excluded }) as never;
|
||||
|
||||
it("names the option that hides it below the shown ancestor, and offers to turn it on", () => {
|
||||
useProjectTree.setState({ listings: new Map([["/p", [entry("build", true), entry("src")]]]) });
|
||||
const gitIgnored = { name: "certs", path: "/p/certs", isDir: true, ignored: true, excluded: false } as never;
|
||||
useProjectTree.setState({ listings: new Map([["/p", [entry("build", true), entry("src"), gitIgnored]]]) });
|
||||
setViewOption("showExcluded", false);
|
||||
expect(hidingOption("/p/build/out.txt", "/p")).toBe("showExcluded");
|
||||
expect(hidingOption("/p/certs/dev.pem", "/p")).toBeNull();
|
||||
expect(hidingOption("/p/.git/config", "/p")).toBe(
|
||||
useProjectTree.getState().options.showHidden ? null : "showHidden",
|
||||
);
|
||||
|
||||
@@ -1003,7 +1003,7 @@ function groupAncestors(model: TreeModel, key: string): string[] {
|
||||
|
||||
/**
|
||||
* The view option that hides `path` below its shown ancestor `shown`: a hidden name
|
||||
* (Show Hidden Files) or an ignored entry (Show Excluded Files). Null when no option does.
|
||||
* (Show Hidden Files) or an excluded entry (Show Excluded Files). Null when no option does.
|
||||
*/
|
||||
export function hidingOption(path: string, shown: string): "showHidden" | "showExcluded" | null {
|
||||
const { listings, options } = get();
|
||||
@@ -1011,7 +1011,7 @@ export function hidingOption(path: string, shown: string): "showHidden" | "showE
|
||||
let dir = shown;
|
||||
for (const name of path.slice(shown.length + 1).split("/")) {
|
||||
if (isIgnoredName(name)) return options.showHidden ? null : "showHidden";
|
||||
if (listings.get(dir)?.find((e) => e.name === name)?.ignored) return options.showExcluded ? null : "showExcluded";
|
||||
if (listings.get(dir)?.find((e) => e.name === name)?.excluded) return options.showExcluded ? null : "showExcluded";
|
||||
dir = `${dir}/${name}`;
|
||||
}
|
||||
return null;
|
||||
|
||||
@@ -63,7 +63,7 @@ vi.mock("../find/windowStore", async (orig) => ({
|
||||
const contributions = await import("@/workbench/contributions");
|
||||
const { commands, emitLocalIdeEvent } = await import("@/platform/ipc");
|
||||
const { ContextMenuHost } = await import("@/ui");
|
||||
const { RecentPopupsOverlay } = await import("../recent/RecentPopups");
|
||||
const { RecentPopupsOverlay, RECENT_FILES_SIZE_KEY } = await import("../recent/RecentPopups");
|
||||
const { cycleSwitcher, showRecentPopup, hideRecentPopup, useRecentPopup } = await import("../recent/store");
|
||||
const { openLocation } = await import("../common/open");
|
||||
const { usePlatform } = await import("@/platform/platformInfo");
|
||||
@@ -86,6 +86,7 @@ beforeEach(() => {
|
||||
textSearch.mockClear();
|
||||
useFindPopup.setState({ caseSensitive: false, wholeWord: false, isRegex: false });
|
||||
localStorage.removeItem(TEXT_SEARCH_OPTIONS_KEY);
|
||||
localStorage.removeItem(RECENT_FILES_SIZE_KEY);
|
||||
vi.mocked(openLocation).mockClear();
|
||||
});
|
||||
|
||||
@@ -850,6 +851,57 @@ describe("Recent Files database consoles", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("Recent Files window chrome", () => {
|
||||
afterEach(() => vi.restoreAllMocks());
|
||||
|
||||
it("drags and resizes, and keeps the path only in the footer", async () => {
|
||||
const path = "/p/src/Orders.java";
|
||||
vi.spyOn(commands, "recentFiles").mockResolvedValue({ status: "ok", data: [path] });
|
||||
render(<RecentPopupsOverlay />);
|
||||
act(() => showRecentPopup("files"));
|
||||
await tick();
|
||||
|
||||
const dialog = screen.getByRole("dialog", { name: "Recent Files" });
|
||||
const header = dialog.querySelector<HTMLElement>("[data-dialog-drag]")!;
|
||||
fireEvent.pointerDown(header, { button: 0, clientX: 10, clientY: 10 });
|
||||
fireEvent.pointerMove(window, { buttons: 1, clientX: 60, clientY: 40 });
|
||||
fireEvent.pointerUp(window);
|
||||
expect(dialog.style.translate).not.toBe("");
|
||||
|
||||
fireEvent.pointerDown(screen.getByRole("separator", { name: "Resize" }), {
|
||||
button: 0,
|
||||
clientX: 0,
|
||||
clientY: 0,
|
||||
});
|
||||
fireEvent.pointerMove(window, { buttons: 1, clientX: 500, clientY: 300 });
|
||||
fireEvent.pointerUp(window);
|
||||
expect([dialog.style.width, dialog.style.height]).toEqual(["560px", "300px"]);
|
||||
|
||||
expect(within(dialog).getByText("Orders.java")).toBeInTheDocument();
|
||||
expect(within(dialog).queryByText("src")).toBeNull();
|
||||
expect(dialog.querySelector("footer")!).toHaveTextContent(path);
|
||||
|
||||
act(() => hideRecentPopup());
|
||||
act(() => showRecentPopup("files"));
|
||||
await tick();
|
||||
const reopened = screen.getByRole("dialog", { name: "Recent Files" });
|
||||
expect([reopened.style.width, reopened.style.height]).toEqual(["560px", "300px"]);
|
||||
});
|
||||
|
||||
it("shows the directory only beside files that share a name", async () => {
|
||||
vi.spyOn(commands, "recentFiles").mockResolvedValue({
|
||||
status: "ok",
|
||||
data: ["/p/src/a/index.ts", "/p/src/b/index.ts", "/p/src/Orders.java"],
|
||||
});
|
||||
render(<RecentPopupsOverlay />);
|
||||
act(() => showRecentPopup("files"));
|
||||
await tick();
|
||||
|
||||
const rows = within(screen.getByRole("listbox", { name: "Recent files" })).getAllByRole("option");
|
||||
expect(rows.map((r) => r.textContent)).toEqual(["index.ts/p/src/a", "index.ts/p/src/b", "Orders.java"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Switcher", () => {
|
||||
afterEach(() => vi.restoreAllMocks());
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
.dialog {
|
||||
--rp-bg-chrome: var(--bg-frame, var(--bg-app));
|
||||
container-type: inline-size;
|
||||
max-height: 80vh;
|
||||
max-height: 100%;
|
||||
background: var(--bg-popup, var(--bg-elev));
|
||||
}
|
||||
.dialog > :global([data-dialog-body]) {
|
||||
@@ -21,12 +21,16 @@
|
||||
color: var(--fg);
|
||||
}
|
||||
.title {
|
||||
flex: none;
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
color: var(--fg-strong);
|
||||
font-weight: 600;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.speed {
|
||||
flex: 1;
|
||||
flex: 0 1 240px;
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
@@ -43,6 +47,7 @@
|
||||
}
|
||||
.speedActive,
|
||||
.speedWide {
|
||||
margin-left: auto;
|
||||
background: var(--bg-input);
|
||||
box-shadow: inset 0 0 0 1px var(--border);
|
||||
}
|
||||
@@ -78,6 +83,7 @@
|
||||
}
|
||||
.columns {
|
||||
display: flex;
|
||||
flex: 1 1 auto;
|
||||
height: 440px;
|
||||
min-height: 0;
|
||||
outline: none;
|
||||
@@ -155,13 +161,6 @@
|
||||
.locationName {
|
||||
flex: 0 1 auto;
|
||||
}
|
||||
.dir {
|
||||
flex: 0 1000 auto;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
color: var(--fg-subtle);
|
||||
}
|
||||
.shortcut {
|
||||
flex: none;
|
||||
color: var(--fg-subtle);
|
||||
@@ -193,6 +192,13 @@
|
||||
.locationName {
|
||||
font-weight: 600;
|
||||
}
|
||||
.dir {
|
||||
flex: 0 1000 auto;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
color: var(--fg-subtle);
|
||||
}
|
||||
.changed {
|
||||
flex: none;
|
||||
margin-left: auto;
|
||||
|
||||
@@ -52,6 +52,7 @@ import {
|
||||
lineSegments,
|
||||
locationBreadcrumb,
|
||||
locationTime,
|
||||
sharedFileNames,
|
||||
switcherItems,
|
||||
switcherPaths,
|
||||
switcherSelection,
|
||||
@@ -100,6 +101,34 @@ const afterClose = (fn: () => void, takesFocus = false) => {
|
||||
fn();
|
||||
};
|
||||
|
||||
export const RECENT_FILES_SIZE_KEY = "openidea.recentFiles.size";
|
||||
|
||||
function readFilesSize(): { w: number; h: number } | null {
|
||||
try {
|
||||
const raw = localStorage.getItem(RECENT_FILES_SIZE_KEY);
|
||||
if (!raw) return null;
|
||||
const size = JSON.parse(raw) as { w?: unknown; h?: unknown };
|
||||
return typeof size.w === "number" &&
|
||||
Number.isFinite(size.w) &&
|
||||
size.w > 0 &&
|
||||
typeof size.h === "number" &&
|
||||
Number.isFinite(size.h) &&
|
||||
size.h > 0
|
||||
? { w: size.w, h: size.h }
|
||||
: null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function rememberFilesSize(size: { w: number; h: number }) {
|
||||
try {
|
||||
localStorage.setItem(RECENT_FILES_SIZE_KEY, JSON.stringify(size));
|
||||
} catch {
|
||||
// A read-only storage still leaves the window resizable for this session.
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// ⌘E — Recent Files; ⌃⇥ — Switcher (open editors only, no speed search)
|
||||
|
||||
@@ -128,6 +157,7 @@ function RecentFilesDialog() {
|
||||
const [column, setColumn] = useState<"files" | "tools">("files");
|
||||
const [fileIndex, setFileIndex] = useState<number | null>(null);
|
||||
const [toolIndex, setToolIndex] = useState(0);
|
||||
const [initialSize] = useState(() => (switcher ? null : readFilesSize()));
|
||||
const opening = useRef(false);
|
||||
const [previousEditedOnly, setPreviousEditedOnly] = useState(editedOnly);
|
||||
const [fileSelection, setFileSelection] = useState<RowSelection>(SINGLE_FIRST);
|
||||
@@ -169,6 +199,7 @@ function RecentFilesDialog() {
|
||||
),
|
||||
[paths, tabs, removed, query, root, labelled, edited, editedOnly],
|
||||
);
|
||||
const sharedNames = useMemo(() => sharedFileNames(files), [files]);
|
||||
const fileRows = useMemo(() => files.map((f) => ({ ...f, key: f.path })), [files]);
|
||||
const tools = useMemo(() => switcherToolWindows(toolWindows.values(), !!root, query), [toolWindows, root, query]);
|
||||
const fIndex = files.length
|
||||
@@ -327,10 +358,15 @@ function RecentFilesDialog() {
|
||||
onClose={hideRecentPopup}
|
||||
restoreFocus={keepFocus}
|
||||
width={switcher ? 560 : 720}
|
||||
resizable={switcher ? undefined : "both"}
|
||||
minWidth={switcher ? undefined : 560}
|
||||
minHeight={switcher ? undefined : 260}
|
||||
initialSize={initialSize}
|
||||
onResized={switcher ? undefined : rememberFilesSize}
|
||||
aria-label={title}
|
||||
className={clsx(styles.dialog, switcher && styles.switcher)}
|
||||
>
|
||||
<header className={styles.header}>
|
||||
<header className={styles.header} data-dialog-drag="">
|
||||
<span className={styles.title}>
|
||||
<T>{title}</T>
|
||||
</span>
|
||||
@@ -428,7 +464,9 @@ function RecentFilesDialog() {
|
||||
</span>
|
||||
)
|
||||
}
|
||||
renderItem={(f) => <RecentFileRow item={f} current={f.path === activePath} />}
|
||||
renderItem={(f) => (
|
||||
<RecentFileRow item={f} current={f.path === activePath} showDir={sharedNames.has(f.name)} />
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
@@ -452,7 +490,7 @@ function ToolRow({ tw, title, indices }: { tw: ToolWindowContribution; title: st
|
||||
);
|
||||
}
|
||||
|
||||
function RecentFileRow({ item, current }: { item: RecentFileItem; current: boolean }) {
|
||||
function RecentFileRow({ item, current, showDir }: { item: RecentFileItem; current: boolean; showDir: boolean }) {
|
||||
const deco = useFileDecoration(item.editor ? "" : item.path);
|
||||
const { icon } = useFilePresentation(item.editor ? "" : item.path);
|
||||
const title = item.editor ? item.name : (deco.tabTitle ?? item.name);
|
||||
@@ -466,7 +504,7 @@ function RecentFileRow({ item, current }: { item: RecentFileItem; current: boole
|
||||
>
|
||||
<HighlightedText text={title} indices={indices} tone="strong" />
|
||||
</span>
|
||||
{item.dir && <span className={styles.dir}>{item.dir}</span>}
|
||||
{showDir && item.dir && <span className={styles.dir}>{item.dir}</span>}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -59,6 +59,18 @@ export function filterRecentFiles(
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Names that more than one listed file has; IDEA shows the directory only to tell those apart. */
|
||||
export function sharedFileNames(items: readonly RecentFileItem[]): Set<string> {
|
||||
const seen = new Set<string>();
|
||||
const shared = new Set<string>();
|
||||
for (const item of items) {
|
||||
if (item.editor) continue;
|
||||
if (seen.has(item.name)) shared.add(item.name);
|
||||
else seen.add(item.name);
|
||||
}
|
||||
return shared;
|
||||
}
|
||||
|
||||
/** IDEA preselects the previous file so ⌘E ↵ toggles between the last two. */
|
||||
export function initialFileIndex(items: readonly RecentFileItem[], activePath: string | null, query: string): number {
|
||||
if (!items.length) return -1;
|
||||
|
||||
@@ -253,6 +253,11 @@ function TerminalOptions() {
|
||||
<BoundToggle k="terminal.closeOnExit" label="Close session when it ends" />
|
||||
<BoundToggle k="terminal.mouseReporting" label="Mouse reporting" />
|
||||
<BoundToggle k="terminal.copyOnSelection" label="Copy to clipboard on selection" />
|
||||
<BoundToggle
|
||||
k="terminal.osc52Clipboard"
|
||||
label="Let programs copy to the clipboard (OSC 52)"
|
||||
hint="For tmux, Neovim and other programs, also over SSH. Programs can't read the clipboard."
|
||||
/>
|
||||
<BoundToggle k="terminal.pasteOnMiddleClick" label="Paste on middle mouse button click" />
|
||||
<BoundToggle k="terminal.rightClickPaste" label="Paste on right click" />
|
||||
<BoundToggle
|
||||
@@ -846,6 +851,7 @@ export const TOOLS_PAGES: PageSpec[] = [
|
||||
"Close session when it ends",
|
||||
"Mouse reporting",
|
||||
"Copy to clipboard on selection",
|
||||
"Let programs copy to the clipboard (OSC 52)",
|
||||
"Paste on middle mouse button click",
|
||||
"Override IDE shortcuts",
|
||||
"Shell integration",
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { OSC52_MAX_BYTES, osc52Text } from "./osc52";
|
||||
|
||||
const b64 = (text: string) => btoa(String.fromCharCode(...new TextEncoder().encode(text)));
|
||||
|
||||
describe("osc52Text", () => {
|
||||
it("decodes the clipboard selection as UTF-8", () => {
|
||||
expect(osc52Text(`c;${b64("hello")}`)).toBe("hello");
|
||||
expect(osc52Text(`c;${b64("中文 ✓")}`)).toBe("中文 ✓");
|
||||
});
|
||||
|
||||
it("accepts the default, primary and select selections", () => {
|
||||
expect(osc52Text(`;${b64("x")}`)).toBe("x");
|
||||
expect(osc52Text(`p;${b64("x")}`)).toBe("x");
|
||||
expect(osc52Text(`s0;${b64("x")}`)).toBe("x");
|
||||
});
|
||||
|
||||
it("never answers a read request", () => {
|
||||
expect(osc52Text("c;?")).toBeNull();
|
||||
expect(osc52Text(";?")).toBeNull();
|
||||
});
|
||||
|
||||
it("ignores cut buffers only, invalid base64, empty and malformed payloads", () => {
|
||||
expect(osc52Text(`0;${b64("x")}`)).toBeNull();
|
||||
expect(osc52Text("c;not base64!")).toBeNull();
|
||||
expect(osc52Text("c;a")).toBeNull();
|
||||
expect(osc52Text("c;")).toBeNull();
|
||||
expect(osc52Text(b64("no selections"))).toBeNull();
|
||||
});
|
||||
|
||||
it("drops payloads over the size limit", () => {
|
||||
expect(osc52Text(`c;${btoa("a".repeat(OSC52_MAX_BYTES))}`)).toBe("a".repeat(OSC52_MAX_BYTES));
|
||||
expect(osc52Text(`c;${btoa("a".repeat(OSC52_MAX_BYTES + 1))}`)).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,36 @@
|
||||
/**
|
||||
* OSC 52 (`ESC ] 52 ; <selections> ; <base64> BEL`): a program that can't reach the local
|
||||
* clipboard (tmux with `set-clipboard on`, Neovim over SSH, TUI multiplexers) asks the terminal
|
||||
* to set it. Only writes are honoured: a read request (`?`) is never answered, as reading the
|
||||
* clipboard back would hand its contents to whatever runs in the terminal.
|
||||
*/
|
||||
|
||||
/** Decoded text larger than this is dropped. */
|
||||
export const OSC52_MAX_BYTES = 1 << 20;
|
||||
|
||||
const BASE64 = /^[A-Za-z0-9+/]*={0,2}$/;
|
||||
|
||||
/**
|
||||
* The text an OSC 52 payload (`<selections>;<base64>`) puts on the clipboard, or null for a read
|
||||
* request, cut buffers only, an oversized or invalid payload.
|
||||
*/
|
||||
export function osc52Text(data: string): string | null {
|
||||
const semi = data.indexOf(";");
|
||||
if (semi < 0) return null;
|
||||
const selections = data.slice(0, semi);
|
||||
const payload = data.slice(semi + 1).replace(/\s+/g, "");
|
||||
if (payload === "?" || !payload) return null;
|
||||
// Empty means the default (`s0`); clipboard, primary and selection all map to the one clipboard.
|
||||
if (selections && !/[cps]/.test(selections)) return null;
|
||||
if (payload.length % 4 === 1 || !BASE64.test(payload)) return null;
|
||||
if (Math.floor((payload.length * 3) / 4) > OSC52_MAX_BYTES + 2) return null;
|
||||
let binary: string;
|
||||
try {
|
||||
binary = atob(payload);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
if (binary.length > OSC52_MAX_BYTES) return null;
|
||||
const bytes = Uint8Array.from(binary, (c) => c.charCodeAt(0));
|
||||
return new TextDecoder().decode(bytes);
|
||||
}
|
||||
@@ -37,7 +37,13 @@ const workbench = vi.hoisted(() => ({
|
||||
notify: vi.fn(),
|
||||
}));
|
||||
|
||||
const clipboard = vi.hoisted(() => ({ writeClipboardText: vi.fn(async (_text: string) => undefined) }));
|
||||
|
||||
vi.mock("@/platform/ipc", () => ({ call: ipc.call, commands: ipc.commands, isTauri: () => true }));
|
||||
vi.mock("@/platform/clipboard", async (importOriginal) => ({
|
||||
...(await importOriginal<object>()),
|
||||
writeClipboardText: clipboard.writeClipboardText,
|
||||
}));
|
||||
vi.mock("@/workbench/contributions", async (importOriginal) => ({
|
||||
...(await importOriginal<object>()),
|
||||
editorService: () => ({ openFile: workbench.openFile }),
|
||||
@@ -772,6 +778,25 @@ describe("terminal tab spinner state (#3831)", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("puts OSC 52 clipboard writes on the clipboard unless turned off, and never answers a read", async () => {
|
||||
const session = new TerminalSession({ key: "s-osc52", cwd: "/repo", onChange() {}, onFocus() {} });
|
||||
const b64 = (text: string) => btoa(String.fromCharCode(...new TextEncoder().encode(text)));
|
||||
try {
|
||||
clipboard.writeClipboardText.mockClear();
|
||||
await feed(session, `\x1b]52;c;${b64("复制 me")}\x07`);
|
||||
expect(clipboard.writeClipboardText).toHaveBeenCalledExactlyOnceWith("复制 me");
|
||||
await feed(session, "\x1b]52;c;?\x07");
|
||||
expect(clipboard.writeClipboardText).toHaveBeenCalledTimes(1);
|
||||
expect(ipc.commands.termWrite).not.toHaveBeenCalled();
|
||||
useProject.setState({ settings: { terminal: { osc52Clipboard: false } } } as never);
|
||||
await feed(session, `\x1b]52;c;${b64("off")}\x07`);
|
||||
expect(clipboard.writeClipboardText).toHaveBeenCalledTimes(1);
|
||||
} finally {
|
||||
useProject.setState({ settings: null });
|
||||
session.dispose();
|
||||
}
|
||||
});
|
||||
|
||||
it("starts each command without the previous program's progress report", async () => {
|
||||
const session = new TerminalSession({ key: "s-progress-reset", cwd: "/repo", onChange() {}, onFocus() {} });
|
||||
try {
|
||||
|
||||
@@ -49,6 +49,7 @@ import { usePlatform } from "@/platform/platformInfo";
|
||||
import { workflowSettings, type TerminalSettingsValid } from "@/platform/workflowSettings";
|
||||
import { editorPrefs } from "@/platform/editorSettings";
|
||||
import type { CompletionInfo } from "./completion";
|
||||
import { osc52Text } from "./osc52";
|
||||
import {
|
||||
readLinkColor,
|
||||
readSearchDecorations,
|
||||
@@ -478,6 +479,16 @@ export class TerminalSession {
|
||||
}
|
||||
return true;
|
||||
}),
|
||||
// OSC 52: a program sets the clipboard (writes only; see osc52.ts).
|
||||
this.term.parser.registerOscHandler(52, (data) => {
|
||||
if (!workflowSettings().terminal.osc52Clipboard) return true;
|
||||
const text = osc52Text(data);
|
||||
if (text !== null) {
|
||||
noteCopySource(text, { kind: "terminal", title: this.snapshot.appTitle ?? this.snapshot.title });
|
||||
void writeClipboardText(text).catch(() => undefined);
|
||||
}
|
||||
return true;
|
||||
}),
|
||||
// OSC 9;4 (ConEmu-style progress): agent CLIs (Claude Code, Gemini CLI, …)
|
||||
// and long jobs report their own working state — state 0 removes it, 1–4
|
||||
// report work in flight. A program that reports progress decides the tab's
|
||||
|
||||
@@ -63,6 +63,7 @@ export const CLIENT_SETTINGS_KEYS = [
|
||||
"terminal.closeOnExit",
|
||||
"terminal.mouseReporting",
|
||||
"terminal.copyOnSelection",
|
||||
"terminal.osc52Clipboard",
|
||||
"terminal.pasteOnMiddleClick",
|
||||
"terminal.rightClickPaste",
|
||||
"terminal.overrideIdeShortcuts",
|
||||
|
||||
@@ -682,6 +682,9 @@
|
||||
"A session could not be forked": "A session could not be forked",
|
||||
"Some sessions could not be forked": "Some sessions could not be forked",
|
||||
"Fork into a new task": "Fork into a new task",
|
||||
"In use": "In use",
|
||||
"Open in another app": "Open in another app",
|
||||
"Another app has this session open. Fork copies it so both can continue.": "Another app has this session open. Fork copies it so both can continue.",
|
||||
"Only the 50 most recent sessions are shown.": "Only the 50 most recent sessions are shown.",
|
||||
"Some sessions could not be imported": "Some sessions could not be imported",
|
||||
"A session could not be imported": "A session could not be imported",
|
||||
|
||||
@@ -3292,6 +3292,8 @@
|
||||
"Services actions": "Действия служб",
|
||||
"Session finished": "Сессия завершена",
|
||||
"Sessions from other apps": "Сессии из других приложений",
|
||||
"Open in another app": "Открыта в другом приложении",
|
||||
"Another app has this session open. Fork copies it so both can continue.": "Эта сессия открыта в другом приложении. Fork создаст копию, чтобы обе могли продолжить.",
|
||||
"Import Sessions…": "Импортировать сессии…",
|
||||
"Import Sessions": "Импорт сессий",
|
||||
"No sessions from other apps": "Нет сессий из других приложений",
|
||||
|
||||
@@ -1268,6 +1268,8 @@
|
||||
"Copy revision number": "複製修訂號",
|
||||
"Copy to clipboard": "複製到剪貼簿",
|
||||
"Copy to clipboard on selection": "選擇時複製到剪貼簿",
|
||||
"For tmux, Neovim and other programs, also over SSH. Programs can't read the clipboard.": "適用於 tmux、Neovim 等程式,SSH 中也有效。程式無法讀取剪貼簿。",
|
||||
"Let programs copy to the clipboard (OSC 52)": "允許程式複製到剪貼簿(OSC 52)",
|
||||
"Copy with Header": "帶標題複製",
|
||||
"Copy/Paste": "複製/貼上",
|
||||
"Could not apply theme": "無法應用主題",
|
||||
@@ -2897,6 +2899,8 @@
|
||||
"Services actions": "服務操作",
|
||||
"Session finished": "工作階段已結束",
|
||||
"Sessions from other apps": "來自其他應用的代理工作階段",
|
||||
"Open in another app": "已在其他應用中開啟",
|
||||
"Another app has this session open. Fork copies it so both can continue.": "另一個應用已開啟此工作階段。Fork 會複製一份,雙方都能繼續。",
|
||||
"Import Sessions…": "匯入工作階段…",
|
||||
"Import Sessions": "匯入工作階段",
|
||||
"No sessions from other apps": "沒有來自其他應用的代理工作階段",
|
||||
@@ -7529,6 +7533,7 @@
|
||||
"Path From Repository Root": "相對於存放庫根的路徑",
|
||||
"Agent Reference": "智能體引用",
|
||||
"Copy Agent Reference": "複製智能體引用",
|
||||
"Copies the `@` reference of the Project view selection, or of the editor's file and selected lines, for pasting into a terminal agent.": "複製專案視圖所選內容的 `@` 引用,或編輯器目前檔案及所選行的引用,用於貼上到終端機智能體中。",
|
||||
"Paste preview": "貼上預覽",
|
||||
"Filter clipboard history": "篩選剪貼簿歷史",
|
||||
"Add Imports": "新增匯入",
|
||||
|
||||
@@ -1762,6 +1762,8 @@
|
||||
"Copy revision number": "复制修订号",
|
||||
"Copy to clipboard": "复制到剪贴板",
|
||||
"Copy to clipboard on selection": "选择时复制到剪贴板",
|
||||
"For tmux, Neovim and other programs, also over SSH. Programs can't read the clipboard.": "适用于 tmux、Neovim 等程序,SSH 中也有效。程序无法读取剪贴板。",
|
||||
"Let programs copy to the clipboard (OSC 52)": "允许程序复制到剪贴板(OSC 52)",
|
||||
"Copy with Header": "带标题复制",
|
||||
"Copy/Paste": "复制/粘贴",
|
||||
"Could not apply theme": "无法应用主题",
|
||||
@@ -3250,6 +3252,7 @@
|
||||
"Reload History": "重新加载历史记录",
|
||||
"Reload List of Packages": "重新加载软件包列表",
|
||||
"Reload Page": "重新加载页面",
|
||||
"Reload the DDL": "重新加载 DDL",
|
||||
"Reload Plugins": "重新加载插件",
|
||||
"Reload Project Tree from Disk": "从磁盘重新加载项目树",
|
||||
"Reload Run Configurations": "重新加载运行配置",
|
||||
@@ -3568,6 +3571,8 @@
|
||||
"A session could not be forked": "一个会话无法 Fork",
|
||||
"Some sessions could not be forked": "部分会话无法 Fork",
|
||||
"Fork into a new task": "Fork 为新任务",
|
||||
"Open in another app": "已在其他应用中打开",
|
||||
"Another app has this session open. Fork copies it so both can continue.": "另一个应用已打开此会话。Fork 会复制一份,双方都可继续。",
|
||||
"Only the 50 most recent sessions are shown.": "仅显示最近的 50 个会话。",
|
||||
"Some sessions could not be imported": "部分会话无法导入",
|
||||
"A session could not be imported": "有一个会话无法导入",
|
||||
@@ -8461,6 +8466,7 @@
|
||||
"Path From Repository Root": "相对于仓库根的路径",
|
||||
"Agent Reference": "智能体引用",
|
||||
"Copy Agent Reference": "复制智能体引用",
|
||||
"Copies the `@` reference of the Project view selection, or of the editor's file and selected lines, for pasting into a terminal agent.": "复制项目视图所选内容的 `@` 引用,或编辑器当前文件及所选行的引用,用于粘贴到终端智能体中。",
|
||||
"Paste preview": "粘贴预览",
|
||||
"Filter clipboard history": "筛选剪贴板历史",
|
||||
"Add Imports": "添加导入",
|
||||
|
||||
@@ -204,6 +204,8 @@ export interface TerminalSettingsValid {
|
||||
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;
|
||||
@@ -442,6 +444,7 @@ export const DEFAULT_WORKFLOW: WorkflowSettings = {
|
||||
closeOnExit: true,
|
||||
mouseReporting: true,
|
||||
copyOnSelection: false,
|
||||
osc52Clipboard: true,
|
||||
pasteOnMiddleClick: true,
|
||||
rightClickPaste: false,
|
||||
overrideIdeShortcuts: true,
|
||||
@@ -688,6 +691,7 @@ export function validateTerminal(raw: unknown): TerminalSettingsValid {
|
||||
closeOnExit: bool(v.closeOnExit, d.closeOnExit),
|
||||
mouseReporting: bool(v.mouseReporting, d.mouseReporting),
|
||||
copyOnSelection: bool(v.copyOnSelection, d.copyOnSelection),
|
||||
osc52Clipboard: bool(v.osc52Clipboard, d.osc52Clipboard),
|
||||
pasteOnMiddleClick: bool(v.pasteOnMiddleClick, d.pasteOnMiddleClick),
|
||||
rightClickPaste: bool(v.rightClickPaste, d.rightClickPaste),
|
||||
overrideIdeShortcuts: bool(v.overrideIdeShortcuts, d.overrideIdeShortcuts),
|
||||
|
||||
@@ -13,6 +13,41 @@ function Harness({ onScroll }: { onScroll: (top: number) => void }) {
|
||||
);
|
||||
}
|
||||
|
||||
function HorizontalHarness() {
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
return (
|
||||
<div style={{ position: "relative" }}>
|
||||
<Scrollbar target={ref} contentWidth={800} horizontal />
|
||||
<div ref={ref} data-testid="scroller" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const flushFrame = () => act(() => new Promise<void>((resolve) => requestAnimationFrame(() => resolve())));
|
||||
|
||||
/** A scroller wide enough for the horizontal overlay to have a thumb. */
|
||||
function overflowX(scroller: HTMLElement, left = 0) {
|
||||
let scrollLeft = left;
|
||||
Object.defineProperties(scroller, {
|
||||
clientWidth: { configurable: true, value: 200 },
|
||||
scrollWidth: { configurable: true, value: 800 },
|
||||
offsetLeft: { configurable: true, value: 0 },
|
||||
scrollLeft: {
|
||||
configurable: true,
|
||||
get: () => scrollLeft,
|
||||
set: (value: number) => void (scrollLeft = value),
|
||||
},
|
||||
});
|
||||
return {
|
||||
get left() {
|
||||
return scrollLeft;
|
||||
},
|
||||
set left(value: number) {
|
||||
scrollLeft = value;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** A ResizeObserver the test fires by hand, for the elements it was told to observe. */
|
||||
function fakeResizeObserver() {
|
||||
const observers = new Set<{ callback: () => void; targets: Set<Element> }>();
|
||||
@@ -121,6 +156,50 @@ describe("Scrollbar", () => {
|
||||
expect(document.querySelector("[data-scrollbar-drag-surface]")).toBeNull();
|
||||
});
|
||||
|
||||
it("does not move or reveal the horizontal overlay when scrollLeft is reverted in the same frame", async () => {
|
||||
const { getByTestId, container } = render(<HorizontalHarness />);
|
||||
const scroller = getByTestId("scroller");
|
||||
overflowX(scroller, 0);
|
||||
act(() => scroller.dispatchEvent(new Event("scroll")));
|
||||
await flushFrame();
|
||||
const track = container.querySelector<HTMLElement>("[data-horizontal-scrollbar]")!;
|
||||
const thumb = track.firstElementChild as HTMLElement;
|
||||
expect(track.getAttribute("data-active")).toBeNull();
|
||||
expect(thumb.style.transform).toBe("translateX(0px)");
|
||||
|
||||
// WebKit autoscrolls toward the pointer, then the tree's drag guard snaps back.
|
||||
Object.getOwnPropertyDescriptor(scroller, "scrollLeft")!.set!.call(scroller, 600);
|
||||
act(() => scroller.dispatchEvent(new Event("scroll")));
|
||||
Object.getOwnPropertyDescriptor(scroller, "scrollLeft")!.set!.call(scroller, 0);
|
||||
act(() => scroller.dispatchEvent(new Event("scroll")));
|
||||
await flushFrame();
|
||||
expect({
|
||||
active: track.getAttribute("data-active"),
|
||||
transform: thumb.style.transform,
|
||||
left: scroller.scrollLeft,
|
||||
}).toEqual({
|
||||
active: null,
|
||||
transform: "translateX(0px)",
|
||||
left: 0,
|
||||
});
|
||||
});
|
||||
|
||||
it("reveals and moves the horizontal overlay after a settled sideways scroll", async () => {
|
||||
const { getByTestId, container } = render(<HorizontalHarness />);
|
||||
const scroller = getByTestId("scroller");
|
||||
const scroll = overflowX(scroller, 0);
|
||||
act(() => scroller.dispatchEvent(new Event("scroll")));
|
||||
await flushFrame();
|
||||
const track = container.querySelector<HTMLElement>("[data-horizontal-scrollbar]")!;
|
||||
const thumb = track.firstElementChild as HTMLElement;
|
||||
scroll.left = 600;
|
||||
act(() => scroller.dispatchEvent(new Event("scroll")));
|
||||
await flushFrame();
|
||||
// clientWidth 200, scrollWidth 800: thumb is 50px, range 150, offset 600 → translateX(150px).
|
||||
expect(track.getAttribute("data-active")).toBe("");
|
||||
expect(thumb.style.transform).toBe("translateX(150px)");
|
||||
});
|
||||
|
||||
it.each([
|
||||
[318, 318, false],
|
||||
// WebKit after a splitter drag: one commit row, scrollHeight a pixel over the viewport.
|
||||
|
||||
@@ -67,10 +67,12 @@ export function Scrollbar({
|
||||
const el = target.current;
|
||||
if (!el) return;
|
||||
let lastLeft = el.scrollLeft;
|
||||
let frame = 0;
|
||||
const sync = () => {
|
||||
geometry.current = layout(el, track.current, thumb.current, horizontal);
|
||||
};
|
||||
const onScroll = () => {
|
||||
const flush = () => {
|
||||
frame = 0;
|
||||
const moved = el.scrollLeft !== lastLeft;
|
||||
lastLeft = el.scrollLeft;
|
||||
sync();
|
||||
@@ -79,6 +81,17 @@ export function Scrollbar({
|
||||
scheduleHide();
|
||||
}
|
||||
};
|
||||
// A same-frame scrollLeft revert (the Project tree's drag guard against WebKit
|
||||
// autoscroll) must not move the thumb or flash the overlay. Thumb drags stay
|
||||
// synchronous so the thumb still tracks the pointer in the same frame.
|
||||
const onScroll = () => {
|
||||
if (horizontal && !drag.current) {
|
||||
if (!frame) frame = requestAnimationFrame(flush);
|
||||
return;
|
||||
}
|
||||
if (frame) cancelAnimationFrame(frame);
|
||||
flush();
|
||||
};
|
||||
el.addEventListener("scroll", onScroll, { passive: true });
|
||||
const observer = new ResizeObserver(() => {
|
||||
lastLeft = el.scrollLeft;
|
||||
@@ -99,6 +112,7 @@ export function Scrollbar({
|
||||
endDrag();
|
||||
window.removeEventListener("blur", endDrag);
|
||||
window.clearTimeout(hideTimer.current);
|
||||
cancelAnimationFrame(frame);
|
||||
el.removeEventListener("scroll", onScroll);
|
||||
observer.disconnect();
|
||||
replaced.disconnect();
|
||||
|
||||
@@ -44,6 +44,17 @@ export const PROJECT_TYPES = {
|
||||
|
||||
export type ProjectType = keyof typeof PROJECT_TYPES;
|
||||
const definitions = Object.entries(PROJECT_TYPES) as [ProjectType, ProjectTypeDefinition][];
|
||||
|
||||
/**
|
||||
* File-type logos must not replace a project-root folder. They are drawn as a
|
||||
* small corner badge instead. Dedicated project glyphs (Maven, Gradle, Flutter,
|
||||
* Vite) still stand in for the folder.
|
||||
*/
|
||||
export function projectTypeFolderBadge(type: ProjectType): IconName | undefined {
|
||||
const { icon } = PROJECT_TYPES[type];
|
||||
return icon.startsWith("file-") ? icon : undefined;
|
||||
}
|
||||
|
||||
const matches = (name: string, marker: Marker) => (typeof marker === "string" ? name === marker : marker.test(name));
|
||||
|
||||
export function isProjectMarker(name: string): boolean {
|
||||
|
||||
Reference in new issue
Заблокувати користувача