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

...
Автор SHA1 Повідомлення Дата
Deng Liu 39d5a62d92 fix(macos): preserve horizontal trackpad scrolling inside iframes
Copilot-Session: fddd7ed1-c260-45fb-9523-7117cdd5e772
2026-11-25 09:26:01 -05:00
l0ng-ai 0b079af75d fix(i18n): drop the text of the removed turn-folding setting (#5914)
#5906 removed foldTurns and its settings row, but its four strings stayed in every locale catalog, so the catalog test that rejects entries missing from the source failed on main.
2026-11-25 21:56:03 +08:00
Deng Liuтаdengliu 6dab294dbf fix(editor): keep syntax and semantic backgrounds on their own row (#5787)
Syntax and semantic token backgrounds no longer cover characters on neighboring lines when the font box is taller than the line height. Token fills now go through the same 1lh-capped inline background as Find and occurrence highlights, with the colour in --openidea-token-bg so semantic roles can override nested syntax fills; an unset fill paints nothing. The background size is a separate declaration, so WebKit without lh support still shows the fill.

Co-authored-by: dengliu <[email protected]>
2026-11-25 21:55:45 +08:00
l0ng-ai fc0ca1e029 test(remote): retry the old backend connect until its socket listens (#5910)
The daemon's socket file appears at bind(), before listen(), so a connect in between is refused; upgraded_build_refuses_live_work_and_then_replaces_idle_backend failed that way on macOS CI. The helper now retries on ConnectionRefused.
2026-11-25 21:42:45 +08:00
l0ng-ai fe024713da fix(java): take the last diagnostic line with next_back (#5909)
lines.last() on the double-ended filter iterator tripped clippy::double_ended_iterator_last, failing the Rust checks on main; next_back() returns the same line.
2026-11-25 21:39:51 +08:00
l0ng-aiтаCursor 42c7834023 feat(agents): fold all consecutive tool calls into runs and remove foldTurns (#5906)
Co-authored-by: Cursor <[email protected]>
2026-11-25 21:28:10 +08:00
l0ng-ai 96f73c82da fix(vcs): keep every repository listed after double-clicking a branch (#5905)
Double-clicking a branch in the Git Log Branches pane now changes only the branch filter. It no longer also sets the repository filter, which narrowed the Branches pane to that one repository and left a second filter to clear by hand. Repositories without the branch contribute no commits, so the log shows the same history, and clearing the branch filter restores the whole log. A repository filter chosen from the Paths filter is kept.

Fixes #5893
2026-11-25 21:22:16 +08:00
854c81e49b feat(browser): browse and inspect localhost in a persistent native panel (#5788)
Open Local Browser opens a Browser tool window hosting a Tauri child webview
for a loopback HTTP(S) origin in a trusted local project: back, forward,
reload, same-origin navigation, and Inspect Element, whose reviewed selection
is appended to the Agent draft without being sent. The guest webview has an
empty capability set; workbench capabilities are scoped by webview label, and
application IPC and the plugin protocol reject guests by label. Workbench
windows are tracked as their original WebviewWindow handles, because Tauri's
single-webview lookup stops matching once a child is attached; window
commands (including the parallel close flow) use those handles.

Console URL clicks keep opening the external browser; loopback URLs get
"Open in Browser Tool Window" in the Run and Debug console context menus.
The panel uses a one-row icon toolbar, fills the panel with the page, has its
own tool window icon and focuses the address field for a new session.

Co-authored-by: dengliu <[email protected]>
Co-authored-by: aditya-786 <[email protected]>
2026-11-25 21:20:37 +08:00
l0ng-ai b19922b71d fix(agents): keep the context ring on the window Claude Code reports (#5902)
A result's modelUsage can give a model a larger contextWindow (1M) than the window Claude Code counts and compacts against (get_context_usage maxTokens, 400k), so the ring and the Context window details disagreed. The window get_context_usage reports, when the details or a compaction read it, now wins for that model.
2026-11-25 21:17:35 +08:00
l0ng-ai afab9d0ba2 fix(java): name a failed Gradle sync's cause when Run or Debug stops on it (#5904)
Buildship marks a Gradle project whose sync failed with the tooling API's message first and the build's own error last; launch errors kept only the first line. For these Gradle messages the last line now follows as the cause, in launch compile errors and in the build-file problems that keep a module out of jdtls.
2026-11-25 21:17:15 +08:00
l0ng-ai 04ed8712b5 fix(markdown): reflow the blocks in view while a pane is resized (#5903)
During a pane resize only the blocks the viewport observer marked reflowed; when the marks were missing (content replaced without a new render, a restored preview) every block kept its old width and visible text was clipped until the drag ended. A resize now marks the blocks in and near the viewport by position, and replaced content is observed again.
2026-11-25 21:17:06 +08:00
l0ng-ai 971b520399 feat(agents): fold shell commands that only read or search into exploration runs (#5898)
A shell command whose every segment only reads or searches (grep, rg, git grep, find, cat, sed -n, ls, git status/diff/log/show…) now joins the exploration run with reasoning and counts in its summary as a read or a search. Commands that may change something (builds, tests, writes, redirects, command substitution, unknown programs) still show on their own row. The leading cd parsing moves into the same module and is shared with command titles.
2026-11-25 20:39:48 +08:00
l0ng-ai c67363ec6b test(sdk): use an absolute temp path for the explicit Dart tool path (#5899)
'/opt/dart/bin/dart' is not absolute on Windows, so it resolved against the project root's drive and the Flutter SDK test failed on windows-latest. The test now uses an absolute path under the temp dir.
2026-11-25 20:37:09 +08:00
l0ng-ai 2568772700 perf(window): close project tabs in parallel and move teardown off the UI thread (#5882)
Quit, closing a tab group and Close Other/Left/Right Tabs now close their windows in parallel and hide them together in one frame; a window that needs to ask (unsaved changes, running processes, remote backend) takes the prompt turn and comes forward, so prompts still appear one at a time. Agent, terminal and process teardown moves off the UI thread into the project's background shutdown, idle agent tasks are no longer rewritten on close, and opening a project only waits for closes of overlapping roots.
2026-11-25 20:19:17 +08:00
l0ng-ai 536f85b9df feat(java): build Maven and Gradle modules with a resident, incremental javac build service (#5854)
Implements #4078 steps 2–4: an IDE-owned Java build service that compiles Maven and Gradle modules with a resident javac, class by class, for launches and the Build menu.

## What changes

- **Model.** The build tool records each project's source roots, compile/runtime classpaths, resources and the compiler configuration it actually uses (release/source/target, encoding, `-parameters`, debug level, `proc`, compiler args, includes/excludes, resolved annotation processor path):
  - Maven: a core extension (`java/java-build`, `BuildModel`) during `process-resources resources:testResources`.
  - Gradle: an init script (`gradle-build.init.gradle`) with an `openideaBuildModel` task that runs source generators and `processResources`.

  The prepare run happens only when what the model is built from changes: build scripts, settings, toolchains, the launcher, the JDK, generator inputs (`src/*/proto`, `antlr4`…), or a generated root that is gone.
- **Outputs.** Every project writes to `<cache>/java-build/<build>/out/<group>.<name>/classes|test-classes`, and dependencies on other projects of the build resolve to those folders. jdtls and a terminal `mvn`/`gradle` never write the classes a launch runs.
- **Compile.** A resident javac process per JDK (and `.mvn/jvm.config`) compiles source sets in dependency order, without `-am` or the full lifecycle.
- **Class-level incremental compilation.** Each source set records, per class: its source, supertypes, the classes its constant pool references, and fingerprints of its API and compile-time constants (read from the class files, private and synthetic members excluded).
  - A build compiles the changed sources.
  - It then compiles, round after round, the sources of classes that reference a class whose API changed (or one of its subclasses), and the sources a new class could shadow.
  - Downstream sets follow an API change log.
  - A changed constant recompiles the set and everything compiled against it.
  - Sources a failed compile left behind stay dirty.
  - Sets whose annotation processors aggregate compile from scratch.
- **Build menu.**
  - Build Project and Build Module compile with the service.
  - Recompile compiles the file with the service and publishes javac's diagnostics.
- **Events.** Steps, positioned javac diagnostics and progress stream on the `BuildEvent` channel from #5801.
- **When it applies.**
  - Maven modules, unless Settings › Maven › *Delegate IDE build/run actions to Maven* is on.
  - Gradle modules when Settings › Gradle › *Build and run using* is the IDE.
  - Debug launches keep jdtls' build, because java-debug's HotSwap reloads what jdtls compiles.
  - jdtls keeps autobuild on: cross-module diagnostics depend on it (verified with a real jdtls, see the ignored test below).
- **Fallback.** These go to the build tool's own build:
  - modules that need it: another compiler (Kotlin, Groovy, AspectJ…), a non-javac compiler id, multi-release output, Java modules, unresolvable dependencies or processor paths, composite Gradle builds;
  - a failed prepare run.

The javac server and the Maven extension are built reproducibly with `--release 8` against Maven 3.9.11 (`java/java-build/build.py`, dependencies pinned) and embedded by `ide-sdk`.

## Tests

- `ide-build` `jbuild::tests`, run against a real Maven/Gradle and JDK (skipped when missing):
  - first build, no-op build, only changed files recompile;
  - API changes reach dependents, including through subclasses and across modules;
  - constant changes recompile dependents;
  - resource changes run only the resources step;
  - deleted sources, compile errors with positions, the test source set;
  - Recompile and Build Project;
  - Gradle projects;
  - fallback for Gradle projects with other compilers;
  - plus class-file parsing, the API change log, javac options and Ant patterns.
- `ide-host` `tests/java_build.rs`: Maven and Gradle launches through `java_resolve_launch` compile with javac into the IDE's outputs, and Build Project reports javac's errors.
- `tests/workspaces.rs`: a Maven that writes no build model falls back to `mvn -pl app -am`.
- `ide-lsp` (ignored, needs jdtls): jdtls reports cross-module errors in open and closed files with autobuild on.
2026-11-25 20:01:26 +08:00
l0ng-ai e5c5915f2e feat(agents): logos for every agent in the ACP registry (#5884)
Every agent in the ACP registry now shows its own logo instead of the generic agents icon. A provider's logo is looked up by id, with legacy and ACP-adapter ids (claude-acp, codex-acp, kimi-code, opencode-v2) sharing their agent's logo and Hermes profiles using Hermes'. The registry logos are listed in THIRD_PARTY_LICENSES.md.
2026-11-25 19:55:06 +08:00
l0ng-ai ca2bf89f86 feat(agents): drop the leading cd from command titles (#5890)
Command titles drop a leading `cd <dir> &&`; a folder other than the task's shows as a small tag before the command, with the full path on hover. The running-command hint in a grouped run's summary uses the same title.
2026-11-25 19:45:51 +08:00
171 змінених файлів з 8920 додано та 880 видалено

No files matched your search

+11
Переглянути файл
@@ -6,6 +6,17 @@
[Simple Icons](https://github.com/simple-icons/simple-icons), retrieved through
Iconify (`simple-icons:angular`, `simple-icons:astro`, `simple-icons:cplusplus`, `simple-icons:dart`, `simple-icons:deepseek`, `simple-icons:django`, `simple-icons:dotnet`, `simple-icons:elixir`, `simple-icons:express`, `simple-icons:fastapi`, `simple-icons:flask`, `simple-icons:flutter`, `simple-icons:go`, `simple-icons:haskell`, `simple-icons:html5`, `simple-icons:kotlin`, `simple-icons:ktor`, `simple-icons:laravel`, `simple-icons:nestjs`, `simple-icons:nextdotjs`, `simple-icons:nodedotjs`, `simple-icons:nuxt`, `simple-icons:openjdk`, `simple-icons:phoenixframework`, `simple-icons:php`, `simple-icons:python`, `simple-icons:quarkus`, `simple-icons:ruby`, `simple-icons:rubyonrails`, `simple-icons:rust`, `simple-icons:scala`, `simple-icons:springboot`, `simple-icons:svelte`, `simple-icons:swift`, `simple-icons:symfony`, `simple-icons:vite`, `simple-icons:zig`) and filled with the brand colors (the standard icon grey for black logos). Licensed under [CC0 1.0 Universal](https://github.com/simple-icons/simple-icons/blob/develop/LICENSE.md).
## Agent logos
The `src/ui/openidea/agents/` logos of agents listed in the
[ACP agent registry](https://github.com/agentclientprotocol/registry) (`agoragentic-acp`, `amp-acp`,
`antigravity-acp`, `autohand`, `bob`, `cline`, `codebuddy-code`, `cortex-code`, `corust-agent`,
`crow-cli`, `deepagents`, `devin`, `dimcode`, `dirac`, `factory-droid`, `fast-agent`, `glm-acp-agent`,
`grok-build`, `harn`, `junie`, `kilo`, `kimchi`, `minimax-code`, `minion-code`, `muse-code`, `nova`,
`pi-acp`, `poolside`, `sigit`, `stakpak`, `vtcode`) are the registry's icons, with a root `fill`
moved onto a group. The registry is licensed under Apache-2.0; the logos remain trademarks of
their owners.
## Microsoft ConPTY
`crates/ide-core/resources/conpty/` contains the unmodified Microsoft Windows Console
+16 -5
Переглянути файл
@@ -2291,14 +2291,25 @@ impl AgentManager {
}
}
/// Stops sending events to UI sinks (project closing).
pub fn detach_sinks(&self) {
self.shared.sinks.write().clear();
}
/// Stops every agent (project closed).
pub fn shutdown(&self) {
for task in self.tasks.read().values() {
task.kill();
// What arrived after the last save (a subagent's late updates).
task.persist();
self.detach_sinks();
let tasks: Vec<_> = self.tasks.read().values().cloned().collect();
for task in tasks {
let was_live = task.kill().is_some();
if was_live {
// Persist late subagent updates and cleared live background state.
task.persist();
} else {
// Flush pending delayed saves without rewriting untouched or archived tasks.
task.save();
}
}
self.shared.sinks.write().clear();
}
}
+10 -1
Переглянути файл
@@ -505,7 +505,16 @@ impl Shim {
"_openidea/context_usage" => {
let session = self.session(&params)?;
let proc = session.st.lock().proc.clone().ok_or_else(|| internal("Claude Code is not running"))?;
rt.block_on(proc.control(json!({ "subtype": "get_context_usage" }))).map_err(internal)
let usage = rt.block_on(proc.control(json!({ "subtype": "get_context_usage" }))).map_err(internal)?;
// The meter shows the same numbers as these details from now on.
let n = |k: &str| usage.get(k).and_then(Value::as_u64);
if let (Some(used), Some(size)) = (n("totalTokens"), n("maxTokens").filter(|m| *m > 0)) {
let update = session.st.lock().tr.on_context_usage(used, size);
if let Some(shim) = session.shim() {
shim.notify(vec![update]);
}
}
Ok(usage)
}
"_openidea/stop_task" => {
let session = self.session(&params)?;
+18
Переглянути файл
@@ -1148,6 +1148,24 @@ fn a_compaction_replaces_the_context_usage() {
assert!(t.on_result(&result).is_empty());
}
#[test]
fn claude_codes_own_window_wins_over_the_results_context_window() {
let mut t = Translator::new("s", PathBuf::from("/w"), true);
let assistant = |model: &str| {
json!({"type": "assistant", "parent_tool_use_id": null,
"message": {"id": "m1", "model": model, "content": [], "usage": {"input_tokens": 900, "output_tokens": 100}}})
};
t.on_message(&assistant("x"));
let result = json!({"modelUsage": {"x": {"contextWindow": 1_000_000}, "y": {"contextWindow": 200_000}}});
assert_eq!(t.on_result(&result)[0].update["size"], 1_000_000);
// `get_context_usage` reports the window Claude Code compacts against.
assert_eq!(t.on_context_usage(1000, 400_000).update["size"], 400_000);
assert_eq!(t.on_result(&result)[0].update["size"], 400_000);
// Another model: its own window again until Claude Code reports one for it.
t.on_message(&assistant("y"));
assert_eq!(t.on_result(&result)[0].update["size"], 200_000);
}
#[test]
fn rate_limits_and_cost() {
let mut t = Translator::new("s", PathBuf::from("/w"), false);
+14 -7
Переглянути файл
@@ -58,6 +58,10 @@ pub(super) struct Translator {
pub used: Option<u64>,
pub model: Option<String>,
windows: HashMap<String, u64>,
/// The window Claude Code itself counts against (`get_context_usage` `maxTokens`) and the
/// model it was read for. It can be smaller than the model's `contextWindow` in a `result`
/// (its compaction threshold follows this one), so it wins while the model is the same.
context_max: Option<(Option<String>, u64)>,
/// The session's cost so far in USD, as the last `result` reported it.
cost_usd: Option<f64>,
}
@@ -77,6 +81,7 @@ impl Translator {
used: None,
model: None,
windows: HashMap::new(),
context_max: None,
cost_usd: None,
}
}
@@ -571,6 +576,7 @@ impl Translator {
/// The context usage Claude Code reports (`get_context_usage`), as a usage update.
pub fn on_context_usage(&mut self, used: u64, size: u64) -> Update {
self.used = Some(used);
self.context_max = Some((self.model.clone(), size));
let mut update = json!({ "sessionUpdate": "usage_update", "used": used, "size": size });
if let Some(amount) = self.cost_usd {
update["cost"] = json!({ "amount": amount, "currency": "USD" });
@@ -580,13 +586,14 @@ impl Translator {
fn usage_update(&self) -> Option<Update> {
let used = self.used?;
let size = self
.model
.as_ref()
.and_then(|m| {
self.windows
.get(m)
.or_else(|| self.windows.iter().find(|(k, _)| k.starts_with(m.as_str())).map(|(_, v)| v))
let own = self.context_max.as_ref().filter(|(model, _)| *model == self.model).map(|(_, size)| size);
let size = own
.or_else(|| {
self.model.as_ref().and_then(|m| {
self.windows
.get(m)
.or_else(|| self.windows.iter().find(|(k, _)| k.starts_with(m.as_str())).map(|(_, v)| v))
})
})
.or_else(|| (self.windows.len() == 1).then(|| self.windows.values().next()).flatten())?;
let mut update = json!({ "sessionUpdate": "usage_update", "used": used, "size": size });
+41
Переглянути файл
@@ -1632,6 +1632,47 @@ async fn shutdown_writes_the_saves_still_waiting_and_a_delete_drops_them() {
assert_eq!(saved_title(&kept_path).as_deref(), Some("renamed"));
}
/// Closing a project with many restored/archived tasks must not rewrite tasks that never changed.
#[tokio::test]
async fn shutdown_skips_rewriting_untouched_restored_tasks() {
let tmp = tempfile::tempdir().unwrap();
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
let untouched = idle_task(&mgr, "untouched").await;
let archived = idle_task(&mgr, "archived").await;
mgr.archive(&archived.id).unwrap();
let dirty = idle_task(&mgr, "dirty").await;
mgr.shutdown();
let (untouched_path, archived_path, dirty_path) =
(task_file(tmp.path(), &untouched.id), task_file(tmp.path(), &archived.id), task_file(tmp.path(), &dirty.id));
let restored = manager(tmp.path(), Arc::new(FakeAgent::default()));
let before_untouched = FILE_WRITES.lock().get(&untouched_path).copied().unwrap_or(0);
let before_archived = FILE_WRITES.lock().get(&archived_path).copied().unwrap_or(0);
let before_dirty = FILE_WRITES.lock().get(&dirty_path).copied().unwrap_or(0);
let dirty_handle = restored.task(&dirty.id).unwrap();
dirty_handle.state.lock().task.title = "updated".into();
dirty_handle.persist_soon();
restored.shutdown();
assert_eq!(
FILE_WRITES.lock().get(&untouched_path).copied().unwrap_or(0),
before_untouched,
"untouched task should not be rewritten on shutdown"
);
assert_eq!(
FILE_WRITES.lock().get(&archived_path).copied().unwrap_or(0),
before_archived,
"archived task should not be rewritten on shutdown"
);
assert!(
FILE_WRITES.lock().get(&dirty_path).copied().unwrap_or(0) > before_dirty,
"pending persist_soon task must still be flushed on shutdown"
);
assert_eq!(saved_title(&dirty_path).as_deref(), Some("updated"));
}
/// Archiving saves the task as it is, including changes nobody asked to be saved.
#[tokio::test]
async fn archiving_saves_the_task_before_it_returns() {
+7 -2
Переглянути файл
@@ -6,7 +6,7 @@ use std::io::Read;
use std::time::SystemTime;
/// `(byte length, mtime, blake3 hex)`; the hash is recorded for files inside the project only.
type Stamp = (u64, SystemTime, Option<String>);
pub(crate) type Stamp = (u64, SystemTime, Option<String>);
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct LaunchFingerprint {
@@ -182,7 +182,7 @@ fn collect(
}
/// Scans every input, storing project inputs relative to the project.
pub(super) fn scan_all(
pub(crate) fn scan_all(
root: &Path,
inputs: Vec<PathBuf>,
cancel: &CancellationToken,
@@ -282,6 +282,11 @@ pub(super) fn module_fingerprint(
}
impl LaunchFingerprint {
/// The fingerprint of `parameters` and the files under `inputs` (see [`scan_all`]).
pub(crate) fn new(parameters: String, files: BTreeMap<PathBuf, Option<Stamp>>) -> Self {
LaunchFingerprint { version: 2, parameters, files }
}
/// Folders (relative to the project) of the Maven projects whose POM is an input.
pub(super) fn project_dirs(&self) -> impl Iterator<Item = &Path> {
self.files
+23 -1
Переглянути файл
@@ -3,7 +3,7 @@
//! background with cancellation and parses the compiler output into messages
//! for the Build tool window, the Problems view and the editor.
mod fingerprint;
pub(crate) mod fingerprint;
mod launch_resources;
mod modules;
mod parse;
@@ -845,6 +845,28 @@ fn reactor_projects<'a>(m: &'a maven::MavenModel, top: &'a maven::MavenProject)
projects
}
/// A step running Maven, its output parsed as Maven's.
pub(crate) fn maven_build_step(program: &str, args: &[&str], cwd: &Path) -> BuildStep {
BuildStep::new(program, args, cwd, Format::Maven)
}
pub(crate) fn gradle_build_step(program: &str, args: &[&str], cwd: &Path) -> BuildStep {
BuildStep::new(program, args, cwd, Format::Gradle)
}
/// The linked reactor root building the project at `module` (project-relative).
pub(crate) fn maven_reactor_dir<'a>(m: &'a maven::MavenModel, module: &str) -> Option<&'a maven::MavenProject> {
maven_reactor(m, module)
}
/// The projects of the reactor `top`.
pub(crate) fn reactor_projects_of<'a>(
m: &'a maven::MavenModel,
top: &'a maven::MavenProject,
) -> Vec<&'a maven::MavenProject> {
reactor_projects(m, top)
}
fn maven_reactor<'a>(m: &'a maven::MavenModel, module: &str) -> Option<&'a maven::MavenProject> {
m.projects.iter().filter(|p| !p.aggregated).find(|top| reactor_projects(m, top).iter().any(|p| p.dir == module))
}
+482
Переглянути файл
@@ -0,0 +1,482 @@
//! What the incremental build needs from a class file (JVMS §4): its name, supertypes, the
//! classes its constant pool refers to, and fingerprints of its API and of its compile-time
//! constants. Bounds-checked: a malformed file is `None`, never a panic.
use std::collections::BTreeSet;
/// A class file, as the dependency graph and the API diff see it.
#[derive(Clone, Debug, PartialEq)]
pub struct ClassFile {
/// Internal name (`com/acme/Order$Line`).
pub name: String,
pub super_name: Option<String>,
pub interfaces: Vec<String>,
/// Classes named in the constant pool: references, descriptors, signatures, annotation types.
pub refs: BTreeSet<String>,
/// What other classes compile against: non-private, non-synthetic members and their
/// signatures, supertypes, nested classes, permitted subclasses, record components.
pub api: u64,
/// The compile-time constants (`static final` fields with a `ConstantValue`), which javac
/// copies into the classes that use them: a change can't be traced through references.
pub constants: u64,
}
const ACC_PRIVATE: u16 = 0x0002;
const ACC_SYNTHETIC: u16 = 0x1000;
struct Bytes<'a> {
data: &'a [u8],
pos: usize,
}
impl<'a> Bytes<'a> {
fn take(&mut self, n: usize) -> Option<&'a [u8]> {
let end = self.pos.checked_add(n)?;
let slice = self.data.get(self.pos..end)?;
self.pos = end;
Some(slice)
}
fn u1(&mut self) -> Option<u8> {
Some(self.take(1)?[0])
}
fn u2(&mut self) -> Option<u16> {
let b = self.take(2)?;
Some(u16::from_be_bytes([b[0], b[1]]))
}
fn u4(&mut self) -> Option<u32> {
let b = self.take(4)?;
Some(u32::from_be_bytes([b[0], b[1], b[2], b[3]]))
}
}
#[derive(Clone, Debug)]
enum Entry {
Empty,
Utf8(String),
Class(u16),
String(u16),
/// Integer, float, long, double: the raw bytes.
Number(Vec<u8>),
NameAndType(u16),
MethodType(u16),
Other,
}
struct Pool(Vec<Entry>);
impl Pool {
fn utf8(&self, index: u16) -> Option<&str> {
match self.0.get(index as usize)? {
Entry::Utf8(s) => Some(s),
_ => None,
}
}
fn class(&self, index: u16) -> Option<&str> {
match self.0.get(index as usize)? {
Entry::Class(name) => self.utf8(*name),
_ => None,
}
}
/// A `ConstantValue`'s value, as bytes.
fn constant(&self, index: u16) -> Option<Vec<u8>> {
match self.0.get(index as usize)? {
Entry::Number(bytes) => Some(bytes.clone()),
Entry::String(utf8) => Some(self.utf8(*utf8)?.as_bytes().to_vec()),
_ => None,
}
}
}
/// FNV-1a: stable across Rust versions, so recorded fingerprints stay comparable.
#[derive(Clone, Copy)]
struct Fnv(u64);
impl Fnv {
fn new() -> Self {
Fnv(0xcbf2_9ce4_8422_2325)
}
fn bytes(&mut self, bytes: &[u8]) {
for b in bytes {
self.0 = (self.0 ^ u64::from(*b)).wrapping_mul(0x100_0000_01b3);
}
// A separator, so `ab`+`c` and `a`+`bc` differ.
self.0 = (self.0 ^ 0xff).wrapping_mul(0x100_0000_01b3);
}
fn str(&mut self, s: &str) {
self.bytes(s.as_bytes());
}
fn u16(&mut self, v: u16) {
self.bytes(&v.to_be_bytes());
}
}
/// Adds the class names a descriptor or signature mentions (`Lcom/acme/Order<Lx/Y;>;`).
fn descriptor_refs(text: &str, out: &mut BTreeSet<String>) {
let bytes = text.as_bytes();
let mut i = 0;
while i < bytes.len() {
if bytes[i] == b'L'
&& (i == 0
|| matches!(
bytes[i - 1],
b'(' | b')'
| b'['
| b';'
| b'<'
| b'>'
| b'+'
| b'-'
| b':'
| b'*'
| b'I'
| b'J'
| b'Z'
| b'B'
| b'C'
| b'S'
| b'F'
| b'D'
| b'V'
| b'^'
))
{
let start = i + 1;
let mut end = start;
while end < bytes.len() && !matches!(bytes[end], b';' | b'<' | b'.') {
end += 1;
}
if end < bytes.len() && end > start {
let name = &text[start..end];
if name.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'/' | b'$' | b'_') || b >= 0x80) {
out.insert(name.to_owned());
}
}
i = end;
} else {
i += 1;
}
}
}
fn class_ref(name: &str, out: &mut BTreeSet<String>) {
if name.starts_with('[') {
descriptor_refs(name, out);
} else {
out.insert(name.to_owned());
}
}
struct Member {
access: u16,
name: String,
descriptor: String,
/// Fingerprint of the attributes that are part of the API.
extra: u64,
constant: Option<Vec<u8>>,
}
fn attributes(r: &mut Bytes, pool: &Pool, mut on: impl FnMut(&str, &[u8])) -> Option<()> {
let count = r.u2()?;
for _ in 0..count {
let name = pool.utf8(r.u2()?)?.to_owned();
let len = r.u4()? as usize;
let body = r.take(len)?;
on(&name, body);
}
Some(())
}
fn members(r: &mut Bytes, pool: &Pool, refs: &mut BTreeSet<String>) -> Option<Vec<Member>> {
let count = r.u2()?;
let mut out = Vec::with_capacity(count as usize);
for _ in 0..count {
let access = r.u2()?;
let name = pool.utf8(r.u2()?)?.to_owned();
let descriptor = pool.utf8(r.u2()?)?.to_owned();
descriptor_refs(&descriptor, refs);
let mut extra = Fnv::new();
let mut constant = None;
attributes(r, pool, |attr, body| {
let mut b = Bytes { data: body, pos: 0 };
match attr {
"Signature" => {
if let Some(sig) = b.u2().and_then(|i| pool.utf8(i)) {
descriptor_refs(sig, refs);
extra.str("S");
extra.str(sig);
}
}
"ConstantValue" => constant = b.u2().and_then(|i| pool.constant(i)),
"Exceptions" => {
let mut names: Vec<&str> = Vec::new();
if let Some(n) = b.u2() {
for _ in 0..n {
if let Some(c) = b.u2().and_then(|i| pool.class(i)) {
names.push(c);
}
}
}
names.sort_unstable();
extra.str("E");
for n in names {
extra.str(n);
}
}
// An annotation element's default value is compiled into its uses.
"AnnotationDefault" => {
extra.str("D");
element_value(&mut b, pool, refs, &mut extra);
}
_ => {}
}
})?;
out.push(Member { access, name, descriptor, extra: extra.0, constant });
}
Some(out)
}
/// Parses a class file; `None` when it isn't a well-formed one.
pub fn parse(data: &[u8]) -> Option<ClassFile> {
let mut r = Bytes { data, pos: 0 };
if r.u4()? != 0xCAFE_BABE {
return None;
}
r.u2()?;
r.u2()?;
let count = r.u2()?;
let mut entries = vec![Entry::Empty];
let mut i = 1;
while i < count {
let tag = r.u1()?;
let entry = match tag {
1 => {
let len = r.u2()? as usize;
Entry::Utf8(String::from_utf8_lossy(r.take(len)?).into_owned())
}
3 | 4 => Entry::Number(r.take(4)?.to_vec()),
5 | 6 => Entry::Number(r.take(8)?.to_vec()),
7 => Entry::Class(r.u2()?),
8 => Entry::String(r.u2()?),
9..=11 => {
r.take(4)?;
Entry::Other
}
12 => {
r.u2()?;
Entry::NameAndType(r.u2()?)
}
15 => {
r.take(3)?;
Entry::Other
}
16 => Entry::MethodType(r.u2()?),
17 | 18 => {
r.take(4)?;
Entry::Other
}
19 | 20 => {
r.take(2)?;
Entry::Other
}
_ => return None,
};
let wide = matches!(tag, 5 | 6);
entries.push(entry);
i += 1;
if wide {
entries.push(Entry::Empty);
i += 1;
}
}
let pool = Pool(entries);
let mut refs = BTreeSet::new();
for entry in &pool.0 {
match entry {
Entry::Class(name) => class_ref(pool.utf8(*name)?, &mut refs),
Entry::NameAndType(descriptor) | Entry::MethodType(descriptor) => {
descriptor_refs(pool.utf8(*descriptor)?, &mut refs)
}
_ => {}
}
}
let access = r.u2()?;
let name = pool.class(r.u2()?)?.to_owned();
let super_index = r.u2()?;
let super_name = if super_index == 0 { None } else { Some(pool.class(super_index)?.to_owned()) };
let mut interfaces = Vec::new();
for _ in 0..r.u2()? {
interfaces.push(pool.class(r.u2()?)?.to_owned());
}
let fields = members(&mut r, &pool, &mut refs)?;
let methods = members(&mut r, &pool, &mut refs)?;
let mut api = Fnv::new();
// ACC_SUPER and ACC_SYNTHETIC say nothing about what compiles against the class.
api.u16(access & !(0x0020 | ACC_SYNTHETIC));
api.str(&name);
api.str(super_name.as_deref().unwrap_or(""));
let mut sorted = interfaces.clone();
sorted.sort();
for i in &sorted {
api.str(i);
}
let mut class_attrs: Vec<(String, u64)> = Vec::new();
attributes(&mut r, &pool, |attr, body| {
let mut b = Bytes { data: body, pos: 0 };
let mut h = Fnv::new();
match attr {
"Signature" => {
if let Some(sig) = b.u2().and_then(|i| pool.utf8(i)) {
descriptor_refs(sig, &mut refs);
h.str(sig);
}
}
"PermittedSubclasses" => {
let mut names = Vec::new();
for _ in 0..b.u2().unwrap_or(0) {
if let Some(c) = b.u2().and_then(|i| pool.class(i)) {
names.push(c.to_owned());
}
}
names.sort();
names.iter().for_each(|n| h.str(n));
}
"Record" => {
for _ in 0..b.u2().unwrap_or(0) {
let (Some(n), Some(d)) = (b.u2().and_then(|i| pool.utf8(i)), b.u2().and_then(|i| pool.utf8(i)))
else {
break;
};
h.str(n);
h.str(d);
let mut component = |attr: &str, body: &[u8]| {
if attr == "Signature"
&& let Some(sig) = (Bytes { data: body, pos: 0 }).u2().and_then(|i| pool.utf8(i))
{
h.str(sig);
}
};
if attributes(&mut b, &pool, &mut component).is_none() {
break;
}
}
}
// Nested classes this class declares, and their access.
"InnerClasses" => {
let mut nested = Vec::new();
for _ in 0..b.u2().unwrap_or(0) {
let (Some(inner), Some(outer), Some(_), Some(flags)) = (b.u2(), b.u2(), b.u2(), b.u2()) else {
break;
};
let inner = pool.class(inner).unwrap_or("");
if outer != 0 && pool.class(outer) == Some(name.as_str()) && flags & ACC_PRIVATE == 0 {
nested.push(format!("{inner}:{flags}"));
}
}
nested.sort();
nested.iter().for_each(|n| h.str(n));
}
"RuntimeVisibleAnnotations" | "RuntimeInvisibleAnnotations" => {
// Annotation types are dependencies; their values aren't API.
annotation_types(body, &pool, &mut refs);
return;
}
_ => return,
}
class_attrs.push((attr.to_owned(), h.0));
})?;
class_attrs.sort();
for (attr, h) in &class_attrs {
api.str(attr);
api.bytes(&h.to_be_bytes());
}
let mut constants = Fnv::new();
let mut api_members: Vec<(u8, &str, &str, u16, u64)> = Vec::new();
for (kind, list) in [(0u8, &fields), (1u8, &methods)] {
for m in list.iter() {
if kind == 0
&& let Some(value) = &m.constant
{
// Private constants are inlined too, but only in their own class.
if m.access & ACC_PRIVATE == 0 {
constants.str(&m.name);
constants.str(&m.descriptor);
constants.bytes(value);
}
}
if m.access & (ACC_PRIVATE | ACC_SYNTHETIC) != 0 || m.name == "<clinit>" {
continue;
}
api_members.push((kind, &m.name, &m.descriptor, m.access & !ACC_SYNTHETIC, m.extra));
}
}
api_members.sort();
for (kind, name, descriptor, access, extra) in api_members {
api.bytes(&[kind]);
api.str(name);
api.str(descriptor);
api.u16(access);
api.bytes(&extra.to_be_bytes());
}
refs.remove(&name);
refs.retain(|r| !r.starts_with("java/"));
Some(ClassFile { name, super_name, interfaces, refs, api: api.0, constants: constants.0 })
}
/// Adds the types of the annotations in a `Runtime*Annotations` attribute.
fn annotation_types(body: &[u8], pool: &Pool, refs: &mut BTreeSet<String>) {
let mut b = Bytes { data: body, pos: 0 };
let Some(count) = b.u2() else { return };
let mut ignored = Fnv::new();
for _ in 0..count {
if annotation(&mut b, pool, refs, &mut ignored).is_none() {
return;
}
}
}
fn annotation(b: &mut Bytes, pool: &Pool, refs: &mut BTreeSet<String>, h: &mut Fnv) -> Option<()> {
let ty = pool.utf8(b.u2()?)?;
descriptor_refs(ty, refs);
h.str(ty);
for _ in 0..b.u2()? {
h.str(pool.utf8(b.u2()?)?);
element_value(b, pool, refs, h)?;
}
Some(())
}
/// An annotation element value: its class names go to `refs`, its value (resolved, not the
/// constant pool indices) to `h`.
fn element_value(b: &mut Bytes, pool: &Pool, refs: &mut BTreeSet<String>, h: &mut Fnv) -> Option<()> {
let tag = b.u1()?;
h.bytes(&[tag]);
match tag {
b'B' | b'C' | b'D' | b'F' | b'I' | b'J' | b'S' | b'Z' => h.bytes(&pool.constant(b.u2()?)?),
b's' => h.str(pool.utf8(b.u2()?)?),
b'e' => {
let ty = pool.utf8(b.u2()?)?;
descriptor_refs(ty, refs);
h.str(ty);
h.str(pool.utf8(b.u2()?)?);
}
b'c' => {
let ty = pool.utf8(b.u2()?)?;
descriptor_refs(ty, refs);
h.str(ty);
}
b'@' => annotation(b, pool, refs, h)?,
b'[' => {
for _ in 0..b.u2()? {
element_value(b, pool, refs, h)?;
}
}
_ => return None,
}
Some(())
}
/// The simple name of a class (`com/acme/Order$Line` → `Line`), which a new class can shadow.
pub fn simple_name(name: &str) -> &str {
let tail = name.rsplit('/').next().unwrap_or(name);
tail.rsplit('$').next().unwrap_or(tail)
}
+145
Переглянути файл
@@ -0,0 +1,145 @@
// OpenIDEA's Java build of a Gradle build (ide_build::jbuild). With -Popenidea.build.output=<dir>,
// every Java source set writes its classes and resources to <dir>/[<group>.]<project>/classes|test-classes,
// so neither the language server nor a terminal `gradle` writes what the IDE runs. The task
// `openideaBuildModel` (-Popenidea.build.model=<file>) runs what generates sources, processes the
// resources and writes, as JSON, each source set's roots, classpaths and how JavaCompile compiles it:
// the same model the Maven extension writes (java/java-build, BuildModel).
import groovy.json.JsonOutput
import org.gradle.api.tasks.compile.AbstractCompile
import org.gradle.api.tasks.compile.JavaCompile
import org.gradle.jvm.tasks.Jar
def property = { String name -> gradle.startParameter.projectProperties[name] }
def outRoot = property('openidea.build.output')
if (outRoot == null || gradle.parent != null) return
// The project's name in the build: unique, unlike `name`.
def nameOf = { Project p -> p == p.rootProject ? p.name : p.path.substring(1).replace(':', '.') }
def outputOf = { Project p, String set ->
def folder = p.group ? "${p.group}.${nameOf(p)}" : nameOf(p)
new File(outRoot, folder + '/' + (set == 'main' ? 'classes' : 'test-classes'))
}
def javaSets = { Project p ->
def sets = p.extensions.findByName('sourceSets')
sets == null ? [] : ['main', 'test'].collect { sets.findByName(it) }.findAll { it != null }
}
gradle.projectsEvaluated {
def root = gradle.rootProject
root.allprojects.each { p ->
javaSets(p).each { ss ->
def out = outputOf(p, ss.name)
ss.java.destinationDirectory.set(out)
ss.output.resourcesDir = out
p.tasks.named(ss.processResourcesTaskName).configure { destinationDir = out }
}
}
root.tasks.register('openideaBuildModel') {
// What compiling needs from the same project (generated sources), and the resources.
dependsOn {
root.allprojects.collectMany { p ->
javaSets(p).collectMany { ss ->
def compile = p.tasks.getByName(ss.compileJavaTaskName)
def generators = compile.taskDependencies.getDependencies(compile).findAll {
it.project == p && !(it instanceof AbstractCompile) && !(it instanceof Jar)
}
generators + [p.tasks.getByName(ss.processResourcesTaskName)]
}
}
}
doLast {
// Project artifacts resolve to the projects' outputs.
def artifacts = [:]
root.allprojects.each { p ->
def main = javaSets(p).find { it.name == 'main' }
if (main == null) return
def jar = p.tasks.findByName('jar')
if (jar instanceof Jar) artifacts[jar.archiveFile.get().asFile.canonicalPath] = outputOf(p, 'main')
}
def files = { collection ->
def out = []
try {
collection?.files?.each { f ->
def mapped = artifacts[f.canonicalPath] ?: f
if (!out.contains(mapped.canonicalPath)) out << mapped.canonicalPath
}
} catch (e) {
out << "!${e.message}".toString()
}
out
}
def included = gradle.includedBuilds.collect { it.name }
def projects = root.allprojects.findAll { !javaSets(it).isEmpty() }.collect { p ->
def problems = included.isEmpty() ? [] : ["it is a composite build (${included.join(', ')})".toString()]
def others = p.tasks.withType(AbstractCompile).findAll {
!(it instanceof JavaCompile) && it.name ==~ /(?i)compile.*(Kotlin|Groovy|Scala|Aspectj).*/
}.collect { "${it.class.name.replace('_Decorated', '')}@${it.name}".toString() }
def setModel = { String name ->
def ss = javaSets(p).find { it.name == name }
if (ss == null) return [sourceRoots: [], output: outputOf(p, name).path, classpath: [], runtimeClasspath: []]
JavaCompile compile = p.tasks.getByName(ss.compileJavaTaskName)
def o = compile.options
def classpath = files(compile.classpath)
def runtime = files(ss.runtimeClasspath)
(classpath + runtime).findAll { it.startsWith('!') }.each { problems << "Cannot resolve the dependencies: ${it.substring(1)}".toString() }
def processorPath = files(o.annotationProcessorPath)
def processorProblems = processorPath.findAll { it.startsWith('!') }
def projectProcessors = processorPath.findAll { path -> artifacts.values().any { it.canonicalPath == path } }
def home = null
try { home = compile.javaCompiler.orNull?.metadata?.installationPath?.asFile?.canonicalPath } catch (ignored) {}
[
sourceRoots: ss.java.srcDirs.collect { it.canonicalPath },
output: outputOf(p, name).canonicalPath,
classpath: classpath.findAll { !it.startsWith('!') },
runtimeClasspath: runtime.findAll { !it.startsWith('!') },
resources: ss.resources.srcDirs.collect { [directory: it.canonicalPath, filtering: false] },
compiler: [
compilerId: 'javac',
source: compile.sourceCompatibility,
target: compile.targetCompatibility,
release: o.release.orNull?.toString(),
encoding: o.encoding,
debug: o.debug,
debuglevel: o.debugOptions.debugLevel,
showWarnings: o.warnings,
showDeprecation: o.deprecation,
fork: home != null,
executable: home == null ? null : new File(home, 'bin/javac').path,
generatedSourcesDirectory: o.generatedSourceOutputDirectory.asFile.orNull?.canonicalPath,
includes: ss.java.includes as List,
excludes: ss.java.excludes as List,
compilerArgs: o.allCompilerArgs.collect { it.toString() },
processorPath: processorProblems.isEmpty() && projectProcessors.isEmpty() ? processorPath : null,
processorPathError: !processorProblems.isEmpty()
? processorProblems[0].substring(1)
: (projectProcessors.isEmpty() ? null : 'its annotation processors are built in the same build'),
],
]
}
def mainModel = setModel('main')
def testModel = setModel('test')
// Gradle compiles tests against the main classes: they're the main output here.
[
dir: p.projectDir.canonicalPath,
groupId: (p.group ?: '').toString(),
artifactId: nameOf(p),
version: p.version.toString(),
packaging: 'jar',
main: mainModel,
test: testModel,
otherCompilers: others,
testGenerators: [],
problems: problems,
gradlePath: p.path,
]
}
def modelFile = property('openidea.build.model')
if (modelFile != null) {
def file = new File(modelFile)
def temporary = new File(file.parentFile, file.name + '.tmp')
temporary.text = JsonOutput.toJson([version: 1, projects: projects])
temporary.renameTo(file) || { file.delete(); temporary.renameTo(file) }()
}
}
}
}
+216
Переглянути файл
@@ -0,0 +1,216 @@
//! Class-level incremental compilation (#4078 step 3). Each source set records, per class it
//! compiled, the source it came from, its supertypes, the classes its constant pool names and
//! fingerprints of its API and constants ([`super::classfile`]). A build compiles the changed
//! sources, then the sources of classes that refer to a class whose API changed (or to a
//! subclass of one), round after round until no API changes. Sets compiled against this one
//! read its log of API changes; a changed compile-time constant, which javac copies into the
//! classes that use it, recompiles the whole set and every set compiled against it.
use super::*;
use std::collections::BTreeSet;
#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq)]
pub(super) struct ClassRecord {
/// The source javac compiled it from; `None` for classes an annotation processor wrote
/// without naming an originating source.
pub source: Option<PathBuf>,
pub file: PathBuf,
pub super_name: Option<String>,
#[serde(default)]
pub interfaces: Vec<String>,
#[serde(default)]
pub refs: Vec<String>,
pub api: u64,
pub constants: u64,
}
impl ClassRecord {
pub fn new(class: classfile::ClassFile, file: PathBuf, source: Option<PathBuf>) -> (String, Self) {
let record = ClassRecord {
source,
file,
super_name: class.super_name,
interfaces: class.interfaces,
refs: class.refs.into_iter().collect(),
api: class.api,
constants: class.constants,
};
(class.name, record)
}
fn has_constants(&self) -> bool {
self.constants != NO_CONSTANTS
}
}
/// The constant fingerprint of a class without compile-time constants.
pub(super) const NO_CONSTANTS: u64 = 0xcbf2_9ce4_8422_2325;
/// The classes whose API one compilation of a set changed.
#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq)]
pub(super) struct ApiChange {
/// The set's generation before and after the compilation.
pub since: u64,
pub generation: u64,
pub classes: Vec<String>,
/// Everything counts as changed: a constant changed, or there was nothing to compare with.
pub all: bool,
}
/// How many compilations' API changes a set keeps for the sets compiled against it; one that
/// fell further behind compiles from scratch.
const CHANGE_LOG: usize = 64;
/// The inputs of a source set that, when changed, compile it from scratch.
#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq)]
pub(super) struct SetStamp {
pub options: Vec<String>,
/// Classpath entries outside the reactor's outputs, with their stamps (folders have none).
pub libraries: Vec<(PathBuf, Option<FileStamp>)>,
/// The reactor outputs on the classpath, in order.
pub reactor: Vec<PathBuf>,
pub processor_path: Vec<(PathBuf, Option<FileStamp>)>,
pub java_home: PathBuf,
}
#[derive(Debug, Default, Deserialize, Serialize)]
pub(super) struct SetState {
pub stamp: SetStamp,
/// The sources as of the last compilation.
pub sources: BTreeMap<PathBuf, FileStamp>,
/// Changes whenever the set's classes do.
pub generation: u64,
/// The generation of each reactor output it was compiled against.
pub upstream: BTreeMap<PathBuf, u64>,
pub classes: BTreeMap<String, ClassRecord>,
/// Sources a failed compilation left uncompiled.
pub dirty: BTreeSet<PathBuf>,
pub changes: Vec<ApiChange>,
/// Sources annotation processors wrote, and other files they wrote without an originating
/// source (`META-INF/services`…): processors that aggregate. While there are any, a change
/// compiles the set from scratch.
pub generated: Vec<PathBuf>,
pub unowned: Vec<PathBuf>,
pub success: bool,
}
impl SetState {
/// The classes whose API changed since generation `since`; `None` when unknown (the log
/// doesn't reach back that far) or when everything counts as changed.
pub fn changes_since(&self, since: u64) -> Option<BTreeSet<String>> {
let mut changed = BTreeSet::new();
let mut at = since;
while at != self.generation {
let change = self.changes.iter().find(|c| c.since == at)?;
if change.all {
return None;
}
changed.extend(change.classes.iter().cloned());
at = change.generation;
}
Some(changed)
}
pub fn log(&mut self, generation: u64, classes: BTreeSet<String>, all: bool) {
self.changes.push(ApiChange {
since: self.generation,
generation,
classes: classes.into_iter().collect(),
all,
});
if self.changes.len() > CHANGE_LOG {
self.changes.drain(..self.changes.len() - CHANGE_LOG);
}
self.generation = generation;
}
}
pub(super) fn load_state(path: &Path) -> Option<SetState> {
serde_json::from_slice(&std::fs::read(path).ok()?).ok()
}
/// `seeds` and the classes of `classes` that extend or implement one of them, transitively:
/// a class that inherits a changed member changes for the classes that use it.
pub(super) fn with_subclasses(classes: &BTreeMap<String, ClassRecord>, seeds: &BTreeSet<String>) -> BTreeSet<String> {
let mut out = seeds.clone();
loop {
let before = out.len();
for (name, record) in classes {
if !out.contains(name)
&& (record.super_name.as_ref().is_some_and(|s| out.contains(s))
|| record.interfaces.iter().any(|i| out.contains(i)))
{
out.insert(name.clone());
}
}
if out.len() == before {
return out;
}
}
}
/// The sources of the classes that refer to one of `affected`.
pub(super) fn dependent_sources(
classes: &BTreeMap<String, ClassRecord>,
affected: &BTreeSet<String>,
) -> BTreeSet<PathBuf> {
if affected.is_empty() {
return BTreeSet::new();
}
classes
.iter()
.filter(|(name, r)| affected.contains(*name) || r.refs.iter().any(|x| affected.contains(x)))
.filter_map(|(_, r)| r.source.clone())
.collect()
}
/// The sources of the classes that refer to a class with the same simple name as one of
/// `added`: a new class can take a simple name over from an on-demand import.
pub(super) fn shadowed_sources(classes: &BTreeMap<String, ClassRecord>, added: &BTreeSet<String>) -> BTreeSet<PathBuf> {
let names: BTreeSet<&str> = added.iter().map(|n| classfile::simple_name(n)).collect();
if names.is_empty() {
return BTreeSet::new();
}
classes
.iter()
.filter(|(name, r)| {
!added.contains(*name)
&& r.refs.iter().any(|x| !added.contains(x) && names.contains(classfile::simple_name(x)))
})
.filter_map(|(_, r)| r.source.clone())
.collect()
}
/// What one round's classes changed, compared with the classes the round replaced.
#[derive(Debug, Default)]
pub(super) struct RoundDiff {
pub api: BTreeSet<String>,
pub added: BTreeSet<String>,
pub constants: bool,
}
pub(super) fn diff(old: &BTreeMap<String, ClassRecord>, new: &BTreeMap<String, ClassRecord>) -> RoundDiff {
let mut out = RoundDiff::default();
for (name, record) in new {
match old.get(name) {
Some(before) => {
if before.api != record.api {
out.api.insert(name.clone());
}
if before.constants != record.constants {
out.constants = true;
}
}
None => {
out.api.insert(name.clone());
out.added.insert(name.clone());
}
}
}
for (name, before) in old {
if !new.contains_key(name) {
out.api.insert(name.clone());
out.constants |= before.has_constants();
}
}
out
}
+263
Переглянути файл
@@ -0,0 +1,263 @@
//! Resident javac processes (`java/java-build`, `ai.openidea.javac.Server`): one JVM per JDK
//! and JVM options, kept warm between builds, compiling one request at a time in process.
use super::*;
use std::io::{BufRead, BufReader, Write};
use std::process::{Child, ChildStdin, Command, Stdio};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::mpsc;
use std::sync::{Arc, Mutex};
use std::time::Duration;
/// A message of the server about one request.
#[derive(Clone, Debug, Deserialize, PartialEq)]
#[serde(tag = "kind", rename_all = "kebab-case", rename_all_fields = "camelCase")]
pub enum Reply {
Diagnostic {
severity: String,
path: Option<PathBuf>,
/// 1-based.
line: Option<u32>,
/// 0-based UTF-16.
column: Option<u32>,
end_line: Option<u32>,
end_column: Option<u32>,
code: Option<String>,
message: String,
},
/// A class (or resource) file javac wrote, and the source it came from.
Output {
path: PathBuf,
source: Option<PathBuf>,
},
/// A source file an annotation processor wrote.
Generated {
path: PathBuf,
source: Option<PathBuf>,
},
OutputText {
text: String,
},
Done {
success: bool,
cancelled: bool,
},
}
#[derive(Debug, Serialize)]
struct Request<'a> {
id: u64,
op: &'static str,
options: &'a [String],
sources: &'a [PathBuf],
encoding: Option<&'a str>,
}
#[derive(Clone, Debug, Hash, PartialEq, Eq)]
pub struct ServerKey {
pub java_home: PathBuf,
/// Options of the compiler's JVM (`.mvn/jvm.config`: `--add-opens` for processors).
pub jvm_args: Vec<String>,
}
type Pending = Arc<Mutex<HashMap<u64, mpsc::Sender<Reply>>>>;
pub struct JavacServer {
child: Mutex<Child>,
stdin: Mutex<ChildStdin>,
pending: Pending,
alive: Arc<AtomicBool>,
next: AtomicU64,
pub version: String,
}
impl JavacServer {
fn start(jar: &Path, key: &ServerKey) -> IdeResult<Self> {
let java = key.java_home.join("bin").join(if cfg!(windows) { "java.exe" } else { "java" });
let mut cmd = Command::new(&java);
cmd.args(&key.jvm_args)
.args(["-XX:+UseSerialGC", "-XX:TieredStopAtLevel=1", "-Dfile.encoding=UTF-8", "-cp"])
.arg(jar)
.arg("ai.openidea.javac.Server")
.env("JAVA_HOME", &key.java_home)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::null());
ide_core::process::prepare(&mut cmd);
ide_core::process::own_group(&mut cmd);
let mut child =
cmd.spawn().map_err(|e| IdeError::unavailable(format!("Cannot start javac ({}): {e}", java.display())))?;
let stdin = child.stdin.take().expect("piped");
let stdout = child.stdout.take().expect("piped");
let pending: Pending = Arc::default();
let alive = Arc::new(AtomicBool::new(true));
let (ready_tx, ready_rx) = mpsc::channel::<Result<String, String>>();
{
let (pending, alive) = (pending.clone(), alive.clone());
std::thread::Builder::new()
.name("javac-server".into())
.spawn(move || {
let mut ready = Some(ready_tx);
for line in BufReader::new(stdout).lines() {
let Ok(line) = line else { break };
let Ok(value) = serde_json::from_str::<serde_json::Value>(&line) else { continue };
match value.get("kind").and_then(|k| k.as_str()) {
Some("ready") => {
let version = value.get("version").and_then(|v| v.as_str()).unwrap_or("").to_owned();
if let Some(ready) = ready.take() {
let _ = ready.send(Ok(version));
}
continue;
}
Some("fatal") => {
let message = value.get("message").and_then(|v| v.as_str()).unwrap_or("").to_owned();
if let Some(ready) = ready.take() {
let _ = ready.send(Err(message));
}
continue;
}
_ => {}
}
let Some(id) = value.get("id").and_then(|v| v.as_u64()) else { continue };
let Ok(reply) = serde_json::from_value::<Reply>(value) else { continue };
let done = matches!(reply, Reply::Done { .. });
let mut pending = pending.lock().unwrap();
if let Some(tx) = pending.get(&id) {
let _ = tx.send(reply);
}
if done {
pending.remove(&id);
}
}
alive.store(false, Ordering::SeqCst);
// Requests still waiting learn that the server is gone.
for (_, tx) in pending.lock().unwrap().drain() {
let _ = tx.send(Reply::Diagnostic {
severity: "error".into(),
path: None,
line: None,
column: None,
end_line: None,
end_column: None,
code: None,
message: "The javac process exited".into(),
});
let _ = tx.send(Reply::Done { success: false, cancelled: false });
}
if let Some(ready) = ready.take() {
let _ = ready.send(Err("The javac process exited while starting".into()));
}
})
.map_err(|e| IdeError::internal(e.to_string()))?;
}
let version = match ready_rx.recv_timeout(Duration::from_secs(60)) {
Ok(Ok(version)) => version,
Ok(Err(message)) => {
ide_core::process::kill_tree(&mut child);
return Err(IdeError::unavailable(format!("Cannot start javac ({}): {message}", java.display())));
}
Err(_) => {
ide_core::process::kill_tree(&mut child);
return Err(IdeError::unavailable(format!("javac ({}) did not start", java.display())));
}
};
Ok(JavacServer {
child: Mutex::new(child),
stdin: Mutex::new(stdin),
pending,
alive,
next: AtomicU64::new(1),
version,
})
}
fn alive(&self) -> bool {
self.alive.load(Ordering::SeqCst)
}
fn send(&self, value: &impl Serialize) -> IdeResult<()> {
let mut line = serde_json::to_vec(value).map_err(|e| IdeError::internal(e.to_string()))?;
line.push(b'\n');
let mut stdin = self.stdin.lock().unwrap();
stdin.write_all(&line).and_then(|()| stdin.flush()).map_err(|e| IdeError::internal(format!("javac: {e}")))
}
/// Compiles `sources` with javac `options`, passing each reply to `on_reply`, until the
/// compilation ends. Cancelling stops javac at its next phase.
pub fn compile(
&self,
options: &[String],
sources: &[PathBuf],
encoding: Option<&str>,
cancel: &CancellationToken,
mut on_reply: impl FnMut(&Reply),
) -> IdeResult<bool> {
let id = self.next.fetch_add(1, Ordering::SeqCst);
let (tx, rx) = mpsc::channel();
self.pending.lock().unwrap().insert(id, tx);
if let Err(e) = self.send(&Request { id, op: "compile", options, sources, encoding }) {
self.pending.lock().unwrap().remove(&id);
return Err(e);
}
let mut cancelled = false;
loop {
match rx.recv_timeout(Duration::from_millis(100)) {
Ok(reply) => {
if let Reply::Done { success, cancelled: stopped } = reply {
if stopped || cancelled {
return Err(IdeError::cancelled());
}
return Ok(success);
}
on_reply(&reply);
}
Err(mpsc::RecvTimeoutError::Timeout) => {
if cancel.is_cancelled() && !cancelled {
cancelled = true;
let _ = self.send(&serde_json::json!({ "op": "cancel", "id": id }));
}
}
Err(mpsc::RecvTimeoutError::Disconnected) => {
return Err(IdeError::internal("The javac process exited"));
}
}
}
}
}
impl Drop for JavacServer {
fn drop(&mut self) {
let _ = self.send(&serde_json::json!({ "op": "exit" }));
let mut child = self.child.lock().unwrap();
for _ in 0..20 {
if child.try_wait().ok().flatten().is_some() {
return;
}
std::thread::sleep(Duration::from_millis(50));
}
ide_core::process::kill_tree(&mut child);
}
}
/// The resident javac servers of one IDE process.
#[derive(Default)]
pub struct JavacPool {
servers: Mutex<HashMap<ServerKey, Arc<JavacServer>>>,
}
impl JavacPool {
/// The running server for `key`, started on first use (or after it died).
pub fn server(&self, jar: &Path, key: &ServerKey) -> IdeResult<Arc<JavacServer>> {
let mut servers = self.servers.lock().unwrap();
if let Some(server) = servers.get(key).filter(|s| s.alive()) {
return Ok(server.clone());
}
let server = Arc::new(JavacServer::start(jar, key)?);
servers.insert(key.clone(), server.clone());
Ok(server)
}
/// Stops every server (the project closed).
pub fn shutdown(&self) {
self.servers.lock().unwrap().clear();
}
}
File diff suppressed because it is too large. Load diff
+342
Переглянути файл
@@ -0,0 +1,342 @@
//! The build model of a Maven reactor or Gradle build as the build tool itself configures it,
//! recorded by the prepare run (`java/java-build` `BuildModel`, `gradle-build.init.gradle`), and when that run is due.
use super::*;
use std::fs;
/// `model.json` of the prepare run (see `BuildModel.java`).
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ReactorModel {
pub version: u32,
pub projects: Vec<ProjectModel>,
}
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ProjectModel {
/// Absolute project directory.
pub dir: PathBuf,
pub group_id: String,
pub artifact_id: String,
pub version: String,
pub packaging: String,
pub main: SourceSet,
pub test: SourceSet,
/// Executions in the compile phases that aren't javac (`group:artifact:goal@id`).
#[serde(default)]
pub other_compilers: Vec<String>,
/// Test source generators the prepare run doesn't reach.
#[serde(default)]
pub test_generators: Vec<String>,
#[serde(default)]
pub problems: Vec<String>,
/// The Gradle project path (`:`, `:app`); `None` for Maven.
#[serde(default)]
pub gradle_path: Option<String>,
}
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SourceSet {
pub source_roots: Vec<PathBuf>,
pub output: PathBuf,
pub classpath: Vec<PathBuf>,
pub runtime_classpath: Vec<PathBuf>,
#[serde(default)]
pub resources: Vec<ResourceRoot>,
pub compiler: Option<CompilerConfig>,
}
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ResourceRoot {
pub directory: PathBuf,
#[serde(default)]
pub filtering: bool,
pub target_path: Option<String>,
#[serde(default)]
pub includes: Vec<String>,
#[serde(default)]
pub excludes: Vec<String>,
}
/// maven-compiler-plugin's configuration of one source set, as its mojo was configured.
#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct CompilerConfig {
pub compiler_id: Option<String>,
pub source: Option<String>,
pub target: Option<String>,
pub release: Option<String>,
pub encoding: Option<String>,
pub parameters: Option<bool>,
pub debug: Option<bool>,
pub debuglevel: Option<String>,
pub proc: Option<String>,
pub enable_preview: Option<bool>,
pub fork: Option<bool>,
pub executable: Option<String>,
pub skip: Option<bool>,
pub show_warnings: Option<bool>,
pub show_deprecation: Option<bool>,
pub generated_sources_directory: Option<PathBuf>,
#[serde(default)]
pub includes: Vec<String>,
#[serde(default)]
pub excludes: Vec<String>,
pub annotation_processors: Option<Vec<String>>,
#[serde(default)]
pub compiler_args: Vec<String>,
pub compiler_argument: Option<String>,
#[serde(default)]
pub compiler_arguments: BTreeMap<String, Option<String>>,
pub multi_release_output: Option<bool>,
pub processor_path: Option<Vec<PathBuf>>,
pub processor_path_error: Option<String>,
}
impl ProjectModel {
pub fn key(&self) -> String {
format!("{}:{}", self.group_id, self.artifact_id)
}
pub fn set(&self, test: bool) -> &SourceSet {
if test { &self.test } else { &self.main }
}
/// Why the IDE can't compile this project with javac itself, if it can't.
pub fn unsupported(&self, test: bool) -> Option<String> {
// What the build tool couldn't resolve or read: the model would be incomplete.
if let Some(problem) = self.problems.first() {
return Some(format!("{}: {problem}", self.artifact_id));
}
if !self.other_compilers.is_empty() {
return Some(format!("{} also compiles with {}", self.artifact_id, self.other_compilers.join(", ")));
}
if test && !self.test_generators.is_empty() {
return Some(format!(
"{} generates test sources with {}",
self.artifact_id,
self.test_generators.join(", ")
));
}
for set in [&self.main, &self.test] {
let Some(c) = &set.compiler else { continue };
if c.compiler_id.as_deref().is_some_and(|id| id != "javac") {
return Some(format!("{} compiles with {}", self.artifact_id, c.compiler_id.as_deref().unwrap()));
}
if c.multi_release_output == Some(true) {
return Some(format!("{} is a multi-release jar", self.artifact_id));
}
if let Some(error) = &c.processor_path_error {
return Some(format!("{}: {error}", self.artifact_id));
}
}
None
}
}
/// Where the IDE's build of the reactor at `top_dir` keeps its model and outputs.
pub(super) fn reactor_dir(cache: &Path, top_dir: &str) -> PathBuf {
let base = cache.join("java-build");
if top_dir.is_empty() { base.join("_root") } else { base.join(top_dir) }
}
/// The outputs of every project, `<out>/<groupId>.<artifactId>/classes`, as the extension
/// redirects them (`-Dopenidea.build.output=<out>`).
pub(super) fn output_root(cache: &Path, top_dir: &str) -> PathBuf {
reactor_dir(cache, top_dir).join("out")
}
/// What the recorded model was prepared from.
#[derive(Debug, Deserialize, Serialize)]
pub(super) struct PrepareRecord {
pub fingerprint: LaunchFingerprint,
pub model: ReactorModel,
}
const MODEL_VERSION: u32 = 1;
/// Files the model depends on: the POM chains, settings, toolchains, the Maven launcher,
/// and generator inputs (any `src/<set>/<dir>` that isn't Java sources or resources:
/// `proto`, `antlr4`, `avro`…), but not the Java sources and resources themselves.
pub(super) fn prepare_fingerprint(
root: &Path,
reactor: &[&maven::MavenProject],
step: &BuildStep,
local_repo: Option<PathBuf>,
jar_version: &str,
cancel: &CancellationToken,
) -> IdeResult<Option<LaunchFingerprint>> {
let Some(mut inputs) = maven::model_inputs(root, reactor, local_repo) else { return Ok(None) };
for project in reactor {
let src = subdir(root, &project.dir).join("src");
for set in fs::read_dir(&src).into_iter().flatten().flatten() {
for dir in fs::read_dir(set.path()).into_iter().flatten().flatten() {
let name = dir.file_name();
if dir.path().is_dir() && !matches!(name.to_str(), Some("java" | "resources")) {
inputs.push(dir.path());
}
}
}
}
for dir in step.cwd.ancestors() {
inputs.extend([dir.join(".mvn"), dir.join("mvnw"), dir.join("mvnw.cmd")]);
if dir == root {
break;
}
}
inputs.push(process::program_path(&step.program, &step.env, &step.cwd));
if let Some(home) = dirs::home_dir() {
inputs.extend([home.join(".m2/settings.xml"), home.join(".m2/toolchains.xml")]);
}
if let Some(home) = step.env.get("JAVA_HOME") {
inputs.push(Path::new(home).join("release"));
}
inputs.sort();
inputs.dedup();
let parameters = serde_json::to_string(&(MODEL_VERSION, jar_version, &step.program, &step.args, &step.env))
.map_err(|e| IdeError::internal(e.to_string()))?;
Ok(Some(LaunchFingerprint::new(parameters, fingerprint::scan_all(root, inputs, cancel)?)))
}
pub(super) fn load_record(dir: &Path) -> Option<PrepareRecord> {
let record: PrepareRecord = serde_json::from_slice(&fs::read(dir.join("prepare.json")).ok()?).ok()?;
(record.model.version == MODEL_VERSION).then_some(record)
}
pub(super) fn save_record(dir: &Path, record: &PrepareRecord) -> IdeResult<()> {
write_json(&dir.join("prepare.json"), record)
}
pub(super) fn write_json(path: &Path, value: &impl Serialize) -> IdeResult<()> {
let parent = path.parent().ok_or_else(|| IdeError::internal("no parent folder"))?;
fs::create_dir_all(parent)?;
let mut file = tempfile::NamedTempFile::new_in(parent)?;
serde_json::to_writer(file.as_file_mut(), value).map_err(|e| IdeError::internal(e.to_string()))?;
file.persist(path).map_err(|e| IdeError::from(e.error))?;
Ok(())
}
/// Whether the generated source roots the model lists still exist: `mvn clean` removes them.
pub(super) fn generated_roots_exist(model: &ReactorModel) -> bool {
model.projects.iter().all(|p| {
[&p.main, &p.test].iter().all(|set| {
set.source_roots.iter().all(|root| {
root.exists() || !root.components().any(|c| c.as_os_str() == "target") || is_processor_output(set, root)
})
})
})
}
/// The annotation processors' output folder, which javac writes into and never reads as a root.
pub(super) fn is_processor_output(set: &SourceSet, root: &Path) -> bool {
set.compiler.as_ref().and_then(|c| c.generated_sources_directory.as_deref()).is_some_and(|dir| dir == root)
}
/// A Maven step at the reactor root running `goals` with the IDE's extension loaded.
pub(super) fn maven_step(
root: &Path,
top: &maven::MavenProject,
jar: &Path,
output_root: &Path,
model_file: Option<&Path>,
extra: &[String],
) -> BuildStep {
let mut step = maven_build_step(
&top.command,
&["-B", "-Dstyle.color=never", maven::LOCAL_REPO_TRACKING_ARG],
&subdir(root, &top.dir),
);
step.args.extend(top.options.iter().cloned());
step.args.push(format!("-Dmaven.ext.class.path={}", jar.display()));
step.args.push(format!("-Dopenidea.build.output={}", output_root.display()));
if let Some(file) = model_file {
step.args.push(format!("-Dopenidea.build.model={}", file.display()));
}
step.args.extend(extra.iter().cloned());
step.env = top.env.clone();
step
}
/// The init script that gives a Gradle build the IDE's outputs and writes its model.
const GRADLE_INIT_SCRIPT: &str = include_str!("gradle-build.init.gradle");
/// Writes the init script into the build's state folder, and returns its path.
pub(super) fn gradle_init_script(dir: &Path) -> IdeResult<PathBuf> {
fs::create_dir_all(dir)?;
let path = dir.join("openidea-build.init.gradle");
if fs::read_to_string(&path).ok().as_deref() != Some(GRADLE_INIT_SCRIPT) {
fs::write(&path, GRADLE_INIT_SCRIPT)?;
}
Ok(path)
}
/// A Gradle step at the build's root running `tasks` with the IDE's init script.
pub(super) fn gradle_step(
root: &Path,
g: &crate::GradleModel,
init: &Path,
output_root: &Path,
model_file: Option<&Path>,
tasks: &[String],
) -> BuildStep {
let mut step = gradle_build_step(
&g.command,
// The init script configures the evaluated projects, which a configuration cache skips.
&["--console=plain", "--no-configuration-cache"],
&subdir(root, &g.dir),
);
step.args.extend(["--init-script".to_owned(), init.to_string_lossy().into_owned()]);
step.args.push(format!("-Popenidea.build.output={}", output_root.display()));
if let Some(file) = model_file {
step.args.push(format!("-Popenidea.build.model={}", file.display()));
}
step.args.extend(tasks.iter().cloned());
step.env = g.env.clone();
step
}
/// Files a Gradle build's model depends on: settings and build scripts (with what they apply),
/// properties, the wrapper and catalogs, `buildSrc`, and generator inputs.
pub(super) fn gradle_prepare_fingerprint(
root: &Path,
g: &crate::GradleModel,
step: &BuildStep,
jar_version: &str,
cancel: &CancellationToken,
) -> IdeResult<LaunchFingerprint> {
let mut inputs = crate::gradle::build_files(root, g);
let dir = subdir(root, &g.dir);
inputs.extend([dir.join("buildSrc"), dir.join("gradle"), dir.join("gradlew"), dir.join("gradlew.bat")]);
for project in &g.projects {
let src = subdir(root, &project.dir).join("src");
for set in fs::read_dir(&src).into_iter().flatten().flatten() {
for generator in fs::read_dir(set.path()).into_iter().flatten().flatten() {
let name = generator.file_name();
if generator.path().is_dir() && !matches!(name.to_str(), Some("java" | "resources")) {
inputs.push(generator.path());
}
}
}
}
inputs.push(process::program_path(&step.program, &step.env, &step.cwd));
if let Some(home) = dirs::home_dir() {
inputs.push(home.join(".gradle/gradle.properties"));
inputs.push(home.join(".gradle/init.d"));
}
if let Some(home) = step.env.get("JAVA_HOME") {
inputs.push(Path::new(home).join("release"));
}
inputs.sort();
inputs.dedup();
let parameters =
serde_json::to_string(&(MODEL_VERSION, jar_version, GRADLE_INIT_SCRIPT, &step.program, &step.args, &step.env))
.map_err(|e| IdeError::internal(e.to_string()))?;
Ok(LaunchFingerprint::new(parameters, fingerprint::scan_all(root, inputs, cancel)?))
}
pub(super) fn read_model(path: &Path) -> IdeResult<ReactorModel> {
let bytes = fs::read(path).map_err(|e| IdeError::internal(format!("The build wrote no model ({e})")))?;
serde_json::from_slice(&bytes).map_err(|e| IdeError::internal(format!("Unreadable build model: {e}")))
}
+544
Переглянути файл
@@ -0,0 +1,544 @@
use super::*;
use crate::BuildModel;
use std::fs;
use std::sync::Mutex as StdMutex;
const JAR: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/../../java/java-build/openidea-java-build.jar");
fn write(root: &Path, rel: &str, text: &str) {
let path = root.join(rel);
fs::create_dir_all(path.parent().unwrap()).unwrap();
fs::write(path, text).unwrap();
}
/// A JDK (`JAVA_HOME`) and Maven on the search path, else `None` (the test is skipped).
fn tools() -> Option<(PathBuf, PathBuf)> {
let home = std::env::var_os("JAVA_HOME").map(PathBuf::from).filter(|h| h.join("bin").is_dir())?;
let mvn = ide_core::process::find_executable("mvn", &ide_core::tool_path::search_path())?;
Some((home, mvn))
}
const ROOT_POM: &str = r#"<project><modelVersion>4.0.0</modelVersion><groupId>t</groupId><artifactId>root</artifactId><version>1</version><packaging>pom</packaging>
<modules><module>lib</module><module>app</module></modules>
<properties><maven.compiler.release>11</maven.compiler.release><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties>
<build><pluginManagement><plugins><plugin><artifactId>maven-compiler-plugin</artifactId><version>3.13.0</version>
<configuration><parameters>true</parameters></configuration></plugin></plugins></pluginManagement></build></project>"#;
const LIB_POM: &str = r#"<project><modelVersion>4.0.0</modelVersion><parent><groupId>t</groupId><artifactId>root</artifactId><version>1</version></parent><artifactId>lib</artifactId></project>"#;
const APP_POM: &str = r#"<project><modelVersion>4.0.0</modelVersion><parent><groupId>t</groupId><artifactId>root</artifactId><version>1</version></parent><artifactId>app</artifactId>
<dependencies><dependency><groupId>t</groupId><artifactId>lib</artifactId><version>1</version></dependency></dependencies>
<build><resources><resource><directory>src/main/resources</directory><filtering>true</filtering></resource></resources></build></project>"#;
/// A `lib` ← `app` reactor built by the IDE's Java build with a real Maven and JDK.
struct Fixture {
_tmp: tempfile::TempDir,
root: PathBuf,
cache: PathBuf,
model: BuildModel,
/// Where the build keeps its state under the cache (`Reactor::key`).
key: &'static str,
service: JavaBuildService,
events: StdMutex<Vec<BuildEvent>>,
}
impl Fixture {
fn new(files: &[(&str, &str)]) -> Option<Self> {
let Some((home, mvn)) = tools() else {
eprintln!("skipped: needs JAVA_HOME and mvn");
return None;
};
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap();
for (rel, text) in
[("pom.xml", ROOT_POM), ("lib/pom.xml", LIB_POM), ("app/pom.xml", APP_POM)].iter().chain(files)
{
write(&root, rel, text);
}
let cache = root.join(".cache");
let mut model = crate::load(&root, &cache, None);
for p in &mut model.maven.as_mut().unwrap().projects {
p.command = mvn.to_string_lossy().into_owned();
p.env.insert("JAVA_HOME".into(), home.to_string_lossy().into_owned());
}
Some(Fixture {
_tmp: tmp,
root,
cache,
model,
key: "",
service: JavaBuildService::default(),
events: StdMutex::default(),
})
}
/// The same `lib` ← `app` build with Gradle (`OPENIDEA_TEST_GRADLE`, else `gradle` on the
/// search path).
fn gradle(files: &[(&str, &str)]) -> Option<Self> {
let home = std::env::var_os("JAVA_HOME").map(PathBuf::from).filter(|h| h.join("bin").is_dir());
let gradle = std::env::var_os("OPENIDEA_TEST_GRADLE")
.map(PathBuf::from)
.or_else(|| ide_core::process::find_executable("gradle", &ide_core::tool_path::search_path()));
let (Some(home), Some(gradle)) = (home, gradle) else {
eprintln!("skipped: needs JAVA_HOME and gradle (OPENIDEA_TEST_GRADLE)");
return None;
};
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap();
let build = [
("settings.gradle", "rootProject.name = 'root'\ninclude 'lib', 'app'\n"),
(
"build.gradle",
"subprojects {\n apply plugin: 'java'\n group = 't'\n tasks.withType(JavaCompile).configureEach { options.release = 11; options.encoding = 'UTF-8' }\n}\n",
),
("lib/build.gradle", ""),
(
"app/build.gradle",
"dependencies { implementation project(':lib') }\nprocessResources { filesMatching('*.properties') { expand(version: '1') } }\n",
),
];
for (rel, text) in build.iter().chain(files) {
write(&root, rel, text);
}
let cache = root.join(".cache");
let mut model = crate::load(&root, &cache, None);
assert_eq!(model.gradle.len(), 1, "{model:?}");
let g = &mut model.gradle[0];
g.command = gradle.to_string_lossy().into_owned();
g.env.insert("JAVA_HOME".into(), home.to_string_lossy().into_owned());
Some(Fixture {
_tmp: tmp,
root,
cache,
model,
key: "_gradle",
service: JavaBuildService::default(),
events: StdMutex::default(),
})
}
fn write(&self, rel: &str, text: &str) {
write(&self.root, rel, text);
}
fn out(&self, rel: &str) -> PathBuf {
model::output_root(&self.cache, self.key).join(rel)
}
/// Builds the launch of `app` (its tests when `test`).
fn launch(&self, test: bool) -> LaunchOutputs {
self.build(Target::Launch { module: &self.root.join("app"), test })
}
fn build(&self, target: Target) -> LaunchOutputs {
let jdk = |_: Option<u32>| None;
let build = JavaBuild {
root: &self.root,
model: &self.model,
cache: &self.cache,
jar: Path::new(JAR),
jar_version: "test",
local_repo: None,
service: &self.service,
jdk: &jdk,
};
let on_event = |e: BuildEvent| self.events.lock().unwrap().push(e);
match build.build(target, BuildKind::Build, &CancellationToken::new(), &on_event) {
Ok(Built::Done(outputs)) => outputs,
Ok(Built::Unsupported(reason)) => panic!("unsupported: {reason}"),
Err(e) => panic!("{e:?}"),
}
}
/// The steps of the launch builds since the last call.
fn steps(&self) -> Vec<String> {
self.events
.lock()
.unwrap()
.drain(..)
.filter_map(|e| match e {
BuildEvent::Step { command, .. } => Some(command),
_ => None,
})
.collect()
}
/// Builds and returns the steps it took, which must succeed.
fn steps_of_launch(&self) -> Vec<String> {
self.steps();
let built = self.launch(false);
assert_eq!(built.failure, None, "{:?}", built.messages);
self.steps()
}
}
#[test]
fn builds_maven_modules_with_javac_and_only_what_changed() {
let Some(f) = Fixture::new(&[
(
"lib/src/main/java/l/L.java",
"package l;\npublic class L { public static String name() { return \"lib\"; } }\n",
),
(
"app/src/main/java/a/A.java",
"package a;\npublic class A { public static void main(String[] args) { System.out.println(l.L.name()); } }\n",
),
("app/src/main/resources/app.properties", "version=${project.version}\n"),
("app/src/test/java/a/ATest.java", "package a;\npublic class ATest { String s = l.L.name(); }\n"),
]) else {
return;
};
// First build: Maven prepares the model, javac compiles lib then app into the IDE's outputs.
let first = f.launch(false);
assert_eq!(first.failure, None, "{:?}", first.messages);
assert_eq!(first.class_paths[0], f.out("t.app/classes"));
assert!(first.class_paths.contains(&f.out("t.lib/classes")), "{:?}", first.class_paths);
assert!(f.out("t.app/classes/a/A.class").is_file());
assert!(f.out("t.lib/classes/l/L.class").is_file());
assert!(!f.root.join("app/target/classes/a/A.class").exists());
assert_eq!(fs::read_to_string(f.out("t.app/classes/app.properties")).unwrap(), "version=1\n");
let steps = f.steps();
assert!(steps[0].contains("process-resources"), "{steps:?}");
assert_eq!(steps[1..], ["javac lib (main, 1 file)", "javac app (main, 1 file)"]);
// Nothing changed: no Maven, no javac.
assert_eq!(f.steps_of_launch(), Vec::<String>::new());
// A change inside a method compiles that class only, without Maven.
f.write(
"lib/src/main/java/l/L.java",
"package l;\npublic class L { public static String name() { return \"lib 2\"; } }\n",
);
assert_eq!(f.steps_of_launch(), ["javac lib (main, 1 file)"]);
// A resource change is processed by Maven (it filters), and compiles nothing.
f.write("app/src/main/resources/app.properties", "version=${project.version}\nmore=1\n");
let steps = f.steps_of_launch();
assert_eq!(steps.len(), 1, "{steps:?}");
assert!(steps[0].contains("resources:resources") && steps[0].contains("-pl app"), "{steps:?}");
assert_eq!(fs::read_to_string(f.out("t.app/classes/app.properties")).unwrap(), "version=1\nmore=1\n");
// A deleted source leaves no class behind.
f.write("app/src/main/java/a/Gone.java", "package a;\nclass Gone {}\n");
assert_eq!(f.steps_of_launch(), ["javac app (main, 1 of 2 files)"]);
assert!(f.out("t.app/classes/a/Gone.class").is_file());
fs::remove_file(f.root.join("app/src/main/java/a/Gone.java")).unwrap();
assert_eq!(f.steps_of_launch(), Vec::<String>::new());
assert!(!f.out("t.app/classes/a/Gone.class").exists());
// Compile errors fail the build with positioned messages.
f.write("app/src/main/java/a/A.java", "package a;\npublic class A { int x = \"s\"; }\n");
let failed = f.launch(false);
let failure = failed.failure.expect("fails");
assert!(failure.contains("incompatible types"), "{failure}");
let error = failed.messages.iter().find(|m| m.severity == Severity::Error).unwrap();
assert_eq!(error.path.as_deref(), Some(f.root.join("app/src/main/java/a/A.java").as_path()));
assert_eq!(error.range.unwrap().start, Pos::new(1, 25));
// It compiles again next time, even unchanged.
f.steps();
assert!(f.launch(false).failure.is_some());
assert_eq!(f.steps(), ["javac app (main, 1 file)"]);
// A test launch compiles the module's tests after its main classes.
f.write(
"app/src/main/java/a/A.java",
"package a;\npublic class A { public static void main(String[] args) { System.out.println(l.L.name()); } }\n",
);
let tests = f.launch(true);
assert_eq!(tests.failure, None, "{:?}", tests.messages);
assert_eq!(tests.class_paths[..2], [f.out("t.app/test-classes"), f.out("t.app/classes")]);
assert!(f.out("t.app/test-classes/a/ATest.class").is_file());
// Recompile compiles the file even unchanged.
f.steps();
let file = f.root.join("app/src/main/java/a/A.java");
assert_eq!(f.build(Target::File(&file)).failure, None);
assert_eq!(f.steps(), ["javac app (main, 1 file)"]);
// Build Project builds every module's main and test classes.
f.write("lib/src/test/java/l/LTest.java", "package l;\nclass LTest { String s = L.name(); }\n");
assert_eq!(f.build(Target::Project).failure, None);
assert_eq!(f.steps(), ["javac lib (tests, 1 file)"]);
assert!(f.out("t.lib/test-classes/l/LTest.class").is_file());
}
#[test]
fn recompiles_the_classes_an_api_change_reaches() {
let Some(f) = Fixture::new(&[
("lib/src/main/java/l/Base.java", "package l;\npublic class Base { public int m() { return 1; } }\n"),
("lib/src/main/java/l/Sub.java", "package l;\npublic class Sub extends Base {}\n"),
("lib/src/main/java/l/User.java", "package l;\nclass User { int u(Sub s) { return s.m(); } }\n"),
("lib/src/main/java/l/Const.java", "package l;\npublic class Const { public static final int X = 1; }\n"),
("lib/src/main/java/l/ConstUser.java", "package l;\nclass ConstUser { int c() { return Const.X; } }\n"),
("lib/src/main/java/l/Other.java", "package l;\npublic class Other { public int o() { return 1; } }\n"),
("app/src/main/java/a/A.java", "package a;\nclass A { int a() { return new l.Other().o(); } }\n"),
("app/src/main/java/a/B.java", "package a;\nclass B { int b() { return l.Const.X; } }\n"),
]) else {
return;
};
assert_eq!(f.steps_of_launch()[1..], ["javac lib (main, 6 files)", "javac app (main, 2 files)"]);
// A body change: that class only, and nothing downstream.
f.write("lib/src/main/java/l/Other.java", "package l;\npublic class Other { public int o() { return 2; } }\n");
assert_eq!(f.steps_of_launch(), ["javac lib (main, 1 of 6 files)"]);
// An API change reaches the classes that use the class or a subclass of it.
f.write(
"lib/src/main/java/l/Base.java",
"package l;\npublic class Base { public int m() { return 1; } public int n() { return 2; } }\n",
);
assert_eq!(f.steps_of_launch(), ["javac lib (main, 1 of 6 files)", "javac lib (main, 2 of 6 files)"]);
// Across modules: only the classes that use it.
f.write(
"lib/src/main/java/l/Other.java",
"package l;\npublic class Other { public int o() { return 2; } public void p() {} }\n",
);
assert_eq!(f.steps_of_launch(), ["javac lib (main, 1 of 6 files)", "javac app (main, 1 of 2 files)"]);
// A compile-time constant is copied into its uses: everything compiled against it compiles again.
f.write("lib/src/main/java/l/Const.java", "package l;\npublic class Const { public static final int X = 2; }\n");
assert_eq!(
f.steps_of_launch(),
["javac lib (main, 1 of 6 files)", "javac lib (main, 5 of 6 files)", "javac app (main, 2 files)"]
);
// A removed method fails the classes that still call it.
f.write("lib/src/main/java/l/Base.java", "package l;\npublic class Base { public int n() { return 2; } }\n");
let failed = f.launch(false);
assert!(failed.failure.expect("fails").contains("User.java"));
}
#[test]
fn an_api_change_from_a_failed_build_still_reaches_other_modules() {
let Some(f) = Fixture::new(&[
("lib/src/main/java/l/L.java", "package l;\npublic class L { public static int m() { return 1; } }\n"),
("lib/src/main/java/l/U.java", "package l;\nclass U { int u() { return L.m(); } }\n"),
("app/src/main/java/a/A.java", "package a;\nclass A { int a() { return l.L.m(); } }\n"),
]) else {
return;
};
assert_eq!(f.launch(false).failure, None);
// L compiles, then U, which still calls the removed method, fails lib before app compiles.
f.write("lib/src/main/java/l/L.java", "package l;\npublic class L { public static int n() { return 1; } }\n");
assert!(f.launch(false).failure.expect("lib fails").contains("U.java"));
// Once lib compiles, app learns that L changed, and A fails too instead of keeping a class
// that calls a method L no longer has.
f.write("lib/src/main/java/l/U.java", "package l;\nclass U { int u() { return L.n(); } }\n");
let failed = f.launch(false);
assert!(failed.failure.expect("app fails").contains("A.java"), "{:?}", failed.messages);
// So does a changed constant: C compiles, then the whole set, where U fails.
f.write("app/src/main/java/a/A.java", "package a;\nclass A { int a() { return l.L.n() + l.C.X; } }\n");
let c = |x: u32, y: &str| format!("package l;\npublic class C {{ public static final int X = {x};{y} }}\n");
f.write("lib/src/main/java/l/C.java", &c(1, " public static int y() { return 0; }"));
f.write("lib/src/main/java/l/U.java", "package l;\nclass U { int u() { return L.n() + C.y(); } }\n");
assert_eq!(f.launch(false).failure, None);
f.write("lib/src/main/java/l/C.java", &c(2, ""));
assert!(f.launch(false).failure.expect("lib fails").contains("U.java"));
f.write("lib/src/main/java/l/U.java", "package l;\nclass U { int u() { return L.n(); } }\n");
f.steps();
assert_eq!(f.launch(false).failure, None);
let steps = f.steps();
assert!(steps.contains(&"javac app (main, 1 file)".to_owned()), "{steps:?}");
}
#[test]
fn reads_what_a_class_file_declares() {
let Some((home, _)) = tools() else { return };
let tmp = tempfile::tempdir().unwrap();
let compile = |text: &str| {
write(tmp.path(), "p/C.java", text);
let status = std::process::Command::new(home.join("bin/javac"))
.args(["-d", "out", "p/C.java"])
.current_dir(tmp.path())
.status()
.unwrap();
assert!(status.success());
classfile::parse(&fs::read(tmp.path().join("out/p/C.class")).unwrap()).unwrap()
};
let a = compile(
"package p;\nimport java.util.List;\npublic class C extends Thread implements Runnable {\n public static final String K = \"k\";\n @Deprecated public List<javax.swing.JButton> f;\n public x.Y g() { return null; }\n private int hidden() { return 1; }\n}\nclass Z {}\n"
.replace("x.Y", "Object")
.as_str(),
);
assert_eq!(a.name, "p/C");
assert_eq!(a.super_name.as_deref(), Some("java/lang/Thread"));
assert_eq!(a.interfaces, ["java/lang/Runnable"]);
assert!(a.refs.contains("javax/swing/JButton"), "{:?}", a.refs);
assert!(!a.refs.iter().any(|r| r.starts_with("java/")), "{:?}", a.refs);
// Private members and method bodies aren't API; constants have their own fingerprint.
let b = compile(
"package p;\nimport java.util.List;\npublic class C extends Thread implements Runnable {\n public static final String K = \"k\";\n @Deprecated public List<javax.swing.JButton> f;\n public Object g() { return \"x\"; }\n private long hidden2() { return 1; }\n}\nclass Z {}\n",
);
assert_eq!((a.api, a.constants), (b.api, b.constants));
let c = compile(
"package p;\nimport java.util.List;\npublic class C extends Thread implements Runnable {\n public static final String K = \"changed\";\n @Deprecated public List<javax.swing.JButton> f;\n public Object g() { return \"x\"; }\n}\nclass Z {}\n",
);
assert_eq!(a.api, c.api);
assert_ne!(a.constants, c.constants);
let d = compile(
"package p;\nimport java.util.List;\npublic class C extends Thread implements Runnable {\n public static final String K = \"k\";\n @Deprecated public List<javax.swing.JLabel> f;\n public Object g() { return \"x\"; }\n}\nclass Z {}\n",
);
assert_ne!(a.api, d.api);
}
#[test]
fn follows_api_changes_through_the_log() {
let mut state = SetState { generation: 1, ..Default::default() };
state.log(2, ["a/A".to_owned()].into(), false);
state.log(3, ["a/B".to_owned()].into(), false);
assert_eq!(state.changes_since(3), Some(BTreeSet::new()));
assert_eq!(state.changes_since(2), Some(["a/B".to_owned()].into()));
assert_eq!(state.changes_since(1), Some(["a/A".to_owned(), "a/B".to_owned()].into()));
// Unknown generations, and a log entry where everything changed, mean everything.
assert_eq!(state.changes_since(0), None);
state.log(4, BTreeSet::new(), true);
assert_eq!(state.changes_since(3), None);
}
#[test]
fn ant_patterns_match_like_maven() {
assert!(ant_match("**/*.java", "a/b/C.java"));
assert!(ant_match("**/*.java", "C.java"));
assert!(ant_match("com/acme/**", "com/acme/x/Y.java"));
assert!(!ant_match("com/acme/**", "com/other/Y.java"));
assert!(ant_match("**/generated/", "x/generated/Y.java"));
assert!(ant_match("**/*Test?.java", "a/FooTest1.java"));
assert!(!ant_match("*.java", "a/B.java"));
}
#[test]
fn javac_options_follow_the_compiler_configuration() {
let set = SourceSet {
output: PathBuf::from("/o"),
compiler: Some(CompilerConfig {
release: Some("17".into()),
source: Some("1.8".into()),
encoding: Some("UTF-8".into()),
parameters: Some(true),
debuglevel: Some("lines,vars".into()),
proc: Some("none".into()),
processor_path: Some(vec![PathBuf::from("/p.jar")]),
annotation_processors: Some(vec!["a.P".into()]),
compiler_args: vec!["-Xlint:unchecked".into()],
compiler_arguments: [("Akey=v".to_owned(), None)].into(),
show_warnings: Some(false),
..Default::default()
}),
..Default::default()
};
let args = javac_options(&set, &[PathBuf::from("/lib.jar")], Path::new("/gen"), Some(21));
let joined = args.join(" ");
let separator = if cfg!(windows) { ";" } else { ":" };
assert!(joined.starts_with(&format!("-d /o -classpath /o{separator}/lib.jar -sourcepath -s /gen")), "{joined}");
for expected in [
"-processorpath /p.jar",
"-processor a.P",
"-proc:none",
"-g:lines,vars",
"-parameters",
"-nowarn",
"-encoding UTF-8",
"--release 17",
"-Akey=v",
] {
assert!(joined.contains(expected), "{expected} in {joined}");
}
assert!(joined.ends_with("-Xlint:unchecked"), "{joined}");
// JDK 8 has no --release: source and target instead.
let old = javac_options(&set, &[], Path::new("/gen"), Some(8)).join(" ");
assert!(old.contains("-source 1.8") && !old.contains("--release"), "{old}");
}
#[test]
fn builds_gradle_projects_with_javac_and_only_what_changed() {
let Some(f) = Fixture::gradle(&[
(
"lib/src/main/java/l/L.java",
"package l;\npublic class L { public static String name() { return \"lib\"; } }\n",
),
(
"app/src/main/java/a/A.java",
"package a;\npublic class A { public static void main(String[] args) { System.out.println(l.L.name()); } }\n",
),
("app/src/main/resources/app.properties", "version=${version}\n"),
("app/src/test/java/a/ATest.java", "package a;\npublic class ATest { String s = l.L.name(); }\n"),
]) else {
return;
};
let steps = f.steps_of_launch();
assert_eq!(steps.len(), 3, "{steps:?}");
assert!(steps[0].contains("openideaBuildModel"), "{steps:?}");
assert!(steps[1].starts_with("javac lib (main"), "{steps:?}");
assert!(steps[2].starts_with("javac app (main"), "{steps:?}");
assert!(f.out("t.lib/classes/l/L.class").is_file());
assert!(f.out("t.app/classes/a/A.class").is_file());
assert_eq!(fs::read_to_string(f.out("t.app/classes/app.properties")).unwrap(), "version=1\n");
// Gradle's own outputs stay untouched.
assert!(!f.root.join("app/build/classes").exists());
let built = f.launch(false);
assert!(built.class_paths.iter().any(|p| p.ends_with("t.lib/classes")), "{:?}", built.class_paths);
assert!(!built.class_paths.iter().any(|p| p.extension().is_some_and(|e| e == "jar")), "{:?}", built.class_paths);
assert_eq!(f.steps(), Vec::<String>::new(), "nothing changed");
f.write(
"app/src/main/java/a/A.java",
"package a;\npublic class A { public static void main(String[] args) { System.out.println(l.L.name() + 1); } }\n",
);
let steps = f.steps_of_launch();
assert_eq!(steps.len(), 1, "{steps:?}");
assert!(steps[0].starts_with("javac app (main"), "{steps:?}");
f.write("app/src/main/resources/app.properties", "version=${version}\nname=app\n");
let steps = f.steps_of_launch();
assert_eq!(steps.len(), 1, "{steps:?}");
assert!(steps[0].contains(":app:processResources"), "{steps:?}");
assert_eq!(fs::read_to_string(f.out("t.app/classes/app.properties")).unwrap(), "version=1\nname=app\n");
// Tests compile against the main classes.
f.steps();
let built = f.launch(true);
assert_eq!(built.failure, None, "{:?}", built.messages);
assert!(f.out("t.app/test-classes/a/ATest.class").is_file());
// A changed build script prepares again.
f.write("lib/build.gradle", "// changed\n");
let steps = f.steps_of_launch();
assert!(steps[0].contains("openideaBuildModel"), "{steps:?}");
// An error is a javac diagnostic on the source.
f.write("lib/src/main/java/l/L.java", "package l;\npublic class L { public static String name() { return 1; } }\n");
let built = f.launch(false);
assert!(built.failure.is_some());
let error = built.messages.iter().find(|m| m.severity == Severity::Error).expect("an error");
assert_eq!(error.path.as_deref(), Some(f.root.join("lib/src/main/java/l/L.java").as_path()));
}
#[test]
fn leaves_gradle_projects_with_other_compilers_to_gradle() {
let Some(f) = Fixture::gradle(&[
("app/build.gradle", "apply plugin: 'groovy'\ndependencies { implementation project(':lib') }\n"),
("app/src/main/java/a/A.java", "package a;\npublic class A {}\n"),
]) else {
return;
};
let jdk = |_: Option<u32>| None;
let build = JavaBuild {
root: &f.root,
model: &f.model,
cache: &f.cache,
jar: Path::new(JAR),
jar_version: "test",
local_repo: None,
service: &f.service,
jdk: &jdk,
};
let target = Target::Launch { module: &f.root.join("app"), test: false };
match build.build(target, BuildKind::Build, &CancellationToken::new(), &|_| {}) {
Ok(Built::Unsupported(reason)) => assert!(reason.contains("GroovyCompile"), "{reason}"),
Ok(Built::Done(outputs)) => panic!("built: {outputs:?}"),
Err(e) => panic!("{e:?}"),
}
}
+1
Переглянути файл
@@ -9,6 +9,7 @@ pub mod application_update;
pub mod compile;
pub mod gradle;
mod gradle_deps;
pub mod jbuild;
pub mod kotlin_bridge;
pub mod maven;
pub mod pom_edit;
+26 -4
Переглянути файл
@@ -753,7 +753,26 @@ pub(crate) fn launch_inputs(
projects: &[&MavenProject],
local_repo: Option<PathBuf>,
) -> Option<Vec<PathBuf>> {
fn roots(el: &Element, parent: &str, dir: &Path, out: &mut Vec<PathBuf>) -> Option<()> {
project_inputs(root, projects, local_repo, true)
}
/// The POM chains (with imported BOMs) of `projects` and the files their profiles activate
/// on: what Maven's model of them is built from, without their sources.
pub(crate) fn model_inputs(
root: &Path,
projects: &[&MavenProject],
local_repo: Option<PathBuf>,
) -> Option<Vec<PathBuf>> {
project_inputs(root, projects, local_repo, false)
}
fn project_inputs(
root: &Path,
projects: &[&MavenProject],
local_repo: Option<PathBuf>,
sources: bool,
) -> Option<Vec<PathBuf>> {
fn roots(el: &Element, parent: &str, dir: &Path, sources: bool, out: &mut Vec<PathBuf>) -> Option<()> {
let input =
matches!(el.name.as_str(), "sourceDirectory" | "testSourceDirectory" | "sourceDir" | "testSourceDir")
|| (matches!(parent, "sources" | "sourceDirs" | "testSources" | "testSourceDirs")
@@ -762,6 +781,7 @@ pub(crate) fn launch_inputs(
|| (parent == "filters" && el.name == "filter");
// Profile activation may depend on the presence of an otherwise unrelated file.
let activation = parent == "file" && matches!(el.name.as_str(), "exists" | "missing");
let input = input && sources;
if input || activation {
// A source root under Maven's build directory is generated by the build itself.
// Skip it without resolving the property: `<build><directory>` may be custom, and
@@ -787,7 +807,7 @@ pub(crate) fn launch_inputs(
}
}
for child in &el.children {
roots(child, &el.name, dir, out)?;
roots(child, &el.name, dir, sources, out)?;
}
Some(())
}
@@ -796,7 +816,9 @@ pub(crate) fn launch_inputs(
for project in projects {
let dir = root.join(&project.dir);
// Include all conventional language/resource roots, including nonstandard files under src.
out.push(dir.join("src"));
if sources {
out.push(dir.join("src"));
}
let pom = root.join(&project.pom);
resolver.context(&pom, 0);
let mut path = pom;
@@ -808,7 +830,7 @@ pub(crate) fn launch_inputs(
}
out.push(path.clone());
let text = xml::read_text(&path)?;
roots(&xml::parse(&text)?, "", &dir, &mut out)?;
roots(&xml::parse(&text)?, "", &dir, sources, &mut out)?;
let raw = resolver.pom(&path)?;
let Some(parent) = raw.parent else { break };
path = resolver.parent_path(path.parent()?, &parent)?;
+1 -6
Переглянути файл
@@ -95,8 +95,6 @@ pub struct AgentSettings {
pub show_usage_limits: bool,
/// What the session has cost so far, as the agent reports it.
pub show_cost: bool,
/// A finished turn's work folds into one line under its message, leaving the reply.
pub fold_turns: bool,
/// Streaming text is revealed at a steady pace rather than chunk by chunk.
pub smooth_text: bool,
/// Conversations and the composer expand to the full width of the pane instead of staying in a centred column.
@@ -145,7 +143,6 @@ impl Default for AgentSettings {
show_work_time: true,
show_usage_limits: true,
show_cost: false,
fold_turns: false,
smooth_text: true,
fit_window_width: false,
thinking: ThinkingDisplay::Auto,
@@ -2120,14 +2117,12 @@ mod tests {
#[test]
fn agent_meters_default_and_round_trip() {
let old: Settings = serde_json::from_str(r#"{"agents":{"showCost":true}}"#).unwrap();
let old: Settings = serde_json::from_str(r#"{"agents":{"showCost":true,"foldTurns":true}}"#).unwrap();
assert!(old.agents.show_cost);
assert!(old.agents.show_context_usage && old.agents.show_work_time && old.agents.show_usage_limits);
assert!(!old.agents.fit_window_width);
assert!(!old.agents.fold_turns);
assert!(!Settings::default().agents.show_cost);
assert!(!Settings::default().agents.fit_window_width);
assert!(!Settings::default().agents.fold_turns);
let mut settings = Settings::default();
settings.agents.show_usage_limits = false;
settings.agents.fit_window_width = true;
+113 -48
Переглянути файл
@@ -118,6 +118,8 @@ pub struct Host {
pub(crate) heap_windows: Mutex<HashMap<ide_heap::HeapSnapshotId, String>>,
pub(crate) heap_requests: ops::heap::HeapRequests,
pub(crate) rebase_editors: Arc<ops::vcs::RebaseEditors>,
/// The IDE's Java build: resident javac processes shared by every window's launches.
pub(crate) java_build: Arc<ide_build::jbuild::JavaBuildService>,
/// SSH connections of Settings › SSH Configurations.
pub ssh: Arc<ide_ssh::SshManager>,
/// SFTP deployment, remote file editing and runs on run targets.
@@ -144,11 +146,31 @@ pub struct Host {
requests: requests::Requests,
project_requests: RwLock<HashMap<String, Vec<RequestId>>>,
/// Shutdowns of projects closed with [`Host::close_project_detached`].
closing: parking_lot::Mutex<Vec<std::thread::JoinHandle<()>>>,
closing: parking_lot::Mutex<Vec<DetachedClose>>,
/// One open at a time per window (see [`Host::opening`]).
open_locks: parking_lot::Mutex<HashMap<String, Arc<parking_lot::Mutex<()>>>>,
}
struct DetachedClose {
root: Option<std::path::PathBuf>,
handle: std::thread::JoinHandle<()>,
}
struct ShutdownWork {
notebooks: Vec<Arc<notebook::NotebookService>>,
bridges: Vec<Arc<kotlin_bridge::KotlinBridge>>,
lsp: Option<Arc<ide_lsp::LspManager>>,
debug: Option<(Arc<ide_dap::DebugManager>, String, Option<std::path::PathBuf>)>,
agents: Vec<Arc<ide_agent::AgentManager>>,
terminals: Option<ide_terminal::DetachedTerminals>,
processes: Option<ide_run::DetachedProcessKills>,
retired: Option<Arc<Project>>,
}
fn roots_overlap(a: &std::path::Path, b: &std::path::Path) -> bool {
a == b || a.starts_with(b) || b.starts_with(a)
}
/// How long exit waits for project shutdown before giving up.
const EXIT_SHUTDOWN_WAIT: std::time::Duration = std::time::Duration::from_secs(10);
@@ -227,6 +249,7 @@ impl Host {
heap_windows: Mutex::default(),
heap_requests: Default::default(),
rebase_editors: Default::default(),
java_build: Default::default(),
languages,
syntax,
config_dir,
@@ -333,7 +356,7 @@ impl Host {
/// [`Self::close_project_detached`] there.
pub fn close_project(&self, window: &str) {
if let Some(shutdown) = self.begin_close(window) {
self.wait_blocking(shutdown);
self.wait_blocking(shutdown.handle);
}
}
@@ -343,15 +366,15 @@ impl Host {
pub fn close_project_detached(&self, window: &str) {
if let Some(shutdown) = self.begin_close(window) {
let mut closing = self.closing.lock();
closing.retain(|handle| !handle.is_finished());
closing.retain(|entry| !entry.handle.is_finished());
closing.push(shutdown);
}
}
/// Detaches the project from `window` and stops what it started, synchronously,
/// so the window can open another project at once. Returns the thread that
/// finishes shutting down its workers.
fn begin_close(&self, window: &str) -> Option<std::thread::JoinHandle<()>> {
/// Detaches the project from `window` synchronously so the caller (including the UI
/// event-loop thread) never blocks on disk I/O or process shutdown, and returns the
/// background handle that stops its workers, agents, terminals and processes.
fn begin_close(&self, window: &str) -> Option<DetachedClose> {
self.mcp_reports.forget_window(window);
self.mcp_requests.forget_window(window);
self.mcp_agent_runs.forget_window(window);
@@ -398,78 +421,115 @@ impl Host {
phpstan.stop();
}
project.documents.clear_workspace_edit_history();
project.agents.shutdown();
project.agents.detach_sinks();
project.flutter.stop();
project.devtools.stop();
project.widget_preview.stop();
project.notebooks.stop_admission();
// What the closing window started goes with it — the builds and searches it
// asked for, its runs, its shells and its debug sessions — and its language
// servers shut down.
self.processes.kill_project(&project.root);
self.terminals.kill_key(self.owner_window(window));
Some(self.spawn_project_shutdown(
vec![project.notebooks.clone()],
project.kotlin_bridge.iter().cloned().collect(),
Some(project.lsp.clone()),
// Detach runs and terminals synchronously so a new project opened in the same window
// never collides with them, then terminate them and shut down agents on the background thread.
let processes = self.processes.detach_project_kills(&project.root);
let terminals = self.terminals.detach_key(self.owner_window(window));
let root = (!project.light).then(|| project.root.clone());
let handle = self.spawn_project_shutdown(ShutdownWork {
notebooks: vec![project.notebooks.clone()],
bridges: project.kotlin_bridge.iter().cloned().collect(),
lsp: Some(project.lsp.clone()),
// Debug sessions under the root belong to windows: a project served without one starts none.
Some((self.debugger.clone(), window.to_owned(), (!background).then(|| project.root.clone()))),
Some(project),
))
debug: Some((self.debugger.clone(), window.to_owned(), (!background).then(|| project.root.clone()))),
agents: vec![project.agents.clone()],
terminals: Some(terminals),
processes: Some(processes),
retired: Some(project),
});
Some(DetachedClose { root, handle })
}
/// Project/window destruction must finish owned kernel cleanup, not enqueue
/// Project/window destruction must finish owned kernel and agent cleanup, not enqueue
/// work which can be lost as the desktop runtime exits: the returned thread is
/// joined by the closer or, for a detached close, before exit.
fn spawn_project_shutdown(
&self,
notebooks: Vec<Arc<notebook::NotebookService>>,
bridges: Vec<Arc<kotlin_bridge::KotlinBridge>>,
lsp: Option<Arc<ide_lsp::LspManager>>,
debug: Option<(Arc<ide_dap::DebugManager>, String, Option<std::path::PathBuf>)>,
retired: Option<Arc<Project>>,
) -> std::thread::JoinHandle<()> {
for bridge in &bridges {
fn spawn_project_shutdown(&self, work: ShutdownWork) -> std::thread::JoinHandle<()> {
for bridge in &work.bridges {
bridge.stop();
}
for service in &notebooks {
for service in &work.notebooks {
service.stop_admission();
}
let runtime = self.runtime.clone();
std::thread::spawn(move || {
if let Some(processes) = work.processes {
processes.kill();
}
if let Some(terminals) = work.terminals {
terminals.terminate();
}
let agents = (!work.agents.is_empty()).then(|| {
let agents = work.agents;
std::thread::spawn(move || {
for manager in agents {
manager.shutdown();
}
})
});
// Dropping the project stops its file watcher and index worker, which first finish the
// batch they are applying (many file events while a build writes its output), so it
// isn't done on the closing caller's thread (the UI thread for a window close).
let retired = retired.map(|project| std::thread::spawn(move || drop(project)));
let retired = work.retired.map(|project| std::thread::spawn(move || drop(project)));
runtime.block_on(async move {
for bridge in bridges {
for bridge in work.bridges {
bridge.shutdown().await;
}
for service in notebooks {
for service in work.notebooks {
service.shutdown().await;
}
if let Some(lsp) = lsp {
if let Some(lsp) = work.lsp {
lsp.shutdown_all().await;
}
if let Some((debug, key, root)) = debug {
if let Some((debug, key, root)) = work.debug {
debug.stop_key(&key).await;
if let Some(root) = root {
debug.stop_under(&root).await;
}
}
});
if let Some(agents) = agents {
let _ = agents.join();
}
if let Some(retired) = retired {
let _ = retired.join();
}
})
}
/// Waits for detached closes, so a project opened next never races the
/// language servers of one still shutting down (e.g. over a shared workspace).
/// Waits for every detached close to finish.
#[cfg(test)]
pub(crate) fn wait_detached_closes(&self) {
let pending: Vec<_> = self.closing.lock().drain(..).collect();
for shutdown in pending {
self.wait_blocking(shutdown);
self.wait_blocking(shutdown.handle);
}
}
/// Waits only for detached closes whose root overlaps `root`, so opening an unrelated project
/// never blocks on another project's background shutdown.
pub(crate) fn wait_detached_closes_for(&self, root: &std::path::Path) {
let matching = {
let mut closing = self.closing.lock();
closing.retain(|entry| !entry.handle.is_finished());
let mut wait = Vec::new();
let mut keep = Vec::new();
for entry in closing.drain(..) {
if entry.root.as_deref().is_some_and(|other| roots_overlap(other, root)) {
wait.push(entry.handle);
} else {
keep.push(entry);
}
}
*closing = keep;
wait
};
for handle in matching {
self.wait_blocking(handle);
}
}
@@ -495,18 +555,23 @@ impl Host {
/// Called before the desktop runtime exits, including update/restart exits, on
/// the event-loop thread: waits for detached closes and the open projects'
/// kernels, but no longer than [`EXIT_SHUTDOWN_WAIT`], so a runtime worker
/// kernels and agents, but no longer than [`EXIT_SHUTDOWN_WAIT`], so a runtime worker
/// stuck on the event loop cannot keep the process from exiting.
pub fn shutdown_notebooks_on_exit(&self) {
let projects = self.projects();
let mut pending: Vec<_> = self.closing.lock().drain(..).collect();
pending.push(self.spawn_project_shutdown(
projects.iter().map(|project| project.notebooks.clone()).collect(),
projects.iter().filter_map(|project| project.kotlin_bridge.clone()).collect(),
None,
None,
None,
));
let mut pending: Vec<_> = self.closing.lock().drain(..).map(|entry| entry.handle).collect();
if !projects.is_empty() {
pending.push(self.spawn_project_shutdown(ShutdownWork {
notebooks: projects.iter().map(|project| project.notebooks.clone()).collect(),
bridges: projects.iter().filter_map(|project| project.kotlin_bridge.clone()).collect(),
lsp: None,
debug: None,
agents: projects.iter().map(|project| project.agents.clone()).collect(),
terminals: None,
processes: None,
retired: None,
}));
}
let deadline = std::time::Instant::now() + EXIT_SHUTDOWN_WAIT;
while pending.iter().any(|handle| !handle.is_finished()) {
if std::time::Instant::now() >= deadline {
+1
Переглянути файл
@@ -513,6 +513,7 @@ async fn resolve_jvm_application(
call.window(),
std::path::PathBuf::from(&module),
test == Some(true),
false,
policy,
&cancel,
None,
+97 -4
Переглянути файл
@@ -9,6 +9,7 @@ use crate::{Host, Project};
use ide_command::command;
use ide_build::compile::{self, BuildEvent, BuildKind, BuildResult};
use ide_build::jbuild::Target;
use ide_build::maven::completion::{PomCompletion, PomCompletionOption};
use ide_build::maven::sources;
use ide_build::maven::{PomGoto, PomManagedDeclaration, PomNavigationOptions};
@@ -975,11 +976,38 @@ pub async fn build_run(
let config_dir = host.config_dir.clone();
let token = host.begin_project_request(window, request);
let launch_project = project.clone();
let (service, data_dir) = (host.java_build.clone(), host.local_data_dir.clone());
let result = blocking(move || {
let single = cmake.is_none() && ide_workspace::workspace::Workspace::load(&root)?.is_none();
// A Maven or Gradle project builds with the IDE's Java build (#4078), unless its
// settings ask for the build tool, or it can't.
if single {
let model = with_profiles(load(&root, &cache, &settings), &cache);
let served = match file.as_deref() {
Some(module) => super::java::served_by_service(&root, &model, &settings, module),
None => super::java::project_served_by_service(&model, &settings),
};
if served {
let service = super::java::ServiceBuild {
service: &service,
data_dir: &data_dir,
root: &root,
cache: &cache,
settings: &settings,
model: &model,
};
let target = match file.as_deref() {
Some(file) => Target::Module(file),
None => Target::Project,
};
if let Some(result) = service_build_result(&service, target, kind, &clear, &sink, &token, &on_event)? {
return Ok(result);
}
}
}
// Fast path (#2476): an unchanged single-project Maven build skips
// Maven entirely. Previous diagnostics stay: nothing changed, so they
// are still accurate.
let single = cmake.is_none() && ide_workspace::workspace::Workspace::load(&root)?.is_none();
if single && kind == BuildKind::Build {
let model = with_profiles(load(&root, &cache, &settings), &cache);
if compile::menu_up_to_date(&cache, &root, &model, file.as_deref(), &token) {
@@ -1102,13 +1130,59 @@ pub async fn build_run(
let outcome = result?;
// Maven generated sources (protobuf, gRPC) stay invisible to jdtls until the
// folders the build wrote are attached. An up-to-date build skips Maven and
// still needs this: the classes can already be on disk.
if outcome.system == ide_build::compile::BuildSystem::Maven {
// still needs this: the classes can already be on disk. The IDE's Java build
// generates them with Maven too.
if matches!(outcome.system, ide_build::compile::BuildSystem::Maven | ide_build::compile::BuildSystem::Javac) {
project.lsp.sync_maven_generated_sources(&project.root).await;
}
Ok(outcome)
}
/// A menu build by the IDE's Java build, as the Build window shows it; `None` when Maven builds.
/// Diagnostics of `clear` are cleared once the service builds; its messages are published.
#[allow(clippy::too_many_arguments)]
fn service_build_result(
service: &super::java::ServiceBuild,
target: Target,
kind: BuildKind,
clear: &[std::path::PathBuf],
sink: &ide_core::SharedSink,
token: &CancellationToken,
on_event: &Channel<BuildEvent>,
) -> IdeResult<Option<BuildResult>> {
let started = std::time::Instant::now();
let title = std::sync::Mutex::new(String::new());
let forward = |event: BuildEvent| {
if let BuildEvent::Started { title: t, .. } = &event {
*title.lock().unwrap() = t.clone();
}
let _ = on_event.send(event);
};
let built = service.build(target, kind, token, &forward)?;
let Some(outputs) = built else { return Ok(None) };
for path in clear {
sink.emit(IdeEvent::Diagnostics {
path: path.clone().into(),
source: compile::DIAGNOSTICS_SOURCE.into(),
items: Vec::new(),
});
}
for (path, items) in compile::diagnostics(&outputs.messages) {
sink.emit(IdeEvent::Diagnostics { path: path.into(), source: compile::DIAGNOSTICS_SOURCE.into(), items });
}
let count =
|severity: ide_core::Severity| outputs.messages.iter().filter(|m| m.severity == severity).count() as u32;
Ok(Some(BuildResult {
system: compile::BuildSystem::Javac,
title: title.into_inner().unwrap(),
success: outputs.failure.is_none(),
errors: count(ide_core::Severity::Error),
warnings: count(ide_core::Severity::Warning),
duration_ms: started.elapsed().as_secs_f64() * 1000.0,
messages: outputs.messages,
}))
}
fn plan_compile_file(
root: &Path,
cache: &Path,
@@ -1167,7 +1241,26 @@ pub async fn build_compile_file(
};
let sink = project.sink.clone();
let token = host.begin_project_request(window, request);
let (service, data_dir) = (host.java_build.clone(), host.local_data_dir.clone());
let result = blocking(move || {
{
let model = with_profiles(load(&scope.root, &scope.cache, &scope.settings), &scope.cache);
if super::java::served_by_service(&scope.root, &model, &scope.settings, &file) {
let service = super::java::ServiceBuild {
service: &service,
data_dir: &data_dir,
root: &scope.root,
cache: &scope.cache,
settings: &scope.settings,
model: &model,
};
let target = Target::File(&file);
let kind = BuildKind::Build;
if let Some(result) = service_build_result(&service, target, kind, &clear, &sink, &token, &on_event)? {
return Ok(result);
}
}
}
for path in clear {
sink.emit(IdeEvent::Diagnostics {
path: path.into(),
@@ -1190,7 +1283,7 @@ pub async fn build_compile_file(
.await;
host.end_request(request);
let outcome = result?;
if outcome.system == ide_build::compile::BuildSystem::Maven {
if matches!(outcome.system, ide_build::compile::BuildSystem::Maven | ide_build::compile::BuildSystem::Javac) {
project.lsp.sync_maven_generated_sources(&scope_root).await;
}
Ok(outcome)
+231 -12
Переглянути файл
@@ -9,6 +9,7 @@ use super::build::{load, with_profiles, workspace};
use cache::LaunchEvents;
use ide_build::BuildModel;
use ide_build::compile::{self, BuildEvent};
use ide_build::jbuild::{Built, JavaBuild, JavaBuildService, LaunchOutputs, Target};
use ide_core::error::ErrorKind;
use ide_core::settings::Settings;
use ide_core::{CancellationToken, IdeError, IdeResult, RequestId};
@@ -22,12 +23,16 @@ use std::path::{Path, PathBuf};
/// A module with Kotlin / Groovy / Scala sources is built by its build system, whose class directories come first.
/// The build streams its console, messages and progress on `on_event` while it runs; a launch
/// whose build another launch's build joins receives that build's events.
/// A Maven module is built by the IDE's Java build, except for a `debug` launch the language
/// server serves: java-debug's HotSwap reloads the classes the language server compiles.
#[allow(clippy::too_many_arguments)]
#[command(trust = trusted)]
pub async fn java_resolve_launch(
host: &Host,
window: &str,
module: PathBuf,
test: bool,
debug: bool,
policy: BuildPolicy,
request: RequestId,
on_event: Channel<BuildEvent>,
@@ -39,16 +44,18 @@ pub async fn java_resolve_launch(
let events: LaunchEvents = std::sync::Arc::new(move |event| {
let _ = on_event.send(event);
});
let result = resolve_launch(host, window, module, test, policy, &cancel, Some(events)).await;
let result = resolve_launch(host, window, module, test, debug, policy, &cancel, Some(events)).await;
host.end_request(request);
result
}
#[allow(clippy::too_many_arguments)]
pub(crate) async fn resolve_launch(
host: &Host,
window: &str,
module: PathBuf,
test: bool,
debug: bool,
policy: BuildPolicy,
cancel: &CancellationToken,
events: Option<LaunchEvents>,
@@ -73,13 +80,12 @@ pub(crate) async fn resolve_launch(
}
let scope = std::sync::Arc::new(scope);
let launches = project.java_launches.for_cache(&scope.cache);
let waiting = launches.waiting.add(module.clone(), test, policy, events.clone());
let prefer_maven = scope.settings.languages.java.maven.delegate_build;
// A launch builds incrementally unless the configuration asks for Rebuild or NoBuild.
let build = policy != BuildPolicy::NoBuild;
let full = policy == BuildPolicy::Rebuild;
let build_kind = if full { compile::BuildKind::Rebuild } else { compile::BuildKind::Build };
let (model, external, mut delegated, is_maven) = {
let (model, external, mut delegated, is_maven, non_java, served) = {
let scope = scope.clone();
let launches = launches.clone();
let module = module.clone();
@@ -89,6 +95,7 @@ pub(crate) async fn resolve_launch(
let model = load_launch_model(&scope);
let non_java = build && compile::launch_has_non_java_sources(root, &model, &module, test);
let is_maven = is_maven_module(root, &model, &module);
let served = served_by_service(root, &model, &scope.settings, &module);
let delegated = build
&& delegates_to_external_build(
is_maven,
@@ -98,11 +105,65 @@ pub(crate) async fn resolve_launch(
prefer_maven,
);
let external = non_java || delegated;
(model, external, delegated, is_maven)
(std::sync::Arc::new(model), external, delegated, is_maven, non_java, served)
})
.await
.map_err(|e| IdeError::internal(e.to_string()))?
};
// A Maven or Gradle module is built by the IDE's Java build ([`served_by_service`]), unless
// the launch debugs with java-debug, whose HotSwap reloads what jdtls compiles (ecj's
// classes differ from javac's: lambda names). jdtls keeps building for its diagnostics
// either way.
if served && !non_java && !debug {
let built = {
let (service, data_dir, scope, model, module, cancel, events) = (
host.java_build.clone(),
host.local_data_dir.clone(),
scope.clone(),
model.clone(),
module.clone(),
cancel.clone(),
events.clone(),
);
tokio::task::spawn_blocking(move || {
let on_event = |event: BuildEvent| {
if let Some(events) = &events {
events(event);
}
};
let kind = build.then_some(build_kind);
build_with_service(&service, &data_dir, &scope, &model, &module, test, kind, &cancel, &on_event)
})
.await
.map_err(|e| IdeError::internal(e.to_string()))??
};
if let Some(outputs) = built {
progress("Resolving the classpath");
let mut info = project.lsp.java_launch(&module, test, false, false, false, cancel).await?;
let data_dir = host.local_data_dir.clone();
let cancel = cancel.clone();
return tokio::task::spawn_blocking(move || {
// javac's verdict replaces JDT's, as a Maven build's does.
if build {
apply_external_build_result(&mut info, outputs.failure, true);
}
info.class_paths = outputs.class_paths.iter().map(|p| p.to_string_lossy().into_owned()).collect();
apply_library_classpath(&mut info, &scope.root, &scope.settings.project_structure.libraries, test);
finish_launch(&mut info, &scope.root, &module, &scope.settings, &model, &data_dir);
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
tracing::info!(
total_ms = started.elapsed().as_millis(),
"Java launch resolved with the IDE's Java build"
);
Ok(info)
})
.await
.map_err(|e| IdeError::internal(e.to_string()))?;
}
}
let waiting = launches.waiting.add(module.clone(), test, policy, events.clone());
let mut external_build =
if delegated { Some(project.lsp.java_external_build(&module, cancel).await?) } else { None };
if build && !delegated {
@@ -124,7 +185,6 @@ pub(crate) async fn resolve_launch(
drop_processor_recreate_errors(&mut info);
}
}
let model = std::sync::Arc::new(model);
let members = if delegated {
build_members(&project, &scope, &model, &module, test, &waiting, cancel).await?
} else {
@@ -217,6 +277,104 @@ pub(crate) async fn resolve_launch(
.map_err(|e| IdeError::internal(e.to_string()))?
}
/// Builds the launch of a Maven module with the IDE's Java build (#4078): javac in a resident
/// process with the configuration Maven gives the compiler, into outputs in the project cache
/// that neither the language server nor a terminal `mvn` writes. `None` when the module needs
/// Maven's own build (another compiler, a multi-release jar, a Java module…), which then runs.
/// Without `kind` (no build before launch), the outputs of its last build, if any.
#[allow(clippy::too_many_arguments)]
fn build_with_service(
service: &JavaBuildService,
data_dir: &Path,
scope: &workspace::Scope,
model: &BuildModel,
module: &Path,
test: bool,
kind: Option<compile::BuildKind>,
cancel: &CancellationToken,
on_event: &(dyn Fn(BuildEvent) + Sync),
) -> IdeResult<Option<LaunchOutputs>> {
let service =
ServiceBuild { service, data_dir, root: &scope.root, cache: &scope.cache, settings: &scope.settings, model };
match kind {
Some(kind) => service.build(Target::Launch { module, test }, kind, cancel, on_event),
// No build: the outputs of the last one, when there was one.
None => Ok(service
.with(module, |build| build.recorded_launch(module, test))
.flatten()
.map(|class_paths| LaunchOutputs { class_paths, ..Default::default() })),
}
}
/// A build of the IDE's Java build service in one project (or workspace member).
pub(crate) struct ServiceBuild<'a> {
pub service: &'a JavaBuildService,
pub data_dir: &'a Path,
pub root: &'a Path,
pub cache: &'a Path,
pub settings: &'a Settings,
pub model: &'a BuildModel,
}
impl ServiceBuild<'_> {
/// Runs `f` with the build, its JDKs resolved for `module`; `None` when the build jar
/// can't be installed.
fn with<R>(&self, module: &Path, f: impl FnOnce(&JavaBuild) -> R) -> Option<R> {
let jar = ide_sdk::java::java_build_jar(self.data_dir)?;
let (root, settings) = (self.root, self.settings);
let jdk = |release: Option<u32>| {
ide_sdk::apply::module_jdk(root, module, settings)
.or_else(|| ide_sdk::java::pick_jdk(&ide_sdk::java::installed_jdks(), release).cloned())
.map(|jdk| jdk.home)
};
let version = ide_sdk::java::java_build_version();
let build = JavaBuild {
root,
model: self.model,
cache: self.cache,
jar: &jar,
jar_version: &version,
local_repo: ide_sdk::apply::maven_local_repository(root, settings),
service: self.service,
jdk: &jdk,
};
Some(f(&build))
}
/// Builds `target`; `None` when the build tool has to (the service doesn't build it, or failed).
pub fn build(
&self,
target: Target,
kind: compile::BuildKind,
cancel: &CancellationToken,
on_event: &(dyn Fn(BuildEvent) + Sync),
) -> IdeResult<Option<LaunchOutputs>> {
let module = match target {
Target::Launch { module, .. } | Target::Module(module) | Target::File(module) => module,
Target::Project => self.root,
};
let Some(built) = self.with(module, |build| build.build(target, kind, cancel, on_event)) else {
return Ok(None);
};
match built {
Ok(Built::Done(outputs)) => Ok(Some(outputs)),
Ok(Built::Unsupported(reason)) => {
tracing::info!(module = %module.display(), reason, "Building with the build tool");
Ok(None)
}
Err(e) if e.kind == ErrorKind::Cancelled => Err(e),
Err(e) => {
tracing::warn!(module = %module.display(), "The IDE's Java build failed: {}", e.message);
on_event(BuildEvent::Output {
text: format!("The IDE's Java build failed, so the build tool builds it: {}\n", e.message),
stderr: true,
});
Ok(None)
}
}
}
}
fn load_launch_model(scope: &workspace::Scope) -> BuildModel {
with_profiles(load(&scope.root, &scope.cache, &scope.settings), &scope.cache)
}
@@ -225,6 +383,39 @@ fn is_maven_module(root: &Path, model: &BuildModel, module: &Path) -> bool {
model.maven.as_ref().is_some_and(|m| m.projects.iter().any(|p| root.join(&p.dir) == module))
}
/// Whether the IDE's Java build builds the module holding `path` (#4078): a Maven module unless
/// Settings › Maven › Delegate IDE build/run actions to Maven asks for Maven; a Gradle module
/// when Settings › Gradle › Build and run using asks for the IDE.
pub(crate) fn served_by_service(root: &Path, model: &BuildModel, settings: &Settings, path: &Path) -> bool {
let maven = model.maven.iter().flat_map(|m| m.projects.iter().map(|p| (root.join(&p.dir), true)));
let gradle = model.gradle.iter().flat_map(|g| g.projects.iter().map(|p| (root.join(&p.dir), false)));
// The deepest module holding it; Maven's when both build the folder.
let module = maven
.chain(gradle)
.filter(|(dir, _)| path.starts_with(dir))
.max_by_key(|(dir, maven)| (dir.components().count(), *maven));
match module {
Some((_, true)) => !settings.languages.java.maven.delegate_build,
Some((_, false)) => gradle_served(settings),
None => false,
}
}
/// Whether the IDE's Java build builds the whole project: it has Maven or Gradle builds, and
/// builds them all.
pub(crate) fn project_served_by_service(model: &BuildModel, settings: &Settings) -> bool {
let maven = model.maven.as_ref().map(|_| !settings.languages.java.maven.delegate_build);
let gradle = (!model.gradle.is_empty()).then(|| gradle_served(settings));
match (maven, gradle) {
(None, None) => false,
(maven, gradle) => maven.unwrap_or(true) && gradle.unwrap_or(true),
}
}
fn gradle_served(settings: &Settings) -> bool {
settings.languages.java.gradle.run_using == ide_core::settings::GradleRunUsing::Ide
}
/// A launch of a module jdtls doesn't serve (another Java language server, or none): the
/// build tool compiles it, and the classpath comes from that server, else from Maven.
#[allow(clippy::too_many_arguments)]
@@ -241,8 +432,9 @@ async fn resolve_launch_without_jdtls(
let started = std::time::Instant::now();
let scope = std::sync::Arc::new(scope);
let kind = if policy == BuildPolicy::Rebuild { compile::BuildKind::Rebuild } else { compile::BuildKind::Build };
let (model, built) = {
let (model, built, by_service) = {
let (scope, module, cancel, events) = (scope.clone(), module.clone(), cancel.clone(), events.clone());
let (service, data_dir) = (host.java_build.clone(), host.local_data_dir.clone());
tokio::task::spawn_blocking(move || {
let model = load_launch_model(&scope);
let on_event = |event: BuildEvent| {
@@ -250,12 +442,33 @@ async fn resolve_launch_without_jdtls(
events(event);
}
};
let built = if policy == BuildPolicy::NoBuild {
None
} else {
Some(compile::build_for_launch(&scope.root, &model, &module, test, kind, &cancel, &on_event))
};
(model, built)
if policy == BuildPolicy::NoBuild {
return (model, None, false);
}
if served_by_service(&scope.root, &model, &scope.settings, &module)
&& !compile::launch_has_non_java_sources(&scope.root, &model, &module, test)
{
match build_with_service(
&service,
&data_dir,
&scope,
&model,
&module,
test,
Some(kind),
&cancel,
&on_event,
) {
Ok(Some(outputs)) => {
let built = compile::LaunchBuild { class_dirs: outputs.class_paths, failure: outputs.failure };
return (model, Some(Ok(built)), true);
}
Ok(None) => {}
Err(e) => return (model, Some(Err(e)), false),
}
}
let built = compile::build_for_launch(&scope.root, &model, &module, test, kind, &cancel, &on_event);
(model, Some(built), false)
})
.await
.map_err(|e| IdeError::internal(e.to_string()))?
@@ -294,6 +507,12 @@ async fn resolve_launch_without_jdtls(
tokio::task::spawn_blocking(move || {
let (root, cache, settings) = (&scope.root, &scope.cache, &scope.settings);
match from_server {
// The IDE's Java build gave the whole classpath; the server adds its JDK.
Some(server) if by_service => {
info.project_root = server.classpath.project_root;
info.java_home = server.jdk_home.map(Into::into);
}
None if by_service => {}
Some(server) => {
info.project_root = server.classpath.project_root;
info.module_paths = server.classpath.module_paths;
+1 -1
Переглянути файл
@@ -8,7 +8,7 @@ use ide_core::proxy_settings::{ProxyMode, ProxySettings};
use std::time::Duration;
/// Whether `url` names this machine (`localhost` or a loopback address).
fn is_loopback(url: &reqwest::Url) -> bool {
pub fn is_loopback(url: &reqwest::Url) -> bool {
let host = url.host_str().unwrap_or_default().trim_start_matches('[').trim_end_matches(']');
host.eq_ignore_ascii_case("localhost") || host.parse::<std::net::IpAddr>().is_ok_and(|ip| ip.is_loopback())
}
+6 -4
Переглянути файл
@@ -125,8 +125,8 @@ impl Host {
// A window takes the root over from the MCP server's background project, whose
// shutdown the wait below sits out; none opens until this open is over.
let _claim = (!crate::mcp::BackgroundProjects::is_key(window)).then(|| self.mcp_background.claim(self, &root));
self.close_project(window);
self.wait_detached_closes();
self.close_project_detached(window);
self.wait_detached_closes_for(&root);
let sink: SharedSink = (self.sink_for)(window);
// Before anything the project starts: its children get the project's environment.
let trusted = Arc::new(AtomicBool::new(self.trust.window_trusted(&root)?));
@@ -867,8 +867,10 @@ impl Host {
}
return Ok(current);
}
self.close_project(window);
self.wait_detached_closes();
self.close_project_detached(window);
if let Some(dir) = watch_dir {
self.wait_detached_closes_for(dir);
}
let sink: SharedSink = (self.sink_for)(window);
let settings = Arc::new(SettingsStore::load(&self.config_dir, None));
let effective = settings.effective();
+215
Переглянути файл
@@ -0,0 +1,215 @@
mod common;
use ide_build::compile::BuildEvent;
use ide_core::RequestId;
use ide_host::{Host, ops};
use ide_run::BuildPolicy;
use ide_workspace::{SettingsStore, settings::SettingsScope};
use std::fs;
use std::path::Path;
use std::sync::{Arc, Mutex};
fn write(root: &Path, rel: &str, text: &str) {
let path = root.join(rel);
fs::create_dir_all(path.parent().unwrap()).unwrap();
fs::write(path, text).unwrap();
}
/// A Maven launch compiles with the IDE's Java build (javac, outputs in the project cache)
/// and runs from its outputs. Needs `mvn` and a JDK (`JAVA_HOME`), else it is skipped.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn maven_launch_compiles_with_the_ides_java_build() {
let has_jdk = std::env::var_os("JAVA_HOME").is_some_and(|h| Path::new(&h).join("bin").is_dir());
if !has_jdk || ide_core::process::find_executable("mvn", &ide_core::tool_path::search_path()).is_none() {
eprintln!("skipped: needs JAVA_HOME and mvn");
return;
}
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
let root = base.join("project");
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>app</module></modules>
<properties><maven.compiler.release>11</maven.compiler.release><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties></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,
"app/pom.xml",
r#"<project><modelVersion>4.0.0</modelVersion><parent><groupId>t</groupId><artifactId>root</artifactId><version>1</version></parent><artifactId>app</artifactId>
<dependencies><dependency><groupId>t</groupId><artifactId>lib</artifactId><version>1</version></dependency></dependencies></project>"#,
);
write(
&root,
"lib/src/main/java/l/L.java",
"package l;\npublic class L { public static String name() { return \"lib\"; } }\n",
);
write(
&root,
"app/src/main/java/a/A.java",
"package a;\npublic class A { public static void main(String[] args) { System.out.println(l.L.name()); } }\n",
);
// No language server: the build tool compiles the launch.
let global = SettingsStore::load(&base.join("config"), None);
for server in ["jdtls", "java-analyzer", "kmp-lsp"] {
global
.set(SettingsScope::Global, &format!("languageServers.{server}.enabled"), serde_json::json!(false))
.unwrap();
}
let host = Host::new(common::host_config(&base));
host.trust.decide(&root, true, false).unwrap();
host.open_project("main", &root).unwrap();
let events = Arc::new(Mutex::new(Vec::new()));
let sink = events.clone();
let channel = ops::Channel::new(move |event: BuildEvent| sink.lock().unwrap().push(event));
let info = ops::java::java_resolve_launch(
&host,
"main",
root.join("app"),
false,
false,
BuildPolicy::Make,
RequestId::next(),
channel,
)
.await
.unwrap();
let steps: Vec<String> = events
.lock()
.unwrap()
.iter()
.filter_map(|e| match e {
BuildEvent::Step { command, .. } => Some(command.clone()),
_ => None,
})
.collect();
assert!(steps.iter().any(|s| s.starts_with("javac lib")), "{steps:?}");
assert!(steps.iter().any(|s| s.starts_with("javac app")), "{steps:?}");
assert!(!steps.iter().any(|s| s.contains("-am")), "{steps:?}");
let first = Path::new(&info.class_paths[0]);
assert!(first.ends_with("out/t.app/classes"), "{:?}", info.class_paths);
assert!(first.join("a/A.class").is_file());
assert!(info.class_paths.iter().any(|p| Path::new(p).ends_with("out/t.lib/classes")), "{:?}", info.class_paths);
assert!(!root.join("app/target/classes").exists());
// Build › Build Project compiles with it too, and reports javac's errors.
write(&root, "lib/src/main/java/l/L.java", "package l;\npublic class L { }\n");
let built = ops::build::build_run(
&host,
"main",
ide_build::compile::BuildKind::Build,
None,
None,
RequestId::next(),
Vec::new(),
ops::Channel::new(|_: BuildEvent| {}),
)
.await
.unwrap();
assert_eq!(built.system, ide_build::compile::BuildSystem::Javac);
assert!(!built.success);
assert_eq!(built.errors, 1, "{:?}", built.messages);
assert!(built.messages[0].path.as_deref().is_some_and(|p| p.ends_with("a/A.java")), "{:?}", built.messages);
assert!(!root.join("lib/target/classes").exists());
host.shutdown().await;
}
/// With Settings › Gradle › Build and run using: IDE, a Gradle launch and Build Project compile
/// with the IDE's Java build too. Needs a JDK (`JAVA_HOME`) and Gradle (`OPENIDEA_TEST_GRADLE`).
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn gradle_launch_compiles_with_the_ides_java_build() {
let has_jdk = std::env::var_os("JAVA_HOME").is_some_and(|h| Path::new(&h).join("bin").is_dir());
let Some(gradle) = std::env::var_os("OPENIDEA_TEST_GRADLE").filter(|_| has_jdk) else {
eprintln!("skipped: needs JAVA_HOME and OPENIDEA_TEST_GRADLE");
return;
};
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
let root = base.join("project");
write(&root, "settings.gradle", "rootProject.name = 'root'\ninclude 'lib', 'app'\n");
write(&root, "build.gradle", "subprojects {\n apply plugin: 'java'\n group = 't'\n}\n");
write(&root, "lib/build.gradle", "");
write(&root, "app/build.gradle", "dependencies { implementation project(':lib') }\n");
write(&root, "gradlew", &format!("#!/bin/sh\nexec '{}' \"$@\"\n", Path::new(&gradle).display()));
use std::os::unix::fs::PermissionsExt;
fs::set_permissions(root.join("gradlew"), fs::Permissions::from_mode(0o755)).unwrap();
write(
&root,
"lib/src/main/java/l/L.java",
"package l;\npublic class L { public static String name() { return \"lib\"; } }\n",
);
write(
&root,
"app/src/main/java/a/A.java",
"package a;\npublic class A { public static void main(String[] args) { System.out.println(l.L.name()); } }\n",
);
let global = SettingsStore::load(&base.join("config"), None);
for server in ["jdtls", "java-analyzer", "kmp-lsp"] {
global
.set(SettingsScope::Global, &format!("languageServers.{server}.enabled"), serde_json::json!(false))
.unwrap();
}
global.set(SettingsScope::Global, "languages.java.gradle.runUsing", serde_json::json!("ide")).unwrap();
let host = Host::new(common::host_config(&base));
host.trust.decide(&root, true, false).unwrap();
host.open_project("main", &root).unwrap();
let events = Arc::new(Mutex::new(Vec::new()));
let sink = events.clone();
let channel = ops::Channel::new(move |event: BuildEvent| sink.lock().unwrap().push(event));
let info = ops::java::java_resolve_launch(
&host,
"main",
root.join("app"),
false,
false,
BuildPolicy::Make,
RequestId::next(),
channel,
)
.await
.unwrap();
let steps: Vec<String> = events
.lock()
.unwrap()
.iter()
.filter_map(|e| match e {
BuildEvent::Step { command, .. } => Some(command.clone()),
_ => None,
})
.collect();
assert!(steps.iter().any(|s| s.contains("openideaBuildModel")), "{steps:?}");
assert!(steps.iter().any(|s| s.starts_with("javac lib")), "{steps:?}");
assert!(steps.iter().any(|s| s.starts_with("javac app")), "{steps:?}");
let first = Path::new(&info.class_paths[0]);
assert!(first.ends_with("out/t.app/classes"), "{:?}", info.class_paths);
assert!(first.join("a/A.class").is_file());
assert!(info.class_paths.iter().any(|p| Path::new(p).ends_with("out/t.lib/classes")), "{:?}", info.class_paths);
assert!(!root.join("app/build/classes").exists());
write(&root, "lib/src/main/java/l/L.java", "package l;\npublic class L { }\n");
let built = ops::build::build_run(
&host,
"main",
ide_build::compile::BuildKind::Build,
None,
None,
RequestId::next(),
Vec::new(),
ops::Channel::new(|_: BuildEvent| {}),
)
.await
.unwrap();
assert_eq!(built.system, ide_build::compile::BuildSystem::Javac);
assert_eq!(built.errors, 1, "{:?}", built.messages);
assert!(built.messages[0].path.as_deref().is_some_and(|p| p.ends_with("a/A.java")), "{:?}", built.messages);
host.shutdown().await;
}
+12 -1
Переглянути файл
@@ -745,7 +745,18 @@ async fn upgraded_build_refuses_live_work_and_then_replaces_idle_backend() {
.unwrap();
until("old backend socket", || guard.0.exists()).await;
let old_open = || async {
let mut stream = UnixStream::connect(&guard.0).await.unwrap();
// bind() creates the socket file before listen(): a connect in between is refused.
let mut stream = 'connect: {
for _ in 0..600 {
match UnixStream::connect(&guard.0).await {
Err(e) if e.kind() == std::io::ErrorKind::ConnectionRefused => {
tokio::time::sleep(Duration::from_millis(15)).await;
}
other => break 'connect other.unwrap(),
}
}
panic!("the old backend never accepted a connection");
};
stream.write_all(OLD_BUILD.as_bytes()).await.unwrap();
assert_eq!(stream.read_u8().await.unwrap(), b'A');
let (reader, writer) = stream.into_split();
+15 -5
Переглянути файл
@@ -88,10 +88,18 @@ done
let events = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
let sink = events.clone();
let channel = ops::Channel::new(move |event: ide_build::compile::BuildEvent| sink.lock().unwrap().push(event));
let info =
ops::java::java_resolve_launch(&host, "main", module, test, BuildPolicy::Make, RequestId::next(), channel)
.await
.unwrap();
let info = ops::java::java_resolve_launch(
&host,
"main",
module,
test,
false,
BuildPolicy::Make,
RequestId::next(),
channel,
)
.await
.unwrap();
// The build streams its command and progress while it runs.
use ide_build::compile::BuildEvent;
let events = events.lock().unwrap();
@@ -110,7 +118,9 @@ done
assert!(info.class_paths.iter().any(|p| std::path::Path::new(p) == out));
assert!(info.class_paths.iter().any(|p| std::path::Path::new(p) == jar));
let calls = fs::read_to_string(root.join("calls")).unwrap();
assert!(calls.lines().next().unwrap().contains("-pl app -am"), "{calls}");
// This Maven records no build model for the IDE's Java build, so Maven builds the module.
assert!(calls.lines().next().unwrap().contains("-Dopenidea.build.model="), "{calls}");
assert!(calls.lines().nth(1).unwrap().contains("-pl app -am"), "{calls}");
assert!(calls.lines().all(|line| line.contains(&format!("-P member-{index}"))), "{calls}");
assert!(calls.contains(":build-classpath"), "{calls}");
}
+42 -2
Переглянути файл
@@ -342,6 +342,27 @@ impl Drop for JavaExternalBuild {
}
}
/// The Gradle tooling API's own messages for a build that failed, ahead of its cause.
const GRADLE_TOOLING_FAILURES: [&str; 4] = [
"The supplied phased action failed with an exception",
"Could not run phased build action",
"Could not run build action",
"Could not fetch model of type",
];
/// A diagnostic's message on one line. Buildship marks a Gradle project whose sync failed with
/// the tooling API's message on the first line and the build's own error last ("… failed with
/// an exception.\nA problem occurred evaluating root project 'app'.\n<the error>"); that error is
/// kept as the cause.
fn launch_message(message: &str) -> String {
let mut lines = message.lines().map(str::trim).filter(|l| !l.is_empty());
let first = lines.next().unwrap_or_default();
match lines.next_back() {
Some(cause) if GRADLE_TOOLING_FAILURES.iter().any(|m| first.contains(m)) => format!("{first} Cause: {cause}"),
_ => first.to_owned(),
}
}
/// Error diagnostics sorted by file and position, capped at `limit`, and their total.
pub fn compile_errors(
diagnostics: Vec<(PathBuf, lsp_types::Diagnostic)>,
@@ -354,7 +375,7 @@ pub fn compile_errors(
path: path.into(),
line: d.range.start.line + 1,
column: d.range.start.character + 1,
message: d.message.lines().next().unwrap_or_default().to_owned(),
message: launch_message(&d.message),
})
.collect();
errors.sort_by(|a, b| (&a.path, a.line, a.column).cmp(&(&b.path, b.line, b.column)));
@@ -535,7 +556,8 @@ fn build_file_errors(diagnostics: &[(PathBuf, lsp_types::Diagnostic)], root: &Pa
&& path.parent().is_some_and(|dir| module.starts_with(dir))
})
.map(|(path, d)| {
let message = d.message.lines().next().unwrap_or_default().trim().trim_end_matches(':');
let message = launch_message(&d.message);
let message = message.trim().trim_end_matches(':');
(path.components().count(), format!("{}: {message}", path.strip_prefix(root).unwrap_or(path).display()))
})
.collect();
@@ -1638,6 +1660,24 @@ mod tests {
assert_eq!(std::fs::read_to_string(prefs).unwrap(), format!("{}=error\n", ACCESS_OPTIONS[0]));
}
#[test]
fn a_failed_gradle_sync_keeps_its_cause_on_one_line() {
let marker = "The supplied phased action failed with an exception.\n\
A problem occurred configuring root project 'app'.\n\
A problem occurred evaluating root project 'app'.\n\
missing generated schema";
assert_eq!(
launch_message(marker),
"The supplied phased action failed with an exception. Cause: missing generated schema"
);
assert_eq!(
launch_message("The supplied phased action failed with an exception."),
"The supplied phased action failed with an exception."
);
// Other messages keep their first line only.
assert_eq!(launch_message("x cannot be resolved\nmore detail"), "x cannot be resolved");
}
#[test]
fn access_warnings_do_not_hide_real_compile_errors() {
let path = PathBuf::from("src/Main.java");
+104
Переглянути файл
@@ -1188,3 +1188,107 @@ async fn phoxite_pulls_a_member_up_end_to_end() {
assert!(!refused.message.is_empty() && !refused.message.starts_with("phoxite:"), "{refused:?}");
mgr.shutdown_all().await;
}
/// jdtls keeps building incrementally even though the IDE's Java build compiles what runs:
/// its build is what reports an API change in one Maven module in the files of the modules
/// that use it, open or not. With `java.autobuild.enabled: false` (and
/// `validateAllOpenBuffersOnChanges`), neither updates.
#[tokio::test(flavor = "multi_thread")]
#[ignore = "requires jdtls on PATH (or OPENIDEA_TEST_JDTLS) and a compatible JDK"]
async fn jdtls_build_reports_cross_module_errors_in_open_and_closed_files() {
let dir = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(dir.path()).unwrap().join("project");
let write = |rel: &str, text: &str| {
let path = root.join(rel);
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(&path, text).unwrap();
path
};
let parent = r#"<parent><groupId>t</groupId><artifactId>root</artifactId><version>1</version></parent>"#;
write(
"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>app</module></modules><properties><maven.compiler.release>11</maven.compiler.release></properties></project>"#,
);
write(
"lib/pom.xml",
&format!("<project><modelVersion>4.0.0</modelVersion>{parent}<artifactId>lib</artifactId></project>"),
);
write(
"app/pom.xml",
&format!(
"<project><modelVersion>4.0.0</modelVersion>{parent}<artifactId>app</artifactId><dependencies><dependency><groupId>t</groupId><artifactId>lib</artifactId><version>1</version></dependency></dependencies></project>"
),
);
let lib_source = "package l;\npublic class L { public static String name() { return \"lib\"; } }\n";
let app_source = "package a;\npublic class A { String s = l.L.name(); }\n";
let lib = write("lib/src/main/java/l/L.java", lib_source);
let app = write("app/src/main/java/a/A.java", app_source);
let closed = write("app/src/main/java/a/B.java", "package a;\nclass B { String s = l.L.name(); }\n");
let mut java = LanguageRegistry::load(None).unwrap().get(&LanguageId::new("java")).unwrap();
java.language_servers.retain(|s| s.name == "jdtls");
let server = &mut java.language_servers[0];
if let Ok(bin) = std::env::var("OPENIDEA_TEST_JDTLS") {
server.command = bin;
}
server.args.extend(["-data".into(), dir.path().join("jdtls-data").to_string_lossy().into_owned()]);
let (mgr, events) = manager(&root, LanguageRegistry::from_configs(vec![java]));
let (lib_doc, app_doc) = (DocId::next(), DocId::next());
mgr.did_open(lib_doc, &lib, &LanguageId::new("java"), 1, lib_source);
mgr.did_open(app_doc, &app, &LanguageId::new("java"), 1, app_source);
let errors = |path: &Path| {
events.lock().iter().rev().find_map(|e| match e {
IdeEvent::Diagnostics { path: p, items, .. } if p.0 == path => Some(
items
.iter()
.filter(|d| d.severity == ide_core::Severity::Error)
.map(|d| d.message.clone())
.collect::<Vec<_>>(),
),
_ => None,
})
};
// The import resolves `lib` from source: the open editor of `app` has no errors.
retry("app imported", Duration::from_secs(300), || {
let status = last_status(&events, "jdtls");
if let Some((ServerStatus::Crashed | ServerStatus::Missing | ServerStatus::Misconfigured, message)) = &status {
panic!("jdtls failed: {message:?}");
}
let clean = errors(&app).is_some_and(|e| e.is_empty());
let mgr = mgr.clone();
let app = app.clone();
async move {
let cp =
tokio::time::timeout(Duration::from_secs(10), mgr.java_classpath(&app, false, &Default::default()))
.await
.ok()?
.ok()?;
(clean && cp.class_paths.iter().any(|p| p.contains("/lib/"))).then_some(())
}
})
.await;
// Rename the method in the editor of `lib`, and save.
let renamed = lib_source.replace("name()", "title()");
let line = lib_source.lines().nth(1).unwrap();
mgr.did_change(
lib_doc,
2,
&[AppliedChange {
range: Range::new(Pos::new(1, 0), Pos::new(1, line.len() as u32)),
text: renamed.lines().nth(1).unwrap().to_owned(),
}],
&|| renamed.clone(),
);
std::fs::write(&lib, &renamed).unwrap();
mgr.did_save(lib_doc, &renamed);
retry("the open editor of app reports the removed method", Duration::from_secs(120), || {
let found = errors(&app).is_some_and(|e| e.iter().any(|m| m.contains("name()")));
async move { found.then_some(()) }
})
.await;
retry("the closed file of app reports it too", Duration::from_secs(60), || {
let found = errors(&closed).is_some_and(|e| e.iter().any(|m| m.contains("name()")));
async move { found.then_some(()) }
})
.await;
tokio::time::timeout(Duration::from_secs(10), mgr.shutdown_all()).await.unwrap();
}
+1 -1
Переглянути файл
@@ -21,7 +21,7 @@ mod utf8;
pub mod wrap;
pub use detect::cmake::{build_configs as cmake_build_configs, prepare as prepare_cmake};
pub use process::{ProcessManager, StartOptions};
pub use process::{DetachedProcessKills, ProcessManager, StartOptions};
use ide_core::{IdeResult, RunId};
use serde::{Deserialize, Serialize};
+26 -3
Переглянути файл
@@ -888,15 +888,25 @@ impl ProcessManager {
}
}
/// Kills every running process tree at once (shutting down).
pub fn kill_project(&self, root: &Path) {
/// Collects every running process tree for `root` and marks it stopping so the actual
/// termination can run on a background thread without blocking the UI thread or racing
/// processes started later.
pub fn detach_project_kills(&self, root: &Path) -> DetachedProcessKills {
let mut targets = Vec::new();
for entry in self.runs.lock().values().filter(|e| e.project_root == root) {
if !entry.exited.load(Ordering::Acquire)
&& let Some(pid) = *entry.pid.lock()
{
kill_tree(entry, pid, true);
entry.stopping.store(true, Ordering::Release);
targets.push((entry.clone(), pid));
}
}
DetachedProcessKills(targets)
}
/// Kills every running process tree at once (shutting down).
pub fn kill_project(&self, root: &Path) {
self.detach_project_kills(root).kill();
}
pub fn kill_all(&self) {
@@ -939,6 +949,19 @@ impl ProcessManager {
}
}
/// Running process trees snapshotted from [`ProcessManager`] to be killed off the caller's thread.
pub struct DetachedProcessKills(Vec<(Arc<Entry>, u32)>);
impl DetachedProcessKills {
pub fn kill(self) {
for (entry, pid) in self.0 {
if !entry.exited.load(Ordering::Acquire) {
kill_tree(&entry, pid, true);
}
}
}
}
impl Drop for ProcessManager {
fn drop(&mut self) {
self.kill_all();
+17
Переглянути файл
@@ -1654,6 +1654,23 @@ pub fn junit_runner_jar(data_dir: &Path) -> Option<PathBuf> {
)
}
/// The IDE's Java build (`java/java-build`): the resident javac server and the Maven
/// extension that records the build model.
const JAVA_BUILD: &[u8] = include_bytes!("../../../java/java-build/openidea-java-build.jar");
/// Extracts the Java build jar into the application's data directory.
pub fn java_build_jar(data_dir: &Path) -> Option<PathBuf> {
install_bundle(data_dir, "java-build", "1.0.0", JAVA_BUILD)
}
/// Changes whenever the embedded Java build jar does (FNV-1a of its bytes), so build models
/// recorded by an older extension are prepared again.
pub fn java_build_version() -> String {
let hash =
JAVA_BUILD.iter().fold(0xcbf2_9ce4_8422_2325u64, |h, b| (h ^ u64::from(*b)).wrapping_mul(0x100_0000_01b3));
format!("{hash:016x}")
}
/// The JUnit Platform launcher a test classpath needs to start the runner.
#[derive(Debug, PartialEq)]
pub enum JunitLauncher {
+4 -3
Переглянути файл
@@ -11,7 +11,7 @@ use ide_core::settings::Settings;
use ide_language::LanguageServerConfig;
use ide_run::RunConfig;
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::path::Path;
use std::time::Duration;
fn fake_venv(root: &Path, name: &str) -> std::path::PathBuf {
@@ -2103,8 +2103,9 @@ fn the_flutter_sdk_setting_picks_flutter_and_dart_for_server_and_run_configurati
// Saved configurations keep the bare name.
assert_eq!(crate::apply::without_derived(&configs[0], tmp.path(), &s).command, "flutter");
// An explicit tool path still wins.
s.tools.insert("dart".into(), ide_core::settings::ToolSettings { path: "/opt/dart/bin/dart".into() });
assert_eq!(crate::apply::tool_command(tmp.path(), &s, "dart"), Some(PathBuf::from("/opt/dart/bin/dart")));
let explicit = tmp.path().join("opt").join("dart");
s.tools.insert("dart".into(), ide_core::settings::ToolSettings { path: explicit.to_string_lossy().into_owned() });
assert_eq!(crate::apply::tool_command(tmp.path(), &s, "dart"), Some(explicit));
}
#[test]
+20 -5
Переглянути файл
@@ -510,13 +510,17 @@ impl TerminalManager {
}
}
/// Detaches every terminal opened by `key` so it can be terminated on a background thread
/// without blocking the caller or racing a new project opened in the same window.
pub fn detach_key(&self, key: &str) -> DetachedTerminals {
let mut sessions = self.sessions.lock();
let ids: Vec<TerminalId> = sessions.iter().filter(|(_, s)| s.key == key).map(|(id, _)| *id).collect();
DetachedTerminals(ids.into_iter().filter_map(|id| sessions.remove(&id)).collect())
}
/// Closes the terminals `key` opened: the project of that window is closing.
pub fn kill_key(&self, key: &str) {
let ids: Vec<TerminalId> =
self.sessions.lock().iter().filter(|(_, s)| s.key == key).map(|(id, _)| *id).collect();
for id in ids {
let _ = self.kill(id);
}
self.detach_key(key).terminate();
}
pub fn kill(&self, id: TerminalId) -> IdeResult<()> {
@@ -733,6 +737,17 @@ mod win {
}
}
/// Terminal sessions detached from [`TerminalManager`] to be terminated off the caller's thread.
pub struct DetachedTerminals(Vec<Arc<Session>>);
impl DetachedTerminals {
pub fn terminate(self) {
for session in self.0 {
terminate(&session);
}
}
}
/// Hangs up the shell (and its process group), escalating to SIGKILL if it lingers.
fn terminate(session: &Session) {
let (writer, killer) = match &session.io {
+8
Переглянути файл
@@ -5,6 +5,14 @@ description: "Carets and selections, line editing, the clipboard history, foldin
The editor follows IntelliJ IDEA's behaviour and default keymap. Shortcuts below are the defaults of the **macOS** keymap on macOS and the **Windows** keymap on Windows and Linux; you can change any of them in **Settings › Keymap** (see [Keymaps](/en/guide/keymap)). Every command is also available from **Find Action** (`⇧⌘A` / `Ctrl+Shift+A`).
## Browse a local development server
In a trusted local project, use **Find Action › Open Local Browser**. Enter a loopback HTTP or HTTPS URL, then choose **Open**. Links, **Back**, **Forward**, and **Reload** operate on the page in the panel. Hiding the panel preserves the page and its history; **Close** ends the session. Navigation stays on the original origin. To switch development servers or ports, close the session and open the new address.
Clicking a URL in a Run or Debug console still opens it in the external browser. To open a localhost URL in the panel instead, right-click it and choose **Open in Browser Tool Window**.
Choose **Inspect Element**, then click an element in the page. Review its selector, opening tag and styles before choosing **Add to Agent Draft**. This appends to the draft without sending it. Press **Escape** in the page to return to normal browsing without selecting anything.
## Carets and selections
| Action | macOS | Windows / Linux |
+8
Переглянути файл
@@ -5,6 +5,14 @@ description: "多光标与选区、行编辑、剪贴板历史、代码折叠、
编辑器的行为和默认快捷键沿用 IntelliJ IDEA。下文的快捷键在 macOS 上是 **macOS** 键位映射的默认值,在 Windows 和 Linux 上是 **Windows** 键位映射的默认值;任何一个都可以在 **设置 › 按键映射** 中修改(见 [键位映射](/zh/guide/keymap))。所有命令也都能在 **查找操作**(`⇧⌘A` / `Ctrl+Shift+A`)里找到。
## 浏览本地开发服务器
在受信任的本地项目中,选择**查找操作 › 打开本地浏览器**。输入指向本机回环地址的 HTTP 或 HTTPS 网址,点击**打开**。可以直接在面板中点击链接、后退、前进和重新加载。隐藏面板会保留页面和浏览历史;点击**关闭**才会结束会话。浏览范围限于原来的源;如需切换开发服务器或端口,请先关闭会话,再打开新地址。
点击运行或调试控制台中的网址仍会在外部浏览器中打开。如需在此面板中打开本机地址,右键点击该地址并选择**在浏览器工具窗口中打开**。
点击**检查元素**,然后在页面中点选元素。确认选择器、起始标签和样式后,可将其添加到 Agent 草稿,不会自动发送。在页面中按 **Escape** 可退出检查并继续浏览。
## 光标与选区
| 操作 | macOS | Windows / Linux |
+11 -16
Переглянути файл
@@ -40,17 +40,14 @@ const entries: AgentEntry[] = Array.from({ length: 80 }, (_, turn): AgentEntry[]
},
]).flat();
/** Opens the 80-turn chat; `foldTurns` folds each earlier turn's work into one row. */
async function openHistory(page: Page, foldTurns = false) {
/** Opens the 80-turn chat; each turn's consecutive tool calls and reasoning fold into one row. */
async function openHistory(page: Page) {
await page.goto("/");
await page.getByRole("tree", { name: "Project" }).waitFor();
await page.evaluate(
async ({ task, entries, foldTurns }) => {
async ({ task, entries }) => {
const path = "/src/features/agents/store.ts";
const projectPath = "/src/platform/project.ts";
const store = await import(path);
const { useProject } = await import(projectPath);
useProject.setState({ settings: { agents: { foldTurns } } });
store.useAgents.setState({
loaded: true,
error: null,
@@ -62,12 +59,11 @@ async function openHistory(page: Page, foldTurns = false) {
});
store.openTaskInEditorLocation(task.id);
},
{ task, entries, foldTurns },
{ task, entries },
);
const stream = page.locator("[class*='_stream_']:visible");
// A turn shows its request, the read and the reasoning runs, the command, the edit and the reply;
// folded, its work is one row. The latest turn stays open.
await expect(stream.locator(":scope > *")).toHaveCount(foldTurns ? 79 * 3 + 6 : 80 * 6);
// Each turn shows its request, its folded process run and its reply.
await expect(stream.locator(":scope > *")).toHaveCount(80 * 3);
await page.evaluate(() => document.fonts.ready);
return stream;
}
@@ -91,7 +87,7 @@ for (const placement of ["editor", "toolWindow"] as const) {
);
// The working indicator ends the conversation, after its rows; the turn ends with a reply.
await expect(stream.getByRole("status").getByText("Writing…", { exact: true })).toBeVisible();
await expect(stream.locator(":scope > *")).toHaveCount(80 * 6 + 1);
await expect(stream.locator(":scope > *")).toHaveCount(80 * 3 + 1);
await expect.poll(() => stream.evaluate((el) => el.scrollHeight - el.clientHeight - el.scrollTop)).toBeLessThan(2);
const timer = await page.evaluate(async (id) => {
const path = "/src/features/agents/store.ts";
@@ -191,21 +187,20 @@ for (const selected of [false, true]) {
});
}
test("opens a folded turn with the keyboard and jumps back to the latest reply", async ({ page }) => {
const stream = await openHistory(page, true);
test("opens a folded process run with the keyboard and jumps back to the latest reply", async ({ page }) => {
const stream = await openHistory(page);
await stream.evaluate((el) => {
el.scrollTop = 0;
});
const jump = page.getByRole("button", { name: "Jump to Latest" });
await expect(jump).toBeVisible();
const fold = stream.locator("[class*='_turnFold_']").first();
const fold = stream.locator("[class*='_processRun_']").first();
const summary = fold.locator(":scope > summary");
await summary.focus();
await page.keyboard.press("Enter");
await expect(fold).toHaveAttribute("open", "");
// A folded turn lists its work without nesting runs.
await expect(fold.locator("[class*='_processRun_']")).toHaveCount(0);
await expect(fold.getByText("read src/module-0.ts", { exact: true })).toBeVisible();
await expect(fold.getByText("execute src/module-0.ts", { exact: true })).toBeVisible();
await summary.focus();
await page.keyboard.press("Space");
await expect(fold).not.toHaveAttribute("open", "");
+27 -33
Переглянути файл
@@ -72,9 +72,9 @@ const entries: AgentEntry[] = [
{ type: "agent", text: "Glad it helped." },
];
async function showImages(page: Page, foldTurns = true) {
async function showImages(page: Page) {
await page.evaluate(
async ({ task, entries, foldTurns }) => {
async ({ task, entries }) => {
const storePath = "/src/features/agents/store.ts";
const projectPath = "/src/platform/project.ts";
const ipcPath = "/src/platform/ipc.ts";
@@ -82,7 +82,7 @@ async function showImages(page: Page, foldTurns = true) {
const { useProject } = await import(projectPath);
const { commands } = await import(ipcPath);
commands.agentEntries = async () => ({ status: "ok", data: entries });
useProject.setState({ settings: { agents: { foldTurns, toolCalls: "grouped" } } });
useProject.setState({ settings: { agents: { toolCalls: "grouped" } } });
store.useAgents.setState({
loaded: true,
error: null,
@@ -92,39 +92,33 @@ async function showImages(page: Page, foldTurns = true) {
});
store.openTaskInEditorLocation(task.id);
},
{ task, entries, foldTurns },
{ task, entries },
);
}
for (const foldTurns of [true, false]) {
test(`tool images remain visible and open a full preview with turn folding=${foldTurns}`, async ({
workbench: page,
}) => {
if (!foldTurns) await page.setViewportSize({ width: 700, height: 750 });
await showImages(page, foldTurns);
await expect(page.getByText("The preview is ready: front, side and back.", { exact: true })).toBeVisible();
const preview = page.getByRole("img", { name: "Image", exact: true });
await expect(preview).toBeVisible();
await expect(preview).toHaveJSProperty("naturalWidth", 900);
expect(await preview.evaluate((img) => img.closest("details") === null)).toBe(true);
const box = (await preview.boundingBox())!;
expect(box.x).toBeGreaterThanOrEqual(0);
expect(box.x + box.width).toBeLessThanOrEqual(page.viewportSize()!.width);
const fold = page.locator("details").first();
await expect(fold).not.toHaveAttribute("open");
if (foldTurns) await expect(fold.locator("summary").first()).toContainText("1s");
else await expect(fold.locator("summary").first()).not.toContainText("1s");
await preview.click();
const dialog = page.getByRole("dialog", { name: "Image", exact: true });
await expect(dialog.getByRole("img")).toHaveJSProperty("naturalWidth", 900);
await dialog.getByText("Close", { exact: true }).click();
await expect(dialog).toHaveCount(0);
await fold.locator("summary").first().click();
await expect(preview).toHaveCount(1);
await fold.locator("summary").first().click();
await expect(preview).toBeVisible();
});
}
test("tool images remain visible and open a full preview", async ({ workbench: page }) => {
await page.setViewportSize({ width: 700, height: 750 });
await showImages(page);
await expect(page.getByText("The preview is ready: front, side and back.", { exact: true })).toBeVisible();
const preview = page.getByRole("img", { name: "Image", exact: true });
await expect(preview).toBeVisible();
await expect(preview).toHaveJSProperty("naturalWidth", 900);
expect(await preview.evaluate((img) => img.closest("details") === null)).toBe(true);
const box = (await preview.boundingBox())!;
expect(box.x).toBeGreaterThanOrEqual(0);
expect(box.x + box.width).toBeLessThanOrEqual(page.viewportSize()!.width);
const fold = page.locator("details").first();
await expect(fold).not.toHaveAttribute("open");
await preview.click();
const dialog = page.getByRole("dialog", { name: "Image", exact: true });
await expect(dialog.getByRole("img")).toHaveJSProperty("naturalWidth", 900);
await dialog.getByText("Close", { exact: true }).click();
await expect(dialog).toHaveCount(0);
await fold.locator("summary").first().click();
await expect(preview).toHaveCount(1);
await fold.locator("summary").first().click();
await expect(preview).toBeVisible();
});
test("copies full-size PNG pixels from the thumbnail menu and the image preview", async ({
workbench: page,
+248
Переглянути файл
@@ -0,0 +1,248 @@
import { readFileSync } from "node:fs";
import type { Page } from "@playwright/test";
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
const script = readFileSync(new URL("../src-tauri/src/browser_picker/element.js", import.meta.url), "utf8");
const element = {
selector: "main:nth-of-type(1) > button:nth-of-type(2)",
html: '<button aria-disabled="true">',
styles: "display: inline-flex;\nposition: relative;\nvisibility: visible;\npointer-events: none;",
};
test("a trusted gesture captures structure without page text or form values", async ({ page }) => {
await page.addInitScript({ content: script });
await page.route("http://localhost:3000/**", (route) =>
route.fulfill({
contentType: "text/html",
body: '<main><input type="password" value="fixture-password"><button>First</button><button disabled data-note="fixture-note" style="display:inline-flex">Fixture customer</button></main><iframe srcdoc="<p>Frame</p>"></iframe>',
}),
);
await page.goto("http://localhost:3000/sample?key=fixture-key");
const button = page.getByRole("button", { name: "Fixture customer" });
await page.getByRole("button", { name: "First" }).click();
expect(await page.evaluate("window.__openideaPickedElement")).toBeNull();
await page.evaluate("window.__openideaInspect(true)");
await button.dispatchEvent("pointerdown", { isPrimary: true, button: 0 });
expect(await page.evaluate("window.__openideaPickedElement")).toBeNull();
expect(await page.frames()[1]!.evaluate("window.__openideaPickedElement")).toBeUndefined();
const rect = await button.boundingBox();
await page.mouse.click(rect!.x + 4, rect!.y + 4);
const picked = await page.evaluate(() => String(Reflect.get(window, "__openideaPickedElement")));
expect(JSON.parse(picked)).toMatchObject({
path: [
{ tag: "html", index: 1 },
{ tag: "body", index: 1 },
{ tag: "main", index: 1 },
{ tag: "button", index: 2 },
],
disabled: true,
display: "inline-flex",
});
expect(picked).not.toMatch(/fixture-|Fixture customer|First/);
await page.evaluate("window.__openideaInspect(true)");
await page.keyboard.press("Escape");
expect(await page.evaluate("window.__openideaPickedElement")).toBe("cancel");
});
async function openBrowser(page: Page) {
await page.evaluate(async () => {
const actions = "/src/platform/actions.ts";
await (await import(actions)).executeAction("web.openLocalBrowser");
});
await expect(page.getByRole("textbox", { name: "Local page URL" })).toBeVisible();
}
async function stubBrowser(page: Page) {
await page.evaluate((snapshot) => {
let history: string[] = [],
index = 0,
inspecting = false;
window.__ipc.handlers.cancel_request = () => null;
window.__ipc.handlers.web_browser_open = ({ url }) => {
history = [String(url)];
index = 0;
};
window.__ipc.handlers.web_browser_control = ({ action }) => {
const command = action as { type: string; url: string };
let element = null;
switch (command.type) {
case "navigate":
history.splice(++index, Infinity, command.url);
break;
case "back":
index--;
break;
case "forward":
index++;
break;
case "inspect":
inspecting = true;
break;
case "cancel":
inspecting = false;
break;
case "status":
if (inspecting && !document.body.hasAttribute("data-hold-pick")) {
inspecting = false;
element = snapshot;
}
}
return { url: history[index], canBack: index > 0, canForward: index + 1 < history.length, inspecting, element };
};
}, element);
}
async function visit(page: Page, url: string) {
await page.getByLabel("Local page URL").fill(url);
await page.getByLabel("Local page URL").press("Enter");
}
for (const key of ["home", "checkout-task"]) {
test(`review appends to the ${key === "home" ? "new" : "active"} Codex task draft`, async ({
workbench: page,
}, info) => {
await stubDesktop(page);
await stubBrowser(page);
await page.evaluate(async (key) => {
const storePath = "/src/features/agents/store.ts";
const store = await import(storePath);
const task = {
id: key,
title: "Checkout review",
provider: "codex",
status: "ready",
isolation: "local",
model: null,
cwd: "/dev/acme-api",
branch: null,
base: null,
baseCommit: null,
error: null,
createdMs: 0,
updatedMs: 0,
config: [],
commands: [],
usage: null,
queue: [],
};
store.useAgents.setState({
loaded: true,
sessionLocation: key === "home" ? "editor" : "toolWindow",
...(key === "home"
? {}
: { tasks: new Map([[key, task]]), entries: new Map([[key, []]]), docked: key, homeOpen: false }),
draft: { provider: "codex", config: {}, isolation: "local", base: null },
});
store.updateComposer(key, {
text: "Why is the checkout button disabled?",
files: [{ path: "/dev/acme-api/README.md", rel: "README.md", attached: true }],
});
}, key);
await openBrowser(page);
await visit(page, "http://localhost:3000");
await page.getByRole("button", { name: "Inspect Element", exact: true }).click();
await expect(page.getByRole("heading", { name: "Selected element" })).toBeVisible();
await expect(page.getByText(element.html, { exact: false })).toBeVisible();
await page.screenshot({ path: info.outputPath("preview.png"), animations: "disabled" });
await page.getByRole("button", { name: "Add to Agent Draft" }).click();
const box = page.getByRole("textbox", { name: "Message", exact: true });
await expect(box).toBeVisible();
const draft = await page.evaluate(async (key) => {
const storePath = "/src/features/agents/store.ts";
const store = await import(storePath);
return {
...store.composerDraft(key),
provider:
key === "home"
? store.useAgents.getState().draft.provider
: store.useAgents.getState().tasks.get(key)?.provider,
};
}, key);
expect(draft).toMatchObject({
text: expect.stringContaining("Why is the checkout button disabled?\n\n"),
files: [{ path: "/dev/acme-api/README.md", rel: "README.md", attached: true }],
provider: "codex",
});
expect(draft.text).toContain(element.selector);
expect(draft.text).toContain(element.html);
expect(draft.text).toContain(element.styles);
await expect(box).toBeEditable();
await page.screenshot({ path: info.outputPath("draft.png"), animations: "disabled" });
expect(await ipcCalls(page, "agent_prompt")).toEqual([]);
expect(await ipcCalls(page, "agent_create")).toEqual([]);
});
}
test("cancelling or revoking trust discards a delayed selection", async ({ workbench: page }) => {
await stubDesktop(page);
await stubBrowser(page);
await page.evaluate(() => document.body.setAttribute("data-hold-pick", ""));
await openBrowser(page);
await visit(page, "http://localhost:3000");
const inspect = page.getByRole("button", { name: "Inspect Element", exact: true });
await inspect.click();
await expect(inspect).toHaveAttribute("aria-pressed", "true");
await inspect.click();
await expect(inspect).toHaveAttribute("aria-pressed", "false");
await expect(page.getByRole("button", { name: "Add to Agent Draft" })).toHaveCount(0);
await inspect.click();
await page.evaluate(async () => {
const projectPath = "/src/platform/project.ts";
const { useProject } = await import(projectPath);
useProject.setState({ project: { ...useProject.getState().project, trusted: false } });
});
await expect(page.getByText("Element inspection requires a trusted local project.")).toBeVisible();
await expect(page.getByRole("button", { name: "Add to Agent Draft" })).toHaveCount(0);
expect(await ipcCalls(page, "cancel_request")).toHaveLength(1);
});
test("navigates the same session and keeps native history until Close", async ({ workbench: page }) => {
await stubDesktop(page);
await stubBrowser(page);
await openBrowser(page);
const panel = page.getByRole("region", { name: "Browser" });
const address = panel.getByLabel("Local page URL");
await visit(page, "http://localhost:3000/first");
await expect(panel.getByRole("button", { name: "Back", exact: true })).toBeDisabled();
await visit(page, "http://localhost:3000/next");
await page.evaluate(async () => {
const path = "/src/workbench/contributions.ts";
(await import(path)).toolWindowService().hide("browser");
});
await expect(panel).toBeHidden();
await openBrowser(page);
await panel.getByRole("button", { name: "Back", exact: true }).click();
await expect(address).toHaveValue("http://localhost:3000/first");
await panel.getByRole("button", { name: "Forward", exact: true }).click();
await expect(address).toHaveValue("http://localhost:3000/next");
await panel.getByRole("button", { name: "Reload", exact: true }).click();
expect(await ipcCalls(page, "web_browser_open")).toHaveLength(1);
await panel.getByRole("button", { name: "Close", exact: true }).click();
await expect(panel.getByRole("button", { name: "Reload", exact: true })).toHaveCount(0);
expect(await ipcCalls(page, "cancel_request")).toHaveLength(1);
});
test("localhost console links offer the Browser in their context menu; a plain click stays external", async ({
workbench: page,
}) => {
await stubDesktop(page);
await stubBrowser(page);
const routed = await page.evaluate(async () => {
const path = "/src/features/run/navigate.ts";
const { consoleLinkMenu, debugConsoleUrl } = await import(path);
const click = { metaKey: false, ctrlKey: false, shiftKey: false };
const urls = ["https://localhost.example.org/", "http://guest@localhost:3000/", "http://127.0.0.1:3000/app"];
const menus = urls.map((url) => {
const link = document.createElement("a");
link.setAttribute("href", url);
link.textContent = url;
return consoleLinkMenu(link);
});
menus[2][0].run();
return { plain: urls.map((url) => debugConsoleUrl(click, url)), offered: menus.map((m) => m.length > 0) };
});
expect(routed).toEqual({ plain: [false, false, false], offered: [false, false, true] });
await expect(page.getByLabel("Local page URL")).toHaveValue("http://127.0.0.1:3000/app");
expect(await ipcCalls(page, "web_browser_open")).toHaveLength(1);
});
+43
Переглянути файл
@@ -967,6 +967,49 @@ test("visible Markdown reflows during a tool window drag and distant blocks catc
await expect.poll(() => width(far)).toBe(await width(near));
});
test("visible Markdown reflows during a drag even when the viewport observer has not marked it", async ({
workbench: page,
}) => {
const editor = await openFromTree(page, "README.md");
const content = editor.locator(".cm-content");
await content.click();
await page.keyboard.press("Meta+a");
await page.keyboard.insertText(
Array.from({ length: 180 }, (_, i) => `Paragraph ${i} with enough text to wrap across the pane.`).join("\n\n"),
);
const preview = page.getByRole("document", { name: "Markdown preview" });
await expect(preview).toContainText("Paragraph 179");
// Widths of a block in view and of the block farthest from it.
const widths = () =>
preview.evaluate((el) => {
const box = el.getBoundingClientRect();
const blocks = [...el.querySelectorAll(":scope > [data-preview-blocks] > [data-line]")];
const shown = blocks.find((n) => n.getBoundingClientRect().top >= box.top)!;
const far = el.scrollTop > el.scrollHeight / 2 ? blocks[0]! : blocks.at(-1)!;
return { near: shown.getBoundingClientRect().width, far: far.getBoundingClientRect().width };
});
await expect.poll(async () => ((w) => w.near === w.far)(await widths())).toBe(true);
const before = (await widths()).far;
// Content swapped in without a new render (e.g. a restored preview) carries no marks yet.
await preview.evaluate((el) =>
el.querySelectorAll("[data-in-viewport]").forEach((n) => n.removeAttribute("data-in-viewport")),
);
const handle = page.getByRole("separator", { name: "Resize left tool window", exact: true });
const box = (await handle.boundingBox())!;
const x = box.x + box.width / 2,
y = box.y + box.height / 2;
await page.mouse.move(x, y);
await page.mouse.down();
try {
await page.mouse.move(x + 160, y, { steps: 4 });
await expect.poll(async () => (await widths()).near).toBeLessThan(before - 30);
expect((await widths()).far).toBe(before);
} finally {
await page.mouse.up();
}
await expect.poll(async () => ((w) => w.near === w.far)(await widths())).toBe(true);
});
test("dragging the Markdown split divider resizes and reflows editor and preview content, keeps the ratio, and resets on double-click", async ({
workbench: page,
}) => {
+9 -3
Переглянути файл
@@ -17,7 +17,7 @@ commands.lspSemanticTokens = async () => ({
data: {
tokenTypes: ["operator", "parameter"],
tokenModifiers: ["declaration", "modification"],
data: [0, 4, 5, 0, 1, 0, 10, 6, 1, 2],
data: [1, 4, 5, 0, 1, 1, 10, 6, 1, 2],
},
});
@@ -35,7 +35,7 @@ document.body.append(host);
const support = await loadSupport(findLanguageDescription("Kotlin", "Demo.kt")!);
const view = new EditorView({
parent: host,
doc: "fun greet(prefix: String) {}",
doc: "// before\nfun greet(prefix: String) {}\n// after",
extensions: [
support!,
syntaxHighlightField,
@@ -49,4 +49,10 @@ const view = new EditorView({
: []),
],
});
view.dispatch({ effects: setSyntaxHighlights.of({ kinds: ["function", "parameter"], data: [4, 9, 0, 10, 16, 1] }) });
const start = view.state.doc.line(2).from;
view.dispatch({
effects: setSyntaxHighlights.of({
kinds: ["function", "parameter"],
data: [start + 4, start + 9, 0, start + 10, start + 16, 1],
}),
});
+26 -2
Переглянути файл
@@ -1,5 +1,29 @@
import { expect, test } from "@playwright/test";
for (const semantic of [false, true]) {
test(`${semantic ? "semantic" : "syntax"} token backgrounds paint only their own row`, async ({ page }) => {
await page.goto(`/e2e/kotlinHighlight.html${semantic ? "?semantic" : ""}`);
await page.addStyleTag({ content: ".cm-editor .cm-scroller { font: 18px/18px monospace; }" });
const editor = page.locator(".cm-editor");
const row = editor.locator(".cm-line", { hasText: "fun greet" });
const token = semantic
? row.locator(".cm-sem-function")
: row
.locator("span")
.filter({ hasText: /^greet$/ })
.last();
await expect(token).toHaveCSS("color", "rgb(85, 119, 153)");
expect((await token.boundingBox())!.height).toBeGreaterThan((await row.boundingBox())!.height);
const neighbors = () => editor.screenshot({ mask: [row] });
const before = await neighbors();
const highlighted = await row.screenshot();
await page.addStyleTag({ content: ".cm-editor .cm-line span { --syn-function-bg: transparent !important; }" });
expect((await row.screenshot()).equals(highlighted), "the token fill should be visible").toBe(false);
expect((await neighbors()).equals(before), "changing the fill must not repaint adjacent rows").toBe(true);
});
}
test("Kotlin backend roles override lexer styles", async ({ page }) => {
await page.goto("/e2e/kotlinHighlight.html");
const greet = page
@@ -7,7 +31,7 @@ test("Kotlin backend roles override lexer styles", async ({ page }) => {
.filter({ hasText: /^greet$/ })
.last();
await expect(greet).toHaveCSS("color", "rgb(85, 119, 153)");
await expect(greet).toHaveCSS("background-color", "rgb(221, 238, 255)");
await expect(greet).toHaveCSS("background-image", /rgb\(221, 238, 255\)/);
await expect(greet).toHaveCSS("font-weight", "700");
await expect(
page
@@ -22,7 +46,7 @@ test("Kotlin semantic roles stay inside backend and lexer marks", async ({ page
const declaration = page.locator(".cm-sem-function.cm-sem-declaration");
await expect(declaration).toHaveText("greet");
await expect(declaration).toHaveCSS("color", "rgb(85, 119, 153)");
await expect(declaration).toHaveCSS("background-color", "rgb(221, 238, 255)");
await expect(declaration).toHaveCSS("background-image", /rgb\(221, 238, 255\)/);
await expect(declaration).toHaveCSS("font-weight", "700");
await expect(declaration.locator("span")).toHaveCount(0);
const parameter = page.locator(".cm-sem-parameter.cm-sem-mutable");
+3
Переглянути файл
@@ -44,6 +44,9 @@ async function requestClose(
idlePolicy: { overrideSeconds },
});
window.__ipc.handlers.window_close_context = () => ({ windows, quitting });
window.__ipc.handlers.window_begin_prompt = () => true;
window.__ipc.handlers.window_end_prompt = () => null;
window.__ipc.handlers.window_ready_to_close = () => true;
window.__ipc.handlers.close_project = () => null;
window.__ipc.handlers.remote_invoke = ({ cmd }) => {
if (cmd === "remote_idle_timeout_minutes") {
+1 -1
Переглянути файл
@@ -12,7 +12,7 @@ test("semantic roles honor all Color Scheme attributes and keep modifier styles"
] as const) {
const role = page.locator(selector);
await expect(role).toHaveCSS("color", color);
await expect(role).toHaveCSS("background-color", "rgb(221, 238, 255)");
await expect(role).toHaveCSS("background-image", /rgb\(221, 238, 255\)/);
}
await expect(page.locator(".cm-sem-namespace")).toHaveCSS("font-style", "italic");
for (const selector of [".cm-sem-type", ".cm-sem-function", ".cm-sem-parameter", ".cm-sem-constant"]) {
+40
Переглянути файл
@@ -0,0 +1,40 @@
# Java build
The IDE's own build of Maven and Gradle modules (`ide_build::jbuild`). The jar holds two parts:
- `ai.openidea.javac.Server` (`src/`): a resident javac. OpenIDEA starts one per JDK (and
`.mvn/jvm.config`) as `java -cp openidea-java-build.jar ai.openidea.javac.Server` and keeps it
running between builds. It reads one JSON request per line on stdin and answers on stdout:
| Request | Meaning |
| ------------------------------------------------------------------------ | ----------------------------------------------- |
| `{"id":1,"op":"compile","options":[…],"sources":[…],"encoding":"UTF-8"}` | Compile with javac (`ToolProvider`), in process |
| `{"op":"cancel","id":1}` | Stop that compilation at javac's next phase |
| `{"op":"exit"}` | Finish the queued requests, then exit |
Replies carry the request's `id`: `diagnostic` (1-based line, 0-based UTF-16 column),
`output` (a class file and the source it came from), `generated` (a source an annotation
processor wrote), `output-text`, then `done`. `ready` and `fatal` concern the server.
- `ai.openidea.javac.maven.BuildModel` (`maven/`): a Maven core extension, loaded with
`-Dmaven.ext.class.path`. With `-Dopenidea.build.output=<dir>` it redirects every project's
output to `<dir>/<groupId>.<artifactId>/classes|test-classes`, and resolves reactor
projects to those folders. With `-Dopenidea.build.model=<file>` it writes, after the build,
each project's source roots, classpaths, resources and the configuration maven-compiler-plugin's
mojos get (including the resolved `annotationProcessorPaths`), as JSON.
OpenIDEA runs `mvn process-resources resources:testResources` with the extension when the POMs,
settings or generator inputs change, then compiles the launch's modules with the server.
Gradle builds get the same model from an init script instead
(`crates/ide-build/src/jbuild/gradle-build.init.gradle`, task `openideaBuildModel`, with
`-Popenidea.build.output` and `-Popenidea.build.model`), when Settings › Gradle › Build and run
using is set to the IDE.
The jar is committed and embedded by `ide-sdk` (`java_build_jar`). It is built with `--release 8`
against Maven 3.9.11, whose files `build-dependencies.sha256` pins. Rebuild it after changing
the source:
```sh
JAVA_HOME=<JDK 11+> python3 build.py <apache-maven-3.9.11 folder>
```
+52
Переглянути файл
@@ -0,0 +1,52 @@
0addec670fedcd3f113c5c8091d783280d23f75e3acb841b61a9cdb079376a08 maven/aopalliance-1.0.jar
876eab6a83daecad5ca67eb9fcabb063c97b5aeb8cf1fca7a989ecde17522051 maven/asm-9.8.jar
d3d530d0f28fd0fbbffe2b0b338f70e8cb96f1605579e2e3abd4db29cac24e69 maven/commons-cli-1.9.0.jar
ba005f304cef92a3dede24a38ad5ac9b8afccf0d8f75839d6c1338634cf7f6e4 maven/commons-codec-1.18.0.jar
6661d5335090a5fc61dd869d2095bc6c1e2156e3aa47a6e4ababdf64c99a7889 maven/error_prone_annotations-2.38.0.jar
cbfc3906b19b8f55dd7cfd6dfe0aa4532e834250d7f080bd8d211a3e246b59cb maven/failureaccess-1.0.3.jar
94855942d4992f112946d3de1c334e709237b8126d8130bf07807c018a4a2120 maven/gson-2.13.1.jar
f3d7f57f67fd622f4d468dfdd692b3a5e3909246c28017ac3263405f0fe617ed maven/guava-33.4.8-jre.jar
142ad4475e19524d2fe3ac995b3f7cbc962fc726f2edb9dbdccc61feab9b2bf9 maven/guice-5.1.0-classes.jar
c8bc7e1c51a6d4ce72f40d2ebbabf1c4b68bfe76e732104b04381b493478e9d6 maven/httpclient-4.5.14.jar
6c9b3dd142a09dc468e23ad39aad6f75a0f2b85125104469f026e52a474e464f maven/httpcore-4.4.16.jar
0b7b8b003a90ea491579b62f5118828e45112914c65589b00faa49d6ec785839 maven/jansi-2.4.2.jar
e04ba5195bcd555dc95650f7cc614d151e4bcd52d29a10b8aa2197f3ab89ab9b maven/javax.annotation-api-1.3.2.jar
91c77044a50c481636c32d916fd89c9118a72195390452c81065080f957de7ff maven/javax.inject-1.jar
ab57ca8fd223772c17365d121f59e94ecbf0ae59d08c03a3cb5b81071c019195 maven/jcl-over-slf4j-1.7.36.jar
1fad6e6be7557781e4d33729d49ae1cdc8fdda6fe477bb0cc68ce351eafdfbab maven/jspecify-1.0.0.jar
0bfd1c121f907642344311d81e4dfd93eba6c24dc712cc0aeae273eb22833022 maven/maven-artifact-3.9.11.jar
5b1de1560ec19c4c69a655f986455888f3a0bcc3c160cac1f1edb87de3825f77 maven/maven-builder-support-3.9.11.jar
b0e2865fc808fd9fb3bee95bf37c0609eeb20c59bf1e6b958b37b365ee11f52e maven/maven-compat-3.9.11.jar
93d3c0523dda6c86c6620d9e692e7df39d0e2e4e4cd860061a8c0d274c2ad185 maven/maven-core-3.9.11.jar
7e15e05035331d0a7e0fe56d7354b2b30e15c0a8c60863cbf28df25190e197db maven/maven-embedder-3.9.11.jar
163aa596f976264384efeb50b4cb8a806086fd64a9b755ad1f69195fed3998ad maven/maven-model-3.9.11.jar
c4c72accdcd848332c1a37995610a6a369d49fdaabc43e85f0022a5b77de3ba7 maven/maven-model-builder-3.9.11.jar
8e985a56412564cf687040efed8bcd3a63eac2202a824bb01e1d5ece2b87458f maven/maven-plugin-api-3.9.11.jar
f8655f5f0060e0032944f2a23688d186e140d2184749bcfa1927f83cd6a8b1a2 maven/maven-repository-metadata-3.9.11.jar
c0ce14849298720dcf3b09fe9e263b3c576d2d6cd43c61f8aa9d6117e04e5e47 maven/maven-resolver-api-1.9.24.jar
18b7d557c41379db8b157ba95263c676f52c293f5416b67bd1db083e99b30383 maven/maven-resolver-connector-basic-1.9.24.jar
3cd88edda00c46242cdbe57aefb47703519d176d9e8a500333de15faf41b0e1d maven/maven-resolver-impl-1.9.24.jar
a222b0a5ca4c145e8e0f45207a23bcce18bdbe1f1c980e4e9fb332591ee8c91a maven/maven-resolver-named-locks-1.9.24.jar
b5d6e52ae1ecf1cb62ede2234234ba3093149524066488e84415187ce478c582 maven/maven-resolver-provider-3.9.11.jar
e3153906e93333c106ee18babb72ba7984ccb15e9116ea08f88c71b8d9387e01 maven/maven-resolver-spi-1.9.24.jar
b09268d41e1dfcae15a829d45a512ca29d62b727421d3bd6383ac6252e5e960f maven/maven-resolver-transport-file-1.9.24.jar
a0de339a8dd3473d9abaa1cf974507f38783e26af31d36a90c1e59cc8714ded0 maven/maven-resolver-transport-http-1.9.24.jar
78ed57fa2123a2d84fad7a0b15ca73b89df47c10294d02d6f8121c4d0e5050cb maven/maven-resolver-transport-wagon-1.9.24.jar
aeb7e776a8c47b1c317a2581f299e2525b044cb8abde31164e970bbbefab12b1 maven/maven-resolver-util-1.9.24.jar
026718d47d19e360d978857bc63d3dc065884fc2c801563d8a2a77b5ab74ccf8 maven/maven-settings-3.9.11.jar
33c96e4ca5a15b7c93180f6b2f8deb15f511dfc15dda0d2b671c968b22108972 maven/maven-settings-builder-3.9.11.jar
b613357e1bad4dfc1dead801691c9460f9585fe7c6b466bc25186212d7d18487 maven/maven-shared-utils-3.4.2.jar
76d9fa894fa61d1492877ca599cb5ab28ca4573d5f389d6c12a8233b995335f9 maven/maven-slf4j-provider-3.9.11.jar
1cbd7a965a5e2a9ea823bab311962a4e5aa5c240705bdbad5a52b40ffdfa1004 maven/org.eclipse.sisu.inject-0.9.0.M4.jar
b90579bc652eac7331436e0a25533fce14130b9c6e015f2dd3a3d4bb07e942b7 maven/org.eclipse.sisu.plexus-0.9.0.M4.jar
9a7f1b5c5a9effd61eadfd8731452a2f76a8e79111fac391ef75ea801bea203a maven/plexus-cipher-2.0.jar
50edb93c73786e62822b4fe1336e22880fdf147191373cf5c911370e16748fcf maven/plexus-component-annotations-2.2.0.jar
ab2a8715570438a2e4164d85ad3e8d489eabc38ea5093c2eb8ab7f58403535b5 maven/plexus-interpolation-1.28.jar
873139960c4c780176dda580b003a2c4bf82188bdce5bb99234e224ef7acfceb maven/plexus-sec-dispatcher-2.0.jar
27ef130e32c236090e408fb5498d94cb9ea26d14070fb1c8985d607b62d098d1 maven/plexus-utils-3.6.0.jar
d3ef575e3e4979678dc01bf1dcce51021493b4d11fb7f1be8ad982877c16a1c0 maven/slf4j-api-1.7.36.jar
afc9216fa97b78dad227b4a8d4d67b9897bf113a57f80598d62993841113e103 maven/wagon-file-3.5.3.jar
d2b6e48c9fcbe579e1858c622d14464011ff265fa6e28e794004a6882154a509 maven/wagon-http-3.5.3.jar
8e7da766f55164fde8779aaaa125832506c2848cab4876b5305138873e28037f maven/wagon-http-shared-3.5.3.jar
5e72000338945ed3e96f8e4f578d1d0672e1af7e19c0e9014197ae5b31af3ef4 maven/wagon-provider-api-3.5.3.jar
1ad3292cd563381e3fd632f3fded1988f9e9b2be7a9f3db63ff4c4cedba13fa5 maven/plexus-classworlds-2.9.0.jar
+38
Переглянути файл
@@ -0,0 +1,38 @@
"""Build the committed jar: python3 build.py /path/to/apache-maven-3.9.11 [--record-dependencies].
One jar, two parts, Java 8 bytecode:
- `src`: the resident javac server (`ai.openidea.javac.Server`), JDK classes only.
- `maven`: the prepare run's Maven extension (`ai.openidea.javac.maven.BuildModel`), compiled
against Maven 3.9.11's API jars, pinned by build-dependencies.sha256.
Archive order and timestamps are deterministic. Use a JDK that still compiles `--release 8`."""
import hashlib
import os
import pathlib
import subprocess
import sys
import tempfile
import zipfile
root = pathlib.Path(__file__).resolve().parent
maven = pathlib.Path(sys.argv[1]).resolve()
jars = sorted((maven / 'lib').glob('*.jar')) + sorted((maven / 'boot').glob('*.jar'))
actual = ''.join(f'{hashlib.sha256(p.read_bytes()).hexdigest()} maven/{p.name}\n' for p in jars)
if '--record-dependencies' in sys.argv:
(root / 'build-dependencies.sha256').write_text(actual)
if (root / 'build-dependencies.sha256').read_text() != actual:
sys.exit('Build dependencies differ from build-dependencies.sha256')
java_home = os.environ.get('JAVA_HOME')
javac = str(pathlib.Path(java_home) / 'bin' / 'javac') if java_home else 'javac'
with tempfile.TemporaryDirectory() as output:
for source, classpath in [('src', []), ('maven', jars)]:
subprocess.run([javac, '--release', '8', '-Xlint:-options', '-proc:none', '-encoding', 'UTF-8', '-g',
'-classpath', os.pathsep.join(map(str, classpath)), '-d', output,
*map(str, sorted((root / source).rglob('*.java')))], check=True)
files = {p.relative_to(output).as_posix(): p.read_bytes() for p in pathlib.Path(output).rglob('*.class')}
files['META-INF/sisu/javax.inject.Named'] = b'ai.openidea.javac.maven.BuildModel\n'
files['META-INF/MANIFEST.MF'] = b'Manifest-Version: 1.0\nMain-Class: ai.openidea.javac.Server\n\n'
staged = root / 'openidea-java-build.jar.pending'
with zipfile.ZipFile(staged, 'w', zipfile.ZIP_DEFLATED) as jar:
for name, data in sorted(files.items()):
jar.writestr(zipfile.ZipInfo(name, (2026, 1, 1, 0, 0, 0)), data)
staged.replace(root / 'openidea-java-build.jar')
+501
Переглянути файл
@@ -0,0 +1,501 @@
package ai.openidea.javac.maven;
import java.io.File;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.lang.reflect.Field;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.maven.AbstractMavenLifecycleParticipant;
import org.apache.maven.MavenExecutionException;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.lifecycle.LifecycleExecutor;
import org.apache.maven.lifecycle.MavenExecutionPlan;
import org.apache.maven.model.Dependency;
import org.apache.maven.model.Resource;
import org.apache.maven.plugin.BuildPluginManager;
import org.apache.maven.plugin.MavenPluginManager;
import org.apache.maven.plugin.Mojo;
import org.apache.maven.plugin.MojoExecution;
import org.apache.maven.project.DefaultDependencyResolutionRequest;
import org.apache.maven.project.DependencyResolutionResult;
import org.apache.maven.project.MavenProject;
import org.apache.maven.project.ProjectDependenciesResolver;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import org.eclipse.aether.DefaultRepositorySystemSession;
import org.eclipse.aether.RepositorySystem;
import org.eclipse.aether.RepositorySystemSession;
import org.eclipse.aether.artifact.Artifact;
import org.eclipse.aether.artifact.DefaultArtifact;
import org.eclipse.aether.collection.CollectRequest;
import org.eclipse.aether.graph.DependencyNode;
import org.eclipse.aether.graph.Exclusion;
import org.eclipse.aether.repository.WorkspaceReader;
import org.eclipse.aether.repository.WorkspaceRepository;
import org.eclipse.aether.resolution.ArtifactResult;
import org.eclipse.aether.resolution.DependencyRequest;
import org.eclipse.aether.resolution.DependencyResult;
/**
* Records how each project of the session compiles, for the IDE's own Java build. Loaded only
* by the IDE's prepare run ({@code -Dmaven.ext.class.path=<jar> -Dopenidea.build.model=<file>
* process-resources resources:testResources}): generated sources exist and resources are
* processed, and nothing is compiled. Test source generators run after {@code compile} in
* Maven's lifecycle, so they don't run; the source roots build-helper adds are read from its
* configuration, and any other generator is listed so the IDE leaves those tests to Maven.
*
* <p>Per project and source set (main, test): the source roots (including the ones generated
* sources added), the output directory, the compile classpath with reactor projects as their
* output directories (never their jars), the runtime classpath, the compiler plugin's resolved
* configuration (release, encoding, arguments, annotation processor path) and the resources.
* Executions bound to the compile phases that are not javac (Kotlin, AspectJ, bytecode
* enhancers) are listed, so the IDE leaves such projects to Maven.
*/
@Named("openidea-build-model")
@Singleton
public final class BuildModel extends AbstractMavenLifecycleParticipant {
private static final String COMPILER = "org.apache.maven.plugins:maven-compiler-plugin";
/** Test phases before test-compile, which the prepare run doesn't reach. */
private static final Set<String> TEST_GENERATE_PHASES = new HashSet<>(Arrays.asList(
"generate-test-sources", "process-test-sources", "generate-test-resources", "process-test-resources"));
/** Phases whose executions change what the compile phases produce. */
private static final Set<String> COMPILE_PHASES =
new HashSet<>(Arrays.asList("compile", "process-classes", "test-compile", "process-test-classes"));
/** Executions in those phases that don't change the classes the IDE compiles. */
private static final Set<String> HARMLESS = new HashSet<>(Arrays.asList(
"org.jacoco:jacoco-maven-plugin", "org.apache.maven.plugins:maven-enforcer-plugin",
"org.codehaus.mojo:animal-sniffer-maven-plugin", "org.apache.maven.plugins:maven-checkstyle-plugin",
"com.github.spotbugs:spotbugs-maven-plugin", "org.apache.maven.plugins:maven-pmd-plugin",
"com.diffplug.spotless:spotless-maven-plugin", "org.apache.maven.plugins:maven-dependency-plugin",
"org.apache.maven.plugins:maven-resources-plugin", "org.codehaus.mojo:build-helper-maven-plugin",
"pl.project13.maven:git-commit-id-plugin", "io.github.git-commit-id:git-commit-id-maven-plugin"));
private final LifecycleExecutor lifecycle;
private final MavenPluginManager plugins;
private final BuildPluginManager buildPlugins;
private final ProjectDependenciesResolver dependencies;
private final RepositorySystem repositories;
@Inject
public BuildModel(LifecycleExecutor lifecycle, MavenPluginManager plugins, BuildPluginManager buildPlugins,
ProjectDependenciesResolver dependencies, RepositorySystem repositories) {
this.lifecycle = lifecycle;
this.plugins = plugins;
this.buildPlugins = buildPlugins;
this.dependencies = dependencies;
this.repositories = repositories;
}
/**
* With {@code -Dopenidea.build.output=<dir>}, every project's classes and resources go to
* {@code <dir>/<groupId>.<artifactId>/classes} (and {@code test-classes}): the IDE's outputs,
* apart from what a terminal build or the language server writes to {@code target}.
*/
@Override public void afterProjectsRead(MavenSession session) {
String output = session.getUserProperties().getProperty("openidea.build.output");
if (output == null) return;
for (MavenProject project : session.getProjects()) {
File dir = new File(output, project.getGroupId() + "." + project.getArtifactId());
project.getBuild().setOutputDirectory(new File(dir, "classes").getAbsolutePath());
project.getBuild().setTestOutputDirectory(new File(dir, "test-classes").getAbsolutePath());
}
}
@Override public void afterSessionEnd(MavenSession session) throws MavenExecutionException {
String destination = session.getUserProperties().getProperty("openidea.build.model");
if (destination == null) return;
StringBuilder json = new StringBuilder("{\"version\":1,\"projects\":[");
boolean first = true;
MavenProject current = session.getCurrentProject();
try {
for (MavenProject project : session.getProjects()) {
if (!first) json.append(',');
first = false;
project(json, session, project);
}
} finally {
session.setCurrentProject(current);
}
json.append("]}");
File target = new File(destination);
try {
File parent = target.getAbsoluteFile().getParentFile();
parent.mkdirs();
File temp = File.createTempFile("build-model", ".json", parent);
try (Writer out = new OutputStreamWriter(Files.newOutputStream(temp.toPath()), StandardCharsets.UTF_8)) {
out.write(json.toString());
}
Files.move(temp.toPath(), target.toPath(), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE);
} catch (IOException e) {
throw new MavenExecutionException("Cannot write the IDE build model: " + e.getMessage(), e);
}
}
private void project(StringBuilder json, MavenSession session, MavenProject project) {
session.setCurrentProject(project);
json.append("{\"dir\":").append(q(project.getBasedir().getAbsolutePath()))
.append(",\"groupId\":").append(q(project.getGroupId()))
.append(",\"artifactId\":").append(q(project.getArtifactId()))
.append(",\"version\":").append(q(project.getVersion()))
.append(",\"packaging\":").append(q(project.getPackaging()));
List<String> problems = new ArrayList<>();
Map<String, Mojo> compilers = new HashMap<>();
List<MojoExecution> configured = new ArrayList<>();
List<String> others = new ArrayList<>();
List<String> testGenerators = new ArrayList<>();
List<String> testRoots = new ArrayList<>(project.getTestCompileSourceRoots());
try {
MavenExecutionPlan plan = lifecycle.calculateExecutionPlan(session, true, "test-compile");
for (MojoExecution execution : plan.getMojoExecutions()) {
String plugin = execution.getGroupId() + ":" + execution.getArtifactId();
String phase = execution.getLifecyclePhase();
if (COMPILER.equals(plugin) && ("compile".equals(execution.getGoal()) || "testCompile".equals(execution.getGoal()))) {
if (compilers.containsKey(execution.getGoal())) {
others.add(plugin + ":" + execution.getGoal() + "@" + execution.getExecutionId());
continue;
}
try {
buildPlugins.getPluginRealm(session, execution.getMojoDescriptor().getPluginDescriptor());
Mojo mojo = plugins.getConfiguredMojo(Mojo.class, session, execution);
compilers.put(execution.getGoal(), mojo);
configured.add(execution);
} catch (Exception e) {
problems.add("Cannot read the " + execution.getGoal() + " configuration: " + e);
}
} else if (phase != null && COMPILE_PHASES.contains(phase) && !HARMLESS.contains(plugin)) {
others.add(plugin + ":" + execution.getGoal() + "@" + execution.getExecutionId());
} else if (phase != null && TEST_GENERATE_PHASES.contains(phase)) {
String goal = plugin + ":" + execution.getGoal();
if (goal.equals("org.apache.maven.plugins:maven-resources-plugin:testResources")) continue;
if (goal.equals("org.codehaus.mojo:build-helper-maven-plugin:add-test-source")) {
try {
buildPlugins.getPluginRealm(session, execution.getMojoDescriptor().getPluginDescriptor());
Mojo mojo = plugins.getConfiguredMojo(Mojo.class, session, execution);
Object sources = get(mojo, "sources");
if (sources instanceof File[])
for (File f : (File[]) sources) testRoots.add(f.getAbsolutePath());
plugins.releaseMojo(mojo, execution);
continue;
} catch (Exception e) {
problems.add("Cannot read build-helper's test sources: " + e);
}
}
testGenerators.add(goal + "@" + execution.getExecutionId());
}
}
} catch (Exception e) {
problems.add("Cannot plan the build: " + e);
}
Set<String> reactor = new HashSet<>();
for (MavenProject p : session.getProjects()) reactor.add(p.getGroupId() + ":" + p.getArtifactId());
RepositorySystemSession repo = reactorSession(session);
List<String> compile = new ArrayList<>();
List<String> runtime = new ArrayList<>();
List<String> test = new ArrayList<>();
try {
DependencyResolutionResult result =
dependencies.resolve(new DefaultDependencyResolutionRequest(project, repo));
classpaths(result.getDependencyGraph(), compile, runtime, test);
for (Exception e : result.getCollectionErrors()) problems.add(e.getMessage());
} catch (Exception e) {
problems.add("Cannot resolve the dependencies: " + rootMessage(e));
org.apache.maven.project.DependencyResolutionException failure = cause(e);
if (failure != null && failure.getResult() != null && failure.getResult().getDependencyGraph() != null)
classpaths(failure.getResult().getDependencyGraph(), compile, runtime, test);
}
json.append(",\"main\":");
sourceSet(json, session, project, compilers.get("compile"), null, compile, runtime, problems);
json.append(",\"test\":");
List<String> testClasspath = new ArrayList<>();
testClasspath.add(project.getBuild().getOutputDirectory());
testClasspath.addAll(test);
sourceSet(json, session, project, compilers.get("testCompile"), testRoots, testClasspath, testClasspath, problems);
json.append(",\"otherCompilers\":").append(strings(others));
json.append(",\"testGenerators\":").append(strings(testGenerators));
json.append(",\"problems\":").append(strings(problems)).append('}');
for (int i = 0; i < configured.size(); i++) {
Mojo mojo = compilers.get(configured.get(i).getGoal());
if (mojo != null) plugins.releaseMojo(mojo, configured.get(i));
}
}
/** `testRoots`: the test source roots, `null` for the main source set. */
private void sourceSet(StringBuilder json, MavenSession session, MavenProject project, Mojo compiler,
List<String> testRoots, List<String> classpath, List<String> runtime, List<String> problems) {
boolean test = testRoots != null;
List<String> roots = test ? testRoots : project.getCompileSourceRoots();
String output = test ? project.getBuild().getTestOutputDirectory() : project.getBuild().getOutputDirectory();
json.append("{\"sourceRoots\":").append(strings(roots))
.append(",\"output\":").append(q(output))
.append(",\"classpath\":").append(strings(classpath))
.append(",\"runtimeClasspath\":").append(strings(runtime))
.append(",\"resources\":");
List<Resource> resources = test ? project.getTestResources() : project.getResources();
json.append('[');
for (int i = 0; i < resources.size(); i++) {
Resource r = resources.get(i);
if (i > 0) json.append(',');
json.append("{\"directory\":").append(q(new File(project.getBasedir(), r.getDirectory()).isAbsolute()
? r.getDirectory() : new File(project.getBasedir(), r.getDirectory()).getAbsolutePath()))
.append(",\"filtering\":").append(r.isFiltering())
.append(",\"targetPath\":").append(q(r.getTargetPath()))
.append(",\"includes\":").append(strings(r.getIncludes()))
.append(",\"excludes\":").append(strings(r.getExcludes())).append('}');
}
json.append(']');
json.append(",\"compiler\":");
if (compiler == null) {
json.append("null}");
return;
}
json.append('{');
String goal = test ? "testCompile" : "compile";
field(json, "compilerId", get(compiler, "compilerId"));
field(json, "source", get(compiler, test ? "testSource" : "source", "source"));
field(json, "target", get(compiler, test ? "testTarget" : "target", "target"));
field(json, "release", get(compiler, test ? "testRelease" : "release", "release"));
field(json, "encoding", get(compiler, "encoding"));
field(json, "parameters", get(compiler, "parameters"));
field(json, "debug", get(compiler, "debug"));
field(json, "debuglevel", get(compiler, "debuglevel"));
field(json, "proc", get(compiler, "proc"));
field(json, "enablePreview", get(compiler, "enablePreview"));
field(json, "fork", get(compiler, "fork"));
field(json, "executable", get(compiler, "executable"));
field(json, "skip", get(compiler, test ? "skip" : "skipMain"));
field(json, "showWarnings", get(compiler, "showWarnings"));
field(json, "showDeprecation", get(compiler, "showDeprecation"));
field(json, "generatedSourcesDirectory",
get(compiler, test ? "generatedTestSourcesDirectory" : "generatedSourcesDirectory"));
field(json, "includes", get(compiler, test ? "testIncludes" : "includes"));
field(json, "excludes", get(compiler, test ? "testExcludes" : "excludes"));
field(json, "annotationProcessors", get(compiler, "annotationProcessors"));
field(json, "compilerArgs", get(compiler, "compilerArgs"));
field(json, "compilerArgument", get(compiler, "compilerArgument"));
field(json, "compilerArguments", get(compiler, "compilerArguments"));
field(json, "multiReleaseOutput", get(compiler, "multiReleaseOutput"));
Object paths = get(compiler, "annotationProcessorPaths");
if (paths instanceof Collection && !((Collection<?>) paths).isEmpty()) {
try {
Object useDepMgmt = get(compiler, "annotationProcessorPathsUseDepMgmt");
field(json, "processorPath", processorPath(session, project, (Collection<?>) paths,
Boolean.TRUE.equals(useDepMgmt)));
} catch (Exception e) {
problems.add("Cannot resolve the annotation processor path of " + goal + ": " + rootMessage(e));
field(json, "processorPathError", rootMessage(e));
}
}
if (json.charAt(json.length() - 1) == ',') json.setLength(json.length() - 1);
json.append("}}");
}
/** The classpaths of the resolved graph, in Maven's order: compile, runtime, test scopes. */
private static void classpaths(DependencyNode root, List<String> compile, List<String> runtime, List<String> test) {
List<DependencyNode> nodes = new ArrayList<>();
collect(root, nodes, new HashSet<>());
for (DependencyNode node : nodes) {
if (node.getDependency() == null || node.getArtifact() == null) continue;
File file = node.getArtifact().getFile();
if (file == null) continue;
String scope = node.getDependency().getScope();
String path = file.getAbsolutePath();
if (!"test".equals(scope) && !"runtime".equals(scope)) compile.add(path);
if (!"test".equals(scope) && !"provided".equals(scope) && !"system".equals(scope)) runtime.add(path);
test.add(path);
}
}
/** Pre-order, as Maven lists `project.getArtifacts()` for classpaths. */
private static void collect(DependencyNode node, List<DependencyNode> out, Set<String> seen) {
for (DependencyNode child : node.getChildren()) {
Artifact a = child.getArtifact();
String key = a == null ? String.valueOf(System.identityHashCode(child))
: a.getGroupId() + ":" + a.getArtifactId() + ":" + a.getExtension() + ":" + a.getClassifier();
if (seen.add(key)) out.add(child);
}
for (DependencyNode child : node.getChildren()) collect(child, out, seen);
}
/**
* A repository session that resolves reactor projects to their output directories, as the
* IDE compiles against them: before (and without) any packaging, and even before they exist.
*/
private static RepositorySystemSession reactorSession(MavenSession session) {
final Map<String, MavenProject> byKey = new HashMap<>();
for (MavenProject p : session.getProjects())
byKey.put(p.getGroupId() + ":" + p.getArtifactId() + ":" + p.getVersion(), p);
final WorkspaceReader fallback = session.getRepositorySession().getWorkspaceReader();
final WorkspaceRepository repository = new WorkspaceRepository("openidea-reactor");
WorkspaceReader reader = new WorkspaceReader() {
@Override public WorkspaceRepository getRepository() {
return repository;
}
@Override public File findArtifact(Artifact artifact) {
MavenProject p = byKey.get(artifact.getGroupId() + ":" + artifact.getArtifactId() + ":" + artifact.getBaseVersion());
if (p == null) return fallback == null ? null : fallback.findArtifact(artifact);
if ("pom".equals(artifact.getExtension())) return p.getFile();
boolean tests = "tests".equals(artifact.getClassifier()) || "test-jar".equals(artifact.getProperty("type", ""));
File dir = new File(tests ? p.getBuild().getTestOutputDirectory() : p.getBuild().getOutputDirectory());
dir.mkdirs();
return dir;
}
@Override public List<String> findVersions(Artifact artifact) {
MavenProject p = byKey.get(artifact.getGroupId() + ":" + artifact.getArtifactId() + ":" + artifact.getBaseVersion());
if (p != null) return java.util.Collections.singletonList(p.getVersion());
return fallback == null ? java.util.Collections.<String>emptyList() : fallback.findVersions(artifact);
}
};
DefaultRepositorySystemSession copy = new DefaultRepositorySystemSession(session.getRepositorySession());
copy.setWorkspaceReader(reader);
return copy;
}
/** maven-compiler-plugin's `annotationProcessorPaths`, resolved with their dependencies as the plugin does. */
private List<String> processorPath(MavenSession session, MavenProject project, Collection<?> coordinates,
boolean useDepMgmt) throws Exception {
Map<String, String> managed = new HashMap<>();
if (project.getDependencyManagement() != null)
for (Dependency d : project.getDependencyManagement().getDependencies())
managed.put(d.getGroupId() + ":" + d.getArtifactId(), d.getVersion());
CollectRequest request = new CollectRequest();
request.setRepositories(project.getRemoteProjectRepositories());
for (Object c : coordinates) {
String group = (String) get(c, "groupId");
String artifact = (String) get(c, "artifactId");
String version = (String) get(c, "version");
if (version == null) version = managed.get(group + ":" + artifact);
if (version == null) throw new IllegalStateException("No version for " + group + ":" + artifact);
String classifier = (String) get(c, "classifier");
String type = (String) get(c, "type");
List<Exclusion> exclusions = new ArrayList<>();
Object declared = get(c, "exclusions");
if (declared instanceof Collection)
for (Object e : (Collection<?>) declared)
exclusions.add(new Exclusion((String) get(e, "groupId"), (String) get(e, "artifactId"), "*", "*"));
DefaultArtifact a = new DefaultArtifact(group, artifact, classifier == null ? "" : classifier,
type == null || "jar".equals(type) ? "jar" : type, version);
request.addDependency(new org.eclipse.aether.graph.Dependency(a, "runtime", false, exclusions));
}
if (useDepMgmt && project.getDependencyManagement() != null) {
for (Dependency d : project.getDependencyManagement().getDependencies()) {
request.addManagedDependency(new org.eclipse.aether.graph.Dependency(new DefaultArtifact(d.getGroupId(),
d.getArtifactId(), d.getClassifier() == null ? "" : d.getClassifier(),
d.getType() == null ? "jar" : d.getType(), d.getVersion()), d.getScope()));
}
}
DependencyResult result =
repositories.resolveDependencies(reactorSession(session), new DependencyRequest(request, null));
Set<String> out = new LinkedHashSet<>();
for (ArtifactResult r : result.getArtifactResults())
if (r.getArtifact() != null && r.getArtifact().getFile() != null) out.add(r.getArtifact().getFile().getAbsolutePath());
return new ArrayList<>(out);
}
private static org.apache.maven.project.DependencyResolutionException cause(Throwable e) {
for (Throwable t = e; t != null; t = t.getCause())
if (t instanceof org.apache.maven.project.DependencyResolutionException)
return (org.apache.maven.project.DependencyResolutionException) t;
return null;
}
private static String rootMessage(Throwable e) {
Throwable t = e;
while (t.getCause() != null && t.getCause() != t) t = t.getCause();
return t.getMessage() == null ? t.toString() : t.getMessage();
}
/** The first of `names` that a field of the mojo (or its superclasses) has, read reflectively. */
private static Object get(Object target, String... names) {
for (String name : names) {
for (Class<?> c = target.getClass(); c != null && c != Object.class; c = c.getSuperclass()) {
try {
Field f = c.getDeclaredField(name);
f.setAccessible(true);
Object value = f.get(target);
if (value != null || names.length == 1) return value;
break;
} catch (NoSuchFieldException e) {
// Try the superclass.
} catch (IllegalAccessException | RuntimeException e) {
return null;
}
}
}
return null;
}
private static void field(StringBuilder json, String name, Object value) {
if (value == null) return;
json.append(q(name)).append(':').append(value(value)).append(',');
}
private static String value(Object value) {
if (value == null) return "null";
if (value instanceof Boolean || value instanceof Number) return value.toString();
if (value instanceof File) return q(((File) value).getAbsolutePath());
if (value instanceof Collection) {
StringBuilder b = new StringBuilder("[");
for (Object o : (Collection<?>) value) {
if (b.length() > 1) b.append(',');
b.append(value(o));
}
return b.append(']').toString();
}
if (value instanceof Object[]) return value(Arrays.asList((Object[]) value));
if (value instanceof Map) {
StringBuilder b = new StringBuilder("{");
for (Map.Entry<?, ?> e : new LinkedHashMap<>((Map<?, ?>) value).entrySet()) {
if (b.length() > 1) b.append(',');
b.append(q(String.valueOf(e.getKey()))).append(':').append(q(e.getValue() == null ? null : String.valueOf(e.getValue())));
}
return b.append('}').toString();
}
return q(value.toString());
}
private static String strings(Collection<String> values) {
StringBuilder b = new StringBuilder("[");
if (values != null) {
for (String s : values) {
if (b.length() > 1) b.append(',');
b.append(q(s));
}
}
return b.append(']').toString();
}
static String q(String s) {
if (s == null) return "null";
StringBuilder b = new StringBuilder(s.length() + 2).append('"');
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
switch (c) {
case '"': b.append("\\\""); break;
case '\\': b.append("\\\\"); break;
case '\n': b.append("\\n"); break;
case '\r': b.append("\\r"); break;
case '\t': b.append("\\t"); break;
default:
if (c < 0x20) b.append(String.format("\\u%04x", (int) c));
else b.append(c);
}
}
return b.append('"').toString();
}
}
Бінарний файл не відображається.
+459
Переглянути файл
@@ -0,0 +1,459 @@
package ai.openidea.javac;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.URI;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import javax.tools.Diagnostic;
import javax.tools.DiagnosticListener;
import javax.tools.FileObject;
import javax.tools.ForwardingJavaFileManager;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileManager;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.StandardLocation;
import javax.tools.ToolProvider;
/**
* A resident javac for the IDE's Java build: one JVM per JDK, compiling requests one at a
* time with the JDK's own compiler, in process, annotation processors included.
*
* <p>Protocol: one JSON object per line. Requests on stdin:
* {@code {"id":1,"op":"compile","options":[...],"sources":[...],"encoding":"UTF-8"}},
* {@code {"op":"cancel","id":1}}, {@code {"op":"exit"}}. Replies on stdout, all carrying the
* request {@code id}: {@code diagnostic} (severity, path, 1-based line, UTF-16 column and end,
* code, message), {@code output} (a class or resource file written, with the source it came
* from), {@code generated} (a source an annotation processor wrote), {@code output-text}
* (javac's own printed text), then one {@code done} (success, cancelled).
*/
public final class Server {
private static final Object OUT_LOCK = new Object();
private static PrintWriter out;
public static void main(String[] args) throws IOException {
out = new PrintWriter(new OutputStreamWriter(System.out, StandardCharsets.UTF_8), false);
// Anything else printing to stdout would break the protocol.
System.setOut(System.err);
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
if (compiler == null) {
send("{\"kind\":\"fatal\",\"message\":" + Json.quote("This Java runtime has no compiler (a JRE, not a JDK)") + "}");
System.exit(2);
}
send("{\"kind\":\"ready\",\"version\":" + Json.quote(System.getProperty("java.version")) + "}");
BufferedReader in = new BufferedReader(new InputStreamReader(System.in, StandardCharsets.UTF_8));
final AtomicReference<Request> running = new AtomicReference<>();
final java.util.concurrent.BlockingQueue<Request> queue = new java.util.concurrent.LinkedBlockingQueue<>();
Thread worker = new Thread(() -> {
while (true) {
Request request;
try {
request = queue.take();
} catch (InterruptedException e) {
return;
}
if (request.exit) return;
running.set(request);
try {
compile(compiler, request);
} catch (Throwable t) {
StringWriter trace = new StringWriter();
t.printStackTrace(new PrintWriter(trace));
send("{\"id\":" + request.id + ",\"kind\":\"diagnostic\",\"severity\":\"error\",\"message\":"
+ Json.quote("javac crashed: " + trace) + "}");
send("{\"id\":" + request.id + ",\"kind\":\"done\",\"success\":false,\"cancelled\":false}");
} finally {
running.set(null);
}
}
}, "javac");
worker.start();
String line;
while ((line = in.readLine()) != null) {
if (line.trim().isEmpty()) continue;
Map<String, Object> message;
try {
message = Json.parseObject(line);
} catch (RuntimeException e) {
send("{\"kind\":\"fatal\",\"message\":" + Json.quote("Bad request: " + e.getMessage()) + "}");
continue;
}
String op = (String) message.get("op");
if ("cancel".equals(op)) {
Request current = running.get();
long id = ((Number) message.get("id")).longValue();
if (current != null && current.id == id) current.cancelled = true;
for (Request queued : queue) if (queued.id == id) queued.cancelled = true;
} else if ("exit".equals(op)) {
break;
} else if ("compile".equals(op)) {
queue.add(Request.of(message));
}
}
Request exit = new Request();
exit.exit = true;
// Requests already sent finish first; the host cancels the ones it no longer wants.
queue.add(exit);
try {
worker.join();
} catch (InterruptedException ignored) {
}
System.exit(0);
}
static void send(String json) {
synchronized (OUT_LOCK) {
out.print(json);
out.print('\n');
out.flush();
}
}
static final class Request {
long id;
List<String> options = new ArrayList<>();
List<String> sources = new ArrayList<>();
String encoding;
volatile boolean cancelled;
boolean exit;
@SuppressWarnings("unchecked")
static Request of(Map<String, Object> message) {
Request r = new Request();
r.id = ((Number) message.get("id")).longValue();
Object options = message.get("options");
if (options != null) for (Object o : (List<Object>) options) r.options.add((String) o);
Object sources = message.get("sources");
if (sources != null) for (Object o : (List<Object>) sources) r.sources.add((String) o);
r.encoding = (String) message.get("encoding");
return r;
}
}
/** Thrown from the task listener to stop a cancelled compilation. */
static final class Cancelled extends RuntimeException {
private static final long serialVersionUID = 1L;
Cancelled() {
super("cancelled", null, false, false);
}
}
private static void compile(JavaCompiler compiler, final Request request) throws IOException {
final long id = request.id;
if (request.cancelled) {
send("{\"id\":" + id + ",\"kind\":\"done\",\"success\":false,\"cancelled\":true}");
return;
}
Charset charset = request.encoding == null ? StandardCharsets.UTF_8 : Charset.forName(request.encoding);
final int[] errors = {0};
DiagnosticListener<JavaFileObject> diagnostics = d -> {
if (d.getKind() == Diagnostic.Kind.ERROR) errors[0]++;
send(diagnostic(id, d));
};
StandardJavaFileManager standard = compiler.getStandardFileManager(diagnostics, Locale.ROOT, charset);
JavaFileManager manager = new Recording(standard, id);
List<File> files = new ArrayList<>();
for (String source : request.sources) files.add(new File(source));
Iterable<? extends JavaFileObject> units = standard.getJavaFileObjectsFromFiles(files);
StringWriter printed = new StringWriter();
boolean success = false;
boolean cancelled = false;
try {
JavaCompiler.CompilationTask task =
compiler.getTask(printed, manager, diagnostics, request.options, null, units);
stopWhenCancelled(task, request);
success = Boolean.TRUE.equals(task.call()) && errors[0] == 0;
} catch (RuntimeException e) {
if (isCancelled(e)) {
cancelled = true;
} else if (e instanceof IllegalArgumentException) {
// An option javac doesn't know (a newer --release than this JDK has).
send("{\"id\":" + id + ",\"kind\":\"diagnostic\",\"severity\":\"error\",\"message\":"
+ Json.quote(e.getMessage()) + "}");
} else {
throw e;
}
} finally {
try {
manager.close();
} catch (IOException ignored) {
}
}
String text = printed.toString();
if (!text.isEmpty()) send("{\"id\":" + id + ",\"kind\":\"output-text\",\"text\":" + Json.quote(text) + "}");
send("{\"id\":" + id + ",\"kind\":\"done\",\"success\":" + success + ",\"cancelled\":" + cancelled + "}");
}
/**
* Stops the compilation at its next phase once {@code request} is cancelled, through
* {@code com.sun.source.util.TaskListener} (reflectively: Java 8's {@code --release} API has no
* {@code jdk.compiler}).
*/
private static void stopWhenCancelled(JavaCompiler.CompilationTask task, final Request request) {
try {
Class<?> listener = Class.forName("com.sun.source.util.TaskListener", false, task.getClass().getClassLoader());
Object proxy = java.lang.reflect.Proxy.newProxyInstance(listener.getClassLoader(), new Class<?>[] {listener},
(self, method, args) -> {
if (method.getDeclaringClass() == Object.class) {
switch (method.getName()) {
case "hashCode": return System.identityHashCode(self);
case "equals": return self == args[0];
default: return "cancellation listener";
}
}
if (request.cancelled) throw new Cancelled();
return null;
});
task.getClass().getMethod("addTaskListener", listener).invoke(task, proxy);
} catch (ReflectiveOperationException | RuntimeException e) {
// Not javac's task: cancellation then waits for the compilation to end.
}
}
private static boolean isCancelled(Throwable e) {
for (Throwable t = e; t != null; t = t.getCause()) if (t instanceof Cancelled) return true;
return false;
}
private static String diagnostic(long id, Diagnostic<? extends JavaFileObject> d) {
StringBuilder json = new StringBuilder("{\"id\":").append(id).append(",\"kind\":\"diagnostic\",\"severity\":");
String severity;
switch (d.getKind()) {
case ERROR: severity = "error"; break;
case WARNING:
case MANDATORY_WARNING: severity = "warning"; break;
default: severity = "info";
}
json.append(Json.quote(severity));
JavaFileObject source = d.getSource();
if (source != null) {
json.append(",\"path\":").append(Json.quote(path(source.toUri())));
long start = d.getStartPosition();
long end = d.getEndPosition();
int[] startCol = start >= 0 ? lineColumn(source, start) : null;
int[] endCol = end >= 0 ? lineColumn(source, end) : null;
if (startCol != null) json.append(",\"line\":").append(startCol[0]).append(",\"column\":").append(startCol[1]);
else if (d.getLineNumber() > 0) json.append(",\"line\":").append(d.getLineNumber());
if (endCol != null) json.append(",\"endLine\":").append(endCol[0]).append(",\"endColumn\":").append(endCol[1]);
}
if (d.getCode() != null) json.append(",\"code\":").append(Json.quote(d.getCode()));
json.append(",\"message\":").append(Json.quote(d.getMessage(Locale.ROOT)));
return json.append('}').toString();
}
/** 1-based line and 0-based UTF-16 column of a char offset (Java chars are UTF-16 units). */
private static int[] lineColumn(JavaFileObject source, long offset) {
CharSequence text;
try {
text = source.getCharContent(true);
} catch (IOException | RuntimeException e) {
return null;
}
if (offset > text.length()) return null;
int line = 1;
int lineStart = 0;
for (int i = 0; i < offset; i++) {
char c = text.charAt(i);
if (c == '\n' || (c == '\r' && (i + 1 >= text.length() || text.charAt(i + 1) != '\n'))) {
line++;
lineStart = i + 1;
}
}
return new int[] {line, (int) offset - lineStart};
}
static String path(URI uri) {
if ("file".equals(uri.getScheme())) return new File(uri).getPath();
return uri.toString();
}
/** Reports every file the compiler writes and the source it came from. */
static final class Recording extends ForwardingJavaFileManager<JavaFileManager> {
private final long id;
Recording(JavaFileManager manager, long id) {
super(manager);
this.id = id;
}
@Override
public JavaFileObject getJavaFileForOutput(Location location, String className, JavaFileObject.Kind kind,
FileObject sibling) throws IOException {
JavaFileObject file = super.getJavaFileForOutput(location, className, kind, sibling);
report(location, file, sibling, kind == JavaFileObject.Kind.SOURCE);
return file;
}
@Override
public FileObject getFileForOutput(Location location, String packageName, String relativeName,
FileObject sibling) throws IOException {
FileObject file = super.getFileForOutput(location, packageName, relativeName, sibling);
report(location, file, sibling, location == StandardLocation.SOURCE_OUTPUT);
return file;
}
private void report(Location location, FileObject file, FileObject sibling, boolean generatedSource) {
StringBuilder json = new StringBuilder("{\"id\":").append(id).append(",\"kind\":")
.append(Json.quote(generatedSource ? "generated" : "output"))
.append(",\"path\":").append(Json.quote(path(file.toUri())));
if (sibling != null && sibling.toUri().getScheme() != null)
json.append(",\"source\":").append(Json.quote(path(sibling.toUri())));
json.append(",\"location\":").append(Json.quote(location.getName()));
send(json.append('}').toString());
}
}
/** Just enough JSON for the protocol: objects, arrays, strings, numbers, booleans, null. */
static final class Json {
private final String text;
private int at;
private Json(String text) {
this.text = text;
}
@SuppressWarnings("unchecked")
static Map<String, Object> parseObject(String text) {
Json json = new Json(text);
Object value = json.value();
json.space();
if (!(value instanceof Map) || json.at != text.length()) throw new IllegalArgumentException("not one JSON object");
return (Map<String, Object>) value;
}
static String quote(String s) {
if (s == null) return "null";
StringBuilder b = new StringBuilder(s.length() + 2).append('"');
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
switch (c) {
case '"': b.append("\\\""); break;
case '\\': b.append("\\\\"); break;
case '\n': b.append("\\n"); break;
case '\r': b.append("\\r"); break;
case '\t': b.append("\\t"); break;
default:
if (c < 0x20) b.append(String.format("\\u%04x", (int) c));
else b.append(c);
}
}
return b.append('"').toString();
}
private void space() {
while (at < text.length() && Character.isWhitespace(text.charAt(at))) at++;
}
private char peek() {
space();
if (at >= text.length()) throw new IllegalArgumentException("unexpected end");
return text.charAt(at);
}
private void expect(char c) {
if (peek() != c) throw new IllegalArgumentException("expected '" + c + "' at " + at);
at++;
}
private Object value() {
char c = peek();
if (c == '{') {
at++;
Map<String, Object> map = new java.util.LinkedHashMap<>();
if (peek() == '}') {
at++;
return map;
}
while (true) {
String key = string();
expect(':');
map.put(key, value());
if (peek() == ',') {
at++;
continue;
}
expect('}');
return map;
}
}
if (c == '[') {
at++;
List<Object> list = new ArrayList<>();
if (peek() == ']') {
at++;
return list;
}
while (true) {
list.add(value());
if (peek() == ',') {
at++;
continue;
}
expect(']');
return list;
}
}
if (c == '"') return string();
if (text.startsWith("true", at)) {
at += 4;
return Boolean.TRUE;
}
if (text.startsWith("false", at)) {
at += 5;
return Boolean.FALSE;
}
if (text.startsWith("null", at)) {
at += 4;
return null;
}
int start = at;
while (at < text.length() && "+-0123456789.eE".indexOf(text.charAt(at)) >= 0) at++;
if (start == at) throw new IllegalArgumentException("unexpected '" + c + "' at " + at);
String number = text.substring(start, at);
return number.contains(".") || number.contains("e") || number.contains("E")
? (Object) Double.parseDouble(number) : (Object) Long.parseLong(number);
}
private String string() {
expect('"');
StringBuilder b = new StringBuilder();
while (true) {
if (at >= text.length()) throw new IllegalArgumentException("unterminated string");
char c = text.charAt(at++);
if (c == '"') return b.toString();
if (c != '\\') {
b.append(c);
continue;
}
char e = text.charAt(at++);
switch (e) {
case 'n': b.append('\n'); break;
case 'r': b.append('\r'); break;
case 't': b.append('\t'); break;
case 'b': b.append('\b'); break;
case 'f': b.append('\f'); break;
case 'u':
b.append((char) Integer.parseInt(text.substring(at, at + 4), 16));
at += 4;
break;
default: b.append(e);
}
}
}
}
private Server() {
}
}
+4 -3
Переглянути файл
@@ -14,7 +14,8 @@ tauri-build = { version = "2", features = [] }
dunce.workspace = true
[dependencies]
tauri = { version = "2", features = [] }
# Tauri 2 gates Window::add_child behind its multiwebview feature.
tauri = { version = "2", features = ["unstable"] }
tauri-plugin-opener = "2"
tauri-plugin-notification = "2.8.1"
tauri-plugin-dialog = { version = "2", default-features = false, features = ["xdg-portal"] }
@@ -79,8 +80,8 @@ security-framework = "3.7"
objc2 = "0.6"
objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "block2", "objc2-core-foundation", "NSApplication", "NSButton", "NSEvent", "NSGraphics", "NSResponder", "NSScreen", "NSTitlebarAccessoryViewController", "NSToolbar", "NSView", "NSViewController", "NSWindow", "NSWindowTabGroup", "NSWorkspace"] }
objc2-foundation = { version = "0.3", default-features = false, features = ["std", "block2", "NSArray", "NSLocale", "NSNotification", "NSOperation", "NSString"] }
# Used only by the debug font-restriction override; Cargo dependency cfg cannot test debug_assertions.
objc2-web-kit = { version = "0.3", default-features = false, features = ["std", "WKWebViewConfiguration", "WKPreferences"] }
# Browser history and the debug font-restriction override.
objc2-web-kit = { version = "0.3", default-features = false, features = ["std", "WKWebView", "WKWebViewConfiguration", "WKPreferences"] }
[target.'cfg(target_os = "linux")'.dependencies]
# Wayland detection and the client size without GTK's CSD shadow (linux_window_state.rs).
+7
Переглянути файл
@@ -0,0 +1,7 @@
{
"$schema": "../gen/schemas/desktop-schema.json",
"identifier": "browser",
"description": "Untrusted localhost Browser child. No core, plugin, or application commands.",
"webviews": ["browser-guest-*"],
"permissions": []
}
+2 -2
Переглянути файл
@@ -1,8 +1,8 @@
{
"$schema": "../gen/schemas/desktop-schema.json",
"identifier": "default",
"description": "Capability for the main window",
"windows": ["main", "project-*", "settings-*", "comparison-*", "diff-*", "editor-*", "deployment-*"],
"description": "Trusted workbench webviews only; child browser pages must not inherit their host window's permissions.",
"webviews": ["main", "project-*", "settings-*", "comparison-*", "diff-*", "editor-*", "deployment-*"],
"permissions": [
"core:default",
"core:window:allow-start-dragging",
+1 -1
Переглянути файл
@@ -2,6 +2,6 @@
"$schema": "../gen/schemas/desktop-schema.json",
"identifier": "e2e-bridge",
"description": "Debug-only automation bridge",
"windows": ["main", "project-*", "settings-*", "comparison-*", "diff-*", "editor-*", "deployment-*"],
"webviews": ["main", "project-*", "settings-*", "comparison-*", "diff-*", "editor-*", "deployment-*"],
"permissions": ["mcp-bridge:default"]
}
+4 -1
Переглянути файл
@@ -1,4 +1,7 @@
//! Debounced application activation, shared by every project window.
#[cfg(not(any(target_os = "macos", windows)))]
use crate::windows::WorkbenchWindows;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use tauri::{Emitter, Manager};
@@ -87,7 +90,7 @@ pub(crate) fn application_active(app: &tauri::AppHandle) -> bool {
process == std::process::id()
}
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
app.webview_windows().values().any(|w| w.is_focused().unwrap_or(true))
app.workbench_windows().values().any(|w| w.is_focused().unwrap_or(true))
}
#[cfg(test)]
+123
Переглянути файл
@@ -0,0 +1,123 @@
// Runs at document start in the unprivileged picker. Only a physical click can fill the slot.
// The workbench reads this view's main-frame slot only while armed. No page-to-IDE IPC.
(() => {
if (window !== window.top) return;
let picked = null;
let armed = false;
let suppressClick = false;
const styleOf = window.getComputedStyle.bind(window);
const encode = JSON.stringify;
const slice = Function.call.bind(String.prototype.slice);
Object.defineProperty(window, "__openideaPickedElement", {
get: () => (picked === null ? null : slice(picked, 0, 8193)),
});
let outline;
function stop() {
armed = false;
outline?.remove();
outline = undefined;
}
Object.defineProperty(window, "__openideaInspect", {
value: (enable) => {
stop();
picked = null;
suppressClick = false;
armed = enable === true;
},
});
window.addEventListener("pagehide", () => {
stop();
picked = null;
suppressClick = false;
});
window.addEventListener(
"pointermove",
(event) => {
if (!armed || !event.isTrusted || !(event.target instanceof Element) || !document.body) return;
if (!outline) {
outline = document.createElement("div");
outline.setAttribute("aria-hidden", "true");
outline.style.cssText =
"all:initial;position:fixed;pointer-events:none;z-index:2147483647;box-sizing:border-box;border:2px solid #4d90fe";
document.body.appendChild(outline);
}
const rect = event.target.getBoundingClientRect();
Object.assign(outline.style, {
left: rect.left + "px",
top: rect.top + "px",
width: rect.width + "px",
height: rect.height + "px",
});
},
true,
);
window.addEventListener(
"pointerdown",
(event) => {
// Some disabled controls never emit the click after pointerdown.
if (event.isTrusted) suppressClick = false;
if (
!armed ||
!event.isTrusted ||
!event.isPrimary ||
event.button !== 0 ||
!(event.target instanceof Element) ||
picked !== null
)
return;
event.preventDefault();
event.stopImmediatePropagation();
const element = event.target;
const path = [];
for (let node = element; node && path.length < 8; node = node.parentElement) {
const tag = node.localName;
let index = 1;
for (
let sibling = node.previousElementSibling;
sibling && index < 65536;
sibling = sibling.previousElementSibling
)
if (sibling.localName === tag) index++;
if (index > 65535) return;
path.unshift({ tag, index });
}
const css = styleOf(element);
picked = encode({
path,
disabled: element.hasAttribute("disabled"),
hidden: element.hasAttribute("hidden"),
ariaDisabled: element.getAttribute("aria-disabled") === "true",
display: css.display,
position: css.position,
visibility: css.visibility,
pointerEvents: css.pointerEvents,
});
stop();
suppressClick = true;
},
true,
);
// Suppress the click that follows the inspection gesture (links, form submits, app buttons).
window.addEventListener(
"click",
(event) => {
if (suppressClick) {
suppressClick = false;
event.preventDefault();
event.stopImmediatePropagation();
}
},
true,
);
window.addEventListener(
"keydown",
(event) => {
if (armed && event.isTrusted && event.key === "Escape") {
event.preventDefault();
stop();
picked = "cancel";
}
},
true,
);
})();
+155
Переглянути файл
@@ -0,0 +1,155 @@
//! Tauri owns both views. Only the workbench webview has the application's capability.
use super::{BrowserBounds, unavailable};
use ide_core::IdeResult;
use tauri::{PhysicalPosition, PhysicalSize, Webview, Window};
pub(super) struct Surface {
pub webview: Webview,
#[cfg(target_os = "linux")]
slot: gtk::Box,
}
impl Surface {
pub fn new(window: &Window, builder: tauri::webview::WebviewBuilder<tauri::Wry>) -> IdeResult<Self> {
let webview =
window.add_child(builder, PhysicalPosition::new(0, 0), PhysicalSize::new(1, 1)).map_err(unavailable)?;
let init = || -> IdeResult<Self> {
webview.hide().map_err(unavailable)?;
// On GTK add_child packs siblings in a vertical box: give the guest a positioned
// overlay instead, on Wayland as well as X11. Never replace the workbench widget.
#[cfg(target_os = "linux")]
let slot = {
use gtk::prelude::*;
let win = window.gtk_window().map_err(unavailable)?;
let root = win.child().ok_or_else(|| unavailable("missing workbench widget"))?;
let overlay = if let Some(existing) = root.downcast_ref::<gtk::Overlay>() {
existing.clone()
} else {
let overlay = gtk::Overlay::new();
win.remove(&root);
overlay.add(&root);
win.add(&overlay);
overlay.show();
overlay
};
let slot = gtk::Box::new(gtk::Orientation::Vertical, 0);
slot.set_halign(gtk::Align::Start);
slot.set_valign(gtk::Align::Start);
// with_webview runs immediately on the UI thread. Keep GTK objects there.
let (tx, rx) = std::sync::mpsc::sync_channel(1);
let weak: gtk::glib::SendWeakRef<gtk::Box> = slot.downgrade().into();
webview
.with_webview(move |native| {
let result = (|| -> IdeResult<()> {
let widget = native.inner();
let parent = widget
.parent()
.and_then(|p| p.downcast::<gtk::Container>().ok())
.ok_or_else(|| unavailable("missing guest container"))?;
let slot = weak.upgrade().ok_or_else(|| unavailable("missing guest slot"))?;
parent.remove(&widget);
slot.add(&widget);
Ok(())
})();
let _ = tx.send(result);
})
.map_err(unavailable)?;
rx.recv().map_err(unavailable)??;
overlay.add_overlay(&slot);
slot
};
Ok(Self {
webview: webview.clone(),
#[cfg(target_os = "linux")]
slot,
})
};
let result = init();
if result.is_err() {
webview.close().map_err(unavailable)?;
}
result
}
pub fn layout(&self, window: &Window, bounds: Option<BrowserBounds>) -> IdeResult<()> {
let size = window.inner_size().map_err(unavailable)?;
let Some(b) = bounds.filter(|b| {
b.x >= 0
&& b.y >= 0
&& b.width > 0
&& b.height > 0
&& (b.x as u32).saturating_add(b.width) <= size.width.saturating_add(1)
&& (b.y as u32).saturating_add(b.height) <= size.height.saturating_add(1)
}) else {
#[cfg(target_os = "linux")]
gtk::prelude::WidgetExt::hide(&self.slot);
return self.webview.hide().map_err(unavailable);
};
#[cfg(not(target_os = "linux"))]
self.webview
.set_bounds(tauri::Rect {
position: PhysicalPosition::new(b.x, b.y).into(),
size: PhysicalSize::new(b.width, b.height).into(),
})
.map_err(unavailable)?;
#[cfg(target_os = "linux")]
{
use gtk::prelude::*;
let scale = window.scale_factor().map_err(unavailable)?;
self.slot.set_margin_start((f64::from(b.x) / scale).round() as i32);
self.slot.set_margin_top((f64::from(b.y) / scale).round() as i32);
self.slot.set_size_request(
(f64::from(b.width) / scale).round() as i32,
(f64::from(b.height) / scale).round() as i32,
);
self.slot.show();
}
self.webview.show().map_err(unavailable)
}
pub fn history(&self) -> IdeResult<(bool, bool)> {
let (tx, rx) = std::sync::mpsc::sync_channel(1);
self.webview
.with_webview(move |native| {
#[cfg(target_os = "macos")]
// SAFETY: Tauri lends the WKWebView on its UI thread for this callback.
let result = unsafe {
let view = &*native.inner().cast::<objc2_web_kit::WKWebView>();
Ok((view.canGoBack(), view.canGoForward()))
};
#[cfg(windows)]
let result = (|| unsafe {
let view = native.controller().CoreWebView2()?;
let (mut back, mut forward) = (windows::core::BOOL::default(), windows::core::BOOL::default());
view.CanGoBack(&mut back)?;
view.CanGoForward(&mut forward)?;
windows::core::Result::Ok((back.as_bool(), forward.as_bool()))
})()
.map_err(unavailable);
#[cfg(target_os = "linux")]
let result = {
use webkit2gtk::WebViewExt;
let view = native.inner();
Ok((view.can_go_back(), view.can_go_forward()))
};
let _ = tx.send(result);
})
.map_err(unavailable)?;
rx.recv().map_err(unavailable)?
}
}
impl Drop for Surface {
fn drop(&mut self) {
if let Err(error) = self.webview.close() {
tracing::debug!(%error, "browser child already closed");
}
#[cfg(target_os = "linux")]
{
use gtk::prelude::*;
if let Some(parent) = self.slot.parent().and_then(|w| w.downcast::<gtk::Overlay>().ok()) {
parent.remove(&self.slot);
}
}
}
}
+342
Переглянути файл
@@ -0,0 +1,342 @@
//! An unprivileged Tauri child webview. The workbench, not the guest, owns its controls.
mod guest;
mod snapshot;
use crate::state::AppState;
use ide_core::{CancellationToken, IdeError, IdeResult, RequestId};
use serde::{Deserialize, Serialize};
pub use snapshot::InspectedElement;
use snapshot::Selection;
use specta::Type;
use std::{
cell::Cell,
cell::RefCell,
collections::HashMap,
sync::{
Arc,
atomic::{AtomicBool, AtomicU64, Ordering},
},
};
use tauri::{Manager, Url, Window};
use tokio::sync::oneshot;
#[derive(Deserialize, Type)]
#[serde(tag = "type", rename_all = "camelCase")]
pub enum BrowserAction {
Navigate { url: String },
Back,
Forward,
Reload,
Inspect,
Cancel,
Layout { bounds: Option<BrowserBounds> },
Status,
}
/// Physical pixels measured from the top left of the workbench webview.
#[derive(Clone, Copy, Deserialize, Type)]
pub struct BrowserBounds {
x: i32,
y: i32,
width: u32,
height: u32,
}
#[derive(Serialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct BrowserStatus {
url: String,
can_back: bool,
can_forward: bool,
inspecting: bool,
element: Option<InspectedElement>,
}
fn local_url(value: &str) -> IdeResult<Url> {
Url::parse(value)
.ok()
.filter(|u| {
value.len() <= 4096
&& matches!(u.scheme(), "http" | "https")
&& u.username().is_empty()
&& u.password().is_none()
&& ide_host::ops::web::is_loopback(u)
})
.ok_or_else(|| IdeError::invalid("Enter a loopback HTTP or HTTPS URL without credentials"))
}
fn same_origin(origin: &Url, value: &str) -> bool {
local_url(value).is_ok_and(|next| next.origin() == origin.origin())
}
const GUEST_PREFIX: &str = "browser-guest-";
pub(crate) fn is_guest(label: &str) -> bool {
label.starts_with(GUEST_PREFIX)
}
#[derive(Default)]
struct Document {
generation: AtomicU64,
loaded: AtomicBool,
armed: AtomicBool,
}
fn unavailable(e: impl std::fmt::Display) -> IdeError {
IdeError::unavailable(format!("Browser: {e}"))
}
struct Panel {
session: RequestId,
cancel: CancellationToken,
origin: Url,
project: Arc<ide_host::Project>,
view: guest::Surface,
document: Arc<Document>,
}
thread_local! {
// GTK, AppKit and WebView2 require these objects to be used and destroyed on the UI thread.
static PANELS: RefCell<HashMap<String, Panel>> = RefCell::new(HashMap::new());
}
async fn on_ui<T: Send + 'static>(
window: Window,
f: impl FnOnce(&Window) -> IdeResult<T> + Send + 'static,
) -> IdeResult<T> {
let (tx, rx) = oneshot::channel();
let owner = window.clone();
window
.run_on_main_thread(move || {
let _ = tx.send(f(&owner));
})
.map_err(unavailable)?;
rx.await.map_err(unavailable)?
}
fn local_project(window: &Window) -> IdeResult<Arc<ide_host::Project>> {
let state = window.state::<AppState>();
if state.remote_dev.get(AppState::owner_window(window.label())).is_some() {
return Err(IdeError::unavailable("The browser requires a trusted local project"));
}
let project = state.project(window.label())?;
project.require_trust()?;
Ok(project)
}
pub async fn open(window: Window, url: String, session: RequestId) -> IdeResult<()> {
let origin = local_url(&url)?;
let project = local_project(&window)?;
let state = window.state::<AppState>();
let cancel = state.begin_project_request(window.label(), session);
let token = cancel.clone();
let opened = on_ui(window.clone(), move |w| {
if token.is_cancelled() || !Arc::ptr_eq(&project, &local_project(w)?) {
return Err(IdeError::cancelled());
}
let document = Arc::new(Document::default());
let builder = tauri::webview::WebviewBuilder::new(
format!("{GUEST_PREFIX}{}-{}", w.label(), session.0),
tauri::WebviewUrl::External(origin.clone()),
)
.incognito(true)
.general_autofill_enabled(false)
.devtools(false)
.disable_drag_drop_handler()
.on_new_window(|_, _| tauri::webview::NewWindowResponse::Deny)
.on_download(|_, _| false)
.on_permission_request(|_, _| tauri::webview::PermissionResponse::Deny)
.initialization_script(include_str!("element.js"))
.on_navigation({
let origin = origin.clone();
let token = token.clone();
move |target| !token.is_cancelled() && same_origin(&origin, target.as_str())
})
.on_page_load({
let doc = document.clone();
let origin = origin.clone();
let token = token.clone();
move |_, payload| {
let url = payload.url().as_str();
if !same_origin(&origin, url) && !url.is_empty() && url != "about:blank" {
token.cancel();
return;
}
if matches!(payload.event(), tauri::webview::PageLoadEvent::Started) {
doc.generation.fetch_add(1, Ordering::SeqCst);
doc.armed.store(false, Ordering::SeqCst);
doc.loaded.store(false, Ordering::SeqCst);
} else if same_origin(&origin, url) {
doc.loaded.store(true, Ordering::SeqCst);
}
}
});
#[cfg(target_os = "macos")]
let builder = builder.allow_link_preview(false);
let view = guest::Surface::new(w, builder)?;
let panel = Panel { session, cancel: token, origin, project, view, document };
if let Some(old) = PANELS.with_borrow_mut(|panels| panels.insert(w.label().to_owned(), panel)) {
old.cancel.cancel();
}
Ok(())
})
.await;
if opened.is_err() {
state.end_request(session);
return opened;
}
let owner = window.clone();
tauri::async_runtime::spawn(async move {
cancel.cancelled().await;
let result = on_ui(owner.clone(), move |w| {
PANELS.with_borrow_mut(|p| {
if p.get(w.label()).is_some_and(|v| v.session == session) {
p.remove(w.label());
}
});
Ok(())
})
.await;
if let Err(error) = result {
tracing::debug!(?error, "browser owner closed");
}
owner.state::<AppState>().end_request(session);
});
Ok(())
}
pub fn forget(label: &str) {
if let Some(panel) = PANELS.with_borrow_mut(|panels| panels.remove(label)) {
panel.cancel.cancel();
}
}
pub async fn control(window: Window, session: RequestId, action: BrowserAction) -> IdeResult<BrowserStatus> {
let (mut status, selection, token, project, document, generation) = on_ui(window.clone(), move |w| {
PANELS.with_borrow(|p| {
let p = p
.get(w.label())
.filter(|p| p.session == session && !p.cancel.is_cancelled())
.ok_or_else(IdeError::cancelled)?;
if !Arc::ptr_eq(&p.project, &local_project(w)?) {
return Err(IdeError::cancelled());
}
let view = &p.view.webview;
let mut selection = None;
// WKWebView has no URL before its first commit; don't ask Wry to unwrap it.
let generation = p.document.generation.load(Ordering::SeqCst);
let url = if p.document.loaded.load(Ordering::SeqCst) {
view.url().map_err(unavailable)?.to_string()
} else {
String::new()
};
let local = same_origin(&p.origin, &url);
if !local && !url.is_empty() && url != "about:blank" {
p.cancel.cancel();
return Err(IdeError::unavailable("Browser left the allowed local origin"));
}
match action {
BrowserAction::Navigate { url } => {
if !same_origin(&p.origin, &url) {
return Err(IdeError::invalid("Close this page before opening another origin"));
}
view.navigate(local_url(&url)?).map_err(unavailable)?;
}
BrowserAction::Back => view.eval("history.back()").map_err(unavailable)?,
BrowserAction::Forward => view.eval("history.forward()").map_err(unavailable)?,
BrowserAction::Reload => view.reload().map_err(unavailable)?,
BrowserAction::Layout { bounds } => p.view.layout(w, bounds)?,
BrowserAction::Inspect | BrowserAction::Cancel => {
let arm = matches!(action, BrowserAction::Inspect);
if arm && !local {
return Err(IdeError::unavailable("The local page has not loaded"));
}
view.eval(if arm {
"window.__openideaInspect?.(true)"
} else {
"window.__openideaInspect?.(false)"
})
.map_err(unavailable)?;
p.document.armed.store(arm, Ordering::SeqCst);
}
BrowserAction::Status if local && p.document.armed.load(Ordering::SeqCst) => {
let (tx, rx) = oneshot::channel();
let reply = Cell::new(Some(tx));
// Read only the gesture-gated main-frame slot through this webview's callback.
// The page cannot invoke an IDE command or emit an IDE event.
view.eval_with_callback("window.__openideaPickedElement ?? null", move |value| {
if let Some(tx) = reply.take() {
let _ = tx.send(value);
}
})
.map_err(unavailable)?;
selection = Some(rx);
}
BrowserAction::Status => {}
}
let (can_back, can_forward) = p.view.history()?;
let status = BrowserStatus {
url: if local { url } else { p.origin.to_string() },
can_back,
can_forward,
inspecting: p.document.armed.load(Ordering::SeqCst),
element: None,
};
Ok((status, selection, p.cancel.clone(), p.project.clone(), p.document.clone(), generation))
})
})
.await?;
if let Some(rx) = selection {
let value = tokio::select! {
biased;
_ = token.cancelled() => return Err(IdeError::cancelled()),
value = tokio::time::timeout(std::time::Duration::from_secs(3), rx) => value.map_err(unavailable)?.map_err(unavailable)?,
};
if token.is_cancelled() || !Arc::ptr_eq(&project, &local_project(&window)?) {
return Err(IdeError::cancelled());
}
if document.generation.load(Ordering::SeqCst) != generation {
status.inspecting = false;
return Ok(status);
}
let json: Option<String> = serde_json::from_str(&value).map_err(unavailable)?;
if let Some(json) = json {
status.inspecting = false;
document.armed.store(false, Ordering::SeqCst);
if json == "cancel" {
return Ok(status);
}
if json.len() > 8192 {
return Err(IdeError::invalid("Element selection too large"));
}
status.element = Some(serde_json::from_str::<Selection>(&json).map_err(unavailable)?.preview()?);
}
}
Ok(status)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn pins_scheme_host_and_port_and_rejects_credentials() {
let origin = local_url("http://127.0.0.1:3000/a?key=private").unwrap();
assert!(same_origin(&origin, "http://127.0.0.1:3000/b#x"));
assert!(local_url("http://localhost/").is_ok());
assert!(local_url("https://[::1]/").is_ok());
for remote in [
"http://localhost.example.org",
"http://0.0.0.0",
"file:///tmp/test",
"tauri://localhost",
"http://user@localhost",
"https://example.org",
] {
assert!(local_url(remote).is_err(), "{remote}");
}
for target in
["http://127.0.0.1:3001", "http://localhost:3000", "https://127.0.0.1:3000", "http://u:[email protected]:3000"]
{
assert!(!same_origin(&origin, target), "{target}");
}
}
}
+149
Переглянути файл
@@ -0,0 +1,149 @@
use ide_core::{IdeError, IdeResult};
use serde::{Deserialize, Serialize};
use specta::Type;
/// Page text, URLs, classes, attribute values and form contents never enter the snapshot.
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub(super) struct Selection {
path: Vec<Step>,
disabled: bool,
hidden: bool,
aria_disabled: bool,
display: String,
position: String,
visibility: String,
pointer_events: String,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
struct Step {
tag: String,
index: u16,
}
#[derive(Debug, Serialize, Type)]
pub struct InspectedElement {
pub selector: String,
pub html: String,
pub styles: String,
}
impl Selection {
pub(super) fn preview(&self) -> IdeResult<InspectedElement> {
let invalid = || IdeError::invalid("The page returned an unsupported element selection");
if self.path.is_empty() || self.path.len() > 8 {
return Err(invalid());
}
let mut parts = Vec::with_capacity(self.path.len());
for step in &self.path {
if step.index == 0
|| step.tag.len() > 64
|| !step.tag.starts_with(|c: char| c.is_ascii_alphabetic())
|| !step.tag.bytes().all(|c| c.is_ascii_alphanumeric() || c == b'-')
{
return Err(invalid());
}
parts.push(format!("{}:nth-of-type({})", step.tag, step.index));
}
let tag = &self.path.last().ok_or_else(invalid)?.tag;
let mut html = format!("<{tag}");
if self.disabled {
html.push_str(" disabled");
}
if self.hidden {
html.push_str(" hidden");
}
if self.aria_disabled {
html.push_str(" aria-disabled=\"true\"");
}
html.push('>');
let mut styles = Vec::new();
for (name, value) in [
("display", &self.display),
("position", &self.position),
("visibility", &self.visibility),
("pointer-events", &self.pointer_events),
] {
if value.is_empty()
|| value.len() > 48
|| !value.bytes().all(|c| c.is_ascii_alphabetic() || matches!(c, b' ' | b'-'))
{
return Err(invalid());
}
// CSSOM keywords only. A page can replace its JS getters; arbitrary words must
// not become agent prompt text. Omit new engine-specific values until recognized.
let keywords = match name {
"display" => {
"none contents block inline run-in flow flow-root flex grid grid-lanes table list-item inline-block inline-flex inline-grid inline-table table-row-group table-header-group table-footer-group table-row table-cell table-column-group table-column table-caption ruby ruby-base ruby-text ruby-base-container ruby-text-container -webkit-box -webkit-inline-box"
}
"position" => "static relative absolute fixed sticky -webkit-sticky",
"visibility" => "visible hidden collapse",
_ => "auto none visiblePainted visibleFill visibleStroke visible painted fill stroke all bounding-box",
};
let known = |token: &str| keywords.split(' ').any(|word| word.eq_ignore_ascii_case(token));
let recognized = if name == "display" {
value.split(' ').take(4).count() <= 3 && value.split(' ').all(known)
} else {
known(value)
};
if recognized {
styles.push(format!("{name}: {value};"));
}
}
Ok(InspectedElement { selector: parts.join(" > "), html, styles: styles.join("\n") })
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::{Value, json};
fn selection() -> Value {
json!({"path": [{"tag":"main","index":1},{"tag":"button","index":2}], "disabled":true,
"hidden":false, "ariaDisabled":true, "display":"inline-flex", "position":"static",
"visibility":"visible", "pointerEvents":"none"})
}
#[test]
fn builds_the_preview_only_from_structured_fields() {
let capture: Selection = serde_json::from_value(selection()).unwrap();
let preview = capture.preview().unwrap();
assert_eq!(preview.selector, "main:nth-of-type(1) > button:nth-of-type(2)");
assert_eq!(preview.html, "<button disabled aria-disabled=\"true\">");
assert_eq!(
preview.styles,
"display: inline-flex;\nposition: static;\nvisibility: visible;\npointer-events: none;"
);
}
#[test]
fn omits_page_supplied_words_in_place_of_a_css_keyword() {
let mut value = selection();
value["display"] = json!("private content");
let preview = serde_json::from_value::<Selection>(value).unwrap().preview().unwrap();
assert!(!preview.styles.contains("private"));
assert!(preview.styles.contains("pointer-events: none;"));
}
#[test]
fn rejects_extra_content_invalid_paths_and_unbounded_styles() {
let mut value = selection();
value["outerHTML"] = json!("unreviewed text");
assert!(serde_json::from_value::<Selection>(value).is_err());
for (field, invalid) in [
("path", json!([])),
("path", json!(vec![json!({"tag":"div","index":1}); 9])),
("path", json!([{"tag":"button><a","index":1}])),
("path", json!([{"tag":"div","index":0}])),
("display", json!("url(local)")),
("position", json!("x".repeat(49))),
] {
let mut value = selection();
value[field] = invalid;
assert!(serde_json::from_value::<Selection>(value).unwrap().preview().is_err());
}
}
}
+3 -3
Переглянути файл
@@ -7,13 +7,13 @@ use ide_core::IdeResult;
#[cfg(not(any(target_os = "macos", target_os = "linux")))]
use ide_host::ops::blocking;
use std::path::{Path, PathBuf};
use tauri::{AppHandle, WebviewWindow};
use tauri::{AppHandle, Window};
/// Writes text locally, without WebView user-activation requirements.
#[desktop_command(trust = always)]
#[tauri::command]
#[specta::specta]
pub async fn clipboard_write_text(app: AppHandle, window: WebviewWindow, text: String) -> IdeResult<()> {
pub async fn clipboard_write_text(app: AppHandle, window: Window, text: String) -> IdeResult<()> {
#[cfg(windows)]
let owner = window.hwnd().map_err(|error| ide_core::IdeError::internal(error.to_string()))?.0 as usize;
#[cfg(not(windows))]
@@ -28,7 +28,7 @@ pub async fn clipboard_write_text(app: AppHandle, window: WebviewWindow, text: S
#[desktop_command(trust = always)]
#[tauri::command]
#[specta::specta]
pub async fn clipboard_write_image(app: AppHandle, window: WebviewWindow, png: String) -> IdeResult<()> {
pub async fn clipboard_write_image(app: AppHandle, window: Window, png: String) -> IdeResult<()> {
use base64::Engine;
if png.len() > 90 * 1024 * 1024 {
return Err(ide_core::IdeError::invalid("Clipboard image is too large"));
+4 -2
Переглянути файл
@@ -1,5 +1,8 @@
//! Diagnostics for the memory indicator / performance overlay.
#[cfg(target_os = "macos")]
use crate::windows::WorkbenchWindows;
use crate::state::AppState;
use ide_command::desktop_command;
use ide_core::IdeResult;
@@ -166,9 +169,8 @@ fn openidea_root(pid: u32, label: String, detail: Option<String>) -> MemoryRoot
async fn webview_processes(app: &AppHandle, state: &AppState) -> Vec<MemoryRoot> {
use std::collections::BTreeMap;
use std::time::Duration;
use tauri::Manager;
let mut pending = Vec::new();
for (label, w) in app.webview_windows() {
for (label, w) in app.workbench_windows() {
let (tx, rx) = tokio::sync::oneshot::channel();
let sent = w.with_webview(move |pv| {
// SAFETY: `with_webview` runs on the main thread with the live WKWebView.
+23 -2
Переглянути файл
@@ -1,9 +1,11 @@
//! Web browsers: the built-in server's URLs and launching browsers.
use crate::browser_picker::{self, BrowserAction, BrowserStatus};
use ide_command::desktop_command;
use ide_core::IdeResult;
use ide_core::{IdeResult, RequestId};
use ide_host::ops::blocking;
use ide_web::Browser;
use tauri::Window;
/// The browsers installed on this machine.
#[desktop_command(trust = always)]
@@ -29,4 +31,23 @@ pub async fn web_open(url: String, browser: Option<String>) -> IdeResult<()> {
blocking(move || ide_web::open(&url, browser.as_deref())).await
}
ide_command::desktop_domain!(web_browsers, web_open, web_serves_page);
/// Creates a private localhost browser session owned by this window and project.
#[desktop_command(trust = trusted)]
#[tauri::command]
#[specta::specta]
pub async fn web_browser_open(window: Window, url: String, session: RequestId) -> IdeResult<()> {
browser_picker::open(window, url, session).await
}
#[desktop_command(trust = trusted)]
#[tauri::command]
#[specta::specta]
pub async fn web_browser_control(
window: Window,
session: RequestId,
action: BrowserAction,
) -> IdeResult<BrowserStatus> {
browser_picker::control(window, session, action).await
}
ide_command::desktop_domain!(web_browser_control, web_browser_open, web_browsers, web_open, web_serves_page);
+65 -25
Переглянути файл
@@ -2,6 +2,7 @@
use crate::menu::{self, MenuConfig, MenuState};
use crate::state::AppState;
use crate::windows::WorkbenchWindow;
use crate::windows::{self, Launch, OpenOutcome, WindowsState};
use ide_command::desktop_command;
use ide_core::{IdeError, IdeResult, RequestId};
@@ -11,7 +12,7 @@ use std::collections::BTreeMap;
use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, Ordering};
use tauri::ipc::Channel;
use tauri::{AppHandle, State, WebviewWindow, Window};
use tauri::{AppHandle, State, Window};
/// Opens `path` in a new window (`new_window`) or tells the caller to open it
/// itself (`current`). A project already open in some window is focused instead.
@@ -37,7 +38,7 @@ pub async fn window_open_project(
#[specta::specta]
pub async fn window_open_files(
app: AppHandle,
window: WebviewWindow,
window: WorkbenchWindow,
files: Vec<PathBuf>,
) -> IdeResult<Vec<ide_core::IpcPath>> {
Ok(windows::open_files_window(&app, window.label(), files))
@@ -87,7 +88,7 @@ pub async fn window_new(app: AppHandle) -> IdeResult<String> {
#[specta::specta]
pub async fn window_open_settings(
app: AppHandle,
window: WebviewWindow,
window: WorkbenchWindow,
page: Option<String>,
new_projects: bool,
background: Option<String>,
@@ -102,7 +103,7 @@ pub async fn window_open_settings(
#[specta::specta]
pub async fn window_open_comparison(
app: AppHandle,
window: WebviewWindow,
window: WorkbenchWindow,
comparison: windows::ComparisonLaunch,
background: Option<String>,
) -> IdeResult<()> {
@@ -116,7 +117,7 @@ pub async fn window_open_comparison(
#[specta::specta]
pub async fn window_open_diff(
app: AppHandle,
window: WebviewWindow,
window: WorkbenchWindow,
diff: windows::DiffLaunch,
background: Option<String>,
) -> IdeResult<()> {
@@ -130,7 +131,7 @@ pub async fn window_open_diff(
#[specta::specta]
pub async fn window_open_editor(
app: AppHandle,
window: WebviewWindow,
window: WorkbenchWindow,
editor: windows::EditorLaunch,
background: Option<String>,
) -> IdeResult<()> {
@@ -144,7 +145,7 @@ pub async fn window_open_editor(
#[specta::specta]
pub async fn window_open_deployment(
app: AppHandle,
window: WebviewWindow,
window: WorkbenchWindow,
server: String,
paths: Vec<PathBuf>,
background: Option<String>,
@@ -156,14 +157,14 @@ pub async fn window_open_deployment(
#[desktop_command(trust = always)]
#[tauri::command]
#[specta::specta]
pub fn window_cycle(app: AppHandle, window: WebviewWindow, forward: bool) {
pub fn window_cycle(app: AppHandle, window: WorkbenchWindow, forward: bool) {
windows::cycle(&app, window.label(), forward);
}
#[desktop_command(trust = always)]
#[tauri::command]
#[specta::specta]
pub fn window_toggle_fullscreen(window: WebviewWindow) -> IdeResult<bool> {
pub fn window_toggle_fullscreen(window: WorkbenchWindow) -> IdeResult<bool> {
crate::window_groups::toggle_fullscreen(&window)
}
@@ -171,7 +172,7 @@ pub fn window_toggle_fullscreen(window: WebviewWindow) -> IdeResult<bool> {
#[desktop_command(trust = always)]
#[tauri::command]
#[specta::specta]
pub fn window_toggle_zoom(window: WebviewWindow) -> IdeResult<bool> {
pub fn window_toggle_zoom(window: WorkbenchWindow) -> IdeResult<bool> {
crate::window_zoom::toggle(&window)
}
@@ -182,7 +183,7 @@ pub fn window_toggle_zoom(window: WebviewWindow) -> IdeResult<bool> {
#[desktop_command(trust = always)]
#[tauri::command]
#[specta::specta]
pub fn window_flash_taskbar(window: WebviewWindow, flash: bool) -> IdeResult<()> {
pub fn window_flash_taskbar(window: WorkbenchWindow, flash: bool) -> IdeResult<()> {
if flash && window.is_focused().unwrap_or(false) {
return Ok(());
}
@@ -195,7 +196,7 @@ pub fn window_flash_taskbar(window: WebviewWindow, flash: bool) -> IdeResult<()>
#[desktop_command(trust = always)]
#[tauri::command]
#[specta::specta]
pub fn window_set_smooth_scrolling(window: WebviewWindow, enabled: bool) -> IdeResult<()> {
pub fn window_set_smooth_scrolling(window: WorkbenchWindow, enabled: bool) -> IdeResult<()> {
#[cfg(target_os = "linux")]
window
.with_webview(move |platform| crate::linux_webkit::set_smooth_scrolling(&platform, enabled))
@@ -209,7 +210,7 @@ pub fn window_set_smooth_scrolling(window: WebviewWindow, enabled: bool) -> IdeR
#[desktop_command(trust = always)]
#[tauri::command]
#[specta::specta]
pub fn window_set_titlebar_height(window: WebviewWindow, height: f64) -> IdeResult<()> {
pub fn window_set_titlebar_height(window: WorkbenchWindow, height: f64) -> IdeResult<()> {
if !height.is_finite() || !(1.0..=1000.0).contains(&height) {
return Err(IdeError::invalid("invalid title bar height"));
}
@@ -224,7 +225,7 @@ pub fn window_set_titlebar_height(window: WebviewWindow, height: f64) -> IdeResu
#[desktop_command(trust = always)]
#[tauri::command]
#[specta::specta]
pub fn window_take_launch(window: WebviewWindow, windows: State<'_, WindowsState>) -> Option<Launch> {
pub fn window_take_launch(window: WorkbenchWindow, windows: State<'_, WindowsState>) -> Option<Launch> {
windows.take_launch(window.label())
}
@@ -245,7 +246,7 @@ pub struct SettingsWindowInit {
#[specta::specta]
pub fn window_take_settings_init(
app: AppHandle,
window: WebviewWindow,
window: WorkbenchWindow,
windows: State<'_, WindowsState>,
state: State<'_, AppState>,
) -> SettingsWindowInit {
@@ -273,7 +274,7 @@ pub fn window_take_settings_init(
#[desktop_command(trust = always)]
#[tauri::command]
#[specta::specta]
pub fn window_complete_launch(window: WebviewWindow, windows: State<'_, WindowsState>) -> IdeResult<()> {
pub fn window_complete_launch(window: WorkbenchWindow, windows: State<'_, WindowsState>) -> IdeResult<()> {
windows.complete_launch(window.label());
Ok(())
}
@@ -295,7 +296,7 @@ pub struct OpenProject {
#[specta::specta]
pub fn window_open_projects(
app: AppHandle,
window: WebviewWindow,
window: WorkbenchWindow,
state: State<'_, AppState>,
) -> IdeResult<Vec<OpenProject>> {
Ok(windows::project_window_labels(&app)
@@ -323,7 +324,7 @@ pub fn window_open_projects(
#[desktop_command(trust = always)]
#[tauri::command]
#[specta::specta]
pub fn window_is_fullscreen(window: WebviewWindow) -> bool {
pub fn window_is_fullscreen(window: WorkbenchWindow) -> bool {
window.is_fullscreen().unwrap_or(false)
}
@@ -334,6 +335,10 @@ pub struct CloseContext {
pub quitting: bool,
/// Number of open project windows (settings windows excluded), including the caller.
pub windows: u32,
/// Whether this window currently has auxiliary document windows that must settle first.
pub has_document_windows: bool,
/// Whether this close runs alongside other windows or on a background tab (prompts serialize and raise).
pub batch: bool,
}
#[desktop_command(trust = always)]
@@ -350,10 +355,40 @@ pub fn window_close_context(app: AppHandle, window: Window, windows: State<'_, W
Some(keeper) if pending.len() > 1 && keeper == window.label() => all.len() - pending.len() + 1,
_ => all.len(),
};
CloseContext { quitting: windows.quitting(), windows: count as u32 }
let quitting = windows.quitting();
let has_document_windows = !windows::document_windows(&app, window.label()).is_empty();
let hidden_tab = windows.groups.lock().group(window.label()).is_some_and(|g| g.selected != window.label());
let batch = quitting || pending.len() > 1 || windows.in_tab_close_batch(window.label()) || hidden_tab;
CloseContext { quitting, windows: count as u32, has_document_windows, batch }
}
/// Quits: closes every window, each of which runs its own unsaved-changes check.
/// Acquires the interactive prompt turn for a batch close and brings this window forward.
/// Returns `false` if the batch was cancelled while waiting.
#[desktop_command(trust = always)]
#[tauri::command]
#[specta::specta]
pub async fn window_begin_prompt(app: AppHandle, window: WorkbenchWindow) -> bool {
crate::window_groups::begin_prompt(&app, &window).await
}
/// Releases the interactive prompt turn held by this window.
#[desktop_command(trust = always)]
#[tauri::command]
#[specta::specta]
pub fn window_end_prompt(app: AppHandle, window: Window) {
crate::window_groups::end_prompt(&app, window.label());
}
/// Signals that this window passed its close checks and waits for peers closing in the same
/// batch/tab group so they hide together in one frame. Returns `false` if the batch was cancelled.
#[desktop_command(trust = always)]
#[tauri::command]
#[specta::specta]
pub async fn window_ready_to_close(app: AppHandle, window: WorkbenchWindow) -> bool {
crate::window_groups::ready_to_close(&app, &window).await
}
/// Quits: closes every window in parallel, each of which runs its own unsaved-changes check.
#[desktop_command(trust = always)]
#[tauri::command]
#[specta::specta]
@@ -362,15 +397,17 @@ pub fn app_quit(app: AppHandle, windows: State<'_, WindowsState>) {
return;
}
windows.set_quitting(true);
windows::continue_quit(&app, None);
windows::start_quit(&app);
}
/// A window vetoed the quit (user cancelled its unsaved-changes prompt).
#[desktop_command(trust = always)]
#[tauri::command]
#[specta::specta]
pub fn app_cancel_quit(app: AppHandle, windows: State<'_, WindowsState>) {
pub fn app_cancel_quit(app: AppHandle, window: Window, windows: State<'_, WindowsState>) {
windows.set_quitting(false);
windows.abort_all_closing(Some(window.label()));
windows.close_settled(window.label());
tauri::async_runtime::spawn(async move {
let _ = crate::window_groups::persist(&app).await;
});
@@ -383,7 +420,7 @@ pub fn app_cancel_quit(app: AppHandle, windows: State<'_, WindowsState>) {
#[tauri::command]
#[specta::specta]
pub fn menu_configure(
window: WebviewWindow,
window: WorkbenchWindow,
app: AppHandle,
menu_state: State<'_, MenuState>,
state: State<'_, AppState>,
@@ -435,7 +472,7 @@ pub fn menu_model(app: AppHandle, state: State<'_, AppState>, menu_state: State<
#[desktop_command(trust = always)]
#[tauri::command]
#[specta::specta]
pub fn menu_set_disabled(window: WebviewWindow, app: AppHandle, menu_state: State<'_, MenuState>, ids: Vec<String>) {
pub fn menu_set_disabled(window: WorkbenchWindow, app: AppHandle, menu_state: State<'_, MenuState>, ids: Vec<String>) {
// The window whose menu runs: a project window also while its Settings window is focused.
if menu::native_menu_bar()
&& windows::target_window(&app).is_some_and(|target| !owns_menu_config(window.label(), target.label()))
@@ -623,7 +660,7 @@ pub(crate) async fn check_update(app: &AppHandle, source: UpdateSource) -> IdeRe
#[specta::specta]
pub fn app_update_window_ready(
app: AppHandle,
window: WebviewWindow,
window: WorkbenchWindow,
ready: bool,
system_locale: String,
) -> IdeResult<()> {
@@ -926,9 +963,11 @@ ide_command::desktop_domain!(
menu_model,
menu_refresh,
menu_set_disabled,
window_begin_prompt,
window_close_context,
window_complete_launch,
window_cycle,
window_end_prompt,
window_flash_taskbar,
window_is_fullscreen,
window_new,
@@ -942,6 +981,7 @@ ide_command::desktop_domain!(
window_open_projects,
window_open_remote,
window_open_settings,
window_ready_to_close,
window_set_smooth_scrolling,
window_set_titlebar_height,
window_take_launch,
+3 -3
Переглянути файл
@@ -3,7 +3,7 @@
use ide_command::desktop_command;
use ide_core::{IdeError, IdeResult};
use std::path::PathBuf;
use tauri::WebviewWindow;
use tauri::Window;
/// Starts dragging `window` while the primary mouse button is still down; returns whether a drag began.
///
@@ -12,7 +12,7 @@ use tauri::WebviewWindow;
#[desktop_command(trust = always)]
#[tauri::command]
#[specta::specta]
pub fn window_start_drag(window: WebviewWindow) -> IdeResult<bool> {
pub fn window_start_drag(window: Window) -> IdeResult<bool> {
#[cfg(target_os = "macos")]
if objc2_app_kit::NSEvent::pressedMouseButtons() & 1 == 0 {
return Ok(false);
@@ -27,7 +27,7 @@ pub fn window_start_drag(window: WebviewWindow) -> IdeResult<bool> {
#[desktop_command(trust = always)]
#[tauri::command]
#[specta::specta]
pub async fn window_drag_files(window: WebviewWindow, paths: Vec<PathBuf>) -> IdeResult<bool> {
pub async fn window_drag_files(window: Window, paths: Vec<PathBuf>) -> IdeResult<bool> {
let paths = ide_drag_out::local_paths(paths)?;
let (started_tx, started_rx) = tokio::sync::oneshot::channel();
let (done_tx, done_rx) = tokio::sync::oneshot::channel();
+14 -13
Переглянути файл
@@ -1,19 +1,21 @@
use crate::windows::WorkbenchWindows;
use crate::{window_groups as groups, windows::WindowsState};
use ide_command::desktop_command;
use ide_core::{IdeError, IdeResult};
use tauri::{Manager, WebviewWindow};
use tauri::{Manager, Window};
#[desktop_command(trust = always)]
#[tauri::command]
#[specta::specta]
pub fn window_group_current(window: WebviewWindow) -> IdeResult<Vec<groups::WindowTab>> {
pub fn window_group_current(window: Window) -> IdeResult<Vec<groups::WindowTab>> {
Ok(groups::current(window.app_handle(), window.label()))
}
#[desktop_command(trust = always)]
#[tauri::command]
#[specta::specta]
pub async fn window_group_merge(window: WebviewWindow) -> IdeResult<()> {
pub async fn window_group_merge(window: Window) -> IdeResult<()> {
groups::merge(window.app_handle(), window.label())?;
groups::persist(window.app_handle()).await
}
@@ -23,7 +25,7 @@ pub async fn window_group_merge(window: WebviewWindow) -> IdeResult<()> {
#[desktop_command(trust = always)]
#[tauri::command]
#[specta::specta]
pub async fn window_group_join(window: WebviewWindow, label: String) -> IdeResult<()> {
pub async fn window_group_join(window: Window, label: String) -> IdeResult<()> {
groups::join(window.app_handle(), window.label(), &label)?;
groups::persist(window.app_handle()).await
}
@@ -31,7 +33,7 @@ pub async fn window_group_join(window: WebviewWindow, label: String) -> IdeResul
#[desktop_command(trust = always)]
#[tauri::command]
#[specta::specta]
pub async fn window_group_select(window: WebviewWindow, label: String) -> IdeResult<()> {
pub async fn window_group_select(window: Window, label: String) -> IdeResult<()> {
groups::select(window.app_handle(), window.label(), &label)?;
groups::persist(window.app_handle()).await
}
@@ -39,7 +41,7 @@ pub async fn window_group_select(window: WebviewWindow, label: String) -> IdeRes
#[desktop_command(trust = always)]
#[tauri::command]
#[specta::specta]
pub async fn window_group_detach(window: WebviewWindow, label: String) -> IdeResult<()> {
pub async fn window_group_detach(window: Window, label: String) -> IdeResult<()> {
groups::select(window.app_handle(), window.label(), &label)?;
groups::detach(window.app_handle(), &label)?;
groups::persist(window.app_handle()).await
@@ -48,11 +50,10 @@ pub async fn window_group_detach(window: WebviewWindow, label: String) -> IdeRes
#[desktop_command(trust = always)]
#[tauri::command]
#[specta::specta]
pub fn window_group_close(window: WebviewWindow, label: String) -> IdeResult<()> {
groups::select(window.app_handle(), window.label(), &label)?;
pub fn window_group_close(window: Window, label: String) -> IdeResult<()> {
window
.app_handle()
.get_webview_window(&label)
.workbench_window(&label)
.ok_or_else(|| IdeError::not_found("Window closed"))?
.close()
.map_err(|e| IdeError::internal(e.to_string()))
@@ -62,7 +63,7 @@ pub fn window_group_close(window: WebviewWindow, label: String) -> IdeResult<()>
#[desktop_command(trust = always)]
#[tauri::command]
#[specta::specta]
pub fn window_group_close_tabs(window: WebviewWindow, keep: String, labels: Vec<String>) -> IdeResult<()> {
pub fn window_group_close_tabs(window: Window, keep: String, labels: Vec<String>) -> IdeResult<()> {
groups::close_tabs(window.app_handle(), window.label(), &keep, labels)
}
@@ -70,14 +71,14 @@ pub fn window_group_close_tabs(window: WebviewWindow, keep: String, labels: Vec<
#[desktop_command(trust = always)]
#[tauri::command]
#[specta::specta]
pub fn window_group_cancel_close(window: WebviewWindow) {
pub fn window_group_cancel_close(window: Window) {
groups::cancel_close(window.app_handle(), window.label());
}
#[desktop_command(trust = always)]
#[tauri::command]
#[specta::specta]
pub async fn window_group_reorder(window: WebviewWindow, labels: Vec<String>) -> IdeResult<()> {
pub async fn window_group_reorder(window: Window, labels: Vec<String>) -> IdeResult<()> {
window.state::<WindowsState>().groups.lock().reorder(window.label(), labels)?;
groups::select(window.app_handle(), window.label(), window.label())?;
groups::persist(window.app_handle()).await
@@ -86,7 +87,7 @@ pub async fn window_group_reorder(window: WebviewWindow, labels: Vec<String>) ->
#[desktop_command(trust = always)]
#[tauri::command]
#[specta::specta]
pub async fn window_group_restore(window: WebviewWindow) -> IdeResult<()> {
pub async fn window_group_restore(window: Window) -> IdeResult<()> {
groups::restore(window.app_handle(), window.label()).await
}
+3 -3
Переглянути файл
@@ -4,7 +4,7 @@ use ide_core::{IdeError, IdeResult, RequestId};
use ide_host::ops::project::ProjectInfo;
use ide_workspace::workspace::Workspace;
use std::path::PathBuf;
use tauri::{Manager, State, WebviewWindow};
use tauri::{Manager, State, Window};
#[desktop_command(trust = always)]
#[tauri::command]
@@ -38,7 +38,7 @@ pub async fn workspace_create(path: PathBuf, name: String, projects: Vec<PathBuf
#[desktop_command(trust = always)]
#[tauri::command]
#[specta::specta]
pub async fn workspace_update(window: WebviewWindow, name: String, projects: Vec<PathBuf>) -> IdeResult<ProjectInfo> {
pub async fn workspace_update(window: Window, name: String, projects: Vec<PathBuf>) -> IdeResult<ProjectInfo> {
let host = window.state::<AppState>().host.clone();
let label = window.label().to_owned();
let info = tauri::async_runtime::spawn_blocking(move || {
@@ -57,7 +57,7 @@ pub async fn workspace_update(window: WebviewWindow, name: String, projects: Vec
#[desktop_command(trust = always)]
#[tauri::command]
#[specta::specta]
pub async fn workspace_attach(window: WebviewWindow, path: PathBuf) -> IdeResult<ide_core::IpcPath> {
pub async fn workspace_attach(window: Window, path: PathBuf) -> IdeResult<ide_core::IpcPath> {
let host = window.state::<AppState>().host.clone();
let label = window.label().to_owned();
let root =
+5 -3
Переглянути файл
@@ -1,9 +1,11 @@
use crate::windows::WorkbenchWindows;
use ide_core::{EventSink, IdeEvent, SharedSink};
use parking_lot::Mutex;
use std::collections::{HashMap, VecDeque};
use std::sync::Arc;
use std::time::Duration;
use tauri::{AppHandle, Emitter, Manager, UserAttentionType};
use tauri::{AppHandle, Emitter, UserAttentionType};
/// Name of the single backend → UI event. Payload: [`IdeEvent`].
pub const IDE_EVENT: &str = "ide://event";
@@ -149,7 +151,7 @@ fn flash_taskbar_unless_focused(app: &AppHandle) {
if crate::application_focus::application_active(&handle) {
return;
}
for window in handle.webview_windows().values() {
for window in handle.workbench_windows().values() {
let _ = window.request_user_attention(Some(UserAttentionType::Informational));
}
});
@@ -188,7 +190,7 @@ impl EventSink for TauriSink {
{
let app = self.app.clone();
let _ = self.app.run_on_main_thread(move || {
if let Some(window) = app.get_webview_window(&label) {
if let Some(window) = app.workbench_window(&label) {
let _ = window.unminimize();
let _ = window.show();
let _ = window.set_focus();
+9 -1
Переглянути файл
@@ -7,6 +7,7 @@
#![recursion_limit = "512"]
mod application_focus;
mod browser_picker;
mod cli;
mod commands;
#[cfg(debug_assertions)]
@@ -48,6 +49,8 @@ mod windows_webview_keys;
#[cfg(windows)]
mod windows_webview_recovery;
use crate::windows::WorkbenchWindows;
use parking_lot::Mutex;
use state::AppState;
use std::path::{Path, PathBuf};
@@ -185,6 +188,10 @@ pub fn run() {
});
app.invoke_handler(move |request| {
let webview = request.message.webview_ref();
if browser_picker::is_guest(webview.label()) {
request.resolver.reject("Browser pages cannot invoke IDE commands");
return true;
}
if let Some(state) = webview.try_state::<AppState>() {
let label = AppState::owner_window(webview.label());
let command = request.message.command();
@@ -298,6 +305,7 @@ pub fn run() {
window_groups::frame_changed(window.app_handle(), window.label());
}
tauri::WindowEvent::Destroyed => {
browser_picker::forget(window.label());
// Also release a view that failed during startup, before the parent could watch it.
if let Some(state) = window.try_state::<AppState>()
&& let Ok(project) = state.host.project(window.label())
@@ -427,7 +435,7 @@ pub(crate) fn dispatch_menu_action(app: &tauri::AppHandle, id: &str) {
let label = match windows::menu_destination(w.label(), &route.action) {
windows::MenuDestination::Own => w.label(),
windows::MenuDestination::Parent { label, raise } => {
if raise && let Some(parent) = app.get_webview_window(label) {
if raise && let Some(parent) = app.workbench_window(label) {
windows::focus(&parent);
return_to = Some(w.label());
}
+7 -6
Переглянути файл
@@ -12,6 +12,7 @@ fn build_hidden(config: &mut WindowConfig) -> bool {
#[cfg(target_os = "linux")]
mod runtime {
use super::*;
use crate::windows::WorkbenchWindows;
use parking_lot::Mutex;
use std::collections::HashMap;
use std::sync::OnceLock;
@@ -336,8 +337,8 @@ mod runtime {
let app = window.app_handle().clone();
let label = window.label().to_owned();
let _ = window.run_on_main_thread(move || {
if let Some(parent) = crate::windows::auxiliary_parent(&label).and_then(|p| app.get_webview_window(p))
&& let Some(aux) = app.get_webview_window(&label)
if let Some(parent) = crate::windows::auxiliary_parent(&label).and_then(|p| app.workbench_window(p))
&& let Some(aux) = app.workbench_window(&label)
&& let Err(error) = crate::windows::place_over_parent(&aux, &parent)
{
tracing::warn!("cannot fit restored auxiliary window: {error}");
@@ -380,7 +381,7 @@ mod runtime {
let saved = cache.saved.entry(key(label).to_owned()).or_default();
saved.set_normal_size(Size(size.width, size.height));
drop(cache);
if let Some(webview) = app.get_webview_window(label) {
if let Some(webview) = app.workbench_window(label) {
request_presentation(webview.as_ref(), request);
}
}
@@ -419,7 +420,7 @@ mod runtime {
}
pub fn save_before_close(app: &AppHandle) {
for window in app.webview_windows().values() {
for window in app.workbench_windows().values() {
sample(&window.as_ref().window(), false, false);
}
persist(app);
@@ -464,7 +465,7 @@ mod runtime {
request: u64,
}
let Ok(presented) = serde_json::from_str::<Presented>(event.payload()) else { return };
let Some(webview) = handle.get_webview_window(&presented.label) else { return };
let Some(webview) = handle.workbench_window(&presented.label) else { return };
let window = webview.as_ref().window();
let cloned = window.clone();
let _ = window.run_on_main_thread(move || {
@@ -510,7 +511,7 @@ mod runtime {
.filter(|p| !p.presented)
.map(|p| p.presentation_request);
if let Some(request) = request
&& let Some(webview) = cloned.app_handle().get_webview_window(cloned.label())
&& let Some(webview) = cloned.app_handle().workbench_window(cloned.label())
{
request_presentation(webview.as_ref(), request);
}
+23 -1
Переглянути файл
@@ -1,4 +1,6 @@
//! macOS project tabs: native window tab groups behind the page's own tab bar.
use crate::windows::WorkbenchWindows;
use crate::windows::{Launch, WindowsState};
use ide_core::{IdeError, IdeResult};
use ide_workspace::window_groups::{TabbingPreference, should_group_new_project};
@@ -31,7 +33,7 @@ fn tabbing_preference(app: &AppHandle) -> IdeResult<TabbingPreference> {
/// Capture before building the new window, which takes focus itself.
pub fn new_project_tab_target(app: &AppHandle, launch: &Launch) -> IdeResult<Option<WebviewWindow>> {
let windows = app.webview_windows();
let windows = app.workbench_windows();
let active = windows
.values()
.find(|w| w.is_focused().unwrap_or(false))
@@ -126,6 +128,26 @@ pub fn move_tab_to_new_window(window: &WebviewWindow) -> tauri::Result<()> {
})
}
/// Hides `windows` together in a single main-thread turn so a closing window or tab group
/// disappears at once instead of flipping through remaining tabs while webviews tear down.
/// Native fullscreen windows are left for AppKit's own Space close transition.
pub fn hide_windows(windows: Vec<WebviewWindow>) {
if windows.is_empty() {
return;
}
let first = windows[0].clone();
let _ = on_main(&first, move || {
for window in &windows {
if window.is_fullscreen().unwrap_or(false) {
continue;
}
if let Some(native) = native(window) {
native.orderOut(None);
}
}
});
}
fn has_tab_bar(view: &objc2_app_kit::NSView) -> bool {
let class = view.class().name().to_string_lossy();
class.contains("TabBar") || view.subviews().iter().any(|v| has_tab_bar(&v))
+4
Переглянути файл
@@ -79,6 +79,10 @@ fn with_bridge(html: &[u8]) -> Vec<u8> {
}
pub fn handle<R: Runtime>(ctx: UriSchemeContext<'_, R>, request: Request<Vec<u8>>, responder: UriSchemeResponder) {
if crate::browser_picker::is_guest(ctx.webview_label()) {
responder.respond(status(StatusCode::FORBIDDEN));
return;
}
let app = ctx.app_handle().clone();
let path = request.uri().path().to_owned();
tauri::async_runtime::spawn_blocking(move || {
+3 -1
Переглянути файл
@@ -5,6 +5,8 @@
//! active. Click focuses the window that raised the toast — balloon actions stay
//! in the IDE.
use crate::windows::WorkbenchWindows;
use parking_lot::Mutex;
use std::collections::HashMap;
use std::sync::LazyLock;
@@ -121,7 +123,7 @@ fn activate(app: &AppHandle, id: i32) {
let Some(window_label) = STATE.take_target(id) else { return };
let app = app.clone();
let _ = app.clone().run_on_main_thread(move || {
let Some(window) = app.get_webview_window(&window_label) else { return };
let Some(window) = app.workbench_window(&window_label) else { return };
let _ = window.unminimize();
let _ = window.show();
let _ = window.set_focus();
+3 -1
Переглянути файл
@@ -1,5 +1,7 @@
//! Desktop updater coordination shared by all webviews.
use crate::windows::WorkbenchWindows;
use crate::commands::window::{UpdateSource, check_update, update_endpoint_env, updates_configured};
use crate::state::AppState;
use ide_core::updates::{UpdateCheck, UpdatePolicy};
@@ -145,7 +147,7 @@ fn announce_available(app: &AppHandle) {
let live = crate::windows::project_window_labels(app);
let owner = {
let mut ready = state.updates.ready.lock();
ready.retain(|label| app.get_webview_window(label).is_some());
ready.retain(|label| app.workbench_window(label).is_some());
ready_owner(focused.as_ref().map(|window| window.label()), &live, &ready)
};
let Some(owner) = owner else { return };
+265 -59
Переглянути файл
@@ -1,4 +1,6 @@
//! Desktop adapter for application-drawn project tabs. Each member retains its WebView and services.
use crate::windows::WorkbenchWindows;
use crate::{
state::AppState,
windows::{self, WindowsState},
@@ -6,7 +8,7 @@ use crate::{
use ide_core::{IdeError, IdeEvent, IdeResult};
use serde::{Deserialize, Serialize};
use specta::Type;
use std::collections::VecDeque;
use std::collections::HashSet;
use std::path::PathBuf;
use std::sync::atomic::Ordering;
use tauri::{AppHandle, Manager, WebviewWindow};
@@ -33,7 +35,7 @@ pub fn current(app: &AppHandle, caller: &str) -> Vec<WindowTab> {
.members
.iter()
.filter_map(|label| {
let window = app.get_webview_window(label)?;
let window = app.workbench_window(label)?;
let project = host.project(label).ok();
let name = project.as_ref().map(|p| ide_host::ops::project::info(p).display_name).unwrap_or_else(|| {
// Taken its launch but not finished opening: name the tab after that project.
@@ -75,7 +77,7 @@ pub fn toggle_fullscreen(window: &WebviewWindow) -> IdeResult<bool> {
}
pub fn select(app: &AppHandle, caller: &str, target: &str) -> IdeResult<()> {
let to = app.get_webview_window(target).ok_or_else(|| IdeError::not_found("Window closed"))?;
let to = app.workbench_window(target).ok_or_else(|| IdeError::not_found("Window closed"))?;
let state = app.state::<WindowsState>();
let previous = state.groups.lock().select(caller, target)?;
#[cfg(target_os = "macos")]
@@ -85,7 +87,7 @@ pub fn select(app: &AppHandle, caller: &str, target: &str) -> IdeResult<()> {
if result.is_err() {
let _ = state.groups.lock().select(caller, &previous.selected);
#[cfg(target_os = "macos")]
if let Some(window) = app.get_webview_window(&previous.selected) {
if let Some(window) = app.workbench_window(&previous.selected) {
let _ = native_select(app, &previous, &window);
}
#[cfg(not(target_os = "macos"))]
@@ -103,8 +105,8 @@ pub fn select(app: &AppHandle, caller: &str, target: &str) -> IdeResult<()> {
/// Shows `to` as the selected tab of the group's native tab group.
#[cfg(target_os = "macos")]
fn native_select(app: &AppHandle, group: &Group, to: &WebviewWindow) -> IdeResult<()> {
let members = group.members.iter().filter_map(|m| app.get_webview_window(m)).collect();
let anchor = app.get_webview_window(&group.selected).unwrap_or_else(|| to.clone());
let members = group.members.iter().filter_map(|m| app.workbench_window(m)).collect();
let anchor = app.workbench_window(&group.selected).unwrap_or_else(|| to.clone());
to.unminimize().map_err(|e| IdeError::internal(e.to_string()))?;
crate::macos::sync_tab_group(members, &anchor, to).map_err(|e| IdeError::internal(e.to_string()))
}
@@ -125,7 +127,7 @@ pub fn merge(app: &AppHandle, caller: &str) -> IdeResult<()> {
}
// Native fullscreen puts each window in a separate Space; leave it before grouping.
for label in &members {
if let Some(window) = app.get_webview_window(label) {
if let Some(window) = app.workbench_window(label) {
window.set_fullscreen(false).map_err(|e| IdeError::internal(e.to_string()))?;
}
}
@@ -140,13 +142,13 @@ pub fn detach(app: &AppHandle, caller: &str) -> IdeResult<()> {
changed(app);
return Ok(());
};
let window = app.get_webview_window(caller);
let window = app.workbench_window(caller);
// A tab moved out of a fullscreen group stays fullscreen in a Space of its own.
#[cfg(target_os = "macos")]
if let Some(window) = &window {
crate::macos::move_tab_to_new_window(window).map_err(err)?;
}
if let Some(next) = app.get_webview_window(&next) {
if let Some(next) = app.workbench_window(&next) {
#[cfg(target_os = "macos")]
if state.groups.lock().group(next.label()).is_some() {
select(app, next.label(), next.label())?;
@@ -169,35 +171,59 @@ pub fn detach(app: &AppHandle, caller: &str) -> IdeResult<()> {
pub fn destroyed(app: &AppHandle, caller: &str) {
let Some(state) = app.try_state::<WindowsState>() else { return };
let next = state.groups.lock().detach(caller);
let batch_done_keep = {
let mut batch = state.tab_closes.lock();
if let Some(b) = batch.as_mut()
&& b.pending.remove(caller)
&& b.pending.is_empty()
{
Some(batch.take().unwrap().keep)
} else {
None
}
};
let next_closing = next.as_deref().is_some_and(|label| state.is_closing(label));
let more_closing = state.has_other_pending_closes(caller);
if !state.quitting() {
if let Some(window) = next.and_then(|label| app.get_webview_window(&label)) {
if let Some(keep) = batch_done_keep {
if let Some(window) = app.workbench_window(&keep)
&& !window.is_focused().unwrap_or(false)
{
windows::focus(&window);
}
} else if !next_closing && let Some(window) = next.as_deref().and_then(|label| app.workbench_window(label)) {
windows::focus(&window);
}
let app = app.clone();
tauri::async_runtime::spawn(async move {
let _ = persist(&app).await;
});
}
changed(app);
let advance = state.tab_closes.lock().as_mut().is_some_and(|batch| {
let closing = batch.pending.front().is_some_and(|l| l == caller);
if closing {
batch.pending.pop_front();
if !more_closing {
let app = app.clone();
tauri::async_runtime::spawn(async move {
let _ = persist(&app).await;
});
}
closing
});
if advance {
close_next(app);
}
if !next_closing || !more_closing {
changed(app);
}
}
/// Tabs left to close; the first one is closing now.
/// Tabs closing together in a batch (Close Other / Left / Right Tabs), keeping `keep`.
pub struct TabCloses {
keep: String,
pending: VecDeque<String>,
pub(crate) keep: String,
pub(crate) pending: HashSet<String>,
}
/// Closes `labels` one at a time so each project's unsaved-changes prompt is shown in turn, then selects `keep`.
impl TabCloses {
pub(crate) fn contains(&self, label: &str) -> bool {
self.pending.contains(label)
}
pub(crate) fn has_other(&self, exclude: &str) -> bool {
self.pending.iter().any(|l| l != exclude)
}
}
/// Closes `labels` in parallel without flipping tabs; any tab that needs a confirmation prompt
/// acquires the prompt turn and raises itself, and `keep` stays selected when the batch finishes.
pub fn close_tabs(app: &AppHandle, caller: &str, keep: &str, labels: Vec<String>) -> IdeResult<()> {
let state = app.state::<WindowsState>();
let members = state
@@ -209,58 +235,238 @@ pub fn close_tabs(app: &AppHandle, caller: &str, keep: &str, labels: Vec<String>
if !members.iter().any(|m| m == keep) {
return Err(IdeError::invalid("The window is not in this group"));
}
let pending = members.into_iter().filter(|m| m != keep && labels.contains(m)).collect();
let targets: Vec<String> = members.into_iter().filter(|m| m != keep && labels.contains(m)).collect();
if targets.is_empty() {
return Ok(());
}
let pending: HashSet<String> = targets.iter().cloned().collect();
*state.tab_closes.lock() = Some(TabCloses { keep: keep.to_owned(), pending });
close_next(app);
// Pre-register every target before invoking `close()` so early responders see the full cohort.
for label in &targets {
state.close_requested(label);
}
let mut any_sent = false;
for label in targets {
if let Some(window) = app.workbench_window(&label)
&& window.close().is_ok()
{
any_sent = true;
continue;
}
if let Some(b) = state.tab_closes.lock().as_mut() {
b.pending.remove(&label);
}
state.close_settled(&label);
}
if !any_sent {
*state.tab_closes.lock() = None;
if let Some(window) = app.workbench_window(keep) {
windows::focus(&window);
}
}
Ok(())
}
/// The closing tab's project vetoed (its unsaved-changes prompt was cancelled): leave the rest open.
/// The closing tab stayed open (either its prompt was cancelled or it returned to Welcome).
pub fn cancel_close(app: &AppHandle, caller: &str) {
let state = app.state::<WindowsState>();
let cancelled_batch = {
let mut batch = state.tab_closes.lock();
if batch.as_ref().is_some_and(|b| b.pending.contains(caller)) { batch.take() } else { None }
};
if let Some(batch) = cancelled_batch {
// A vetoed Close Other/Left/Right Tabs leaves the remaining tabs open too.
state.abort_batch(batch.pending.into_iter().filter(|l| l != caller));
state.close_settled(caller);
return;
}
state.close_settled(caller);
let mut batch = state.tab_closes.lock();
if batch.as_ref().is_some_and(|b| b.pending.front().is_some_and(|l| l == caller)) {
*batch = None;
// For a red-button group close where this tab stayed open (e.g. returned to Welcome),
// select it so closing siblings disappear behind it without flashing.
if state.groups.lock().group(caller).is_some()
&& let Some(window) = app.workbench_window(caller)
{
windows::focus(&window);
}
if !state.has_other_pending_closes(caller) && !state.quitting() {
let app = app.clone();
tauri::async_runtime::spawn(async move {
let _ = persist(&app).await;
});
}
}
fn close_next(app: &AppHandle) {
/// Waits for the caller's interactive prompt turn in a parallel batch close and brings it forward.
/// Returns `false` if the batch was cancelled while waiting (the caller should stay open quietly).
pub async fn begin_prompt(app: &AppHandle, window: &WebviewWindow) -> bool {
let label = window.label();
let state = app.state::<WindowsState>();
loop {
let next = {
let mut batch = state.tab_closes.lock();
let Some(b) = batch.as_mut() else { return };
match b.pending.front() {
Some(label) => Ok(label.clone()),
None => Err(batch.take().unwrap().keep),
let notified = state.close_notify.notified();
tokio::pin!(notified);
notified.as_mut().enable();
match state.try_acquire_prompt(label) {
Ok(true) => {
windows::focus(window);
return true;
}
};
match next {
Ok(label) => {
if let Some(window) = app.get_webview_window(&label) {
windows::focus(&window);
if window.close().is_ok() {
return;
}
}
if let Some(b) = state.tab_closes.lock().as_mut() {
b.pending.pop_front();
}
Ok(false) => {
notified.await;
}
Err(keep) => {
if let Some(window) = app.get_webview_window(&keep) {
windows::focus(&window);
}
return;
Err(()) => {
state.take_aborted(label);
return false;
}
}
}
}
pub fn end_prompt(app: &AppHandle, caller: &str) {
app.state::<WindowsState>().release_prompt(caller);
}
/// Coordinates the final hide/destroy step across windows closing together.
/// Returns `false` if the batch was cancelled while waiting (the caller must stay open).
pub async fn ready_to_close(app: &AppHandle, window: &WebviewWindow) -> bool {
let label = window.label();
let state = app.state::<WindowsState>();
if !state.mark_ready(label) {
return false;
}
const BARRIER_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(3);
const POLL_STEP: std::time::Duration = std::time::Duration::from_millis(250);
let mut waited_idle = std::time::Duration::ZERO;
let mut last_tick = std::time::Instant::now();
loop {
let notified = state.close_notify.notified();
tokio::pin!(notified);
notified.as_mut().enable();
if state.take_aborted(label) {
return false;
}
let (cohort, keep_label) = close_cohort(app, &state, label);
let any_undecided =
cohort.iter().any(|peer| peer != label && app.workbench_window(peer).is_some() && !state.is_ready(peer));
if !any_undecided {
finish_cohort_visuals(app, &state, label, &cohort, keep_label.as_deref());
state.close_notify.notify_waiters();
return true;
}
match tokio::time::timeout(POLL_STEP, notified).await {
Ok(()) => {
waited_idle = std::time::Duration::ZERO;
last_tick = std::time::Instant::now();
}
Err(_) => {
// Never time out while another tab is waiting on the user's answer to a dialog.
if state.has_prompt_holder() {
waited_idle = std::time::Duration::ZERO;
} else {
waited_idle += last_tick.elapsed();
if waited_idle >= BARRIER_TIMEOUT {
let single = vec![label.to_owned()];
if !state.claim_hide(&single).is_empty() && state.groups.lock().group(label).is_none() {
windows::hide_windows(vec![window.clone()]);
}
return true;
}
}
last_tick = std::time::Instant::now();
}
}
}
}
fn close_cohort(app: &AppHandle, state: &WindowsState, label: &str) -> (Vec<String>, Option<String>) {
if state.quitting() {
let pending = state.pending_closes();
let mut cohort: Vec<String> = windows::project_window_labels(app)
.into_iter()
.filter(|l| l == label || pending.iter().any(|p| p == l))
.collect();
if !cohort.iter().any(|l| l == label) {
cohort.push(label.to_owned());
}
return (cohort, None);
}
if let Some((keep, pending)) = state
.tab_closes
.lock()
.as_ref()
.filter(|b| b.pending.contains(label))
.map(|b| (b.keep.clone(), b.pending.iter().cloned().collect::<Vec<_>>()))
{
return (pending, Some(keep));
}
let pending = state.pending_closes();
let group_members = state.groups.lock().group(label).map(|g| g.members.clone());
if let Some(members) = group_members {
let mut cohort: Vec<String> =
members.into_iter().filter(|m| m == label || pending.iter().any(|p| p == m)).collect();
if !cohort.iter().any(|l| l == label) {
cohort.push(label.to_owned());
}
return (cohort, None);
}
(vec![label.to_owned()], None)
}
/// Applies the visual transition once every peer in `cohort` is ready to close:
/// - Whole closing window or whole closing tab group (or quit): hide all of them in a single frame.
/// - Partial tab group close (Close Other Tabs, single tab close, or keeper returning to Welcome):
/// ensure a surviving tab is selected so the closing tabs tear down invisibly behind it.
fn finish_cohort_visuals(
app: &AppHandle,
state: &WindowsState,
label: &str,
cohort: &[String],
keep_label: Option<&str>,
) {
if state.quitting() {
let to_hide = state.claim_hide(cohort);
let windows: Vec<_> = to_hide.into_iter().filter_map(|l| app.workbench_window(&l)).collect();
windows::hide_windows(windows);
return;
}
let group_snapshot = state.groups.lock().group(label).cloned();
if let Some(group) = group_snapshot {
let cohort_set: HashSet<&str> = cohort.iter().map(String::as_str).collect();
let all_closing = group.members.iter().all(|m| cohort_set.contains(m.as_str()));
if all_closing {
let to_hide = state.claim_hide(&group.members);
let windows: Vec<_> = to_hide.into_iter().filter_map(|l| app.workbench_window(&l)).collect();
windows::hide_windows(windows);
} else {
let survivor = keep_label
.filter(|k| !cohort_set.contains(*k))
.map(str::to_owned)
.or_else(|| group.members.iter().find(|m| !cohort_set.contains(m.as_str())).cloned());
// Only switch tabs if the currently visible tab is one of the closing ones.
if cohort_set.contains(group.selected.as_str())
&& let Some(survivor) = survivor
&& !state.claim_hide(cohort).is_empty()
&& let Some(window) = app.workbench_window(&survivor)
{
windows::focus(&window);
}
}
} else {
let to_hide = state.claim_hide(cohort);
let windows: Vec<_> = to_hide.into_iter().filter_map(|l| app.workbench_window(&l)).collect();
windows::hide_windows(windows);
}
}
/// Window labels in creation order: `main`, then `project-1`, `project-2`, ….
fn labels_in_order(app: &AppHandle) -> Vec<String> {
let mut labels: Vec<String> = app.webview_windows().into_keys().collect();
let mut labels: Vec<String> = app.workbench_windows().into_keys().collect();
labels.sort_by_key(|l| (l != "main", l.rsplit('-').next().and_then(|n| n.parse::<u32>().ok()), l.clone()));
labels
}
+7 -5
Переглянути файл
@@ -1,5 +1,7 @@
//! Window groups without native tabs: one member is shown at a time, and the hidden ones are kept
//! at its frame so that selecting a tab only changes which window is visible.
use crate::windows::WorkbenchWindows;
use super::Group;
use crate::windows::WindowsState;
use ide_core::{IdeError, IdeResult};
@@ -153,12 +155,12 @@ fn sync_member_frames(app: &AppHandle, selected: &str) {
if group.selected != selected {
return;
}
let Some(from) = app.get_webview_window(selected) else { return };
let Some(from) = app.workbench_window(selected) else { return };
if from.is_fullscreen().unwrap_or(false) || from.is_minimized().unwrap_or(false) {
return;
}
for member in group.members.iter().filter(|member| member.as_str() != selected) {
let Some(to) = app.get_webview_window(member) else { continue };
let Some(to) = app.workbench_window(member) else { continue };
// A visible peer is the one being presented; never move it behind the user's back.
if to.is_visible().unwrap_or(false) {
continue;
@@ -194,7 +196,7 @@ pub(super) fn frame_changed(app: &AppHandle, label: &str) {
pub(super) fn present(app: &AppHandle, previous: &Group, target: &str, to: &WebviewWindow) -> IdeResult<()> {
let err = |e: tauri::Error| IdeError::internal(e.to_string());
if previous.selected != target
&& let Some(from) = app.get_webview_window(&previous.selected)
&& let Some(from) = app.workbench_window(&previous.selected)
{
show_at_frame(&from, to)?;
} else {
@@ -204,7 +206,7 @@ pub(super) fn present(app: &AppHandle, previous: &Group, target: &str, to: &Webv
}
for member in &previous.members {
if member != target
&& let Some(window) = app.get_webview_window(member)
&& let Some(window) = app.workbench_window(member)
{
window.hide().map_err(err)?;
}
@@ -215,7 +217,7 @@ pub(super) fn present(app: &AppHandle, previous: &Group, target: &str, to: &Webv
/// Shows the previously selected member again after a failed selection.
pub(super) fn restore_selection(app: &AppHandle, previous: &Group) {
for member in &previous.members {
if let Some(window) = app.get_webview_window(member) {
if let Some(window) = app.workbench_window(member) {
if member == &previous.selected {
let _ = window.show();
let _ = window.set_focus();
+327 -40
Переглянути файл
@@ -24,8 +24,9 @@ use ide_core::{IdeError, IdeResult};
use parking_lot::Mutex;
use serde::{Deserialize, Serialize};
use specta::Type;
use std::collections::HashMap;
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use tauri::utils::config::{Color, WindowConfig};
use tauri::{AppHandle, Emitter, Manager, Theme, WebviewWindow, WebviewWindowBuilder};
@@ -289,7 +290,7 @@ pub(crate) fn reopen_saved_window(app: &AppHandle, path: &Path) -> IdeResult<Opt
};
if let Some(remote) = launch.remote.clone() {
let open = app.try_state::<AppState>().and_then(|s| s.remote_dev.window_of(&remote.target, &remote.path));
if let Some(w) = open.and_then(|label| app.get_webview_window(&label)) {
if let Some(w) = open.and_then(|label| app.workbench_window(&label)) {
return Ok(Some(w));
}
let title = remote
@@ -309,6 +310,7 @@ pub(crate) fn reopen_saved_window(app: &AppHandle, path: &Path) -> IdeResult<Opt
#[derive(Default)]
pub struct WindowsState {
primary: Mutex<HashMap<String, WebviewWindow>>,
pub groups: Mutex<ide_workspace::window_groups::WindowGroups>,
pub groups_restored: AtomicBool,
/// Serialises writes of the saved session. Holds the previous run's session once read: it is
@@ -320,15 +322,16 @@ pub struct WindowsState {
cli: Mutex<cli::Queue>,
/// Most recently focused window label (menu events go there).
last_focused: Mutex<Option<String>>,
/// Set by Quit while windows close one by one.
/// Set by Quit while windows close in parallel.
quitting: AtomicBool,
/// The last closed project opted out of Welcome; macOS keeps its app in the Dock.
#[cfg(target_os = "macos")]
pub keep_alive: AtomicBool,
/// Windows asked to close whose guards have not finished. AppKit closes a whole tab group at
/// once, so its members ask together.
close_requests: Mutex<Vec<String>>,
/// Project tabs closing one by one (Close Other Tabs and friends).
/// Coordinates parallel window/tab-group closes so clean tabs hide together in one frame
/// and interactive prompts still run one at a time.
close: Mutex<CloseState>,
pub close_notify: Arc<tokio::sync::Notify>,
/// Project tabs closing in parallel (Close Other Tabs and friends).
pub tab_closes: Mutex<Option<crate::window_groups::TabCloses>>,
/// Relaunch once the quit completes (after installing an update).
restart: AtomicBool,
@@ -355,20 +358,221 @@ pub(crate) struct AuxGeometry {
pub maximized: bool,
}
/// Tauri's WebviewWindow lookup and command argument both stop matching as soon as a
/// window has a second webview. Keep addressing its original, trusted workbench instead.
pub(crate) trait WorkbenchWindows {
fn workbench_window(&self, label: &str) -> Option<WebviewWindow>;
fn workbench_windows(&self) -> HashMap<String, WebviewWindow>;
}
impl WorkbenchWindows for AppHandle {
fn workbench_window(&self, label: &str) -> Option<WebviewWindow> {
self.state::<WindowsState>().primary.lock().get(label).cloned()
}
fn workbench_windows(&self) -> HashMap<String, WebviewWindow> {
self.state::<WindowsState>().primary.lock().clone()
}
}
pub struct WorkbenchWindow(WebviewWindow);
impl std::ops::Deref for WorkbenchWindow {
type Target = WebviewWindow;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<'a> tauri::ipc::CommandArg<'a, tauri::Wry> for WorkbenchWindow {
fn from_command(item: tauri::ipc::CommandItem<'a, tauri::Wry>) -> Result<Self, tauri::ipc::InvokeError> {
let view = item.message.webview_ref();
view.app_handle()
.workbench_window(view.label())
.map(Self)
.ok_or_else(|| tauri::ipc::InvokeError::from("Not a workbench webview"))
}
}
impl specta::function::FunctionArg for WorkbenchWindow {
fn to_datatype(_: &mut specta::Types) -> Option<specta::datatype::DataType> {
None
}
}
#[derive(Default)]
struct CloseState {
/// Windows asked to close whose guards have not finished. AppKit closes a whole tab group at
/// once, so its members ask together; Quit and Close Other Tabs also close members in parallel.
pending: Vec<String>,
/// Members that passed their close guard and are waiting at the batch barrier before destroying.
ready: HashSet<String>,
/// Members whose batch was cancelled while they waited; they stay open.
aborted: HashSet<String>,
/// Windows already hidden as part of their closing cohort so hiding only runs once per batch.
hidden: HashSet<String>,
/// Window currently showing an interactive close dialog (at most one across a batch).
prompt_holder: Option<String>,
}
impl WindowsState {
pub fn close_requested(&self, label: &str) {
let mut requests = self.close_requests.lock();
if !requests.iter().any(|l| l == label) {
requests.push(label.to_owned());
let mut close = self.close.lock();
close.aborted.remove(label);
close.ready.remove(label);
close.hidden.remove(label);
if !close.pending.iter().any(|l| l == label) {
close.pending.push(label.to_owned());
}
}
pub fn close_settled(&self, label: &str) {
self.close_requests.lock().retain(|l| l != label);
{
let mut close = self.close.lock();
close.pending.retain(|l| l != label);
close.ready.remove(label);
close.aborted.remove(label);
close.hidden.remove(label);
if close.prompt_holder.as_deref() == Some(label) {
close.prompt_holder = None;
}
}
self.close_notify.notify_waiters();
}
pub fn pending_closes(&self) -> Vec<String> {
self.close_requests.lock().clone()
self.close.lock().pending.clone()
}
pub fn is_closing(&self, label: &str) -> bool {
let in_close = {
let close = self.close.lock();
close.pending.iter().any(|l| l == label) || close.ready.contains(label)
};
in_close || self.in_tab_close_batch(label)
}
pub fn has_other_pending_closes(&self, exclude: &str) -> bool {
let other_pending = self.close.lock().pending.iter().any(|l| l != exclude);
other_pending || self.tab_closes.lock().as_ref().is_some_and(|b| b.has_other(exclude))
}
pub fn in_tab_close_batch(&self, label: &str) -> bool {
self.tab_closes.lock().as_ref().is_some_and(|b| b.contains(label))
}
/// Marks `label` ready to destroy. Returns `false` if its batch was already cancelled.
pub fn mark_ready(&self, label: &str) -> bool {
let ok = {
let mut close = self.close.lock();
if close.aborted.remove(label) {
close.pending.retain(|l| l != label);
close.ready.remove(label);
close.hidden.remove(label);
if close.prompt_holder.as_deref() == Some(label) {
close.prompt_holder = None;
}
false
} else {
if close.prompt_holder.as_deref() == Some(label) {
close.prompt_holder = None;
}
close.ready.insert(label.to_owned());
true
}
};
self.close_notify.notify_waiters();
ok
}
pub fn is_ready(&self, label: &str) -> bool {
self.close.lock().ready.contains(label)
}
pub fn take_aborted(&self, label: &str) -> bool {
let mut close = self.close.lock();
if close.aborted.remove(label) {
close.pending.retain(|l| l != label);
close.ready.remove(label);
close.hidden.remove(label);
true
} else {
false
}
}
/// Marks `labels` as hidden once and returns those newly claimed for hiding.
pub fn claim_hide(&self, labels: &[String]) -> Vec<String> {
let mut close = self.close.lock();
labels.iter().filter(|l| close.hidden.insert((*l).clone())).cloned().collect()
}
/// Marks `labels` as aborted so peers waiting at the close barrier or prompt turn stay open.
pub fn abort_batch(&self, labels: impl IntoIterator<Item = String>) {
{
let mut close = self.close.lock();
for label in labels {
close.ready.remove(&label);
close.hidden.remove(&label);
close.pending.retain(|l| l != &label);
close.aborted.insert(label);
}
close.prompt_holder = None;
}
self.close_notify.notify_waiters();
}
/// Aborts every in-flight close except `initiator` (used when cancelling Quit).
pub fn abort_all_closing(&self, initiator: Option<&str>) {
{
let mut close = self.close.lock();
let mut targets: Vec<String> = std::mem::take(&mut close.pending);
for label in close.ready.drain() {
if !targets.iter().any(|l| l == &label) {
targets.push(label);
}
}
close.hidden.clear();
close.prompt_holder = None;
for label in targets {
if initiator != Some(label.as_str()) {
close.aborted.insert(label);
}
}
}
self.close_notify.notify_waiters();
}
/// Tries to acquire the interactive prompt turn. `Err(())` means this close was aborted.
pub fn try_acquire_prompt(&self, label: &str) -> Result<bool, ()> {
let mut close = self.close.lock();
if close.aborted.contains(label) {
return Err(());
}
if close.prompt_holder.is_none() || close.prompt_holder.as_deref() == Some(label) {
close.prompt_holder = Some(label.to_owned());
Ok(true)
} else {
Ok(false)
}
}
pub fn release_prompt(&self, label: &str) {
let released = {
let mut close = self.close.lock();
if close.prompt_holder.as_deref() == Some(label) {
close.prompt_holder = None;
true
} else {
false
}
};
if released {
self.close_notify.notify_waiters();
}
}
pub fn has_prompt_holder(&self) -> bool {
self.close.lock().prompt_holder.is_some()
}
pub fn set_launch(&self, label: &str, launch: Launch) {
@@ -429,6 +633,7 @@ impl WindowsState {
}
pub fn forget(&self, label: &str) {
self.primary.lock().remove(label);
self.close_settled(label);
{
let mut launches = self.launches.lock();
@@ -614,7 +819,7 @@ pub fn state_key(label: &str) -> &str {
/// `parent`'s auxiliary windows that show its project's documents.
pub fn document_windows(app: &AppHandle, parent: &str) -> Vec<String> {
app.webview_windows()
app.workbench_windows()
.into_keys()
.filter(|label| auxiliary(label).is_some_and(|(kind, p)| kind.shares_documents() && p == parent))
.collect()
@@ -624,7 +829,7 @@ pub fn document_windows(app: &AppHandle, parent: &str) -> Vec<String> {
/// Windows with documents are destroyed: the parent's leave guard has already settled their
/// unsaved changes (`closeAuxiliaryWindows` in the UI).
pub fn close_auxiliary_windows(app: &AppHandle, parent: &str) {
for (label, window) in app.webview_windows() {
for (label, window) in app.workbench_windows() {
match auxiliary(&label) {
Some((kind, p)) if p == parent && kind.shares_documents() => drop(window.destroy()),
Some((_, p)) if p == parent => drop(window.close()),
@@ -635,7 +840,7 @@ pub fn close_auxiliary_windows(app: &AppHandle, parent: &str) {
/// Project windows, excluding auxiliary windows, for counting and cycling.
pub fn project_window_labels(app: &AppHandle) -> Vec<String> {
sorted_labels(app.webview_windows().keys().map(String::as_str).filter(|l| auxiliary_parent(l).is_none()))
sorted_labels(app.workbench_windows().keys().map(String::as_str).filter(|l| auxiliary_parent(l).is_none()))
}
/// Sort key: `main` first, then `project-<n>` by n, then anything else.
@@ -747,29 +952,75 @@ pub fn focus(window: &WebviewWindow) {
let _ = window.set_focus();
}
/// Present one project's save prompt at a time, including hidden group members.
pub fn continue_quit(app: &AppHandle, closed: Option<&str>) {
if !app.state::<WindowsState>().quitting() {
pub fn hide_windows(windows: Vec<WebviewWindow>) {
#[cfg(target_os = "macos")]
crate::macos::hide_windows(windows);
#[cfg(not(target_os = "macos"))]
for window in windows {
let _ = window.hide();
}
}
/// Closes every project window in parallel without flipping focus across clean tabs.
/// Windows that need user confirmation acquire the prompt turn one at a time via `begin_prompt`.
pub fn start_quit(app: &AppHandle) {
let state = app.state::<WindowsState>();
let labels = project_window_labels(app);
if labels.is_empty() {
app.exit(0);
return;
}
let next = project_window_labels(app)
.into_iter()
.filter(|label| Some(label.as_str()) != closed)
.find_map(|label| app.get_webview_window(&label));
if let Some(window) = next {
focus(&window);
if window.close().is_err() {
app.state::<WindowsState>().set_quitting(false);
for label in &labels {
state.close_requested(label);
}
let mut any_sent = false;
for label in labels {
if let Some(window) = app.workbench_window(&label)
&& window.close().is_ok()
{
any_sent = true;
continue;
}
} else {
state.close_settled(&label);
}
if !any_sent {
if project_window_labels(app).is_empty() {
app.exit(0);
} else {
state.set_quitting(false);
}
}
}
/// Exits once every project window has finished closing during Quit.
pub fn continue_quit(app: &AppHandle, closed: Option<&str>) {
let state = app.state::<WindowsState>();
if !state.quitting() {
return;
}
let remaining: Vec<String> =
project_window_labels(app).into_iter().filter(|label| Some(label.as_str()) != closed).collect();
if remaining.is_empty() {
app.exit(0);
return;
}
// Close any window that appeared after Quit began and was not yet asked to close.
for label in remaining {
if !state.is_closing(&label)
&& let Some(window) = app.workbench_window(&label)
{
state.close_requested(&label);
if window.close().is_err() {
state.close_settled(&label);
}
}
}
}
/// The window whose open project is `root` (already canonical).
pub fn find_project_window(app: &AppHandle, root: &Path) -> Option<WebviewWindow> {
let state = app.try_state::<AppState>()?;
app.webview_windows().into_iter().filter(|(label, _)| auxiliary_parent(label).is_none()).find_map(|(label, w)| {
app.workbench_windows().into_iter().filter(|(label, _)| auxiliary_parent(label).is_none()).find_map(|(label, w)| {
let project = state.project(&label).ok()?;
(project.root == root && !project.light).then_some(w)
})
@@ -788,7 +1039,7 @@ fn send_files_at(app: &AppHandle, window: &WebviewWindow, files: Vec<PathBuf>, p
/// The focused window, else the last focused, else any.
pub fn target_window(app: &AppHandle) -> Option<WebviewWindow> {
let windows = app.webview_windows();
let windows = app.workbench_windows();
if let Some(w) = windows.values().find(|w| w.is_focused().unwrap_or(false)) {
return Some(w.clone());
}
@@ -863,6 +1114,7 @@ fn build_project_window(app: &AppHandle, mut config: WindowConfig) -> IdeResult<
let window = WebviewWindowBuilder::from_config(app, &config)
.and_then(|b| dev_font_preferences(webview_profile(app, b)).on_new_window(open_popup_in_browser).build())
.map_err(|e| IdeError::internal(format!("cannot create window: {e}")))?;
app.state::<WindowsState>().primary.lock().insert(window.label().into(), window.clone());
#[cfg(target_os = "linux")]
decorate_csd(&window);
#[cfg(target_os = "macos")]
@@ -977,7 +1229,7 @@ fn create_window_for(
let tab_target = if _restoring { None } else { crate::macos::new_project_tab_target(app, &launch)? };
// The label is free only until the window exists, so concurrent opens take turns.
let creating = CREATING.lock();
let windows = app.webview_windows();
let windows = app.workbench_windows();
let label = next_label(windows.keys().map(String::as_str));
let mut config = window_config(app)?;
config.label = label.clone();
@@ -1113,7 +1365,7 @@ pub fn open_remote_window(
new_window: bool,
) -> IdeResult<OpenOutcome> {
tracing::info!("open_remote_window {target:?}:{path} new_window={new_window}");
let windows = app.webview_windows();
let windows = app.workbench_windows();
let open = app.try_state::<AppState>().and_then(|s| s.remote_dev.window_of(target, path));
if let Some(w) = open.and_then(|label| windows.get(&label)) {
focus(w);
@@ -1397,18 +1649,18 @@ pub(crate) fn run_open_at(
for step in steps {
match step {
OpenStep::Focus(label) => {
if let Some(w) = app.get_webview_window(&label) {
if let Some(w) = app.workbench_window(&label) {
focus(&w);
}
}
OpenStep::Files(label, files) => match app.get_webview_window(&label) {
OpenStep::Files(label, files) => match app.workbench_window(&label) {
Some(w) => send_files_at(app, &w, files, positions),
None => windows.add_files_at(&label, files, positions),
},
OpenStep::Launch(label, mut launch) => {
launch.add_positions(positions);
windows.set_launch(&label, *launch);
if let Some(w) = app.get_webview_window(&label) {
if let Some(w) = app.workbench_window(&label) {
let _ = app.emit_to(&label, LAUNCH_EVENT, ());
focus(&w);
}
@@ -1467,7 +1719,7 @@ fn dispatch_cli(app: &AppHandle, args: Vec<String>, cwd: String) {
{
let target = target_window(app)
.filter(|window| auxiliary_parent(window.label()).is_none())
.or_else(|| project_window_labels(app).into_iter().find_map(|label| app.get_webview_window(&label)));
.or_else(|| project_window_labels(app).into_iter().find_map(|label| app.workbench_window(&label)));
if let Some(window) = target {
let _ = app.emit_to(
window.label(),
@@ -1549,7 +1801,7 @@ fn open_diff_files_at(app: &AppHandle, diff: DiffFilesLaunch, wait_for_window: b
&& matches!(holds(app, window.label()), Holds::Nothing | Holds::Project(_) | Holds::LightEdit)
};
let target = target_window(app).filter(local).or_else(|| {
project_window_labels(app).into_iter().filter_map(|label| app.get_webview_window(&label)).find(local)
project_window_labels(app).into_iter().filter_map(|label| app.workbench_window(&label)).find(local)
});
if let Some(window) = target {
app.state::<WindowsState>().add_diff(window.label(), diff);
@@ -1614,7 +1866,7 @@ fn drain_cli(app: &AppHandle) {
}
pub fn cycle(app: &AppHandle, current: &str, forward: bool) {
let windows = app.webview_windows();
let windows = app.workbench_windows();
let sorted = project_window_labels(app);
if let Some(w) = cycle_target(&sorted, current, forward).and_then(|l| windows.get(&l)) {
focus(w);
@@ -1651,7 +1903,7 @@ pub fn open_auxiliary_window(app: &AppHandle, caller: &WebviewWindow, aux: AuxWi
} else {
format!("{}-{parent_label}", aux.kind.name())
};
if let Some(existing) = app.get_webview_window(&label) {
if let Some(existing) = app.workbench_window(&label) {
if aux.launch != Launch::default() {
windows.set_launch(&label, aux.launch);
let _ = app.emit_to(label.as_str(), LAUNCH_EVENT, ());
@@ -1659,7 +1911,7 @@ pub fn open_auxiliary_window(app: &AppHandle, caller: &WebviewWindow, aux: AuxWi
focus(&existing);
return Ok(());
}
let parent = app.get_webview_window(&parent_label).ok_or_else(|| IdeError::not_found("no parent window"))?;
let parent = app.workbench_window(&parent_label).ok_or_else(|| IdeError::not_found("no parent window"))?;
let mut config = window_config(app)?;
config.label = label.clone();
config.title = aux.title.into();
@@ -1703,6 +1955,7 @@ pub fn open_auxiliary_window(app: &AppHandle, caller: &WebviewWindow, aux: AuxWi
windows.forget(&label);
IdeError::internal(format!("cannot create {} window: {e}", aux.kind.name()))
})?;
windows.primary.lock().insert(label.clone(), window.clone());
#[cfg(target_os = "linux")]
decorate_csd(&window);
#[cfg(target_os = "macos")]
@@ -1786,7 +2039,7 @@ pub fn open_settings_from_menu(app: &AppHandle, target: &WebviewWindow, action:
else {
return false;
};
let Some(parent) = app.get_webview_window(parent_label) else {
let Some(parent) = app.workbench_window(parent_label) else {
return false;
};
match open_settings_window(app, &parent, page, new_projects, None) {
@@ -3106,4 +3359,38 @@ mod tests {
assert_eq!(menu_settings_launch("main", true, true, "file.settings", None), None);
assert_eq!(menu_settings_launch("main", false, true, "file.openProject", None), None);
}
#[test]
fn parallel_close_coordination_tracks_ready_prompt_and_abort() {
let st = WindowsState::default();
st.close_requested("main");
st.close_requested("project-1");
assert!(st.is_closing("main"));
assert!(st.has_other_pending_closes("main"));
// Prompt turn allows only one holder at a time.
assert_eq!(st.try_acquire_prompt("main"), Ok(true));
assert_eq!(st.try_acquire_prompt("project-1"), Ok(false));
assert!(st.has_prompt_holder());
// Marking ready releases the prompt turn.
assert!(st.mark_ready("main"));
assert!(!st.has_prompt_holder());
assert_eq!(st.try_acquire_prompt("project-1"), Ok(true));
// Cancelling the batch aborts waiting ready peers and clears the prompt holder.
st.abort_all_closing(Some("project-1"));
assert!(!st.has_prompt_holder());
assert!(st.take_aborted("main"));
assert!(!st.is_closing("main"));
assert!(!st.take_aborted("project-1"));
// A fresh close clears any stale aborted state and claims hide once per cohort.
st.close_requested("main");
assert_eq!(
st.claim_hide(&["main".into(), "project-1".into()]),
vec!["main".to_string(), "project-1".to_string()]
);
assert!(st.claim_hide(&["main".into(), "project-1".into()]).is_empty());
}
}
+5
Переглянути файл
@@ -824,16 +824,20 @@ vcs_watch_commit_messages always project_host bin
vcs_worktree_include always project_host bindings async
vcs_worktrees always project_host bindings async
vcs_write_patch always project_host bindings async
web_browser_control trusted desktop bindings async
web_browser_open trusted desktop bindings async
web_browsers always desktop bindings async
web_goto always project_host bindings async
web_open always desktop bindings async
web_serves_page trusted desktop bindings async
web_unresolved_references always project_host bindings async
web_url always project_host bindings async
window_begin_prompt always desktop bindings async
window_close_context always desktop bindings sync
window_complete_launch always desktop bindings sync
window_cycle always desktop bindings sync
window_drag_files always desktop bindings async
window_end_prompt always desktop bindings sync
window_flash_taskbar always desktop bindings sync
window_group_cancel_close always desktop bindings sync
window_group_close always desktop bindings sync
@@ -857,6 +861,7 @@ window_open_project always desktop bin
window_open_projects always desktop bindings sync
window_open_remote always desktop bindings async
window_open_settings always desktop bindings async
window_ready_to_close always desktop bindings async
window_set_smooth_scrolling always desktop bindings sync
window_set_titlebar_height always desktop bindings sync
window_start_drag always desktop bindings sync
+47 -6
Переглянути файл
@@ -218,7 +218,7 @@ export const commands = {
* Async: the process walk runs on the blocking pool, not the main thread.
*/
appMetrics: () => typedError<AppMetrics, IdeError>(__TAURI_INVOKE("app_metrics")),
/** Quits: closes every window, each of which runs its own unsaved-changes check. */
/** Quits: closes every window in parallel, each of which runs its own unsaved-changes check. */
appQuit: () => __TAURI_INVOKE<void>("app_quit"),
/**
* Release notes of `version` from the update manifest (`latest.json`), read
@@ -858,8 +858,10 @@ export const commands = {
* A module with Kotlin / Groovy / Scala sources is built by its build system, whose class directories come first.
* The build streams its console, messages and progress on `on_event` while it runs; a launch
* whose build another launch's build joins receives that build's events.
* A Maven module is built by the IDE's Java build, except for a `debug` launch the language
* server serves: java-debug's HotSwap reloads the classes the language server compiles.
*/
javaResolveLaunch: (module: string, test: boolean, policy: BuildPolicy, request: RequestId, onEvent: Channel<BuildEvent>) => typedError<JavaLaunchInfo, IdeError>(__TAURI_INVOKE("java_resolve_launch", { module, test, policy, request, onEvent })),
javaResolveLaunch: (module: string, test: boolean, debug: boolean, policy: BuildPolicy, request: RequestId, onEvent: Channel<BuildEvent>) => typedError<JavaLaunchInfo, IdeError>(__TAURI_INVOKE("java_resolve_launch", { module, test, debug, policy, request, onEvent })),
/**
* Downloads the latest `vendor` JDK of Java `version` into `location` (default:
* [`jdk_download_location`]), streaming progress through `on_event`; cancellable
@@ -2263,6 +2265,9 @@ export const commands = {
vcsWorktrees: (repo: string | null) => typedError<Worktree[], IdeError>(__TAURI_INVOKE("vcs_worktrees", { repo })),
/** Create Patch › Save to file. */
vcsWritePatch: (path: string, patch: string, encoding: string | null) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_write_patch", { path, patch, encoding })),
webBrowserControl: (session: RequestId, action: BrowserAction) => typedError<BrowserStatus, IdeError>(__TAURI_INVOKE("web_browser_control", { session, action })),
/** Creates a private localhost browser session owned by this window and project. */
webBrowserOpen: (url: string, session: RequestId) => typedError<null, IdeError>(__TAURI_INVOKE("web_browser_open", { url, session })),
/** The browsers installed on this machine. */
webBrowsers: () => typedError<Browser[], IdeError>(__TAURI_INVOKE("web_browsers")),
/** The web reference at `pos` of `doc` and its targets; `None` when there is no reference. */
@@ -2281,6 +2286,11 @@ export const commands = {
* HTML (Settings › File Types can make it so) is served as a page, whatever its extension.
*/
webUrl: (path: IpcPath) => typedError<string, IdeError>(__TAURI_INVOKE("web_url", { path })),
/**
* Acquires the interactive prompt turn for a batch close and brings this window forward.
* Returns `false` if the batch was cancelled while waiting.
*/
windowBeginPrompt: () => __TAURI_INVOKE<boolean>("window_begin_prompt"),
windowCloseContext: () => __TAURI_INVOKE<CloseContext>("window_close_context"),
/** Release the opening window's reservation after navigation or cancellation. */
windowCompleteLaunch: () => typedError<null, IdeError>(__TAURI_INVOKE("window_complete_launch")),
@@ -2292,6 +2302,8 @@ export const commands = {
* with whether a target took the files.
*/
windowDragFiles: (paths: string[]) => typedError<boolean, IdeError>(__TAURI_INVOKE("window_drag_files", { paths })),
/** Releases the interactive prompt turn held by this window. */
windowEndPrompt: () => __TAURI_INVOKE<void>("window_end_prompt"),
/**
* Flash (`true`) or stop flashing (`false`) this window's taskbar button, like IDEA when a
* breakpoint is hit while the window is in the background (macOS bounces the dock icon,
@@ -2371,6 +2383,11 @@ export const commands = {
* `background` (`#rrggbb`) paints a new window until its page has loaded.
*/
windowOpenSettings: (page: string | null, newProjects: boolean, background: string | null) => typedError<null, IdeError>(__TAURI_INVOKE("window_open_settings", { page, newProjects, background })),
/**
* Signals that this window passed its close checks and waits for peers closing in the same
* batch/tab group so they hide together in one frame. Returns `false` if the batch was cancelled.
*/
windowReadyToClose: () => __TAURI_INVOKE<boolean>("window_ready_to_close"),
/** Appearance › Smooth scrolling for this window's web view (Linux only) */
windowSetSmoothScrolling: (enabled: boolean) => typedError<null, IdeError>(__TAURI_INVOKE("window_set_smooth_scrolling", { enabled })),
/** Height of the web title bar in native logical pixels (CSS height × IDE zoom). */
@@ -3022,8 +3039,6 @@ export type AgentSettings_Deserialize = {
showUsageLimits?: boolean,
/** What the session has cost so far, as the agent reports it. */
showCost?: boolean,
/** A finished turn's work folds into one line under its message, leaving the reply. */
foldTurns?: boolean,
/** Streaming text is revealed at a steady pace rather than chunk by chunk. */
smoothText?: boolean,
/** Conversations and the composer expand to the full width of the pane instead of staying in a centred column. */
@@ -3067,8 +3082,6 @@ export type AgentSettings_Serialize = {
showUsageLimits: boolean,
/** What the session has cost so far, as the agent reports it. */
showCost: boolean,
/** A finished turn's work folds into one line under its message, leaving the reply. */
foldTurns: boolean,
/** Streaming text is revealed at a steady pace rather than chunk by chunk. */
smoothText: boolean,
/** Conversations and the composer expand to the full width of the pane instead of staying in a centred column. */
@@ -3909,6 +3922,24 @@ export type Browser = {
name: string,
};
export type BrowserAction = { type: "navigate"; url: string } | { type: "back" } | { type: "forward" } | { type: "reload" } | { type: "inspect" } | { type: "cancel" } | { type: "layout"; bounds: BrowserBounds | null } | { type: "status" };
/** Physical pixels measured from the top left of the workbench webview. */
export type BrowserBounds = {
x: number,
y: number,
width: number,
height: number,
};
export type BrowserStatus = {
url: string,
canBack: boolean,
canForward: boolean,
inspecting: boolean,
element: InspectedElement | null,
};
export type BuildEvent =
/** The build starts: its tree root. */
{ kind: "started"; system: BuildSystem; title: string } |
@@ -4245,6 +4276,10 @@ export type CloseContext = {
quitting: boolean,
/** Number of open project windows (settings windows excluded), including the caller. */
windows: number,
/** Whether this window currently has auxiliary document windows that must settle first. */
hasDocumentWindows: boolean,
/** Whether this close runs alongside other windows or on a background tab (prompts serialize and raise). */
batch: boolean,
};
export type CodeAction = {
@@ -8510,6 +8545,12 @@ export type InspectSummary = {
elapsedMs: number,
};
export type InspectedElement = {
selector: string,
html: string,
styles: string,
};
export type InspectedFile = {
path: IpcPath,
relPath: string,
+3 -1
Переглянути файл
@@ -5,6 +5,7 @@
*/
import { HighlightStyle, type TagStyle } from "@codemirror/language";
import { Tag, tags as t } from "@lezer/highlight";
import { inlineTokenBackground } from "./inlineBg";
/** Log warnings: the UI warning colour, since no syntax token reads as one in every scheme. */
export const logWarning = Tag.define("logWarning");
@@ -28,7 +29,8 @@ function token(
color: defaults.color ? variable("", "inherit") : `var(--syn-${name})`,
fontStyle: variable("-italic", defaults.italic ?? "inherit"),
fontWeight: variable("-bold", defaults.bold ?? "inherit"),
backgroundColor: variable("-bg", "transparent"),
"--openidea-token-bg": variable("-bg", "initial"),
...inlineTokenBackground,
textDecoration: variable("-effect", defaults.effect ?? "none"),
// WebKit takes a decoration with a style or colour only through the prefixed property.
WebkitTextDecoration: variable("-effect", defaults.effect ?? "none"),
+9 -5
Переглянути файл
@@ -1,22 +1,26 @@
/**
* Paints an inline mark's background capped at `1lh` so a font taller than the line height
* does not bleed into the rows above and below. When the inline box is shorter than `1lh`,
* its own border box clips the gradient. Safari before 16.4 has no `lh` and drops the
* shorthand, keeping the plain colour before it.
* its own border box clips the gradient. Keep the size separate so Safari before 16.4
* ignores only the unsupported `lh` and still paints the fill.
*/
export function inlineBackground(color: string) {
return {
backgroundColor: color,
background: `linear-gradient(${color}, ${color}) center / 100% 1lh no-repeat`,
background: `linear-gradient(${color}, ${color}) center no-repeat`,
backgroundSize: "100% 1lh",
WebkitBoxDecorationBreak: "clone",
boxDecorationBreak: "clone",
};
}
// Semantic roles can override this colour on nested syntax tokens without repainting
// unrelated descendants (e.g. a selection). An unset colour produces no background image.
export const inlineTokenBackground = inlineBackground("var(--openidea-token-bg)");
/** Fallback style for an inline mark with a 1px frame (`inlineFramedModern` caps it at `1lh`). */
export function inlineFramedFallback(fill: string, frame: string) {
return {
backgroundColor: fill,
background: fill,
outline: `1px solid ${frame}`,
outlineOffset: "-1px",
WebkitBoxDecorationBreak: "clone",
+3 -3
Переглянути файл
@@ -58,13 +58,13 @@ describe("selectionMarks", () => {
it("caps inline highlight backgrounds and 1px frames at 1lh with pre-16.4 fallbacks", () => {
expect(inlineBackground("var(--editor-search)")).toEqual({
backgroundColor: "var(--editor-search)",
background: "linear-gradient(var(--editor-search), var(--editor-search)) center / 100% 1lh no-repeat",
background: "linear-gradient(var(--editor-search), var(--editor-search)) center no-repeat",
backgroundSize: "100% 1lh",
WebkitBoxDecorationBreak: "clone",
boxDecorationBreak: "clone",
});
expect(inlineFramedFallback("var(--fill)", "var(--frame)")).toMatchObject({
backgroundColor: "var(--fill)",
background: "var(--fill)",
outline: "1px solid var(--frame)",
outlineOffset: "-1px",
});
+19 -7
Переглянути файл
@@ -1,6 +1,11 @@
/** Editor-side styling for LSP features (CodeMirror theme; tokens only). */
import { EditorView } from "@codemirror/view";
import { inlineBackground, inlineFramedFallback, inlineFramedModern } from "@/editor/core/cm/inlineBg";
import {
inlineBackground,
inlineFramedFallback,
inlineFramedModern,
inlineTokenBackground,
} from "@/editor/core/cm/inlineBg";
import { RAINBOW_COLORS } from "./semantic";
const tooltipSurface = {
@@ -84,17 +89,21 @@ const markdown = {
".tok-invalid": { color: "var(--syn-invalid)" },
};
function semanticStyle(token: string, fallback: string) {
function semanticAttributes(token: string, fallback: string) {
return {
color: `var(--syn-${token}, var(--syn-${fallback}))`,
fontWeight: `var(--syn-${token}-bold, inherit)`,
fontStyle: `var(--syn-${token}-italic, inherit)`,
backgroundColor: `var(--syn-${token}-bg, transparent)`,
"--openidea-token-bg": `var(--syn-${token}-bg, initial)`,
textDecoration: `var(--syn-${token}-effect, none)`,
WebkitTextDecoration: `var(--syn-${token}-effect, none)`,
};
}
function semanticStyle(token: string, fallback: string) {
return { ...semanticAttributes(token, fallback), ...inlineTokenBackground };
}
/** A token that shows `parent`'s colour and style while its own are unset (an `inherit` attribute). */
function inheritedStyle(token: string, parent: string) {
const v = (suffix: string, fallback: string) =>
@@ -103,7 +112,8 @@ function inheritedStyle(token: string, parent: string) {
color: v("", "inherit"),
fontWeight: v("-bold", "inherit"),
fontStyle: v("-italic", "inherit"),
backgroundColor: v("-bg", "transparent"),
"--openidea-token-bg": v("-bg", "initial"),
...inlineTokenBackground,
textDecoration: v("-effect", "none"),
WebkitTextDecoration: v("-effect", "none"),
};
@@ -117,7 +127,8 @@ function fallbackStyle(token: string, parents: string[]) {
color: v("", "inherit"),
fontWeight: v("-bold", "inherit"),
fontStyle: v("-italic", "inherit"),
backgroundColor: v("-bg", "transparent"),
"--openidea-token-bg": v("-bg", "initial"),
...inlineTokenBackground,
textDecoration: v("-effect", "none"),
WebkitTextDecoration: v("-effect", "none"),
};
@@ -575,7 +586,8 @@ export const lspTheme = EditorView.theme({
".cm-sem-python-nested": semanticStyle("python-nested-function", "function"),
".cm-sem-python-predefined-definition": semanticStyle("python-predefined-definition", "predefined"),
".cm-sem-python-predefined-usage": semanticStyle("python-predefined-usage", "predefined"),
".cm-sem-python-docstring, .cm-sem-python-docstring *": semanticStyle("docstring", "string"),
".cm-sem-python-docstring": inlineTokenBackground,
".cm-sem-python-docstring, .cm-sem-python-docstring *": semanticAttributes("docstring", "string"),
// After the docstring wildcard above so the tag's own colour wins inside it.
".cm-sem-python-docstring-tag": {
...semanticStyle("python-docstring-tag", "doc-comment-tag"),
@@ -645,7 +657,7 @@ export const lspTheme = EditorView.theme({
color: "var(--syn-static-property, var(--syn-property))",
fontStyle: "var(--syn-static-property-italic, var(--syn-static-italic, italic))",
fontWeight: "var(--syn-static-property-bold, var(--syn-property-bold, inherit))",
backgroundColor: "var(--syn-static-property-bg, transparent)",
"--openidea-token-bg": "var(--syn-static-property-bg, initial)",
textDecoration: "var(--syn-static-property-effect, none)",
WebkitTextDecoration: "var(--syn-static-property-effect, none)",
},
+13 -22
Переглянути файл
@@ -375,8 +375,7 @@
.shownElsewhere {
display: none;
}
.processBody,
.turnBody {
.processBody {
padding-left: var(--space-2);
}
.processBody > .thoughtEntry ~ .toolEntry {
@@ -1818,26 +1817,6 @@
mask-image: linear-gradient(to bottom, transparent, black 40%);
}
/* A finished turn's work, folded under its message. */
.turnFold > summary {
cursor: default;
list-style: none;
}
.turnFold > summary::-webkit-details-marker {
display: none;
}
.turnFold[open] .processChevron {
transform: rotate(90deg);
}
.turnBody {
display: flex;
flex-direction: column;
gap: var(--space-2);
margin: 2px 0 0 10px;
padding-left: var(--space-3);
border-left: 1px solid var(--border);
}
/* Above the composer: what waits for the user, the plan and changes, what runs now. */
.tray {
display: flex;
@@ -1916,6 +1895,18 @@
flex: none;
color: var(--fg-muted);
}
.toolDir {
flex: none;
max-width: 140px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
padding: 0 4px;
border-radius: var(--radius-small);
background: var(--bg-hover);
color: var(--fg-muted);
font-size: var(--agent-fs-small, var(--fs-small));
}
.toolPath {
flex: none;
max-width: 180px;
-1
Переглянути файл
@@ -10,7 +10,6 @@ export const AGENT_SETTINGS_DEFAULTS: ResolvedAgentSettings = {
showWorkTime: true,
showUsageLimits: true,
showCost: false,
foldTurns: false,
smoothText: true,
fitWindowWidth: false,
thinking: "auto",
+17
Переглянути файл
@@ -43,6 +43,7 @@ import {
entriesKey,
findSubagent,
groupTasks,
providerIcon,
subagentTitle,
turnNumbers,
upsertEntry,
@@ -82,6 +83,22 @@ const option = (category: string, values: string[], current: string | null): Age
via: "option",
});
describe("providerIcon", () => {
it("uses the agent's logo, shared by its legacy and adapter ids", () => {
expect(providerIcon("devin")).toBe("agent-devin");
expect(providerIcon("amp-acp")).toBe("agent-amp-acp");
expect(providerIcon("claude-acp")).toBe("agent-claude");
expect(providerIcon("codex-acp")).toBe("agent-codex");
expect(providerIcon("kimi-code")).toBe("agent-kimi");
expect(providerIcon("opencode-v2")).toBe("agent-opencode");
expect(providerIcon("hermes-work")).toBe("agent-hermes");
});
it("falls back to the generic agents icon", () => {
expect(providerIcon("my-agent")).toBe("toolwindow-agents");
});
});
describe("fenced blocks", () => {
it("finds closed blocks, a longer fence holding backticks", () => {
const text = fenced("a ``` b\n```", "terminal zsh");
+3
Переглянути файл
@@ -17,6 +17,7 @@ import {
maybeEditorService,
registerAgentContextSource,
registerEditorDropHandler,
provideAgentDraftAppender,
registerEditorKind,
registerMenuGroup,
registerMenuSlotItem,
@@ -44,6 +45,7 @@ import { focusedSession, inputSession } from "./sessionFocus";
import { cycleFocusedEffort } from "./effortFocus";
import { clearAgentTabFontZoom } from "./fontZoom";
import {
appendContextBlock,
closeActiveTask,
closeAndNewTask,
connect,
@@ -125,6 +127,7 @@ export function activate(): () => void {
else if (s.settings?.agents?.newTaskApprovals !== prev.settings?.agents?.newTaskApprovals && s.project?.root)
void refreshProviders();
}),
provideAgentDraftAppender(appendContextBlock),
registerToolWindow({
id: TOOL_WINDOW,
title: "Agents",
+11 -22
Переглянути файл
@@ -1,5 +1,6 @@
/** Pure helpers: task grouping, entry updates, labels. */
import type { AgentEntry, AgentStatus, AgentSubagentStatus, AgentTask } from "@/bindings";
import { isIconName } from "@/ui/icons";
export const SESSION_KIND = "agent-session";
export const HOME_KIND = "agent-home";
@@ -52,26 +53,6 @@ export function subagentStatusLabel(s: AgentSubagentStatus): string {
}
}
const PROVIDER_ICONS = new Set([
"claude",
"codex",
"gemini",
"copilot",
"cursor",
"opencode",
"qwen",
"qoder",
"qodercn",
"kimi",
"goose",
"auggie",
"kiro",
"vibe",
"omp",
"deepseek-harness",
"hermes",
]);
/** Suggests an agent-file id for a display name (`"My Agent!"` → `"my-agent"`). */
export function slugifyId(name: string): string {
return name
@@ -83,10 +64,18 @@ export function slugifyId(name: string): string {
/** The agent a Hermes profile runs as: `hermes` for `default`, else `hermes-<slug>` (`hermes -p <name> acp`). */
export const hermesAgentId = (profile: string) => (profile === "default" ? "hermes" : `hermes-${slugifyId(profile)}`);
/** Providers whose logo is another provider's: legacy and ACP-adapter ids of the same agent. */
const ICON_ALIASES: Record<string, string> = {
"claude-acp": "claude",
"codex-acp": "codex",
"kimi-code": "kimi",
"opencode-v2": "opencode",
};
/** The agent's logo; custom agents get the generic agents icon, Hermes profiles Hermes'. */
export function providerIcon(provider: string): string {
if (PROVIDER_ICONS.has(provider)) return `agent-${provider}`;
return provider.startsWith("hermes-") ? "agent-hermes" : "toolwindow-agents";
const id = ICON_ALIASES[provider] ?? (provider.startsWith("hermes-") ? "hermes" : provider);
return isIconName(`agent-${id}`) ? `agent-${id}` : "toolwindow-agents";
}
export interface TaskGroup {
+7 -65
Переглянути файл
@@ -2,25 +2,15 @@ import type { AgentTask } from "@/bindings";
import { useTx } from "@/platform/i18n";
import { Icon } from "@/ui";
import clsx from "clsx";
import { createContext, memo, useContext, type ReactNode } from "react";
import { formatDuration } from "../conversation";
import { memo } from "react";
import styles from "../Session.module.css";
import { summarizeWork, workParts, type WorkSummary } from "../timeline";
import {
liveTool,
rowEntries,
sameRow,
type ConversationRow,
type IndexedEntry,
type ProcessRow,
type ToolEntryData,
type TurnRow,
} from "./conversationRows";
import { liveTool, sameRow, type IndexedEntry, type ProcessRow, type ToolEntryData } from "./conversationRows";
import { Fold } from "./Folds";
import { samePropsExcept, shortTitle } from "./shared";
import { commandTitle, samePropsExcept, shortTitle } from "./shared";
import { ThoughtEntry, ToolEntry } from "./toolEntries";
/** "Edited 2 files · Read 4 files": what a run of work did; "Reasoning" when it only thought. */
/** "Edited 2 files · Ran 3 commands": what a run of work did; "Reasoning" when it only thought. */
function workSummaryText(work: WorkSummary, tx: ReturnType<typeof useTx>, toolCalls: number): string[] {
const parts = workParts(work).map((p) => tx(p.text).replace("{count}", String(p.count)));
if (!parts.length && toolCalls) parts.push(`${toolCalls} ${tx(toolCalls === 1 ? "tool call" : "tool calls")}`);
@@ -28,56 +18,6 @@ function workSummaryText(work: WorkSummary, tx: ReturnType<typeof useTx>, toolCa
return parts;
}
/** Renders the rows inside an open turn; the stream owns what a row needs (`Stream`). */
export const RowRenderer = createContext<(row: ConversationRow) => ReactNode>(() => null);
/** A finished turn's work, opened: its rows, painted only while the turn is open. */
function TurnBody({ row }: { row: TurnRow }) {
const renderRow = useContext(RowRenderer);
return (
<div className={styles.turnBody}>
{row.rows.map((inner) => (
<div key={inner.index} className={styles.conversationRow}>
{renderRow(inner)}
</div>
))}
</div>
);
}
/** A finished turn's work, folded under its message: one line saying what it did and for how long. */
export const TurnFold = memo(
function TurnFold({ row }: { row: TurnRow }) {
const tx = useTx();
const { turn } = row;
const entries = row.rows.flatMap(rowEntries);
const work = summarizeWork(entries);
const parts = workSummaryText(work, tx, 0);
const messages = entries.filter((e) => e.type === "agent").length;
if (messages)
parts.push(tx(messages === 1 ? "1 message" : "{count} messages").replace("{count}", String(messages)));
const took = turn.sentMs != null && turn.doneMs != null ? formatDuration(turn.doneMs - turn.sentMs) : null;
return (
<Fold
id={`turn:${turn.user}`}
className={clsx(styles.turnFold, styles.process)}
summary={
<summary className={styles.processSummary}>
<Icon name="chevron-right" size={12} className={styles.processChevron} />
<span className={styles.processParts}>{parts.join(" · ")}</span>
{work.added > 0 && <span className={styles.added}>+{work.added}</span>}
{work.removed > 0 && <span className={styles.removed}>−{work.removed}</span>}
{took && <span className={styles.muted}>{took}</span>}
</summary>
}
>
<TurnBody row={row} />
</Fold>
);
},
(a, b) => sameRow(a.row, b.row),
);
interface ProcessRunProps {
row: ProcessRow;
task: AgentTask;
@@ -124,7 +64,9 @@ export const ProcessRun = memo(function ProcessRun({
const live = [...tools].reverse().find(({ entry }) => liveTool(entry))?.entry;
const last = row.entries.at(-1)!.entry;
const current = live
? shortTitle(task, live.title || live.kind)
? live.kind === "execute"
? commandTitle(task, live.title || live.kind).title
: shortTitle(task, live.title || live.kind)
: working && last.type === "thought"
? tx("Thinking")
: null;
+9 -20
Переглянути файл
@@ -42,18 +42,12 @@ import {
import { selectionIn } from "../selection";
import styles from "../Session.module.css";
import { useAgents } from "../store";
import { foldedTurns, thoughtDurations } from "../timeline";
import {
conversationRows,
foldTurnRows,
isProcessEntry,
type ConversationRow,
type EntryRow,
} from "./conversationRows";
import { thoughtDurations } from "../timeline";
import { conversationRows, isProcessEntry, rowEntries, type ConversationRow, type EntryRow } from "./conversationRows";
import { FindBar } from "./FindBar";
import { KeepFoldHeader, OpenFolds } from "./Folds";
import { Entry } from "./messages";
import { ProcessRun, RowRenderer, TurnFold } from "./ProcessRows";
import { ProcessRun } from "./ProcessRows";
import { type QuestionAnswer } from "./QuestionForm";
import { providerName } from "./shared";
import { WorkingRow } from "./WorkingRow";
@@ -163,9 +157,7 @@ function useOffscreenRows(
/** Images remain visible beside the work's folded summary, without duplicating them when it opens. */
function toolImages(row: ConversationRow): AgentImage[] {
if (row.kind === "turn") return row.rows.flatMap(toolImages);
const entries = row.kind === "process" ? row.entries.map(({ entry }) => entry) : [row.entry];
return entries.flatMap((entry) => (entry.type === "tool" ? (entry.images ?? []) : []));
return rowEntries(row).flatMap((entry) => (entry.type === "tool" ? (entry.images ?? []) : []));
}
interface StreamProps {
@@ -351,7 +343,7 @@ export function Stream({
}, HIDDEN_TRIM_MS);
return () => window.clearTimeout(timer);
}, [visible]);
const { foldTurns, toolCalls, fitWindowWidth } = useAgentSettings();
const { toolCalls, fitWindowWidth } = useAgentSettings();
useOffscreenRows(ref, visible, !finding, fitWindowWidth, fontZoom);
/**
* Blank space after the conversation that lets a section folded near the end keep its header
@@ -514,9 +506,8 @@ export function Stream({
// Keep the row stable when earlier history is prepended; its author can move with the work.
const rows = useMemo(() => {
if (!entries) return [];
const rows = conversationRows(entries, start, toolCalls === "grouped");
return foldTurns && !finding ? foldTurnRows(rows, foldedTurns(entries, start)) : rows;
}, [entries, start, foldTurns, toolCalls, finding]);
return conversationRows(entries, start, toolCalls === "grouped");
}, [entries, start, toolCalls]);
const authorHeaders = useMemo(() => {
const headers = new Set<number>();
const byAgent = (row: ConversationRow) =>
@@ -551,9 +542,7 @@ export function Stream({
);
const renderConversationRow = useCallback(
(row: ConversationRow): ReactNode =>
row.kind === "turn" ? (
<TurnFold row={row} />
) : row.kind === "process" ? (
row.kind === "process" ? (
<ProcessRun
row={row}
task={task}
@@ -712,7 +701,7 @@ export function Stream({
) : entries.length === 0 && !busy && !loadError ? (
<EmptyState title="No conversation history" />
) : (
<RowRenderer.Provider value={renderConversationRow}>{renderedRows}</RowRenderer.Provider>
renderedRows
)}
<WorkingRow task={task} entries={entries} subagent={subagent} />
</div>
+31 -42
Переглянути файл
@@ -1,7 +1,7 @@
import { describe, expect, it } from "vitest";
import type { AgentEntry } from "@/bindings";
import { foldedTurns } from "../timeline";
import { conversationRows, foldTurnRows, rowEntries, sameRow } from "./conversationRows";
import { summarizeWork } from "../timeline";
import { conversationRows, rowEntries, sameRow } from "./conversationRows";
const user = (text: string): AgentEntry => ({
type: "user",
@@ -23,13 +23,8 @@ const tool = (id: string, kind = "read", added = 0): AgentEntry => ({
diffs: added ? [{ path: `/${id}.ts`, added, removed: 0 }] : [],
});
const rowsOf = (entries: AgentEntry[]) => {
const rows = conversationRows(entries, 0);
return foldTurnRows(rows, foldedTurns(entries, 0));
};
describe("conversationRows", () => {
it("groups consecutive read-only exploration entries and keeps edits and commands separate", () => {
it("groups consecutive reasoning, exploration, edits and commands into one run", () => {
const entries: AgentEntry[] = [
user("a"),
{ type: "thought", text: "inspect" },
@@ -37,54 +32,53 @@ describe("conversationRows", () => {
tool("s1", "search"),
tool("e1", "edit", 3),
tool("cmd1", "execute"),
tool("f1", "fetch"),
tool("r2", "read"),
tool("cmd2", "execute"),
agent("done"),
];
const rows = conversationRows(entries, 0);
expect(rows.map((row) => row.kind)).toEqual(["entry", "process", "entry", "entry", "process", "entry"]);
expect(rows[1]!.kind === "process" ? rows[1]!.entries.length : 0).toBe(3);
expect(rows[4]!.kind === "process" ? rows[4]!.entries.length : 0).toBe(2);
expect(rows.map((row) => row.kind)).toEqual(["entry", "process", "entry"]);
expect(rows[1]!.kind === "process" ? rows[1]!.entries.length : 0).toBe(6);
const work = summarizeWork(rowEntries(rows[1]!));
expect([work.edited, work.run, work.read, work.search]).toEqual([1, 2, 1, 1]);
});
it("flattens grouped runs inside a folded turn to avoid nested folds", () => {
it("keeps direct composer shell commands separate from grouped runs", () => {
const entries: AgentEntry[] = [
user("a"),
tool("r1", "read"),
tool("r2", "search"),
tool("e1", "edit", 2),
tool("shell-1", "execute"),
tool("cmd1", "execute"),
tool("cmd2", "execute"),
agent("done"),
user("b"),
agent("next"),
];
const rows = rowsOf(entries);
const turn = rows[1]!;
expect(turn.kind).toBe("turn");
if (turn.kind === "turn") {
expect(turn.rows.map((r) => r.kind)).toEqual(["entry", "entry", "entry"]);
}
const rows = conversationRows(entries, 0);
expect(rows.map((row) => row.kind)).toEqual(["entry", "entry", "entry", "process", "entry"]);
expect(rows[3]!.kind === "process" ? rows[3]!.entries.map((e) => e.index) : []).toEqual([3, 4]);
});
});
describe("sameRow", () => {
const entries = [user("a"), tool("t1", "edit"), tool("t2", "edit"), agent("done"), user("b"), agent("streaming")];
const entries = [user("a"), tool("t1", "edit"), tool("t2", "execute"), agent("done"), user("b"), agent("streaming")];
it("sees the rows of the same conversation as the same, whichever copy it was built from", () => {
const again = rowsOf(entries);
expect(again.map((row) => row.kind)).toEqual(["entry", "turn", "entry", "entry", "entry"]);
rowsOf(entries).forEach((row, i) => expect(sameRow(row, again[i]!)).toBe(true));
const again = conversationRows(entries, 0);
expect(again.map((row) => row.kind)).toEqual(["entry", "process", "entry", "entry", "entry"]);
conversationRows(entries, 0).forEach((row, i) => expect(sameRow(row, again[i]!)).toBe(true));
});
it("leaves the rows a streamed chunk did not touch the same and the grown one different", () => {
const before = rowsOf(entries);
const after = rowsOf([...entries.slice(0, -1), agent("streaming on")]);
const before = conversationRows(entries, 0);
const after = conversationRows([...entries.slice(0, -1), agent("streaming on")], 0);
expect(after.map((row, i) => sameRow(before[i]!, row))).toEqual([true, true, true, true, false]);
});
it("tells a turn whose work changed from one whose work did not", () => {
const [, turn] = rowsOf(entries);
const [, edited] = rowsOf([entries[0]!, tool("t1", "edit"), tool("t2", "edit", 7), ...entries.slice(3)]);
expect(sameRow(turn!, edited!)).toBe(false);
it("tells a run whose entry changed from one whose entries did not", () => {
const [, run] = conversationRows(entries, 0);
const [, edited] = conversationRows(
[entries[0]!, tool("t1", "edit"), tool("t2", "edit", 7), ...entries.slice(3)],
0,
);
expect(sameRow(run!, edited!)).toBe(false);
});
it("tells a run that gained a call from the run before", () => {
@@ -98,17 +92,12 @@ describe("sameRow", () => {
const shared = agent("same");
expect(sameRow(conversationRows([shared], 0)[0]!, conversationRows([user("x"), shared], 1)[0]!)).toBe(false);
});
it("tells a turn that finished at another time from the turn before", () => {
const later = [{ ...(entries[0] as Extract<AgentEntry, { type: "user" }>), doneMs: 9000 }, ...entries.slice(1)];
expect(sameRow(rowsOf(entries)[1]!, rowsOf(later)[1]!)).toBe(false);
});
});
describe("rowEntries", () => {
it("lists the entries a folded turn paints, work first", () => {
it("lists the entries a process row paints, in order", () => {
const entries = [user("a"), tool("t1"), tool("t2"), agent("done")];
const [, turn] = rowsOf(entries);
expect(rowEntries(turn!)).toEqual([entries[1], entries[2]]);
const [, run] = conversationRows(entries, 0);
expect(rowEntries(run!)).toEqual([entries[1], entries[2]]);
});
});
+8 -50
Переглянути файл
@@ -1,5 +1,4 @@
import type { AgentEntry } from "@/bindings";
import { type FoldedTurn } from "../timeline";
export type ToolEntryData = Extract<AgentEntry, { type: "tool" }>;
@@ -9,30 +8,25 @@ export type IndexedEntry = { index: number; entry: AgentEntry };
/** A row of the conversation: an entry, or a run of reasoning/tool calls folded together. */
export type ConversationRow =
| { kind: "entry"; index: number; entry: AgentEntry }
| { kind: "process"; index: number; entries: IndexedEntry[] }
/** A finished turn's work before its reply, folded into one line under its message. */
| { kind: "turn"; index: number; turn: FoldedTurn; rows: ConversationRow[] };
| { kind: "process"; index: number; entries: IndexedEntry[] };
export type EntryRow = Extract<ConversationRow, { kind: "entry" }>;
export type ProcessRow = Extract<ConversationRow, { kind: "process" }>;
export type TurnRow = Extract<ConversationRow, { kind: "turn" }>;
export const liveTool = (entry: AgentEntry) =>
entry.type === "tool" && (entry.status === "running" || entry.status === "pending");
const EXPLORATION_KINDS = new Set(["read", "search", "fetch", "think"]);
/**
* Reasoning and read-only exploration tool calls fold together, running ones included: the run
* keeps its place while a call finishes, and its summary line says what is running. Edits,
* commands and other side-effecting calls stay visible as their own rows.
* Reasoning and tool calls fold together, running calls included: the run keeps its place while
* a call finishes, and its summary line says what is running. Direct `!` shell commands stay on
* their own row so their output remains open.
*/
export const isProcessEntry = (entry: AgentEntry) =>
entry.type === "thought" || (entry.type === "tool" && EXPLORATION_KINDS.has(entry.kind) && entry.diffs.length === 0);
entry.type === "thought" || (entry.type === "tool" && !entry.id.startsWith("shell-"));
/**
* The conversation's rows from `from`: a run of reasoning and finished tool calls becomes
* one folded row (the work behind a decision), so messages and decisions stay readable.
* The conversation's rows from `from`: a run of reasoning and tool calls becomes one folded row
* (the work behind a decision), so messages and decisions stay readable.
*/
export function conversationRows(entries: readonly AgentEntry[], from: number, group = true): ConversationRow[] {
if (!group) return entries.slice(from).map((entry, i) => ({ kind: "entry", index: from + i, entry }));
@@ -54,35 +48,9 @@ export function conversationRows(entries: readonly AgentEntry[], from: number, g
return rows;
}
/** `rows` with the work of each turn in `turns` (keyed by its message) folded into one row. */
export function foldTurnRows(rows: ConversationRow[], turns: ReadonlyMap<number, FoldedTurn>): ConversationRow[] {
if (!turns.size) return rows;
const out: ConversationRow[] = [];
let open: Extract<ConversationRow, { kind: "turn" }> | null = null;
for (const row of rows) {
if (open && row.index < open.turn.reply) {
if (row.kind === "process") {
for (const item of row.entries) open.rows.push({ kind: "entry", ...item });
} else {
open.rows.push(row);
}
continue;
}
open = null;
out.push(row);
const turn = row.kind === "entry" ? turns.get(row.index) : undefined;
if (turn) {
open = { kind: "turn", index: row.index + 1, turn, rows: [] };
out.push(open);
}
}
return out;
}
/** The entries a row paints, in order. */
export function rowEntries(row: ConversationRow): AgentEntry[] {
if (row.kind === "entry") return [row.entry];
return row.kind === "process" ? row.entries.map(({ entry }) => entry) : row.rows.flatMap(rowEntries);
return row.kind === "process" ? row.entries.map(({ entry }) => entry) : [row.entry];
}
/**
@@ -101,15 +69,5 @@ export function sameRow(a: ConversationRow, b: ConversationRow): boolean {
a.entries.length === b.entries.length &&
a.entries.every(({ entry }, i) => entry === b.entries[i]!.entry)
);
case "turn":
return (
b.kind === "turn" &&
a.turn.user === b.turn.user &&
a.turn.reply === b.turn.reply &&
a.turn.sentMs === b.turn.sentMs &&
a.turn.doneMs === b.turn.doneMs &&
a.rows.length === b.rows.length &&
a.rows.every((row, i) => sameRow(row, b.rows[i]!))
);
}
}
+26
Переглянути файл
@@ -0,0 +1,26 @@
import { describe, expect, it } from "vitest";
import type { AgentTask } from "@/bindings";
import { commandTitle } from "./shared";
const task = { cwd: "/repo/app" } as AgentTask;
describe("commandTitle", () => {
it("drops a cd into the task's own folder", () => {
expect(commandTitle(task, "cd /repo/app && git grep -n foo")).toEqual({ title: "git grep -n foo", dir: null });
expect(commandTitle(task, "cd . ; ls")).toEqual({ title: "ls", dir: null });
});
it("keeps another folder as the place the command ran", () => {
expect(commandTitle(task, "cd /repo/app-icons && pnpm test")).toEqual({
title: "pnpm test",
dir: "/repo/app-icons",
});
expect(commandTitle(task, `cd "/repo/my app/" && ls`)).toEqual({ title: "ls", dir: "/repo/my app" });
});
it("leaves commands without a leading cd, or that are only a cd, as they are", () => {
expect(commandTitle(task, "git status && cd x && ls")).toEqual({ title: "git status && cd x && ls", dir: null });
expect(commandTitle(task, "cd /tmp")).toEqual({ title: "cd /tmp", dir: null });
expect(commandTitle(task, "cat /repo/app/src/a.ts")).toEqual({ title: "cat src/a.ts", dir: null });
});
});
+10
Переглянути файл
@@ -1,5 +1,6 @@
import type { AgentEntry, AgentTask } from "@/bindings";
import { useEffect, useState } from "react";
import { splitLeadingCd } from "../shellCommand";
import { useAgents } from "../store";
export function providerName(id: string) {
@@ -21,6 +22,15 @@ export type UserEntry = Extract<AgentEntry, { type: "user" }>;
/** Agent-written titles with the task's own folder dropped from paths. */
export const shortTitle = (task: AgentTask, title: string) => title.replaceAll(`${task.cwd}/`, "");
/**
* A command's title without the `cd <dir> &&` agents put before every call, and the folder it
* moved to when that is not the task's own: the command is what tells calls apart.
*/
export function commandTitle(task: AgentTask, title: string): { title: string; dir: string | null } {
const { command, dir } = splitLeadingCd(title);
return { title: shortTitle(task, command), dir: dir === task.cwd || dir === "." ? null : dir };
}
/**
* `memo`'s comparison for props rebuilt with every render without changing: a prop named in
* `by` is equal when its rule says so, any other prop when it is the same value.
+11 -2
Переглянути файл
@@ -16,7 +16,7 @@ import { cancelTask } from "../store";
import { openChangeDiff } from "./ChangesTab";
import { Fold } from "./Folds";
import { liveTool } from "./conversationRows";
import { shortTitle, useNow } from "./shared";
import { commandTitle, shortTitle, useNow } from "./shared";
/** A location as the agent reported it: absolute on any platform, or relative to the task's folder. */
const isAbsolute = (path: string) => path.startsWith("/") || /^[A-Za-z]:[\\/]/.test(path) || path.startsWith("\\\\");
@@ -104,13 +104,22 @@ export const ToolEntry = memo(function ToolEntry({
const live = liveTool(entry);
const took = toolDuration(entry);
const run = entry.kind === "execute" ? toolRun(entry) : null;
const title = shortTitle(task, entry.title || entry.kind);
// Commands lose the `cd <dir> &&` agents start them with; another folder shows as a tag.
const { title, dir } =
entry.kind === "execute"
? commandTitle(task, entry.title || entry.kind)
: { title: shortTitle(task, entry.title || entry.kind), dir: null };
// A title that already names the file ("Read pom.xml") needs no second link to it.
const links =
entry.kind === "execute" ? [] : entry.locations.slice(0, 3).filter((path) => !title.includes(basename(path)));
const head = (
<>
<Icon name={TOOL_ICONS[entry.kind] ?? "run"} size={14} className={styles.toolKindIcon} />
{dir && (
<span className={styles.toolDir} title={dir}>
{basename(dir)}
</span>
)}
<span className={styles.toolTitle} title={entry.title || entry.kind}>
{title}
</span>
+18 -71
Переглянути файл
@@ -299,9 +299,6 @@ beforeEach(() => {
describe("conversation rows", () => {
it("keeps authors above messages and their folded work with matching icon-only actions", async () => {
useProject.setState({
settings: { agents: { foldTurns: false } } as never,
});
const user = (text: string): AgentEntry => ({
type: "user",
text,
@@ -396,9 +393,6 @@ describe("conversation rows", () => {
);
it("puts the time and hover actions under a turn's final reply only", async () => {
useProject.setState({
settings: { agents: { foldTurns: false } } as never,
});
backend.entries.set("A", [
{
type: "user",
@@ -468,13 +462,8 @@ describe("process folding", () => {
});
describe("tool result images", () => {
it.each([
["grouped", true],
["grouped", false],
["each", true],
["each", false],
] as const)("keeps tool images visible with %s tools and folded turns=%s", async (toolCalls, foldTurns) => {
useProject.setState({ settings: { agents: { toolCalls, foldTurns } } as never });
it.each(["grouped", "each"] as const)("keeps tool images visible with %s tools", async (toolCalls) => {
useProject.setState({ settings: { agents: { toolCalls } } as never });
const image = { mimeType: "image/png", data: "aW1hZ2U=", name: null };
backend.entries.set("A", [
{ type: "user", text: "Render a preview", attachments: [], steered: false, sentMs: 1000, doneMs: 2000 },
@@ -488,7 +477,7 @@ describe("tool result images", () => {
useAgents.setState({ entries: new Map(backend.entries) });
render(<SessionEditor input={input("A")} />);
await screen.findByText("Here is the result.");
expect(!!stream().querySelector(`.${styles.turnFold}`)).toBe(foldTurns);
expect(!!stream().querySelector(`.${styles.processRun}`)).toBe(toolCalls === "grouped");
const preview = screen.getByRole("img", { name: "Image" });
expect(preview).toHaveAttribute("src", "data:image/png;base64,aW1hZ2U=");
expect(preview.closest("details")).toBeNull();
@@ -501,8 +490,8 @@ describe("tool result images", () => {
});
});
describe("turn folding", () => {
it("keeps a finished turn's interim text and tools visible by default", async () => {
describe("turn layout", () => {
it("keeps interim text visible while folding tool runs between messages", async () => {
backend.entries.set("A", [
{
type: "user",
@@ -516,61 +505,18 @@ describe("turn folding", () => {
tool("one"),
{ type: "agent", text: "Interim note" },
tool("two", { kind: "execute" }),
tool("three", { kind: "execute" }),
{ type: "agent", text: "Final reply" },
]);
useAgents.setState({ entries: new Map(backend.entries) });
render(<SessionEditor input={input("A")} />);
expect(await screen.findByText("Interim note")).toBeInTheDocument();
expect(screen.getByText("two")).toBeInTheDocument();
expect(screen.getByText("Read 1 file")).toBeInTheDocument();
expect(screen.getByText("Ran 2 commands")).toBeInTheDocument();
expect(screen.getByText("Final reply")).toBeInTheDocument();
expect(stream().querySelector(`.${styles.turnFold}`)).toBeNull();
});
it("folds earlier turns when foldTurns is enabled, keeping the latest turn open and flattening runs inside", async () => {
useProject.setState({ settings: { agents: { foldTurns: true } } as never });
backend.entries.set("A", [
{
type: "user",
text: "Question",
attachments: [],
steered: false,
sentMs: 1000,
doneMs: 13000,
},
{ type: "thought", text: "think" },
tool("one"),
{ type: "agent", text: "Interim note" },
tool("two", { kind: "execute" }),
{ type: "agent", text: "Final reply" },
{
type: "user",
text: "Follow up",
attachments: [],
steered: false,
sentMs: 14000,
doneMs: 15000,
},
tool("latest", { kind: "execute" }),
{ type: "agent", text: "Latest reply" },
]);
useAgents.setState({ entries: new Map(backend.entries) });
render(<SessionEditor input={input("A")} />);
await screen.findByText("Latest reply");
expect(screen.getByText("latest")).toBeInTheDocument();
const summary = screen.getByText("Ran 1 command · Read 1 file · 1 message");
const fold = summary.closest("details")!;
expect(fold).toHaveClass(styles.turnFold!);
expect(fold).toHaveTextContent("12s");
expect(screen.queryByText("Interim note")).toBeNull();
fold.open = true;
fireEvent(fold, new Event("toggle"));
expect(await screen.findByText("Interim note")).toBeInTheDocument();
expect(screen.getByText("one")).toBeInTheDocument();
expect(fold.querySelector(`.${styles.processRun}`)).toBeNull();
});
it("leaves the turn the agent works on open", async () => {
useProject.setState({ settings: { agents: { foldTurns: true } } as never });
it("shows the working indicator after the latest output while a turn runs", async () => {
backend.entries.set("A", [
{
type: "user",
@@ -592,7 +538,6 @@ describe("turn folding", () => {
});
render(<SessionEditor input={input("A")} />);
expect(await screen.findByText("Interim note")).toBeInTheDocument();
expect(stream().querySelector(`.${styles.turnFold}`)).toBeNull();
// The turn isn't over: its latest message is no final reply yet.
expect(stream().querySelector(`.${styles.agentMessage} > .${styles.messageFooter}`)).toBeNull();
// What the agent is doing ends the conversation, below its latest output.
@@ -1295,7 +1240,7 @@ describe("tool calls", () => {
expect(screen.queryByText("Reading files…")).toBeNull();
});
it("folds consecutive exploration calls into one collapsed row while keeping edits visible", async () => {
it("folds consecutive exploration, edits and commands into one collapsed row", async () => {
const edit = (id: string) =>
tool(id, {
kind: "edit",
@@ -1306,16 +1251,18 @@ describe("tool calls", () => {
tool("s1", { kind: "search" }),
edit("one"),
edit("two"),
tool("cmd", { kind: "execute", title: "pnpm test" }),
{ type: "agent", text: "Answer A" },
]);
useAgents.setState({ entries: new Map(backend.entries) });
render(<SessionEditor input={input("A")} />);
const summary = await screen.findByText("Read 1 file · Searched once");
expect(summary.closest("details")!.open).toBe(false);
expect(screen.getByText("one")).toBeInTheDocument();
expect(screen.getByText("two")).toBeInTheDocument();
expect(screen.getAllByText("+2")).toHaveLength(2);
expect(screen.getAllByText("−1")).toHaveLength(2);
const summary = await screen.findByText("Edited 1 file · Ran 1 command · Read 1 file · Searched once");
const fold = summary.closest("details")!;
expect(fold).toHaveClass(styles.processRun!);
expect(fold.open).toBe(false);
expect(fold).toHaveTextContent("+4");
expect(fold).toHaveTextContent("−2");
expect(screen.queryByText("pnpm test")).toBeNull();
});
});
+10
Переглянути файл
@@ -0,0 +1,10 @@
import { describe, expect, it } from "vitest";
import { splitLeadingCd } from "./shellCommand";
describe("splitLeadingCd", () => {
it("takes the folder off the front", () => {
expect(splitLeadingCd("cd /repo && git status")).toEqual({ command: "git status", dir: "/repo" });
expect(splitLeadingCd(`cd "/my repo/" ; ls`)).toEqual({ command: "ls", dir: "/my repo" });
expect(splitLeadingCd("cd /tmp")).toEqual({ command: "cd /tmp", dir: null });
});
});
+12
Переглянути файл
@@ -0,0 +1,12 @@
/** Reading what an agent's shell command does, from its text alone. */
/** A leading `cd <dir> &&` (or `;`), with the directory quoted or bare. */
const LEADING_CD = /^\s*cd\s+("[^"]+"|'[^']+'|\S+)\s*(?:&&|;)\s*/;
/** `command` without the `cd <dir> &&` agents put before it, and that folder; `null` when there is none. */
export function splitLeadingCd(command: string): { command: string; dir: string | null } {
const match = LEADING_CD.exec(command);
if (!match || match[0].length === command.length) return { command, dir: null };
const dir = match[1]!.replace(/^(["'])(.*)\1$/, "$2").replace(/\/+$/, "");
return { command: command.slice(match[0].length), dir };
}
+13
Переглянути файл
@@ -42,6 +42,7 @@ import {
cursorModelDefaults,
emptyDraft,
hasMention,
fenced,
isMentioned,
isPerModelOption,
mentionOf,
@@ -1694,6 +1695,18 @@ export async function setTaskSkillOverrides(task: string, overrides: Record<stri
}));
}
/** Attach a reviewed block without submitting, changing providers, or replacing draft attachments. */
export function appendContextBlock({ text, info }: { text: string; info: string }) {
const selected = activeComposerKey();
const task = useAgents.getState().tasks.get(selected);
const key = task && task.status !== "archived" ? task.id : HOME;
const existing = composerDraft(key).text;
const block = fenced(text, info);
updateComposer(key, { text: existing ? `${existing}\n\n${block}` : block });
if (key === HOME) openHome();
else openTask(key);
}
/** The composer the user is looking at: the Agents surface on show, else the one typed in last. */
function activeComposerKey(): string {
const s = useAgents.getState();
+41 -51
Переглянути файл
@@ -204,16 +204,11 @@ afterEach(() => {
});
describe("streaming into a long conversation", () => {
it.each([
{ turns: 5, foldTurns: true },
{ turns: 40, foldTurns: true },
{ turns: 5, foldTurns: false },
{ turns: 40, foldTurns: false },
])(
"renders none of the $turns earlier turns again for a chunk (fold turns: $foldTurns)",
async ({ turns, foldTurns }) => {
it.each([{ turns: 5 }, { turns: 40 }])(
"renders none of the $turns earlier turns again for a chunk",
async ({ turns }) => {
useProject.setState({
settings: { agents: { smoothText: false, foldTurns } } as never,
settings: { agents: { smoothText: false } } as never,
});
const { stream } = await openStreaming(turns);
// The first chunk opens the streaming message; what follows is the steady state.
@@ -236,7 +231,7 @@ describe("streaming into a long conversation", () => {
);
it("still shows what a new turn changes in the turns above it", async () => {
useProject.setState({ settings: { agents: { smoothText: false, foldTurns: true } } as never });
useProject.setState({ settings: { agents: { smoothText: false } } as never });
const { stream, at } = await openStreaming(3);
stream(3);
send({
@@ -263,56 +258,51 @@ describe("streaming into a long conversation", () => {
entry: { type: "agent", text: "Final answer" },
});
const copies = () => screen.getAllByRole("button", { name: "Copy Markdown" }).length;
// The turn in progress has no actions yet; the three before it do, and its work is open.
// The turn in progress has no actions yet; the three before it do.
expect(copies()).toBe(3);
expect(harness.folds.has(`turn:${at - 1}`)).toBe(false);
send({ type: "entry", task: task.id, subagent: null, index: at + 3, entry: user("Next?") });
// The turn that began mid-stream has ended: its reply has actions and its work is folded.
// The turn that began mid-stream has ended: its reply has actions.
expect(copies()).toBe(4);
expect(harness.folds.has(`turn:${at - 1}`)).toBe(true);
expect(screen.getByText("Final answer")).toBeInTheDocument();
expect(screen.getByText("Next?")).toBeInTheDocument();
});
it.each([{ foldTurns: true }, { foldTurns: false }])(
"still shows an earlier edit that arrives while a reply streams (fold turns: $foldTurns)",
async ({ foldTurns }) => {
useProject.setState({ settings: { agents: { smoothText: false, foldTurns } } as never });
const { stream } = await openStreaming(3);
stream(3);
const added = () => within(document.body).queryAllByText("+7").length;
expect(added()).toBe(0);
it("still shows an earlier edit that arrives while a reply streams", async () => {
useProject.setState({ settings: { agents: { smoothText: false } } as never });
const { stream } = await openStreaming(3);
stream(3);
const added = () => within(document.body).queryAllByText("+7").length;
expect(added()).toBe(0);
// Turn 1's edit (index 8) is rewritten, and so is the reply of turn 2 (index 14).
send({
type: "entry",
task: task.id,
subagent: null,
index: 8,
entry: {
type: "tool",
id: "edit-1",
title: "Edit src/file1.ts",
kind: "edit",
status: "completed",
locations: [],
output: null,
diffs: [{ path: "/project/src/file1.ts", added: 7, removed: 1 }],
},
});
send({
type: "entry",
task: task.id,
subagent: null,
index: 14,
entry: { type: "agent", text: "Reply 2, revised" },
});
// Turn 1's edit (index 8) is rewritten, and so is the reply of turn 2 (index 14).
send({
type: "entry",
task: task.id,
subagent: null,
index: 8,
entry: {
type: "tool",
id: "edit-1",
title: "Edit src/file1.ts",
kind: "edit",
status: "completed",
locations: [],
output: null,
diffs: [{ path: "/project/src/file1.ts", added: 7, removed: 1 }],
},
});
send({
type: "entry",
task: task.id,
subagent: null,
index: 14,
entry: { type: "agent", text: "Reply 2, revised" },
});
expect(await screen.findByText("Reply 2, revised")).toBeInTheDocument();
expect(added()).toBe(1);
expect(screen.getByText("Reply 1")).toBeInTheDocument();
},
);
expect(await screen.findByText("Reply 2, revised")).toBeInTheDocument();
expect(added()).toBe(1);
expect(screen.getByText("Reply 1")).toBeInTheDocument();
});
});
+5 -29
Переглянути файл
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
import type { AgentEntry } from "@/bindings";
import { foldedTurns, summarizeWork, thoughtDurations, toolDuration, toolRun, workParts } from "./timeline";
import { summarizeWork, thoughtDurations, toolDuration, toolRun, workParts } from "./timeline";
const user = (text: string, extra: Partial<Extract<AgentEntry, { type: "user" }>> = {}): AgentEntry => ({
type: "user",
@@ -10,7 +10,6 @@ const user = (text: string, extra: Partial<Extract<AgentEntry, { type: "user" }>
doneMs: 5000,
...extra,
});
const agent = (text: string): AgentEntry => ({ type: "agent", text });
const tool = (kind: string, extra: Partial<Extract<AgentEntry, { type: "tool" }>> = {}): AgentEntry => ({
type: "tool",
id: kind,
@@ -33,13 +32,14 @@ describe("summarizeWork", () => {
tool("edit", { diffs: [{ path: "/a.ts", added: 3, removed: 1 }] }),
tool("edit", { diffs: [{ path: "/a.ts", added: 2, removed: 0 }] }),
tool("edit", { locations: ["/b.ts"] }),
tool("execute"),
tool("execute", { title: "git status" }),
tool("execute", { title: "pnpm test" }),
tool("mcp_custom"),
]);
expect(s).toMatchObject({ thoughts: 1, read: 2, search: 1, edited: 2, run: 1, other: 1, added: 5, removed: 1 });
expect(s).toMatchObject({ thoughts: 1, read: 2, search: 1, edited: 2, run: 2, other: 1, added: 5, removed: 1 });
expect(workParts(s)).toEqual([
{ text: "Edited {count} files", count: 2 },
{ text: "Ran 1 command", count: 1 },
{ text: "Ran {count} commands", count: 2 },
{ text: "Read {count} files", count: 2 },
{ text: "Searched once", count: 1 },
{ text: "1 other tool call", count: 1 },
@@ -47,30 +47,6 @@ describe("summarizeWork", () => {
});
});
describe("foldedTurns", () => {
it("folds earlier finished turns' work before their reply and keeps the latest turn open", () => {
const entries = [user("q"), tool("read"), agent("mid"), tool("edit"), agent("done"), user("next"), agent("ok")];
expect([...foldedTurns(entries, 0).values()]).toEqual([{ user: 0, reply: 4, sentMs: 1000, doneMs: 5000 }]);
});
it("leaves the latest turn, turns without work, and turns ending otherwise open", () => {
const latestOnly = [user("q"), tool("read"), agent("a")];
expect(foldedTurns(latestOnly, 0).size).toBe(0);
expect(foldedTurns([user("q"), agent("a"), user("next")], 0).size).toBe(0);
expect(foldedTurns([user("q"), tool("read"), user("next")], 0).size).toBe(0);
expect(
foldedTurns([user("q"), tool("read"), agent("a"), { type: "error", message: "x" }, user("next")], 0).size,
).toBe(0);
expect(
foldedTurns([user("q"), { type: "error", message: "x" }, tool("read"), agent("a"), user("next")], 0).size,
).toBe(0);
expect(
foldedTurns([user("q"), tool("read"), user("more", { steered: true }), agent("a"), user("next")], 0).size,
).toBe(0);
expect(foldedTurns([user("q"), tool("read"), agent("a"), user("next")], 1).size).toBe(0);
});
});
// Fragments of a real Hermes 0.22.2 ACP stream (`hermes acp`), as the timeline folds them.
describe("Hermes tool calls", () => {
type Tool = Extract<AgentEntry, { type: "tool" }>;
Loaded 100 of 171 files, more files were not shown because too many files have changed in this diff. Show more