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

...
Автор SHA1 Повідомлення Дата
l0ng-ai fc8546acdb fix(java): put Maven system-scope jars on the run and build classpath
A dependency with <scope>system</scope> and a <systemPath> (e.g.
${pom.basedir}/src/main/resources/lib/x.jar) was missing at run time: the POM reader
dropped systemPath, so when Maven's runtime classpath or the Java language server left the
jar out, nothing added it back. Existing system-scope jars are now added to the owning
module's javac and Run/Debug classpaths, as IntelliJ IDEA does, with basedir and POM
properties (inherited, nested) resolved.

Fixes #7194
2026-12-01 19:44:33 +08:00
Ivan 281c2ff1e5 fix(logging): shrink the log writer queue from 128000 to 16384 lines (#7211)
tracing-appender's default non-blocking queue holds 128 000 lines and is allocated up front (about 4 MB) for a backlog the writer thread never builds. The log writer uses a 16 384-line queue.

Co-authored-by: Pecnikas <[email protected]>
2026-12-01 19:22:17 +08:00
langxpтаkradme 4276250056 fix(agents): keep Codex forks writable (#7204)
A Codex fork could fail on its first message with "already has an active writer" because the original task's app-server owned the new thread. The fork is created on its own task's connection, and a session held by another writer offers Retry or Fork while keeping the submitted draft.

Co-authored-by: kradme <[email protected]>
2026-12-01 19:21:51 +08:00
koeriaтаkoeria ba04491ace fix(index): skip rewriting index.snapshot when a scan has no changes (#7214)
A reconcile scan that found nothing new still rewrote the whole index snapshot (30 MB, 1.3–19 s on a large Flutter project). The snapshot is now written only when the scan changed the index or the snapshot is missing; tests pin root-anchored .gitignore / info/exclude handling for build output.

Fixes #7208

Co-authored-by: koeria <[email protected]>
2026-12-01 19:21:43 +08:00
Ivan 660a311f21 fix(host): free a closed project's documents and language registry (#7210)
The language manager's apply-edit hook held the project's documents strongly while the documents kept the manager alive through their observers, so every closed project's documents, language registry and language manager leaked. The hook now holds a weak reference.

Co-authored-by: Pecnikas <[email protected]>
2026-12-01 19:21:30 +08:00
koeriaтаkoeria 92bf9354fe fix(lsp): skip Dart Code Vision references for inherited Flutter lifecycle methods (#7216)
Code Vision asked the Dart server for references of every @override Flutter lifecycle method (build, initState, dispose…), which on a large app floods the single-isolate server and stalls completions. Usages counts are no longer requested for those inherited overrides.

Fixes #7206

Co-authored-by: koeria <[email protected]>
2026-12-01 18:57:07 +08:00
audichuang 54da9c2c12 fix(editor): overwrite a whole emoji instead of leaving half a surrogate pair (#7220)
In overwrite mode, typing over an emoji replaced only its high surrogate and left a broken low half. A replaced range that ends inside a surrogate pair now takes the whole pair.

Co-authored-by: audichuang <[email protected]>
2026-12-01 18:57:01 +08:00
audichuang 9ba3150998 fix(editor): unescape \/ when copying from a JavaScript string (#7218)
Copying from inside a JavaScript/TypeScript string literal unescapes its escapes, as IDEA does, but left \/ as is. It is now unescaped in JavaScript strings, and kept in strings of languages embedded in template literals.

Co-authored-by: audichuang <[email protected]>
2026-12-01 18:56:52 +08:00
l0ng-ai 190e5639f1 feat(docker): run Dockerfile and Docker Image containers in the background (#7215)
Dockerfile (when it runs the built image) and Docker Image run configurations get Run in the background (-d), as Docker Compose has: the container starts detached (a previous one of the same name is removed first) and the Run window follows docker logs; Stop ends only the log follower. Unchecked, command lines are unchanged.

Fixes #7180
2026-12-01 18:06:09 +08:00
28 змінених файлів з 1092 додано та 91 видалено

No files matched your search

+75 -38
Переглянути файл
@@ -2050,46 +2050,63 @@ impl AgentManager {
return Err(IdeError::invalid("wait until the agent is done"));
}
let epoch = self.shared.shutdown_epoch();
let live = source.ensure_session(epoch).await.map_err(IdeError::internal)?;
// A Codex fork must be opened by its own task: the creating app-server owns its writer.
// It can also fork a recorded thread whose writer is held by another process.
let codex_source = {
let s = source.state.lock();
(s.task.provider == "codex").then(|| s.session_id.clone()).flatten()
};
let live = if codex_source.is_none() {
Some(source.ensure_session(epoch).await.map_err(IdeError::internal)?)
} else {
None
};
let total = turn_starts(&source.state.lock().history.conversation.main.entries).len() as u32;
let keep = turns.unwrap_or(total).min(total);
if !live.capabilities.fork || (keep < total && !live.capabilities.rollback) {
let capabilities = live.as_ref().map(|l| l.capabilities).unwrap_or(source.state.lock().task.capabilities);
if !capabilities.fork || (keep < total && !capabilities.rollback) {
return Err(IdeError::invalid("this agent can't copy a conversation from there"));
}
let (cwd, provider_id, mcp_overrides, project_root) = {
let s = source.state.lock();
let t = &s.task;
(t.cwd.0.clone(), t.provider.clone(), t.mcp_overrides.clone(), t.project_root.clone().map(|p| p.0))
};
let mcp_servers = source.shared.mcp_servers_for_session(&provider_id, &live.init, &mcp_overrides);
let roots = source.shared.additional_directories(&live.init, &cwd, project_root.as_deref());
let skills_delivery = source.stage_skills(stage_key(live.driver), &cwd).await;
let memory_delivery = source.stage_memory(&provider_id, &cwd).await;
let cwd_s = dunce::canonicalize(&cwd).unwrap_or(cwd).to_string_lossy().into_owned();
let reply: Value = live
.peer
.request(
"session/fork",
{
let mut params = session_params(
&cwd_s,
&mcp_servers,
skills_delivery.as_ref(),
memory_delivery.as_ref(),
&roots,
);
params["sessionId"] = json!(live.session);
params
},
None,
let session = if let Some(live) = &live {
let (cwd, provider_id, mcp_overrides, project_root) = {
let s = source.state.lock();
let t = &s.task;
(t.cwd.0.clone(), t.provider.clone(), t.mcp_overrides.clone(), t.project_root.clone().map(|p| p.0))
};
let mcp_servers = source.shared.mcp_servers_for_session(&provider_id, &live.init, &mcp_overrides);
let roots = source.shared.additional_directories(&live.init, &cwd, project_root.as_deref());
let skills_delivery = source.stage_skills(stage_key(live.driver), &cwd).await;
let memory_delivery = source.stage_memory(&provider_id, &cwd).await;
let cwd_s = dunce::canonicalize(&cwd).unwrap_or(cwd).to_string_lossy().into_owned();
let reply: Value = live
.peer
.request(
"session/fork",
{
let mut params = session_params(
&cwd_s,
&mcp_servers,
skills_delivery.as_ref(),
memory_delivery.as_ref(),
&roots,
);
params["sessionId"] = json!(live.session);
params
},
None,
)
.await
.map_err(|e| IdeError::internal(source.describe(e)))?;
Some(
reply
.get("sessionId")
.and_then(Value::as_str)
.ok_or_else(|| IdeError::internal("the agent returned no session"))?
.to_owned(),
)
.await
.map_err(|e| IdeError::internal(source.describe(e)))?;
let session = reply
.get("sessionId")
.and_then(Value::as_str)
.ok_or_else(|| IdeError::internal("the agent returned no session"))?
.to_owned();
} else {
None
};
let file = {
let s = source.state.lock();
let mut entries = s.history.conversation.main.entries.clone();
@@ -2115,7 +2132,7 @@ impl AgentManager {
};
TaskFile {
task,
session_id: Some(session),
session_id: session,
entries,
wanted: s.wanted.clone(),
pending_model: None,
@@ -2130,12 +2147,19 @@ impl AgentManager {
pending_rollback: total - keep,
title_renamed: s.title_renamed,
ephemeral: s.ephemeral,
pending_native_fork: None,
pending_native_fork: codex_source.map(|source| ForkStart { source, target: None }),
}
};
// Copying may have started the source's agent: it stops again once idle.
source.release_when_idle();
if live.is_some() {
source.release_when_idle();
}
let task = Task::restore(file, self.shared.clone());
if live.is_none() {
// Establish the fork before returning so its snapshot cannot drift while the source continues.
task.ensure_session(epoch).await.map_err(IdeError::internal)?;
task.release_when_idle();
}
self.tasks.write().insert(task.id.clone(), task.clone());
task.persist();
task.emit_task();
@@ -4949,6 +4973,19 @@ impl Task {
if let Some(message) = self.sign_in_error(&e, Some(&sign_in_message)) {
return Err(SessionOpenError { message, allow_acp_fallback: false });
}
// A writer conflict is temporary: retrying must retain the original session ID.
if spec.driver == provider::Driver::Codex
&& matches!(&e, RpcError::Server { message, .. } if message.contains("already has an active writer"))
{
return Err(SessionOpenError {
message: format!(
"Couldn't reopen this conversation's {} session: {}",
spec.name,
self.describe(e)
),
allow_acp_fallback: false,
});
}
if pending_model.is_some() {
return Err(SessionOpenError {
message: format!(
+35
Переглянути файл
@@ -2191,6 +2191,41 @@ async fn a_session_that_fails_to_load_is_reported_and_replaced_only_when_sent_ag
assert_eq!(calls(&agent), ["session/load", "session/new", "session/prompt"]);
}
/// A locked Codex recording can be forked without resuming it or moving its writer between tasks.
#[tokio::test(flavor = "multi_thread")]
async fn codex_writer_conflict_can_retry_or_fork_on_a_new_connection() {
let tmp = tempfile::tempdir().unwrap();
let task = {
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
let task = mgr
.create(NewAgentTask { prompt: text("again"), provider: "codex".into(), ..Default::default() })
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
mgr.shutdown();
task
};
let agent = Arc::new(FakeAgent {
load_error: Some((codes::INVALID_PARAMS, "thread s1 already has an active writer".into())),
..Default::default()
});
let mgr = manager(tmp.path(), agent.clone());
for _ in 0..2 {
mgr.prompt(&task.id, text("again"), false).await.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Failed).await;
}
assert!(!agent.calls.lock().iter().any(|c| c == "session/new"));
let copy = mgr.fork(&task.id, None).await.unwrap();
assert_eq!(agent.forks.lock().last().unwrap()["sessionId"], "s1");
let copy_handle = mgr.task(&copy.id).unwrap();
assert_eq!(copy_handle.live.lock().as_ref().unwrap().session, "s2");
let loads = agent.calls.lock().iter().filter(|c| *c == "session/load").count();
mgr.prompt(&copy.id, text("again"), false).await.unwrap();
wait_for(&mgr, &copy.id, AgentStatus::Ready).await;
assert_eq!(agent.calls.lock().iter().filter(|c| *c == "session/load").count(), loads);
mgr.shutdown();
}
fn text(t: &str) -> AgentPrompt {
AgentPrompt { text: t.into(), ..AgentPrompt::default() }
}
+3 -3
Переглянути файл
@@ -17,8 +17,8 @@ pub use launch_resources::process_launch_resources;
pub use modules::record_module_build;
pub use single::{
SingleFileTarget, compile_file_plan, compile_file_plan_cancellable, find_javac, gradle_compile_file_plan,
has_gradle_file_target, javac_step, module_classpath, module_classpath_without_build, module_classpaths,
single_file_classpath, single_file_target,
has_gradle_file_target, javac_step, maven_system_classpath, module_classpath, module_classpath_without_build,
module_classpaths, single_file_classpath, single_file_target,
};
pub use structure::{
StructureJdk, StructureRoots, artifact_file, artifact_output, language_release, structure_compile_file_plan,
@@ -986,7 +986,7 @@ fn maven_launch_projects<'a>(
}
projects.push(p);
for dep in &p.dependencies {
if !dep.resolved() || (dep.scope == "test" && (!test || p.pom != start.pom)) {
if !dep.resolved() || dep.scope == "system" || (dep.scope == "test" && (!test || p.pom != start.pom)) {
continue;
}
if let Some(upstream) = reactor.iter().find(|u| {
+87 -4
Переглянути файл
@@ -180,6 +180,30 @@ pub fn find_javac(env: &BTreeMap<String, String>) -> String {
exe.to_owned()
}
/// Existing system-scope dependencies of this module. Maven resolves these from
/// their local files and does not pass them transitively to reactor dependents.
pub fn maven_system_classpath(root: &Path, model: &BuildModel, module: &Path) -> Vec<PathBuf> {
let Some(maven) = &model.maven else { return Vec::new() };
let module = root.join(module);
maven
.projects
.iter()
.find(|p| root.join(&p.dir) == module)
.into_iter()
.flat_map(|p| &p.system_paths)
.filter(|p| p.is_file())
.cloned()
.collect()
}
fn with_system_classpath(root: &Path, model: &BuildModel, module: &Path, classpath: String) -> String {
let system = maven_system_classpath(root, model, module);
if system.is_empty() {
return classpath;
}
join_classpath(std::env::split_paths(&classpath).chain(system).map(|p| p.to_string_lossy().into_owned()))
}
/// Dependency classpath of the module: existing reactor class directories plus
/// `mvn dependency:build-classpath` (which resolves without compiling anything,
/// so `-am` stays cheap). Entries are platform-separated (`;` on Windows).
@@ -233,7 +257,7 @@ pub fn module_classpath_without_build(
&& cached.version == CLASSPATH_CACHE_VERSION
&& classpath_entries_exist(root, &cached.classpath)
{
return Ok(cached.classpath);
return Ok(with_system_classpath(root, model, &target.module, cached.classpath));
}
classpath(root, model, &target, if test { "test" } else { "runtime" }, false, cancel)
}
@@ -270,7 +294,7 @@ pub fn module_classpaths(
&& classpath_entries_exist(root, &cached.classpath)
{
if i == 0 {
return Ok(cached.classpath);
return Ok(with_system_classpath(root, model, &target.module, cached.classpath));
}
continue;
}
@@ -298,7 +322,7 @@ pub fn module_classpaths(
}
}
}
Ok(classpaths.into_iter().next().unwrap())
Ok(with_system_classpath(root, model, &modules[0], classpaths.into_iter().next().unwrap()))
}
/// A module whose classpath the Maven probe resolves, with its cache key and file.
@@ -346,7 +370,8 @@ fn classpath(
compile_first: bool,
cancel: &CancellationToken,
) -> IdeResult<String> {
Ok(classpaths(root, model, &[target], scope, compile_first, cancel)?.pop().unwrap())
let classpath = classpaths(root, model, &[target], scope, compile_first, cancel)?.pop().unwrap();
Ok(with_system_classpath(root, model, &target.module, classpath))
}
/// The classpath of each of `targets` (modules of one reactor) from one Maven probe.
@@ -912,6 +937,64 @@ mod tests {
assert!(args.lines().any(|a| a == "-Dmdep.includeScope=test"), "{args}");
}
#[cfg(unix)]
#[test]
fn system_jars_augment_maven_javac_and_launch_classpaths() {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(dir.path()).unwrap();
write(
&root,
"pom.xml",
r#"<project><groupId>demo</groupId><artifactId>parent</artifactId><version>1</version>
<packaging>pom</packaging><modules><module>app</module></modules>
<properties><lib.dir>src/main/resources/lib</lib.dir></properties></project>"#,
);
write(
&root,
"app/pom.xml",
r#"<project><parent><groupId>demo</groupId><artifactId>parent</artifactId><version>1</version></parent>
<artifactId>app</artifactId>
<properties><lib.file>${lib.dir}/offline.jar</lib.file></properties>
<dependencies>
<dependency><groupId>local</groupId><artifactId>offline</artifactId><version>1</version>
<scope>system</scope><systemPath>${pom.basedir}/${lib.file}</systemPath></dependency>
<dependency><groupId>local</groupId><artifactId>late</artifactId><version>1</version>
<scope>system</scope><systemPath>${project.basedir}/${lib.dir}/late.jar</systemPath></dependency>
<dependency><groupId>local</groupId><artifactId>directory</artifactId><version>1</version>
<scope>system</scope><systemPath>${project.basedir}/${lib.dir}</systemPath></dependency>
</dependencies></project>"#,
);
let jars = "app/src/main/resources/lib";
write(&root, &format!("{jars}/offline.jar"), "");
write(&root, "app/src/main/java/demo/Main.java", "class Main {}");
// The scope-filtered Maven classpath can contain no dependencies.
write(&root, "mvnw", "#!/bin/sh\nmkdir -p app/target\n: > app/target/ide-compile-cp.txt\n");
fs::set_permissions(root.join("mvnw"), fs::Permissions::from_mode(0o755)).unwrap();
let cache = root.join("cache");
let model = crate::load(&root, &cache, None);
let module = root.join("app");
let file = module.join("src/main/java/demo/Main.java");
let jar = root.join(jars).join("offline.jar");
let plan = compile_file_plan(&root, &model, &file).unwrap();
assert!(plan.steps[0].args.windows(2).any(|arg| arg[0] == "-cp" && Path::new(&arg[1]) == jar));
let cancel = CancellationToken::new();
let cp = module_classpath(&root, &model, &module, false, None, &cache, &cancel).unwrap();
let paths: Vec<_> = std::env::split_paths(&cp).collect();
assert_eq!(paths, [module.join("target/classes"), jar.clone()]);
assert!(maven_system_classpath(&root, &model, &root).is_empty());
// Adding a previously absent jar or deleting an old one updates a no-build launch.
fs::remove_file(jar).unwrap();
write(&root, &format!("{jars}/late.jar"), "");
fs::remove_file(root.join("mvnw")).unwrap();
let cp = module_classpath_without_build(&root, &model, &module, false, &cache, &cancel).unwrap();
let paths: Vec<_> = std::env::split_paths(&cp).collect();
assert_eq!(paths, [module.join("target/classes"), root.join(jars).join("late.jar")]);
}
/// Modules launched together resolve their classpaths in one Maven probe and leave
/// the others' cached; a probe another module breaks still resolves the first one.
#[cfg(unix)]
+27 -2
Переглянути файл
@@ -69,6 +69,9 @@ pub struct MavenProject {
pub aggregated: bool,
pub plugins: Vec<MavenPlugin>,
pub dependencies: Vec<MavenDependency>,
/// Local classpath entries from the POM. The synced dependency tree has coordinates only.
#[serde(skip)]
pub system_paths: Vec<PathBuf>,
/// Profile ids declared in this POM.
pub profiles: Vec<String>,
/// Java feature version the project compiles for (`maven.compiler.release`, `java.version`…).
@@ -176,6 +179,7 @@ struct RawDep {
kind: Option<String>,
classifier: Option<String>,
scope: Option<String>,
system_path: Option<String>,
optional: bool,
}
@@ -248,6 +252,7 @@ fn read_dep(e: &Element) -> Option<RawDep> {
kind: e.text_of("type"),
classifier: e.text_of("classifier"),
scope: e.text_of("scope"),
system_path: e.text_of("systemPath"),
optional: e.text_of("optional").is_some_and(|o| o == "true"),
})
}
@@ -1519,7 +1524,13 @@ pub fn load_with_linked_jdk(
let packaging = i(pom.packaging.as_deref().unwrap_or("jar"));
let managed: HashMap<String, &RawDep> = ctx.managed.iter().map(|m| (m.key(), m)).collect();
let managed_version = |d: &RawDep| managed.get(&d.key()).and_then(|m| m.version.clone());
let managed_scope = |d: &RawDep| managed.get(&d.key()).and_then(|m| m.scope.clone());
let scope = |d: &RawDep| {
d.scope
.as_deref()
.or_else(|| managed.get(&d.key()).and_then(|m| m.scope.as_deref()))
.map(i)
.unwrap_or_else(|| "compile".into())
};
let dependencies = ctx
.deps
.iter()
@@ -1529,11 +1540,24 @@ pub fn load_with_linked_jdk(
version: d.version.clone().or_else(|| managed_version(d)).map(|v| i(&v)),
kind: d.kind.clone().unwrap_or_else(|| "jar".into()),
classifier: d.classifier.clone(),
scope: d.scope.clone().or_else(|| managed_scope(d)).unwrap_or_else(|| "compile".into()),
scope: scope(d),
optional: d.optional,
..MavenDependency::default()
})
.collect();
let system_paths = ctx
.deps
.iter()
.filter(|d| scope(d) == "system")
.filter_map(|d| {
let path = d
.system_path
.as_deref()
.or_else(|| managed.get(&d.key()).and_then(|m| m.system_path.as_deref()))?;
let path = i(path);
(!path.contains("${") && Path::new(&path).is_absolute()).then(|| PathBuf::from(path))
})
.collect();
let mut plugins: Vec<RawPlugin> = ctx.plugins.clone();
for a in lifecycle_plugins(&packaging) {
@@ -1592,6 +1616,7 @@ pub fn load_with_linked_jdk(
aggregated,
plugins,
dependencies,
system_paths,
profiles: ctx.profiles.iter().map(|(id, _)| id.clone()).collect(),
java_version: jv,
command: wrapper(&canonical_root, &dir_canon),
+41
Переглянути файл
@@ -246,6 +246,7 @@ pub(crate) async fn resolve_launch(
append_unique_class_paths(&mut class_paths, std::mem::take(&mut info.class_paths));
}
info.class_paths = class_paths;
apply_maven_system_classpath(&mut info, root, &model, &module);
apply_library_classpath(&mut info, root, &settings.project_structure.libraries, test);
if build && !delegated {
match compile::process_launch_resources(root, &model, cache, &info.class_paths, &cancel) {
@@ -563,6 +564,9 @@ async fn resolve_launch_without_jdtls(
},
)?;
info.class_paths = class_paths;
if !by_service {
apply_maven_system_classpath(&mut info, root, &model, &module);
}
apply_library_classpath(&mut info, root, &settings.project_structure.libraries, test);
finish_launch(&mut info, root, &module, settings, &model, &data_dir);
if cancel.is_cancelled() {
@@ -681,6 +685,15 @@ fn entry_key(path: &str, windows: bool) -> String {
if windows { key.to_lowercase() } else { key }
}
fn apply_maven_system_classpath(info: &mut JavaLaunchInfo, root: &Path, model: &BuildModel, module: &Path) {
for path in compile::maven_system_classpath(root, model, module) {
let path = path.to_string_lossy();
if !info.class_paths.iter().chain(&info.module_paths).any(|entry| same_entry(entry, &path, cfg!(windows))) {
info.class_paths.push(path.into_owned());
}
}
}
fn apply_library_classpath(
info: &mut JavaLaunchInfo,
root: &std::path::Path,
@@ -1275,6 +1288,34 @@ mod tests {
assert!(info.hints[0].contains("offline dependency"), "{:?}", info.hints);
}
#[test]
fn java_server_launch_classpath_includes_local_maven_system_jars() {
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap();
let jar = root.join("src/main/resources/lib/offline.jar");
std::fs::create_dir_all(jar.parent().unwrap()).unwrap();
std::fs::write(&jar, "").unwrap();
std::fs::write(
root.join("pom.xml"),
r#"<project><groupId>demo</groupId><artifactId>app</artifactId><version>1</version>
<dependencies><dependency><groupId>local</groupId><artifactId>offline</artifactId><version>1</version>
<scope>system</scope><systemPath>${pom.basedir}/src/main/resources/lib/offline.jar</systemPath>
</dependency></dependencies></project>"#,
)
.unwrap();
let model = ide_build::load(&root, &root.join("cache"), None);
let jar = jar.to_string_lossy().into_owned();
let mut info = JavaLaunchInfo { class_paths: vec!["classes".into()], ..Default::default() };
apply_maven_system_classpath(&mut info, &root, &model, &root);
apply_maven_system_classpath(&mut info, &root, &model, &root);
assert_eq!(info.class_paths, ["classes", &jar]);
info.class_paths.pop();
info.module_paths.push(jar);
apply_maven_system_classpath(&mut info, &root, &model, &root);
assert_eq!(info.class_paths, ["classes"]);
}
/// Maven's launch classpath lists the module's and its reactor siblings' outputs, which
/// the launch already runs from a snapshot: listed twice, MyBatis loads each mapper XML
/// twice and fails with "XML fragments parsed from previous mappers already contains value".
+6 -2
Переглянути файл
@@ -386,8 +386,12 @@ impl Host {
}));
}
{
let documents = documents.clone();
lsp.set_apply_edit_hook(Box::new(move |edit| documents.apply_workspace_edit(&edit).is_ok()));
// Weak: `documents` keeps `lsp` alive through its observers, so a strong handle here would be
// a cycle that leaks every closed project's documents, registry and language manager.
let documents = Arc::downgrade(&documents);
lsp.set_apply_edit_hook(Box::new(move |edit| {
documents.upgrade().is_some_and(|documents| documents.apply_workspace_edit(&edit).is_ok())
}));
}
let syntax = Arc::new(SyntaxCache::new(self.syntax()));
documents.add_observer(Arc::new(SyntaxObserver(syntax.clone())));
+43
Переглянути файл
@@ -87,3 +87,46 @@ fn detached_close_returns_while_runtime_workers_wait_for_the_closing_thread() {
host.shutdown_notebooks_on_exit();
assert!(started.elapsed() < Duration::from_secs(5), "exit joined the finished close instead of timing out");
}
/// `Documents` keeps the language manager alive through its observers and the manager once held the
/// documents back, so a closed project's documents (and everything they reference) were never freed.
/// Checked for the synchronous close and for the detached close that a window uses.
#[test]
fn closing_a_project_frees_its_documents() {
for detached in [false, true] {
assert_close_frees_documents(detached);
}
}
fn assert_close_frees_documents(detached: bool) {
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap().join("project");
std::fs::create_dir_all(&root).unwrap();
let runtime = tokio::runtime::Builder::new_multi_thread().worker_threads(2).enable_all().build().unwrap();
let _guard = runtime.enter();
let host = Arc::new(Host::new(common::host_config(tmp.path())));
host.trust.decide(&root, true, false).unwrap();
host.open_project("main", &root).unwrap();
let (documents, languages) = {
let project = host.project("main").unwrap();
(Arc::downgrade(&project.documents), Arc::downgrade(&project.languages))
};
assert!(documents.upgrade().is_some(), "the open project owns its documents");
if detached {
host.close_project_detached("main");
} else {
host.close_project("main");
}
// The detached close drops the project on its own thread.
let deadline = Instant::now() + Duration::from_secs(5);
while documents.upgrade().is_some() && Instant::now() < deadline {
std::thread::sleep(Duration::from_millis(10));
}
assert!(documents.upgrade().is_none(), "detached={detached}: the documents of a closed project are still alive");
assert!(
languages.upgrade().is_none(),
"detached={detached}: the language registry of a closed project is still alive"
);
}
+71
Переглянути файл
@@ -530,6 +530,77 @@ src/local/
assert!(listed[0].ignored);
}
#[test]
fn root_anchored_gitignore_is_honoured_and_does_not_match_nested_names() {
let dir = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(dir.path()).unwrap();
for f in ["src/a.rs", "build/gen.rs", "build/nested/out.rs", "packages/foo/build/x.rs", "tmp/scratch.rs"] {
touch(&root, f);
}
std::fs::write(
root.join(".gitignore"),
"# Flutter-style root build output
/build/
tmp/
",
)
.unwrap();
let filter = PathFilter::new(&root, &vec![].into(), &[]);
let mut found: Vec<(String, bool)> = filter
.walk(&root, &AtomicBool::new(false))
.iter()
.filter_map(|f| Some((filter.rel(&f.path)?, f.ignored)))
.collect();
found.sort();
// Root-anchored `/build/` ignores only the root `build/` tree. Unanchored
// `tmp/` is also filename-only. A nested directory named `build` is kept.
assert_eq!(
found,
[
(".gitignore", false),
("build/gen.rs", true),
("build/nested/out.rs", true),
("packages/foo/build/x.rs", false),
("src/a.rs", false),
("tmp/scratch.rs", true),
]
.map(|(p, i)| (p.to_owned(), i))
);
for rel in ["build/gen.rs", "build/nested/out.rs", "packages/foo/build/x.rs", "tmp/scratch.rs", "src/a.rs"] {
assert!(!filter.is_excluded(&root.join(rel)), "{rel}");
}
let mut listed: Vec<(String, bool)> = filter
.list_dir(&root.join("build"))
.iter()
.filter_map(|f| Some((filter.rel(&f.path)?, f.ignored)))
.collect();
listed.sort();
assert_eq!(listed, [("build/gen.rs", true)].map(|(p, i)| (p.to_owned(), i)));
}
#[test]
fn root_anchored_exclude_file_is_honoured() {
let dir = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(dir.path()).unwrap();
touch(&root, "src/a.rs");
touch(&root, "build/gen.rs");
std::fs::create_dir_all(root.join(".git/info")).unwrap();
std::fs::write(
root.join(".git/info/exclude"),
"/build/
",
)
.unwrap();
let filter = PathFilter::new(&root, &vec![].into(), &[]);
let mut found: Vec<(String, bool)> = filter
.walk(&root, &AtomicBool::new(false))
.iter()
.filter_map(|f| Some((filter.rel(&f.path)?, f.ignored)))
.collect();
found.sort();
assert_eq!(found, [("build/gen.rs", true), ("src/a.rs", false)].map(|(p, i)| (p.to_owned(), i)));
}
#[test]
fn a_nested_repository_is_not_hidden_by_the_outer_repositorys_gitignore() {
let dir = tempfile::tempdir().unwrap();
+4
Переглянути файл
@@ -390,6 +390,10 @@ impl Store {
})
}
pub(crate) fn snapshot_exists(&self) -> bool {
self.snapshot.is_file()
}
fn open_db(&self) -> Result<Database> {
let file = self.snapshot.with_file_name("index.redb");
let db = match Database::builder().set_cache_size(DB_CACHE_BYTES).create(&file) {
+51 -8
Переглянути файл
@@ -601,8 +601,11 @@ impl Shared {
d.remove(path);
}
}
let index_changed = !stale.is_empty() || !todo.is_empty();
let stale: Vec<String> = stale.iter().filter_map(|p| filter.store_key(p)).collect();
self.persist(&[], &stale, false);
if !stale.is_empty() {
self.persist(&[], &stale, false);
}
let total = todo.len();
if task.is_none() && total >= QUIET_SCAN_FILES {
@@ -674,25 +677,31 @@ impl Shared {
return None;
}
let durable_started = Instant::now();
self.persist(&[], &[], true);
if index_changed {
self.persist(&[], &[], true);
}
let durable = durable_started.elapsed();
let update_elapsed = update_started.elapsed();
let snapshot_started = Instant::now();
if let Some(store) = &self.store {
let recent: Vec<String> = self.recent.lock().iter().filter_map(|p| filter.recent_key(p)).collect();
let d = self.data.read();
let snapshot_started = Instant::now();
if let Err(e) = store.save_snapshot(&d, &filter, guard) {
tracing::warn!("index snapshot: {e}");
// process() may already have applied the change and deleted the snapshot;
// a follow-up reconcile scan can have scheduled=0 and still need to write it.
if index_changed || !store.snapshot_exists() {
let d = self.data.read();
let snapshot_started = Instant::now();
if let Err(e) = store.save_snapshot(&d, &filter, guard) {
tracing::warn!("index snapshot: {e}");
}
tracing::info!("index snapshot: written in {:?}", snapshot_started.elapsed());
*self.snapshot_saved.lock() = Some(Instant::now());
}
tracing::info!("index snapshot: written in {:?}", snapshot_started.elapsed());
if let Err(e) = store.save_recent_file(&recent) {
tracing::warn!("index recent snapshot: {e}");
}
}
let snapshot_elapsed = snapshot_started.elapsed();
*self.snapshot_due.lock() = None;
*self.snapshot_saved.lock() = Some(Instant::now());
if let Some(task) = task {
self.indexing.store(false, Ordering::SeqCst);
self.sink.emit(IdeEvent::Task {
@@ -1443,6 +1452,40 @@ mod metric_tests {
assert_eq!(shared.data.read().symbol_count, 1);
}
#[test]
fn no_change_scan_skips_snapshot_rewrite() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path().join("project");
std::fs::create_dir(&root).unwrap();
let root = dunce::canonicalize(root).unwrap();
std::fs::write(root.join("main.rs"), "fn main() {}\n").unwrap();
let cache = dir.path().join("cache");
let mut index = shared(&root);
index.store = Some(Store::open(&cache, &root, "metrics-test").unwrap());
// A guard after every write, so save_snapshot does not discard the file
// when a directory mtime lands on the same instant as the scan start.
let guard = || SystemTime::now() + std::time::Duration::from_secs(2);
let cold = index.scan(None, &[], None, guard()).unwrap();
assert_eq!(cold.scheduled, 1);
let snapshot = cache.join("index.snapshot");
assert!(snapshot.exists());
let before = std::fs::metadata(&snapshot).unwrap();
// A rewrite would bump mtime; give the filesystem a distinct timestamp.
std::thread::sleep(std::time::Duration::from_millis(20));
let hot = index.scan(None, &[], None, guard()).unwrap();
assert_eq!((hot.discovered, hot.metadata_reused, hot.scheduled), (1, 1, 0));
let after = std::fs::metadata(&snapshot).unwrap();
assert_eq!(after.len(), before.len(), "a no-change scan must not rewrite the snapshot");
assert_eq!(after.modified().unwrap(), before.modified().unwrap());
std::fs::write(root.join("main.rs"), "fn renamed() {}\n").unwrap();
std::thread::sleep(std::time::Duration::from_millis(20));
let changed = index.scan(None, &[], None, guard()).unwrap();
assert_eq!(changed.scheduled, 1);
let rewritten = std::fs::metadata(&snapshot).unwrap();
assert!(rewritten.modified().unwrap() > after.modified().unwrap(), "a changed scan must refresh the snapshot");
}
#[test]
fn extraction_outcomes_are_exclusive_and_forced_parsing_is_counted() {
let dir = tempfile::tempdir().unwrap();
+16
Переглянути файл
@@ -62,6 +62,22 @@ fn round_trip() {
assert!(!loaded[0].detected);
}
#[test]
fn docker_detach_round_trips_in_project_params() {
let dir = tempfile::tempdir().unwrap();
let mut configs = sample();
for (config, (kind, detach)) in configs.iter_mut().zip([("docker-dockerfile", "true"), ("docker-image", "false")]) {
config.kind = kind.into();
config.extras.params.insert("detach".into(), detach.into());
}
save_user_configs(dir.path(), &configs).unwrap();
let project = fs::read_to_string(user_configs_path(dir.path())).unwrap();
assert!(project.contains("params = { detach = \"true\" }"), "{project}");
assert!(project.contains("params = { detach = \"false\" }"), "{project}");
assert_eq!(load_user_configs(dir.path()).unwrap(), configs);
}
#[test]
fn preserves_unrelated_content() {
let dir = tempfile::tempdir().unwrap();
+32 -8
Переглянути файл
@@ -215,20 +215,20 @@ impl GitignoreStack {
{
let mut nested = self.nested.lock();
let target = if dir.file_name().is_some_and(|n| n == ".git") { dir.parent().unwrap_or(dir) } else { dir };
if nested.by_dir.contains_key(target) || nested.by_root.contains_key(target) {
nested.by_dir.retain(|k, _| !k.starts_with(target));
nested.by_root.retain(|k, _| !k.starts_with(target));
}
// Always drop descendant keys. Requiring `target` itself to be a key
// misses a repository created after the watch started: lookups then
// stop at the new `.git`, so the filesystem root is never recorded,
// and `reload_ignore_rules` from that root would leave a stale
// "no rules" cache behind.
nested.by_dir.retain(|k, _| !k.starts_with(target));
nested.by_root.retain(|k, _| !k.starts_with(target));
for stack in nested.by_root.values() {
stack.invalidate_tree(dir);
}
}
let mut cache = self.cache.lock();
self.generation.fetch_add(1, Ordering::Relaxed);
// Lookups always populate every ancestor, so no key below `dir` exists without `dir`.
if cache.contains_key(dir) {
cache.retain(|k, _| !k.starts_with(dir));
}
cache.retain(|k, _| !k.starts_with(dir));
}
pub fn repo_root(&self) -> Option<&Path> {
@@ -545,4 +545,28 @@ mod tests {
stack.invalidate_tree(&workspace.join("sub/.git"));
assert!(stack.is_ignored(&workspace.join("sub/deep/a.tmp"), false));
}
#[test]
fn git_init_after_the_first_listing_is_picked_up_from_the_filesystem_root() {
// The project was opened before `git init`. A listing after the repository
// appears, but before any ignore file is written, caches a nested stack whose
// keys stop at the new `.git` and never include the filesystem root. Reloading
// from that root must still drop those stale "no rules" entries.
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap();
std::fs::write(root.join("shared.ignore-me"), "x").unwrap();
std::fs::write(root.join("private.ignore-me"), "x").unwrap();
let stack = GitignoreStack::new(&root);
assert_eq!(stack.repo_root(), None);
std::fs::create_dir_all(root.join(".git/info")).unwrap();
assert!(!stack.is_ignored(&root.join("shared.ignore-me"), false));
assert!(!stack.is_ignored(&root.join("private.ignore-me"), false));
std::fs::write(root.join(".gitignore"), "/shared.ignore-me\n").unwrap();
std::fs::write(root.join(".git/info/exclude"), "/private.ignore-me\n").unwrap();
stack.reload_repo_level();
let top = root.ancestors().last().unwrap();
stack.invalidate_tree(top);
assert!(stack.is_ignored(&root.join("shared.ignore-me"), false));
assert!(stack.is_ignored(&root.join("private.ignore-me"), false));
}
}
+8 -1
Переглянути файл
@@ -146,7 +146,14 @@ impl Watcher {
// `.git` that now exists (`git init`). `/` is no ancestor of `C:\…` on Windows, so take
// the watch root's own topmost ancestor.
let top = self.root.ancestors().last().unwrap_or(&self.root);
self.rules.invalidate_tree(self.rules.repo_root().unwrap_or(top));
let origin = self.rules.repo_root().unwrap_or(top);
self.rules.invalidate_tree(origin);
// After `git init`, a listing may have cached a nested stack whose keys
// stop at the new `.git` and never include `top`. Drop the watched tree
// itself too, which also covers a Windows `C:\` vs `\\?\C:\` mismatch.
if origin != self.root.as_path() {
self.rules.invalidate_tree(&self.root);
}
}
/// The watched directory (canonical).
+22
Переглянути файл
@@ -371,6 +371,28 @@ fn watcher_read_dir_sees_a_repository_made_after_it_started() {
assert_eq!(ignored, BTreeSet::from(["private.ignore-me".to_string(), "shared.ignore-me".to_string()]));
}
/// Same as above, but the first listing happens after `git init` and before the
/// ignore files exist. That caches a nested stack that never recorded the
/// filesystem root as a key — the case `reload_ignore_rules` hits when the
/// watcher has already seen the new `.git`.
#[test]
fn watcher_read_dir_sees_ignore_files_written_after_a_post_init_listing() {
let (_t, r) = root();
write(&r.join("shared.ignore-me"), "x");
write(&r.join("private.ignore-me"), "x");
let sink: SharedSink = Arc::new(|_| {});
let watcher = Watcher::start(&r, vec![], sink, Box::new(|_| {})).unwrap();
assert_eq!(watcher.repo_root(), None);
write(&r.join(".git/HEAD"), "ref: refs/heads/main\n");
assert!(watcher.read_dir(&r, &[]).unwrap().iter().all(|e| !e.ignored));
write(&r.join(".gitignore"), "/shared.ignore-me\n");
write(&r.join(".git/info/exclude"), "/private.ignore-me\n");
watcher.reload_ignore_rules();
let ignored: BTreeSet<String> =
watcher.read_dir(&r, &[]).unwrap().into_iter().filter(|e| e.ignored).map(|e| e.name).collect();
assert_eq!(ignored, BTreeSet::from(["private.ignore-me".to_string(), "shared.ignore-me".to_string()]));
}
#[test]
fn watcher_reports_changes() {
let (_t, r) = root();
+7 -1
Переглянути файл
@@ -15,6 +15,8 @@ use tracing_subscriber::{EnvFilter, Layer};
const PREFIX: &str = "openidea";
const SUFFIX: &str = "log";
/// Lines waiting for the log writer thread before new ones are dropped.
const LOG_QUEUE_LINES: usize = 16_384;
static LOG_DIR: OnceLock<PathBuf> = OnceLock::new();
static GUARD: OnceLock<WorkerGuard> = OnceLock::new();
@@ -38,7 +40,11 @@ pub fn init(identifier: &str) {
.max_log_files(7)
.build(&dir)
.ok()?;
let (writer, guard) = tracing_appender::non_blocking(appender);
// The default queue holds 128 000 lines and is filled when it is created: 4 MB of memory for a
// backlog the writer thread never builds.
let (writer, guard) = tracing_appender::non_blocking::NonBlockingBuilder::default()
.buffered_lines_limit(LOG_QUEUE_LINES)
.finish(appender);
let _ = GUARD.set(guard);
log_panics(dir.clone());
let _ = LOG_DIR.set(dir);
+21
Переглянути файл
@@ -457,6 +457,27 @@ describe("overwrite mode", () => {
type("XYZ");
expect(show(v)).toBe("abXYZ|\nx");
});
it("overwrites a whole surrogate pair after the caret", () => {
for (const [text, typed, after] of [
["|😀b", "A", "A|b"],
["|ab😀c", "XYZ", "XYZ|c"],
["|是\u200D全角", "非", "非|\u200D全角"],
// A DOM change from 😀 to 🨀 arrives as the new high surrogate alone.
["|😀b", "\ud83e", "\ud83e|\ude00b"],
]) {
const v = make(text!, overwriteField);
toggleOverwrite(v);
v.state.facet(EditorView.inputHandler).some((h) => h(v, 0, 0, typed!, () => v.state.update({})));
expect(show(v)).toBe(after);
}
// A caret between the halves of a pair (Go to Line:Column can put it there) replaces nothing on its own.
const v = make("|😀b", overwriteField);
toggleOverwrite(v);
v.dispatch({ selection: { anchor: 1 } });
v.state.facet(EditorView.inputHandler).some((h) => h(v, 1, 1, "", () => v.state.update({})));
expect(v.state.doc.toString()).toBe("😀b");
});
});
describe("smooth caret", () => {
+4
Переглянути файл
@@ -24,6 +24,10 @@ const overwriteInput = EditorView.inputHandler.of((view, _from, _to, text) => {
if (r.empty) {
const line = state.doc.lineAt(r.head);
to = Math.min(line.to, r.head + text.length);
// A range that ends between the halves of a surrogate pair takes the low half too, unless the
// typed text ends with a high surrogate that pairs with it.
const pair = state.doc.sliceString(to - 1, to + 1);
if (to > r.head && /^[\ud800-\udbff][\udc00-\udfff]$/.test(pair) && !/[\ud800-\udbff]$/.test(text)) to++;
}
return { changes: { from: r.from, to, insert: text }, range: EditorSelection.cursor(r.from + text.length) };
});
+20
Переглянути файл
@@ -98,6 +98,26 @@ describe("string clipboard", () => {
expect(view.state.doc.toString()).toBe('value = ""\\\n"');
});
it.each([
["JavaScript", "javascript", "https://example.test"],
["TypeScript", "typescript", "https://example.test"],
["Python", "python", "https:\\/\\/example.test"],
])("%s unescapes an escaped slash only where the language does", async (mode, language, expected) => {
const view = await make(mode, language, 'value = "«https:\\/\\/example.test»"');
expect(copiedText(view.state)).toBe(expected);
});
it("keeps an escaped slash in a string of a language embedded in JavaScript", async () => {
// The embedded mode loads lazily; load it first so the first parse mounts it.
await loadSupport(findLanguageDescription("SQL", "")!);
const views = await Promise.all(
["", "// filler\n".repeat(400)].map((before) =>
make("JavaScript", "javascript", before + "const q = sql`SELECT '«a\\/b»'`;"),
),
);
for (const view of views) expect(copiedText(view.state)).toBe("a\\/b");
});
it("disables both escaping and unescaping with the setting", async () => {
const settings = { smartKeys: { escapeOnPaste: false, reformatOnPaste: "none" } };
const view = await make("Java", "java", 'value = "«a\\nb»"', settings);
+16 -6
Переглянути файл
@@ -8,9 +8,11 @@ const JS = new Set(["javascript", "typescript"]);
interface PlainString {
quote: string;
language: string;
/** `\/` is an escape: a JavaScript string, not one of a language embedded in a template literal. */
slash: boolean;
}
function readEscape(text: string, at: number, language: string): { end: number; value: string } {
function readEscape(text: string, at: number, language: string, slash = false): { end: number; value: string } {
const rest = text.slice(at + 1);
const ch = rest[0];
const basic: Record<string, string> = { n: "\n", r: "\r", t: "\t", "\\": "\\", '"': '"', "'": "'" };
@@ -18,6 +20,7 @@ function readEscape(text: string, at: number, language: string): { end: number;
if (!["kotlin", "rust"].includes(language)) basic.f = "\f";
if (["python", "go", "c", "cpp"].includes(language)) basic.a = "\x07";
if (!["java", "kotlin", "rust"].includes(language)) basic.v = "\v";
if (slash) basic["/"] = "/";
if (language === "kotlin") basic.$ = "$";
if (language === "java") basic.s = " ";
if (language === "c" || language === "cpp") basic["?"] = "?";
@@ -85,7 +88,9 @@ function plainStringAt(state: EditorState, from: number, to: number, language: s
if ([from, to].some((pos) => pos > node.from + i && pos < node.from + end)) return null;
i = end - 1;
}
return { quote, language };
let embedded = false;
for (let n = node.parent; n; n = n.parent) if (n.type.isTop && n.parent) embedded = true;
return { quote, language, slash: JS.has(language) && !embedded };
}
if (!node.parent) return null;
node = node.parent;
@@ -109,12 +114,12 @@ function escapeText(text: string, literal: PlainString): string {
});
}
function unescapeText(text: string, language: string): string {
function unescapeText(text: string, literal: PlainString): string {
let out = "";
for (let i = 0; i < text.length; i++) {
if (text[i] !== "\\") out += text[i];
else {
const escape = readEscape(text, i, language);
const escape = readEscape(text, i, literal.language, literal.slash);
out += escape.value;
i = escape.end - 1;
}
@@ -151,10 +156,15 @@ export function stringClipboard(language: string | undefined): Extension {
),
EditorView.clipboardOutputFilter.of((text, state) => {
const ranges = state.selection.ranges;
if (ranges.some((r) => r.empty || !plainStringAt(state, r.from, r.to, language))) return text;
const literals: PlainString[] = [];
for (const r of ranges) {
const literal = r.empty ? null : plainStringAt(state, r.from, r.to, language);
if (!literal) return text;
literals.push(literal);
}
const selected = ranges.map((r) => state.sliceDoc(r.from, r.to));
if (text !== selected.join(state.lineBreak)) return text;
return selected.map((part) => unescapeText(part, language)).join(state.lineBreak);
return selected.map((part, i) => unescapeText(part, literals[i]!)).join(state.lineBreak);
}),
];
}
+149 -1
Переглянути файл
@@ -39,7 +39,7 @@ vi.mock("@tauri-apps/api/core", async (orig) => ({
},
}));
const { lensTargets, usagesLensExtension } = await import("./codeLens");
const { lensTargets, skipInheritedLifecycleUsages, usagesLensExtension } = await import("./codeLens");
const { foregroundStarted } = await import("./foreground");
const { lspDoc } = await import("./lsp");
const { useProject } = await import("@/platform/project");
@@ -692,3 +692,151 @@ describe("file changes on disk", () => {
expect(ipc.lspReferences).toHaveBeenCalledTimes(80);
});
});
describe("inherited Dart lifecycle usages", () => {
const textOf = (src: string) => EditorState.create({ doc: src }).doc;
const src = [
"class _PageState extends State<Page> {",
" @override",
" void initState() { super.initState(); }",
"",
" @override",
" Widget build(BuildContext context) { return const SizedBox(); }",
"",
" @override",
" void dispose() { super.dispose(); }",
"",
" @override",
" void didUpdateWidget(Page oldWidget) { super.didUpdateWidget(oldWidget); }",
"",
" @override",
" void didChangeDependencies() { super.didChangeDependencies(); }",
"",
" Future<void> loadData() async {}",
"",
" Widget buildHelper() { return const SizedBox(); }",
"",
" @override Widget createState() => this;",
"",
" @override",
" String toString() => 'page';",
"",
" @override",
" int get hashCode => 1;",
"",
" @override",
" bool operator ==(Object other) => other is _PageState;",
"}",
].join("\n");
const doc = textOf(src);
const lineOf = (snippet: string) => src.split("\n").findIndex((l) => l.includes(snippet));
it("skips Flutter @override lifecycle methods, not other Dart names", () => {
expect(skipInheritedLifecycleUsages("dart", "initState", doc, lineOf("void initState"))).toBe(true);
expect(skipInheritedLifecycleUsages("dart", "build", doc, lineOf("Widget build(BuildContext"))).toBe(true);
expect(skipInheritedLifecycleUsages("dart", "dispose", doc, lineOf("void dispose"))).toBe(true);
expect(skipInheritedLifecycleUsages("dart", "didUpdateWidget", doc, lineOf("void didUpdateWidget"))).toBe(true);
expect(
skipInheritedLifecycleUsages("dart", "didChangeDependencies", doc, lineOf("void didChangeDependencies")),
).toBe(true);
expect(skipInheritedLifecycleUsages("dart", "createState", doc, lineOf("@override Widget createState"))).toBe(true);
expect(skipInheritedLifecycleUsages("dart", "toString", doc, lineOf("String toString"))).toBe(true);
expect(skipInheritedLifecycleUsages("dart", "hashCode", doc, lineOf("int get hashCode"))).toBe(true);
expect(skipInheritedLifecycleUsages("dart", "operator ==", doc, lineOf("bool operator"))).toBe(true);
expect(skipInheritedLifecycleUsages("dart", "==", doc, lineOf("bool operator"))).toBe(true);
expect(skipInheritedLifecycleUsages("dart", "loadData", doc, lineOf("Future<void> loadData"))).toBe(false);
expect(skipInheritedLifecycleUsages("dart", "buildHelper", doc, lineOf("Widget buildHelper"))).toBe(false);
expect(skipInheritedLifecycleUsages("dart", "_PageState", doc, 0)).toBe(false);
expect(skipInheritedLifecycleUsages("rust", "build", doc, lineOf("Widget build(BuildContext"))).toBe(false);
});
it("does not skip a lifecycle name that is not an override", () => {
const plain = textOf("void dispose() {}\nWidget build() { return const SizedBox(); }");
expect(skipInheritedLifecycleUsages("dart", "dispose", plain, 0)).toBe(false);
expect(skipInheritedLifecycleUsages("dart", "build", plain, 1)).toBe(false);
});
});
describe("Dart Code Vision references", () => {
const dart = { doc: 11, path: "/p/page.dart", language: "dart", uiMode: "Dart", readOnly: false };
const src = [
"class _PageState extends State<Page> {",
" @override",
" void initState() {}",
" @override",
" Widget build(BuildContext context) { return const SizedBox(); }",
" Future<void> loadData() async {}",
" void refresh() {}",
"}",
].join("\n");
it("does not query references for @override lifecycle methods", async () => {
ipc.docOutline.mockResolvedValue(
ok([
item("_PageState", "class", 0, [
item("initState", "method", 2),
item("build", "method", 4),
item("loadData", "method", 5),
item("refresh", "method", 6),
]),
]),
);
const view = new EditorView({
state: EditorState.create({
doc: src,
extensions: [lspDoc.of(dart), usagesLensExtension()],
}),
parent: document.body,
});
views.push(view);
await settle();
expect(ipc.lspReferences.mock.calls.map((c) => c[2])).toEqual([
{ line: 0, col: 0 },
{ line: 5, col: 0 },
{ line: 6, col: 0 },
]);
expect(titles(view)).toEqual(["2 usages", "2 usages", "2 usages"]);
});
it("asks Dart references one at a time", async () => {
const pending = deferred<ReturnType<typeof refs>>();
ipc.docOutline.mockResolvedValue(ok(Array.from({ length: 8 }, (_, i) => item(`f${i}`, "function", i))));
ipc.lspReferences.mockReturnValue(pending.promise);
const view = new EditorView({
state: EditorState.create({
doc: Array.from({ length: 8 }, (_, i) => `void f${i}() {}`).join("\n"),
extensions: [lspDoc.of(dart), usagesLensExtension()],
}),
parent: document.body,
});
views.push(view);
await settle();
expect(ipc.lspReferences).toHaveBeenCalledTimes(1);
pending.resolve(refs(1));
await settle();
expect(ipc.lspReferences).toHaveBeenCalledTimes(8);
});
it("does not start a new Dart references wave until a cancelled request has finished", async () => {
const first = deferred<ReturnType<typeof refs>>();
ipc.lspReferences.mockReturnValueOnce(first.promise).mockResolvedValue(refs(2));
ipc.docOutline.mockResolvedValue(ok([item("loadData", "function", 0)]));
const view = new EditorView({
state: EditorState.create({
doc: "void loadData() {}",
extensions: [lspDoc.of(dart), usagesLensExtension()],
}),
parent: document.body,
});
views.push(view);
await settle();
expect(ipc.lspReferences).toHaveBeenCalledTimes(1);
_emitEditorEvent({ type: "docChanged", doc: 9, path: "/p/b.dart", baseVersion: 1, version: 2, changes: [] });
await settle();
expect(ipc.lspReferences).toHaveBeenCalledTimes(1);
first.resolve(refs(1));
await settle();
expect(ipc.lspReferences).toHaveBeenCalledTimes(2);
expect(titles(view)).toEqual(["2 usages"]);
});
});
+76 -4
Переглянути файл
@@ -3,7 +3,11 @@
* construction: only declarations in (and near) the viewport are counted, one
* debounced pass after edits / scrolling, results cached per document text
* and symbol until the project's documents change, and at most a few reference
* requests in flight. Counts run the same references query the Find Usages
* requests in flight. Dart is the exception: inherited Flutter lifecycle methods
* (`@override build`, `initState`, …) resolve to the framework and a single
* isolate cannot cancel `textDocument/references` promptly, so those methods are
* skipped and remaining Dart counts run one at a time, never overlapping a
* request that has not finished. Counts run the same references query the Find Usages
* panel runs (including the plugin indexers' anchors), scoped to what the
* server analyses: opening candidate files or the libraries for every count
* would trigger expensive server analysis, so only an explicit Find Usages
@@ -54,6 +58,8 @@ const LENS_KINDS = new Set<SymbolKind>([
const MAX_PER_PASS = 40;
const CONCURRENCY = 4;
/** The Dart analyzer is a single isolate; overlapping references stall completion. */
const DART_CONCURRENCY = 1;
/** Lines above/below the viewport that are counted too, so scrolling feels instant. */
const MARGIN_LINES = 10;
/**
@@ -132,6 +138,46 @@ export function usagesLabel(n: number): string {
return n === 1 ? tx("1 usage") : tx`${n} usages`;
}
/**
* Flutter / Dart `@override` lifecycle and Object methods. A references query
* for any of them walks the framework (and the project) from the superclass.
*/
const DART_INHERITED_LIFECYCLE = new Set([
"build",
"createState",
"initState",
"dispose",
"didUpdateWidget",
"didChangeDependencies",
"deactivate",
"activate",
"reassemble",
"toString",
"hashCode",
"==",
]);
/** Outline names for `operator ==` (`==`, `operator ==`). */
function dartMethodName(name: string): string {
return name.replace(/^operator\s+/, "").trim();
}
/**
* Whether Code Vision should skip a usages query for this declaration: a Dart
* method whose name is a framework lifecycle / Object member, with `@override`
* on or just above the name. Exported for tests.
*/
export function skipInheritedLifecycleUsages(language: string, name: string, text: Text, line: number): boolean {
if (language !== "dart") return false;
if (!DART_INHERITED_LIFECYCLE.has(dartMethodName(name))) return false;
const from = Math.max(1, line + 1 - 4);
const to = Math.min(text.lines, line + 1);
for (let n = from; n <= to; n++) {
if (/@override\b/.test(text.line(n).text)) return true;
}
return false;
}
const setLenses = StateEffect.define<CodeLens[]>();
const lensField = StateField.define<CodeLens[]>({
@@ -186,6 +232,11 @@ class UsagesLensPlugin {
private skipped = false;
/** A pass was cut short or held back by a foreground request, and runs once it is done. */
private yielded = false;
/** Reference requests still running on the server, including ones already cancelled. */
private inflight = 0;
/** A Dart pass is waiting for `inflight` to reach 0 before asking again. */
private drain = false;
private closed = false;
constructor(private view: EditorView) {
this.refresh();
@@ -276,6 +327,11 @@ class UsagesLensPlugin {
this.yielded = true;
return;
}
// Dart's analyzer does not cancel promptly; a new wave on top of a cancelled one stalls it.
if (doc.language === "dart" && this.inflight > 0) {
this.drain = true;
return;
}
const gen = this.generation;
const usagesWanted = usagesEnabled() && !isLibrarySource(doc);
const usages = usagesWanted && !usagesBackoff.active(doc.doc);
@@ -307,20 +363,30 @@ class UsagesLensPlugin {
.filter((t) => t.line >= firstLine && t.line <= lastLine)
.slice(0, MAX_PER_PASS);
const key = (t: LensTarget) => `${t.line}:${t.col}:${t.name}`;
const todo = usages ? visible.filter((t) => !this.cache.has(key(t)) && !this.incomplete.has(key(t))) : [];
const todo = usages
? visible.filter(
(t) =>
!this.cache.has(key(t)) &&
!this.incomplete.has(key(t)) &&
!skipInheritedLifecycleUsages(doc.language, t.name, text, t.line),
)
: [];
let unavailable = false;
let retry = false;
// A base file is outlined once per pass, however many of its methods are overridden here.
const outlines: OutlineCache = new Map([[doc.path, Promise.resolve(this.outline.items)]]);
for (let i = 0; i < todo.length && !unavailable; i += CONCURRENCY) {
const concurrency = doc.language === "dart" ? DART_CONCURRENCY : CONCURRENCY;
for (let i = 0; i < todo.length && !unavailable; i += concurrency) {
if (inForeground()) {
this.yielded = true;
return;
}
if (!wanted()) return;
// oxlint-disable-next-line no-await-in-loop -- batched in groups of CONCURRENCY; a batch's flags decide whether the next batch runs
await Promise.all(
todo.slice(i, i + CONCURRENCY).map(async (t) => {
todo.slice(i, i + concurrency).map(async (t) => {
const request = nextRequestId();
this.inflight++;
try {
// Opening candidate files for each count triggers expensive server analysis.
// Only an explicit Find Usages should widen the server's scope.
@@ -351,6 +417,11 @@ class UsagesLensPlugin {
if (wanted() && isUnavailable(e)) unavailable = true;
} finally {
this.pending.delete(request);
this.inflight--;
if (this.inflight === 0 && this.drain && !this.closed) {
this.drain = false;
this.schedule();
}
}
}),
);
@@ -425,6 +496,7 @@ class UsagesLensPlugin {
}
destroy() {
this.closed = true;
this.schedule.cancel();
this.unsubscribe();
this.offReady();
+62 -1
Переглянути файл
@@ -20,7 +20,17 @@ import { formatDuration, formatSentAt, userMessageText } from "../conversation";
import { isSignInErrorMessage, useAgentErrorText } from "../loginHint";
import { isBusy, recoveryDividerLabel, type ReplyTimes, type ReplyTurn } from "../model";
import { useRevealedText } from "../reveal";
import { forkTask, refreshProviders, rerunFrom, resendMessage, useAgents } from "../store";
import {
composerDraft,
forkTask,
refreshProviders,
rerunFrom,
resendMessage,
retrySubmittedDraft,
submittedDraft,
updateComposer,
useAgents,
} from "../store";
import { PermissionLine, QuestionForm, type QuestionAnswer } from "./QuestionForm";
import { providerName, samePropsExcept, type UserEntry } from "./shared";
import { SubagentCard, ThoughtEntry, ToolEntry } from "./toolEntries";
@@ -242,17 +252,68 @@ export const Entry = memo(
}),
);
/** Offers recovery for the current writer conflict without replacing the saved conversation. */
function AgentErrorEntry({ task, message }: { task: AgentTask; message: string }) {
const [signingIn, setSigningIn] = useState(false);
const [recovering, setRecovering] = useState(false);
const text = useAgentErrorText(message);
const providerCanSignIn = useAgents((s) => s.providers.find((p) => p.id === task.provider)?.canSignIn ?? false);
const entries = useAgents((s) => s.entries.get(task.id));
const canSignIn = isTauri() && providerCanSignIn && isSignInErrorMessage(message);
const locked =
task.provider === "codex" &&
task.status === "failed" &&
task.error === message &&
message.includes("already has an active writer");
const lastUser = locked
? entries?.findLast((entry): entry is UserEntry => entry.type === "user" && !entry.steered)
: undefined;
const name = providerName(task.provider);
// Restore the unsent message alongside any text typed since the failed attempt.
const recover = async (fork: boolean) => {
setRecovering(true);
try {
const original =
(lastUser && submittedDraft(task.id, lastUser.text)) ??
(lastUser ? { text: lastUser.text, images: lastUser.images ?? [], files: [] } : undefined);
if (!fork) {
if (original) await retrySubmittedDraft(task.id, original);
return;
}
const target = await forkTask(task.id, null);
if (target && original) {
const draft = composerDraft(task.id);
updateComposer(target, {
text: [original.text, draft.text].filter(Boolean).join("\n"),
files: [...original.files, ...draft.files],
images: [...original.images, ...draft.images],
});
}
} catch (error) {
notifications().notify({
level: "error",
title: fork ? "Couldn't fork the task" : "Couldn't retry the message",
body: String(error),
});
} finally {
setRecovering(false);
}
};
return (
<div className={styles.error} role="alert">
<Icon name="error" size={14} />
<div className={styles.errorContent}>
<span>{text}</span>
{locked && (
<div>
<Button size="small" disabled={recovering || !lastUser} onClick={() => void recover(false)}>
<T>Retry</T>
</Button>
<Button size="small" disabled={recovering} onClick={() => void recover(true)}>
<T>Fork</T>
</Button>
</div>
)}
{canSignIn && (
<div>
<Button size="small" onClick={() => setSigningIn(true)}>
+25
Переглянути файл
@@ -59,6 +59,8 @@ const backend = vi.hoisted(() => ({
}>,
imported: [] as Array<[string, string]>,
forked: [] as Array<[string, string, string]>,
retryPrompt: vi.fn(),
forkTask: vi.fn(),
importError: null as string | null,
importErrors: new Map<string, string>(),
importWait: null as Promise<void> | null,
@@ -78,6 +80,8 @@ const backend = vi.hoisted(() => ({
vi.mock("@/platform/ipc", async (original) => ({
...(await original<typeof import("@/platform/ipc")>()),
commands: {
agentPrompt: backend.retryPrompt,
agentFork: backend.forkTask,
fsProbe: async () => ({
status: "ok",
data: { size: 1, binary: false, tooLarge: false },
@@ -284,6 +288,8 @@ beforeEach(() => {
useChangesOptions.setState({ groupByCommit: false, scope: "task" });
backend.imported = [];
backend.forked = [];
backend.retryPrompt.mockReset().mockResolvedValue({ status: "ok", data: null });
backend.forkTask.mockReset().mockResolvedValue({ status: "ok", data: task("forked") });
backend.importError = null;
backend.importErrors = new Map();
backend.importWait = null;
@@ -315,6 +321,25 @@ beforeEach(() => {
});
});
it("offers recovery for a Codex writer conflict and keeps the failed message in a fork", async () => {
const message = "thread s1 already has an active writer";
const failed: AgentTask = { ...task("A"), status: "failed", error: message };
const entries: AgentEntry[] = [
{ type: "user", text: "Please continue", attachments: [], images: [], steered: false, sentMs: null, doneMs: null },
{ type: "error", message },
];
backend.entries.set("A", entries);
useAgents.setState({ tasks: new Map([["A", failed]]), entries: new Map(backend.entries) });
render(<SessionEditor input={input("A")} />);
fireEvent.click(await screen.findByRole("button", { name: "Retry" }));
await waitFor(() =>
expect(backend.retryPrompt).toHaveBeenCalledWith("A", expect.objectContaining({ text: "Please continue" }), false),
);
fireEvent.click(screen.getByRole("button", { name: "Fork" }));
await waitFor(() => expect(backend.forkTask).toHaveBeenCalledWith("A", null));
await waitFor(() => expect(useAgents.getState().composers.get("forked")?.text).toBe("Please continue"));
});
describe("conversation rows", () => {
it("keeps authors above messages and their folded work with matching icon-only actions", async () => {
const user = (text: string): AgentEntry => ({
+20 -2
Переглянути файл
@@ -1729,6 +1729,21 @@ export function trackNetworkOnline(): () => void {
return () => window.removeEventListener("online", onOnline);
}
// A failed session open happens after submission; keep file paths for an explicit recovery.
const submittedDrafts = new Map<string, { draft: ComposerDraft; prompt: AgentPrompt }>();
/** Returns the latest submitted draft while this window is alive, including file paths. */
export function submittedDraft(task: string, text: string): ComposerDraft | undefined {
const submitted = submittedDrafts.get(task);
return submitted?.prompt.text === text ? submitted.draft : undefined;
}
/** Retries the original prompt without consuming a newer composer draft. */
export async function retrySubmittedDraft(task: string, draft: ComposerDraft): Promise<void> {
const submitted = submittedDrafts.get(task);
await call(commands.agentPrompt(task, submitted?.draft === draft ? submitted.prompt : promptOf(task, draft), false));
}
/** Sends the session composer's message: queued while the agent works, or with `now` interrupting it. */
export async function sendMessage(task: string, now: boolean): Promise<void> {
const composer = composerDraft(task);
@@ -1736,7 +1751,9 @@ export async function sendMessage(task: string, now: boolean): Promise<void> {
const command = shellCommand(composer);
if (command !== null) return runShell(task, composer, command);
const started = generation;
await call(commands.agentPrompt(task, promptOf(task, composer), now));
const prompt = promptOf(task, composer);
await call(commands.agentPrompt(task, prompt, now));
submittedDrafts.set(task, { draft: composer, prompt });
clearSubmittedComposer(task, composer, started);
}
@@ -1752,7 +1769,7 @@ export function quoteInComposer(task: string, text: string) {
}
/** Copies the task's conversation into a new task (up to its first `turns` turns) and opens it. */
export async function forkTask(task: string, turns: number | null): Promise<void> {
export async function forkTask(task: string, turns: number | null): Promise<string | undefined> {
const started = generation;
try {
const copy = await call(commands.agentFork(task, turns));
@@ -1761,6 +1778,7 @@ export async function forkTask(task: string, turns: number | null): Promise<void
tasks: s.tasks.has(copy.id) ? s.tasks : new Map(s.tasks).set(copy.id, copy),
}));
openTask(copy.id);
return copy.id;
} catch (e) {
if (generation === started) throw e;
}
+19
Переглянути файл
@@ -8,7 +8,10 @@ import {
connect,
disconnect,
forkTask,
retrySubmittedDraft,
sendMessage,
startTask,
submittedDraft,
updateComposer,
updateDraft,
useAgents,
@@ -17,6 +20,7 @@ import {
const backend = vi.hoisted(() => ({
create: vi.fn(),
fork: vi.fn(),
prompt: vi.fn(),
subscribe: vi.fn(),
open: vi.fn(),
close: vi.fn(),
@@ -36,6 +40,7 @@ vi.mock("@/platform/ipc", async (original) => ({
commands: {
agentCreate: backend.create,
agentFork: backend.fork,
agentPrompt: backend.prompt,
agentSubscribe: backend.subscribe,
agentProviders: async () => ({ status: "ok", data: [] }),
},
@@ -112,6 +117,20 @@ beforeEach(() => {
});
afterEach(() => disconnect());
it("retains the submitted file paths for retry without consuming a newer draft", async () => {
backend.prompt.mockResolvedValue(ok(null));
updateComposer("source", { text: "inspect", files: [{ path: "/project-a/a.txt", rel: "a.txt", attached: true }] });
await sendMessage("source", false);
const sent = backend.prompt.mock.calls[0]![1];
const original = submittedDraft("source", sent.text)!;
expect(original.files[0]?.path).toBe("/project-a/a.txt");
updateComposer("source", { text: "new draft" });
await retrySubmittedDraft("source", original);
expect(backend.prompt.mock.calls[1]![1]).toEqual(sent);
expect(composerDraft("source").text).toBe("new draft");
expect(submittedDraft("source", "a different message")).toBeUndefined();
});
const transitions = [
"disconnect",
"reconnect",
+137
Переглянути файл
@@ -0,0 +1,137 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { formParams, withParams } from "@/features/run/types";
import { hostOs } from "@/platform/remote";
import { dockerfileType, dockerImageType, typedConfig } from "./runTypes";
vi.mock("@/platform/remote", async (original) => ({
...(await original<typeof import("@/platform/remote")>()),
hostOs: vi.fn(),
}));
const dockerfileParams = {
dockerfile: "docker files/Dockerfile",
tag: "sample/app:latest",
target: "production",
buildArgs: "MODE=production",
buildOptions: "--no-cache",
runImage: "true",
containerName: "sample-app",
ports: "8080:80",
volumes: "./app data:/data",
containerEnv: "MODE=production",
runOptions: "--network bridge",
command: 'serve --title "Sample app"',
};
const imageParams = {
image: "registry.example.com/team/postgres:16",
pull: "true",
ports: "5432:5432",
containerEnv: "APP_NAME=Local database",
};
const foregroundSettings: Record<string, string>[] = [{}, { detach: "false" }];
describe.each([
{
os: "linux" as const,
build:
"docker build -f 'docker files/Dockerfile' -t sample/app:latest --target production --build-arg MODE=production --no-cache 'docker files'",
buildOnly: "docker build -f 'docker files/Dockerfile' -t sample/app:latest 'docker files'",
remove: ">/dev/null 2>&1;",
appArgs: "-p 8080:80 -v './app data:/data' -e MODE=production --network bridge sample/app:latest",
imageArgs: "--pull always -p 5432:5432 -e 'APP_NAME=Local database' registry.example.com/team/postgres:16",
},
{
os: "windows" as const,
build:
'docker build -f "docker files/Dockerfile" -t sample/app:latest --target production --build-arg MODE=production --no-cache "docker files"',
buildOnly: 'docker build -f "docker files/Dockerfile" -t sample/app:latest "docker files"',
remove: ">nul 2>&1 &",
appArgs: '-p 8080:80 -v "./app data:/data" -e MODE=production --network bridge sample/app:latest',
imageArgs: '--pull always -p 5432:5432 -e "APP_NAME=Local database" registry.example.com/team/postgres:16',
},
])("Docker run command lines on $os", ({ os, build, buildOnly, remove, appArgs, imageArgs }) => {
beforeEach(() => vi.mocked(hostOs).mockReturnValue(os));
it.each(foregroundSettings)("runs a Dockerfile in the foreground with %j", (detach) => {
expect(dockerfileType.commandLine({ ...dockerfileParams, ...detach })).toEqual({
command: `${build} && (docker rm -f sample-app ${remove} docker run --name sample-app ${appArgs} serve --title "Sample app")`,
args: [],
cwd: null,
stop: "docker stop sample-app",
});
});
it.each(foregroundSettings)("runs a Docker Image in the foreground with %j", (detach) => {
expect(dockerImageType.commandLine({ ...imageParams, ...detach })).toEqual({
command: `(docker rm -f postgres ${remove} docker run --name postgres ${imageArgs})`,
args: [],
cwd: null,
stop: "docker stop postgres",
});
});
it("runs the built image in the background and follows its logs", () => {
expect(dockerfileType.commandLine({ ...dockerfileParams, detach: "true" })).toEqual({
command: `${build} && (docker rm -f sample-app ${remove} docker run -d --name sample-app ${appArgs} serve --title "Sample app") && docker logs --tail 500 -f sample-app`,
args: [],
cwd: null,
stop: null,
});
});
it("runs a Docker Image in the background and follows logs using its derived name", () => {
expect(dockerImageType.commandLine({ ...imageParams, containerName: " ", detach: "true" })).toEqual({
command: `(docker rm -f postgres ${remove} docker run -d --name postgres ${imageArgs}) && docker logs --tail 500 -f postgres`,
args: [],
cwd: null,
stop: null,
});
});
it("builds without starting a container when Run built image is off", () => {
expect(
dockerfileType.commandLine({
dockerfile: dockerfileParams.dockerfile,
tag: dockerfileParams.tag,
detach: "true",
}),
).toEqual({ command: buildOnly, args: [], cwd: null });
});
});
describe("Docker detach setting", () => {
beforeEach(() => vi.mocked(hostOs).mockReturnValue("linux"));
it("offers the checkbox only when the configuration starts a container", () => {
const dockerfile = dockerfileType.fields.find((field) => field.key === "detach");
const image = dockerImageType.fields.find((field) => field.key === "detach");
const checkbox = { label: "Run in the background (-d)", control: "checkbox" };
expect(dockerfile).toMatchObject(checkbox);
expect(dockerfile?.visible?.({ runImage: "true" })).toBe(true);
expect(dockerfile?.visible?.({ runImage: "false" })).toBe(false);
expect(image).toMatchObject(checkbox);
expect(image?.visible).toBeUndefined();
});
it.each([
{ type: dockerfileType, params: dockerfileParams, name: "sample-app" },
{ type: dockerImageType, params: imageParams, name: "postgres" },
])("round-trips detach through saved $type.label params and the run form", ({ type, params, name }) => {
const foreground = typedConfig(type, "user:docker", "Docker", params);
expect(foreground.stopCommand).toBe(`docker stop ${name}`);
const detached = withParams(foreground, { ...params, detach: "true" }, type);
expect(detached.params?.detach).toBe("true");
expect(detached.stopCommand).toBeUndefined();
const reopened = formParams(detached, type)!;
expect(reopened.detach).toBe("true");
expect(withParams(detached, reopened, type)).toEqual(detached);
expect(withParams(detached, { ...reopened, detach: "false" }, type)).toEqual({
...foreground,
params: { ...params, detach: "false" },
});
});
});
+15 -10
Переглянути файл
@@ -3,8 +3,8 @@
* Dockerfile (build the image, then run a container from it), Docker Image (run
* a container from an image) and Docker Compose (`up` the selected services).
* They launch docker command lines in the Run tool window against the Docker
* connection chosen from the Services tool window's connections; Stop stops the
* container (`docker stop`) or takes the Compose project down.
* connection chosen from the Services tool window's connections. Stop stops the
* attached container or takes the Compose project down. Detached containers keep running.
*/
import { splitCommandLine } from "@/platform/commandLine";
import { call, commands, type RunConfig } from "@/platform/ipc";
@@ -62,21 +62,23 @@ export function containerName(p: Readonly<Record<string, string>>, image: string
}
/**
* Removes a previous container of the same name (IDEA redeploys over it), then runs
* the new one attached, so its output is the run's output.
* Redeploys a container of the same name. Detached runs follow the new container's logs.
*/
function runContainer(name: string, image: string, p: Readonly<Record<string, string>>, windows: boolean): string {
const remove = `${line(["docker", "rm", "-f", name], windows)} ${windows ? ">nul 2>&1 &" : ">/dev/null 2>&1;"}`;
const detach = on(p.detach);
const run = [
"docker",
"run",
...(detach ? ["-d"] : []),
"--name",
name,
...(on(p.pull) ? ["--pull", "always"] : []),
...containerArgs(p),
image,
];
return `${remove} ${line([...run], windows)}${p.command?.trim() ? ` ${p.command.trim()}` : ""}`;
const redeploy = `(${remove} ${line(run, windows)}${p.command?.trim() ? ` ${p.command.trim()}` : ""})`;
return detach ? `${redeploy} && ${line(["docker", "logs", "--tail", "500", "-f", name], windows)}` : redeploy;
}
/** The servers the form offers: the saved connections, else the default daemon ("Docker"). */
@@ -97,8 +99,11 @@ const connectionField = {
},
};
const detachField = { key: "detach", label: "Run in the background (-d)", control: "checkbox" } as const;
const containerFields: RunConfigTypeContribution["fields"] = [
{ key: "containerName", label: "Container name", mono: true, placeholder: "Derived from the image" },
detachField,
{ key: "ports", label: "Bind ports", mono: true, placeholder: "8080:80, 5005:5005" },
{ key: "volumes", label: "Bind mounts", mono: true, placeholder: "./data:/data; cache:/root/.cache" },
{ key: "containerEnv", label: "Container environment", mono: true, placeholder: "KEY=value; OTHER=value" },
@@ -191,10 +196,10 @@ export const dockerfileType: RunConfigTypeContribution = {
if (!on(p.runImage)) return { command: line(build, windows), args: [], cwd: null };
const name = containerName(p, tag);
return {
command: `${line(build, windows)} && (${runContainer(name, tag, p, windows)})`,
command: `${line(build, windows)} && ${runContainer(name, tag, p, windows)}`,
args: [],
cwd: null,
stop: line(["docker", "stop", name], windows),
stop: on(p.detach) ? null : line(["docker", "stop", name], windows),
};
},
prepareLaunch: withConnection,
@@ -221,10 +226,10 @@ export const dockerImageType: RunConfigTypeContribution = {
const image = p.image?.trim() ?? "";
const name = containerName(p, image);
return {
command: `(${runContainer(name, image, p, windows)})`,
command: runContainer(name, image, p, windows),
args: [],
cwd: null,
stop: line(["docker", "stop", name], windows),
stop: on(p.detach) ? null : line(["docker", "stop", name], windows),
};
},
prepareLaunch: withConnection,
@@ -249,7 +254,7 @@ export const dockerComposeType: RunConfigTypeContribution = {
},
{ key: "services", label: "Services", mono: true, placeholder: "All services" },
{ key: "project", label: "Project name", mono: true, placeholder: "The folder name" },
{ key: "detach", label: "Run in the background (-d)", control: "checkbox" },
detachField,
{ key: "build", label: "Build images before starting (--build)", control: "checkbox" },
{ key: "upOptions", label: "Up options", mono: true, placeholder: "e.g. --force-recreate --remove-orphans" },
],