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

...
Автор SHA1 Повідомлення Дата
l0ng-ai bb1b3689b4 fix(java): recheck open files when Java sources change on disk
When another tool (an AI agent, a generator) rewrote an open Java file to
call a class or method it added in another file, the open file kept a
"cannot be resolved" error until it was closed and reopened. jdtls
rebuilds sources reported through workspace/didChangeWatchedFiles but
does not re-reconcile the open working copies it already checked. When
the open file's reload reaches it before the new class, the stale
error stays.

After sending Java source changes to jdtls, the open documents are sent
again (resync_documents, as after a configuration change), so jdtls
checks them against the new sources. Changes to other files (pom.xml,
resources) don't trigger it.

Fixes #6986
2026-12-01 07:02:49 +08:00
Deng Liuтаdengliu 50ba6b5c56 fix(agents): resolve VS Code Copilot session titles and search across all project sessions (#7118)
Copilot sessions started from VS Code got their titles from VS Code's Agent Host, which stores summaries and user renames in <user>/globalStorage/agent-host.db and does not write them back to workspace.yaml. The import list now reads that database read-only to resolve the titles, skipping unrenamed "New session" / "New Chat" placeholders. It also parses YAML block scalars (|, |-, >, >-) in workspace.yaml names instead of showing a literal "|-".

The backend now lists every session of the project. The Import Sessions dialog filters by title, folder or session ID before taking the 50 newest matches, so older sessions and sessions searched by ID can be found. The 50-session hint appears only when more sessions match.

Co-authored-by: dengliu <[email protected]>

Co-authored-by: dengliu <[email protected]>
2026-12-01 06:56:32 +08:00
l0ng-ai 36910712d1 fix(ci): run Language smoke when the inline background helper changes (#7120)
#7110 made src/editor/lsp/diagnostics.ts import src/editor/core/cm/inlineBg.ts. The frontend smoke loads diagnostics.ts, but the new import was missing from the workflow's trigger paths and from the Changes step's smoke pattern, so scripts/smoke-paths.test.ts failed on main. Add the file to both; only path filters change.
2026-12-01 06:55:29 +08:00
l0ng-ai 5b99b8b5ab fix(vcs): dim Git log metadata columns only for merge commits (#7119)
The User, Date and Hash cells in the Git log always used the muted color, while the subject is only dimmed for merge commits (Highlight > Merge Commits) and for commits outside the cherry-pick selection. The metadata cells now use the same condition, so a row is dimmed as a whole or not at all. My Commits still shows the author in bold.

Fixes #7112
2026-12-01 06:51:40 +08:00
14 змінених файлів з 488 додано та 53 видалено

No files matched your search

+2 -1
Переглянути файл
@@ -34,6 +34,7 @@ on:
- "src/editor/relatedProviders.ts"
- "src/editor/core/cm/cornerInset.ts"
- "src/editor/core/cm/iconArea.ts"
- "src/editor/core/cm/inlineBg.ts"
- "src/editor/core/cm/localAppearance.ts"
- "src/editor/lsp/availability.ts"
- "src/editor/lsp/diagnostics.ts"
@@ -109,7 +110,7 @@ jobs:
# ide-lsp/dap/run/sdk/tools.
unused='^crates/(ide-agent|ide-analysis|ide-android|ide-cli|ide-clipboard|ide-coverage|ide-db|ide-docker|ide-fonts|ide-github|ide-mcp|ide-notebook|ide-profiler|ide-scaffold|ide-spell|ide-ssh|ide-vcs|ide-web)/'
# The workflow's paths, less those handled per language below.
smoke='^(crates/|Cargo\.(toml|lock)$|src/features/(run|debugger|build|build-tools)/|src/platform/|src/workbench/|src/ui/|src/editor/(api|navigationProviders|refactorProviders|relatedProviders|core/cm/(cornerInset|iconArea|localAppearance)|lsp/(availability|diagnostics|files|hint|lsp|positions|snippet))\.ts$|src/bindings\.ts$|src/styles/tokens\.css$|src/test/setup\.ts$|src-tauri/icons/128x128\.png$|smoke/|vite\.config\.ts$|tsconfig\.json$|package\.json$|pnpm-(lock|workspace)\.yaml$|patches/|\.github/workflows/language-smoke\.yml$|\.github/tool-versions\.env$)'
smoke='^(crates/|Cargo\.(toml|lock)$|src/features/(run|debugger|build|build-tools)/|src/platform/|src/workbench/|src/ui/|src/editor/(api|navigationProviders|refactorProviders|relatedProviders|core/cm/(cornerInset|iconArea|inlineBg|localAppearance)|lsp/(availability|diagnostics|files|hint|lsp|positions|snippet))\.ts$|src/bindings\.ts$|src/styles/tokens\.css$|src/test/setup\.ts$|src-tauri/icons/128x128\.png$|smoke/|vite\.config\.ts$|tsconfig\.json$|package\.json$|pnpm-(lock|workspace)\.yaml$|patches/|\.github/workflows/language-smoke\.yml$|\.github/tool-versions\.env$)'
langs=""
while read -r f; do
case "$f" in
Створено
+1
Переглянути файл
@@ -4166,6 +4166,7 @@ dependencies = [
"ide-tools",
"ide-vcs",
"ide-vfs",
"libsqlite3-sys",
"parking_lot 0.12.5",
"rustix",
"semver",
+1
Переглянути файл
@@ -115,6 +115,7 @@ reqwest = { version = "0.13", default-features = false, features = ["rustls-no-p
rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12", "logging"] }
rustls-platform-verifier = "0.7"
# Until SQLx releases its libsqlite3-sys 0.39 update (RUSTSEC-2026-0459).
libsqlite3-sys = { version = "0.39", features = ["bundled"] }
sqlx = { version = "0.9", git = "https://github.com/l0ng-ai/sqlx", rev = "9894985a1babc7e6bc0437da4fd43e3143184073", default-features = false, features = ["runtime-tokio", "tls-rustls-ring-webpki", "sqlite", "postgres", "mysql"] }
tiberius = { version = "0.13", default-features = false, features = ["tds73", "rustls", "sql-browser-tokio"] }
# Pure-Rust thin Oracle driver; pinned to the beta until it stabilizes.
+1
Переглянути файл
@@ -15,6 +15,7 @@ ide-mcp.workspace = true
ide-jsonrpc.workspace = true
ide-vcs.workspace = true
ide-tools = { path = "../ide-tools" }
libsqlite3-sys.workspace = true
serde.workspace = true
serde_json.workspace = true
specta.workspace = true
+327 -39
Переглянути файл
@@ -247,35 +247,71 @@ pub fn codex_sessions(codex_home: &Path, root: &Path) -> Vec<ExternalSession> {
sessions
}
/// One scalar at the root of Copilot's `workspace.yaml`.
///
/// Copilot writes a flat mapping of scalar values. Most values are plain, while names can
/// be JSON-compatible double-quoted YAML strings (including `\n`).
fn yaml_scalar(line: &str) -> Option<(String, String)> {
let (key, raw) = line.split_once(':')?;
let key = key.trim();
let raw = raw.trim();
if key.is_empty() || raw.is_empty() || line.starts_with(char::is_whitespace) {
return None;
}
let value = if raw.starts_with('"') {
/// Whether `raw` is a YAML block-scalar header (`|`, `|-`, `|+`, `>`, `>-`, `>+`, with optional indent digit).
fn is_yaml_block_header(raw: &str) -> bool {
let mut chars = raw.chars();
matches!(chars.next(), Some('|' | '>')) && chars.all(|c| matches!(c, '-' | '+') || c.is_ascii_digit())
}
/// Unquotes a single-line YAML scalar value from Copilot's `workspace.yaml`.
fn parse_yaml_inline_value(raw: &str) -> String {
if raw.starts_with('"') {
serde_json::from_str(raw).unwrap_or_else(|_| raw.trim_matches('"').to_owned())
} else if raw.starts_with('\'') && raw.ends_with('\'') && raw.len() >= 2 {
raw[1..raw.len() - 1].replace("''", "'")
} else {
raw.to_owned()
};
Some((key.to_owned(), value))
}
}
/// Metadata for one Copilot session, read without opening its potentially multi-gigabyte event log.
/// Supports both inline scalars (`name: "Fix\nbug"`) and block scalars (`name: |-\n Fix\n bug`).
fn copilot_metadata(path: &Path) -> Option<HashMap<String, String>> {
let file = std::fs::File::open(path).ok()?;
let metadata = std::io::BufReader::new(file)
.lines()
.map_while(Result::ok)
.filter_map(|line| yaml_scalar(&line))
.collect::<HashMap<_, _>>();
let mut lines = std::io::BufReader::new(file).lines().map_while(Result::ok).peekable();
let mut metadata = HashMap::new();
while let Some(line) = lines.next() {
if line.is_empty() || line.starts_with(char::is_whitespace) || line.trim_start().starts_with('#') {
continue;
}
let Some((key, raw)) = line.split_once(':') else { continue };
let key = key.trim();
let raw = raw.trim();
if key.is_empty() {
continue;
}
if is_yaml_block_header(raw) {
let folded = raw.starts_with('>');
let mut block = Vec::new();
while let Some(next) = lines.peek() {
if next.is_empty() || next.starts_with(' ') || next.starts_with('\t') {
block.push(lines.next().unwrap_or_default());
} else {
break;
}
}
while block.last().is_some_and(|l| l.trim().is_empty()) {
block.pop();
}
let indent = block
.iter()
.filter(|l| !l.trim().is_empty())
.map(|l| l.bytes().take_while(|&b| b == b' ').count())
.min()
.unwrap_or(0);
let sep = if folded { " " } else { "\n" };
let joined = block
.iter()
.map(|l| if l.len() >= indent { &l[indent..] } else { l.trim_start() })
.collect::<Vec<_>>()
.join(sep);
if !joined.trim().is_empty() {
metadata.insert(key.to_owned(), joined);
}
} else if !raw.is_empty() {
metadata.insert(key.to_owned(), parse_yaml_inline_value(raw));
}
}
(!metadata.is_empty()).then_some(metadata)
}
@@ -296,11 +332,187 @@ fn copilot_prompt(path: &Path) -> Option<String> {
})
}
/// Copilot sessions of the project at `root`: `<config>/session-state/<id>`, titled by
/// their recorded name or first prompt. Directories without an event log are unfinished
/// sessions and are not listed.
pub fn copilot_sessions(copilot_home: &Path, root: &Path) -> Vec<ExternalSession> {
std::fs::read_dir(copilot_home.join("session-state"))
struct SqliteDb(*mut libsqlite3_sys::sqlite3);
impl SqliteDb {
fn open_readonly(path: &Path) -> Option<Self> {
if !path.is_file() {
return None;
}
let c_path = std::ffi::CString::new(path.to_str()?).ok()?;
let mut raw: *mut libsqlite3_sys::sqlite3 = std::ptr::null_mut();
let flags = libsqlite3_sys::SQLITE_OPEN_READONLY | libsqlite3_sys::SQLITE_OPEN_NOMUTEX;
let rc = unsafe { libsqlite3_sys::sqlite3_open_v2(c_path.as_ptr(), &mut raw, flags, std::ptr::null()) };
let guard = Self(raw);
if rc != libsqlite3_sys::SQLITE_OK || raw.is_null() {
return None;
}
unsafe {
libsqlite3_sys::sqlite3_busy_timeout(raw, 200);
}
Some(guard)
}
fn prepare(&self, sql: &str) -> Option<SqliteStmt> {
let c_sql = std::ffi::CString::new(sql).ok()?;
let mut stmt: *mut libsqlite3_sys::sqlite3_stmt = std::ptr::null_mut();
let rc =
unsafe { libsqlite3_sys::sqlite3_prepare_v2(self.0, c_sql.as_ptr(), -1, &mut stmt, std::ptr::null_mut()) };
let guard = SqliteStmt(stmt);
(rc == libsqlite3_sys::SQLITE_OK && !stmt.is_null()).then_some(guard)
}
}
impl Drop for SqliteDb {
fn drop(&mut self) {
if !self.0.is_null() {
unsafe {
libsqlite3_sys::sqlite3_close(self.0);
}
}
}
}
struct SqliteStmt(*mut libsqlite3_sys::sqlite3_stmt);
impl SqliteStmt {
fn step(&self) -> bool {
unsafe { libsqlite3_sys::sqlite3_step(self.0) == libsqlite3_sys::SQLITE_ROW }
}
fn text(&self, col: std::ffi::c_int) -> Option<String> {
unsafe {
let ptr = libsqlite3_sys::sqlite3_column_text(self.0, col);
if ptr.is_null() {
return None;
}
let len = libsqlite3_sys::sqlite3_column_bytes(self.0, col);
if len <= 0 {
return None;
}
let bytes = std::slice::from_raw_parts(ptr, len as usize);
std::str::from_utf8(bytes).ok().map(str::to_owned)
}
}
}
impl Drop for SqliteStmt {
fn drop(&mut self) {
if !self.0.is_null() {
unsafe {
libsqlite3_sys::sqlite3_finalize(self.0);
}
}
}
}
/// Candidate VS Code Agent Host SQLite databases (`<user>/globalStorage/agent-host.db`),
/// ordered oldest-first so a newer database wins when two editions share a session.
fn vscode_agent_host_dbs(home: &Path) -> Vec<PathBuf> {
let mut bases = vec![home.join("Library/Application Support"), home.join(".config"), home.join("AppData/Roaming")];
let real_home = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE"));
if real_home.as_deref().is_some_and(|h| Path::new(h) == home) {
for var in ["XDG_CONFIG_HOME", "APPDATA"] {
if let Some(dir) = std::env::var_os(var).filter(|v| !v.is_empty()).map(PathBuf::from)
&& !bases.contains(&dir)
{
bases.push(dir);
}
}
}
let mut dbs = Vec::new();
for base in bases {
for app in ["Code", "Code - Insiders"] {
dbs.push(base.join(app).join("User/globalStorage/agent-host.db"));
}
}
for server in [".vscode-server", ".vscode-server-insiders"] {
dbs.push(home.join(server).join("data/User/globalStorage/agent-host.db"));
}
dbs.retain(|p| p.is_file());
dbs.sort_by(|a, b| mtime(a).total_cmp(&mtime(b)));
dbs
}
fn is_generic_vscode_placeholder(title: &str, source: Option<&str>) -> bool {
source != Some("user") && (title.eq_ignore_ascii_case("new session") || title.eq_ignore_ascii_case("new chat"))
}
fn pick_vscode_chat_title(
scs_title: Option<&str>,
scs_source: Option<&str>,
metadata_json: Option<&str>,
payload_json: Option<&str>,
) -> Option<String> {
if let Some(t) = scs_title.map(str::trim).filter(|t| !t.is_empty())
&& !is_generic_vscode_placeholder(t, scs_source)
{
return Some(t.to_owned());
}
for blob in [metadata_json, payload_json].into_iter().flatten() {
let Ok(v) = serde_json::from_str::<serde_json::Value>(blob) else { continue };
let summary = v.pointer("/data/summary").and_then(serde_json::Value::as_str).map(str::trim);
let source = v.pointer("/data/titleSource").and_then(serde_json::Value::as_str);
if let Some(t) = summary.filter(|t| !t.is_empty())
&& !is_generic_vscode_placeholder(t, source)
{
return Some(t.to_owned());
}
}
None
}
/// Session titles VS Code's Agent Host (`vscode-agent-host`) assigns to backing Copilot CLI
/// sessions (`sdkSessionId` → summary or user rename), read from `agent-host.db` without writing.
fn vscode_copilot_titles(home: Option<&Path>) -> HashMap<String, String> {
const FULL_QUERY: &str = "\
SELECT c.provider_data, scs.title, scs.title_source, c.metadata, s.payload \
FROM chats_v2 c \
LEFT JOIN session_chat_state scs \
ON scs.session_uri = c.owner_session_uri AND scs.chat_uri = c.chat_uri \
LEFT JOIN sessions_v2 s \
ON s.session_uri = c.owner_session_uri \
WHERE c.tombstoned = 0 \
ORDER BY COALESCE(s.modified_time, 0) ASC, COALESCE(c.chat_order, 0) ASC";
const FALLBACK_QUERY: &str = "\
SELECT provider_data, NULL, NULL, metadata, NULL \
FROM chats_v2 \
WHERE tombstoned = 0";
let Some(home) = home else { return HashMap::new() };
let mut titles = HashMap::new();
for path in vscode_agent_host_dbs(home) {
let Some(db) = SqliteDb::open_readonly(&path) else { continue };
let Some(stmt) = db.prepare(FULL_QUERY).or_else(|| db.prepare(FALLBACK_QUERY)) else { continue };
while stmt.step() {
let Some(pdata) = stmt.text(0) else { continue };
let Ok(pv) = serde_json::from_str::<serde_json::Value>(&pdata) else { continue };
let Some(sdk_id) = pv.get("sdkSessionId").and_then(serde_json::Value::as_str).filter(|s| !s.is_empty())
else {
continue;
};
let scs_title = stmt.text(1);
let scs_source = stmt.text(2);
let metadata = stmt.text(3);
let payload = stmt.text(4);
if let Some(title) = pick_vscode_chat_title(
scs_title.as_deref(),
scs_source.as_deref(),
metadata.as_deref(),
payload.as_deref(),
) {
titles.insert(sdk_id.to_owned(), title);
}
}
}
titles
}
/// Copilot sessions of the project at `root`: `<config>/session-state/<id>`, titled by VS Code's
/// Agent Host summary/rename (when started from VS Code), their recorded CLI name, or first prompt.
/// Directories without an event log are unfinished sessions and are not listed.
pub fn copilot_sessions(copilot_home: &Path, home: Option<&Path>, root: &Path) -> Vec<ExternalSession> {
let mut pending: Vec<(ExternalSession, bool)> = std::fs::read_dir(copilot_home.join("session-state"))
.into_iter()
.flatten()
.flatten()
@@ -316,17 +528,28 @@ pub fn copilot_sessions(copilot_home: &Path, root: &Path) -> Vec<ExternalSession
if !in_project(cwd.as_deref(), root) {
return None;
}
let title = metadata
.get("name")
.map(String::as_str)
.map(str::trim)
.filter(|name| !name.is_empty())
let raw_name = metadata.get("name").map(String::as_str).map(str::trim).filter(|name| !name.is_empty());
let cli_user_named = metadata.get("user_named").is_some_and(|v| v == "true")
&& raw_name.is_some_and(|n| !n.eq_ignore_ascii_case("new session"));
let title = raw_name
.map(short)
.or_else(|| copilot_prompt(&events))
.unwrap_or_else(|| format!("Copilot session {}", &session_id[..session_id.len().min(8)]));
Some(ExternalSession { provider: "copilot".to_owned(), session_id, title, cwd, updated_ms: mtime(&events) })
Some((
ExternalSession { provider: "copilot".to_owned(), session_id, title, cwd, updated_ms: mtime(&events) },
cli_user_named,
))
})
.collect()
.collect();
if !pending.is_empty() {
let vscode_titles = vscode_copilot_titles(home);
for (session, cli_user_named) in &mut pending {
if !*cli_user_named && let Some(title) = vscode_titles.get(&session.session_id) {
session.title = short(title);
}
}
}
pending.into_iter().map(|(s, _)| s).collect()
}
#[cfg(test)]
@@ -427,13 +650,37 @@ mod tests {
let tmp = tempfile::tempdir().unwrap();
assert!(claude_sessions(&tmp.path().join("nope"), Path::new("/work")).is_empty());
assert!(codex_sessions(&tmp.path().join("nope"), Path::new("/work")).is_empty());
assert!(copilot_sessions(&tmp.path().join("nope"), Path::new("/work")).is_empty());
assert!(copilot_sessions(&tmp.path().join("nope"), None, Path::new("/work")).is_empty());
}
fn exec_sqlite(path: &Path, sql: &str) {
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
let c_path = std::ffi::CString::new(path.to_str().unwrap()).unwrap();
let c_sql = std::ffi::CString::new(sql).unwrap();
unsafe {
let mut db: *mut libsqlite3_sys::sqlite3 = std::ptr::null_mut();
assert_eq!(
libsqlite3_sys::sqlite3_open_v2(
c_path.as_ptr(),
&mut db,
libsqlite3_sys::SQLITE_OPEN_READWRITE | libsqlite3_sys::SQLITE_OPEN_CREATE,
std::ptr::null(),
),
libsqlite3_sys::SQLITE_OK
);
assert_eq!(
libsqlite3_sys::sqlite3_exec(db, c_sql.as_ptr(), None, std::ptr::null_mut(), std::ptr::null_mut()),
libsqlite3_sys::SQLITE_OK
);
libsqlite3_sys::sqlite3_close(db);
}
}
#[test]
fn lists_copilot_sessions_with_names_and_prompt_fallbacks() {
fn lists_copilot_sessions_with_names_block_scalars_vscode_titles_and_prompt_fallbacks() {
let tmp = tempfile::tempdir().unwrap();
let session = tmp.path().join("session-state/copilot-1");
let copilot_home = tmp.path().join(".copilot");
let session = copilot_home.join("session-state/copilot-1");
write(
&session.join("events.jsonl"),
&[
@@ -447,30 +694,71 @@ mod tests {
)
.unwrap();
let unnamed = tmp.path().join("session-state/copilot-2");
let block_scalar = copilot_home.join("session-state/copilot-block");
write(&block_scalar.join("events.jsonl"), &[json!({"type": "session.start", "data": {}})]);
std::fs::write(
block_scalar.join("workspace.yaml"),
"id: copilot-block\ncwd: /work/app\nname: |-\n check why excalidraw font\n is not displayed\nuser_named: false\n",
)
.unwrap();
let vscode_renamed = copilot_home.join("session-state/copilot-vscode");
write(
&vscode_renamed.join("events.jsonl"),
&[json!({"type": "user.message", "data": {"content": "create a branch deng/session add Create Session"}})],
);
std::fs::write(
vscode_renamed.join("workspace.yaml"),
"id: copilot-vscode\ncwd: /work/app\nclient_name: vscode-agent-host\nname: create a branch deng/session add Create Session\nuser_named: false\n",
)
.unwrap();
let vscode_placeholder = copilot_home.join("session-state/copilot-placeholder");
write(&vscode_placeholder.join("events.jsonl"), &[json!({"type": "session.start", "data": {}})]);
std::fs::write(
vscode_placeholder.join("workspace.yaml"),
"id: copilot-placeholder\ncwd: /work/app\nname: Greeting exchange\nuser_named: false\n",
)
.unwrap();
let unnamed = copilot_home.join("session-state/copilot-2");
write(
&unnamed.join("events.jsonl"),
&[json!({"type": "user.message", "data": {"content": "add a regression test"}})],
);
std::fs::write(unnamed.join("workspace.yaml"), "id: copilot-2\ncwd: /work/app\n").unwrap();
let empty = tmp.path().join("session-state/copilot-empty");
let empty = copilot_home.join("session-state/copilot-empty");
std::fs::create_dir_all(&empty).unwrap();
std::fs::write(empty.join("workspace.yaml"), "id: copilot-empty\ncwd: /work/app\n").unwrap();
let other = tmp.path().join("session-state/copilot-other");
let other = copilot_home.join("session-state/copilot-other");
write(
&other.join("events.jsonl"),
&[json!({"type": "user.message", "data": {"content": "unrelated project"}})],
);
std::fs::write(other.join("workspace.yaml"), "id: copilot-other\ncwd: /other\n").unwrap();
let sessions = copilot_sessions(tmp.path(), Path::new("/work"));
assert_eq!(sessions.len(), 2);
exec_sqlite(
&tmp.path().join(".config/Code/User/globalStorage/agent-host.db"),
"CREATE TABLE sessions_v2 (session_uri TEXT PRIMARY KEY, payload TEXT, modified_time INTEGER);
CREATE TABLE session_chat_state (session_uri TEXT, chat_uri TEXT, title TEXT, title_source TEXT);
CREATE TABLE chats_v2 (chat_uri TEXT PRIMARY KEY, owner_session_uri TEXT, chat_order INTEGER, provider_data TEXT, metadata TEXT, tombstoned INTEGER);
INSERT INTO sessions_v2 VALUES ('copilotcli:/vs1', '{}', 100);
INSERT INTO chats_v2 VALUES ('chat:/vs1', 'copilotcli:/vs1', 0, '{\"sdkSessionId\":\"copilot-vscode\"}', '{\"data\":{\"summary\":\"Session\",\"titleSource\":\"user\"}}', 0);
INSERT INTO sessions_v2 VALUES ('copilotcli:/vs2', '{}', 100);
INSERT INTO chats_v2 VALUES ('chat:/vs2', 'copilotcli:/vs2', 0, '{\"sdkSessionId\":\"copilot-placeholder\"}', '{\"data\":{\"summary\":\"New session\",\"titleSource\":\"auto\"}}', 0);",
);
let sessions = copilot_sessions(&copilot_home, Some(tmp.path()), Path::new("/work"));
assert_eq!(sessions.len(), 5);
let mut by_id: HashMap<_, _> = sessions.into_iter().map(|s| (s.session_id.clone(), s)).collect();
let named = by_id.remove("copilot-1").unwrap();
assert_eq!((named.provider.as_str(), named.title.as_str()), ("copilot", "Fix parser and tests"));
assert_eq!(named.cwd.as_deref(), Some("/work/app/api"));
assert_eq!(by_id.remove("copilot-block").unwrap().title, "check why excalidraw font is not displayed");
assert_eq!(by_id.remove("copilot-vscode").unwrap().title, "Session");
assert_eq!(by_id.remove("copilot-placeholder").unwrap().title, "Greeting exchange");
assert_eq!(by_id.remove("copilot-2").unwrap().title, "add a regression test");
}
+1 -2
Переглянути файл
@@ -1415,12 +1415,11 @@ impl AgentManager {
if let Some(spec) = self.shared.spec("copilot")
&& let Some(dir) = native::copilot::config_dir(&spec.env, home.as_deref())
{
out.extend(external::copilot_sessions(&dir, &root));
out.extend(external::copilot_sessions(&dir, home.as_deref(), &root));
}
let known = self.imported_session_ids();
out.retain(|s| !known.contains(&s.session_id));
out.sort_by(|a, b| b.updated_ms.total_cmp(&a.updated_ms));
out.truncate(50);
out
}
+1 -1
Переглянути файл
@@ -730,7 +730,7 @@ impl CopilotShim {
let history = match self.call("session.getMessages", json!({ "sessionId": session_id })).await {
Ok(history) => history,
Err(error) => {
tracing::info!("copilot session {session_id}: could not load history: {}", error.message);
tracing::warn!("copilot session {session_id}: could not load history: {}", error.message);
return;
}
};
+7
Переглянути файл
@@ -3405,10 +3405,17 @@ impl LspManager {
if changes.is_empty() {
continue;
}
// jdtls rebuilds a source file that changed on disk but keeps the diagnostics of the
// open files it checked before: a reference to a class another tool adds after
// rewriting the open file stays "cannot be resolved" until the file is reopened.
// Sending the open files again makes it check them against the new sources.
let recheck_open = jdtls && changes.iter().any(|(p, _)| p.extension().is_some_and(|e| e == "java"));
let changes: Vec<Value> =
changes.iter().map(|(p, c)| json!({ "uri": uri::path_to_uri(p), "type": *c as u8 })).collect();
if let Err(e) = run.peer.notify("workspace/didChangeWatchedFiles", json!({ "changes": changes })) {
tracing::debug!("{}: didChangeWatchedFiles: {e}", s.name);
} else if recheck_open {
self.resync_documents(&s, run.generation);
}
}
}
+25
Переглянути файл
@@ -482,6 +482,31 @@ async fn dart_file_watching_requires_an_explicit_registration() {
}
}
#[tokio::test(flavor = "multi_thread")]
async fn java_sources_changed_on_disk_send_the_open_files_to_jdtls_again() {
let h = harness_for("java", "java", &[("jdtls", incremental_caps())], &[]);
let (_, main) = h.open("Main.java", "class Main { String s = Helper.greet(); }");
h.wait_status("jdtls", ServerStatus::Ready).await;
let s = h.launcher.state("jdtls");
let resent = || {
s.notified("textDocument/didChange")
.iter()
.filter(|v| v["textDocument"]["uri"] == uri_of(&main) && v["contentChanges"][0]["text"].is_string())
.count()
};
// Another tool adds the class the open file refers to.
let helper = h.root.join("Helper.java");
h.mgr.watched_files_changed(std::slice::from_ref(&helper), &[], &[], &[]);
eventually(|| s.notified("workspace/didChangeWatchedFiles").len() == 1).await;
eventually(|| resent() == 1).await;
// Files that are not Java sources leave the open files alone.
h.mgr.watched_files_changed(&[], &[h.root.join("notes.txt")], &[], &[]);
h.mgr.watched_files_changed(&[], &[h.root.join("pom.xml")], &[], &[]);
tokio::time::sleep(Duration::from_millis(200)).await;
assert_eq!(resent(), 1);
h.mgr.shutdown_all().await;
}
// ------------------------------------------------------------------ tests
#[tokio::test(flavor = "multi_thread")]
+90
Переглянути файл
@@ -0,0 +1,90 @@
/**
* Git log row colors: User, Date and Hash use the normal text color on a regular
* commit, and are dimmed together with the subject on a merge commit.
*/
import { expect, stubDesktop, test } from "./fixtures";
test("dims the metadata columns only on merge commits", async ({ workbench: page }) => {
await stubDesktop(page);
await page.evaluate(async () => {
const root = "/dev/acme-api";
const id = (i: number) => i.toString(16).padStart(40, "0");
const commit = (i: number, parents: number[], summary: string) => ({
id: id(i),
shortId: id(i).slice(-8),
parents: parents.map(id),
refs: i === 0 ? ["HEAD", "main"] : [],
author: `Author ${i}`,
email: "[email protected]",
timeMs: 1_700_000_000_000 - i * 60_000,
summary,
message: summary,
});
const commits = [
commit(0, [1, 2], "Merge branch 'feature'"),
commit(1, [3], "Regular change"),
commit(2, [3], "Feature change"),
commit(3, [], "Initial"),
];
const h = window.__ipc.handlers;
h.vcs_log = ({ query }) => {
const { skip, limit, range } = query as { skip: number; limit: number; range?: string };
return range ? [] : commits.slice(skip, limit ? skip + limit : undefined);
};
h.vcs_log_refs = () => ({});
h.vcs_branches = () => [];
h.vcs_branch_info = () => ({
head: "main",
headCommit: id(0),
upstream: null,
ahead: 0,
behind: 0,
operation: null,
});
h.vcs_config_get = () => null;
h.vcs_commit_files = () => [];
h.vcs_log_details_batch = ({ revisions }) =>
(revisions as string[]).map(() => ({
message: "",
containingBranches: [],
signature: "N",
signer: "",
key: "",
fingerprint: "",
}));
const storeModule = "/src/features/vcs/store.ts";
const { useVcs } = await import(/* @vite-ignore */ storeModule);
useVcs.setState({ available: true, root, repo: root, roots: [root], branchesLoaded: true });
const contextModule = "/src/platform/context.ts";
const { setContext } = await import(/* @vite-ignore */ contextModule);
setContext("vcsAvailable", true);
const optionsModule = "/src/features/vcs/logOptions.ts";
const { useLogOptions } = await import(/* @vite-ignore */ optionsModule);
useLogOptions.setState({ showHash: true, highlightMerges: true });
const actionsModule = "/src/platform/actions.ts";
const { executeAction } = await import(/* @vite-ignore */ actionsModule);
await executeAction("vcs.showLog");
});
const list = page.getByRole("listbox", { name: "Commits" });
await expect(list.getByRole("option")).toHaveCount(4);
const colors = (summary: string) =>
list
.getByRole("option")
.filter({ hasText: summary })
.evaluate((row) => {
const color = (el: Element | null) => (el ? getComputedStyle(el).color : null);
const subject = row.querySelector("[class*=subjectText]");
const author = row.querySelector('[title^="Author "]');
const hash = [...row.querySelectorAll("span")].find((s) => /^0+[0-9a-f]$/.test(s.textContent ?? ""));
return { subject: color(subject), author: color(author), hash: color(hash ?? null) };
});
const regular = await colors("Regular change");
const merge = await colors("Merge branch 'feature'");
expect(regular.author).toBe(regular.subject);
expect(regular.hash).toBe(regular.subject);
expect(merge.author).toBe(merge.subject);
expect(merge.hash).toBe(merge.subject);
expect(merge.author).not.toBe(regular.author);
});
+1 -1
Переглянути файл
@@ -754,7 +754,7 @@ export function AgentsView() {
<div className={styles.empty}>{externalError}</div>
) : (
<div className={styles.external}>
{external.map((s) => {
{external.slice(0, 50).map((s) => {
const key = externalKey(s.provider, s.sessionId);
return (
<div key={key} className={styles.row} title={s.cwd ?? s.sessionId}>
+11 -4
Переглянути файл
@@ -16,7 +16,7 @@ import {
} from "./store";
import styles from "./Agents.module.css";
/** The backend lists at most this many sessions, newest first. */
/** At most this many matching sessions are shown at once, newest first. */
const LISTED_MAX = 50;
const ROW = 24;
@@ -74,7 +74,7 @@ function ImportSessionsDialog() {
const [frozen, setFrozen] = useState<Row[] | null>(null);
const abort = useRef<AbortController | null>(null);
const rows = useMemo<Row[]>(() => {
const matched = useMemo<Row[]>(() => {
const q = query.trim().toLowerCase();
return external
.map((s) => ({
@@ -87,8 +87,15 @@ function ImportSessionsDialog() {
updatedMs: s.updatedMs ?? 0,
}))
.filter((r) => !importing.has(r.key))
.filter((r) => !q || r.title.toLowerCase().includes(q) || r.folder.toLowerCase().includes(q));
.filter(
(r) =>
!q ||
r.title.toLowerCase().includes(q) ||
r.folder.toLowerCase().includes(q) ||
r.sessionId.toLowerCase().includes(q),
);
}, [external, importing, query, root]);
const rows = useMemo(() => matched.slice(0, LISTED_MAX), [matched]);
const view = frozen ?? rows;
// The lead is drawn as selected: keep it on a selected row the list still shows, else on none.
@@ -192,7 +199,7 @@ function ImportSessionsDialog() {
? tx`Forking ${Math.min(progress.done + 1, progress.total)} of ${progress.total}…`
: tx`Importing ${Math.min(progress.done + 1, progress.total)} of ${progress.total}…`}
</span>
) : shown && external.length >= LISTED_MAX ? (
) : shown && matched.length > LISTED_MAX ? (
<span className={styles.chooserHint}>
<T>Only the 50 most recent sessions are shown.</T>
</span>
+18 -4
Переглянути файл
@@ -2955,16 +2955,29 @@ describe("import sessions dialog", () => {
expect(box.getAttribute("aria-activedescendant")).toBe(row(/Add tests/).id);
});
it("filters by title and folder", async () => {
backend.external = [...sessions, third];
it("filters by title, folder, and session id, including past the first 50 sessions", async () => {
const older = Array.from({ length: 55 }, (_, i) => ({
provider: "copilot",
sessionId: `older-${i}`,
title: i === 53 ? "Storage team work summary" : `Routine sync ${i}`,
cwd: "/work",
updatedMs: 0,
}));
backend.external = [...sessions, third, ...older];
open();
await listed("Login fix");
expect(screen.queryByText("Storage team work summary")).toBeNull();
fireEvent.change(screen.getByLabelText("Filter sessions"), { target: { value: "work/api" } });
expect(screen.queryByText("Login fix")).toBeNull();
expect(screen.getByText("Fix flaky test")).toBeInTheDocument();
fireEvent.change(screen.getByLabelText("Filter sessions"), { target: { value: "ADD" } });
expect(screen.getByText("Add tests")).toBeInTheDocument();
expect(screen.queryByText("Fix flaky test")).toBeNull();
fireEvent.change(screen.getByLabelText("Filter sessions"), { target: { value: "THREAD-1" } });
expect(screen.getByText("Add tests")).toBeInTheDocument();
fireEvent.change(screen.getByLabelText("Filter sessions"), { target: { value: "Storage team" } });
expect(screen.getByText("Storage team work summary")).toBeInTheDocument();
expect(screen.queryByText("Only the 50 most recent sessions are shown.")).toBeNull();
});
it("does not import a session that the filter hides", async () => {
@@ -3067,11 +3080,12 @@ describe("import sessions dialog", () => {
cwd: null,
updatedMs: 0,
}));
backend.external = many(50);
// The backend lists every session; the dialog shows the 50 newest matches.
backend.external = many(51);
open();
await waitFor(() => expect(screen.getByText("Only the 50 most recent sessions are shown.")).toBeInTheDocument());
act(() => hideImportSessions());
backend.external = many(49);
backend.external = many(50);
act(() => showImportSessions());
await listed("Session 0");
expect(screen.queryByText("Only the 50 most recent sessions are shown.")).toBeNull();
+2 -1
Переглянути файл
@@ -217,7 +217,8 @@ function CommitRowView({
key={cid}
className={clsx(
styles.columnCell,
styles.muted,
// Dimmed with the subject: merge commits and commits outside the cherry-pick selection.
(merge || outsideUnpicked) && styles.muted,
column.id === "author" && mine && styles.mine,
column.id === "hash" && styles.hash,
)}