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

...
Автор SHA1 Повідомлення Дата
l0ng-ai e41e4fba2c test: fix three tests failing on main
- e2e/toolwindows: tool window splitters lock the col-resize cursor while dragging
  since the WebKit splitter cursor change.
- trust_vcs_sweep: sweep vcs_detected_roots, the Directory Mappings command
  allowed in Restricted Mode, so it is checked to start no program of the
  repository.
- acp::e2e: wait for the resumed turn's entries before waiting for Ready; the
  task is Ready until that turn starts, so a slow runner saw no entries.
2026-11-19 03:09:13 +08:00
Mansur Akhmadiтаmansur-akhmadi dfd7a177f5 feat(vcs): Options submenu in the annotate gutter (date, author, revision) (#4367)
The annotate gutter's context menu gets Options with Date, Author and Revision check items; Revision shows the 8-character commit hash. Date and Author stay on by default, the last shown column can't be turned off, and the choice is remembered and applied to every annotated editor, including other windows. Options also shows on uncommitted lines.

Closes #4366

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-19 02:40:20 +08:00
Gabriel Gondim 5c3b144db9 feat(project): Open In › Associated Application (#4365)
Project view and editor tab menus get Open In › Associated Application, and Find Action gets Open in Associated Application: the selected files open in the application the OS associates with them, through the existing fs_open_with_system command (trusted local projects only; hidden in remote windows).

Closes #4352

Co-authored-by: GGVidal <[email protected]>
2026-11-19 02:03:24 +08:00
Vadim LazukтаInf1mum 7492bebeef feat(java): module-level incremental Build Project for multi-module Maven projects (#4361)
Build Project on a Maven reactor records per-module input fingerprints after each successful project build. The next Build Project finds the changed modules, spreads the change to the modules that depend on them (test-scoped consumers included, version-matched) and runs `mvn -pl <modules> -am` over just that set; an unchanged reactor is skipped, and a missing or unreadable record or unresolvable inputs fall back to the full build. Baselines are recorded only after a project build, so modules changed but not built by Build Module are still built next time. Content edits with preserved mtimes are re-stamped so Maven recompiles them.

Refs #4078

Co-authored-by: Inf1mum <[email protected]>
2026-11-19 01:55:34 +08:00
l0ng-ai 9673a704a2 feat(agents): run ! commands from the agent composer (#4364)
A composer message starting with `!` runs as a shell command in the task's folder instead of starting an agent turn. The command and its output appear as an execute tool entry, Stop kills it, and the command with its output is sent ahead of the next message (once) so the agent sees what was run. New cancellable command agent_shell.

Closes #4339
2026-11-19 01:39:55 +08:00
Deng Liuтаdengliu a6569552b1 perf(settings): single-IPC local bootstrap snapshot and lazy page bodies (#4056)
The Settings window starts from one window_take_settings_init snapshot (launch, project, global settings, remote, updates) instead of several startup calls; on a remote session it paints with the client settings and reconciles with the host's projectCurrent() afterwards, rebasing without touching staged edits. Seven heavy pages (Color Scheme, Inspections, Scopes, Updates, Deployment, Run Targets, SSH) are split into a spec module (metadata and search labels, loaded with the registry) and a lazily loaded body; lazyComponent gains preload() so the target page is warmed before it is revealed. A launch that arrives between the snapshot and the event listener is still applied.

Co-authored-by: dengliu <[email protected]>
2026-11-19 01:28:28 +08:00
l0ng-ai 437e8b747e fix(i18n): translate the terminal refresh-rate options into Chinese (#4360)
The zh catalog carried the English "60 FPS" etc. for the Maximum refresh rate options from #4358, which i18n.test.ts rejects for a locale with its own script; they are now "60 帧/秒" etc.
2026-11-19 01:23:09 +08:00
67 змінених файлів з 3810 додано та 2211 видалено

No files matched your search

+5 -1
Переглянути файл
@@ -203,7 +203,11 @@ async fn a_task_runs_on_a_v2_agent_and_resumes_its_session() {
let agent2 = Arc::new(FakeV2Agent::default());
let mgr2 = manager(tmp.path(), agent2.clone());
mgr2.prompt(&task.id, text("again"), false).await.unwrap();
tokio::time::sleep(Duration::from_millis(50)).await;
// The task is Ready until the resumed turn starts: wait for the turn's entries first.
let deadline = std::time::Instant::now() + Duration::from_secs(10);
while mgr2.entries(&task.id, None).unwrap().len() < 8 && std::time::Instant::now() < deadline {
tokio::time::sleep(Duration::from_millis(10)).await;
}
wait_for(&mgr2, &task.id, AgentStatus::Ready).await;
let entries = mgr2.entries(&task.id, None).unwrap();
assert_eq!(summary(&entries[6..]), ["user: again", "agent: second turn"]);
+61 -2
Переглянути файл
@@ -20,6 +20,7 @@ mod native;
mod provider;
pub mod registry;
pub mod security;
mod shell;
mod skills;
mod timeline;
mod worktree;
@@ -400,6 +401,9 @@ struct TaskState {
/// the like), as it sent them: unlike a turn they outlive it, so an idle release
/// waits for the last one. A (re)started process runs nothing yet.
background_tasks: Vec<Value>,
/// Shell commands the user ran with `!` since the last prompt, as the text block that
/// goes ahead of the next one.
shell_context: Vec<String>,
}
impl TaskState {
@@ -957,6 +961,26 @@ impl AgentManager {
Ok(())
}
/// Runs `command` (a composer line starting with `!`) in the task's folder with the user's
/// shell, without starting a turn: it shows as one entry with its output and exit code,
/// and goes to the agent with the next message.
pub async fn run_shell(&self, id: &str, command: &str, cancel: ide_core::CancellationToken) -> IdeResult<()> {
let task = self.task(id)?;
let command = command.trim();
if command.is_empty() {
return Err(IdeError::invalid("empty command"));
}
let cwd = {
let s = task.state.lock();
if s.task.status == AgentStatus::Archived {
return Err(IdeError::invalid("the task is archived"));
}
s.task.cwd.0.clone()
};
task.shell(command, &cwd, &cancel).await;
Ok(())
}
/// Drops a queued message.
pub fn unqueue(&self, id: &str, queued: &str) -> IdeResult<AgentQueued> {
let task = self.task(id)?;
@@ -1885,6 +1909,7 @@ impl Task {
title_renamed: file.title_renamed,
busy: false,
background_tasks: Vec::new(),
shell_context: Vec::new(),
}),
live: Mutex::new(None),
connecting: tokio::sync::Mutex::new(()),
@@ -2115,6 +2140,33 @@ impl Task {
}
}
/// Folds an update made here (not by the agent) into the main conversation.
fn apply_local(self: &Arc<Self>, update: &Value) {
let changed = self.state.lock().conversation.apply(None, update, now_ms());
self.mark_dirty(changed);
}
async fn shell(self: &Arc<Self>, command: &str, cwd: &Path, cancel: &ide_core::CancellationToken) {
let call = format!("shell-{}", uuid::Uuid::new_v4().simple());
self.apply_local(&json!({
"sessionUpdate": "tool_call",
"toolCallId": call,
"title": format!("! {command}"),
"kind": "execute",
"status": "in_progress",
}));
let ran = shell::run(command, cwd, cancel).await;
let status = if ran.code == Some(0) { "completed" } else { "failed" };
self.apply_local(&json!({
"sessionUpdate": "tool_call_update",
"toolCallId": call,
"status": status,
"content": [{ "type": "content", "content": { "type": "text", "text": ran.shown() } }],
}));
self.state.lock().shell_context.push(ran.context(command));
self.persist();
}
fn push_entry(self: &Arc<Self>, entry: AgentEntry) -> usize {
let i = self.state.lock().conversation.main.push(entry);
self.mark_dirty([(None, i)]);
@@ -2431,7 +2483,14 @@ impl Task {
if !prompt.images.is_empty() && !live.capabilities.images {
return Err(Failure::from("This agent can't read images.".to_owned()));
}
let mut content = self.content(&live, prompt).await;
let shell = std::mem::take(&mut self.state.lock().shell_context);
let with_shell = |mut content: Vec<Value>| {
if !shell.is_empty() {
content.insert(0, json!({ "type": "text", "text": shell.join("\n") }));
}
content
};
let mut content = with_shell(self.content(&live, prompt).await);
let mut result: Result<Value, RpcError> =
live.peer.request("session/prompt", json!({ "sessionId": live.session, "prompt": content }), None).await;
if live.driver == provider::Driver::Copilot
@@ -2453,7 +2512,7 @@ impl Task {
if !prompt.images.is_empty() && !live.capabilities.images {
return Err(Failure::from("This agent can't read images.".to_owned()));
}
content = self.content(&live, prompt).await;
content = with_shell(self.content(&live, prompt).await);
result = live
.peer
.request("session/prompt", json!({ "sessionId": live.session, "prompt": content }), None)
+160
Переглянути файл
@@ -0,0 +1,160 @@
//! `!` commands from the composer: run in the task's folder with the user's shell, outside
//! any turn, and handed to the agent with the next message as Claude Code's bash mode does.
use ide_core::CancellationToken;
use std::path::Path;
use std::process::Stdio;
use tokio::io::AsyncReadExt;
use tokio::process::Command;
/// Output kept from each stream; longer output keeps its tail.
const MAX_STREAM: usize = 32 * 1024;
#[derive(Debug, Default, PartialEq)]
pub(crate) struct Ran {
/// The exit code; `None` when it didn't start, was stopped or ended by a signal.
pub code: Option<i32>,
pub stdout: String,
pub stderr: String,
/// Why it didn't finish: it couldn't start, or it was stopped.
pub error: Option<String>,
}
impl Ran {
/// What the conversation shows: the output, then how it ended unless it succeeded.
pub fn shown(&self) -> String {
let mut text = [self.stdout.trim_end(), self.stderr.trim_end()]
.into_iter()
.filter(|t| !t.is_empty())
.collect::<Vec<_>>()
.join("\n");
let end = match (&self.error, self.code) {
(Some(error), _) => Some(error.clone()),
(None, Some(0)) => None,
(None, Some(code)) => Some(format!("Exit code {code}")),
(None, None) => Some("Terminated".into()),
};
if let Some(end) = end {
if !text.is_empty() {
text.push('\n');
}
text.push_str(&end);
}
text
}
/// The block that goes to the agent ahead of the next message.
pub fn context(&self, command: &str) -> String {
let mut stderr = self.stderr.trim_end().to_owned();
if let Some(error) = &self.error {
if !stderr.is_empty() {
stderr.push('\n');
}
stderr.push_str(error);
} else if let Some(code) = self.code.filter(|c| *c != 0) {
if !stderr.is_empty() {
stderr.push('\n');
}
stderr.push_str(&format!("Exit code {code}"));
}
format!(
"<bash-input>{command}</bash-input>\n<bash-stdout>{}</bash-stdout><bash-stderr>{stderr}</bash-stderr>",
self.stdout.trim_end()
)
}
}
/// Runs `command` with the user's shell in `cwd` until it ends or `cancel` stops it.
pub(crate) async fn run(command: &str, cwd: &Path, cancel: &CancellationToken) -> Ran {
let mut cmd = shell(command);
ide_core::process::prepare(cmd.as_std_mut());
cmd.current_dir(cwd).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped()).kill_on_drop(true);
let mut child = match cmd.spawn() {
Ok(child) => child,
Err(e) => return Ran { error: Some(format!("Cannot run it: {e}")), ..Ran::default() },
};
let (Some(mut out), Some(mut err)) = (child.stdout.take(), child.stderr.take()) else {
return Ran { error: Some("Cannot read its output".into()), ..Ran::default() };
};
let finished = async move {
let (mut stdout, mut stderr) = (Vec::new(), Vec::new());
let _ = tokio::join!(out.read_to_end(&mut stdout), err.read_to_end(&mut stderr));
let code = child.wait().await.ok().and_then(|s| s.code());
Ran { code, stdout: tail(&stdout), stderr: tail(&stderr), error: None }
};
tokio::select! {
ran = finished => ran,
// Dropping the child kills it.
() = cancel.cancelled() => Ran { error: Some("Stopped".into()), ..Ran::default() },
}
}
#[cfg(not(windows))]
fn shell(command: &str) -> Command {
let shell = std::env::var("SHELL").ok().filter(|s| !s.trim().is_empty()).unwrap_or_else(|| "/bin/sh".into());
let mut cmd = Command::new(shell);
cmd.arg("-c").arg(command);
cmd
}
#[cfg(windows)]
fn shell(command: &str) -> Command {
let mut cmd = Command::new(std::env::var("COMSPEC").unwrap_or_else(|_| "cmd.exe".into()));
// `/S /C "…"` runs the line as typed: cmd strips only the outer quotes.
cmd.raw_arg("/D /S /C \"").raw_arg(command).raw_arg("\"");
cmd
}
fn tail(bytes: &[u8]) -> String {
let text = String::from_utf8_lossy(bytes);
if text.len() <= MAX_STREAM {
return text.into_owned();
}
let mut cut = text.len() - MAX_STREAM;
while !text.is_char_boundary(cut) {
cut += 1;
}
format!("…{}", &text[cut..])
}
#[cfg(all(test, not(windows)))]
mod tests {
use super::*;
#[tokio::test]
async fn runs_in_the_folder_and_reports_output_and_exit_code() {
let dir = tempfile::tempdir().unwrap();
std::fs::write(dir.path().join("marker.txt"), "").unwrap();
let ran = run("ls; echo oops >&2; exit 3", dir.path(), &CancellationToken::new()).await;
assert_eq!(ran.code, Some(3));
assert_eq!(ran.stdout.trim(), "marker.txt");
assert_eq!(ran.stderr.trim(), "oops");
assert_eq!(ran.shown(), "marker.txt\noops\nExit code 3");
assert_eq!(
ran.context("ls"),
"<bash-input>ls</bash-input>\n<bash-stdout>marker.txt</bash-stdout><bash-stderr>oops\nExit code 3</bash-stderr>"
);
}
#[tokio::test]
async fn a_stopped_command_is_killed() {
let dir = tempfile::tempdir().unwrap();
let cancel = CancellationToken::new();
let stop = cancel.clone();
tokio::spawn(async move {
tokio::time::sleep(std::time::Duration::from_millis(200)).await;
stop.cancel();
});
let started = std::time::Instant::now();
let ran = run("sleep 30", dir.path(), &cancel).await;
assert!(started.elapsed() < std::time::Duration::from_secs(5));
assert_eq!(ran.shown(), "Stopped");
}
#[test]
fn long_output_keeps_its_tail() {
let long = "x".repeat(MAX_STREAM + 10) + "end";
let kept = tail(long.as_bytes());
assert!(kept.starts_with('…') && kept.ends_with("end"));
}
}
+60 -1
Переглянути файл
@@ -59,6 +59,8 @@ struct FakeAgent {
session_steering: bool,
/// Records the `mcpServers` array passed to `session/new`, `session/load`, and `session/fork`.
mcp_calls: Mutex<Vec<(String, Vec<String>)>>,
/// The content blocks of each `session/prompt`.
prompts: Mutex<Vec<Value>>,
}
impl FakeAgent {
@@ -247,7 +249,17 @@ impl Handler for FakeAgent {
Ok(json!({}))
}
"session/prompt" => {
let text = params.pointer("/prompt/0/text").and_then(Value::as_str).unwrap_or_default().to_owned();
self.prompts.lock().push(params.get("prompt").cloned().unwrap_or(Value::Null));
// `!` commands run since the last message come first; the message follows.
let first = match params.pointer("/prompt/0/text").and_then(Value::as_str) {
Some(t) if t.starts_with("<bash-input>") => 1,
_ => 0,
};
let text = params
.pointer(&format!("/prompt/{first}/text"))
.and_then(Value::as_str)
.unwrap_or_default()
.to_owned();
if text.starts_with("<send_user_message_question_reply>") {
self.say(&session, "answer received");
return Ok(json!({"stopReason": "end_turn"}));
@@ -1361,6 +1373,53 @@ async fn messages_sent_while_busy_are_queued_and_send_now_interrupts() {
assert!(mgr.task(&task.id).unwrap().state.lock().task.queue.is_empty());
}
#[cfg(not(windows))]
#[tokio::test(flavor = "multi_thread")]
async fn shell_commands_show_in_the_conversation_and_go_with_the_next_message() {
let tmp = tempfile::tempdir().unwrap();
let agent = Arc::new(FakeAgent::default());
let mgr = manager(tmp.path(), agent.clone());
let task = mgr
.create(NewAgentTask {
project_root: None,
prompt: text("again"),
provider: "claude".into(),
config: vec![],
isolation: Isolation::Local,
base: None,
..Default::default()
})
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
let turns = agent.prompts.lock().len();
mgr.run_shell(&task.id, " echo shell-out ", ide_core::CancellationToken::new()).await.unwrap();
assert_eq!(agent.prompts.lock().len(), turns, "a `!` command starts no turn");
let entries = mgr.entries(&task.id, None).unwrap();
let Some(AgentEntry::Tool { title, kind, status, output, .. }) = entries.last() else {
panic!("no entry for the command: {entries:?}")
};
assert_eq!((title.as_str(), kind.as_str(), *status), ("! echo shell-out", "execute", AgentToolStatus::Completed));
assert_eq!(output.as_deref(), Some("shell-out"));
mgr.prompt(&task.id, text("again"), false).await.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
let sent = agent.prompts.lock().last().cloned().unwrap();
assert_eq!(
sent.pointer("/0/text").and_then(Value::as_str),
Some(
"<bash-input>echo shell-out</bash-input>\n<bash-stdout>shell-out</bash-stdout><bash-stderr></bash-stderr>"
)
);
assert_eq!(sent.pointer("/1/text").and_then(Value::as_str), Some("again"));
// Only once.
mgr.prompt(&task.id, text("again"), false).await.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
let sent = agent.prompts.lock().last().cloned().unwrap();
assert_eq!(sent.pointer("/0/text").and_then(Value::as_str), Some("again"));
}
#[tokio::test(flavor = "multi_thread")]
async fn send_now_interrupts_the_turn_when_steering_is_refused() {
let tmp = tempfile::tempdir().unwrap();
+20 -3
Переглянути файл
@@ -182,7 +182,7 @@ fn collect(
}
/// Scans every input, storing project inputs relative to the project.
fn scan_all(
pub(super) fn scan_all(
root: &Path,
inputs: Vec<PathBuf>,
cancel: &CancellationToken,
@@ -210,7 +210,7 @@ pub fn launch_fingerprint(
if projects.is_empty() {
return Ok(None);
}
let plan = launch_plan(root, model, module, test, BuildKind::Build)?;
let plan = launch_plan(root, model, module, test, BuildKind::Build, cancel)?;
let Some(collected) = collect(root, &projects, &plan, local_repo)? else { return Ok(None) };
let Collected { inputs, environment, steps, inherited_hash } = collected;
let parameters = serde_json::to_string(&(root, module, test, steps, environment, inherited_hash, projects))
@@ -229,7 +229,7 @@ pub fn menu_fingerprint(
file: Option<&Path>,
cancel: &CancellationToken,
) -> IdeResult<Option<LaunchFingerprint>> {
let plan = plan(root, model, BuildKind::Build, file, None)?;
let plan = plan(root, model, BuildKind::Build, file, None, None, cancel)?;
if plan.system != BuildSystem::Maven {
return Ok(None);
}
@@ -264,6 +264,23 @@ pub fn menu_fingerprint(
Ok(Some(LaunchFingerprint { version: 2, parameters, files: scan_all(root, inputs, cancel)? }))
}
/// Input fingerprint of one Maven module's menu build (#4078): its POM chain,
/// source and resource trees plus the launcher settings that shape the build.
/// `None` disables the module-scoped reuse (unresolved custom roots).
/// All filesystem work belongs on the caller's blocking thread.
pub(super) fn module_fingerprint(
root: &Path,
project: &maven::MavenProject,
cancel: &CancellationToken,
) -> IdeResult<Option<LaunchFingerprint>> {
let projects = [project];
let Some(inputs) = maven::launch_inputs(root, &projects, None) else { return Ok(None) };
let parameters =
serde_json::to_string(&("module-build", &project.dir, &project.command, &project.options, &project.env))
.map_err(|e| IdeError::internal(e.to_string()))?;
Ok(Some(LaunchFingerprint { version: 2, parameters, files: scan_all(root, inputs, cancel)? }))
}
impl LaunchFingerprint {
/// Folders (relative to the project) of the Maven projects whose POM is an input.
pub(super) fn project_dirs(&self) -> impl Iterator<Item = &Path> {
+168 -40
Переглянути файл
@@ -5,6 +5,7 @@
mod fingerprint;
mod launch_resources;
mod modules;
mod parse;
mod single;
mod structure;
@@ -12,6 +13,7 @@ mod up_to_date;
pub use fingerprint::{LaunchFingerprint, launch_fingerprint, menu_fingerprint};
pub use launch_resources::process_launch_resources;
pub use modules::record_module_build;
pub use single::{
SingleFileTarget, compile_file_plan, find_javac, javac_step, module_classpath, single_file_classpath,
single_file_target,
@@ -220,12 +222,16 @@ fn ancestors_within<'a>(root: &'a Path, file: &'a Path) -> impl Iterator<Item =
/// The build of `root`, or of the module containing `file` (Build Module / Recompile).
/// `cmake`: the CMake profiles of the settings (the first one is built), if any.
/// `cache` enables the module-scoped Maven narrowing of `Build` project builds;
/// `None` plans every build exactly as before.
pub fn plan(
root: &Path,
model: &BuildModel,
kind: BuildKind,
file: Option<&Path>,
cmake: Option<&[CMakeProfile]>,
cache: Option<&Path>,
cancel: &CancellationToken,
) -> IdeResult<BuildPlan> {
let project_name = root.file_name().map_or_else(|| "project".to_owned(), |n| n.to_string_lossy().into_owned());
let module_dir = match file {
@@ -262,7 +268,7 @@ pub fn plan(
None => project_name,
};
let steps = match system {
BuildSystem::Maven => maven_steps(root, model, kind, module_dir.as_deref())?,
BuildSystem::Maven => maven_steps(root, model, kind, module_dir.as_deref(), cache, cancel)?,
BuildSystem::Gradle => gradle_steps(root, model, kind, module_dir.as_deref())?,
BuildSystem::Cargo => cargo_steps(&dir, kind),
// Go builds the file's package (a module holds many).
@@ -281,6 +287,8 @@ pub(super) fn maven_steps(
model: &BuildModel,
kind: BuildKind,
module: Option<&Path>,
cache: Option<&Path>,
cancel: &CancellationToken,
) -> IdeResult<Vec<BuildStep>> {
let fallback;
let m = match &model.maven {
@@ -320,7 +328,15 @@ pub(super) fn maven_steps(
s.env = p.env.clone();
s
};
let Some(module) = module else { return Ok(tops.iter().map(|p| step(p, &[])).collect()) };
let Some(module) = module else {
if kind == BuildKind::Build
&& let Some(cache) = cache
&& let Some(steps) = modules::narrowed_maven_steps(cache, root, m, &step, cancel)?
{
return Ok(steps);
}
return Ok(tops.iter().map(|p| step(p, &[])).collect());
};
// The reactor root containing the module builds it with what it depends on (`-pl … -am`).
let rel = rel_str(root, module);
if !m.projects.iter().any(|p| p.dir == rel) {
@@ -881,8 +897,15 @@ pub fn launch_has_non_java_sources(root: &Path, model: &BuildModel, module: &Pat
has_non_java_sources(module)
}
fn launch_plan(root: &Path, model: &BuildModel, module: &Path, test: bool, kind: BuildKind) -> IdeResult<BuildPlan> {
let mut plan = plan(root, model, kind, Some(module), None)?;
fn launch_plan(
root: &Path,
model: &BuildModel,
module: &Path,
test: bool,
kind: BuildKind,
cancel: &CancellationToken,
) -> IdeResult<BuildPlan> {
let mut plan = plan(root, model, kind, Some(module), None, None, cancel)?;
if plan.system == BuildSystem::Maven && !test {
for step in &mut plan.steps {
if let Some(goal) = step.args.last_mut() {
@@ -909,7 +932,7 @@ pub fn build_for_launch(
kind: BuildKind,
cancel: &CancellationToken,
) -> IdeResult<LaunchBuild> {
let plan = launch_plan(root, model, module, test, kind)?;
let plan = launch_plan(root, model, module, test, kind, cancel)?;
let result = run(root, &plan, cancel, &|_| {})?;
let failure = if !result.success {
let errors: Vec<String> = result
@@ -974,7 +997,9 @@ mod tests {
write(root, "../external/main.go", "package main\nimport \"example.com/lib\"\nfunc main(){_ = lib.Value()}\n");
// std canonicalization also exercises verbatim paths on Windows.
for root in [root.to_path_buf(), std::fs::canonicalize(root).unwrap()] {
let plan = plan(&root, &BuildModel::default(), BuildKind::Build, None, None).unwrap();
let plan =
plan(&root, &BuildModel::default(), BuildKind::Build, None, None, None, &CancellationToken::new())
.unwrap();
for step in plan.steps {
let result = std::process::Command::new(&go)
.args(&step.args)
@@ -1000,7 +1025,7 @@ mod tests {
let canonical = std::fs::canonicalize(&root).unwrap();
for root in [&root, &canonical, &canonical.join("..").join("workspace")] {
for kind in [BuildKind::Build, BuildKind::Rebuild, BuildKind::Artifacts] {
let p = plan(root, &BuildModel::default(), kind, None, None).unwrap();
let p = plan(root, &BuildModel::default(), kind, None, None, None, &CancellationToken::new()).unwrap();
assert_eq!(p.system, BuildSystem::Go);
assert_eq!(p.steps.len(), 3);
for (step, module) in p.steps.iter().zip(["api", "lib with spaces", "../shared"]) {
@@ -1015,20 +1040,30 @@ mod tests {
}
}
}
let member =
plan(&root, &BuildModel::default(), BuildKind::Build, Some(&root.join("api/pkg/a.go")), None).unwrap();
let member = plan(
&root,
&BuildModel::default(),
BuildKind::Build,
Some(&root.join("api/pkg/a.go")),
None,
None,
&CancellationToken::new(),
)
.unwrap();
assert_eq!(member.steps.len(), 1);
assert_eq!(member.steps[0].cwd, root.join("api"));
assert_eq!(member.steps[0].args, ["build", "./pkg/..."]);
write(&root, "go.work", "use ./missing\n");
assert!(
plan(&root, &BuildModel::default(), BuildKind::Build, None, None)
plan(&root, &BuildModel::default(), BuildKind::Build, None, None, None, &CancellationToken::new())
.unwrap_err()
.to_string()
.contains("go.mod")
);
write(&root, "go.work", "go 1.22\n");
assert!(plan(&root, &BuildModel::default(), BuildKind::Build, None, None).is_err());
assert!(
plan(&root, &BuildModel::default(), BuildKind::Build, None, None, None, &CancellationToken::new()).is_err()
);
}
#[test]
@@ -1049,11 +1084,21 @@ mod tests {
let mut model = crate::load_linked(root, &root.join("cache"), None, &Default::default(), &settings);
model.gradle[0].env.insert("JAVA_HOME".into(), "/jdk-a".into());
model.gradle[1].env.insert("JAVA_HOME".into(), "/jdk-b".into());
let all = super::plan(root, &model, super::BuildKind::Build, None, None).unwrap();
let all =
super::plan(root, &model, super::BuildKind::Build, None, None, None, &CancellationToken::new()).unwrap();
assert_eq!(all.steps.len(), 2);
assert_eq!(all.steps[0].cwd, root.join("a"));
assert_eq!(all.steps[1].cwd, root.join("b"));
let module = super::plan(root, &model, super::BuildKind::Rebuild, Some(&root.join("b/app")), None).unwrap();
let module = super::plan(
root,
&model,
super::BuildKind::Rebuild,
Some(&root.join("b/app")),
None,
None,
&CancellationToken::new(),
)
.unwrap();
assert_eq!(module.steps.len(), 1);
assert_eq!(module.steps[0].program, root.join("b").join(wrapper).to_string_lossy());
assert_eq!(module.steps[0].cwd, root.join("b"));
@@ -1066,11 +1111,31 @@ mod tests {
let mut nested = model.gradle[1].projects[1].clone();
nested.path = ":b:app".into();
model.gradle[0].projects.push(nested);
let nested = super::plan(root, &model, super::BuildKind::Build, Some(&root.join("b/app")), None).unwrap();
let nested = super::plan(
root,
&model,
super::BuildKind::Build,
Some(&root.join("b/app")),
None,
None,
&CancellationToken::new(),
)
.unwrap();
assert_eq!(nested.steps[0].program, root.join("b").join(wrapper).to_string_lossy());
assert_eq!(nested.steps[0].args, ["--console=plain", ":app:classes", ":app:testClasses"]);
model.gradle.clear();
assert!(super::plan(root, &model, super::BuildKind::Build, Some(&root.join("b/app")), None).is_err());
assert!(
super::plan(
root,
&model,
super::BuildKind::Build,
Some(&root.join("b/app")),
None,
None,
&CancellationToken::new()
)
.is_err()
);
}
#[test]
@@ -1092,18 +1157,24 @@ mod tests {
};
let mut model = crate::load_linked(&root, &base.join("cache"), None, &Default::default(), &settings);
model.gradle[0].env.insert("JAVA_HOME".into(), "/external-jdk".into());
let all = super::plan(&root, &model, super::BuildKind::Build, None, None).unwrap();
let all =
super::plan(&root, &model, super::BuildKind::Build, None, None, None, &CancellationToken::new()).unwrap();
assert_eq!(all.steps[0].cwd, external);
// Linked roots are saved with forward slashes, so on Windows the program mixes separators.
assert_eq!(std::path::Path::new(&all.steps[0].program), external.join(wrapper));
let module = super::plan(&root, &model, super::BuildKind::Rebuild, Some(&source), None).unwrap();
let module =
super::plan(&root, &model, super::BuildKind::Rebuild, Some(&source), None, None, &CancellationToken::new())
.unwrap();
assert_eq!(module.steps[0].cwd, external);
assert_eq!(module.steps[0].env["JAVA_HOME"], "/external-jdk");
assert_eq!(module.steps[0].args, ["--console=plain", ":app:clean", ":app:classes", ":app:testClasses"]);
let other = base.join("unlinked");
std::fs::create_dir(&other).unwrap();
std::fs::write(other.join("build.gradle"), "").unwrap();
assert!(super::plan(&root, &model, super::BuildKind::Build, Some(&other), None).is_err());
assert!(
super::plan(&root, &model, super::BuildKind::Build, Some(&other), None, None, &CancellationToken::new())
.is_err()
);
}
use super::*;
@@ -1144,7 +1215,7 @@ mod tests {
write(&root, "pom.xml", "<project><artifactId>demo</artifactId></project>");
let model = crate::load(&root, &tmp.path().join("cache"), None);
for (kind, expected) in [(BuildKind::Build, true), (BuildKind::Rebuild, true), (BuildKind::Artifacts, false)] {
let plan = plan(&root, &model, kind, None, None).unwrap();
let plan = plan(&root, &model, kind, None, None, None, &CancellationToken::new()).unwrap();
assert_eq!(
plan.steps[0].args.iter().any(|arg| arg == "-Djacoco.skip=true"),
expected,
@@ -1165,7 +1236,7 @@ mod tests {
write(&root, "core/pom.xml", "<project><artifactId>core</artifactId></project>");
write(&root, "core/src/main/java/A.java", "class A {}");
let model = crate::load(&root, &tmp.path().join("cache"), None);
let p = plan(&root, &model, BuildKind::Build, None, None).unwrap();
let p = plan(&root, &model, BuildKind::Build, None, None, None, &CancellationToken::new()).unwrap();
assert_eq!(p.system, BuildSystem::Maven);
assert_eq!(p.title, "demo");
assert_eq!(p.steps.len(), 1);
@@ -1173,7 +1244,16 @@ mod tests {
p.steps[0].args,
["-B", "-Dstyle.color=never", maven::LOCAL_REPO_TRACKING_ARG, "-Djacoco.skip=true", "test-compile"]
);
let p = plan(&root, &model, BuildKind::Rebuild, Some(&root.join("core/src/main/java/A.java")), None).unwrap();
let p = plan(
&root,
&model,
BuildKind::Rebuild,
Some(&root.join("core/src/main/java/A.java")),
None,
None,
&CancellationToken::new(),
)
.unwrap();
assert_eq!(
p.steps[0].args,
[
@@ -1195,24 +1275,36 @@ mod tests {
write(&g, "settings.gradle", "include 'app'");
write(&g, "app/build.gradle", "apply plugin: 'java'");
let model = crate::load(&g, &tmp.path().join("cache2"), None);
let p = plan(&g, &model, BuildKind::Build, Some(&g.join("app/src/A.java")), None).unwrap();
let p =
plan(&g, &model, BuildKind::Build, Some(&g.join("app/src/A.java")), None, None, &CancellationToken::new())
.unwrap();
assert_eq!(p.system, BuildSystem::Gradle);
assert_eq!(p.steps[0].args, ["--console=plain", ":app:classes", ":app:testClasses"]);
assert_eq!(
plan(&g, &model, BuildKind::Artifacts, None, None).unwrap().steps[0].args,
plan(&g, &model, BuildKind::Artifacts, None, None, None, &CancellationToken::new()).unwrap().steps[0].args,
["--console=plain", "assemble"]
);
let c = tmp.path().join("c");
write(&c, "Cargo.toml", "[package]\nname='c'");
let p = plan(&c, &BuildModel::default(), BuildKind::Rebuild, None, None).unwrap();
let p =
plan(&c, &BuildModel::default(), BuildKind::Rebuild, None, None, None, &CancellationToken::new()).unwrap();
assert_eq!(p.system, BuildSystem::Cargo);
assert_eq!(p.steps.len(), 2);
assert_eq!(p.steps[0].args[0], "clean");
let go = tmp.path().join("go");
write(&go, "go.mod", "module x");
let p = plan(&go, &BuildModel::default(), BuildKind::Build, Some(&go.join("pkg/a/a.go")), None).unwrap();
let p = plan(
&go,
&BuildModel::default(),
BuildKind::Build,
Some(&go.join("pkg/a/a.go")),
None,
None,
&CancellationToken::new(),
)
.unwrap();
assert_eq!(p.steps[0].args, ["build", "./pkg/a/..."]);
assert_eq!(p.steps[0].cwd, go);
@@ -1220,9 +1312,11 @@ mod tests {
write(&ts, "package.json", r#"{"scripts":{"build":"vite build"}}"#);
write(&ts, "tsconfig.json", "{}");
write(&ts, "pnpm-lock.yaml", "");
let p = plan(&ts, &BuildModel::default(), BuildKind::Build, None, None).unwrap();
let p =
plan(&ts, &BuildModel::default(), BuildKind::Build, None, None, None, &CancellationToken::new()).unwrap();
assert_eq!(p.steps[0].args, ["--noEmit", "--pretty", "false", "-p", "."]);
let p = plan(&ts, &BuildModel::default(), BuildKind::Artifacts, None, None).unwrap();
let p = plan(&ts, &BuildModel::default(), BuildKind::Artifacts, None, None, None, &CancellationToken::new())
.unwrap();
assert_eq!(
(p.steps[0].program.as_str(), p.steps[0].args.as_slice()),
("pnpm", &["run".to_owned(), "build".to_owned()][..])
@@ -1235,21 +1329,32 @@ mod tests {
write(&net, "src/Api/Api.csproj", "<Project/>");
write(&net, "src/Api/package.json", "{}");
write(&net, "src/Api/Program.cs", "");
let p = plan(&net, &BuildModel::default(), BuildKind::Build, None, None).unwrap();
let p =
plan(&net, &BuildModel::default(), BuildKind::Build, None, None, None, &CancellationToken::new()).unwrap();
assert_eq!(p.system, BuildSystem::Dotnet);
assert_eq!(p.steps[0].args, ["build", "App.sln", "-nologo", "-clp:NoSummary"]);
assert_eq!(p.steps[0].env["MSBUILDTERMINALLOGGER"], "off");
let p = plan(&net, &BuildModel::default(), BuildKind::Rebuild, Some(&net.join("src/Api/Program.cs")), None)
.unwrap();
let p = plan(
&net,
&BuildModel::default(),
BuildKind::Rebuild,
Some(&net.join("src/Api/Program.cs")),
None,
None,
&CancellationToken::new(),
)
.unwrap();
assert_eq!(p.steps[0].args, ["build", "Api.csproj", "-nologo", "-clp:NoSummary", "--no-incremental"]);
assert_eq!(p.steps[0].cwd, net.join("src/Api"));
let p = plan(&net, &BuildModel::default(), BuildKind::Artifacts, None, None).unwrap();
let p = plan(&net, &BuildModel::default(), BuildKind::Artifacts, None, None, None, &CancellationToken::new())
.unwrap();
assert_eq!(p.steps[0].args[0], "publish");
let cm = tmp.path().join("cm");
write(&cm, "CMakeLists.txt", "project(app)");
let args = |p: &BuildPlan| p.steps.iter().map(|s| s.args.join(" ")).collect::<Vec<_>>();
let p = plan(&cm, &BuildModel::default(), BuildKind::Build, None, None).unwrap();
let p =
plan(&cm, &BuildModel::default(), BuildKind::Build, None, None, None, &CancellationToken::new()).unwrap();
assert_eq!(p.system, BuildSystem::CMake);
assert_eq!(
args(&p),
@@ -1260,7 +1365,8 @@ mod tests {
"an unconfigured project is configured first"
);
write(&cm, "cmake-build-release/CMakeCache.txt", "");
let p = plan(&cm, &BuildModel::default(), BuildKind::Rebuild, None, None).unwrap();
let p =
plan(&cm, &BuildModel::default(), BuildKind::Rebuild, None, None, None, &CancellationToken::new()).unwrap();
assert_eq!(
args(&p),
["--build cmake-build-release --config Debug --clean-first"],
@@ -1272,17 +1378,34 @@ mod tests {
build_args: vec!["-j".into(), "8".into()],
..CMakeProfile::default()
};
let p =
plan(&cm, &BuildModel::default(), BuildKind::Build, None, Some(std::slice::from_ref(&profile))).unwrap();
let p = plan(
&cm,
&BuildModel::default(),
BuildKind::Build,
None,
Some(std::slice::from_ref(&profile)),
None,
&CancellationToken::new(),
)
.unwrap();
assert_eq!(args(&p), ["--build cmake-build-release --config Release -j 8"]);
let p = plan(&cm, &BuildModel::default(), BuildKind::Build, None, Some(&[CMakeProfile::default()])).unwrap();
let p = plan(
&cm,
&BuildModel::default(),
BuildKind::Build,
None,
Some(&[CMakeProfile::default()]),
None,
&CancellationToken::new(),
)
.unwrap();
assert_eq!(p.steps[0].args[..4], ["-S", ".", "-B", "cmake-build-debug"]);
let siblings = tmp.path().join("siblings");
write(&siblings, "core/pom.xml", "<project><artifactId>core</artifactId></project>");
write(&siblings, "system/pom.xml", "<project><artifactId>system</artifactId></project>");
let model = crate::load(&siblings, &tmp.path().join("cache3"), None);
let p = plan(&siblings, &model, BuildKind::Build, None, None).unwrap();
let p = plan(&siblings, &model, BuildKind::Build, None, None, None, &CancellationToken::new()).unwrap();
assert_eq!(p.system, BuildSystem::Maven);
assert_eq!(
p.steps.iter().map(|s| s.cwd.clone()).collect::<Vec<_>>(),
@@ -1291,7 +1414,9 @@ mod tests {
let none = tmp.path().join("none");
std::fs::create_dir_all(&none).unwrap();
assert!(plan(&none, &BuildModel::default(), BuildKind::Build, None, None).is_err());
assert!(
plan(&none, &BuildModel::default(), BuildKind::Build, None, None, None, &CancellationToken::new()).is_err()
);
}
#[test]
@@ -1490,7 +1615,8 @@ mod tests {
let model = reactor_model();
for (test, goal) in [(false, "compile"), (true, "test-compile")] {
// A normal launch is incremental: no `clean` (IDEA's Make, not Rebuild).
let plan = launch_plan(root, &model, &root.join("app"), test, BuildKind::Build).unwrap();
let plan = launch_plan(root, &model, &root.join("app"), test, BuildKind::Build, &CancellationToken::new())
.unwrap();
let step = &plan.steps[0];
assert_eq!(step.cwd, root);
assert_eq!(step.program, "mvnw");
@@ -1511,7 +1637,9 @@ mod tests {
]
);
// Rebuild cleans first, as IDEA's Rebuild does.
let plan = launch_plan(root, &model, &root.join("app"), test, BuildKind::Rebuild).unwrap();
let plan =
launch_plan(root, &model, &root.join("app"), test, BuildKind::Rebuild, &CancellationToken::new())
.unwrap();
assert_eq!(
plan.steps[0].args,
[
+408
Переглянути файл
@@ -0,0 +1,408 @@
//! Module-scoped Maven menu builds (`Build Project` on a multi-module reactor, #4078).
//!
//! A project build used to run every linked reactor from end to end; only the
//! all-or-nothing up-to-date check could skip it, so one edited file anywhere
//! paid a full reactor build. This module narrows the scope: per-module input
//! fingerprints recorded after the last successful build tell which modules'
//! sources, resources, POM chain or outputs changed, the module dependency graph
//! spreads that to the modules depending on them, and the reactor runs
//! `mvn -pl <modules> -am` over just that set. Maven still decides what
//! recompiles inside the selected modules; `-am` keeps the upstream modules a
//! changed module was built against. Reactors without a usable record, and any
//! analysis that cannot resolve its inputs, build everything as before.
use super::up_to_date::restamp;
use super::*;
use std::fs;
/// The per-module input fingerprints of one reactor's last successful build.
#[derive(serde::Serialize, serde::Deserialize)]
struct ReactorRecord {
/// Module directory (project-relative, `/`-separated) → its record.
modules: BTreeMap<String, ModuleRecord>,
}
#[derive(serde::Serialize, serde::Deserialize)]
struct ModuleRecord {
fingerprint: LaunchFingerprint,
/// Output folders of the module that existed after the build, relative to the
/// project. Deleting one outside the IDE (`mvn clean` in a terminal) leaves every
/// input unchanged, so the module is rebuilt only while they are gone.
outputs: Vec<PathBuf>,
}
fn record_path(cache: &Path, top_dir: &str) -> PathBuf {
let base = cache.join("menu-build").join("modules");
if top_dir.is_empty() { base.join("root.json") } else { base.join(format!("{top_dir}.json")) }
}
fn load_record(cache: &Path, top_dir: &str) -> Option<ReactorRecord> {
let bytes = fs::read(record_path(cache, top_dir)).ok()?;
serde_json::from_slice(&bytes).ok()
}
/// Projects of `reactor` that (transitively) depend on one of `changed`, through
/// dependencies whose version matches the provider. The reverse of the launch
/// upstream walk: a changed module's new classes force its consumers to recompile,
/// `test`-scoped ones included, since the project build compiles every module's tests.
fn affected_projects(reactor: &[&maven::MavenProject], changed: &HashSet<String>) -> HashSet<String> {
let mut affected = changed.clone();
let mut pending: Vec<&str> = changed.iter().map(String::as_str).collect();
while let Some(dir) = pending.pop() {
let Some(upstream) = reactor.iter().find(|p| p.dir == dir) else { continue };
for consumer in reactor {
if affected.contains(&consumer.dir) {
continue;
}
let depends = consumer.dependencies.iter().any(|d| {
d.resolved()
&& upstream.group_id == d.group_id
&& upstream.artifact_id == d.artifact_id
&& d.version.as_ref().is_none_or(|v| *v == upstream.version)
});
if depends {
affected.insert(consumer.dir.clone());
pending.push(consumer.dir.as_str());
}
}
}
affected
}
/// `-pl` entries of the affected modules, relative to the reactor root the step
/// runs in, sorted so the command line does not depend on the model's project
/// order (Maven reorders the selection into its own reactor order anyway).
fn selection(reactor: &[&maven::MavenProject], top_dir: &str, affected: &HashSet<String>) -> String {
let mut entries: Vec<String> = reactor
.iter()
.filter(|p| affected.contains(&p.dir))
.map(|p| {
Path::new(&p.dir).strip_prefix(top_dir).unwrap_or(Path::new(&p.dir)).to_string_lossy().replace('\\', "/")
})
.collect();
entries.sort();
entries.join(",")
}
/// Narrowed `Build Project` steps: per reactor, one full step when the reactor
/// or most of it is affected, one `-pl <modules> -am` step for the affected
/// subset, or no step at all when nothing changed since the last successful
/// build. `None` = some module's inputs cannot be fingerprinted, so the caller
/// falls back to the unscoped build. The `step` closure builds a reactor step
/// with the caller's goals and options.
pub(super) fn narrowed_maven_steps(
cache: &Path,
root: &Path,
m: &maven::MavenModel,
step: &impl Fn(&maven::MavenProject, &[String]) -> BuildStep,
cancel: &CancellationToken,
) -> IdeResult<Option<Vec<BuildStep>>> {
let mut steps = Vec::new();
for top in m.projects.iter().filter(|p| !p.aggregated) {
let Some(record) = load_record(cache, &top.dir) else {
steps.push(step(top, &[]));
continue;
};
let reactor = reactor_projects(m, top);
let mut changed = HashSet::new();
let mut lying: Vec<PathBuf> = Vec::new();
for project in &reactor {
let Some(current) = fingerprint::module_fingerprint(root, project, cancel)? else {
return Ok(None);
};
let Some(recorded) = record.modules.get(&project.dir) else {
changed.insert(project.dir.clone());
continue;
};
if recorded.fingerprint != current {
changed.insert(project.dir.clone());
lying.extend(recorded.fingerprint.mtime_preserved_edits(&current));
}
if !recorded.outputs.iter().all(|out| root.join(out).is_dir()) {
changed.insert(project.dir.clone());
}
}
if changed.is_empty() {
continue;
}
let affected = affected_projects(&reactor, &changed);
restamp(root, &lying);
if affected.len() >= reactor.len() || affected.contains(&top.dir) {
steps.push(step(top, &[]));
} else {
let pl = selection(&reactor, &top.dir, &affected);
steps.push(step(top, &["-pl".into(), pl, "-am".into()]));
}
}
Ok(Some(steps))
}
/// Records the per-module inputs of every linked reactor as the baseline of the
/// next narrowed build. Failures are swallowed: a missing record only costs one
/// unscoped Maven run. Called after a successful project build.
pub fn record_module_build(cache: &Path, root: &Path, model: &BuildModel, cancel: &CancellationToken) {
let Some(m) = &model.maven else { return };
for top in m.projects.iter().filter(|p| !p.aggregated) {
let mut modules = BTreeMap::new();
for project in reactor_projects(m, top) {
let Ok(Some(fingerprint)) = fingerprint::module_fingerprint(root, project, cancel) else { continue };
let outputs = ["target/classes", "target/test-classes"]
.iter()
.map(|out| Path::new(&project.dir).join(out))
.filter(|rel| root.join(rel).is_dir())
.collect();
modules.insert(project.dir.clone(), ModuleRecord { fingerprint, outputs });
}
let path = record_path(cache, &top.dir);
if path.parent().is_some_and(|p| fs::create_dir_all(p).is_err()) {
continue;
}
let Ok(bytes) = serde_json::to_vec(&ReactorRecord { modules }) else { continue };
let _ = fs::write(&path, bytes);
}
}
#[cfg(test)]
mod tests {
use super::*;
fn write(root: &Path, rel: &str, value: &str) {
let path = root.join(rel);
fs::create_dir_all(path.parent().unwrap()).unwrap();
fs::write(path, value).unwrap();
}
/// `other` ← nothing, `app` ← `mid` ← `lib`, all under one reactor root.
fn fixture(root: &Path) -> BuildModel {
write(
root,
"pom.xml",
r#"<project><modelVersion>4.0.0</modelVersion><groupId>t</groupId><artifactId>root</artifactId><version>1</version><packaging>pom</packaging><modules><module>lib</module><module>mid</module><module>app</module><module>other</module></modules></project>"#,
);
for (dir, class, deps) in [
("lib", "L", ""),
(
"mid",
"M",
"<dependencies><dependency><groupId>t</groupId><artifactId>lib</artifactId><version>1</version></dependency></dependencies>",
),
(
"app",
"A",
"<dependencies><dependency><groupId>t</groupId><artifactId>mid</artifactId><version>1</version></dependency></dependencies>",
),
("other", "O", ""),
] {
write(
root,
&format!("{dir}/pom.xml"),
&format!(
r#"<project><modelVersion>4.0.0</modelVersion><parent><groupId>t</groupId><artifactId>root</artifactId><version>1</version></parent><artifactId>{dir}</artifactId>{deps}</project>"#
),
);
write(
root,
&format!("{dir}/src/main/java/t/{class}.java"),
&format!("package t; public class {class} {{}}"),
);
}
BuildModel { maven: Some(maven::load(root)), ..Default::default() }
}
fn steps(cache: &Path, root: &Path, model: &BuildModel) -> Option<Vec<BuildStep>> {
narrowed_maven_steps(
cache,
root,
model.maven.as_ref().unwrap(),
&|p, extra| {
let mut s = BuildStep::new(&p.command, &["-B"], &subdir(root, &p.dir), Format::Maven);
s.args.extend(extra.iter().cloned());
s.args.push("test-compile".into());
s
},
&CancellationToken::new(),
)
.unwrap()
}
fn pl_arg(step: &BuildStep) -> String {
let i = step.args.iter().position(|a| a == "-pl").unwrap();
step.args[i + 1].clone()
}
#[test]
fn changed_module_selects_itself_and_transitive_dependents() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
let model = fixture(root);
let cache = root.join("cache");
record_module_build(&cache, root, &model, &CancellationToken::new());
write(root, "lib/src/main/java/t/L.java", "package t; public class L { int x; }");
let steps = steps(&cache, root, &model).unwrap();
assert_eq!(steps.len(), 1);
assert_eq!(pl_arg(&steps[0]), "app,lib,mid");
assert!(steps[0].args.contains(&"-am".into()));
}
#[test]
fn unchanged_reactor_runs_nothing() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
let model = fixture(root);
let cache = root.join("cache");
record_module_build(&cache, root, &model, &CancellationToken::new());
assert!(steps(&cache, root, &model).unwrap().is_empty());
}
#[test]
fn missing_or_corrupt_record_builds_everything() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
let model = fixture(root);
let cache = root.join("cache");
assert_eq!(steps(&cache, root, &model).unwrap().len(), 1);
record_module_build(&cache, root, &model, &CancellationToken::new());
fs::create_dir_all(cache.join("menu-build").join("modules")).unwrap();
fs::write(cache.join("menu-build").join("modules").join("root.json"), b"{not json").unwrap();
assert_eq!(steps(&cache, root, &model).unwrap().len(), 1);
}
#[test]
fn deleted_output_rebuilds_the_module_without_spreading() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
let model = fixture(root);
let cache = root.join("cache");
for out in ["mid/target/classes/t", "other/target/classes"] {
fs::create_dir_all(root.join(out)).unwrap();
}
record_module_build(&cache, root, &model, &CancellationToken::new());
fs::remove_dir_all(root.join("mid/target")).unwrap();
let steps = steps(&cache, root, &model).unwrap();
assert_eq!(pl_arg(&steps[0]), "app,mid");
}
#[test]
fn mtime_preserved_edit_is_restamped_before_the_build() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
let model = fixture(root);
let cache = root.join("cache");
let rel = "lib/src/main/java/t/L.java";
write(root, rel, "package t; public class L { int x; }");
let mtime = fs::metadata(root.join(rel)).unwrap().modified().unwrap();
record_module_build(&cache, root, &model, &CancellationToken::new());
write(root, rel, "package t; public class L { int z; }");
fs::File::options().write(true).open(root.join(rel)).unwrap().set_modified(mtime).unwrap();
assert!(!steps(&cache, root, &model).unwrap().is_empty());
assert!(fs::metadata(root.join(rel)).unwrap().modified().unwrap() > mtime);
}
#[test]
fn test_scoped_consumers_are_rebuilt_and_version_mismatch_does_not_spread() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
write(
root,
"pom.xml",
r#"<project><modelVersion>4.0.0</modelVersion><groupId>t</groupId><artifactId>root</artifactId><version>1</version><packaging>pom</packaging><modules><module>lib</module><module>tester</module><module>v2</module></modules></project>"#,
);
write(
root,
"lib/pom.xml",
r#"<project><modelVersion>4.0.0</modelVersion><parent><groupId>t</groupId><artifactId>root</artifactId><version>1</version></parent><artifactId>lib</artifactId></project>"#,
);
write(
root,
"tester/pom.xml",
r#"<project><modelVersion>4.0.0</modelVersion><parent><groupId>t</groupId><artifactId>root</artifactId><version>1</version></parent><artifactId>tester</artifactId><dependencies><dependency><groupId>t</groupId><artifactId>lib</artifactId><version>1</version><scope>test</scope></dependency></dependencies></project>"#,
);
write(
root,
"v2/pom.xml",
r#"<project><modelVersion>4.0.0</modelVersion><parent><groupId>t</groupId><artifactId>root</artifactId><version>1</version></parent><artifactId>v2</artifactId><dependencies><dependency><groupId>t</groupId><artifactId>lib</artifactId><version>2</version></dependency></dependencies></project>"#,
);
for module in ["lib", "tester", "v2"] {
write(root, &format!("{module}/src/main/java/t/{module}.java"), "package t;");
}
let model = BuildModel { maven: Some(maven::load(root)), ..Default::default() };
let cache = root.join("cache");
record_module_build(&cache, root, &model, &CancellationToken::new());
write(root, "lib/src/main/java/t/L.java", "package t; public class L {}");
let steps = steps(&cache, root, &model).unwrap();
// `tester`'s tests compile against `lib`.
assert_eq!(pl_arg(&steps[0]), "lib,tester");
}
#[test]
fn root_pom_change_selects_the_whole_reactor() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
let model = fixture(root);
let cache = root.join("cache");
record_module_build(&cache, root, &model, &CancellationToken::new());
write(
root,
"pom.xml",
fs::read_to_string(root.join("pom.xml")).unwrap().replace("<modules>", "<!-- x --><modules>").as_str(),
);
let steps = steps(&cache, root, &model).unwrap();
assert_eq!(steps.len(), 1);
assert!(!steps[0].args.contains(&"-pl".into()));
}
/// A folder of two sibling reactors: `chain` (lib ← mid ← app) and `solo`.
fn two_reactors(root: &Path) -> BuildModel {
write(
root,
"chain/pom.xml",
r#"<project><modelVersion>4.0.0</modelVersion><groupId>t</groupId><artifactId>chain</artifactId><version>1</version><packaging>pom</packaging><modules><module>lib</module><module>mid</module><module>app</module></modules></project>"#,
);
for (dir, class, deps) in [
("lib", "L", ""),
(
"mid",
"M",
"<dependencies><dependency><groupId>t</groupId><artifactId>lib</artifactId><version>1</version></dependency></dependencies>",
),
(
"app",
"A",
"<dependencies><dependency><groupId>t</groupId><artifactId>mid</artifactId><version>1</version></dependency></dependencies>",
),
] {
write(
root,
&format!("chain/{dir}/pom.xml"),
&format!(
r#"<project><modelVersion>4.0.0</modelVersion><parent><groupId>t</groupId><artifactId>chain</artifactId><version>1</version></parent><artifactId>{dir}</artifactId>{deps}</project>"#
),
);
write(
root,
&format!("chain/{dir}/src/main/java/t/{class}.java"),
&format!("package t; public class {class} {{}}"),
);
}
write(
root,
"solo/pom.xml",
r#"<project><modelVersion>4.0.0</modelVersion><groupId>t</groupId><artifactId>solo</artifactId><version>1</version></project>"#,
);
write(root, "solo/src/main/java/t/S.java", "package t;");
BuildModel { maven: Some(maven::load(root)), ..Default::default() }
}
#[test]
fn unrelated_reactors_are_judged_separately() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
let model = two_reactors(root);
let cache = root.join("cache");
record_module_build(&cache, root, &model, &CancellationToken::new());
write(root, "solo/src/main/java/t/S.java", "package t; public class S {}");
let steps = steps(&cache, root, &model).unwrap();
assert_eq!(steps.len(), 1);
assert_eq!(steps[0].cwd, subdir(root, "solo"));
}
}
+1 -1
Переглянути файл
@@ -41,7 +41,7 @@ fn record_path(cache: &Path, root: &Path, file: Option<&Path>) -> PathBuf {
/// Re-stamps files whose content changed without advancing mtime (git
/// checkout, external sync): timestamp-incremental Maven would otherwise skip
/// them as "unchanged" and the rebuild would compile nothing.
fn restamp(root: &Path, edits: &[PathBuf]) {
pub(super) fn restamp(root: &Path, edits: &[PathBuf]) {
let now = std::time::SystemTime::now();
for rel in edits {
let path = root.join(rel);
+5 -5
Переглянути файл
@@ -78,14 +78,14 @@ fn has_kotlin_sources(root: &Path) -> bool {
})
}
fn plan(root: &Path, model: &BuildModel) -> IdeResult<compile::BuildPlan> {
fn plan(root: &Path, model: &BuildModel, cancel: &CancellationToken) -> IdeResult<compile::BuildPlan> {
if model.maven.as_ref().is_none_or(|m| m.projects.is_empty()) {
return Err(IdeError::invalid("Kotlin bridge requires a Maven build root"));
}
Ok(compile::BuildPlan {
system: compile::BuildSystem::Maven,
title: root.file_name().unwrap_or_default().to_string_lossy().into_owned(),
steps: compile::maven_steps(root, model, BuildKind::Build, None)?,
steps: compile::maven_steps(root, model, BuildKind::Build, None, None, cancel)?,
})
}
@@ -99,7 +99,7 @@ pub fn build(
cancel: &CancellationToken,
) -> IdeResult<Outcome> {
std::fs::create_dir_all(generation)?;
let mut plan = plan(root, model)?;
let mut plan = plan(root, model, cancel)?;
let mut manifests = Vec::new();
for (index, step) in plan.steps.iter_mut().enumerate() {
step.args.push("--fail-at-end".into());
@@ -522,7 +522,7 @@ mod tests {
}
std::fs::write(root.join("kotlin/App.kt"), "class App").unwrap();
assert!(has_kotlin(root, &model), "{marker}");
let plan = plan(root, &model).unwrap();
let plan = plan(root, &model, &CancellationToken::new()).unwrap();
assert_eq!(plan.system, compile::BuildSystem::Maven);
assert_eq!(plan.steps.len(), 2);
for (step, name) in plan.steps.iter().zip(["java", "kotlin"]) {
@@ -562,7 +562,7 @@ mod tests {
..Default::default()
};
assert!(has_kotlin(workspace.path(), &model));
assert_eq!(plan(workspace.path(), &model).unwrap().steps[0].cwd, external.path());
assert_eq!(plan(workspace.path(), &model, &CancellationToken::new()).unwrap().steps[0].cwd, external.path());
}
#[test]
+19
Переглянути файл
@@ -268,6 +268,24 @@ pub async fn agent_prompt(host: &Host, window: &str, task: String, prompt: Agent
host.project(window)?.agents.prompt(&task, prompt, now).await
}
/// Runs a `!` line of the composer in the task's folder with the user's shell, without
/// starting a turn; its output goes to the agent with the next message.
#[command(trust = trusted)]
pub async fn agent_shell(
host: &Host,
window: &str,
task: String,
command: String,
request: RequestId,
) -> IdeResult<()> {
host.require_trust(window)?;
let agents = host.project(window)?.agents.clone();
let cancel = host.begin_request(request);
let result = agents.run_shell(&task, &command, cancel).await;
host.end_request(request);
result
}
/// Answers a non-blocking question, without cancelling the current turn.
#[command(trust = trusted)]
pub async fn agent_answer_question(
@@ -1080,6 +1098,7 @@ ide_command::domain!(
agent_rollback_changes,
agent_send_queued_now,
agent_set_command,
agent_shell,
agent_set_config,
agent_set_env,
agent_set_mcp_overrides,
+48 -6
Переглянути файл
@@ -815,7 +815,15 @@ pub async fn build_run(
if compile::menu_up_to_date(&cache, &root, &model, file.as_deref(), &token) {
let started = std::time::Instant::now();
let plan = prepare_plan(
compile::plan(&root, &model, kind, file.as_deref(), settings.cmake.profiles.as_deref())?,
compile::plan(
&root,
&model,
kind,
file.as_deref(),
settings.cmake.profiles.as_deref(),
None,
&token,
)?,
&root,
&settings,
);
@@ -853,7 +861,15 @@ pub async fn build_run(
if member == &root { cache.clone() } else { cache.join(crate::project::project_key(member)) };
let model = with_profiles(load(member, &member_cache, &settings), &member_cache);
let plan = prepare_plan(
compile::plan(member, &model, kind, file.as_deref(), settings.cmake.profiles.as_deref())?,
compile::plan(
member,
&model,
kind,
file.as_deref(),
settings.cmake.profiles.as_deref(),
None,
&token,
)?,
member,
&settings,
);
@@ -867,7 +883,15 @@ pub async fn build_run(
plan
} else {
let model = with_profiles(load(&root, &cache, &settings), &cache);
match compile::plan(&root, &model, kind, file.as_deref(), settings.cmake.profiles.as_deref()) {
match compile::plan(
&root,
&model,
kind,
file.as_deref(),
settings.cmake.profiles.as_deref(),
Some(&cache),
&token,
) {
Ok(plan) => prepare_plan(plan, &root, &settings),
// No build tool: a Java project builds from its Project Structure.
Err(e) if e.kind == ide_core::error::ErrorKind::NotFound => {
@@ -882,6 +906,11 @@ pub async fn build_run(
if result.success && single && kind == BuildKind::Build {
let model = with_profiles(load(&root, &cache, &settings), &cache);
compile::record_menu_build(&cache, &root, &model, file.as_deref(), &token);
// Only a project build covers every changed module; after Build Module the
// others may still be stale.
if file.is_none() {
compile::record_module_build(&cache, &root, &model, &token);
}
}
for (path, items) in compile::diagnostics(&result.messages) {
sink.emit(IdeEvent::Diagnostics { path: path.into(), source: compile::DIAGNOSTICS_SOURCE.into(), items });
@@ -1015,7 +1044,16 @@ mod build_tool_settings_tests {
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join(marker), source).unwrap();
let plan = prepare_plan(
compile::plan(&dir, &Default::default(), BuildKind::Artifacts, None, None).unwrap(),
compile::plan(
&dir,
&Default::default(),
BuildKind::Artifacts,
None,
None,
None,
&ide_core::CancellationToken::new(),
)
.unwrap(),
root,
&settings,
);
@@ -1089,7 +1127,9 @@ mod build_tool_settings_tests {
let expected = root.join(if runner.is_empty() { "project-jdk" } else { runner });
let model = load(&root, &root.join("cache"), &settings);
assert_eq!(model.maven.as_ref().unwrap().projects[0].env["JAVA_HOME"], expected.to_string_lossy());
let plan = compile::plan(&root, &model, BuildKind::Build, None, None).unwrap();
let plan =
compile::plan(&root, &model, BuildKind::Build, None, None, None, &ide_core::CancellationToken::new())
.unwrap();
assert!(!plan.steps.is_empty());
for step in plan.steps {
assert_eq!(step.env["JAVA_HOME"], expected.to_string_lossy());
@@ -1121,7 +1161,9 @@ mod build_tool_settings_tests {
let expected = root.join(name);
let model = load(&root, &root.join("cache"), &settings);
assert_eq!(model.maven.as_ref().unwrap().projects[0].env["JAVA_HOME"], expected.to_string_lossy());
let plan = compile::plan(&root, &model, BuildKind::Build, None, None).unwrap();
let plan =
compile::plan(&root, &model, BuildKind::Build, None, None, None, &ide_core::CancellationToken::new())
.unwrap();
assert!(!plan.steps.is_empty());
for step in plan.steps {
assert_eq!(step.env["JAVA_HOME"], expected.to_string_lossy());
+1
Переглянути файл
@@ -174,6 +174,7 @@ async fn restricted_vcs_commands_run_no_program_of_the_repository() {
call!("vcs_status", "", ops::vcs::vcs_status(host, w)),
call!("vcs_status_paths", "", ops::vcs::vcs_status_paths(host, w, vec![file.clone()])),
sync!("vcs_roots", "", vcs::vcs_roots(host, w)),
call!("vcs_detected_roots", "", vcs::vcs_detected_roots(host, w)),
call!("vcs_branch_info", "", vcs::vcs_branch_info(host, w, root())),
call!("vcs_line_hunks", "", vcs::vcs_line_hunks(host, w, file.clone())),
call!("vcs_file_at", "", vcs::vcs_file_at(host, w, file.clone(), None)),
+2
Переглянути файл
@@ -354,6 +354,8 @@ fn nested_builds_of_every_kind_and_depth() {
ide_build::compile::BuildKind::Build,
Some(&dir.path().join("services/api/app/src/main/kotlin/com/acme/Api.kt")),
None,
None,
&ide_core::CancellationToken::new(),
)
.unwrap();
assert_eq!(plan.steps[0].cwd, dir.path().join("services/api"));
+1 -1
Переглянути файл
@@ -178,7 +178,7 @@ test("a tool window resize keeps its cursor over other controls until release",
await page.mouse.down();
await page.mouse.move(box.x + 80, box.y + box.height / 2, { steps: 4 });
// The pointer is over the Project tree now; the button's own arrow cursor must not win.
await expect.poll(cursor).toBe("ew-resize");
await expect.poll(cursor).toBe("col-resize");
expect(await page.evaluate(() => document.documentElement.hasAttribute("data-drag-cursor"))).toBe(true);
await page.mouse.up();
+49
Переглянути файл
@@ -214,6 +214,54 @@ pub fn window_take_launch(window: WebviewWindow, windows: State<'_, WindowsState
windows.take_launch(window.label())
}
#[derive(Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct SettingsWindowInit {
pub launch: Option<Launch>,
pub remote: Option<crate::remote_dev::RemoteSession>,
pub project: Option<ide_host::ops::project::ProjectInfo>,
pub global_settings: ide_core::settings::Settings,
pub updates: bool,
}
/// Local bootstrap snapshot for a `settings-<parent>` window, avoiding a sequential
/// startup IPC waterfall and any blocking SSH `project_current` round-trip before first paint.
#[desktop_command(trust = always)]
#[tauri::command]
#[specta::specta]
pub fn window_take_settings_init(
app: AppHandle,
window: WebviewWindow,
windows: State<'_, WindowsState>,
state: State<'_, AppState>,
) -> SettingsWindowInit {
let owner = AppState::owner_window(window.label());
let launch = windows.take_launch(window.label());
let (remote, project) = if let Some(c) = state.remote_dev.get(owner) {
let session = crate::remote_dev::RemoteSession {
target: c.target.clone(),
root: c.root.clone(),
host: c.host.clone(),
os: c.os.clone(),
commands: c.commands.clone(),
};
// Leave `project` empty on remote sessions: the Settings page tree renders immediately
// from local client settings, and `projectCurrent()` fills in project-scoped settings
// right after first paint without keeping a shadow cache in sync.
(Some(session), None)
} else {
let project = state.project(owner).ok().filter(|p| !p.light).map(|p| ide_host::ops::project::info(&p));
(None, project)
};
SettingsWindowInit {
launch,
remote,
project,
global_settings: state.host.with_proxy_password(state.global_settings.effective()),
updates: updates_configured(&app),
}
}
/// Release the opening window's reservation after navigation or cancellation.
#[desktop_command(trust = always)]
#[tauri::command]
@@ -889,6 +937,7 @@ ide_command::desktop_domain!(
window_set_smooth_scrolling,
window_set_titlebar_height,
window_take_launch,
window_take_settings_init,
window_toggle_fullscreen,
window_toggle_zoom,
);
+2
Переглянути файл
@@ -42,6 +42,7 @@ agent_set_command trusted project_host bin
agent_set_config trusted project_host bindings async
agent_set_env trusted project_host bindings sync
agent_set_mcp_overrides always project_host bindings sync
agent_shell trusted project_host bindings async
agent_stop_background always project_host bindings async
agent_subscribe always project_host bindings sync
agent_unarchive always project_host bindings sync
@@ -730,6 +731,7 @@ window_set_smooth_scrolling always desktop bin
window_set_titlebar_height always desktop bindings sync
window_start_drag always desktop bindings sync
window_take_launch always desktop bindings sync
window_take_settings_init always desktop bindings sync
window_toggle_fullscreen always desktop bindings sync
window_toggle_zoom always desktop bindings sync
workspace_attach always desktop bindings async
+28
Переглянути файл
@@ -135,6 +135,11 @@ export const commands = {
agentSetEnv: (id: string, env: { [key in string]: string }) => typedError<null, IdeError>(__TAURI_INVOKE("agent_set_env", { id, env })),
/** Updates per-session MCP server enable/disable overrides on `task`. */
agentSetMcpOverrides: (task: string, overrides: { [key in string]: boolean }) => typedError<AgentTask_Serialize, IdeError>(__TAURI_INVOKE("agent_set_mcp_overrides", { task, overrides })),
/**
* Runs a `!` line of the composer in the task's folder with the user's shell, without
* starting a turn; its output goes to the agent with the next message.
*/
agentShell: (task: string, command: string, request: RequestId) => typedError<null, IdeError>(__TAURI_INVOKE("agent_shell", { task, command, request })),
/** Stops one of the task's background tasks. */
agentStopBackground: (task: string, background: string) => typedError<null, IdeError>(__TAURI_INVOKE("agent_stop_background", { task, background })),
/** Streams the project's agent events to this window; returns every task. */
@@ -1963,6 +1968,11 @@ export const commands = {
/** Deployment windows: the server and local selection to compare. */
deployment: DeploymentLaunch | null,
} | null>("window_take_launch"),
/**
* Local bootstrap snapshot for a `settings-<parent>` window, avoiding a sequential
* startup IPC waterfall and any blocking SSH `project_current` round-trip before first paint.
*/
windowTakeSettingsInit: () => __TAURI_INVOKE<SettingsWindowInit_Serialize>("window_take_settings_init"),
windowToggleFullscreen: () => typedError<boolean, IdeError>(__TAURI_INVOKE("window_toggle_fullscreen")),
/** Fills the work area without the platform zoom animation. Returns whether it is filled now. */
windowToggleZoom: () => typedError<boolean, IdeError>(__TAURI_INVOKE("window_toggle_zoom")),
@@ -10702,6 +10712,24 @@ export type SettingsImport_Serialize = {
export type SettingsScope = "global" | "project";
export type SettingsWindowInit = SettingsWindowInit_Serialize | SettingsWindowInit_Deserialize;
export type SettingsWindowInit_Deserialize = {
launch: Launch_Deserialize | null,
remote: RemoteSession | null,
project: ProjectInfo_Deserialize | null,
globalSettings: Settings_Deserialize,
updates: boolean,
};
export type SettingsWindowInit_Serialize = {
launch: Launch_Serialize | null,
remote: RemoteSession | null,
project: ProjectInfo_Serialize | null,
globalSettings: Settings_Serialize,
updates: boolean,
};
export type Settings_Deserialize = {
general?: GeneralSettings,
appearance?: AppearanceSettings_Deserialize,
+12 -2
Переглянути файл
@@ -52,7 +52,7 @@ import { save as saveFileDialog, type DialogFilter as SaveDialogFilter } from "@
import { isUntitledUri, untitledTitle } from "@/platform/virtualDocs";
import { isRemoteWindow } from "@/platform/remote";
import { fileIconName, showContextMenu, type MenuItem } from "@/ui";
import { canRevealInFileManager, fileManagerName } from "@/platform/fileManager";
import { canOpenWithSystemApp, canRevealInFileManager, fileManagerName } from "@/platform/fileManager";
import {
activateTab,
changeSplitOrientation,
@@ -2255,7 +2255,7 @@ export class EditorController implements SlotHost {
}
}
/** Open In › for a file: Project View, Finder / Explorer / Files, Terminal. */
/** Open In › for a file: Project View, Finder / Explorer / Files, associated app, Terminal. */
function openInMenu(path: string, line?: number): MenuItem {
return {
label: "Open In",
@@ -2264,6 +2264,16 @@ function openInMenu(path: string, line?: number): MenuItem {
...(canRevealInFileManager()
? [{ kind: "action" as const, action: "project.revealInFinder", arg: path, label: fileManagerName() }]
: []),
...(canOpenWithSystemApp()
? [
{
kind: "action" as const,
action: "project.openWithAssociatedApp",
arg: path,
label: "Associated Application",
},
]
: []),
{ kind: "action", action: "project.openInTerminal", arg: path, label: "Terminal" },
{ kind: "separator" },
...menuGroupItems("openIn", { paths: [path], line }),
+9
Переглянути файл
@@ -396,6 +396,15 @@ export function toPrompt(draft: ComposerDraft): AgentPrompt {
};
}
/**
* The shell command of a message starting with `!` (Claude Code's bash mode): it runs in the
* task's folder instead of going to the agent. `null` for any other message.
*/
export function shellCommand(d: ComposerDraft): string | null {
if (!d.text.startsWith("!") || d.images.length > 0 || d.files.some((f) => f.attached)) return null;
return d.text.slice(1).trim() || null;
}
export const canSend = (d: ComposerDraft) => !!d.text.trim() || d.images.length > 0 || d.files.some((f) => f.attached);
/**
+74
Переглянути файл
@@ -0,0 +1,74 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { AgentTask } from "@/bindings";
import { emptyDraft, shellCommand } from "./composerModel";
import { composerDraft, sendMessage, stopTask, updateComposer, useAgents } from "./store";
const backend = vi.hoisted(() => ({
shell: vi.fn(),
prompt: vi.fn(),
cancelRequest: vi.fn(),
cancel: vi.fn(),
}));
vi.mock("@/platform/ipc", async (original) => ({
...(await original<typeof import("@/platform/ipc")>()),
commands: {
agentShell: backend.shell,
agentPrompt: backend.prompt,
agentCancel: backend.cancel,
cancelRequest: backend.cancelRequest,
},
}));
const ok = { status: "ok" as const, data: null };
beforeEach(() => {
for (const f of Object.values(backend)) f.mockReset();
backend.prompt.mockResolvedValue(ok);
backend.cancel.mockResolvedValue(ok);
useAgents.setState({
tasks: new Map([["t", { id: "t", status: "ready" } as AgentTask]]),
shellRunning: new Set(),
});
updateComposer("t", emptyDraft());
});
describe("`!` commands in the composer", () => {
it("are told apart from messages", () => {
const draft = (text: string) => ({ ...emptyDraft(), text });
expect(shellCommand(draft("! git status "))).toBe("git status");
expect(shellCommand(draft("!ls"))).toBe("ls");
expect(shellCommand(draft("!"))).toBeNull();
expect(shellCommand(draft("fix this!"))).toBeNull();
expect(shellCommand(draft(" !ls"))).toBeNull();
const image = { name: "a.png", data: "", mimeType: "image/png" };
expect(shellCommand({ ...draft("!ls"), images: [image] })).toBeNull();
});
it("run in the task instead of going to the agent, and Stop ends them", async () => {
let finish!: () => void;
backend.shell.mockReturnValue(new Promise((done) => (finish = () => done(ok))));
updateComposer("t", { text: "! git status" });
const sent = sendMessage("t", false);
await vi.waitFor(() => expect(backend.shell).toHaveBeenCalled());
const [task, command, request] = backend.shell.mock.calls[0]!;
expect([task, command]).toEqual(["t", "git status"]);
expect(composerDraft("t").text).toBe("");
expect(useAgents.getState().shellRunning.has("t")).toBe(true);
await stopTask("t");
expect(backend.cancelRequest).toHaveBeenCalledWith(request);
// The agent isn't working: nothing else to stop.
expect(backend.cancel).not.toHaveBeenCalled();
finish();
await sent;
expect(useAgents.getState().shellRunning.has("t")).toBe(false);
expect(backend.prompt).not.toHaveBeenCalled();
});
it("leave other messages to the agent", async () => {
updateComposer("t", { text: "fix this!" });
await sendMessage("t", false);
expect(backend.prompt).toHaveBeenCalledOnce();
expect(backend.shell).not.toHaveBeenCalled();
});
});
+3 -2
Переглянути файл
@@ -18,7 +18,7 @@ import { useEffortFocus } from "../effortFocus";
import { isBusy } from "../model";
import { asksInCard, type PermissionEntry } from "../permission";
import {
cancelTask,
stopTask,
editQueued,
refreshTaskModels,
removeQueued,
@@ -177,6 +177,7 @@ export function SessionComposer({
const [assetFocus, setAssetFocus] = useState(0);
const agentCommands = useAgentCommands(task.provider, task.id, task.commands);
const busy = isBusy(task.status);
const shellRunning = useAgents((s) => s.shellRunning.has(task.id));
// ↑ recalls this conversation's messages, newest first.
const history = useMemo(
() => (entries ?? []).flatMap((e) => (e.type === "user" && e.text ? [e.text] : [])).reverse(),
@@ -297,7 +298,7 @@ export function SessionComposer({
}
actions={
<>
{busy && <IconButton icon="stop" title="Stop" onClick={() => void cancelTask(task.id)} />}
{(busy || shellRunning) && <IconButton icon="stop" title="Stop" onClick={() => void stopTask(task.id)} />}
<SubmitButton
label={busy ? "Queue" : "Send"}
pending={sending}
+43 -1
Переглянути файл
@@ -19,19 +19,21 @@ import type {
AgentTask,
ExternalSession,
Isolation,
RequestId,
} from "@/bindings";
import { useChangesOptions } from "./changesOptions";
import { clearAgentTaskFontZoom, resetAllAgentFontZoom } from "./fontZoom";
import { clearDismissedAssets } from "./sessionAssetsModel";
import { basename, useProject } from "@/platform/project";
import { defaultTaskProject } from "./project";
import { call, commands, isTauri } from "@/platform/ipc";
import { call, commands, isTauri, nextRequestId } from "@/platform/ipc";
import { editorService, notifications, notifyTabTitlesChanged, toolWindowService } from "@/workbench/contributions";
import { tx } from "@/platform/i18n";
import { confirm, showError } from "@/workbench/messages";
import {
bypassDefaults,
canSend,
shellCommand,
cursorModelDefaults,
emptyDraft,
isMentioned,
@@ -87,6 +89,8 @@ export type SessionLocation = "editor" | "toolWindow";
interface AgentsState {
loaded: boolean;
/** Tasks running a `!` command from their composer. */
shellRunning: Set<string>;
/** Why the tasks could not be loaded. */
error: string | null;
tasks: Map<string, AgentTask>;
@@ -181,6 +185,7 @@ export function savedDraft(saved: Partial<Draft>): Draft {
export const useAgents = create<AgentsState>(() => ({
loaded: false,
shellRunning: new Set(),
error: null,
tasks: new Map(),
unread: new Set(),
@@ -1337,10 +1342,47 @@ function remember(text: string) {
save(HISTORY_KEY, history);
}
/** The `!` commands running per task, so Stop ends them. */
const shellRuns = new Map<string, Set<RequestId>>();
function trackShell(task: string, request: RequestId, running: boolean) {
const runs = shellRuns.get(task) ?? new Set<RequestId>();
if (running) runs.add(request);
else runs.delete(request);
if (runs.size) shellRuns.set(task, runs);
else shellRuns.delete(task);
useAgents.setState((s) => {
const shellRunning = new Set(s.shellRunning);
if (runs.size) shellRunning.add(task);
else shellRunning.delete(task);
return { shellRunning };
});
}
/** Runs a `!` line in the task's folder; its output reaches the agent with the next message. */
async function runShell(task: string, composer: ComposerDraft, command: string) {
const request = nextRequestId();
trackShell(task, request, true);
clearSubmittedComposer(task, composer, generation);
try {
await call(commands.agentShell(task, command, request));
} finally {
trackShell(task, request, false);
}
}
/** Stops the task's turn and the `!` commands it runs. */
export async function stopTask(task: string): Promise<void> {
for (const request of shellRuns.get(task) ?? []) void commands.cancelRequest(request);
if (isBusy(useAgents.getState().tasks.get(task)?.status ?? "ready")) await cancelTask(task);
}
/** 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);
if (!canSend(composer)) return;
const command = shellCommand(composer);
if (command !== null) return runShell(task, composer, command);
const started = generation;
await call(commands.agentPrompt(task, promptOf(task, composer), now));
clearSubmittedComposer(task, composer, started);
+10
Переглянути файл
@@ -28,6 +28,7 @@ import {
paste,
reformatNodes,
reloadFromDisk,
openWithAssociatedApp,
revealInFinder,
selectedFiles,
selectedNodes,
@@ -411,6 +412,15 @@ export function registerProjectActions(): () => void {
keywords: ["show in explorer", "open in finder"],
run: ({ arg }) => revealInFinder(nodesFrom(contextTarget(arg))),
},
{
id: "project.openWithAssociatedApp",
title: "Open in Associated Application",
category: "Project View",
icon: "external-link",
when: OPEN,
keywords: ["open with", "default application", "system application", "external"],
run: ({ arg }) => void openWithAssociatedApp(nodesFrom(contextTarget(arg))),
},
{
id: "project.openInTerminal",
title: "Open in Terminal",
+8 -3
Переглянути файл
@@ -1,5 +1,5 @@
import { clearContext, setContext } from "@/platform/context";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { registerActions } from "@/platform/actions";
import { useProject } from "@/platform/project";
import { useRemote } from "@/platform/remote";
@@ -9,6 +9,11 @@ import { contextMenuItems, keyLabel, revealLabel } from "./contextMenu";
import type { ProjectNode } from "./model";
import { useProjectTree } from "./store";
vi.mock("@/platform/ipc", async (importOriginal) => ({
...(await importOriginal<typeof import("@/platform/ipc")>()),
isTauri: () => true,
}));
const ROOT = "/p";
const SCRATCHES = "/config/scratches";
@@ -175,7 +180,7 @@ describe("project view context menu", () => {
"-",
"Edit File Colors…",
]);
expect(sub(items, "Open In")).toEqual([revealLabel(), "Terminal"]);
expect(sub(items, "Open In")).toEqual([revealLabel(), "Associated Application", "Terminal"]);
expect(sub(items, "Git")?.slice(0, 4)).toEqual(["Commit File…", "Add", "-", "Annotate with Git Blame"]);
});
@@ -199,7 +204,7 @@ describe("project view context menu", () => {
it("hides the OS file manager in an SSH or dev-container window, whose files are not on this desktop", () => {
const library = { ...node("/root/.m2/lib.jar"), readOnly: true };
expect(sub(contextMenuItems([library]), "Open In")).toEqual([revealLabel()]);
expect(sub(contextMenuItems([library]), "Open In")).toEqual([revealLabel(), "Associated Application"]);
for (const target of [
{ kind: "ssh", config: "box" },
{ kind: "devContainer", folder: "/Users/me/app", config: "" },
+16 -1
Переглянути файл
@@ -1,7 +1,7 @@
/** Context menu and "New" popup of the project view. */
import { executeAction, getAction } from "@/platform/actions";
import { getContext } from "@/platform/context";
import { canRevealInFileManager, fileManagerName } from "@/platform/fileManager";
import { canOpenWithSystemApp, canRevealInFileManager, fileManagerName } from "@/platform/fileManager";
import { formatBinding, hostBinding, isMacHost, shortcutLabel } from "@/platform/keymap";
import { projectFolder, relativePath, useProject } from "@/platform/project";
import { currentDetectedRoots, currentRoots } from "@/platform/projectRoots";
@@ -28,6 +28,7 @@ import {
openRenameDialog,
openSelectionInRightSplit,
paste,
openWithAssociatedApp,
reformatNodes,
reloadFromDisk,
revealInFinder,
@@ -341,6 +342,13 @@ export function contextMenuItems(nodes: ProjectNode[]): MenuItem[] {
icon: "external-link",
run: () => void revealInFinder(nodes),
},
files.length > 0 &&
canOpenWithSystemApp() && {
id: "associatedApp",
label: "Associated Application",
icon: "external-link",
run: () => void openWithAssociatedApp(files),
},
folder && getAction("terminal.openAt")
? { id: "terminal", label: "Terminal", icon: "terminal", run: () => void delegate("terminal.openAt", folder) }
: null,
@@ -502,6 +510,13 @@ function libraryMenuItems(nodes: ProjectNode[]): MenuItem[] {
icon: "external-link",
run: () => void revealInFinder(nodes),
},
nodes.every((n) => !n.dir) &&
canOpenWithSystemApp() && {
id: "associatedApp",
label: "Associated Application",
icon: "external-link",
run: () => void openWithAssociatedApp(nodes),
},
]),
single &&
!single.dir &&
+17 -1
Переглянути файл
@@ -6,7 +6,13 @@ import { writeClipboardText } from "@/platform/clipboard";
import { createElement, Fragment } from "react";
import { askUsagesDetected, fileUsages, viewUsages } from "@/editor/refactor";
import { executeAction, getAction } from "@/platform/actions";
import { canRevealInFileManager, fileManagerName, fileManagerPath, revealInFileManager } from "@/platform/fileManager";
import {
canRevealInFileManager,
fileManagerName,
fileManagerPath,
openWithSystemApp,
revealInFileManager,
} from "@/platform/fileManager";
import { maybeEditorService, notifications } from "@/workbench/contributions";
import { ask, confirmChecked } from "@/workbench/messages";
import { osClipboard } from "./clipboard";
@@ -897,6 +903,16 @@ export async function revealInFinder(nodes: ProjectNode[] = selectedNodes()) {
}
}
/** Opens each selected file with the application the OS associates with it. */
export async function openWithAssociatedApp(nodes: ProjectNode[] = selectedNodes()) {
for (const file of nodes.filter((n) => !n.dir && !n.placeholder)) {
if (!(await openWithSystemApp(file.path))) {
notifications().notify({ level: "error", title: tx`Cannot open ${nameOf(file.path)} with its application` });
return;
}
}
}
export function folderOf(node: ProjectNode | null = leadNode()): string | null {
return targetFolder(node);
}
+3 -1
Переглянути файл
@@ -1,6 +1,6 @@
import { readFileSync } from "node:fs";
import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import { executeAction } from "@/platform/actions";
import { CLEAR_COLOR, _setSchemeSource } from "@/platform/colorScheme";
import { setLocale } from "@/platform/i18n";
@@ -9,6 +9,7 @@ import { DEFAULT_SETTINGS } from "../model/schema";
import { openSettings, stage, stagedValue, useSettingsDialog } from "../model/staging";
import { PageContext } from "../components/context";
import { COLOR_SCHEME_PAGES } from "../pages/editor/colorScheme";
import { preloadBuiltinPage } from "../pages/lazyPage";
const mocks = vi.hoisted(() => ({
open: vi.fn(),
@@ -40,6 +41,7 @@ const schemePage = (id: string) => {
);
};
beforeAll(() => preloadBuiltinPage("editor.colorScheme"));
beforeEach(() => {
vi.resetAllMocks();
mocks.open.mockResolvedValue("/schemes/forest.icls");
+3 -1
Переглянути файл
@@ -1,11 +1,12 @@
import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import { DEFAULT_DEPLOYMENT_SERVER } from "@/platform/remoteSettings";
import { useProject } from "@/platform/project";
import { PageContext } from "../components/context";
import { validateSettings } from "../model/schema";
import { applySettings, openSettings, useSettingsDialog } from "../model/staging";
import { DEPLOYMENT_PAGES } from "../pages/deployment";
import { preloadBuiltinPage } from "../pages/lazyPage";
const mocks = vi.hoisted(() => ({ store: vi.fn(), saved: vi.fn(), test: vi.fn() }));
vi.mock("@/platform/ipc", async (original) => {
@@ -29,6 +30,7 @@ const savedDialog = useSettingsDialog.getState();
const savedProject = useProject.getState();
const PAGE = DEPLOYMENT_PAGES[0]!.id;
beforeAll(() => preloadBuiltinPage(PAGE));
beforeEach(() => {
vi.resetAllMocks();
mocks.store.mockResolvedValue(undefined);
+4 -1
Переглянути файл
@@ -1,15 +1,18 @@
import { act, cleanup, fireEvent, render, screen } from "@testing-library/react";
import type { ComponentType } from "react";
import { afterEach, beforeEach, expect, it } from "vitest";
import { afterEach, beforeAll, beforeEach, expect, it } from "vitest";
import { DEFAULT_DEPLOYMENT_SERVER } from "@/platform/remoteSettings";
import { useContextMenuStore } from "@/ui";
import { PageContext } from "../components/context";
import { DEFAULT_SETTINGS } from "../model/schema";
import { stagedValue, useSettingsDialog } from "../model/staging";
import { DEPLOYMENT_PAGES } from "../pages/deployment";
import { preloadBuiltinPage } from "../pages/lazyPage";
const server = (id: string, name: string) => ({ ...DEFAULT_DEPLOYMENT_SERVER, id, name });
beforeAll(() => preloadBuiltinPage("build.deployment"));
beforeEach(() => {
const base = structuredClone(DEFAULT_SETTINGS) as typeof DEFAULT_SETTINGS & { deployment: Record<string, unknown> };
base.deployment = { ...base.deployment, servers: [server("a", "Alpha"), server("b", "Beta")], defaultServer: "a" };
+98 -7
Переглянути файл
@@ -1,6 +1,17 @@
import { describe, expect, it, vi } from "vitest";
const logFrontend = vi.hoisted(() => vi.fn(() => Promise.resolve()));
const defaultInit = () => ({
launch: null,
remote: null,
project: null,
globalSettings: {},
updates: false,
});
const windowTakeSettingsInit = vi.hoisted(() => vi.fn<() => Promise<unknown>>(() => Promise.resolve(defaultInit())));
const windowTakeLaunch = vi.hoisted(() => vi.fn<() => Promise<unknown>>(() => Promise.resolve(null)));
const projectCurrent = vi.hoisted(() => vi.fn<() => Promise<unknown>>(() => Promise.resolve(null)));
const settingsGetGlobal = vi.hoisted(() => vi.fn(() => Promise.resolve({})));
vi.mock("@tauri-apps/api/webviewWindow", () => ({
getCurrentWebviewWindow: () => ({
label: "settings-main",
@@ -11,32 +22,42 @@ vi.mock("@tauri-apps/api/webviewWindow", () => ({
}));
vi.mock("@/platform/ipc", async (importOriginal) => {
const real = await importOriginal<typeof import("@/platform/ipc")>();
const ok = (data: unknown) => Promise.resolve({ status: "ok", data });
return {
...real,
isTauri: () => true,
commands: {
...real.commands,
logFrontend,
remoteCurrent: () => ok(null),
projectCurrent: () => ok(null),
settingsGetGlobal: () => ok({}),
windowTakeLaunch: () => Promise.resolve(null),
remoteCurrent: () => Promise.resolve(null),
projectCurrent,
settingsGet: () => Promise.resolve({}),
settingsGetGlobal,
windowTakeLaunch,
windowTakeSettingsInit,
},
};
});
const loadBuiltinPages = vi.hoisted(() =>
vi.fn<() => Promise<() => void>>(() => Promise.reject(new Error("page failed"))),
);
const preloadBuiltinRegistry = vi.hoisted(() => vi.fn(() => Promise.resolve()));
vi.mock("../dialog/LazySettingsDialog", () => ({
LazySettingsDialog: () => null,
loadBuiltinPages: () => Promise.reject(new Error("page failed")),
LazyProjectStructureDialog: () => null,
loadBuiltinPages,
preloadBuiltinRegistry,
unloadBuiltinPages: () => {},
}));
const { activateSettingsWindow } = await import("..");
const { useSettingsDialog } = await import("../model/staging");
const { disableRemote } = await import("@/platform/remote");
const { useProject } = await import("@/platform/project");
const { stage, useSettingsDialog } = await import("../model/staging");
describe("the native Settings window", () => {
it("opens even when a page fails to register, and logs why", async () => {
vi.spyOn(console, "error").mockImplementation(() => {});
windowTakeSettingsInit.mockResolvedValueOnce(defaultInit());
const dispose = activateSettingsWindow("main");
expect(useSettingsDialog.getState().open).toBe(true);
expect(useSettingsDialog.getState().pagesLoading).toBe(true);
@@ -48,4 +69,74 @@ describe("the native Settings window", () => {
);
dispose();
});
it("hydrates from windowTakeSettingsInit without blocking on SSH and rebases base while keeping staged edits", async () => {
loadBuiltinPages.mockClear().mockResolvedValue(() => {});
settingsGetGlobal.mockClear();
windowTakeLaunch.mockClear().mockResolvedValueOnce(null);
let resolveRemoteRefresh!: (v: unknown) => void;
projectCurrent.mockReturnValueOnce(new Promise((r) => (resolveRemoteRefresh = r)));
windowTakeSettingsInit.mockResolvedValueOnce({
launch: { settingsPage: "keymap", newProjects: false },
remote: {
target: { type: "ssh", config: "devbox" },
root: "/home/dev/repo",
host: "devbox",
os: "linux",
commands: ["project_current"],
},
project: null,
globalSettings: { appearance: { theme: "dark" }, editor: { tabSize: 4 } },
updates: true,
});
const dispose = activateSettingsWindow("main");
// Unblocks pagesLoading immediately from local client settings while SSH projectCurrent is still pending.
await vi.waitFor(() => expect(useSettingsDialog.getState().pagesLoading).toBe(false));
await vi.waitFor(() => expect(windowTakeLaunch).toHaveBeenCalledTimes(1));
expect(loadBuiltinPages).toHaveBeenCalledTimes(1);
expect(loadBuiltinPages).toHaveBeenCalledWith({ pageId: "keymap", updates: true });
expect(useSettingsDialog.getState().pageId).toBe("keymap");
expect(useSettingsDialog.getState().base.appearance.theme).toBe("dark");
expect(useSettingsDialog.getState().globalBase.editor.tabSize).toBe(4);
expect(settingsGetGlobal).not.toHaveBeenCalled();
// Even if the user stages an edit before SSH returns, remote `base` updates while `staged` stays intact.
stage("editor.codeStyle.other", "project", "editor.tabSize", 8);
resolveRemoteRefresh({
root: "/home/dev/repo",
name: "repo",
displayName: "repo",
trusted: true,
isGit: true,
settings: { editor: { tabSize: 6 }, appearance: { theme: "dark" } },
});
await vi.waitFor(() => expect(useSettingsDialog.getState().base.editor.tabSize).toBe(6));
expect(useProject.getState().project?.root).toBe("/home/dev/repo");
expect(useSettingsDialog.getState().staged["project|editor.tabSize"]?.value).toBe(8);
disableRemote();
useProject.setState({ project: null, settings: null });
dispose();
});
it("picks up a launch queued between windowTakeSettingsInit and listen()", async () => {
loadBuiltinPages.mockResolvedValue(() => {});
windowTakeLaunch.mockResolvedValueOnce({ settingsPage: "appearance", newProjects: true });
windowTakeSettingsInit.mockResolvedValueOnce({
launch: { settingsPage: "keymap", newProjects: false },
remote: null,
project: null,
globalSettings: {},
updates: false,
});
const dispose = activateSettingsWindow("main");
await vi.waitFor(() => expect(useSettingsDialog.getState().pagesLoading).toBe(false));
await vi.waitFor(() => expect(useSettingsDialog.getState().newProjects).toBe(true));
expect(useSettingsDialog.getState().pageId).toBe("appearance");
useProject.setState({ project: null, settings: null });
dispose();
});
});
+3 -1
Переглянути файл
@@ -1,12 +1,13 @@
import { act, cleanup, fireEvent, render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import { DEFAULT_SSH_CONFIG, type SshAuthValid } from "@/platform/remoteSettings";
import { useProject } from "@/platform/project";
import { PageContext } from "../components/context";
import { validateSettings } from "../model/schema";
import { applySettings, closeSettings, openSettings, resetPage, useSettingsDialog } from "../model/staging";
import { SettingsFooter } from "../dialog/SettingsDialog";
import { preloadBuiltinPage } from "../pages/lazyPage";
import { SSH_PAGES } from "../pages/ssh";
const mocks = vi.hoisted(() => ({ store: vi.fn(), test: vi.fn(), needsSecret: vi.fn(), trust: vi.fn() }));
@@ -32,6 +33,7 @@ const savedDialog = useSettingsDialog.getState();
const savedProject = useProject.getState();
let typed: string;
beforeAll(() => preloadBuiltinPage("tools.sshConfigurations"));
beforeEach(() => {
vi.resetAllMocks();
typed = crypto.randomUUID();
+1 -1
Переглянути файл
@@ -4,7 +4,7 @@ import { nativeToAsciiAction } from "./nativeToAscii";
/** Java's page first: JDK, Maven and the language server are what new projects most often need. */
export const NEW_PROJECTS_PAGE = "languages.java";
export function settingsActions(open: (page?: string, newProjects?: boolean) => void): Action[] {
export function settingsActions(open: (page?: string, newProjects?: boolean) => void | Promise<void>): Action[] {
return [
nativeToAsciiAction(),
{
+15 -4
Переглянути файл
@@ -4,13 +4,24 @@
* window rarely needs them.
*/
import { lazyComponent } from "@/ui";
import { useSettingsDialog } from "../model/staging";
import { DEFAULT_PAGE, splitPageTarget, useSettingsDialog } from "../model/staging";
let registry: Promise<typeof import("../pages/registry")> | null = null;
let pages: Promise<() => void> | null = null;
/** Registers the built-in pages once; resolves with their disposer. */
export function loadBuiltinPages(): Promise<() => void> {
return (pages ??= import("../pages/registry").then((m) => m.registerBuiltinPages()));
/** Pre-fetches the built-in page registry chunk without registering pages yet. */
export function preloadBuiltinRegistry(): Promise<unknown> {
return (registry ??= import("../pages/registry"));
}
/** Registers the built-in pages once and preloads `pageId`'s body; resolves with their disposer. */
export async function loadBuiltinPages(opts: { pageId?: string; updates?: boolean } = {}): Promise<() => void> {
const mod = await (registry ??= import("../pages/registry"));
const dispose = await (pages ??= Promise.resolve(mod.registerBuiltinPages({ updates: opts.updates })));
const target = opts.pageId ? splitPageTarget(opts.pageId).pageId : DEFAULT_PAGE;
const preload = mod.preloadBuiltinPage(target);
if (preload) await preload;
return dispose;
}
/** Drops the pages registered by `loadBuiltinPages` (feature deactivation). */
+4 -3
Переглянути файл
@@ -18,7 +18,7 @@ import { lazyWhen } from "@/ui";
import { useProject } from "@/platform/project";
import { provideSettingsSearchIndex, registerOverlay } from "@/workbench/contributions";
import { windowBackgroundHex } from "@/workbench/theme";
import { settingsActions } from "./actions";
import { NEW_PROJECTS_PAGE, settingsActions } from "./actions";
import {
LazyProjectStructureDialog,
LazySettingsDialog,
@@ -57,7 +57,8 @@ async function showSettings(page?: string, newProjects = false) {
console.warn("settings window unavailable, using the dialog", e);
}
}
await loadBuiltinPages();
const targetPage = page ?? (newProjects ? NEW_PROJECTS_PAGE : useSettingsDialog.getState().pageId);
await loadBuiltinPages({ pageId: targetPage });
// Like a launch into the open window: go to the page, keep the edits not applied yet.
if (useSettingsDialog.getState().open) relaunchSettings({ page, newProjects });
else openSettings(page, { newProjects });
@@ -87,7 +88,7 @@ export function activate(): () => void {
...appearanceToggleActions(),
presentationAssistantAction(),
...navigationBarActions(),
...settingsActions((page, newProjects) => void showSettings(page, newProjects)),
...settingsActions((page, newProjects) => showSettings(page, newProjects)),
{
id: "file.projectStructure",
title: "Project Structure…",
+4 -8
Переглянути файл
@@ -8,8 +8,8 @@
*/
import { useMemo, useRef, useState, type MouseEvent } from "react";
import clsx from "clsx";
import { useActions, allActions, type Action } from "@/platform/actions";
import { defaultPreset, formatBinding, type Keymap, PRESET_TITLES, PRESETS, useKeymap } from "@/platform/keymap";
import { allActions, useActions, type Action } from "@/platform/actions";
import { defaultPreset, formatBinding, type Keymap, PRESET_TITLES, PRESETS } from "@/platform/keymap";
import { call, commands } from "@/platform/ipc";
import { notifications } from "@/workbench/contributions";
import { ask, confirm, showError } from "@/workbench/messages";
@@ -40,6 +40,7 @@ import {
isModified,
isKeymapAction,
keymapName,
keymapSearchLabels,
removeBinding,
removeConflicts,
renameKeymap,
@@ -65,12 +66,7 @@ type KNode =
type GroupNode = Extract<KNode, { kind: "group" }>;
export function keymapSearchLabels(): string[] {
const draft = useKeymap.getState();
return allActions()
.filter((a) => isKeymapAction(a, draft))
.map((a) => a.title);
}
export { keymapSearchLabels };
const groupKey = (path: readonly string[]) => `grp:${path.join("/")}`;
+9 -1
Переглянути файл
@@ -3,7 +3,7 @@
* (plugins' default shortcuts count as the preset's), add / remove / reset,
* conflict detection with `when` overlap, and shortcut search.
*/
import type { Action } from "@/platform/actions";
import { allActions, type Action } from "@/platform/actions";
import { evaluateWhen, type ContextKeys } from "@/platform/context";
import {
customKeymapId,
@@ -12,6 +12,7 @@ import {
presetBindings,
PRESET_TITLES,
PRESETS,
useKeymap,
withBindings,
type Keymap,
type KeymapDraft,
@@ -19,6 +20,13 @@ import {
export { presetBindings, withBindings, type KeymapDraft };
export function keymapSearchLabels(): string[] {
const draft = useKeymap.getState();
return allActions()
.filter((a) => isKeymapAction(a, draft))
.map((a) => a.title);
}
export function resolveBindings(draft: KeymapDraft, id: string): string[] {
return draft.overrides[id]?.map(normalizeBinding) ?? presetBindings(draft.preset, id);
}
+6 -6
Переглянути файл
@@ -109,7 +109,7 @@ export function splitPageTarget(target: string): { pageId: string; focus: string
return i < 0 ? { pageId: target, focus: null } : { pageId: target.slice(0, i), focus: target.slice(i + 1) || null };
}
export function openSettings(pageId?: string, opts: { newProjects?: boolean } = {}) {
export function openSettings(pageId?: string, opts: { newProjects?: boolean; globalBase?: ValidSettings } = {}) {
const s = useSettingsDialog.getState();
const base = validateSettings(useProject.getState().settings);
const target = pageId ? splitPageTarget(pageId) : { pageId: s.pageId, focus: null };
@@ -120,7 +120,7 @@ export function openSettings(pageId?: string, opts: { newProjects?: boolean } =
focus: target.focus,
query: "",
base,
globalBase: base,
globalBase: opts.globalBase ?? base,
newProjects: opts.newProjects ?? false,
staged: {},
stagedSecrets: {},
@@ -129,7 +129,7 @@ export function openSettings(pageId?: string, opts: { newProjects?: boolean } =
saving: false,
error: null,
});
void loadGlobalBase();
if (!opts.globalBase) void loadGlobalBase();
}
export function openProjectStructure(section?: string) {
@@ -182,10 +182,10 @@ async function loadGlobalBase() {
}
}
export function rebaseSettings() {
export function rebaseSettings(globalBase?: ValidSettings) {
const base = validateSettings(useProject.getState().settings);
useSettingsDialog.setState((s) => (s.open || s.projectStructureOpen ? { base, globalBase: base } : {}));
void loadGlobalBase();
useSettingsDialog.setState((s) => (s.open || s.projectStructureOpen ? { base, globalBase: globalBase ?? base } : {}));
if (!globalBase) void loadGlobalBase();
}
/** IDEA's File › New Projects Setup › Settings for New Projects. */
+2 -90
Переглянути файл
@@ -50,8 +50,6 @@ import {
updateMapping,
} from "./deploymentModel";
import { choosePath } from "@/platform/choosePath";
import { BUILD_GROUP } from "./execution";
import type { PageSpec } from "./spec";
import { parseSshPort, sshTestRemedy } from "./sshConnection";
import { PageLink } from "./workflowControls";
import workflow from "./Workflow.module.css";
@@ -733,7 +731,7 @@ function GroupPanel({
type Selection = { kind: "server" | "group"; id: string } | null;
function DeploymentServersEditor() {
export function DeploymentServersEditor() {
const tx = useTx();
const [servers, setServers] = useSetting<DeploymentServerValid[]>("deployment.servers");
const [groups, setGroups] = useSetting<DeploymentGroupValid[]>("deployment.groups");
@@ -955,7 +953,7 @@ function DeploymentServersEditor() {
// ---------------------------------------------------------------------------
// Options
function ExcludeNamesRow() {
export function ExcludeNamesRow() {
const [names, setNames] = useSetting<string[]>("deployment.exclude");
const [draft, setDraft] = useState<string | null>(null);
const id = useId();
@@ -979,89 +977,3 @@ function ExcludeNamesRow() {
</Row>
);
}
export const DEPLOYMENT_PAGES: PageSpec[] = [
{
id: "build.deployment",
title: "Deployment",
group: BUILD_GROUP,
order: 365,
projectScope: true,
defaultScope: "project",
keywords: [
"local",
"mounted",
"sftp",
"ftp",
"ftps",
"ssh",
"server",
"upload",
"remote host",
"mappings",
"web server",
"deploy",
],
sections: [
{
options: [
{
kind: "custom",
label: "Deployment servers",
keywords: [
"Connection",
"Mappings",
"Excluded Paths",
"Root path",
"Web server URL",
"SSH configuration",
"FTP",
"Passive mode",
"Password",
"Save password",
"Test Connection",
"Use as Default",
"Server Group",
"Local path",
"Deployment path",
"Web path",
],
component: DeploymentServersEditor,
},
],
},
],
},
{
id: "build.deployment.options",
title: "Options",
order: 0,
projectScope: true,
defaultScope: "project",
keywords: ["deployment", "upload", "exclude", "timestamps", "automatic upload", "sftp"],
sections: [
{
options: [
{
kind: "custom",
label: "Exclude items by name",
keywords: ["exclude"],
component: ExcludeNamesRow,
},
{
kind: "select",
key: "deployment.autoUpload",
label: "Upload changed files automatically to the default server",
options: [
{ value: "never", label: "Never" },
{ value: "onExplicitSave", label: "On explicit save action" },
{ value: "always", label: "Always" },
],
},
{ kind: "toggle", key: "deployment.deleteRemote", label: "Delete remote files when local are deleted" },
{ kind: "toggle", key: "deployment.preserveTimestamps", label: "Preserve files timestamps" },
],
},
],
},
];
+2 -56
Переглянути файл
@@ -19,20 +19,10 @@ import { Button, Checkbox, Dialog, Icon, IconButton, Input, T, type SelectOption
import { Row, Section, Select } from "../components/Form";
import { useSetting } from "../components/context";
import { SshConfigSelect, useSshConfigs } from "../components/SshConfigSelect";
import { BUILD_GROUP } from "./execution";
import type { PageSpec } from "./spec";
import { parentPath, splitList } from "./runTargetsPaths";
import styles from "./Workflow.module.css";
import own from "./RunTargets.module.css";
/** Parent of a remote path (`~/a` → `~`, `/a` → `/`); null at the top. */
export function parentPath(path: string): string | null {
const p = path.length > 1 ? path.replace(/\/+$/, "") : path;
if (p === "/" || p === "~" || p === "") return null;
const i = p.lastIndexOf("/");
if (i < 0) return null;
return i === 0 ? "/" : p.slice(0, i);
}
const UNKNOWN_HOST = /^Unknown SSH host key/;
const NEEDS_SECRET = /^SSH (password|key passphrase) required|passphrase required|^cannot decrypt SSH key/;
@@ -259,13 +249,6 @@ function ProjectFolderField({ target, onChange }: { target: RunTargetValid; onCh
);
}
/** Settings typed as lists of words (`8000:8000 5678:5678`, `a.yaml; b.yaml`). */
export const splitList = (text: string): string[] =>
text
.split(/[\s,;]+/)
.map((s) => s.trim())
.filter(Boolean);
function ListField({
label,
value,
@@ -414,7 +397,7 @@ function ContainerFields({ target, update }: { target: RunTargetValid; update: (
);
}
function RunTargetsEditor() {
export function RunTargetsEditor() {
const plugins = usePluginRunTargets((s) => s.targets);
const [defaultTarget, setDefaultTarget] = useSetting<string>("run.defaultTarget");
const [raw, setTargets] = useSetting<RunTargetValid[] | undefined>("runTargets");
@@ -593,40 +576,3 @@ function RunTargetsEditor() {
</div>
);
}
export const RUN_TARGET_PAGES: PageSpec[] = [
{
id: "build.runTargets",
title: "Run Targets",
group: BUILD_GROUP,
order: 364,
projectScope: true,
keywords: ["ssh", "remote", "target", "run on", "interpreter", "upload", "sync", "docker", "compose", "container"],
sections: [
{
options: [
{
kind: "custom",
label: "Run Targets",
keywords: [
"SSH configuration",
"Project folder on target",
"Upload changed project files before each run",
"Python interpreter",
"Node.js interpreter",
"Java executable",
"Docker connection",
"Image",
"Compose files",
"Service",
"Container folder",
"Published ports",
"Run options",
],
component: RunTargetsEditor,
},
],
},
],
},
];
+2 -49
Переглянути файл
@@ -10,8 +10,6 @@ import { BUILTIN_SCOPES, scopeError, validateScopes, type NamedScope } from "@/p
import { IconButton, Input, T, type SelectOption } from "@/ui";
import { ColorSwatches, Row, Section, Select } from "../components/Form";
import { useSetting } from "../components/context";
import { APPEARANCE_GROUP } from "./behavior";
import type { PageSpec } from "./spec";
import styles from "./Workflow.module.css";
import own from "./Scopes.module.css";
@@ -73,7 +71,7 @@ function errorText(error: { message: string; at: number }): string {
return tx`${message} at column ${column}`;
}
function ScopesEditor() {
export function ScopesEditor() {
const [raw, setRaw] = useSetting<unknown>("scopes");
const scopes = validateScopes(raw);
const [selected, setSelected] = useState(0);
@@ -182,7 +180,7 @@ const COLOR_LABELS: Record<string, string> = {
const colorLabel = (color: string) => COLOR_LABELS[color.toLowerCase()] ?? color;
function FileColorsEditor() {
export function FileColorsEditor() {
const [raw, setRaw] = useSetting<unknown>("fileColors");
const [rawScopes] = useSetting<unknown>("scopes");
const settings = validateFileColors(raw);
@@ -266,48 +264,3 @@ function FileColorsEditor() {
</div>
);
}
export const SCOPE_PAGES: PageSpec[] = [
{
id: "fileColors",
title: "File Colors",
group: APPEARANCE_GROUP,
order: 1.5,
projectScope: true,
defaultScope: "project",
keywords: ["colour", "color", "tab", "background", "tests", "non-project"],
sections: [
{
options: [
{ kind: "toggle", key: "fileColors.enabled", label: "Enable file colors" },
{ kind: "toggle", key: "fileColors.editorTabs", label: "Use in editor tabs" },
{ kind: "toggle", key: "fileColors.projectView", label: "Use in project view" },
],
},
{
options: [
{
kind: "custom",
label: "File Colors",
keywords: ["Scope", "Color", "Custom", "Hex value"],
component: FileColorsEditor,
},
],
},
],
},
{
id: "scopes",
title: "Scopes",
group: APPEARANCE_GROUP,
order: 1.6,
projectScope: true,
defaultScope: "project",
keywords: ["scope", "file set", "pattern"],
sections: [
{
options: [{ kind: "custom", label: "Scopes", keywords: ["Name", "Pattern"], component: ScopesEditor }],
},
],
},
];
+1 -37
Переглянути файл
@@ -17,9 +17,7 @@ import { Button, Checkbox, IconButton, Input, type SelectOption, T } from "@/ui"
import { Row, Section, Select } from "../components/Form";
import { useSetting } from "../components/context";
import { stageSshSecret, useSettingsDialog } from "../model/staging";
import type { PageSpec } from "./spec";
import { parseSshPort, sshTestRemedy, type SshTestRemedy } from "./sshConnection";
import { TOOLS_GROUP } from "./tools";
import styles from "./Workflow.module.css";
const AUTH: Array<SelectOption<SshAuthValid>> = [
@@ -284,7 +282,7 @@ function SshConfigForm({
);
}
function SshConfigsEditor() {
export function SshConfigsEditor() {
const [stored, setConfigs] = useSetting<SshConfigValid[] | undefined>("ssh.configs", "global");
const configs = stored ?? [];
const [selected, setSelected] = useState<string | null>(configs[0]?.id ?? null);
@@ -360,37 +358,3 @@ function SshConfigsEditor() {
</div>
);
}
export const SSH_PAGES: PageSpec[] = [
{
id: "tools.sshConfigurations",
title: "SSH Configurations",
group: TOOLS_GROUP,
order: 603,
keywords: ["ssh", "remote", "host", "server", "key pair", "private key", "password", "known_hosts", "agent"],
sections: [
{
options: [
{
kind: "custom",
label: "SSH Configurations",
keywords: [
"Host",
"Port",
"User name",
"Authentication type",
"Private key file",
"Password",
"Passphrase",
"Save password",
"Save passphrase",
"Test Connection",
"OpenSSH config and authentication agent",
],
component: SshConfigsEditor,
},
],
},
],
},
];
+1 -44
Переглянути файл
@@ -5,9 +5,8 @@ import { call, commands, onIdeEvent, type UpdateStatus } from "@/platform/ipc";
import { useTx } from "@/platform/i18n";
import { Button, T } from "@/ui";
import { Row } from "../components/Form";
import type { PageSpec } from "./spec";
function UpdateStatusRows() {
export function UpdateStatusRows() {
const tx = useTx();
const [version, setVersion] = useState<string | null>(null);
const [status, setStatus] = useState<UpdateStatus | null>(null);
@@ -49,45 +48,3 @@ function UpdateStatusRows() {
</>
);
}
export const UPDATES_PAGE: PageSpec = {
id: "general.updates",
title: "Updates",
order: 3,
keywords: ["update", "upgrade", "version", "automatic", "GitHub", "CNB"],
sections: [
{
options: [
{
kind: "custom",
label: "Current version",
keywords: ["Last checked", "Check Now"],
component: UpdateStatusRows,
},
{
kind: "toggle",
key: "general.autoCheckUpdates",
label: "Check for updates automatically",
hint: "At startup and every 4 hours while OpenIDEA runs. Each new version is announced once per session.",
},
{
kind: "toggle",
key: "general.showWhatsNewAfterUpdate",
label: "Show What's New after an update",
hint: "Opens a page with the release notes when a new version starts. Help › What's New opens it any time.",
},
{
kind: "select",
key: "general.updateSource",
label: "Update source",
hint: "Where updates are downloaded from. If it can't be reached, the other source is tried.",
options: [
{ value: "auto", label: "Automatic" },
{ value: "github", label: "GitHub" },
{ value: "cnb", label: "CNB (China mirror)" },
],
},
],
},
],
};
+8 -2
Переглянути файл
@@ -1,11 +1,17 @@
/** Built-in settings pages (IDEA layout: Appearance & Behavior, Keymap, Editor). */
import { GlobListEditor, Row } from "../components/Form";
import { useSetting } from "../components/context";
import { KeymapPage, keymapSearchLabels } from "../keymap/KeymapPage";
import { AssociatedApplicationsRow, RecognizedFileTypes } from "./FileTypes";
import { keymapSearchLabels } from "../keymap/model";
import { lazyPage } from "./lazyPage";
import type { PageSpec } from "./spec";
export const EDITOR_GROUP = "Editor";
const KeymapPage = lazyPage("keymap", () => import("../keymap/KeymapPage").then((m) => m.KeymapPage));
const RecognizedFileTypes = lazyPage("editor.files", () => import("./FileTypes").then((m) => m.RecognizedFileTypes));
const AssociatedApplicationsRow = lazyPage("editor.files", () =>
import("./FileTypes").then((m) => m.AssociatedApplicationsRow),
);
function ExcludeRow() {
const [exclude, setExclude] = useSetting<string[]>("files.exclude");
return (
+96
Переглянути файл
@@ -0,0 +1,96 @@
import { BUILD_GROUP } from "./execution";
import { lazyPage } from "./lazyPage";
import type { PageSpec } from "./spec";
const DeploymentServersEditor = lazyPage("build.deployment", () =>
import("./DeploymentBody").then((m) => m.DeploymentServersEditor),
);
const ExcludeNamesRow = lazyPage("build.deployment.options", () =>
import("./DeploymentBody").then((m) => m.ExcludeNamesRow),
);
export const DEPLOYMENT_PAGES: PageSpec[] = [
{
id: "build.deployment",
title: "Deployment",
group: BUILD_GROUP,
order: 365,
projectScope: true,
defaultScope: "project",
keywords: [
"local",
"mounted",
"sftp",
"ftp",
"ftps",
"ssh",
"server",
"upload",
"remote host",
"mappings",
"web server",
"deploy",
],
sections: [
{
options: [
{
kind: "custom",
label: "Deployment servers",
keywords: [
"Connection",
"Mappings",
"Excluded Paths",
"Root path",
"Web server URL",
"SSH configuration",
"FTP",
"Passive mode",
"Password",
"Save password",
"Test Connection",
"Use as Default",
"Server Group",
"Local path",
"Deployment path",
"Web path",
],
component: DeploymentServersEditor,
},
],
},
],
},
{
id: "build.deployment.options",
title: "Options",
order: 0,
projectScope: true,
defaultScope: "project",
keywords: ["deployment", "upload", "exclude", "timestamps", "automatic upload", "sftp"],
sections: [
{
options: [
{
kind: "custom",
label: "Exclude items by name",
keywords: ["exclude"],
component: ExcludeNamesRow,
},
{
kind: "select",
key: "deployment.autoUpload",
label: "Upload changed files automatically to the default server",
options: [
{ value: "never", label: "Never" },
{ value: "onExplicitSave", label: "On explicit save action" },
{ value: "always", label: "Always" },
],
},
{ kind: "toggle", key: "deployment.deleteRemote", label: "Delete remote files when local are deleted" },
{ kind: "toggle", key: "deployment.preserveTimestamps", label: "Preserve files timestamps" },
],
},
],
},
];
File diff suppressed because it is too large. Load diff
@@ -7,7 +7,6 @@
*/
import { useEffect, useId, useMemo, useRef, useState, type MouseEvent } from "react";
import clsx from "clsx";
import { commands, isTauri } from "@/platform/ipc";
import {
BUILTIN_INSPECTIONS,
copyProfileName,
@@ -44,10 +43,8 @@ import {
import { useSetting } from "../../components/context";
import { useSettingsDialog } from "../../model/staging";
import { useProject } from "@/platform/project";
import type { PageSpec } from "../spec";
import {
AS_REPORTED,
INSPECTION_KEYWORDS,
LEVEL_OPTIONS,
buildInspectionTree,
checkState,
@@ -62,29 +59,20 @@ import {
setLevel,
withProfileOverrides,
type InspectionNode,
cachedInspectionLanguages,
loadInspectionLanguages,
type LanguageServers,
} from "./inspectionsModel";
import styles from "./Inspections.module.css";
import { tx } from "@/platform/i18n";
import { onLanguageListChanged, useLanguageListVersion } from "@/platform/languageList";
let languagesCache: LanguageServers[] | null = null;
onLanguageListChanged(() => (languagesCache = null));
async function loadLanguages(): Promise<LanguageServers[]> {
if (languagesCache) return languagesCache;
if (!isTauri()) return [];
const list = await commands.languages();
languagesCache = list.map((l) => ({ name: l.name, servers: l.languageServers ?? [] }));
return languagesCache;
}
import { useLanguageListVersion } from "@/platform/languageList";
function useLanguages(): LanguageServers[] {
const [langs, setLangs] = useState<LanguageServers[]>(() => languagesCache ?? []);
const [langs, setLangs] = useState<LanguageServers[]>(() => cachedInspectionLanguages());
const version = useLanguageListVersion((s) => s.version);
useEffect(() => {
let alive = true;
void loadLanguages().then(
void loadInspectionLanguages().then(
(l) => alive && setLangs(l),
() => {},
);
@@ -103,7 +91,7 @@ function expandableKeys(nodes: readonly InspectionNode[], out = new Set<string>(
return out;
}
function InspectionsPage() {
export function InspectionsPage() {
const hasProject = useProject((s) => !!s.project);
const newProjects = useSettingsDialog((s) => s.newProjects);
const projectAvailable = hasProject && !newProjects;
@@ -510,13 +498,3 @@ function InspectionOptions({
</fieldset>
);
}
export const INSPECTIONS_PAGE: PageSpec = {
id: "editor.inspections",
title: "Inspections",
group: "Editor",
order: 25,
keywords: INSPECTION_KEYWORDS,
component: InspectionsPage,
dynamicLabels: () => (languagesCache ?? []).flatMap((l) => [l.name, ...l.servers]),
};
File diff suppressed because it is too large. Load diff
+19
Переглянути файл
@@ -0,0 +1,19 @@
import { ATTRIBUTES } from "@/platform/colorScheme";
export const LANGUAGES = [...new Set(ATTRIBUTES.map((a) => a.path[0]!))].filter(
(s) => !["General", "Debugger", "Language Defaults", "Console Colors", "Git"].includes(s),
);
/** A sub-page id: `C#` → `csharp`, `Console Colors` → `console-colors` (`#` would end a settings link). */
export const languagePageId = (language: string) =>
`editor.colorScheme.${language.toLowerCase().replace(/#/g, "sharp").replace(/\s+/g, "-")}`;
/** Sub-pages linked from the Color Scheme landing page, in sidebar order. */
export const SCHEME_SUBPAGES = [
{ id: "editor.colorScheme.general", title: "General" },
{ id: "editor.colorScheme.language-defaults", title: "Language Defaults" },
{ id: "editor.colorScheme.debugger", title: "Debugger" },
{ id: "editor.colorScheme.console-colors", title: "Console Colors" },
{ id: "editor.colorScheme.git", title: "Git" },
...LANGUAGES.map((l) => ({ id: languagePageId(l), title: l })),
];
+1 -1
Переглянути файл
@@ -1,8 +1,8 @@
/** Settings › Editor pages (General and sub-pages, Code Editing, Font, Color Scheme, Code Style, Inspections, Natural Languages › Spelling, File Encodings, Inlay Hints). */
import type { PageSpec } from "../spec";
import { COLOR_SCHEME_PAGES } from "./colorScheme";
import { GENERAL_PAGES } from "./general";
import { FONT_PAGE } from "./font";
import { COLOR_SCHEME_PAGES } from "./colorScheme";
import { CODE_STYLE_PAGES } from "./codeStyle";
import { INSPECTIONS_PAGE } from "./inspections";
import { NATURAL_LANGUAGES_PAGE, SPELLING_PAGE } from "./spelling";
+17
Переглянути файл
@@ -0,0 +1,17 @@
import { lazyPage } from "../lazyPage";
import type { PageSpec } from "../spec";
import { INSPECTION_KEYWORDS, cachedInspectionLanguages } from "./inspectionsModel";
const InspectionsPage = lazyPage("editor.inspections", () =>
import("./InspectionsBody").then((m) => m.InspectionsPage),
);
export const INSPECTIONS_PAGE: PageSpec = {
id: "editor.inspections",
title: "Inspections",
group: "Editor",
order: 25,
keywords: INSPECTION_KEYWORDS,
component: InspectionsPage,
dynamicLabels: () => cachedInspectionLanguages().flatMap((l) => [l.name, ...l.servers]),
};
+17
Переглянути файл
@@ -1,3 +1,5 @@
import { commands, isTauri } from "@/platform/ipc";
import { onLanguageListChanged } from "@/platform/languageList";
/**
* Editor › Inspections tree: language → language server → diagnostic codes
* seen, plugins' problems under Plugins, plus the built-in checks; enabled /
@@ -308,3 +310,18 @@ function codeDescription(server: string, { code, source, sample }: SeenCode): st
: tx`${server} problems with code ${code}.`;
return sample ? tx`${what}\n\nExample: ${sample}` : what;
}
let languagesCache: LanguageServers[] | null = null;
onLanguageListChanged(() => (languagesCache = null));
export function cachedInspectionLanguages(): LanguageServers[] {
return languagesCache ?? [];
}
export async function loadInspectionLanguages(): Promise<LanguageServers[]> {
if (languagesCache) return languagesCache;
if (!isTauri()) return [];
const list = await commands.languages();
languagesCache = list.map((l) => ({ name: l.name, servers: l.languageServers ?? [] }));
return languagesCache;
}
+5 -2
Переглянути файл
@@ -3,17 +3,20 @@
* Stepping), Python Debugger and Run/Debug. Consumed by the run and debugger
* features (and `ide-run` for encoding / termination timeout).
*/
import { CMakeProfiles } from "./cmake";
import { WORKFLOW_LIMITS } from "@/platform/workflowSettings";
import type { SelectOption } from "@/ui";
import { ColorSwatches, FormGroup, GlobListEditor, NumberInput, Row, Toggle } from "../components/Form";
import { GradlePage, MavenPage } from "../languages/LanguagePages";
import { useSetting } from "../components/context";
import { lazyPage } from "./lazyPage";
import type { PageSpec } from "./spec";
import { Indented, ToggleNumber } from "./workflowControls";
import styles from "./Workflow.module.css";
import { T } from "@/ui";
const CMakeProfiles = lazyPage("build.cmake", () => import("./cmake").then((m) => m.CMakeProfiles));
const GradlePage = lazyPage("build.gradle", () => import("../languages/LanguagePages").then((m) => m.GradlePage));
const MavenPage = lazyPage("build.maven", () => import("../languages/LanguagePages").then((m) => m.MavenPage));
export const BUILD_GROUP = "Build, Execution, Deployment";
const L = WORKFLOW_LIMITS;
+31 -17
Переглянути файл
@@ -3,25 +3,39 @@
* Languages & Frameworks › Go / Java / Markdown / Node.js / PHP / Rust / TypeScript / Zig. Pages live in
* `../languages/`; settings are `languages.*` / `projectStructure.*`.
*/
import {
GoPage,
JavaPage,
NodePage,
PhpPage,
RubyPage,
RustPage,
TypeScriptPage,
ZigPage,
} from "../languages/LanguagePages";
import { MarkdownPage } from "../languages/MarkdownPage";
import { OxfmtPage, PrettierPage, RuffPage } from "../languages/FormatterPage";
import { PythonInterpreterPage } from "../languages/PythonInterpreterPage";
import { PythonInterpretersPage } from "../languages/PythonInterpretersPage";
import { DocstringsPage } from "../languages/DocstringsPage";
import { GoBuildTagsPage, GO_BUILD_TAG_SECTIONS } from "../languages/GoBuildTags";
import { GoModulesPage, GO_MODULE_SECTIONS } from "../languages/GoModules";
import { GO_BUILD_TAG_SECTIONS, GoBuildTagsPage } from "../languages/GoBuildTags";
import { GO_MODULE_SECTIONS, GoModulesPage } from "../languages/GoModules";
import { lazyPage } from "./lazyPage";
import type { PageSpec } from "./spec";
const PythonInterpreterPage = lazyPage("python.interpreter", () =>
import("../languages/PythonInterpreterPage").then((m) => m.PythonInterpreterPage),
);
const PythonInterpretersPage = lazyPage("python.interpreters", () =>
import("../languages/PythonInterpretersPage").then((m) => m.PythonInterpretersPage),
);
const GoPage = lazyPage("languages.go", () => import("../languages/LanguagePages").then((m) => m.GoPage));
const JavaPage = lazyPage("languages.java", () => import("../languages/LanguagePages").then((m) => m.JavaPage));
const NodePage = lazyPage("languages.node", () => import("../languages/LanguagePages").then((m) => m.NodePage));
const MarkdownPage = lazyPage("languages.markdown", () =>
import("../languages/MarkdownPage").then((m) => m.MarkdownPage),
);
const PrettierPage = lazyPage("languages.prettier", () =>
import("../languages/FormatterPage").then((m) => m.PrettierPage),
);
const OxfmtPage = lazyPage("languages.oxfmt", () => import("../languages/FormatterPage").then((m) => m.OxfmtPage));
const DocstringsPage = lazyPage("python.docstrings", () =>
import("../languages/DocstringsPage").then((m) => m.DocstringsPage),
);
const RuffPage = lazyPage("python.ruff", () => import("../languages/FormatterPage").then((m) => m.RuffPage));
const PhpPage = lazyPage("languages.php", () => import("../languages/LanguagePages").then((m) => m.PhpPage));
const RubyPage = lazyPage("languages.ruby", () => import("../languages/LanguagePages").then((m) => m.RubyPage));
const RustPage = lazyPage("languages.rust", () => import("../languages/LanguagePages").then((m) => m.RustPage));
const TypeScriptPage = lazyPage("languages.typescript", () =>
import("../languages/LanguagePages").then((m) => m.TypeScriptPage),
);
const ZigPage = lazyPage("languages.zig", () => import("../languages/LanguagePages").then((m) => m.ZigPage));
export const LANGUAGES_GROUP = "Languages & Frameworks";
export const LANGUAGE_PAGES: PageSpec[] = [
+29
Переглянути файл
@@ -0,0 +1,29 @@
import type { ComponentType } from "react";
import { lazyComponent, type LazyComponent } from "@/ui";
const preloaders = new Map<string, Array<() => Promise<unknown>>>();
/**
* Registers a built-in page component via `lazyComponent` and indexes its
* preloader under `pageIds` so `preloadBuiltinPage` can warm it ahead of mount.
*/
export function lazyPage<P extends object = Record<string, never>>(
pageIds: string | readonly string[],
load: () => Promise<ComponentType<P>>,
): LazyComponent<P> {
const Component = lazyComponent(load);
const ids = typeof pageIds === "string" ? [pageIds] : pageIds;
for (const id of ids) {
const list = preloaders.get(id) ?? [];
list.push(Component.preload);
preloaders.set(id, list);
}
return Component;
}
/** Preloads any lazy component registered for `pageId` before revealing it. */
export function preloadBuiltinPage(pageId: string): Promise<void> | undefined {
const list = preloaders.get(pageId);
if (!list?.length) return undefined;
return Promise.all(list.map((fn) => fn().catch(() => {}))).then(() => undefined);
}
+15 -8
Переглянути файл
@@ -1,6 +1,5 @@
/** Registers the built-in pages as ordinary settings-page contributions and indexes their labels. */
import { commands } from "@/platform/ipc";
import { UPDATES_PAGE } from "./updates";
import { onLanguageListChanged } from "@/platform/languageList";
import { registerSettingsPage, registerSettingsPages, type SettingsPageContribution } from "@/workbench/contributions";
import { BEHAVIOR_PAGES } from "./behavior";
@@ -9,14 +8,18 @@ import { DEPLOYMENT_PAGES } from "./deployment";
import { EDITOR_PAGES, codeStyleLanguagePages } from "./editor";
import { EXECUTION_PAGES } from "./execution";
import { LANGUAGE_PAGES } from "./languages";
import { preloadBuiltinPage } from "./lazyPage";
import { OptionsPage } from "./OptionsPage";
import { RUN_TARGET_PAGES } from "./runTargets";
import { SCOPE_PAGES } from "./scopes";
import { flattenOptions, specLabels, type PageSpec } from "./spec";
import { SSH_PAGES } from "./ssh";
import { TOOLS_PAGES } from "./tools";
import { UPDATES_PAGE } from "./updates";
import { VCS_PAGES } from "./vcs";
export { preloadBuiltinPage };
const BUILTIN_PAGES = [
...BEHAVIOR_PAGES,
...SCOPE_PAGES,
@@ -59,19 +62,23 @@ function toContribution(spec: PageSpec): SettingsPageContribution {
return { id: spec.id, title: spec.title, group: spec.group, order: spec.order, keywords: spec.keywords, component };
}
export function registerBuiltinPages(): () => void {
export function registerBuiltinPages(opts: { updates?: boolean } = {}): () => void {
const disposeBuiltins = registerSettingsPages(
BUILTIN_PAGES.filter((spec) => spec !== UPDATES_PAGE).map(toContribution),
);
// Code Style › <Language> pages come from the backend's language list, which plugins change.
let live = true;
let disposeUpdates = () => {};
void commands
.appBuildInfo()
.then((info) => {
if (live && info.updates) disposeUpdates = registerSettingsPage(toContribution(UPDATES_PAGE));
})
.catch(() => {});
if (opts.updates !== undefined) {
if (opts.updates) disposeUpdates = registerSettingsPage(toContribution(UPDATES_PAGE));
} else {
void commands
.appBuildInfo()
.then((info) => {
if (live && info.updates) disposeUpdates = registerSettingsPage(toContribution(UPDATES_PAGE));
})
.catch(() => {});
}
let disposeLanguagePages = () => {};
let generation = 0;
const loadLanguagePages = () => {
+44
Переглянути файл
@@ -0,0 +1,44 @@
import { BUILD_GROUP } from "./execution";
import { lazyPage } from "./lazyPage";
import type { PageSpec } from "./spec";
export { parentPath, splitList } from "./runTargetsPaths";
const RunTargetsEditor = lazyPage("build.runTargets", () => import("./RunTargetsBody").then((m) => m.RunTargetsEditor));
export const RUN_TARGET_PAGES: PageSpec[] = [
{
id: "build.runTargets",
title: "Run Targets",
group: BUILD_GROUP,
order: 364,
projectScope: true,
keywords: ["ssh", "remote", "target", "run on", "interpreter", "upload", "sync", "docker", "compose", "container"],
sections: [
{
options: [
{
kind: "custom",
label: "Run Targets",
keywords: [
"SSH configuration",
"Project folder on target",
"Upload changed project files before each run",
"Python interpreter",
"Node.js interpreter",
"Java executable",
"Docker connection",
"Image",
"Compose files",
"Service",
"Container folder",
"Published ports",
"Run options",
],
component: RunTargetsEditor,
},
],
},
],
},
];
+15
Переглянути файл
@@ -0,0 +1,15 @@
/** Parent of a remote path (`~/a` → `~`, `/a` → `/`); null at the top. */
export function parentPath(path: string): string | null {
const p = path.length > 1 ? path.replace(/\/+$/, "") : path;
if (p === "/" || p === "~" || p === "") return null;
const i = p.lastIndexOf("/");
if (i < 0) return null;
return i === 0 ? "/" : p.slice(0, i);
}
/** Settings typed as lists of words (`8000:8000 5678:5678`, `a.yaml; b.yaml`). */
export const splitList = (text: string): string[] =>
text
.split(/[\s,;]+/)
.map((s) => s.trim())
.filter(Boolean);
+51
Переглянути файл
@@ -0,0 +1,51 @@
import { APPEARANCE_GROUP } from "./behavior";
import { lazyPage } from "./lazyPage";
import type { PageSpec } from "./spec";
const FileColorsEditor = lazyPage("fileColors", () => import("./ScopesBody").then((m) => m.FileColorsEditor));
const ScopesEditor = lazyPage("scopes", () => import("./ScopesBody").then((m) => m.ScopesEditor));
export const SCOPE_PAGES: PageSpec[] = [
{
id: "fileColors",
title: "File Colors",
group: APPEARANCE_GROUP,
order: 1.5,
projectScope: true,
defaultScope: "project",
keywords: ["colour", "color", "tab", "background", "tests", "non-project"],
sections: [
{
options: [
{ kind: "toggle", key: "fileColors.enabled", label: "Enable file colors" },
{ kind: "toggle", key: "fileColors.editorTabs", label: "Use in editor tabs" },
{ kind: "toggle", key: "fileColors.projectView", label: "Use in project view" },
],
},
{
options: [
{
kind: "custom",
label: "File Colors",
keywords: ["Scope", "Color", "Custom", "Hex value"],
component: FileColorsEditor,
},
],
},
],
},
{
id: "scopes",
title: "Scopes",
group: APPEARANCE_GROUP,
order: 1.6,
projectScope: true,
defaultScope: "project",
keywords: ["scope", "file set", "pattern"],
sections: [
{
options: [{ kind: "custom", label: "Scopes", keywords: ["Name", "Pattern"], component: ScopesEditor }],
},
],
},
];
+39
Переглянути файл
@@ -0,0 +1,39 @@
import { lazyPage } from "./lazyPage";
import type { PageSpec } from "./spec";
import { TOOLS_GROUP } from "./tools";
const SshConfigsEditor = lazyPage("tools.sshConfigurations", () => import("./SshBody").then((m) => m.SshConfigsEditor));
export const SSH_PAGES: PageSpec[] = [
{
id: "tools.sshConfigurations",
title: "SSH Configurations",
group: TOOLS_GROUP,
order: 603,
keywords: ["ssh", "remote", "host", "server", "key pair", "private key", "password", "known_hosts", "agent"],
sections: [
{
options: [
{
kind: "custom",
label: "SSH Configurations",
keywords: [
"Host",
"Port",
"User name",
"Authentication type",
"Private key file",
"Password",
"Passphrase",
"Save password",
"Save passphrase",
"Test Connection",
"OpenSSH config and authentication agent",
],
component: SshConfigsEditor,
},
],
},
],
},
];
+46
Переглянути файл
@@ -0,0 +1,46 @@
import { lazyPage } from "./lazyPage";
import type { PageSpec } from "./spec";
const UpdateStatusRows = lazyPage("general.updates", () => import("./UpdatesBody").then((m) => m.UpdateStatusRows));
export const UPDATES_PAGE: PageSpec = {
id: "general.updates",
title: "Updates",
order: 3,
keywords: ["update", "upgrade", "version", "automatic", "GitHub", "CNB"],
sections: [
{
options: [
{
kind: "custom",
label: "Current version",
keywords: ["Last checked", "Check Now"],
component: UpdateStatusRows,
},
{
kind: "toggle",
key: "general.autoCheckUpdates",
label: "Check for updates automatically",
hint: "At startup and every 4 hours while OpenIDEA runs. Each new version is announced once per session.",
},
{
kind: "toggle",
key: "general.showWhatsNewAfterUpdate",
label: "Show What's New after an update",
hint: "Opens a page with the release notes when a new version starts. Help › What's New opens it any time.",
},
{
kind: "select",
key: "general.updateSource",
label: "Update source",
hint: "Where updates are downloaded from. If it can't be reached, the other source is tried.",
options: [
{ value: "auto", label: "Automatic" },
{ value: "github", label: "GitHub" },
{ value: "cnb", label: "CNB (China mirror)" },
],
},
],
},
],
};
+52 -29
Переглянути файл
@@ -8,12 +8,13 @@ import { registerActions } from "@/platform/actions";
import { logError } from "@/platform/errorLog";
import { isImeKey } from "@/platform/ime";
import { commands } from "@/platform/ipc";
import { loadSettings, useProject } from "@/platform/project";
import { restoreRemote } from "@/platform/remote";
import { useProject } from "@/platform/project";
import { enableRemote } from "@/platform/remote";
import { isPopupOpen } from "@/ui";
import { settingsActions } from "./actions";
import { loadBuiltinPages, unloadBuiltinPages } from "./dialog/LazySettingsDialog";
import { NEW_PROJECTS_PAGE, settingsActions } from "./actions";
import { loadBuiltinPages, preloadBuiltinRegistry, unloadBuiltinPages } from "./dialog/LazySettingsDialog";
import { trackIconThemePages } from "./iconThemePages";
import { validateSettings } from "./model/schema";
import {
closeSettings,
openSettings,
@@ -53,16 +54,18 @@ export function relaunchSettings(launch: SettingsLaunch | null) {
navigate(launch.page);
}
function listenLaunch(): () => void {
function listenLaunch(afterInit: Promise<unknown>): () => void {
let disposed = false;
let off: (() => void) | undefined;
void getCurrentWebviewWindow()
.listen(LAUNCH_EVENT, () => void takeLaunch().then(relaunchSettings))
.then((u) => {
.then(async (u) => {
if (disposed) return u();
off = u;
// A page requested before we listened: its event is gone, the launch is not.
void takeLaunch().then(relaunchSettings);
// A page requested after `window_take_settings_init` read the slot but before `listen`
// attached: its event is gone, the launch is not. Apply it after the initial launch settles.
await afterInit.catch(() => {});
if (!disposed) void takeLaunch().then(relaunchSettings);
});
return () => {
disposed = true;
@@ -91,13 +94,53 @@ function installWindowKeys(): () => void {
* the parent's project; Cancel / OK / Esc close the window.
*/
export function activateSettingsWindow(parent: string): () => void {
const bootstrap = (async () => {
useSettingsDialog.setState({ pagesLoading: true });
openSettings(undefined, { globalBase: useSettingsDialog.getState().globalBase });
try {
const [init] = await Promise.all([commands.windowTakeSettingsInit(), preloadBuiltinRegistry().catch(() => null)]);
if (init.remote) enableRemote(init.remote);
const globalBase = validateSettings(init.globalSettings);
if (init.project) {
useProject.setState({ project: init.project, settings: init.project.settings });
} else {
useProject.setState({ project: null, settings: init.globalSettings });
}
const launch = init.launch && {
page: init.launch.settingsPage ?? undefined,
newProjects: init.launch.newProjects,
};
const targetPage =
launch?.page ?? (launch?.newProjects ? NEW_PROJECTS_PAGE : useSettingsDialog.getState().pageId);
await loadBuiltinPages({ pageId: targetPage, updates: init.updates }).catch((e) =>
logError("cannot register settings pages", e),
);
relaunchSettings(launch);
rebaseSettings(globalBase);
if (init.remote) {
// Reconcile remote-host settings asynchronously without blocking first paint on SSH.
// `rebaseSettings` updates only `base` / `globalBase` and leaves any staged edits intact.
void commands
.projectCurrent()
.then((fresh) => {
if (!fresh || !useSettingsDialog.getState().open) return;
useProject.setState({ project: fresh, settings: fresh.settings });
rebaseSettings(globalBase);
})
.catch(() => {});
}
} finally {
useSettingsDialog.setState({ pagesLoading: false });
}
})();
bootstrap.catch((e) => logError("settings window startup failed", e));
const disposers = [
trackRuntimeSettings(),
trackIconThemePages(),
unloadBuiltinPages,
registerActions(settingsActions((page, newProjects) => relaunchSettings({ page, newProjects: !!newProjects }))),
installActionProxies(parent),
listenLaunch(),
listenLaunch(bootstrap),
installWindowKeys(),
useSettingsDialog.subscribe((s, prev) => {
if (prev.open && !s.open) void getCurrentWebviewWindow().close();
@@ -108,25 +151,5 @@ export function activateSettingsWindow(parent: string): () => void {
}
}),
];
void (async () => {
useSettingsDialog.setState({ pagesLoading: true });
openSettings();
try {
const launch = await takeLaunch();
relaunchSettings(launch);
await Promise.all([
loadBuiltinPages().catch((e) => logError("cannot register settings pages", e)),
(async () => {
await restoreRemote();
const project = await commands.projectCurrent().catch(() => null);
if (project) useProject.setState({ project, settings: project.settings });
else await loadSettings().catch((e) => console.warn("cannot load settings", e));
rebaseSettings();
})(),
]);
} finally {
useSettingsDialog.setState({ pagesLoading: false });
}
})().catch((e) => logError("settings window startup failed", e));
return () => disposers.reverse().forEach((d) => d());
}
+103 -2
Переглянути файл
@@ -4,7 +4,7 @@ import { act, fireEvent, screen } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { BlameLine, Commit } from "@/bindings";
import { useI18n } from "@/platform/i18n";
import { annotationsShown, blameSlot, toggleAnnotations } from "../blame";
import { annotationsShown, blameSlot, readAnnotateColumns, toggleAnnotations, useAnnotateColumns } from "../blame";
import { closeBlamePopup } from "../BlamePopup";
import { useVcs } from "../store";
@@ -184,6 +184,107 @@ describe("git blame gutter and commit popup", () => {
)!;
fireEvent.contextMenu(edited);
const items = mocks.menu.mock.calls[0]![1] as { label?: string }[];
expect(items.map((i) => i.label)).toEqual(["Close Annotations"]);
expect(items.map((i) => i.label)).toEqual(["Options", "Close Annotations"]);
});
});
describe("annotate Options", () => {
type Item = { label?: string; checked?: boolean; disabled?: boolean; run?: () => void; submenu?: Item[] };
beforeEach(() => {
localStorage.clear();
useAnnotateColumns.setState(readAnnotateColumns());
});
async function annotated(doc = "first\nsecond\nthird") {
const v = new EditorView({ parent: document.body, state: EditorState.create({ doc, extensions: [blameSlot()] }) });
await toggleAnnotations(v, "/repo/src/main.py");
return v;
}
function options(v: EditorView): Item[] {
mocks.menu.mockClear();
fireEvent.contextMenu(v.dom.querySelector(".cm-vcs-blame .cm-gutterElement [data-commit]")!);
const items = mocks.menu.mock.calls[0]![1] as Item[];
return items.find((i) => i.label === "Options")!.submenu!;
}
const hidden = (v: EditorView) =>
["date", "author", "revision"].filter((c) => v.dom.classList.contains(`cm-vcs-blame-hide-${c}`));
it("shows date and author by default and adds the revision from Options", async () => {
view = await annotated();
expect(options(view).map((i) => [i.label, i.checked])).toEqual([
["Date", true],
["Author", true],
["Revision", false],
]);
expect(hidden(view)).toEqual(["revision"]);
expect(view.dom.querySelector(`[data-commit="${sha}"] .cm-vcs-blame-revision`)?.textContent).toBe("f122f5af");
act(() => options(view!)[2]!.run!());
expect(hidden(view)).toEqual([]);
expect(options(view).map((i) => i.checked)).toEqual([true, true, true]);
act(() => options(view!)[1]!.run!());
expect(hidden(view)).toEqual(["author"]);
});
it("keeps the last shown column", async () => {
view = await annotated();
act(() => options(view!)[1]!.run!());
const last = options(view);
expect(last.map((i) => [i.checked, i.disabled])).toEqual([
[true, true],
[false, false],
[false, false],
]);
act(() => last[0]!.run!());
expect(hidden(view)).toEqual(["author", "revision"]);
});
it("updates every annotated editor and remembers the choice", async () => {
view = await annotated();
const other = await annotated("a\nb\nc");
try {
act(() => options(view!)[0]!.run!());
expect(hidden(other)).toEqual(["date", "revision"]);
expect(JSON.parse(localStorage.getItem("openidea.vcs.annotateColumns")!)).toEqual({
date: false,
author: true,
revision: false,
});
expect(readAnnotateColumns()).toEqual({ date: false, author: true, revision: false });
} finally {
other.destroy();
}
});
it("follows a choice made in another window", async () => {
view = await annotated();
localStorage.setItem("openidea.vcs.annotateColumns", '{"date":true,"author":false,"revision":true}');
act(() => {
window.dispatchEvent(new StorageEvent("storage", { key: "openidea.vcs.annotateColumns" }));
});
expect(hidden(view)).toEqual(["author"]);
expect(options(view).map((i) => i.checked)).toEqual([true, false, true]);
});
it("falls back to the defaults for a stored value it cannot use", () => {
const defaults = { date: true, author: true, revision: false };
for (const raw of ["{", "[]", "null", '"x"', '{"date":false,"author":false,"revision":false}']) {
localStorage.setItem("openidea.vcs.annotateColumns", raw);
expect(readAnnotateColumns()).toEqual(defaults);
}
localStorage.setItem("openidea.vcs.annotateColumns", '{"date":"no","revision":true}');
expect(readAnnotateColumns()).toEqual({ date: true, author: true, revision: true });
});
it("leaves the editor's classes alone once annotations are closed", async () => {
view = await annotated();
await toggleAnnotations(view, "/repo/src/main.py");
expect(hidden(view)).toEqual([]);
act(() => useAnnotateColumns.setState({ date: false, author: true, revision: true }));
expect(hidden(view)).toEqual([]);
});
});
+86 -2
Переглянути файл
@@ -2,6 +2,7 @@
import { writeClipboardText } from "@/platform/clipboard";
import { Compartment, Prec, RangeSet, StateEffect, StateField, type Extension, type Text } from "@codemirror/state";
import { EditorView, GutterMarker, ViewPlugin, gutter, type PluginValue, type ViewUpdate } from "@codemirror/view";
import { create } from "zustand";
import type { BlameLine } from "@/bindings";
import { executeAction } from "@/platform/actions";
import { tx } from "@/platform/i18n";
@@ -88,7 +89,10 @@ class BlameMarker extends GutterMarker {
const date = document.createElement("span");
date.className = "cm-vcs-blame-date";
date.textContent = formatDate(l.timeMs);
el.append(date, author);
const revision = document.createElement("span");
revision.className = "cm-vcs-blame-revision";
revision.textContent = l.commit.slice(0, 8);
el.append(date, author, revision);
if (this.bg) {
el.style.setProperty("--blame-bg", this.bg);
el.style.backgroundColor = this.bg;
@@ -98,7 +102,82 @@ class BlameMarker extends GutterMarker {
}
}
const spacer = new BlameMarker({ commit: "f", author: "Mmmmmmmm", timeMs: Date.UTC(2020, 11, 28), summary: "" });
const spacer = new BlameMarker({
commit: "ffffffff",
author: "Mmmmmmmm",
timeMs: Date.UTC(2020, 11, 28),
summary: "",
});
/** The columns the gutter shows (IDEA's annotate Options); kept across sessions. */
const COLUMNS = ["date", "author", "revision"] as const;
type AnnotateColumn = (typeof COLUMNS)[number];
type AnnotateColumns = Record<AnnotateColumn, boolean>;
const COLUMNS_KEY = "openidea.vcs.annotateColumns";
const DEFAULT_COLUMNS: AnnotateColumns = { date: true, author: true, revision: false };
export function readAnnotateColumns(): AnnotateColumns {
try {
const raw: unknown = JSON.parse(localStorage.getItem(COLUMNS_KEY) ?? "null");
const o = raw && typeof raw === "object" ? (raw as Record<string, unknown>) : {};
const out = { ...DEFAULT_COLUMNS };
for (const k of COLUMNS) if (typeof o[k] === "boolean") out[k] = o[k];
return COLUMNS.some((k) => out[k]) ? out : { ...DEFAULT_COLUMNS };
} catch {
return { ...DEFAULT_COLUMNS };
}
}
export const useAnnotateColumns = create<AnnotateColumns>(() => readAnnotateColumns());
// Other windows (project, diff) annotate too.
if (typeof window !== "undefined")
window.addEventListener("storage", (e) => {
if (e.key === COLUMNS_KEY) useAnnotateColumns.setState(readAnnotateColumns());
});
/** Shows or hides a column in every annotated editor; the last shown column stays. */
function setAnnotateColumn(column: AnnotateColumn, shown: boolean) {
const next = { ...useAnnotateColumns.getState(), [column]: shown };
if (!COLUMNS.some((k) => next[k])) return;
useAnnotateColumns.setState(next);
try {
localStorage.setItem(COLUMNS_KEY, JSON.stringify(next));
} catch {
// ignore
}
}
/** Hides the columns turned off in Options, here and in editors annotated before the change. */
const annotateColumns = ViewPlugin.define(
(view) => ({ destroy: useAnnotateColumns.subscribe(() => view.dispatch({})) }),
{
provide: () =>
EditorView.editorAttributes.of(() => {
const c = useAnnotateColumns.getState();
const hidden = COLUMNS.filter((k) => !c[k]);
return hidden.length ? { class: hidden.map((k) => `cm-vcs-blame-hide-${k}`).join(" ") } : null;
}),
},
);
const COLUMN_LABELS: Record<AnnotateColumn, string> = { date: "Date", author: "Author", revision: "Revision" };
function optionsMenu() {
const c = useAnnotateColumns.getState();
const shown = COLUMNS.filter((k) => c[k]).length;
return {
label: "Options",
submenu: COLUMNS.map((k) => ({
label: COLUMN_LABELS[k],
checked: c[k],
// At least one column stays, as in IDEA.
disabled: c[k] && shown === 1,
run: () => setAnnotateColumn(k, !c[k]),
})),
};
}
const setBlame = StateEffect.define<BlameLine[]>();
@@ -178,6 +257,9 @@ const blameTheme = EditorView.baseTheme({
},
".cm-vcs-blame-date": { minWidth: "7ch", fontVariantNumeric: "tabular-nums" },
".cm-vcs-blame-author": { minWidth: "9ch" },
".cm-vcs-blame-revision": { fontFamily: "var(--font-mono)" },
"&.cm-vcs-blame-hide-date .cm-vcs-blame-date, &.cm-vcs-blame-hide-author .cm-vcs-blame-author, &.cm-vcs-blame-hide-revision .cm-vcs-blame-revision":
{ display: "none" },
".cm-vcs-blame .cm-gutterElement:hover .cm-vcs-blame-line, .cm-vcs-blame .cm-gutterElement.cm-vcs-blame-same-commit .cm-vcs-blame-line":
{
color: "var(--fg-strong)",
@@ -307,6 +389,7 @@ function blameExtension(lines: BlameLine[], path: string, live: boolean): Extens
{ kind: "separator" as const },
]
: []),
optionsMenu(),
{ label: "Close Annotations", run: () => setAnnotations(view, null, path, false) },
]);
return true;
@@ -315,6 +398,7 @@ function blameExtension(lines: BlameLine[], path: string, live: boolean): Extens
}),
),
ViewPlugin.define((view) => new BlameInteraction(view)),
annotateColumns,
// Static content (a merge pane's side) is not re-blamed on edits / HEAD moves.
...(live ? [ViewPlugin.define((view) => new BlameRefresher(view, path))] : []),
blameTheme,
+3
Переглянути файл
@@ -372,6 +372,9 @@
"Show in Explorer": "Show in Explorer",
"Show in Files": "Show in Files",
"Reveal in Finder": "Reveal in Finder",
"Cannot open {path} with its application": "Cannot open {path} with its application",
"Open in Associated Application": "Open in Associated Application",
"Associated Application": "Associated Application",
"Patch file created successfully. Show it in Finder?": "Patch file created successfully. Show it in Finder?",
"Patch file created successfully. Show it in Explorer?": "Patch file created successfully. Show it in Explorer?",
"Patch file created successfully. Show it in Files?": "Patch file created successfully. Show it in Files?",
+7 -4
Переглянути файл
@@ -339,6 +339,9 @@
"Finder": "访达",
"Explorer": "资源管理器",
"Reveal in Finder": "在访达中显示",
"Cannot open {path} with its application": "无法用关联的应用程序打开 {path}",
"Open in Associated Application": "在关联的应用程序中打开",
"Associated Application": "关联的应用程序",
"Classes reloaded": "类已重新加载",
"Active frames keep running the old code until they return. New calls use the reloaded code.": "活动栈帧将继续执行旧代码,直到方法返回。新的调用将使用重新加载的代码。",
"The bottom frame cannot be reset. Re-enter the method or restart the debug session to run the new code.": "无法重置栈底帧。请重新进入该方法或重启调试会话,以执行新代码。",
@@ -8902,8 +8905,8 @@
"Maximum refresh rate": "最大刷新率",
"Caps how often fast terminal output is painted. Hidden windows always paint more slowly.": "限制快速终端输出的绘制频率。隐藏的窗口总会更慢地绘制。",
"Unlimited": "不限制",
"60 FPS": "60 FPS",
"30 FPS": "30 FPS",
"15 FPS": "15 FPS",
"10 FPS": "10 FPS"
"60 FPS": "60 帧/秒",
"30 FPS": "30 帧/秒",
"15 FPS": "15 帧/秒",
"10 FPS": "10 帧/秒"
}
+1 -1
Переглянути файл
@@ -36,7 +36,7 @@ export { fuzzyMatch, wordMatch } from "./match";
export { badgeKind } from "./symbolKind";
export { acquirePopup, isPopupOpen } from "./popupState";
export * from "./BarButton";
export { lazyComponent, lazyWhen, prefetchLazyComponents } from "./lazy";
export { lazyComponent, lazyWhen, prefetchLazyComponents, type LazyComponent } from "./lazy";
export { Given, T } from "./T";
export { selectableText, copyMenuFor, copyText } from "./selectableText";
export { selectReadingPane, useSelectionBoundary } from "./useSelectionBoundary";
+6 -1
Переглянути файл
@@ -2,13 +2,17 @@ import { useEffect, useState, type ComponentType } from "react";
const loaders: Array<() => Promise<unknown>> = [];
export type LazyComponent<P extends object = Record<string, never>> = ComponentType<P> & {
preload(): Promise<ComponentType<P>>;
};
/**
* A component whose code loads on first render (rendering nothing until then),
* so contributions keep heavy views out of the start-up bundle. Deliberately
* not `React.lazy`: a suspended boundary is revealed ~300 ms late (React's
* fallback throttling), even when the chunk is already there.
*/
export function lazyComponent<P extends object>(load: () => Promise<ComponentType<P>>): ComponentType<P> {
export function lazyComponent<P extends object>(load: () => Promise<ComponentType<P>>): LazyComponent<P> {
let loaded: ComponentType<P> | null = null;
let pending: Promise<ComponentType<P>> | null = null;
const get = () =>
@@ -36,6 +40,7 @@ export function lazyComponent<P extends object>(load: () => Promise<ComponentTyp
}, [Component]);
return Component ? <Component {...props} /> : null;
}
LazyComponent.preload = get;
return LazyComponent;
}