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

..
Автор SHA1 Повідомлення Дата
l0ng-ai fffca3cd2a fix(agents): drop the model settings chip's removed CSS class
The composer's dynamic overflow (#5827) removed .modelDetail from
Composer.module.css, but the model settings chip still read it, which
failed the CSS module check.
2026-11-25 18:52:16 +08:00
l0ng-ai 497948eeff fix(flutter): compile the Flutter tests on Windows (#5880)
The process tests that use FlutterDaemon::with_executable and ToolServer::is_stopped only run on Unix, so on Windows both helpers were dead code and the ide-flutter test build failed under -D warnings. They are now compiled only for Unix tests.
2026-11-25 18:50:59 +08:00
Vladislav Kuzmin 834846840b test(run): use the native path in the JVM JSON thread-dump assertion (#5837)
The JSON thread-dump test built its expected path with a forward slash, so it failed on Windows where the path uses backslashes. Join the file name onto the directory instead.

Co-authored-by: principalwater <[email protected]>
2026-11-25 18:47:05 +08:00
Muuтаmuutot a393bcdcc2 fix(search): keep focus in the search field when clicking a Find in Files scope tab (#5868)
Clicking In Project / Module / Directory / Scope in the Find in Files popup moved focus onto the tab button. The shared Tabs strip gains a keepFocusOnClick option (mousedown no longer focuses the tab) used by the scope strip; keyboard navigation of a focused strip and Tab traversal out of the search field are unchanged.

Co-authored-by: muutot <[email protected]>
2026-11-25 18:43:30 +08:00
Muuтаmuutot 08f6079316 fix(vcs): align Push dialog footer checkbox with buttons (#5876)
The Force (with lease) checkbox sat in a bare inline span (the protected-branch tooltip), so it lined up on the text baseline about 2px above the other footer controls. The wrapper is now an inline-flex box centred like its siblings.

Co-authored-by: muutot <[email protected]>
2026-11-25 18:43:20 +08:00
l0ng-ai 0db493b944 feat(project-tree): paste Java code into a folder as a class file (#5878)
Pasting text that declares a Java type into a Project view folder creates <Class>.java there, named after its first public top-level type (else its first), and opens it. Inside a Java source or test root the file declares the folder's package. An existing file is replaced only after asking. Paste is enabled while the clipboard holds such code.

Fixes #5821
2026-11-25 18:29:24 +08:00
l0ng-ai 2a90677e4f test(e2e): pick effort and context from the model settings lists (#5870)
#5806 replaced the Effort Level and Context Size radio groups with listboxes. agentCycleEffort.spec.ts still looked for radio groups, and five of its tests failed on main; they now use listbox / option.
2026-11-25 18:14:04 +08:00
l0ng-ai fed9a00dd9 fix(agents): lay out a chat row again when it loses its author header off-screen (#5869)
History loads in front of the first row shown, which carries the agent's author header. Once earlier rows arrive the header moves, but an off-screen row already marked as measured kept the height it had with the header (content-visibility: auto). Jumping through a long chat therefore changed the scroll height by one header. Rows whose data-author changes are now laid out again.

The agent e2e specs now follow #5804's defaults (turns unfolded; only reasoning and read-only calls join a run). agentScroll counts six rows per turn and folds turns only for the folded-turn test. agentMarkdown opens the latest turn's reasoning directly, finds a command as its own row, and builds its run-layout fixture from read-only calls.
2026-11-25 18:11:29 +08:00
l0ng-ai f034d96ed4 fix(ui): prevent WebKit height: 100% overflow in flex-basis dialogs (#5864) 2026-11-25 18:00:43 +08:00
l0ng-aiтаCursor eead66df7d fix(agents): align session composer and asset pills with Islands style (#5863)
Co-authored-by: Cursor <[email protected]>
2026-11-25 17:50:42 +08:00
l0ng-ai 0dccfafa90 fix(ci): run language smoke when the build feature changes (#5865)
Since #5801, the frontend smoke loads src/features/build through run/store.ts, but that folder was not among the Language smoke triggers, so scripts/smoke-paths.test.ts failed on main. This adds src/features/build/** to the workflow's paths and to the Changes step's smoke pattern.
2026-11-25 17:50:00 +08:00
guiqingle520 6fba7e9424 fix(maven): skip help:effective-pom during offline sync without cached help plugin (#5856)
Offline sync named the pinned maven-help-plugin 3.5.1 when the local repository held no 3.x maven-help-plugin. Repositories filled by ordinary builds often lack it, so mvn -o failed with a plugin resolution error before dependency:tree could run.

Offline without a cached 3.x maven-help-plugin, the sync now runs only dependency:tree -Dverbose. The effective-POM consumers already fall back to the static POM model when the file is missing.

Closes #5844

Co-authored-by: guiqingle520 <[email protected]>
2026-11-25 17:40:34 +08:00
l0ng-ai 475e35281b fix(run): apply a plugin's JetBrains-only JVM options when the configuration runs a bare java (#5860)
The jdk filter of a plugin's javaAgents.vmOptions looked at the configuration's command before the project's JDK was resolved. A bare java, which generated configurations use, never matched jdk = "jetbrains", so those options were dropped.

Local runs now add agents after the project settings and run-command resolution. A bare java is resolved the way the launch finds it: the run's PATH in its working directory. When the java found there is not a JDK launcher, such as the macOS stub, JAVA_HOME is used instead. Runs on a target keep the existing notice.

Fixes #5807
2026-11-25 17:39:26 +08:00
LU XIANGRUIтаwildcatDownstairs 387670573f feat(flutter): add the Flutter Widget Preview tool window (#5843)
Flutter projects get a Flutter Widget Preview tool window that shows the project's @Preview widgets and updates them as files are saved. The first time the window opens, it runs flutter widget-preview start --machine --web-server in the project root, passing the project's DevTools server for the preview inspector. It then embeds the page reported by widget_preview.started on 127.0.0.1, in the IDE's light or dark theme.

The server stops when the project closes or loses trust, and it is killed with the app. Refresh reloads the page, or restarts a server that exited or failed. An older flutter without widget-preview reports that Flutter 3.38 or later is needed. Remote windows say it is not available yet.

DevTools and Widget Preview now share one ToolServer, which starts, waits for and stops these processes. Both take the configured Flutter SDK (dart / flutter) before the search path.

Related to #4096.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-25 17:34:48 +08:00
LU XIANGRUIтаwildcatDownstairs 48aac102e1 feat(run): hot reload and DevTools for Flutter apps started by Run (#5839)
Flutter apps started with Run now run through flutter run --machine. Hot Reload and Hot Restart send app.restart requests with the app's id instead of typing r / R into the process. The buttons are enabled once the app reports app.started and supportsRestart.

The JSON protocol on stdout is decoded into plain console lines (app.log, progress, daemon messages, failed restarts). Lines outside the protocol show unchanged, and these runs never go through a terminal emulator.

Run-mode apps are kept in a workbench store, so the Flutter Inspector, DevTools and Extensions windows connect to them through the wsUri of app.debugPort, the same way they connect to Debug sessions. The Inspector lists Debug and Run apps together.

Part of #4096.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-25 17:29:13 +08:00
faysouтаfaysou 2d7353e39f perf(tree): keep virtual rows painted while switching panes and scrolling (#5850)
Hiding a tool window reset the tree's measured viewport, so switching panes could briefly blank a populated tree. Large wheel jumps could also paint the new offset before the virtualizer mounted its rows.

Trees now keep their last viewport and offset while hidden. They scroll wheel jumps in the same event that updates the virtual rows, and they use the DOM scrollbar that already serves the commit list. Tool window content is no longer recreated on every frame re-render.

Co-authored-by: faysou <[email protected]>
2026-11-25 17:26:33 +08:00
faysouтаfaysou 912da2551b fix(project-tree): restore folders faster and expand selected subtrees (#5851)
Restoring many open folders rebuilt the tree model for every directory reply. Replies that arrive in the same frame are now applied in one update, so deep files appear sooner.

The Project view header's Expand All becomes Expand Selected. It opens each selected subtree as its folders load, and stays disabled without a visible selection. Collapse All now also closes the root rows and cancels a queued expansion. Expand All remains available as an action.

Co-authored-by: faysou <[email protected]>
2026-11-25 17:20:57 +08:00
l0ng-ai 06bd43e46f fix(agents): optically center the full-page New Task prompt (#5849) 2026-11-25 17:20:44 +08:00
l0ng-ai b9a5b8d90b fix(color-scheme): import the default Interface name as TypeScript's interface colour (#5852)
DEFAULT_INTERFACE_NAME only targeted Class name, where JS.CLASS outranks it, so a scheme without JS./TS. interface keys lost its interface colour on import. It now also colours JavaScript and TypeScript › Interface name as its fallback; an explicit JS./TS.INTERFACE still wins.

Fixes #5619
2026-11-25 17:13:15 +08:00
l0ng-ai 92917d1c26 fix(index): give the indexing threads a 32 MiB stack (#5848)
Indexing a large project crashed the IDE on Windows with a stack overflow (0xc00000fd) during the initial scan: parsing and outlining a deeply nested file recurse as deep as it nests, and the index pool and worker thread ran on Rust's default 2 MiB stack. Both now reserve 32 MiB; only touched pages are committed.

Fixes #5739
2026-11-25 17:11:44 +08:00
l0ng-ai 4f0ab6c968 fix(debugger): bound the debug console's output backlog under a log flood (#5847)
Debug output arriving faster than the console parsed it piled up in the per-frame queue, and each frame re-measured the widest line of all 50,000 lines because the growing last line is replaced by a copy. Pending output is now capped at 4 MiB per session (oldest whole lines first), the widest-line measure resumes by line id, lines over 8,000 characters are broken up as in the Run console, and dropped lines are counted and shown as "N earlier lines were discarded".

Fixes #5769
2026-11-25 17:09:51 +08:00
LU XIANGRUIтаwildcatDownstairs 43fdb0aba7 feat(flutter): add a Flutter SDK setting for the Dart server, debugger, runs and devices (#5831)
Settings › Languages & Frameworks › Flutter › Flutter SDK path chooses the SDK whose flutter and Dart the Dart language server, the debugger, run configurations, pub commands, the device list (flutter daemon) and DevTools use; empty keeps PATH. The page shows flutter --version --machine for the chosen SDK and lists detected SDKs (PATH, ~/flutter, ~/development/flutter, ~/sdk/flutter, fvm). Changing it restarts the daemon and stops DevTools.

Part of #4096.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-25 17:05:12 +08:00
l0ng-aiтаCursor d65d58a4e8 feat(agents): polish session status meters with context ring and grouped limits (#5840)
* feat(agents): polish session status meters with context ring, grouped limits, and severity tones

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

* chore(i18n): update text catalogs for status meters and removed work time

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

---------

Co-authored-by: Cursor <[email protected]>
2026-11-25 17:02:55 +08:00
l0ng-ai d3792e5667 fix(build-tools): import a Gradle build or a plain folder from Import Module from Existing Sources (#5835)
Import Module from Existing Sources only accepted a directory with pom.xml. It now takes any directory: pom.xml is linked as a Maven project, a Gradle settings or build script as a Gradle build, and a folder with neither is attached as another root after asking. A folder inside the opened project is reported as already part of it.

Fixes #5781
2026-11-25 16:47:50 +08:00
l0ng-ai d0bffb5e90 fix(project-tree): ask before overwriting a dropped or pasted file with the same name (#5833)
Files dropped or pasted from outside the project were always saved under a new name when the name was taken. Each conflict now asks: Overwrite (files only; the replaced file goes to Local History), Skip, or Create Copy, optionally for the remaining conflicts. Cancelling stops the import.

Fixes #5740
2026-11-25 16:39:29 +08:00
LU XIANGRUIтаwildcatDownstairs 8e26003894 feat(flutter): add the Flutter Property Editor tool window (#5823)
Flutter projects get a Flutter Property Editor tool window. With the caret in a widget constructor call in a Dart file, it lists that call's arguments (name, type, required marker, current value or the expression passed, the default as placeholder, the constructor's documentation) and edits them: text fields for String, int and double, dropdowns for bool and enums. The data comes from the Dart analysis server's dart/textDocument/editableArguments and dart/textDocument/editArgument requests; the edit comes back as workspace/applyEdit, so the editor's Undo reverts it. Values keep their type, since the server rejects 1.0 for an int parameter. Flags an older Dart SDK leaves out default to false, and isEditable to true.

Part of #4096

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-25 16:34:52 +08:00
guiqingle520 372d23b7e4 fix(windows): link the app with an 8 MB main-thread stack (#5830)
Windows gives the main thread a 1 MB stack by default, where macOS and Linux give 8 MB. Unoptimized debug frames overflowed it (STATUS_STACK_OVERFLOW, 0xc00000fd) after opening a Java project and clicking Settings. The MSVC build now links with /STACK:8388608, so the main thread gets the same 8 MB as elsewhere; other threads are unchanged.

Closes #5825

Co-authored-by: guiqingle520 <[email protected]>
2026-11-25 16:30:05 +08:00
RuyimgByCN dc35952cf4 feat(vcs): group Commit changes by module (#5789)
Adds View Options › Group By › Module to the Commit and Local Changes trees. Changes are grouped under the innermost module holding them: Maven and Gradle modules (named by their display name, artifactId or Gradle name), sbt projects, modules detected from build files, and attached workspace members. Files outside every module stay at the top level. Under Group By › Repository the module nodes sit inside each repository. The choice is remembered, F7 / Shift+F7 follow the grouped tree, and a module node can't be ignored as a whole. The option shows only when the project has modules.

Co-authored-by: RuyimgByCN <[email protected]>
2026-11-25 16:29:24 +08:00
RuyimgByCN 2622c9d778 feat(vcs): use Project-tree folder, module and attached-member file icons in Commit (#5816)
The Commit changes tree showed every directory with a plain folder icon and resolved file icons against the main project only. Directory rows now get the Project view's icons (source, test, resources, package, excluded, output, module, .github) from a folder presentation shared by both trees, and files of an attached workspace member resolve their test and Spring icons against that member's roots. Repository rows keep their folder icon and grey branch text.

The shared JVM package check keeps the Gradle sync and Eclipse .classpath source-set markers, so those folders keep their package icon in the Project tree.

Co-authored-by: RuyimgByCN <[email protected]>
2026-11-25 16:26:38 +08:00
l0ng-aiтаCursor c878fb1edc fix(agents): keep composer toolbar on one row with dynamic overflow (#5827)
Co-authored-by: Cursor <[email protected]>
2026-11-25 16:25:22 +08:00
l0ng-ai 9ca7a297e1 fix(search): keep search history per project (#5829)
Search Everywhere history and the find / replace history shared by the
editor's find bar and Find in Files were kept in one store for every
project, so one project's class names and search strings showed up in
another project's history dropdowns.

Each project now keeps its own history, keyed by its root (IntelliJ IDEA
keeps it in the project's workspace); a window without a project keeps the
shared one. File masks stay one list for all projects, as in IDEA. Earlier
history isn't carried over, since it can't be told apart by project.

Fixes #5758
2026-11-25 16:23:06 +08:00
l0ng-ai b748a4cfbc fix(vcs): scroll the merge panes together sideways and say when every change is processed (#5828)
The merge editor's three panes followed each other only vertically: scrolling
one sideways left the other two where they were. Each pane now gives the
others its horizontal offset, telling a scroll's direction by comparing with
its last position, and ignoring the scroll events its own moves cause.

When the last change is resolved, a notice under the toolbar says that all
changes have been processed and offers Save changes and finish merging, which
writes and stages the result.

Fixes #5731
2026-11-25 16:18:31 +08:00
l0ng-ai 5be5487ac6 fix(agents): translate the per-model Default (fallback) label (#5826)
#5806 added the "Default ({fallback})" option label to the agent model
settings without catalog entries, which failed the source-text catalog test
on main. Adds it next to "Agent's default ({fallback})" in every catalog
that has that key.
2026-11-25 16:17:47 +08:00
156 змінених файлів з 5627 додано та 708 видалено

No files matched your search

+2 -1
Переглянути файл
@@ -23,6 +23,7 @@ on:
- "Cargo.lock"
- "src/features/run/**"
- "src/features/debugger/**"
- "src/features/build/**"
- "src/features/build-tools/**"
- "src/platform/**"
- "src/workbench/**"
@@ -105,7 +106,7 @@ jobs:
# ide-lsp/dap/run/sdk/tools.
unused='^crates/(ide-agent|ide-analysis|ide-android|ide-cli|ide-clipboard|ide-coverage|ide-db|ide-docker|ide-fonts|ide-github|ide-http|ide-mcp|ide-notebook|ide-profiler|ide-scaffold|ide-spell|ide-ssh|ide-vcs|ide-web)/'
# The workflow's paths, less those handled per language below.
smoke='^(crates/|Cargo\.(toml|lock)$|src/features/(run|debugger|build-tools)/|src/platform/|src/workbench/|src/ui/|src/editor/(api|navigationProviders|relatedProviders|core/cm/(cornerInset|iconArea)|lsp/(availability|diagnostics|files|hint|lsp|positions))\.ts$|src/bindings\.ts$|src/styles/tokens\.css$|src/test/setup\.ts$|src-tauri/icons/128x128\.png$|smoke/|vite\.config\.ts$|tsconfig\.json$|package\.json$|pnpm-(lock|workspace)\.yaml$|patches/|\.github/workflows/language-smoke\.yml$|\.github/tool-versions\.env$)'
smoke='^(crates/|Cargo\.(toml|lock)$|src/features/(run|debugger|build|build-tools)/|src/platform/|src/workbench/|src/ui/|src/editor/(api|navigationProviders|relatedProviders|core/cm/(cornerInset|iconArea)|lsp/(availability|diagnostics|files|hint|lsp|positions))\.ts$|src/bindings\.ts$|src/styles/tokens\.css$|src/test/setup\.ts$|src-tauri/icons/128x128\.png$|smoke/|vite\.config\.ts$|tsconfig\.json$|package\.json$|pnpm-(lock|workspace)\.yaml$|patches/|\.github/workflows/language-smoke\.yml$|\.github/tool-versions\.env$)'
langs=""
while read -r f; do
case "$f" in
+1 -1
Переглянути файл
@@ -66,7 +66,7 @@ At render time `src/ui/icons.tsx` may recolour monochrome icons to `currentColor
These icons of [flutter-intellij](https://github.com/flutter/flutter-intellij) (commit `d02813ad5890`) are used
under the BSD 3-Clause License:
- `src/ui/expui/flutter/*.svg`: the DevTools tool window icons, copied unmodified from
- `src/ui/expui/flutter/*.svg`: the Flutter tool window icons, copied unmodified from
`resources/icons/expui/`.
- `src/ui/expui/flutter/[email protected]` and `[email protected]`: the Flutter outline's widget
icons, `resources/icons/custom/[email protected]` and `[email protected]`, renamed, content unmodified.
+24 -13
Переглянути файл
@@ -95,6 +95,8 @@ const DEPENDENCY_TREE_JAR: &str =
/// The goals that read the effective POM into `effective` and the verbose dependency trees;
/// `repo` is the local repository the build resolves from. Both goals name their plugin by
/// coordinates: offline, a prefix resolves only from group metadata the repository may lack.
/// Offline without a cached 3.x `maven-help-plugin`, `effective-pom` is skipped so `mvn -o`
/// still resolves the dependency tree instead of failing to download the help plugin.
fn maven_sync_goals(effective: &Path, offline: bool, repo: Option<&Path>) -> Vec<String> {
let pinned = !offline || repo.is_some_and(|repo| repo.join(DEPENDENCY_TREE_JAR).is_file());
let tree = if pinned {
@@ -105,12 +107,16 @@ fn maven_sync_goals(effective: &Path, offline: bool, repo: Option<&Path>) -> Vec
|v| format!("org.apache.maven.plugins:maven-dependency-plugin:{v}:tree"),
)
};
vec![
maven::plugin_goal("help:effective-pom", repo),
format!("-Doutput={}", effective.to_string_lossy()),
tree,
"-Dverbose".into(),
]
let has_help =
!offline || repo.is_some_and(|repo| maven::newest_local_plugin(repo, "maven-help-plugin", 3).is_some());
let mut goals = Vec::with_capacity(4);
if has_help {
goals.push(maven::plugin_goal("help:effective-pom", repo));
goals.push(format!("-Doutput={}", effective.to_string_lossy()));
}
goals.push(tree);
goals.push("-Dverbose".into());
goals
}
/// The settings' Maven options for the sync runs: the thread count (`-T`, also
@@ -947,19 +953,24 @@ mod tests {
let help = "org.apache.maven.plugins:maven-help-plugin:3.5.1:effective-pom";
let online = maven_sync_goals(Path::new("e.xml"), false, Some(tmp.path()));
assert_eq!(online, [help, "-Doutput=e.xml", DEPENDENCY_TREE, "-Dverbose"]);
// Offline with neither plugin cached: the tree falls back to the project's own version.
// Offline with neither plugin cached: `effective-pom` is skipped so `mvn -o` does not fail
// on an uncached `maven-help-plugin`, and the tree falls back to the project's own version.
let offline = maven_sync_goals(Path::new("e.xml"), true, Some(tmp.path()));
assert_eq!(offline, [help, "-Doutput=e.xml", "dependency:tree", "-Dverbose"]);
// #5757: offline, plugins in the local repository are named by their coordinates, since
// the prefix needs group metadata a repository filled from a private mirror may lack.
for (artifact, version) in
[("maven-help-plugin", "3.4.0"), ("maven-help-plugin", "2.2"), ("maven-dependency-plugin", "3.6.1")]
{
assert_eq!(offline, ["dependency:tree", "-Dverbose"]);
// #5757 / #5844: offline, plugins in the local repository are named by their coordinates,
// since the prefix needs group metadata a repository filled from a private mirror may lack;
// a repository with `maven-dependency-plugin` but no 3.x `maven-help-plugin` runs only the tree.
for (artifact, version) in [("maven-help-plugin", "2.2"), ("maven-dependency-plugin", "3.6.1")] {
let jar =
tmp.path().join(format!("org/apache/maven/plugins/{artifact}/{version}/{artifact}-{version}.jar"));
std::fs::create_dir_all(jar.parent().unwrap()).unwrap();
std::fs::write(&jar, "").unwrap();
}
let offline = maven_sync_goals(Path::new("e.xml"), true, Some(tmp.path()));
assert_eq!(offline, ["org.apache.maven.plugins:maven-dependency-plugin:3.6.1:tree", "-Dverbose"]);
let help_jar = tmp.path().join("org/apache/maven/plugins/maven-help-plugin/3.4.0/maven-help-plugin-3.4.0.jar");
std::fs::create_dir_all(help_jar.parent().unwrap()).unwrap();
std::fs::write(&help_jar, "").unwrap();
// A version folder without its jar (only the POM was fetched) doesn't count.
std::fs::create_dir_all(tmp.path().join("org/apache/maven/plugins/maven-help-plugin/3.10.0")).unwrap();
let offline = maven_sync_goals(Path::new("e.xml"), true, Some(tmp.path()));
+11
Переглянути файл
@@ -1218,6 +1218,7 @@ pub struct LanguagesSettings {
pub markdown: MarkdownSettings,
pub arduino: ArduinoSettings,
pub zig: ZigSettings,
pub flutter: FlutterSettings,
}
impl Default for LanguagesSettings {
@@ -1249,6 +1250,7 @@ impl Default for LanguagesSettings {
markdown: MarkdownSettings::default(),
arduino: ArduinoSettings::default(),
zig: ZigSettings::default(),
flutter: FlutterSettings::default(),
}
}
}
@@ -1515,6 +1517,15 @@ pub struct ZigSettings {
pub zig: String,
}
/// The Flutter plugin's "Flutter SDK path".
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct FlutterSettings {
/// Flutter SDK root (holding `bin/flutter`); its `flutter` and Dart replace the ones on
/// `PATH`. Empty = `PATH`.
pub sdk: String,
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct GoSettings {
+15 -14
Переглянути файл
@@ -897,6 +897,21 @@ impl DebugManager {
if config.adapter == "rdbg" {
rdbg_command_line(&mut spec, &config, &cwd)?;
}
// Flutter: a project depending on the Flutter SDK needs `flutter debug_adapter`
// (the Dart adapter cannot start a program importing `dart:ui`, and hot reload
// is Flutter-only). Plain Dart projects keep the configured `dart`. Before
// `custom_command`, which picks the Flutter SDK setting's `flutter`.
if config.adapter == "dart" {
let program = arguments.get("program").and_then(Value::as_str).map(Path::new);
if force_flutter || is_flutter_project(&cwd, program) {
if spec.command == "dart" {
spec.command = "flutter".into();
}
if let Some(device) = flutter_device {
add_flutter_device(&mut arguments, device);
}
}
}
if let Some(command) = custom_command(&spec.command) {
spec.command = command;
}
@@ -912,20 +927,6 @@ impl DebugManager {
spec.command = python;
}
}
// Flutter: a project depending on the Flutter SDK needs `flutter debug_adapter`
// (the Dart adapter cannot start a program importing `dart:ui`, and hot reload
// is Flutter-only). Plain Dart projects keep the configured `dart`.
if config.adapter == "dart" {
let program = arguments.get("program").and_then(Value::as_str).map(Path::new);
if force_flutter || is_flutter_project(&cwd, program) {
if spec.command == "dart" {
spec.command = "flutter".into();
}
if let Some(device) = flutter_device {
add_flutter_device(&mut arguments, device);
}
}
}
let id = DebugSessionId::next();
let debug_server = take_debug_server(&mut arguments)?;
if let Some(server) = &debug_server {
+43 -194
Переглянути файл
@@ -1,23 +1,34 @@
//! One `dart devtools` server per project window, started when first asked for. In `--machine`
//! mode it reports its port as a `server.started` line on stdout. A server that fails or exits
//! is not restarted on its own: the next request starts a new one.
//! One `dart devtools` server per project window. In `--machine` mode it reports its port as a
//! `server.started` line on stdout.
use crate::{KILL_GRACE, OUTPUT_TAIL, keep_output, read_lines, spawn_watched};
use ide_core::process::{kill_tree, terminate_tree};
use crate::flutter_executable;
use crate::server::{Line, Spec, ToolServer};
use ide_core::tool_path::{find_command, search_path_in};
use parking_lot::{Condvar, Mutex};
use serde_json::Value;
use std::collections::VecDeque;
use std::path::{Path, PathBuf};
use std::process::Child;
use std::sync::Arc;
use std::time::{Duration, Instant};
use std::time::Duration;
const START_TIMEOUT: Duration = Duration::from_secs(60);
/// The address embedded pages are allowed to come from, so never `localhost`.
const HOST: &str = "127.0.0.1";
pub(crate) const HOST: &str = "127.0.0.1";
const ARGS: [&str; 7] = ["devtools", "--machine", "--allow-embedding", "--host", HOST, "--port", "0"];
pub(crate) static DEVTOOLS: Spec = Spec {
name: "Flutter DevTools",
args: &ARGS,
timeout: Duration::from_secs(60),
executable: dart_executable,
not_found: "Dart SDK not found: install Flutter or add it to PATH",
line,
failed: |message| if message.is_empty() { "dart devtools exited".into() } else { message },
};
impl ToolServer {
/// `dart` is the configured one, else the one of the `flutter` on the search path.
pub fn devtools(root: PathBuf, dart: crate::Configured) -> Self {
Self::new(root, &DEVTOOLS, dart)
}
}
fn started_port(line: &str) -> Option<u16> {
let message: Value = serde_json::from_str(line.trim()).ok()?;
if message.get("event")?.as_str()? != "server.started" {
@@ -26,186 +37,23 @@ fn started_port(line: &str) -> Option<u16> {
u16::try_from(message.get("params")?.get("port")?.as_u64()?).ok()
}
fn line(line: &str) -> Line {
match started_port(line) {
Some(port) => Line::Url(format!("http://{HOST}:{port}")),
None => Line::Output(line.to_owned()),
}
}
/// The `dart` of the SDK `flutter` belongs to, so that DevTools matches the debugged app.
fn dart_executable(root: &Path) -> Option<PathBuf> {
let path = search_path_in(root);
find_command("flutter", &path, root)
flutter_executable(root)
.and_then(|flutter| {
// On the search path `flutter` is often a link into the SDK.
let flutter = if cfg!(unix) { std::fs::canonicalize(&flutter).unwrap_or(flutter) } else { flutter };
let dart = flutter.with_file_name(if cfg!(windows) { "dart.bat" } else { "dart" });
dart.is_file().then_some(dart)
})
.or_else(|| find_command("dart", &path, root))
}
#[derive(Default)]
enum Status {
#[default]
Stopped,
Starting,
Ready(String),
Failed(String),
}
#[derive(Default)]
struct State {
/// Bumped by every start and stop: a reader of an older process no longer has a say.
generation: u64,
child: Option<Child>,
status: Status,
}
impl State {
fn shut_down(&mut self) {
self.generation += 1;
if let Some(mut child) = self.child.take() {
std::thread::spawn(move || terminate_tree(&mut child, KILL_GRACE));
}
}
}
struct Shared {
root: PathBuf,
/// Replaces the lookup on the search path (tests).
executable: Option<PathBuf>,
timeout: Duration,
state: Mutex<State>,
changed: Condvar,
}
impl Shared {
/// Applies `status` unless this process was replaced or stopped; false if it was.
fn set(&self, generation: u64, status: Status) -> bool {
let mut state = self.state.lock();
if state.generation != generation {
return false;
}
state.status = status;
self.changed.notify_all();
true
}
}
pub struct DevToolsServer(Arc<Shared>);
impl DevToolsServer {
pub fn new(root: PathBuf) -> Self {
Self::with_executable(root, None, START_TIMEOUT)
}
fn with_executable(root: PathBuf, executable: Option<PathBuf>, timeout: Duration) -> Self {
Self(Arc::new(Shared { root, executable, timeout, state: Mutex::default(), changed: Condvar::new() }))
}
/// The server's address, starting it if none runs. Blocks until it is known.
pub fn url(&self) -> Result<String, String> {
let shared = &self.0;
let deadline = Instant::now() + shared.timeout;
let mut state = shared.state.lock();
if matches!(state.status, Status::Stopped | Status::Failed(_)) {
state.generation += 1;
state.status = Status::Starting;
let (shared, generation) = (shared.clone(), state.generation);
std::thread::spawn(move || run(&shared, generation));
}
loop {
match &state.status {
Status::Ready(url) => return Ok(url.clone()),
Status::Failed(message) => return Err(message.clone()),
Status::Stopped => return Err("Flutter DevTools was stopped".into()),
Status::Starting => {}
}
if shared.changed.wait_until(&mut state, deadline).timed_out() {
state.shut_down();
let message = "Flutter DevTools did not start in time".to_owned();
state.status = Status::Failed(message.clone());
shared.changed.notify_all();
return Err(message);
}
}
}
/// Ends the server (project closed, or no longer trusted).
pub fn stop(&self) {
let mut state = self.0.state.lock();
state.shut_down();
state.status = Status::Stopped;
self.0.changed.notify_all();
}
/// Ends the server before returning, for a process about to exit.
pub fn kill(&self) {
let mut state = self.0.state.lock();
state.generation += 1;
state.status = Status::Stopped;
if let Some(mut child) = state.child.take() {
kill_tree(&mut child);
}
self.0.changed.notify_all();
}
}
/// One server's whole life, on its own thread.
fn run(shared: &Arc<Shared>, generation: u64) {
let fail = |message: String| {
shared.set(generation, Status::Failed(message));
};
let Some(executable) = shared.executable.clone().or_else(|| dart_executable(&shared.root)) else {
return fail("Dart SDK not found: install Flutter or add it to PATH".into());
};
let mut child = match spawn_watched(&executable, &ARGS, &shared.root) {
Ok(child) => child,
Err(e) => return fail(format!("could not run {}: {e}", executable.display())),
};
let (Some(stdout), Some(stderr)) = (child.stdout.take(), child.stderr.take()) else {
terminate_tree(&mut child, Duration::ZERO);
return fail("no output pipe".into());
};
{
let mut state = shared.state.lock();
if state.generation != generation {
drop(state);
terminate_tree(&mut child, KILL_GRACE);
return;
}
state.child = Some(child);
}
let tail = Arc::new(Mutex::new(VecDeque::with_capacity(OUTPUT_TAIL)));
let errors = {
let tail = tail.clone();
std::thread::spawn(move || {
read_lines(stderr, |line| {
keep_output(&tail, line);
true
});
})
};
read_lines(stdout, |line| match started_port(line) {
Some(port) => shared.set(generation, Status::Ready(format!("http://{HOST}:{port}"))),
None => {
keep_output(&tail, line);
true
}
});
let _ = errors.join();
let mut state = shared.state.lock();
if state.generation != generation {
return;
}
let child = state.child.take();
state.status = if matches!(state.status, Status::Ready(_)) {
Status::Stopped
} else {
let message = Vec::from(std::mem::take(&mut *tail.lock())).join("\n");
Status::Failed(if message.is_empty() { "dart devtools exited".into() } else { message })
};
shared.changed.notify_all();
drop(state);
if let Some(mut child) = child {
std::thread::spawn(move || terminate_tree(&mut child, Duration::ZERO));
}
.or_else(|| find_command("dart", &search_path_in(root), root))
}
#[cfg(test)]
@@ -225,14 +73,15 @@ mod tests {
mod process {
use super::*;
use std::os::unix::fs::PermissionsExt;
use std::time::Instant;
const STARTED: &str = r#"echo '{"event":"server.started","params":{"port":4242}}'"#;
fn server(dir: &Path, script: &str, timeout: Duration) -> DevToolsServer {
fn server(dir: &Path, script: &str, timeout: Duration) -> ToolServer {
let path = dir.join("dart");
std::fs::write(&path, format!("#!/bin/sh\necho run >> runs\n{script}")).unwrap();
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
DevToolsServer::with_executable(dir.to_owned(), Some(path), timeout)
ToolServer::with_executable(dir.to_owned(), &DEVTOOLS, Box::new(move || Some(path.clone())), timeout)
}
fn runs(dir: &Path) -> usize {
@@ -252,8 +101,8 @@ mod tests {
let dir = tempfile::tempdir().unwrap();
let script = format!("echo \"$*\" > args\necho $$ > pid\n{STARTED}\nexec sleep 30");
let devtools = server(dir.path(), &script, Duration::from_secs(10));
assert_eq!(devtools.url().unwrap(), "http://127.0.0.1:4242");
assert_eq!(devtools.url().unwrap(), "http://127.0.0.1:4242");
assert_eq!(devtools.url(&[]).unwrap(), "http://127.0.0.1:4242");
assert_eq!(devtools.url(&[]).unwrap(), "http://127.0.0.1:4242");
assert_eq!(runs(dir.path()), 1);
let args = std::fs::read_to_string(dir.path().join("args")).unwrap();
assert_eq!(args.trim(), ARGS.join(" "));
@@ -271,10 +120,10 @@ mod tests {
fn a_failure_is_reported_and_only_a_new_request_retries() {
let dir = tempfile::tempdir().unwrap();
let devtools = server(dir.path(), "echo boom >&2\nexit 3", Duration::from_secs(10));
assert_eq!(devtools.url().unwrap_err(), "boom");
assert_eq!(devtools.url(&[]).unwrap_err(), "boom");
std::thread::sleep(Duration::from_millis(100));
assert_eq!(runs(dir.path()), 1);
assert_eq!(devtools.url().unwrap_err(), "boom");
assert_eq!(devtools.url(&[]).unwrap_err(), "boom");
assert_eq!(runs(dir.path()), 2);
}
@@ -282,10 +131,10 @@ mod tests {
fn a_server_that_exits_is_not_restarted_until_asked() {
let dir = tempfile::tempdir().unwrap();
let devtools = server(dir.path(), STARTED, Duration::from_secs(10));
devtools.url().unwrap();
wait_for("the exit to be noticed", || matches!(devtools.0.state.lock().status, Status::Stopped));
devtools.url(&[]).unwrap();
wait_for("the exit to be noticed", || devtools.is_stopped());
assert_eq!(runs(dir.path()), 1);
devtools.url().unwrap();
devtools.url(&[]).unwrap();
assert_eq!(runs(dir.path()), 2);
}
@@ -293,7 +142,7 @@ mod tests {
fn a_server_that_never_reports_times_out() {
let dir = tempfile::tempdir().unwrap();
let devtools = server(dir.path(), "exec sleep 30", Duration::from_millis(200));
assert_eq!(devtools.url().unwrap_err(), "Flutter DevTools did not start in time");
assert_eq!(devtools.url(&[]).unwrap_err(), "Flutter DevTools did not start in time");
}
}
}
+27 -8
Переглянути файл
@@ -10,8 +10,10 @@
//! daemon that fails stays failed until the user restarts it.
mod devtools;
mod server;
mod widget_preview;
pub use devtools::DevToolsServer;
pub use server::ToolServer;
use ide_android::AndroidDevice;
use ide_core::event::{FlutterDaemonStatus, FlutterDevice, FlutterDeviceList, FlutterEmulator};
@@ -189,8 +191,7 @@ impl State {
struct Shared {
root: PathBuf,
sink: SharedSink,
/// Replaces the lookup on the search path (tests).
executable: Option<PathBuf>,
executable: Configured,
state: Mutex<State>,
}
@@ -200,16 +201,21 @@ impl Shared {
}
}
/// The configured `flutter` / `dart` (the Flutter SDK setting), asked at each start; `None`
/// looks it up on the search path.
pub type Configured = Box<dyn Fn() -> Option<PathBuf> + Send + Sync>;
/// One project window's `flutter daemon`, started on first use.
pub struct FlutterDaemon(Arc<Shared>);
impl FlutterDaemon {
pub fn new(root: PathBuf, sink: SharedSink) -> Self {
Self::with_executable(root, sink, None)
pub fn new(root: PathBuf, sink: SharedSink, executable: Configured) -> Self {
Self(Arc::new(Shared { root, sink, executable, state: Mutex::default() }))
}
#[cfg(all(test, unix))]
fn with_executable(root: PathBuf, sink: SharedSink, executable: Option<PathBuf>) -> Self {
Self(Arc::new(Shared { root, sink, executable, state: Mutex::default() }))
Self::new(root, sink, Box::new(move || executable.clone()))
}
/// The current list; starts the daemon unless it already ran. Never blocks on the process.
@@ -271,6 +277,15 @@ impl FlutterDaemon {
}
}
/// Starts a running daemon again, with the SDK the settings now choose.
pub fn sdk_changed(&self) {
let mut state = self.0.state.lock();
if state.status != FlutterDaemonStatus::Stopped {
state.shut_down();
start(&self.0, &mut state);
}
}
/// Ends the daemon (project closed, or no longer trusted).
pub fn stop(&self) {
let mut state = self.0.state.lock();
@@ -385,10 +400,14 @@ fn read_lines(pipe: impl Read, mut on_line: impl FnMut(&str) -> bool) {
}
}
/// The `flutter` that commands run in `root` use.
fn flutter_executable(root: &Path) -> Option<PathBuf> {
find_command("flutter", &search_path_in(root), root)
}
/// One daemon's whole life, on its own thread.
fn run(shared: &Arc<Shared>, generation: u64) {
let executable =
shared.executable.clone().or_else(|| find_command("flutter", &search_path_in(&shared.root), &shared.root));
let executable = (shared.executable)().or_else(|| flutter_executable(&shared.root));
let Some(executable) = executable else {
return finish(shared, generation, FlutterDaemonStatus::NotInstalled);
};
+218
Переглянути файл
@@ -0,0 +1,218 @@
//! A Flutter tool serving pages for the IDE to embed, one per project window, started when first
//! asked for. It reports its address on stdout. A server that fails or exits is not restarted on
//! its own: the next request starts a new one.
use crate::{KILL_GRACE, OUTPUT_TAIL, keep_output, read_lines, spawn_watched};
use ide_core::process::{kill_tree, terminate_tree};
use parking_lot::{Condvar, Mutex};
use std::collections::VecDeque;
use std::path::{Path, PathBuf};
use std::process::Child;
use std::sync::Arc;
use std::time::{Duration, Instant};
/// What one line of the tool's output says.
pub(crate) enum Line {
/// The page's address: the server is ready.
Url(String),
/// Text worth showing if the server fails.
Output(String),
/// Nothing worth keeping.
Skip,
}
/// How to run one kind of server.
pub(crate) struct Spec {
/// For messages, e.g. "Flutter DevTools".
pub name: &'static str,
pub args: &'static [&'static str],
pub timeout: Duration,
pub executable: fn(&Path) -> Option<PathBuf>,
pub not_found: &'static str,
pub line: fn(&str) -> Line,
/// The failure to report, from the output kept until the tool exited.
pub failed: fn(String) -> String,
}
#[derive(Default)]
enum Status {
#[default]
Stopped,
Starting,
Ready(String),
Failed(String),
}
#[derive(Default)]
struct State {
/// Bumped by every start and stop: a reader of an older process no longer has a say.
generation: u64,
child: Option<Child>,
status: Status,
}
impl State {
fn shut_down(&mut self) {
self.generation += 1;
if let Some(mut child) = self.child.take() {
std::thread::spawn(move || terminate_tree(&mut child, KILL_GRACE));
}
}
}
struct Shared {
root: PathBuf,
spec: &'static Spec,
/// The configured executable; the spec's lookup on the search path without one.
executable: crate::Configured,
timeout: Duration,
state: Mutex<State>,
changed: Condvar,
}
impl Shared {
/// Applies `status` unless this process was replaced or stopped; false if it was.
fn set(&self, generation: u64, status: Status) -> bool {
let mut state = self.state.lock();
if state.generation != generation {
return false;
}
state.status = status;
self.changed.notify_all();
true
}
}
pub struct ToolServer(Arc<Shared>);
impl ToolServer {
pub(crate) fn new(root: PathBuf, spec: &'static Spec, executable: crate::Configured) -> Self {
Self::with_executable(root, spec, executable, spec.timeout)
}
pub(crate) fn with_executable(
root: PathBuf,
spec: &'static Spec,
executable: crate::Configured,
timeout: Duration,
) -> Self {
Self(Arc::new(Shared { root, spec, executable, timeout, state: Mutex::default(), changed: Condvar::new() }))
}
/// The server's address, starting it with `extra` arguments if none runs. Blocks until it is known.
pub fn url(&self, extra: &[String]) -> Result<String, String> {
let shared = &self.0;
let deadline = Instant::now() + shared.timeout;
let mut state = shared.state.lock();
if matches!(state.status, Status::Stopped | Status::Failed(_)) {
state.generation += 1;
state.status = Status::Starting;
let (shared, generation, extra) = (shared.clone(), state.generation, extra.to_vec());
std::thread::spawn(move || run(&shared, generation, &extra));
}
loop {
match &state.status {
Status::Ready(url) => return Ok(url.clone()),
Status::Failed(message) => return Err(message.clone()),
Status::Stopped => return Err(format!("{} was stopped", shared.spec.name)),
Status::Starting => {}
}
if shared.changed.wait_until(&mut state, deadline).timed_out() {
state.shut_down();
let message = format!("{} did not start in time", shared.spec.name);
state.status = Status::Failed(message.clone());
shared.changed.notify_all();
return Err(message);
}
}
}
/// Ends the server (project closed, or no longer trusted).
pub fn stop(&self) {
let mut state = self.0.state.lock();
state.shut_down();
state.status = Status::Stopped;
self.0.changed.notify_all();
}
/// Ends the server before returning, for a process about to exit.
pub fn kill(&self) {
let mut state = self.0.state.lock();
state.generation += 1;
state.status = Status::Stopped;
if let Some(mut child) = state.child.take() {
kill_tree(&mut child);
}
self.0.changed.notify_all();
}
#[cfg(all(test, unix))]
pub(crate) fn is_stopped(&self) -> bool {
matches!(self.0.state.lock().status, Status::Stopped)
}
}
/// One server's whole life, on its own thread.
fn run(shared: &Arc<Shared>, generation: u64, extra: &[String]) {
let spec = shared.spec;
let fail = |message: String| {
shared.set(generation, Status::Failed(message));
};
let Some(executable) = (shared.executable)().or_else(|| (spec.executable)(&shared.root)) else {
return fail(spec.not_found.into());
};
let args: Vec<&str> = spec.args.iter().copied().chain(extra.iter().map(String::as_str)).collect();
let mut child = match spawn_watched(&executable, &args, &shared.root) {
Ok(child) => child,
Err(e) => return fail(format!("could not run {}: {e}", executable.display())),
};
let (Some(stdout), Some(stderr)) = (child.stdout.take(), child.stderr.take()) else {
terminate_tree(&mut child, Duration::ZERO);
return fail("no output pipe".into());
};
{
let mut state = shared.state.lock();
if state.generation != generation {
drop(state);
terminate_tree(&mut child, KILL_GRACE);
return;
}
state.child = Some(child);
}
let tail = Arc::new(Mutex::new(VecDeque::with_capacity(OUTPUT_TAIL)));
let errors = {
let tail = tail.clone();
std::thread::spawn(move || {
read_lines(stderr, |line| {
keep_output(&tail, line);
true
});
})
};
read_lines(stdout, |line| match (spec.line)(line) {
Line::Url(url) => shared.set(generation, Status::Ready(url)),
Line::Output(text) => {
keep_output(&tail, &text);
true
}
Line::Skip => true,
});
let _ = errors.join();
let mut state = shared.state.lock();
if state.generation != generation {
return;
}
let child = state.child.take();
state.status = if matches!(state.status, Status::Ready(_)) {
Status::Stopped
} else {
let message = Vec::from(std::mem::take(&mut *tail.lock())).join("\n");
Status::Failed((spec.failed)(message))
};
shared.changed.notify_all();
drop(state);
if let Some(mut child) = child {
std::thread::spawn(move || terminate_tree(&mut child, Duration::ZERO));
}
}
+118
Переглянути файл
@@ -0,0 +1,118 @@
//! One `flutter widget-preview` server per project window: the `@Preview` widgets of the project,
//! served as a web page that reloads as they change. Like the Flutter plugins of Android Studio
//! and VS Code it runs on the `web-server` device, in `--machine` mode, where it reports events
//! as bracketed JSON lines and the page's address with `widget_preview.started`. Without
//! `--dtd-url` it starts its own analysis server and Dart Tooling Daemon to find the previews.
use crate::devtools::HOST;
use crate::flutter_executable;
use crate::server::{Line, Spec, ToolServer};
use serde_json::Value;
use std::path::PathBuf;
use std::time::Duration;
/// The release whose `widget-preview start` has the options used here.
const MIN_FLUTTER: &str = "3.38";
static WIDGET_PREVIEW: Spec = Spec {
name: "Flutter Widget Preview",
args: &["widget-preview", "start", "--machine", "--web-server"],
// The first start runs `pub get` and compiles the preview environment.
timeout: Duration::from_secs(300),
executable: flutter_executable,
not_found: "Flutter SDK not found: install Flutter or add it to PATH",
line,
failed,
};
impl ToolServer {
/// `flutter` is the configured one, else the one on the search path.
pub fn widget_preview(root: PathBuf, flutter: crate::Configured) -> Self {
Self::new(root, &WIDGET_PREVIEW, flutter)
}
}
fn line(line: &str) -> Line {
let Ok(Value::Array(messages)) = serde_json::from_str(line.trim()) else {
return Line::Output(line.to_owned());
};
let Some(message) = messages.first() else { return Line::Skip };
let params = &message["params"];
match message["event"].as_str() {
// The server listens on every interface; embedded pages may only come from `HOST`.
Some("widget_preview.started") => params["url"]
.as_str()
.map_or(Line::Skip, |url| Line::Url(url.replacen("//localhost:", &format!("//{HOST}:"), 1))),
Some("widget_preview.logMessage") if matches!(params["level"].as_str(), Some("error" | "warning")) => {
params["message"].as_str().map_or(Line::Skip, |text| Line::Output(text.to_owned()))
}
_ => Line::Skip,
}
}
fn failed(message: String) -> String {
// What an older `flutter` says of a command or an option it doesn't know.
if message.contains("Could not find a") && message.contains(" named \"") {
format!(
"Flutter Widget Preview needs Flutter {MIN_FLUTTER} or later. Upgrade Flutter, then refresh the window."
)
} else if message.is_empty() {
"flutter widget-preview exited".into()
} else {
message
}
}
#[cfg(test)]
mod tests {
use super::*;
fn url(line: &str) -> Option<String> {
match super::line(line) {
Line::Url(url) => Some(url),
_ => None,
}
}
fn output(line: &str) -> Option<String> {
match super::line(line) {
Line::Output(text) => Some(text),
_ => None,
}
}
#[test]
fn started_gives_the_address_on_the_embeddable_host() {
let line = r#"[{"event":"widget_preview.started","params":{"url":"http://localhost:56207"}}]"#;
assert_eq!(url(line).as_deref(), Some("http://127.0.0.1:56207"));
let launch =
r#"[{"event":"widget_preview.app.webLaunchUrl","params":{"url":"http://localhost:1","launched":false}}]"#;
assert_eq!(url(launch), None);
}
#[test]
fn only_errors_warnings_and_plain_text_are_kept() {
let log = |level: &str| {
format!(r#"[{{"event":"widget_preview.logMessage","params":{{"level":"{level}","message":"m"}}}}]"#)
};
assert_eq!(output(&log("error")).as_deref(), Some("m"));
assert_eq!(output(&log("warning")).as_deref(), Some("m"));
assert_eq!(output(&log("status")), None);
assert_eq!(output(r#"[{"event":"widget_preview.initializing","params":{"pid":1}}]"#), None);
assert_eq!(
output("Could not find a command named \"widget-preview\".").as_deref(),
Some("Could not find a command named \"widget-preview\".")
);
}
#[test]
fn an_older_flutter_is_named_as_the_cause() {
for message in
[r#"Could not find a command named "widget-preview"."#, r#"Could not find an option named "--web-server"."#]
{
assert!(failed(message.into()).starts_with("Flutter Widget Preview needs Flutter 3.38"));
}
assert_eq!(failed("pub get failed".into()), "pub get failed");
assert_eq!(failed(String::new()), "flutter widget-preview exited");
}
}
+3
Переглянути файл
@@ -399,6 +399,7 @@ impl Host {
project.agents.shutdown();
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
@@ -528,6 +529,7 @@ impl Host {
for project in self.projects() {
project.flutter.kill();
project.devtools.kill();
project.widget_preview.kill();
}
}
@@ -570,6 +572,7 @@ impl Host {
project.files_events_active.store(false, std::sync::atomic::Ordering::Release);
project.flutter.kill();
project.devtools.kill();
project.widget_preview.kill();
}
for project in &projects {
project.plugin_diagnostics.close();
+18 -2
Переглянути файл
@@ -40,11 +40,27 @@ pub async fn flutter_emulator_launch(host: &Host, window: &str, id: String) -> I
#[command(trust = trusted)]
pub async fn flutter_devtools_url(host: &Host, window: &str) -> IdeResult<String> {
let project = host.project(window)?;
tokio::task::spawn_blocking(move || project.devtools.url())
tokio::task::spawn_blocking(move || project.devtools.url(&[]))
.await
.map_err(|e| IdeError::internal(e.to_string()))?
.map_err(IdeError::unavailable)
}
/// The address of the project's Widget Preview page, its server started on first use with the
/// project's DevTools for its inspector. A server that failed or exited is only started again by
/// the next request.
#[command(trust = trusted)]
pub async fn flutter_widget_preview_url(host: &Host, window: &str) -> IdeResult<String> {
let project = host.project(window)?;
tokio::task::spawn_blocking(move || {
// Without it the tool starts a DevTools of its own.
let devtools = project.devtools.url(&[]).map(|url| format!("--devtools-server-address={url}"));
project.widget_preview.url(&Vec::from_iter(devtools.ok()))
})
.await
.map_err(|e| IdeError::internal(e.to_string()))?
.map_err(IdeError::unavailable)
}
ide_command::domain!(flutter: flutter_devices, flutter_devices_refresh, flutter_daemon_restart, flutter_emulator_launch,
flutter_devtools_url);
flutter_devtools_url, flutter_widget_preview_url);
+27
Переглянути файл
@@ -413,6 +413,31 @@ pub async fn lsp_signature_help(host: &Host, window: &str, doc: DocId, pos: Pos)
}
}
/// The Flutter Property Editor's arguments of the call at `pos`.
#[command(trust = trusted)]
pub async fn lsp_editable_arguments(
host: &Host,
window: &str,
doc: DocId,
pos: Pos,
) -> IdeResult<Option<EditableArguments>> {
host.project(window)?.lsp.editable_arguments(doc, pos).await
}
/// Sets an argument of the call at `pos`; the edit reaches the document as the server's
/// `workspace/applyEdit`, undoable like any other.
#[command(trust = trusted)]
pub async fn lsp_edit_argument(
host: &Host,
window: &str,
doc: DocId,
pos: Pos,
name: String,
value: Option<ArgumentValue>,
) -> IdeResult<()> {
host.project(window)?.lsp.edit_argument(doc, pos, name, value).await
}
#[command(trust = trusted)]
pub async fn lsp_goto(host: &Host, window: &str, doc: DocId, pos: Pos, kind: GotoKind) -> IdeResult<Vec<Location>> {
let target = position_document(host, window, doc, pos).await?;
@@ -3200,6 +3225,8 @@ ide_command::domain!(
lsp_completion,
lsp_document_colors,
lsp_document_highlights,
lsp_edit_argument,
lsp_editable_arguments,
lsp_document_links,
lsp_exception_class_at,
lsp_execute_code_action,
+7
Переглянути файл
@@ -407,6 +407,13 @@ pub fn set_settings(
if key == "vcs" || key == "vcs.git" || key == "vcs.git.executable" {
host.apply_git_executable();
}
// `flutter daemon` and DevTools run on the Flutter SDK; the next request starts DevTools again.
if ["languages", "languages.flutter", "languages.flutter.sdk"].contains(&key) {
for project in affected() {
project.flutter.sdk_changed();
project.devtools.stop();
}
}
if is_proxy {
host.apply_proxy();
}
+20 -6
Переглянути файл
@@ -391,8 +391,10 @@ async fn start_inner(
if config.command.is_empty() {
return Err(IdeError::invalid("run configuration has no command"));
}
let on_target = config.extras.target.as_deref().is_some_and(|t| !t.is_empty());
add_java_agents(&mut config, &on_output, !on_target);
// A JVM on a run target gets no plugin agents; a local one gets them once its JDK is resolved.
if config.extras.target.as_deref().is_some_and(|t| !t.is_empty()) {
add_java_agents(&mut config, &on_output, None);
}
// Settings › Run Targets: over SSH, or in a container.
if config.kind == "tomcat" && config.extras.target.as_deref().is_some_and(|t| !t.is_empty()) {
return Err(IdeError::invalid("Tomcat Local requires the local machine"));
@@ -483,6 +485,8 @@ async fn start_inner(
);
ide_sdk::go::apply_to_run(&mut config, &settings.languages.go.build_tags);
}
let run_dir = project.root.join(config.cwd.as_deref().unwrap_or(Path::new("")));
add_java_agents(&mut config, &on_output, Some(&run_dir));
if config.command == ide_sdk::godot::COMMAND {
return Err(IdeError::unavailable(ide_sdk::godot::NOT_FOUND));
}
@@ -555,14 +559,24 @@ async fn start_inner(
/// Plugins' Java agents (`[[contributes.javaAgents]]`, granted `java.agent`) for the JVM of an
/// Application, Spring Boot or JAR Application configuration started on this machine. A JVM on a
/// run target gets none; the console says so, and why an approved agent was left out.
fn add_java_agents(config: &mut RunConfig, on_output: &Emit<OutputChunk>, local: bool) {
fn add_java_agents(config: &mut RunConfig, on_output: &Emit<OutputChunk>, run_dir: Option<&Path>) {
if !ide_run::java_agent::applies(&config.kind) {
return;
}
let java = std::path::Path::new(&config.command);
let agents = ide_run::java_agent::current_for(Some(java));
// The JVM the launch starts: a bare `java` (what generated configurations name) is looked
// up the way the process start finds it, so the `jdk` filter of `vmOptions` sees that JDK.
let java = run_dir.and_then(|dir| {
let search = ide_run::wrap::search_path_in(config, dir);
let home = config
.env
.get("JAVA_HOME")
.map(std::path::PathBuf::from)
.or_else(|| std::env::var_os("JAVA_HOME").map(std::path::PathBuf::from));
ide_run::java_agent::launched_java(&config.command, &search, home.as_deref())
});
let agents = ide_run::java_agent::current_for(java.as_deref());
let say = |text: &str| on_output(OutputChunk::System { text: format!("{text}\n") });
if !local {
if run_dir.is_none() {
if !agents.options.is_empty() {
say(
"Plugin Java agents were not added: they load only into JVMs started on this machine, not on a run target.",
+22
Переглянути файл
@@ -470,6 +470,27 @@ pub async fn sdk_jdk_at(path: String) -> IdeResult<Option<Sdk>> {
blocking_value(move || ide_sdk::java::jdk_at(std::path::Path::new(&path)).map(|j| ide_sdk::jdk_sdk(&j))).await
}
/// `flutter --version --machine` of the Flutter SDK at `path`, or of the `flutter` on the
/// search path when `path` is empty; `None` when there is no Flutter SDK.
#[command(trust = trusted)]
pub async fn sdk_flutter_at(
host: &Host,
window: &str,
path: String,
) -> IdeResult<Option<ide_sdk::flutter::FlutterVersion>> {
let root = host.project(window).ok().map(|p| p.root.clone());
blocking_value(move || {
let root = root.unwrap_or_default();
let sdk = match ide_sdk::apply::setting_path(&root, &path) {
Some(sdk) => Some(sdk),
None => ide_core::tool_path::find_command("flutter", &ide_core::tool_path::search_path_in(&root), &root)
.and_then(|f| ide_sdk::flutter::sdk_of(&f)),
};
sdk.and_then(|sdk| ide_sdk::flutter::version(&sdk))
})
.await
}
#[cfg(all(test, unix))]
mod tests {
use super::*;
@@ -628,6 +649,7 @@ mod tests {
ide_command::domain!(
sdk:
sdk_detect,
sdk_flutter_at,
sdk_jdk_at,
sdk_locate_tools,
sdk_php_composer_install,
+29 -5
Переглянути файл
@@ -68,7 +68,9 @@ pub struct Project {
/// Flutter's devices; its daemon starts when the UI first asks for them.
pub(crate) flutter: ide_flutter::FlutterDaemon,
/// Flutter DevTools; its server starts when the UI first asks for it.
pub(crate) devtools: ide_flutter::DevToolsServer,
pub(crate) devtools: ide_flutter::ToolServer,
/// Flutter Widget Preview; its server starts when its tool window first opens.
pub(crate) widget_preview: ide_flutter::ToolServer,
pub(crate) kotlin_bridge: Option<Arc<crate::kotlin_bridge::KotlinBridge>>,
pub(crate) phpstan: Option<Arc<crate::phpstan::Phpstan>>,
pub(crate) watcher: Arc<Watcher>,
@@ -644,8 +646,16 @@ impl Host {
let project = Arc::new(Project {
plugin_diagnostics,
trusted,
flutter: ide_flutter::FlutterDaemon::new(root.clone(), sink.clone()),
devtools: ide_flutter::DevToolsServer::new(root.clone()),
flutter: ide_flutter::FlutterDaemon::new(
root.clone(),
sink.clone(),
flutter_tool(&root, &settings, "flutter"),
),
devtools: ide_flutter::ToolServer::devtools(root.clone(), flutter_tool(&root, &settings, "dart")),
widget_preview: ide_flutter::ToolServer::widget_preview(
root.clone(),
flutter_tool(&root, &settings, "flutter"),
),
root,
sink,
languages,
@@ -895,8 +905,16 @@ impl Host {
let project = Arc::new(Project {
plugin_diagnostics,
trusted: Arc::new(AtomicBool::new(false)),
flutter: ide_flutter::FlutterDaemon::new(dir.clone(), sink.clone()),
devtools: ide_flutter::DevToolsServer::new(dir.clone()),
flutter: ide_flutter::FlutterDaemon::new(
dir.clone(),
sink.clone(),
flutter_tool(&dir, &settings, "flutter"),
),
devtools: ide_flutter::ToolServer::devtools(dir.clone(), flutter_tool(&dir, &settings, "dart")),
widget_preview: ide_flutter::ToolServer::widget_preview(
dir.clone(),
flutter_tool(&dir, &settings, "flutter"),
),
sink,
languages,
settings,
@@ -1024,6 +1042,12 @@ fn light_watcher(
)
}
/// `flutter` / `dart` as Settings › Flutter chooses them, read each time the daemon or DevTools starts.
fn flutter_tool(root: &Path, settings: &Arc<SettingsStore>, command: &'static str) -> ide_flutter::Configured {
let (root, settings) = (root.to_path_buf(), settings.clone());
Box::new(move || ide_sdk::apply::tool_command(&root, &settings.effective(), command))
}
/// Looks for repositories nested below the project (and the one containing it);
/// emits `VcsChanged` when the set of roots changed.
fn scan_repositories(
+1
Переглянути файл
@@ -287,6 +287,7 @@ impl crate::Host {
project.agents.shutdown();
project.flutter.stop();
project.devtools.stop();
project.widget_preview.stop();
self.processes.kill_project(&project.root);
project.notebooks.restrict().await;
let windows: Vec<_> = self
+7
Переглянути файл
@@ -26,6 +26,12 @@ pub use filter::walk_skips;
pub use worker::MAX_SYMBOL_FILE;
use worker::{Job, MAX_RECENT, Shared};
/// Stack of the indexing threads. Parsing and outlining a deeply nested file (generated
/// code, a big JSON or minified script) recurse as deep as the file nests; the 2 MiB a Rust
/// thread gets by default overflowed on Windows and took the whole IDE down (#5739). Only
/// what a thread touches is committed, so the reservation costs address space, not memory.
const INDEX_STACK: usize = 32 * 1024 * 1024;
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct FileMatch {
@@ -150,6 +156,7 @@ impl ProjectIndex {
let shared = shared.clone();
std::thread::Builder::new()
.name("openidea-index".into())
.stack_size(INDEX_STACK)
.spawn(move || shared.run(scan))
.map_err(|e| ide_core::IdeError::internal(format!("cannot start indexer: {e}")))?
};
+1
Переглянути файл
@@ -22,6 +22,7 @@ use std::time::{Duration, Instant, SystemTime};
static INDEX_POOL: LazyLock<rayon::ThreadPool> = LazyLock::new(|| {
rayon::ThreadPoolBuilder::new()
.thread_name(|i| format!("openidea-index-{i}"))
.stack_size(crate::INDEX_STACK)
.build()
.expect("cannot build index thread pool")
});
+1 -1
Переглянути файл
@@ -320,7 +320,7 @@ mod tests {
})
.unwrap();
assert_eq!(json, "{\"threadDump\":{}}");
let prefix = format!("Thread.dump_to_file -format=json \"{}/threads-42-", dir.display());
let prefix = format!("Thread.dump_to_file -format=json \"{}", dir.join("threads-42-").display());
assert!(sent.starts_with(&prefix) && sent.ends_with(".json\""), "{sent}");
assert!(is_empty(&dir));
}
+29
Переглянути файл
@@ -87,6 +87,7 @@ use std::time::Duration;
use text::{DocText, Encoding};
use types::*;
const DART_SERVER: &str = "dart";
const DEFAULT_TIMEOUT: Duration = Duration::from_secs(10);
const COMPLETION_TIMEOUT: Duration = Duration::from_secs(5);
const LONG_TIMEOUT: Duration = Duration::from_secs(30);
@@ -2448,6 +2449,34 @@ impl LspManager {
.then(|| outline.items.clone())
}
/// The arguments of the call at `pos` the Flutter Property Editor shows; `None` outside a
/// call, or when no Dart server serves the document.
pub async fn editable_arguments(&self, doc: DocId, pos: Pos) -> IdeResult<Option<EditableArguments>> {
let (snap, targets) = self.doc_targets(doc, "the property editor", |_| true).await?;
let Some(t) = targets.iter().find(|t| t.server.name == DART_SERVER) else { return Ok(None) };
self.call(t, "dart/textDocument/editableArguments", snap.pos_params(t, pos), None, DEFAULT_TIMEOUT).await
}
/// Sets the argument `name` of the call at `pos` to `value` (`None` passes null). The server
/// sends the edit back as `workspace/applyEdit`, which the apply-edit hook applies.
pub async fn edit_argument(
&self,
doc: DocId,
pos: Pos,
name: String,
value: Option<ArgumentValue>,
) -> IdeResult<()> {
let (snap, targets) = self.doc_targets(doc, "the property editor", |_| true).await?;
let t = targets
.iter()
.find(|t| t.server.name == DART_SERVER)
.ok_or_else(|| IdeError::unavailable("no Dart language server serves this document"))?;
let mut params = snap.pos_params(t, pos);
params["edit"] = json!({ "name": name, "newValue": value });
let _: Value = self.call(t, "dart/textDocument/editArgument", params, None, DEFAULT_TIMEOUT).await?;
Ok(())
}
/// Records a published outline; whether what the open documents of `path` show changed.
fn set_flutter_outline(
&self,
+54
Переглянути файл
@@ -654,3 +654,57 @@ pub struct ClassifiedReference {
#[specta(optional)]
pub text: Option<String>,
}
/// The arguments the Flutter Property Editor edits: those of the widget (or other) call at a
/// position, as the Dart server's `dart/textDocument/editableArguments` reports them.
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct EditableArguments {
/// The widget's (or callee's) name.
pub name: Option<String>,
pub documentation: Option<String>,
pub arguments: Vec<EditableArgument>,
}
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct EditableArgument {
pub name: String,
pub documentation: Option<String>,
/// How to edit it: `string`, `int`, `double`, `bool` or `enum`.
#[serde(rename = "type")]
pub kind: String,
/// The literal value in the code (only while `has_argument`); an expression has `display_value`.
pub value: Option<ArgumentValue>,
#[serde(default)]
pub has_argument: bool,
pub default_value: Option<ArgumentValue>,
pub display_value: Option<String>,
// Absent from older Dart SDKs (`isDeprecated` came later): read as false rather than
// failing the whole list.
#[serde(default)]
pub is_required: bool,
#[serde(default)]
pub is_nullable: bool,
#[serde(default)]
pub is_deprecated: bool,
#[serde(default = "editable_by_default")]
pub is_editable: bool,
pub not_editable_reason: Option<String>,
/// An enum's values, as `EnumName.value`.
pub options: Option<Vec<String>>,
}
fn editable_by_default() -> bool {
true
}
/// A literal argument value. Ints stay ints: the server rejects `1.0` for an `int` parameter.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(untagged)]
pub enum ArgumentValue {
Bool(bool),
Int(i64),
Double(f64),
Text(String),
}
+79
Переглянути файл
@@ -1549,6 +1549,85 @@ async fn flutter_outline_follows_the_document_and_the_server_instance() {
assert!(h.mgr.flutter_outline(reopened).is_none());
}
#[tokio::test(flavor = "multi_thread")]
async fn property_editor_lists_the_dart_servers_arguments_and_applies_its_edit() {
let h = harness(&[("dart", incremental_caps())]);
let (doc, path) = h.open("a.mk", "Text('x')\n");
h.wait_status("dart", ServerStatus::Ready).await;
let s = h.launcher.state("dart");
let arg = |name: &str, extra: Value| {
let mut a = json!({ "name": name, "hasArgument": false, "isRequired": false, "isNullable": true,
"isDeprecated": false, "isEditable": true });
a.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());
a
};
let at = json!({"start":{"line":0,"character":0},"end":{"line":0,"character":9}});
s.respond(
"dart/textDocument/editableArguments",
json!({ "textDocument": { "uri": uri_of(&path), "version": 1 }, "name": "Text", "range": at, "arguments": [
arg("data", json!({ "type": "string", "value": "x", "hasArgument": true, "isRequired": true, "isNullable": false })),
arg("textAlign", json!({ "type": "enum", "options": ["TextAlign.left", "TextAlign.center"] })),
arg("maxLines", json!({ "type": "int", "value": 2, "hasArgument": true })),
// An older SDK leaves out flags it doesn't know yet.
json!({ "name": "softWrap", "type": "bool", "hasArgument": false }),
]}),
);
let args = h.mgr.editable_arguments(doc, Pos::new(0, 2)).await.unwrap().unwrap();
assert_eq!(args.name.as_deref(), Some("Text"));
assert_eq!(
(args.arguments[0].kind.as_str(), args.arguments[0].value.clone()),
("string", Some(ArgumentValue::Text("x".into())))
);
assert_eq!(args.arguments[1].options.as_ref().unwrap()[1], "TextAlign.center");
assert_eq!(args.arguments[1].value, None);
assert!(args.arguments[3].is_editable && !args.arguments[3].is_deprecated && !args.arguments[3].is_required);
assert_eq!(args.arguments[2].value, Some(ArgumentValue::Int(2)));
let asked = s.requested("dart/textDocument/editableArguments");
assert_eq!(asked[0]["position"], json!({"line":0,"character":2}));
// The server answers editArgument with null and sends the edit as workspace/applyEdit.
let applied: Arc<Mutex<Vec<WorkspaceEdit>>> = Arc::default();
let received = applied.clone();
h.mgr.set_apply_edit_hook(Box::new(move |e| {
received.lock().push(e);
true
}));
let uri = uri_of(&path);
*s.responder.lock() = Some(Arc::new(move |s, method, _| {
(method == "dart/textDocument/editArgument").then(|| {
let edit = json!({ "changes": { uri.clone(): [{ "range":
{"start":{"line":0,"character":5},"end":{"line":0,"character":8}}, "newText": "'y'" }] } });
let reply: Value = tokio::task::block_in_place(|| {
tokio::runtime::Handle::current().block_on(s.peer().request(
"workspace/applyEdit",
json!({ "edit": edit }),
None,
))
})
.unwrap();
assert_eq!(reply, json!({"applied": true}));
Value::Null
})
}));
h.mgr.edit_argument(doc, Pos::new(0, 2), "data".into(), Some(ArgumentValue::Text("y".into()))).await.unwrap();
let sent = s.requested("dart/textDocument/editArgument");
assert_eq!(sent[0]["edit"], json!({ "name": "data", "newValue": "y" }));
assert_eq!(sent[0]["position"], json!({"line":0,"character":2}));
let edits = applied.lock().clone();
assert!(
matches!(&edits[..], [e] if matches!(&e.files[0], FileEdit::Edit { edits, .. } if edits[0].new_text == "'y'"))
);
}
#[tokio::test(flavor = "multi_thread")]
async fn property_editor_has_nothing_without_a_dart_server() {
let h = harness(&[("mock", incremental_caps())]);
let (doc, _) = h.open("a.mk", "Text('x')\n");
h.wait_status("mock", ServerStatus::Ready).await;
assert!(h.mgr.editable_arguments(doc, Pos::new(0, 2)).await.unwrap().is_none());
assert!(h.launcher.state("mock").requested("dart/textDocument/editableArguments").is_empty());
}
#[tokio::test(flavor = "multi_thread")]
async fn closing_labels_join_the_inlay_hints_until_the_next_edit() {
let h = harness(&[("mock", incremental_caps())]);
+57
Переглянути файл
@@ -123,6 +123,27 @@ fn is_jetbrains_jdk(java: &Path) -> bool {
release_field(java, "IMPLEMENTOR").is_some_and(|v| v.to_ascii_lowercase().contains("jetbrains"))
}
/// The JVM a configuration whose command is `command` starts, for the JDK filter. A path is
/// itself. A bare `java` is the first one on `search`, as the launch finds it; when that is
/// no JDK's own launcher (macOS's `/usr/bin/java` stub, which runs `JAVA_HOME`'s), it is
/// `java_home`'s. `None` when neither is found.
pub fn launched_java(command: &str, search: &std::ffi::OsStr, java_home: Option<&Path>) -> Option<PathBuf> {
let path = Path::new(command);
if path.components().count() > 1 {
return Some(path.to_path_buf());
}
let windows = cfg!(windows);
let found =
ide_core::process::find_executable_in(command, search, windows, std::env::var("PATHEXT").ok().as_deref());
if let Some(java) = &found
&& release_field(java, "JAVA_VERSION").is_some()
{
return found;
}
let java = java_home.map(|home| home.join("bin").join(if windows { "java.exe" } else { "java" }));
java.filter(|java| java.is_file()).or(found)
}
/// `KEY="value"` from the JDK `release` file next to `bin/java` (or JDK 8's `jre/bin/java`).
fn release_field(java: &Path, key: &str) -> Option<String> {
let java = std::fs::canonicalize(java).unwrap_or_else(|_| java.to_path_buf());
@@ -226,6 +247,42 @@ fn split_text(text: &str) -> Vec<String> {
mod tests {
use super::*;
/// A JDK home with `bin/java` and a `release` file naming `implementor`.
#[cfg(unix)]
fn jdk(root: &Path, name: &str, implementor: &str) -> PathBuf {
let home = root.join(name);
std::fs::create_dir_all(home.join("bin")).unwrap();
std::fs::write(home.join("bin/java"), "#!/bin/sh\n").unwrap();
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(home.join("bin/java"), std::fs::Permissions::from_mode(0o755)).unwrap();
std::fs::write(home.join("release"), format!("JAVA_VERSION=\"21\"\nIMPLEMENTOR=\"{implementor}\"\n")).unwrap();
home
}
#[cfg(unix)]
#[test]
fn a_bare_java_is_the_one_the_launch_finds() {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().unwrap();
let jbr = jdk(dir.path(), "jbr", "JetBrains s.r.o.");
let openjdk = jdk(dir.path(), "openjdk", "Eclipse Adoptium");
// A JDK's own launcher on the search path is what runs, whatever JAVA_HOME says.
let search = std::env::join_paths([jbr.join("bin")]).unwrap();
let java = launched_java("java", &search, Some(&openjdk)).unwrap();
assert!(jdk_allows(Some(&java), Some("jetbrains")));
// A stub outside any JDK (macOS /usr/bin/java) runs JAVA_HOME's.
let stub = dir.path().join("usr/bin");
std::fs::create_dir_all(&stub).unwrap();
std::fs::write(stub.join("java"), "#!/bin/sh\n").unwrap();
std::fs::set_permissions(stub.join("java"), std::fs::Permissions::from_mode(0o755)).unwrap();
let search = std::env::join_paths([stub]).unwrap();
let java = launched_java("java", &search, Some(&jbr)).unwrap();
assert!(jdk_allows(Some(&java), Some("jetbrains")));
assert!(!jdk_allows(launched_java("java", &search, Some(&openjdk)).as_deref(), Some("jetbrains")));
// A path is itself.
assert_eq!(launched_java("/opt/jdk/bin/java", &search, Some(&jbr)), Some(PathBuf::from("/opt/jdk/bin/java")));
}
fn strings(a: &[&str]) -> Vec<String> {
a.iter().map(|s| (*s).to_owned()).collect()
}
+27 -6
Переглянути файл
@@ -1184,13 +1184,31 @@ pub fn tool_command(root: &Path, s: &Settings, command: &str) -> Option<PathBuf>
if command == godot::COMMAND {
return godot::find(custom);
}
custom
custom.or_else(|| flutter_sdk_tool(root, s, command))
}
/// `flutter` / `dart` of the Flutter SDK in Settings › Languages & Frameworks › Flutter, else
/// `None` (the search path). Dart is the SDK's own (`bin/cache/dart-sdk`), else its `bin/dart`
/// wrapper, which downloads it on first use.
pub fn flutter_sdk_tool(root: &Path, s: &Settings, command: &str) -> Option<PathBuf> {
let bin = setting_path(root, &s.languages.flutter.sdk)?.join("bin");
let script = |name: &str| bin.join(if cfg!(windows) { format!("{name}.bat") } else { name.to_owned() });
match command {
"flutter" => Some(script("flutter")),
"dart" => Some(
Some(bin.join("cache/dart-sdk/bin").join(exe("dart")))
.filter(|d| d.is_file())
.unwrap_or_else(|| script("dart")),
),
_ => None,
}
}
/// Points a run configuration launching a bare tool name at the executable from
/// [`tool_command`] (Godot apps live outside the search path).
/// [`tool_command`] (Godot apps live outside the search path; `flutter` / `dart` follow the
/// Flutter SDK setting).
pub fn resolve_run_command(config: &mut RunConfig, root: &Path, s: &Settings) {
if config.command == godot::COMMAND
if matches!(config.command.as_str(), godot::COMMAND | "flutter" | "dart")
&& let Some(path) = tool_command(root, s, &config.command)
{
config.command = path.to_string_lossy().into_owned();
@@ -2207,9 +2225,12 @@ pub fn without_derived_in(config: &RunConfig, root: &Path, fallback: Option<&Pat
&& let Some(name) = path.file_name().map(|n| n.to_string_lossy().into_owned())
{
// Generated configurations name the bare program (`java`), also on Windows where the
// derived path ends in `java.exe`.
let bare =
name.len().checked_sub(4).filter(|&at| name[at..].eq_ignore_ascii_case(".exe")).map(|at| &name[..at]);
// derived path ends in `java.exe` (`flutter.bat`).
let bare = name
.len()
.checked_sub(4)
.filter(|&at| name[at..].eq_ignore_ascii_case(".exe") || name[at..].eq_ignore_ascii_case(".bat"))
.map(|at| &name[..at]);
for candidate in bare.into_iter().chain([name.as_str()]) {
let mut probe = out.clone();
probe.command = candidate.to_owned();
+7 -1
Переглянути файл
@@ -32,6 +32,7 @@ pub fn detect(kind: SdkKind, root: Option<&Path>) -> Vec<Sdk> {
SdkKind::Ruby => crate::ruby::detect(root),
SdkKind::Zig => zig(),
SdkKind::Dotnet => dotnet(),
SdkKind::Flutter => crate::flutter::detect(),
};
if let Some(root) = root {
pinned_first(&mut out, kind, root);
@@ -48,7 +49,12 @@ fn tool_of(kind: SdkKind) -> Option<Tool> {
SdkKind::Maven => Some(Tool::Maven),
SdkKind::Ruby => Some(Tool::Ruby),
SdkKind::Zig => Some(Tool::Zig),
SdkKind::Php | SdkKind::PackageManager | SdkKind::Rust | SdkKind::TypeScript | SdkKind::Dotnet => None,
SdkKind::Php
| SdkKind::PackageManager
| SdkKind::Rust
| SdkKind::TypeScript
| SdkKind::Dotnet
| SdkKind::Flutter => None,
}
}
+121
Переглянути файл
@@ -0,0 +1,121 @@
//! Flutter SDKs: Settings › Languages & Frameworks › Flutter (the Flutter plugin's "Flutter SDK path").
use crate::exec::query_in;
use crate::{Sdk, home_dir};
use serde::{Deserialize, Serialize};
use specta::Type;
use std::path::{Path, PathBuf};
use std::time::Duration;
/// `flutter --version` may first unpack the Dart SDK or print the analytics notice.
const VERSION_TIMEOUT: Duration = Duration::from_secs(60);
/// What `flutter --version --machine` reports of an SDK.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase", default)]
pub struct FlutterVersion {
/// SDK root (not part of Flutter's answer).
pub root: String,
pub framework_version: String,
pub channel: Option<String>,
pub dart_sdk_version: Option<String>,
}
pub(crate) fn flutter_script(sdk: &Path) -> PathBuf {
sdk.join("bin").join(if cfg!(windows) { "flutter.bat" } else { "flutter" })
}
/// The SDK root of a `flutter` executable; on the search path it is often a link into the SDK.
pub fn sdk_of(flutter: &Path) -> Option<PathBuf> {
let real = dunce::canonicalize(flutter).ok()?;
let root = real.parent()?.parent()?;
flutter_script(root).is_file().then(|| root.to_path_buf())
}
/// `flutter --version --machine` of the SDK at `sdk`. `None` when `sdk` holds no `bin/flutter`;
/// an empty `framework_version` when it did not answer.
pub fn version(sdk: &Path) -> Option<FlutterVersion> {
let flutter = flutter_script(sdk);
if !flutter.is_file() {
return None;
}
let out = query_in(&flutter, &["--version", "--machine"], Some(sdk), &[], VERSION_TIMEOUT).unwrap_or_default();
let mut version = parse_version(&out).unwrap_or_default();
version.root = sdk.to_string_lossy().into_owned();
Some(version)
}
/// The JSON object of `flutter --version --machine`, after anything it printed first.
fn parse_version(out: &str) -> Option<FlutterVersion> {
let json = &out[out.find('{')?..=out.rfind('}')?];
serde_json::from_str(json).ok()
}
/// The framework version an SDK records, without running it.
fn recorded_version(sdk: &Path) -> Option<String> {
let json = std::fs::read_to_string(sdk.join("bin/cache/flutter.version.json")).ok();
json.and_then(|j| parse_version(&j))
.map(|v| v.framework_version)
.or_else(|| std::fs::read_to_string(sdk.join("version")).ok().map(|v| v.trim().to_owned()))
.filter(|v| !v.is_empty())
}
/// Flutter SDKs: the one on the search path, fvm's and the usual install folders.
pub(crate) fn detect() -> Vec<Sdk> {
let mut roots: Vec<(PathBuf, &str)> = Vec::new();
if let Some(sdk) = crate::exec::which("flutter").and_then(|f| sdk_of(&f)) {
roots.push((sdk, "path"));
}
if let Some(home) = home_dir() {
for dir in ["flutter", "development/flutter", "sdk/flutter"] {
roots.push((home.join(dir), "system"));
}
if let Ok(versions) = std::fs::read_dir(home.join("fvm/versions")) {
roots.extend(versions.flatten().map(|e| (e.path(), "fvm")));
}
}
let mut seen = std::collections::HashSet::new();
roots
.into_iter()
.filter(|(sdk, _)| flutter_script(sdk).is_file())
.filter(|(sdk, _)| seen.insert(dunce::canonicalize(sdk).unwrap_or_else(|_| sdk.clone())))
.map(|(sdk, source)| {
let version = recorded_version(&sdk);
Sdk {
path: sdk.clone().into(),
name: format!("Flutter {}", version.as_deref().unwrap_or_default()).trim().to_owned(),
version,
source: source.to_owned(),
home: Some(sdk.into()),
extra: None,
}
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn reads_the_version_after_what_flutter_printed_first() {
let out = "Downloading Dart SDK…\n{\n \"frameworkVersion\": \"3.38.1\",\n \"channel\": \"stable\",\n \"dartSdkVersion\": \"3.10.0\"\n}\n";
let v = parse_version(out).unwrap();
assert_eq!(
(v.framework_version.as_str(), v.channel.as_deref(), v.dart_sdk_version.as_deref()),
("3.38.1", Some("stable"), Some("3.10.0"))
);
assert_eq!(parse_version("flutter: command not found"), None);
}
#[test]
fn a_folder_without_bin_flutter_is_no_sdk() {
let dir = tempfile::tempdir().unwrap();
assert_eq!(version(dir.path()), None);
std::fs::create_dir_all(dir.path().join("bin/cache")).unwrap();
std::fs::write(flutter_script(dir.path()), "").unwrap();
std::fs::write(dir.path().join("bin/cache/flutter.version.json"), r#"{"frameworkVersion":"3.35.0"}"#).unwrap();
assert_eq!(recorded_version(dir.path()).as_deref(), Some("3.35.0"));
assert_eq!(sdk_of(&flutter_script(dir.path())), Some(dunce::canonicalize(dir.path()).unwrap()));
}
}
+3
Переглянути файл
@@ -12,6 +12,7 @@ mod astro;
pub mod container_python;
mod discover;
mod exec;
pub mod flutter;
pub mod go;
pub mod godot;
pub mod java;
@@ -57,6 +58,8 @@ pub enum SdkKind {
Zig,
/// .NET SDKs of the `dotnet` on the search path; `version` is what `global.json` pins.
Dotnet,
/// Flutter SDK roots.
Flutter,
}
/// One installed interpreter / toolchain.
+50 -1
Переглянути файл
@@ -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;
use std::path::{Path, PathBuf};
use std::time::Duration;
fn fake_venv(root: &Path, name: &str) -> std::path::PathBuf {
@@ -2058,6 +2058,55 @@ fn the_godot_setting_applies_to_server_debugger_and_run_configurations() {
assert_eq!(crate::apply::tool_command(tmp.path(), &s, "zls"), None);
}
#[test]
fn the_flutter_sdk_setting_picks_flutter_and_dart_for_server_and_run_configurations() {
let tmp = tempfile::tempdir().unwrap();
let sdk = tmp.path().join("flutter");
let run = |command: &str| RunConfig {
id: "dart:pub get".into(),
name: "pub get".into(),
kind: "dart-command".into(),
command: command.into(),
args: vec!["pub".into(), "get".into()],
cwd: None,
env: BTreeMap::new(),
detected: true,
is_test: false,
debug_adapter: None,
allow_parallel: false,
extras: Default::default(),
};
// No setting: the names stay for the search path.
let mut s = Settings::default();
let mut plain = run("flutter");
apply_to_run_configs(std::slice::from_mut(&mut plain), tmp.path(), &s);
assert_eq!(plain.command, "flutter");
assert_eq!(crate::apply::tool_command(tmp.path(), &s, "dart"), None);
// A project-relative SDK: `bin/flutter`, and `bin/dart` until the Dart SDK is unpacked.
s.languages.flutter.sdk = "flutter".into();
let flutter = sdk.join("bin").join(if cfg!(windows) { "flutter.bat" } else { "flutter" });
let wrapper = sdk.join("bin").join(if cfg!(windows) { "dart.bat" } else { "dart" });
assert_eq!(crate::apply::tool_command(tmp.path(), &s, "dart"), Some(wrapper));
let dart = sdk.join("bin/cache/dart-sdk/bin").join(exe("dart"));
std::fs::create_dir_all(dart.parent().unwrap()).unwrap();
std::fs::write(&dart, "").unwrap();
let mut cfg = server("dart");
configure_server(&mut cfg, tmp.path(), tmp.path(), &s);
assert_eq!(Path::new(&cfg.command), dart);
let mut configs = [run("flutter"), run("dart"), run("/usr/bin/flutter")];
apply_to_run_configs(&mut configs, tmp.path(), &s);
assert_eq!(Path::new(&configs[0].command), flutter);
assert_eq!(Path::new(&configs[1].command), dart);
assert_eq!(configs[2].command, "/usr/bin/flutter");
// 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")));
}
#[test]
fn python_library_paths_are_parsed_and_deduplicated() {
let tmp = tempfile::tempdir().unwrap();
+1 -1
Переглянути файл
@@ -164,7 +164,7 @@ Each form has **Host** and **Port** fields and shows the command to start the re
- **Java HotSwap**: **Run › Debugging Actions › Reload Changed Classes** compiles your changes and reloads the changed classes into the running Java debug session. Active frames keep running the old code until they return. When JDT LS finishes a build after a save, the IDE offers the reload.
- **JavaScript in the browser**: a **JavaScript Debug** configuration opens a URL in Chrome or Edge and debugs the page's scripts in their sources through source maps. See [JavaScript and TypeScript](/en/languages/javascript#debugging).
- **Maven and Gradle**: debugging a Maven or Gradle configuration starts the JVM with a JDWP agent and attaches java-debug to it.
- **Dart / Flutter**: **Hot Reload** and **Hot Restart** are available while a Dart session is running. In a Flutter project, the device selector next to the run configuration chooses where Run and Debug start the app; a run configuration's **Device** field pins it to one device. A Flutter configuration also sets the **Build mode** (Debug, Profile or Release; Profile and Release run without the debugger or hot reload), **Build flavor** and **Additional run args** (such as `--dart-define=KEY=value`); **Run › Flutter Attach** attaches the debugger to the app of the selected Flutter configuration that was started elsewhere (an add-to-app host), passing its **Additional attach args** to `flutter attach`. Saving a Dart file of a running Flutter debug session also hot reloads the app, unless the file has errors. Turn this off with **Hot reload on save** in **Settings › Build, Execution, Deployment › Debugger**.
- **Dart / Flutter**: **Settings › Languages & Frameworks › Flutter › Flutter SDK path** chooses the Flutter SDK whose `flutter` and Dart the language server, the debugger, run configurations, pub commands, the device list and **Build › Flutter** use; empty uses the ones on `PATH`. **Hot Reload** and **Hot Restart** are available while a Dart session is running. In a Flutter project, the device selector next to the run configuration chooses where Run and Debug start the app; a run configuration's **Device** field pins it to one device. A Flutter configuration also sets the **Build mode** (Debug, Profile or Release; Profile and Release run without the debugger or hot reload), **Build flavor** and **Additional run args** (such as `--dart-define=KEY=value`); **Run › Flutter Attach** attaches the debugger to the app of the selected Flutter configuration that was started elsewhere (an add-to-app host), passing its **Additional attach args** to `flutter attach`. Saving a Dart file of a running Flutter debug session also hot reloads the app, unless the file has errors. Turn this off with **Hot reload on save** in **Settings › Build, Execution, Deployment › Debugger**.
- **PHP**: if the PHP interpreter does not load Xdebug, breakpoints are skipped; the IDE warns about this when the session starts.
- **Python**: **Settings › Build, Execution, Deployment › Python Debugger** has **Attach to subprocess automatically while debugging** and **Gevent compatible**.
+1 -1
Переглянути файл
@@ -166,7 +166,7 @@ C 和 C++ 的配置也可以改用 GDB 14 及以上版本(`gdb -i dap`):
- **Java HotSwap**:**运行 › 调试操作 › 重新加载已更改的类** 编译改动,并把变化的类重新加载到正在运行的 Java 调试会话中。已经在执行的帧要等返回后才会用上新代码。保存后 JDT LS 自动完成构建时,IDE 也会提示是否重新加载。
- **浏览器中的 JavaScript**:**JavaScript 调试** 配置在 Chrome 或 Edge 中打开一个 URL,通过 source map 在源码中调试页面脚本。见 [JavaScript 与 TypeScript](/zh/languages/javascript)。
- **Maven 和 Gradle**:调试 Maven 或 Gradle 配置时,IDE 会让 JVM 带上 JDWP agent 启动,再用 java-debug 附加上去。
- **Dart / Flutter**:Dart 会话运行时可以用 **热重载** 和 **热重启**。在 Flutter 项目中,运行配置旁边的设备选择器决定运行和调试在哪台设备上启动应用;运行配置的 **设备** 字段可以固定使用某台设备。Flutter 配置还可以设置 **构建模式**(调试、性能分析或发布;后两者不带调试器,也不能热重载)、**构建 flavor** 和 **附加 run 参数**(例如 `--dart-define=KEY=value`);**运行 › Flutter 附加** 把调试器附加到所选 Flutter 配置在别处启动的应用(例如 add-to-app 的宿主应用),并把 **附加 attach 参数** 传给 `flutter attach`。保存正在运行的 Flutter 调试会话里的 Dart 文件时也会自动热重载,文件有错误时跳过。可在 **设置 › 构建、执行、部署 › 调试器** 中关闭 **保存时热重载**。
- **Dart / Flutter**:**设置 › 语言和框架 › Flutter › Flutter SDK 路径** 选择 Flutter SDK,语言服务器、调试器、运行配置、pub 命令、设备列表和 **构建 › Flutter** 都使用它的 `flutter` 和 Dart;留空则使用 `PATH` 中的。Dart 会话运行时可以用 **热重载** 和 **热重启**。在 Flutter 项目中,运行配置旁边的设备选择器决定运行和调试在哪台设备上启动应用;运行配置的 **设备** 字段可以固定使用某台设备。Flutter 配置还可以设置 **构建模式**(调试、性能分析或发布;后两者不带调试器,也不能热重载)、**构建 flavor** 和 **附加 run 参数**(例如 `--dart-define=KEY=value`);**运行 › Flutter 附加** 把调试器附加到所选 Flutter 配置在别处启动的应用(例如 add-to-app 的宿主应用),并把 **附加 attach 参数** 传给 `flutter attach`。保存正在运行的 Flutter 调试会话里的 Dart 文件时也会自动热重载,文件有错误时跳过。可在 **设置 › 构建、执行、部署 › 调试器** 中关闭 **保存时热重载**。
- **PHP**:如果 PHP 解释器没有加载 Xdebug,断点会被跳过;会话启动时 IDE 会提示。
- **Python**:**设置 › 构建、执行、部署 › Python 调试器** 中有 **调试时自动附加到子进程** 和 **兼容 Gevent**。
+10 -10
Переглянути файл
@@ -313,8 +313,8 @@ for (const surface of ["new", "task"] as const) {
const settings = page.getByRole("button", { name: /^Model settings:/ });
await settings.click();
await expect(page.getByRole("button", { name: "Back to models" })).toHaveCount(0);
await page.getByRole("radio", { name: "Thorough" }).click();
await page.getByRole("radio", { name: "1M" }).click();
await page.getByRole("option", { name: "Thorough" }).click();
await page.getByRole("option", { name: "1M" }).click();
await expect(settings).toHaveText("Thorough · 1M");
await page.keyboard.press("Escape");
await expect(box(page)).toHaveText("Review the project structure");
@@ -418,7 +418,7 @@ test("Settings and effort popup exclude the agent shortcut", async ({ workbench:
await expect(search).toHaveValue("keymap");
await settings.getByRole("button", { name: "Cancel", exact: true }).click();
await effortLabel(page).click();
const popup = page.getByRole("radiogroup", { name: "Effort Level", exact: true });
const popup = page.getByRole("listbox", { name: "Effort Level", exact: true });
await expect(popup).toBeVisible();
await page.keyboard.press("Alt+t");
expect(await ipcCalls(page, "agent_set_config")).toEqual([]);
@@ -642,10 +642,10 @@ test("New Task discovers uncached model effort before the first prompt", async (
await page.evaluate(() => document.dispatchEvent(new Event("test:model-settings-ready")));
await expectEffort(page, "Quick");
await effortLabel(page).click();
const efforts = page.getByRole("radiogroup", { name: "Effort Level", exact: true });
await expect(efforts.getByRole("radio", { name: "Quick", exact: true })).toBeVisible();
await expect(efforts.getByRole("radio", { name: "Thorough", exact: true })).toBeVisible();
await expect(efforts.getByRole("radio", { name: "Gentle", exact: true })).toHaveCount(0);
const efforts = page.getByRole("listbox", { name: "Effort Level", exact: true });
await expect(efforts.getByRole("option", { name: "Quick", exact: true })).toBeVisible();
await expect(efforts.getByRole("option", { name: "Thorough", exact: true })).toBeVisible();
await expect(efforts.getByRole("option", { name: "Gentle", exact: true })).toHaveCount(0);
await page.keyboard.press("Escape");
await expect(box(page)).toHaveText("Keep this first task unsent");
await expectNoSubmission(page);
@@ -675,9 +675,9 @@ test("an existing chat can choose effort for a refreshed model before sending",
await expect(modelButton(page)).toHaveAttribute("title", /^Model: Swift\b/);
await expectEffort(page, "Quick");
await effortLabel(page).click();
const efforts = page.getByRole("radiogroup", { name: "Effort Level", exact: true });
await expect(efforts.getByRole("radio", { name: "Gentle", exact: true })).toHaveCount(0);
await efforts.getByRole("radio", { name: "Thorough", exact: true }).click();
const efforts = page.getByRole("listbox", { name: "Effort Level", exact: true });
await expect(efforts.getByRole("option", { name: "Gentle", exact: true })).toHaveCount(0);
await efforts.getByRole("option", { name: "Thorough", exact: true }).click();
await page.keyboard.press("Escape");
await expectEffort(page, "Thorough");
await expect(send).toBeEnabled();
+6 -7
Переглянути файл
@@ -413,8 +413,7 @@ test("keeps chat history readable and selections free of timestamps and status l
expect(selected).not.toMatch(/AM|PM|5s|Reasoning|Requesting task context/);
await page.keyboard.press("ControlOrMeta+c");
expect(await page.evaluate(() => navigator.clipboard.readText())).toBe(selected);
// The finished turn's reasoning is folded with its work.
await stream.locator("[class*='_turnFold_'] > summary").click();
// The latest turn stays open: its reasoning shows as its own collapsed row.
await stream.locator("[class*='_thought_'] > summary").click();
await expect(stream.locator("[class*='_thoughtPreview_']")).toHaveText("Requesting task context");
await expect(stream.locator("[class*='_thoughtBody_'] strong")).toHaveText("Requesting task context");
@@ -795,8 +794,7 @@ test("Find in Conversation skips user-select:none summaries and closed <details>
}, TASK);
const stream = page.locator("[class*='_stream_']:visible");
const runSummary = stream.locator("details[class*='_processRun_'] > summary");
await runSummary.click();
// A command is its own row, outside the reasoning's run.
await expect(stream.getByText("stop_bash")).toBeVisible();
await stream.focus();
@@ -894,13 +892,14 @@ test("indents process-run thoughts and tool calls clearly and aligns output-less
entries: new Map([
[
task.id,
// Reasoning and read-only calls group into one run; commands and edits would be rows of their own.
[
{ type: "thought", text: "**Checking CI Status**\n\nInspecting workflow runs." },
{
type: "tool",
id: "t1",
title: "gh pr checks 3631 --repo l0ng-ai/openidea",
kind: "execute",
kind: "fetch",
status: "completed",
locations: [],
output: "All checks pending",
@@ -911,7 +910,7 @@ test("indents process-run thoughts and tool calls clearly and aligns output-less
type: "tool",
id: "t2",
title: "read_bash",
kind: "other",
kind: "read",
status: "completed",
locations: [],
output: "E2E pass",
@@ -921,7 +920,7 @@ test("indents process-run thoughts and tool calls clearly and aligns output-less
type: "tool",
id: "t3",
title: "read_bash",
kind: "other",
kind: "read",
status: "running",
locations: [],
output: "",
+14 -9
Переглянути файл
@@ -40,13 +40,17 @@ const entries: AgentEntry[] = Array.from({ length: 80 }, (_, turn): AgentEntry[]
},
]).flat();
async function openHistory(page: Page) {
/** Opens the 80-turn chat; `foldTurns` folds each earlier turn's work into one row. */
async function openHistory(page: Page, foldTurns = false) {
await page.goto("/");
await page.getByRole("tree", { name: "Project" }).waitFor();
await page.evaluate(
async ({ task, entries }) => {
async ({ task, entries, foldTurns }) => {
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,
@@ -58,10 +62,12 @@ async function openHistory(page: Page) {
});
store.openTaskInEditorLocation(task.id);
},
{ task, entries },
{ task, entries, foldTurns },
);
const stream = page.locator("[class*='_stream_']:visible");
await expect(stream.locator(":scope > *")).toHaveCount(80 * 3);
// 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);
await page.evaluate(() => document.fonts.ready);
return stream;
}
@@ -85,7 +91,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 * 3 + 1);
await expect(stream.locator(":scope > *")).toHaveCount(80 * 6 + 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";
@@ -186,7 +192,7 @@ 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);
const stream = await openHistory(page, true);
await stream.evaluate((el) => {
el.scrollTop = 0;
});
@@ -197,9 +203,8 @@ test("opens a folded turn with the keyboard and jumps back to the latest reply",
await summary.focus();
await page.keyboard.press("Enter");
await expect(fold).toHaveAttribute("open", "");
const run = fold.locator("[class*='_processRun_']").first();
await expect(run).toBeVisible();
await run.locator(":scope > summary").click();
// 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 summary.focus();
await page.keyboard.press("Space");
+8 -1
Переглянути файл
@@ -63,7 +63,14 @@ test("the chosen device is used for Run, and replaced while it is disconnected",
await page.keyboard.press("Control+r");
await expect.poll(async () => (await ipcCalls(page, "run_start")).length).toBe(1);
const [started] = await ipcCalls(page, "run_start");
expect((started!.config as { args: string[] }).args).toEqual(["run", "-t", "lib/main.dart", "-d", "chrome"]);
expect((started!.config as { args: string[] }).args).toEqual([
"run",
"-t",
"lib/main.dart",
"-d",
"chrome",
"--machine",
]);
const emit = (devices: unknown[]) =>
page.evaluate(
+43
Переглянути файл
@@ -476,3 +476,46 @@ test("difference navigation focuses and centres the merge result caret with sync
await page.keyboard.press("Shift+F7");
await check(101);
});
test("scrolling one pane sideways scrolls the other two to the same offset", async ({ page }) => {
await page.setViewportSize({ width: 900, height: 600 });
const long = (tag: string) => `const ${tag} = "${"x".repeat(400)}";`;
await mountMerge(page, [
lines(long("base"), "a", "b"),
lines(long("ours"), "a", "b"),
lines(long("theirs"), "a", "b"),
]);
const lefts = () =>
page
.locator("#merge-host .cm-scroller")
.evaluateAll((els) => els.map((el) => Math.round((el as HTMLElement).scrollLeft)));
for (const pane of ["Your version", "Result", "Their version"]) {
const offset = pane === "Result" ? 240 : pane === "Your version" ? 120 : 60;
await page
.getByRole("region", { name: pane })
.locator(".cm-scroller")
.evaluate((el, x) => (el.scrollLeft = x), offset);
await expect.poll(lefts).toEqual([offset, offset, offset]);
}
});
test("says when every change is processed and saves the result from the notice", async ({ page }) => {
await mountMerge(page);
await captureWrites(page);
const notice = page.locator("#merge-host").getByText("All changes have been processed.");
await expect(notice).toBeHidden();
await page.getByRole("button", { name: "Resolve Simple Conflicts" }).click();
await expect(status(page)).toHaveText("1 change left, 1 conflict");
await expect(notice).toBeHidden();
// The conflict left takes both sides.
await page.getByRole("region", { name: "Your version" }).locator(".cm-merge-accept").first().click();
await expect(notice).toBeHidden();
await page.getByRole("region", { name: "Their version" }).locator(".cm-merge-accept").first().click();
await expect(status(page)).toHaveText("All changes processed");
await expect(notice).toBeVisible();
await page.screenshot({ path: process.env.MERGE_SHOT, animations: "disabled" }).catch(() => undefined);
await page.getByRole("button", { name: "Save changes and finish merging" }).click();
// Nothing is left to confirm: the result is written and staged.
await expect.poll(async () => (await writes(page)).some((call) => call.command === "vcsStage")).toBe(true);
await expect(page.getByRole("dialog")).toHaveCount(0);
});
+9 -2
Переглянути файл
@@ -23,7 +23,7 @@ for (const theme of ["light", "dark"] as const) {
await page.getByRole("option", { name: "Current File", exact: true }).click();
const project = page.getByRole("region", { name: "Project", exact: true });
const buttons = [
...["Select Opened File", "Expand All", "Collapse All", "Options", "Hide"].map((name) =>
...["Select Opened File", "Expand Selected", "Collapse All", "Options", "Hide"].map((name) =>
project.getByRole("button", { name, exact: true }),
),
...[
@@ -66,7 +66,8 @@ for (const theme of ["light", "dark"] as const) {
await expect(button).toHaveCSS("outline-width", "2px");
}
const expand = project.getByRole("button", { name: "Expand All", exact: true });
const expand = project.getByRole("button", { name: "Expand Selected", exact: true });
await project.getByRole("treeitem", { name: "src", exact: true }).click();
await expand.hover();
const hover = await expand.evaluate((button) => getComputedStyle(button).backgroundColor);
await page.mouse.down();
@@ -74,6 +75,12 @@ for (const theme of ["light", "dark"] as const) {
await page.mouse.up();
await expect(project.getByRole("treeitem", { name: "src", exact: true })).toHaveAttribute("aria-expanded", "true");
await project.getByRole("button", { name: "Collapse All", exact: true }).click();
const projectRoot = project.getByRole("treeitem", { name: /^acme-api/ });
await expect(projectRoot).toHaveAttribute("aria-expanded", "false");
await expect(project.getByRole("treeitem", { name: "src", exact: true })).toHaveCount(0);
await projectRoot.click();
await project.getByRole("tree", { name: "Project" }).press("ArrowRight");
await expect(projectRoot).toHaveAttribute("aria-expanded", "true");
await expect(project.getByRole("treeitem", { name: "src", exact: true })).toHaveAttribute("aria-expanded", "false");
await project.getByRole("button", { name: "Options", exact: true }).click();
+2 -1
Переглянути файл
@@ -7,10 +7,11 @@ interface Node {
label: string;
children?: Node[];
}
const rowCount = new URLSearchParams(location.search).has("large") ? 6000 : 160;
const longLabel = `z_${"long_file_name_".repeat(16)}.ts`;
const initial: Node[] = [
{ key: "src", label: "src", children: [{ key: "child", label: "child.ts" }] },
...Array.from({ length: 160 }, (_, i) => ({ key: `file-${i}`, label: `file_${i}.ts` })),
...Array.from({ length: rowCount }, (_, i) => ({ key: `file-${i}`, label: `file_${i}.ts` })),
{ key: "wide", label: longLabel },
];
const shorten = (nodes: Node[]): Node[] =>
+94 -1
Переглянути файл
@@ -131,14 +131,17 @@ test("offscreen same-key updates remain estimates until the row is mounted again
await expect.poll(async () => (await metrics(tree)).width).toBe(240);
});
test("hidden trees keep their widths and reconcile pending removals when shown", async ({ page }) => {
test("hidden trees retain the virtual viewport and reconcile pending width changes when shown", async ({ page }) => {
await open(page);
const tree = page.getByRole("tree", { name: "Width fixture", includeHidden: true });
const before = await measureLong(page, tree);
const row = await tree.getByRole("treeitem", { name: /^z_long/ }).elementHandle();
const top = await tree.evaluate((node) => node.scrollTop);
const spacer = tree.locator("[data-content-width]");
const stored = await spacer.evaluate((node) => (node as HTMLElement).style.width);
await page.getByRole("button", { name: "Toggle visibility" }).click();
await expect(tree).toBeHidden();
await tree.evaluate((node) => node.dispatchEvent(new Event("scroll")));
// Give ResizeObserver deliveries a chance to run while there is no layout.
await page.evaluate(
() =>
@@ -146,13 +149,103 @@ test("hidden trees keep their widths and reconcile pending removals when shown",
requestAnimationFrame(() => requestAnimationFrame(() => requestAnimationFrame(() => resolve())));
}),
);
expect(await row.evaluate((node) => node.isConnected)).toBe(true);
expect(await spacer.evaluate((node) => (node as HTMLElement).style.width)).toBe(stored);
await page.getByRole("button", { name: "Toggle visibility" }).click();
await expect(tree).toBeVisible();
await expect.poll(() => metrics(tree)).toEqual(before);
expect(await tree.evaluate((node) => node.scrollTop)).toBe(top);
await page.getByRole("button", { name: "Toggle visibility" }).click();
await page.getByRole("button", { name: "Delete widest" }).click();
await page.getByRole("button", { name: "Change indent" }).click();
await page.getByRole("button", { name: "Toggle visibility" }).click();
await expect.poll(async () => (await metrics(tree)).width).toBe(240);
});
test("a scroll just before hiding takes effect when the tree is shown again", async ({ page }) => {
const tree = await open(page);
await wheel(page, tree, 0, 10000);
await expect(tree.getByRole("treeitem", { name: /^z_long/ })).toBeVisible();
const visibility = page.getByRole("button", { name: "Toggle visibility" });
await visibility.evaluate((button) => {
document.querySelector<HTMLElement>('[role="tree"]')!.scrollTop = 0;
(button as HTMLButtonElement).click();
});
await expect(tree).toBeHidden();
await visibility.click();
expect(await tree.evaluate((node) => node.scrollTop)).toBe(0);
await expect(tree.getByRole("treeitem", { name: "src", exact: true })).toBeVisible();
});
test("large wheel and thumb jumps keep the viewport covered", async ({ page }) => {
await page.goto("/e2e/treeWidth.html?large");
const tree = page.getByRole("tree", { name: "Width fixture" });
await expect(tree.getByRole("treeitem", { name: "src", exact: true })).toBeVisible();
const box = (await tree.boundingBox())!;
const eventState = await tree.evaluateHandle((element) => {
const coverage = () => {
const { top, left } = element.getBoundingClientRect();
const bottom = top + element.clientHeight;
let covered = true;
for (let y = top + 1; y < bottom; y += 8) {
const row = element.ownerDocument.elementFromPoint(left + 12, y)?.closest("[data-row]");
if (!row || !element.contains(row)) covered = false;
}
return { offset: element.scrollTop, covered, mounted: element.querySelectorAll("[data-row]").length };
};
const state = { wheel: coverage(), drag: coverage() };
// At the end of the input event, before the browser can paint the new offset.
window.addEventListener("wheel", () => (state.wheel = coverage()));
window.addEventListener("pointermove", (event) => {
if (event.buttons === 1) state.drag = coverage();
});
return state;
});
const maximum = await tree.evaluate((element) => element.scrollHeight - element.clientHeight);
expect(maximum).toBeGreaterThan(140_000);
await page.mouse.move(box.x + 40, box.y + 100);
for (const [delta, offset] of [
[40_000, 40_000],
[80_000, 120_000],
[-90_000, 30_000],
[-50_000, 0],
] as const) {
await page.mouse.wheel(0, delta);
await expect.poll(async () => eventState.evaluate((state) => state.wheel.offset)).toBe(offset);
expect(await eventState.evaluate((state) => state.wheel.covered)).toBe(true);
}
const thumbX = box.x + box.width - 5;
const thumbY = box.y + 12;
const travel = await page.evaluate(
({ x, y }) => {
const thumb = document.elementFromPoint(x, y) as HTMLElement;
return thumb.parentElement!.clientHeight - thumb.offsetHeight;
},
{ x: thumbX, y: thumbY },
);
expect(travel).toBeGreaterThan(0);
await page.mouse.move(thumbX, thumbY);
await page.mouse.down();
try {
for (const fraction of [0.65, 0.2, 0.95, 0.4, 1]) {
const distance = Math.round(travel * fraction);
await page.mouse.move(thumbX, thumbY + distance);
const state = await eventState.evaluate((state) => state.drag);
expect(state.covered).toBe(true);
expect(state.mounted).toBeLessThanOrEqual(40);
expect(Math.abs(state.offset - (distance / travel) * maximum)).toBeLessThanOrEqual(1);
}
} finally {
await page.mouse.up();
}
await expect(tree.getByRole("treeitem", { name: /^z_long/ })).toBeVisible();
// The pointer can remain over the tree's scrollbar for the next wheel gesture.
await page.mouse.move(thumbX, box.y + box.height - 12);
await page.mouse.wheel(0, -maximum);
await expect.poll(async () => eventState.evaluate((state) => state.wheel.offset)).toBe(0);
expect(await eventState.evaluate((state) => state.wheel.covered)).toBe(true);
await expect(tree.getByRole("treeitem", { name: "src", exact: true })).toBeVisible();
});
+3
Переглянути файл
@@ -15,6 +15,9 @@ fn main() {
println!("cargo:rerun-if-changed={}", manifest.display());
println!("cargo:rustc-link-arg=/MANIFEST:EMBED");
println!("cargo:rustc-link-arg=/MANIFESTINPUT:{}", manifest.display());
// Windows gives the main thread a 1 MB stack by default (macOS and Linux: 8 MB), which
// unoptimized debug frames overflow (STATUS_STACK_OVERFLOW). Match the 8 MB elsewhere.
println!("cargo:rustc-link-arg=/STACK:8388608");
}
tauri_build::try_build(tauri_build::Attributes::new().windows_attributes(windows)).expect("tauri build");
}
+4
Переглянути файл
@@ -278,6 +278,7 @@ flutter_devices trusted project_host bin
flutter_devices_refresh trusted project_host bindings sync
flutter_devtools_url trusted project_host bindings async
flutter_emulator_launch trusted project_host bindings async
flutter_widget_preview_url trusted project_host bindings async
fs_compare_directories always project_host bindings async
fs_copy always project_host bindings async
fs_copy_merge always project_host bindings async
@@ -362,6 +363,8 @@ lsp_completion trusted project_host bin
lsp_document_colors trusted project_host bindings async
lsp_document_highlights trusted project_host bindings async
lsp_document_links trusted project_host bindings async
lsp_edit_argument trusted project_host bindings async
lsp_editable_arguments trusted project_host bindings async
lsp_exception_class_at trusted project_host bindings async
lsp_execute_code_action trusted project_host bindings async
lsp_execute_command trusted project_host bindings async
@@ -610,6 +613,7 @@ scope_files always project_host bin
sdk_container_python trusted project_host bindings sync
sdk_container_python_refresh trusted project_host bindings async
sdk_detect outside_restricted project_host bindings async
sdk_flutter_at trusted project_host bindings async
sdk_jdk_at trusted project_host bindings async
sdk_locate_tools trusted project_host bindings async
sdk_php_composer_install trusted project_host bindings async
+84 -1
Переглянути файл
@@ -700,6 +700,12 @@ export const commands = {
flutterDevtoolsUrl: () => typedError<string, IdeError>(__TAURI_INVOKE("flutter_devtools_url")),
/** Starts an emulator from [`FlutterDeviceList::emulators`]. Returns once the launch is under way: the device follows as `IdeEvent::FlutterDevices`. */
flutterEmulatorLaunch: (id: string) => typedError<null, IdeError>(__TAURI_INVOKE("flutter_emulator_launch", { id })),
/**
* The address of the project's Widget Preview page, its server started on first use with the
* project's DevTools for its inspector. A server that failed or exited is only started again by
* the next request.
*/
flutterWidgetPreviewUrl: () => typedError<string, IdeError>(__TAURI_INVOKE("flutter_widget_preview_url")),
fsCompareDirectories: (left: string, right: string, mode: DirectoryCompareMode, request: RequestId, onProgress: Channel<DirectoryCompareProgress>) => typedError<DirectoryCompareEntry[], IdeError>(__TAURI_INVOKE("fs_compare_directories", { left, right, mode, request, onProgress })),
fsCopy: (from: string, to: string) => typedError<null, IdeError>(__TAURI_INVOKE("fs_copy", { from, to })),
fsCopyMerge: (sourceRoot: string, destinationRoot: string, path: string, overwrite: boolean) => typedError<null, IdeError>(__TAURI_INVOKE("fs_copy_merge", { sourceRoot, destinationRoot, path, overwrite })),
@@ -900,6 +906,18 @@ export const commands = {
lspDocumentHighlights: (doc: DocId, pos: Pos) => typedError<Highlight[], IdeError>(__TAURI_INVOKE("lsp_document_highlights", { doc, pos })),
/** Links in a document (`href`s, Markdown links, `#include`s…) from its language servers. */
lspDocumentLinks: (doc: DocId) => typedError<DocumentLink[], IdeError>(__TAURI_INVOKE("lsp_document_links", { doc })),
/**
* Sets an argument of the call at `pos`; the edit reaches the document as the server's
* `workspace/applyEdit`, undoable like any other.
*/
lspEditArgument: (doc: DocId, pos: Pos, name: string, value: boolean | number | number | null | string | null) => typedError<null, IdeError>(__TAURI_INVOKE("lsp_edit_argument", { doc, pos, name, value })),
/** The Flutter Property Editor's arguments of the call at `pos`. */
lspEditableArguments: (doc: DocId, pos: Pos) => typedError<{
/** The widget's (or callee's) name. */
name: string | null,
documentation: string | null,
arguments: EditableArgument[],
} | null, IdeError>(__TAURI_INVOKE("lsp_editable_arguments", { doc, pos })),
/** The Throwable class the caret at `pos` names, for the exception breakpoint intention. */
lspExceptionClassAt: (request: RequestId, doc: DocId, pos: Pos) => typedError<{
/** The binary name (`app.Outer$Failure`), as exception breakpoints take it. */
@@ -1695,6 +1713,17 @@ export const commands = {
} | null, IdeError>(__TAURI_INVOKE("sdk_container_python_refresh")),
/** Installed interpreters / toolchains of `kind`; project-local ones first. */
sdkDetect: (kind: SdkKind) => typedError<Sdk[], IdeError>(__TAURI_INVOKE("sdk_detect", { kind })),
/**
* `flutter --version --machine` of the Flutter SDK at `path`, or of the `flutter` on the
* search path when `path` is empty; `None` when there is no Flutter SDK.
*/
sdkFlutterAt: (path: string) => typedError<{
/** SDK root (not part of Flutter's answer). */
root?: string,
frameworkVersion?: string,
channel?: string | null,
dartSdkVersion?: string | null,
} | null, IdeError>(__TAURI_INVOKE("sdk_flutter_at", { path })),
/** The JDK whose home is `path`, as the SDK list shows it; `None` when it is no JDK home. */
sdkJdkAt: (path: string) => typedError<{
/**
@@ -3620,6 +3649,9 @@ export type ArduinoSettings = {
fqbn?: string,
};
/** A literal argument value. Ints stay ints: the server rejects `1.0` for an `int` parameter. */
export type ArgumentValue = boolean | number | number | null | string;
/** Packaging artifact definition (Project Structure › Artifacts). */
export type ArtifactConfig = {
name?: string,
@@ -6441,6 +6473,36 @@ export type DynamicItem = {
checked?: boolean | null,
};
export type EditableArgument = {
name: string,
documentation: string | null,
/** How to edit it: `string`, `int`, `double`, `bool` or `enum`. */
type: string,
/** The literal value in the code (only while `has_argument`); an expression has `display_value`. */
value: ArgumentValue | null,
hasArgument?: boolean,
defaultValue: ArgumentValue | null,
displayValue: string | null,
isRequired?: boolean,
isNullable?: boolean,
isDeprecated?: boolean,
isEditable?: boolean,
notEditableReason: string | null,
/** An enum's values, as `EnumName.value`. */
options: string[] | null,
};
/**
* The arguments the Flutter Property Editor edits: those of the widget (or other) call at a
* position, as the Dart server's `dart/textDocument/editableArguments` reports them.
*/
export type EditableArguments = {
/** The widget's (or callee's) name. */
name: string | null,
documentation: string | null,
arguments: EditableArgument[],
};
/** Editor › General › Appearance. */
export type EditorAppearanceSettings = {
caretBlinking?: boolean,
@@ -7247,6 +7309,24 @@ export type FlutterEmulator = {
platformType: string | null,
};
/** The Flutter plugin's "Flutter SDK path". */
export type FlutterSettings = {
/**
* Flutter SDK root (holding `bin/flutter`); its `flutter` and Dart replace the ones on
* `PATH`. Empty = `PATH`.
*/
sdk?: string,
};
/** What `flutter --version --machine` reports of an SDK. */
export type FlutterVersion = {
/** SDK root (not part of Flutter's answer). */
root?: string,
frameworkVersion?: string,
channel?: string | null,
dartSdkVersion?: string | null,
};
export type FocusedEditor = {
path: IpcPath,
/** Zero-based lines and UTF-16 columns, end exclusive. */
@@ -9109,6 +9189,7 @@ export type LanguagesSettings = {
markdown?: MarkdownSettings,
arduino?: ArduinoSettings,
zig?: ZigSettings,
flutter?: FlutterSettings,
};
export type LargeCommitFile = {
@@ -12595,7 +12676,9 @@ export type SdkKind = "python" | "node" |
/** Zig toolchain directories. */
"zig" |
/** .NET SDKs of the `dotnet` on the search path; `version` is what `global.json` pins. */
"dotnet";
"dotnet" |
/** Flutter SDK roots. */
"flutter";
/**
* IDEA's search context: matches anywhere, only in, or outside comments and
+17 -10
Переглянути файл
@@ -1,17 +1,20 @@
/* A framed text area (IDEA text field frame), with the pickers in its bottom row. */
/* A framed text area (IDEA Islands surface), with compact pickers in its bottom row. */
.composer {
container: agent-composer / inline-size;
min-width: 0;
position: relative;
display: flex;
flex-direction: column;
border-radius: var(--radius-control);
background: var(--bg-field, var(--bg-button));
box-shadow: inset 0 0 0 1px var(--border-button);
border-radius: var(--radius-toolbar-button);
background: var(--bg-elev);
box-shadow: inset 0 0 0 1px var(--border-popup);
cursor: text;
transition: box-shadow var(--dur-fast) var(--ease);
transition:
background var(--dur-fast) var(--ease),
box-shadow var(--dur-fast) var(--ease);
}
.composer:focus-within {
background: var(--bg-field, var(--bg-button));
box-shadow:
inset 0 0 0 1px var(--focus-ring),
0 0 0 1px var(--focus-ring);
@@ -47,8 +50,8 @@
must land in the editable text, or they focus the bare scroller and no caret appears.
A host sets --composer-min-height rather than overriding the rule, so stylesheet order can't undo it. */
.field :global(.cm-content) {
min-height: var(--composer-min-height, 44px);
padding: var(--space-2) var(--space-2) var(--space-0-5);
min-height: var(--composer-min-height, 38px);
padding: 9px 12px 4px;
caret-color: var(--fg-strong);
white-space: pre-wrap;
overflow-wrap: anywhere;
@@ -100,6 +103,7 @@
min-width: 0;
overflow: hidden;
gap: var(--space-0-5);
font-size: var(--fs-small);
}
.toolbar > button {
flex: 0 1 auto;
@@ -197,14 +201,17 @@
.chip {
display: inline-flex;
align-items: center;
gap: var(--space-1-5);
gap: var(--space-1);
height: var(--h-control);
min-width: 0;
padding: 0 4px 0 6px;
border-radius: var(--radius-control);
border-radius: var(--radius-toolbar-button);
color: var(--fg-secondary);
font-size: var(--fs-small);
white-space: nowrap;
transition: background var(--dur-fast) var(--ease);
transition:
background var(--dur-fast) var(--ease),
color var(--dur-fast) var(--ease);
}
.chip.chipLoading,
.chip.chipLoading:hover {
+5 -5
Переглянути файл
@@ -517,7 +517,7 @@ function ModelPicker({
onClick={() => toggle("models")}
>
<span className={styles.chipValue}>{modelName}</span>
<Icon name="chevron-down" size={14} className={styles.chipChevron} />
<Icon name="chevron-down" size={12} className={styles.chipChevron} />
</button>
{!unavailable && modelRefresh?.loadingSettings ? (
<LoadingSettingsChip />
@@ -526,7 +526,7 @@ function ModelPicker({
!unavailable && (
<button
type="button"
className={clsx(styles.chip, styles.modelDetail)}
className={styles.chip}
aria-label={tx`Model settings: ${summary}`}
title={
fullSummary && fullSummary !== summary
@@ -538,7 +538,7 @@ function ModelPicker({
onClick={() => toggle("settings")}
>
<span className={styles.chipValue}>{summary}</span>
<Icon name="chevron-down" size={14} className={styles.chipChevron} />
<Icon name="chevron-down" size={12} className={styles.chipChevron} />
</button>
)
)}
@@ -753,14 +753,14 @@ function ModePicker({
title={summary}
onClick={() => setOpen((v) => !v)}
>
<Icon name={on ? "unlock" : modeIcon(current?.value ?? "")} size={14} />
<Icon name={on ? "unlock" : modeIcon(current?.value ?? "")} size={13} />
<span className={styles.chipValue}>{current?.name ?? tx("Default")}</span>
{on && (
<span className={clsx(styles.chipDetail, compactDetail && styles.compactDetail)} data-chip-detail="">
{tx(toggle.chipLabel)}
</span>
)}
<Icon name="chevron-down" size={14} className={styles.chipChevron} />
<Icon name="chevron-down" size={12} className={styles.chipChevron} />
</button>
<Popup
open={open}
+14 -7
Переглянути файл
@@ -8,13 +8,13 @@
display: flex;
flex-direction: column;
align-items: center;
justify-content: flex-start;
padding: var(--space-4);
justify-content: center;
padding: 24px 24px 12vh;
background: var(--bg-editor);
color: var(--fg);
}
.inner {
/* A compact block at the top of the editor: narrower than a session's conversation. */
/* A compact block in the middle of the page: narrower than a session's conversation. */
width: min(680px, 100%);
display: flex;
flex-direction: column;
@@ -24,12 +24,14 @@
width: 100%;
}
.heading {
margin: 0;
padding: 0 4px;
font-size: var(--agent-fs-ui);
font-weight: 600;
margin: 0 0 10px;
font-size: calc(18px + var(--agent-font-zoom, 0px));
font-weight: 500;
letter-spacing: -0.01em;
line-height: 1.4;
text-align: center;
color: var(--fg-strong);
text-wrap: balance;
}
/* A box to write in, not a search bar: room for a few lines before it grows. */
@@ -104,7 +106,12 @@
padding-bottom: var(--space-2);
}
.docked .heading {
margin: 0;
padding: 0 4px;
font-size: var(--agent-fs-ui);
font-weight: 400;
letter-spacing: normal;
text-align: left;
color: var(--fg-muted);
}
-1
Переглянути файл
@@ -257,7 +257,6 @@
background: none;
color: var(--link);
font-size: var(--fs-small);
cursor: pointer;
}
.codeMore:hover {
background: var(--bg-hover);
+170 -14
Переглянути файл
@@ -1088,12 +1088,12 @@
flex: none;
display: flex;
flex-direction: column;
gap: var(--space-1-5);
gap: var(--space-1);
align-self: center;
width: 100%;
max-width: calc(var(--session-content-width) + var(--space-3) * 2);
box-sizing: border-box;
padding: var(--space-2) var(--space-3) var(--space-4);
padding: var(--space-1-5) var(--space-3) var(--space-3);
}
.background {
@@ -1154,32 +1154,86 @@
flex-wrap: wrap;
align-items: center;
align-content: flex-start;
gap: 0 10px;
gap: 0 6px;
color: var(--fg-subtle);
font-size: var(--fs-small);
font-variant-numeric: tabular-nums;
white-space: nowrap;
}
.meterSegment {
display: inline-flex;
flex: 0 1 auto;
align-items: center;
min-width: 0;
height: 22px;
gap: 6px;
}
.meterGroup {
display: inline-flex;
flex: 0 1 auto;
align-items: center;
min-width: 0;
height: 22px;
gap: 6px;
}
.meterDivider {
flex: none;
width: 1px;
height: 11px;
background: var(--border-strong);
opacity: 0.5;
}
.meter {
display: inline-flex;
flex: 0 1 auto;
align-items: center;
min-width: 0;
height: 22px;
height: 20px;
gap: 5px;
overflow: hidden;
}
.usageBar {
width: 36px;
height: 4px;
border-radius: 2px;
background: var(--border);
overflow: hidden;
.meterValue {
line-height: 1;
}
.usageBar > span {
.usageRing {
flex: none;
width: 13px;
height: 13px;
display: block;
height: 100%;
background: var(--fg-muted);
}
.usageRingTrack {
fill: none;
stroke: color-mix(in srgb, currentColor 22%, transparent);
stroke-width: 1.75;
}
.usageRingArc {
fill: none;
stroke: var(--fg-muted);
stroke-width: 1.75;
stroke-linecap: round;
transition:
stroke-dashoffset 200ms var(--ease),
stroke var(--dur-fast) var(--ease);
}
.limitsButton {
gap: 0;
}
.limitItem {
display: inline-flex;
align-items: baseline;
gap: 3px;
}
.limitWindow {
color: var(--fg-faint);
}
.limitPercent {
color: inherit;
}
.meterDot {
flex: none;
margin: 0 5px;
color: var(--fg-faint);
opacity: 0.65;
}
.images {
@@ -1937,8 +1991,110 @@
color: inherit;
font: inherit;
border: 0;
border-radius: var(--radius-control);
background: transparent;
padding: 0 var(--space-1);
padding: 0 5px;
transition:
background var(--dur-fast) var(--ease),
color var(--dur-fast) var(--ease);
}
.meterButton:hover,
.meterButton[aria-expanded="true"] {
background: var(--bg-toolbar-hover);
color: var(--fg);
}
.meterButton:hover .usageRingArc,
.meterButton[aria-expanded="true"] .usageRingArc {
stroke: currentColor;
}
.limitsButton:hover .limitWindow,
.limitsButton[aria-expanded="true"] .limitWindow {
color: var(--fg-subtle);
}
.meterButton:focus-visible {
outline: 1px solid var(--focus-ring);
outline-offset: -1px;
}
.meterWarning,
.meterWarning:hover,
.meterWarning[aria-expanded="true"] {
color: var(--warning);
}
.meterDanger,
.meterDanger:hover,
.meterDanger[aria-expanded="true"] {
color: var(--danger);
}
.meterWarning .usageRingArc,
.meterDanger .usageRingArc {
stroke: currentColor;
}
.meterWarning .meterValue,
.meterDanger .meterValue,
.meterWarning .limitPercent,
.meterDanger .limitPercent {
font-weight: 500;
}
.limitsDetails {
display: grid;
gap: var(--space-2);
width: min(272px, 80vw);
padding: var(--space-3);
color: var(--fg-secondary);
font-size: var(--fs-ui);
font-variant-numeric: tabular-nums;
}
.limitsList {
display: grid;
gap: var(--space-3);
}
.limitsRow {
display: grid;
gap: 5px;
}
.limitsRowHeader {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: var(--space-2);
}
.limitsRowName {
color: var(--fg);
font-size: var(--fs-small);
}
.limitsRowPercent {
color: var(--fg-secondary);
font-size: var(--fs-small);
}
.meterWarning .limitsRowPercent {
color: var(--warning);
font-weight: 500;
}
.meterDanger .limitsRowPercent {
color: var(--danger);
font-weight: 500;
}
.limitsTrack {
height: 4px;
border-radius: 2px;
background: var(--border);
overflow: hidden;
}
.limitsFill {
display: block;
height: 100%;
border-radius: 2px;
background: var(--fg-muted);
}
.meterWarning .limitsFill {
background: var(--warning);
}
.meterDanger .limitsFill {
background: var(--danger);
}
.limitsReset {
color: var(--fg-subtle);
font-size: var(--fs-tiny, var(--fs-small));
}
.contextPopover {
max-width: calc(100vw - 24px);
+32 -16
Переглянути файл
@@ -1,24 +1,25 @@
/* Session Pull Requests, Issues, References, and Artifacts pills above the composer. */
/* Session Pull Requests, Issues, References, and Artifacts pills above the composer.
Flat like Chip / statusChip: no frame at rest, toolbar hover when interactive. */
.bar {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: var(--space-1-5);
gap: var(--space-0-5);
min-width: 0;
padding: 0 2px;
padding: 0;
}
.pill {
display: inline-flex;
align-items: center;
gap: var(--space-1-5);
height: 24px;
gap: var(--space-1);
height: 22px;
max-width: 100%;
min-width: 0;
padding: 0 8px;
border: 1px solid var(--border-popup);
border-radius: var(--radius-control);
background: var(--bg-elev);
padding: 0 4px 0 6px;
border: 0;
border-radius: var(--radius-toolbar-button);
background: transparent;
color: var(--fg-secondary);
font: inherit;
font-size: var(--fs-small);
@@ -26,17 +27,30 @@
white-space: nowrap;
transition:
background var(--dur-fast) var(--ease),
border-color var(--dur-fast) var(--ease),
color var(--dur-fast) var(--ease);
}
.pill:hover,
.pill[aria-expanded="true"] {
background: var(--bg-hover);
border-color: var(--border-strong);
background: var(--bg-toolbar-hover);
color: var(--fg-strong);
}
.pill:focus-visible {
outline: 2px solid var(--focus-ring);
outline-offset: -2px;
}
.pillIcon {
flex: none;
color: var(--fg-muted);
}
.pill:hover .pillIcon,
.pill[aria-expanded="true"] .pillIcon {
color: inherit;
}
.pillLabel {
min-width: 0;
overflow: hidden;
@@ -63,7 +77,7 @@
}
.sectionHeader {
padding: 4px 12px;
padding: 4px 14px;
color: var(--fg-muted);
font-size: var(--fs-small);
font-weight: 600;
@@ -75,13 +89,15 @@
display: flex;
align-items: center;
gap: var(--space-1);
min-height: 28px;
padding: 1px 6px 1px 10px;
min-height: 26px;
margin: 0 6px;
padding: 1px 4px 1px 8px;
border-radius: var(--radius-selection, 5px);
}
.row:hover,
.row:focus-within {
background: var(--bg-hover);
background: var(--bg-tree-hover, var(--bg-hover));
}
.rowMain {
+3 -3
Переглянути файл
@@ -514,7 +514,7 @@ export function SessionAssets({ task, entries, head, onFocusComposer }: SessionA
>
<Icon name={issueCount === 1 ? issueIcon(assets.createdIssues[0]!.state) : "issue-open"} size={13} />
<span className={styles.pillLabel}>{issuePillLabel}</span>
{issueCount > 1 && <Icon name="chevron-down" size={11} className={styles.chevron} />}
<Icon name="chevron-down" size={11} className={styles.chevron} />
</button>
<AssetPopup
open={activeCategory === "issues"}
@@ -538,7 +538,7 @@ export function SessionAssets({ task, entries, head, onFocusComposer }: SessionA
aria-expanded={activeCategory === "references"}
onClick={() => toggle("references")}
>
<Icon name="toolwindow-bookmarks" size={13} />
<Icon name="toolwindow-bookmarks" size={13} className={styles.pillIcon} />
<span className={styles.pillLabel}>{refPillLabel}</span>
<Icon name="chevron-down" size={11} className={styles.chevron} />
</button>
@@ -564,7 +564,7 @@ export function SessionAssets({ task, entries, head, onFocusComposer }: SessionA
aria-expanded={activeCategory === "artifacts"}
onClick={() => toggle("artifacts")}
>
<Icon name="artifact" size={13} />
<Icon name="artifact" size={13} className={styles.pillIcon} />
<span className={styles.pillLabel}>{artifactPillLabel}</span>
<Icon name="chevron-down" size={11} className={styles.chevron} />
</button>
-1
Переглянути файл
@@ -72,7 +72,6 @@
color: var(--link);
font: inherit;
font-size: var(--fs-small);
cursor: pointer;
}
.resetBtn:hover {
+7
Переглянути файл
@@ -1,4 +1,11 @@
.submit {
--button-radius: var(--radius-toolbar-button);
width: var(--h-control);
padding: 0;
}
.submit:disabled {
background: var(--bg-toolbar-hover);
color: var(--fg-faint);
box-shadow: none;
}
+41 -13
Переглянути файл
@@ -599,23 +599,51 @@ const LIMIT_WINDOWS: Record<string, { short: string; name: string }> = {
seven_day_sonnet: { short: "7d Sonnet", name: "Weekly Sonnet limit" },
};
/** Visual severity for a usage percentage meter: quiet until nearing the cap. */
export type MeterTone = "warning" | "danger";
export function meterTone(percent: number): MeterTone | undefined {
if (percent >= 95) return "danger";
if (percent >= 80) return "warning";
return undefined;
}
/** Structured fields for a usage-limit window, shared by inline badges and the detail popover. */
export function limitParts(
l: AgentLimit,
now: number,
): {
windowShort: string;
name: string;
percent: number;
resetIn: string | null;
detail: string;
} {
const known = LIMIT_WINDOWS[l.window];
const windowShort = known?.short ?? l.window;
const percent = Math.min(100, Math.round(l.usedPercent ?? 0));
const name = known ? tx(known.name) : l.window;
const used = tx`${known ? txPart(known.name) : l.window}: ${percent}% used`;
if (l.resetsMs == null) {
return { windowShort, name, percent, resetIn: null, detail: used };
}
const resetIn = untilReset(Math.max(0, l.resetsMs - now));
return {
windowShort,
name,
percent,
resetIn,
detail: tx`${used}, resets in ${resetIn}`,
};
}
/** "5h 19%" for a usage-limit window, and a tooltip saying when it resets. */
export function limitLabel(l: AgentLimit, now: number): { short: string; percent: number; detail: string } {
const known = LIMIT_WINDOWS[l.window];
const percent = Math.min(100, Math.round(l.usedPercent ?? 0));
const name = known ? txPart(known.name) : l.window;
const used = tx`${name}: ${percent}% used`;
if (l.resetsMs == null)
return {
short: `${known?.short ?? l.window} ${percent}%`,
percent,
detail: used,
};
const reset = untilReset(Math.max(0, l.resetsMs - now));
const { windowShort, percent, detail } = limitParts(l, now);
return {
short: `${known?.short ?? l.window} ${percent}%`,
short: `${windowShort} ${percent}%`,
percent,
detail: tx`${used}, resets in ${reset}`,
detail,
};
}
+33 -7
Переглянути файл
@@ -1,13 +1,17 @@
import { useEffect, useRef, useState } from "react";
import clsx from "clsx";
import type { AgentContextUsage, AgentTask, AgentUsage } from "@/bindings";
import { call, commands } from "@/platform/ipc";
import { useTx } from "@/platform/i18n";
import { Button, Popup, T, tooltipAttrs } from "@/ui";
import { usageLabel } from "../composerModel";
import { meterTone, usageLabel } from "../composerModel";
import { isBusy } from "../model";
import { resendMessage } from "../store";
import styles from "../Session.module.css";
const RING_RADIUS = 5;
const RING_CIRCUMFERENCE = 2 * Math.PI * RING_RADIUS;
const categoryTones = new Map([
["System prompt", "var(--accent)"],
["System tools", "var(--warning)"],
@@ -37,17 +41,38 @@ export function ContextMeter({ task, usage }: { task: AgentTask; usage: AgentUsa
const timer = window.setTimeout(() => setPhase("closed"), 100);
return () => window.clearTimeout(timer);
}, [phase]);
const severity = meterTone(label.percent);
const severityClass =
severity === "danger" ? styles.meterDanger : severity === "warning" ? styles.meterWarning : undefined;
const dashOffset = RING_CIRCUMFERENCE * (1 - label.percent / 100);
const meter = (
<>
<span className={styles.usageBar} aria-hidden>
<span style={{ width: label.percent + "%" }} />
</span>
{label.percent}%
<svg className={styles.usageRing} viewBox="0 0 14 14" aria-hidden>
<circle className={styles.usageRingTrack} cx="7" cy="7" r={RING_RADIUS} />
<circle
className={styles.usageRingArc}
cx="7"
cy="7"
r={RING_RADIUS}
strokeDasharray={RING_CIRCUMFERENCE}
strokeDashoffset={dashOffset}
strokeOpacity={label.percent > 0 ? 1 : 0}
transform="rotate(-90 7 7)"
data-percent={label.percent}
/>
</svg>
<span className={styles.meterValue}>{label.percent}%</span>
</>
);
if (!task.capabilities?.contextUsage)
return (
<span tabIndex={0} className={styles.meter} aria-label={hint} {...tooltipAttrs(hint, undefined, true)}>
<span
tabIndex={0}
className={clsx(styles.meter, severityClass)}
data-tone={severity}
aria-label={hint}
{...tooltipAttrs(hint, undefined, true)}
>
{meter}
</span>
);
@@ -56,7 +81,8 @@ export function ContextMeter({ task, usage }: { task: AgentTask; usage: AgentUsa
<button
type="button"
ref={anchor}
className={styles.meterButton}
className={clsx(styles.meterButton, severityClass)}
data-tone={severity}
aria-label={hint}
aria-haspopup="dialog"
aria-expanded={open}
-1
Переглянути файл
@@ -376,7 +376,6 @@ export function SessionComposer({
/>
<SessionStatus
task={task}
entries={entries}
head={head}
changes={changes}
commits={commits}
+140 -27
Переглянути файл
@@ -1,13 +1,14 @@
import type { AgentChange, AgentCommit, AgentEntry, AgentLimit, AgentTask } from "@/bindings";
import { Fragment, useEffect, useRef, useState, type ReactNode } from "react";
import type { AgentChange, AgentCommit, AgentLimit, AgentTask } from "@/bindings";
import { executeAction } from "@/platform/actions";
import { useTx } from "@/platform/i18n";
import { basename, useProject } from "@/platform/project";
import clsx from "clsx";
import { Icon, IconButton, showContextMenu, T } from "@/ui";
import { Icon, IconButton, Popup, showContextMenu, T, tooltipAttrs } from "@/ui";
import styles from "../Session.module.css";
import { costLabel, limitLabel, turnTokensLabel, workTime } from "../composerModel";
import { costLabel, limitParts, meterTone, turnTokensLabel } from "../composerModel";
import { ContextMeter } from "./ContextMeter";
import { formatDuration, formatSentAt } from "../conversation";
import { formatSentAt } from "../conversation";
import { branchLabel, hasTaskTerminal, isBusy, providerIcon, statusLabel } from "../model";
import { useAgents } from "../store";
import { taskMenu } from "../taskActions";
@@ -35,7 +36,6 @@ function StatusActions({ task }: { task: AgentTask }) {
*/
export function SessionStatus({
task,
entries,
head,
changes,
commits,
@@ -43,7 +43,6 @@ export function SessionStatus({
onOpenChanges,
}: {
task: AgentTask;
entries: AgentEntry[] | null;
head: string | null;
changes: AgentChange[] | null;
commits: readonly AgentCommit[];
@@ -145,7 +144,7 @@ export function SessionStatus({
</span>
)}
<span className={styles.statusMeters}>
<Meters task={task} entries={entries} />
<Meters task={task} />
{hasTaskTerminal(task, projectRoot) && <StatusActions task={task} />}
</span>
</span>
@@ -154,42 +153,156 @@ export function SessionStatus({
}
/**
* Context use, usage limits and cost (when the agent reports them) and the time spent on
* the task, each as Settings › Agents › Chat allows.
* Context use, usage limits and cost (when the agent reports them), grouped with subtle
* dividers and controlled by Settings › Tools › Agents › Chat.
*/
function Meters({ task, entries }: { task: AgentTask; entries: AgentEntry[] | null }) {
function Meters({ task }: { task: AgentTask }) {
const tx = useTx();
const show = useProject((s) => s.settings?.agents);
const busy = isBusy(task.status);
const now = useNow(busy ? 1000 : 60_000);
const now = useNow(60_000);
const usage = show?.showContextUsage !== false ? task.usage : null;
const reported = useAgents((s) => s.limits.get(task.provider));
const limits = show?.showUsageLimits !== false ? (reported ?? []) : [];
const cost = show?.showCost === true ? task.usage?.cost : null;
const turnTokens = show?.showContextUsage !== false && !busy ? task.stats?.tokens : null;
const work = show?.showWorkTime !== false && entries ? workTime(entries, busy ? now : null) : 0;
const groups: { key: string; node: ReactNode }[] = [];
if (usage || turnTokens) {
groups.push({
key: "context",
node: (
<span className={styles.meterGroup}>
{usage && <ContextMeter key={task.id} task={task} usage={usage} />}
{turnTokens && (
<span className={styles.meter} {...tooltipAttrs(tx("Tokens of the last turn"), undefined, true)}>
{turnTokensLabel(turnTokens)}
</span>
)}
</span>
),
});
}
if (limits.length > 0) {
groups.push({
key: "limits",
node: <LimitsMeter limits={limits} now={now} />,
});
}
if (cost) {
groups.push({
key: "cost",
node: (
<span
className={styles.meter}
{...tooltipAttrs(tx("What the session has cost so far, as the agent reports it"), undefined, true)}
>
{costLabel(cost)}
</span>
),
});
}
if (!groups.length) return null;
return (
<span className={styles.meters}>
{usage && <ContextMeter key={task.id} task={task} usage={usage} />}
{turnTokens && <span title={tx("Tokens of the last turn")}>{turnTokensLabel(turnTokens)}</span>}
{limits.map((l) => (
<Limit key={l.window} limit={l} now={now} />
{groups.map((group, i) => (
<span key={group.key} className={styles.meterSegment}>
{i > 0 && <span className={styles.meterDivider} aria-hidden />}
{group.node}
</span>
))}
{cost && <span title={tx("What the session has cost so far, as the agent reports it")}>{costLabel(cost)}</span>}
{work >= 1000 && <span title={tx("Time the agent spent on this task")}>{formatDuration(work)}</span>}
</span>
);
}
/** A usage-limit window: "5h 19%", when it resets in the tooltip. */
function Limit({ limit, now }: { limit: AgentLimit; now: number }) {
const label = limitLabel(limit, now);
/** Compact account usage limits ("5h 77% · 7d 95%") with a click popover for bars and reset times. */
function LimitsMeter({ limits, now }: { limits: readonly AgentLimit[]; now: number }) {
const tx = useTx();
const anchor = useRef<HTMLButtonElement>(null);
const [phase, setPhase] = useState<"closed" | "open" | "closing">("closed");
const open = phase === "open";
const close = () => setPhase(window.matchMedia("(prefers-reduced-motion: reduce)").matches ? "closed" : "closing");
useEffect(() => {
if (phase !== "closing") return;
const timer = window.setTimeout(() => setPhase("closed"), 100);
return () => window.clearTimeout(timer);
}, [phase]);
const items = limits.map((limit) => ({ window: limit.window, ...limitParts(limit, now) }));
return (
<span className={styles.meter} title={label.detail} aria-label={label.detail}>
<span className={styles.usageBar} aria-hidden>
<span style={{ width: `${label.percent}%` }} />
</span>
{label.short}
</span>
<>
<button
type="button"
ref={anchor}
className={clsx(styles.meterButton, styles.limitsButton)}
aria-label={tx("Usage limits")}
aria-haspopup="dialog"
aria-expanded={open}
onClick={() => (open ? close() : setPhase("open"))}
>
{items.map((item, i) => {
const severity = meterTone(item.percent);
const severityClass =
severity === "danger" ? styles.meterDanger : severity === "warning" ? styles.meterWarning : undefined;
return (
<Fragment key={item.window}>
{i > 0 && (
<span className={styles.meterDot} aria-hidden>
·
</span>
)}
<span
className={clsx(styles.limitItem, severityClass)}
data-tone={severity}
aria-label={item.detail}
{...tooltipAttrs(open ? undefined : item.detail, undefined, true)}
>
<span className={styles.limitWindow}>{item.windowShort}</span>{" "}
<span className={styles.limitPercent}>{item.percent}%</span>
</span>
</Fragment>
);
})}
</button>
<Popup
open={phase !== "closed"}
onClose={close}
anchor={anchor}
placement="top-end"
trapFocus={open}
role={open ? "dialog" : "presentation"}
aria-label={tx("Usage limits")}
className={phase === "closing" ? styles.contextClosing : styles.contextPopover}
>
<div className={styles.limitsDetails} inert={!open}>
<div className={styles.contextHeading}>
<strong>
<T>Usage limits</T>
</strong>
</div>
<div className={styles.limitsList}>
{items.map((item) => {
const severity = meterTone(item.percent);
const severityClass =
severity === "danger" ? styles.meterDanger : severity === "warning" ? styles.meterWarning : undefined;
return (
<div key={item.window} className={clsx(styles.limitsRow, severityClass)} data-tone={severity}>
<div className={styles.limitsRowHeader}>
<span className={styles.limitsRowName}>{item.name}</span>
<span className={styles.limitsRowPercent}>{item.percent}%</span>
</div>
<div className={styles.limitsTrack} aria-hidden>
<span className={styles.limitsFill} style={{ width: `${item.percent}%` }} />
</div>
{item.resetIn && <span className={styles.limitsReset}>{tx`Resets in ${item.resetIn}`}</span>}
</div>
);
})}
</div>
</div>
</Popup>
</>
);
}
+9
Переглянути файл
@@ -132,6 +132,14 @@ function useOffscreenRows(
mark();
const rows = new MutationObserver(mark);
rows.observe(el, { childList: true });
// Earlier rows load in front of the first one shown, which then loses its author header while
// it may be off-screen: lay it out again, or it keeps the height it had with the header.
const authors = new MutationObserver((records) => {
for (const { target } of records)
if (target.parentNode === el) (target as Element).removeAttribute("data-measured");
mark();
});
authors.observe(el, { subtree: true, attributes: true, attributeFilter: ["data-author"] });
const resize = new ResizeObserver(() => {
window.clearTimeout(timer);
timer = window.setTimeout(() => {
@@ -144,6 +152,7 @@ function useOffscreenRows(
cancelAnimationFrame(frame);
window.clearTimeout(timer);
rows.disconnect();
authors.disconnect();
resize.disconnect();
};
}, [ref, visible, enabled, fitWindowWidth, fontZoom]);
+37 -7
Переглянути файл
@@ -2301,14 +2301,12 @@ describe("meters in the task header", () => {
render(<SessionEditor input={input("A")} />);
await screen.findByText("Answer A");
const usage = screen.getByLabelText(/^Context /);
// The bar and percent show; the counts are in its label and tooltip.
// The ring and percent show; the counts are in its label and tooltip.
expect(usage).toHaveTextContent("12%");
expect(usage).toHaveAccessibleName(/24k\/200k \(12%\)/);
expect(usage.querySelector(`.${styles.usageBar} span`)).toHaveStyle({
width: "12%",
});
expect(screen.getByText("5h 19%")).toBeInTheDocument();
expect(screen.getByText("7d 9%")).toBeInTheDocument();
expect(usage.querySelector(`.${styles.usageRingArc}`)).toHaveAttribute("data-percent", "12");
expect(screen.getByLabelText("5-hour limit: 19% used")).toHaveTextContent("5h 19%");
expect(screen.getByLabelText("Weekly limit: 9% used")).toHaveTextContent("7d 9%");
expect(screen.queryByText("$0.42")).toBeNull();
act(() =>
useProject.setState({
@@ -2322,10 +2320,42 @@ describe("meters in the task header", () => {
}),
);
expect(screen.queryByText("24k/200k (12%)")).toBeNull();
expect(screen.queryByText("5h 19%")).toBeNull();
expect(screen.queryByLabelText("5-hour limit: 19% used")).toBeNull();
expect(screen.getByText("$0.42")).toBeInTheDocument();
});
it("colors meters at warning/danger thresholds and opens usage-limit details on click", async () => {
const reported: AgentTask = {
...task("A"),
usage: { used: 164_000, size: 200_000, cost: null },
};
const limits = [
{ window: "five_hour", usedPercent: 82, resetsMs: Date.now() + 2 * 3_600_000 },
{ window: "seven_day", usedPercent: 95, resetsMs: null },
];
useAgents.setState({
tasks: new Map([["A", reported]]),
limits: new Map([["codex", limits]]),
});
render(<SessionEditor input={input("A")} />);
await screen.findByText("Answer A");
expect(screen.getByLabelText(/^Context /)).toHaveAttribute("data-tone", "warning");
const fiveHour = screen.getByLabelText(/^5-hour limit: 82% used/);
const sevenDay = screen.getByLabelText("Weekly limit: 95% used");
expect(fiveHour).toHaveTextContent("5h 82%");
expect(fiveHour).toHaveAttribute("data-tone", "warning");
expect(sevenDay).toHaveTextContent("7d 95%");
expect(sevenDay).toHaveAttribute("data-tone", "danger");
fireEvent.click(screen.getByRole("button", { name: "Usage limits" }));
expect(await screen.findByRole("dialog", { name: "Usage limits" })).toBeInTheDocument();
expect(screen.getByText("5-hour limit")).toBeInTheDocument();
expect(screen.getByText("Weekly limit")).toBeInTheDocument();
fireEvent.keyDown(document, { key: "Escape" });
expect(screen.queryByRole("dialog", { name: "Usage limits" })).toBeNull();
});
it("toggles fitWidth on the session root and remeasures off-screen rows from settings.agents.fitWindowWidth", async () => {
const frames: FrameRequestCallback[] = [];
const raf = vi.spyOn(window, "requestAnimationFrame").mockImplementation((cb) => {
+11
Переглянути файл
@@ -389,6 +389,17 @@ export function windowActions(): Action[] {
if (path) await attachProject(path);
},
},
{
// Import Module from Existing Sources for a folder without a build file.
id: "project.attachFolder",
title: t("app.action.attachProject"),
category: t("app.category.file"),
hidden: true,
when: "projectLocal",
run: async ({ arg }) => {
if (typeof arg === "string" && !desktopOnly()) await attachProject(arg);
},
},
{
id: "workspace.removeProject",
title: "Remove from Workspace",
+2 -2
Переглянути файл
@@ -317,11 +317,11 @@ export function activate(): () => void {
id: "maven.importExternal",
title: "Import Module from Existing Sources",
description:
"Choose a module directory outside the opened project. If it contains pom.xml, that Maven project is attached. The opened folder stays the project root, and neither POM is edited.",
"Choose a module directory. A pom.xml is linked as a Maven project and a Gradle settings or build script as a Gradle build; a folder with neither is attached as another root. The opened folder stays the project root, and no build file is edited.",
category: "Maven",
icon: "plus",
when: "projectOpen && !workspaceOpen",
keywords: ["import", "module", "existing", "sources", "external", "maven", "pom"],
keywords: ["import", "module", "existing", "sources", "external", "maven", "pom", "gradle"],
run: () => importModuleFromExistingSources(),
},
{
+50 -6
Переглянути файл
@@ -285,19 +285,63 @@ it("imports a module directory from Project Structure when that directory contai
expect(mocks.set).toHaveBeenCalledWith("project", "languages.java.maven.linkedProjects", '["/B/pom.xml"]');
});
it("does not link a module directory that has no pom.xml", async () => {
const fileEntry = (dir: string, name: string) => ({
name,
path: `${dir}/${name}`,
kind: "file" as const,
size: 1,
mtimeMs: 1,
ignored: false,
excluded: false,
hidden: false,
});
it("imports a module directory with a Gradle build as a linked Gradle build", async () => {
mocks.open.mockResolvedValue("/B");
mocks.readDir.mockResolvedValue([fileEntry("/B", "build.gradle.kts"), fileEntry("/B", "settings.gradle.kts")]);
mocks.link.mockResolvedValue(model);
await act(async () => {
await executeAction("maven.importExternal");
});
expect(mocks.show).toHaveBeenCalledWith("gradle");
expect(mocks.link).toHaveBeenCalledWith(["/B/settings.gradle.kts"]);
expect(mocks.set).not.toHaveBeenCalled();
});
it("attaches a module directory without a build file outside the project, after asking", async () => {
const attached = vi.fn();
const off = registerAction({ id: "project.attachFolder", title: "Attach", run: ({ arg }) => attached(arg) });
mocks.open.mockResolvedValue("/code/B");
mocks.readDir.mockResolvedValue([fileEntry("/code/B", "Main.java")]);
await act(async () => {
await executeAction("maven.importExternal");
});
off();
expect(mocks.confirm).toHaveBeenCalledWith(expect.objectContaining({ ok: "Attach" }));
expect(attached).toHaveBeenCalledWith("/code/B");
expect(mocks.set).not.toHaveBeenCalled();
expect(mocks.link).not.toHaveBeenCalled();
});
it("says a module directory without a build file inside the project is already part of it", async () => {
mocks.open.mockResolvedValue("/p/lib");
mocks.readDir.mockResolvedValue([]);
await act(async () => {
await executeAction("maven.importExternal");
});
expect(mocks.confirm).not.toHaveBeenCalled();
expect(mocks.notify).toHaveBeenCalledWith(expect.objectContaining({ title: "Already in the project" }));
});
it("reports a module directory that can't be read", async () => {
mocks.open.mockResolvedValue("/B");
mocks.readDir.mockRejectedValue(new Error("denied"));
await act(async () => {
await executeAction("maven.importExternal");
});
expect(mocks.set).not.toHaveBeenCalled();
expect(mocks.notify).toHaveBeenCalledWith(
expect.objectContaining({
level: "warning",
title: "Maven project was not imported",
body: expect.stringContaining("pom.xml"),
}),
expect.objectContaining({ level: "warning", title: "Module was not imported" }),
);
});
+91 -26
Переглянути файл
@@ -454,38 +454,99 @@ export function mavenPomForImport(picked: string): string {
return isPomFileName(path) ? path : `${path}/pom.xml`;
}
/** Gradle files that make a directory a Gradle build, most specific first. */
const GRADLE_BUILD_FILES = ["settings.gradle.kts", "settings.gradle", "build.gradle.kts", "build.gradle"];
/**
* Project Structure › Modules › Import Module from Existing Sources.
* A directory is the module folder; a `pom.xml` is that file. Either way the
* opened folder stays the project root and the existing link pipeline stores the POM.
* How a picked module directory (or its `pom.xml`) is imported: by its `pom.xml`, else by its
* Gradle settings or build script, else as plain sources. One listing of the directory itself,
* not a scan of its children; `null` when it can't be read.
*/
export async function moduleImportKind(
picked: string,
): Promise<{ kind: "maven" | "gradle"; file: string } | { kind: "sources"; dir: string } | null> {
const path = lexicalPath(comparablePath(picked)).replace(/\/$/, "");
const dir = isPomFileName(path) ? path.slice(0, path.lastIndexOf("/")) || "/" : path;
const files = await fileNames(dir);
if (!files) return null;
const has = (name: string) =>
hostOs() === "windows" ? [...files].find((f) => f.toLowerCase() === name.toLowerCase()) : files.has(name) && name;
const child = (name: string) => `${dir === "/" ? "" : dir}/${name}`;
const pom = has("pom.xml");
if (pom) return { kind: "maven", file: child(pom) };
for (const name of GRADLE_BUILD_FILES) {
const found = has(name);
if (found) return { kind: "gradle", file: child(found) };
}
return { kind: "sources", dir };
}
/**
* Project Structure › Modules › Import Module from Existing Sources: any directory, like IDEA.
* A `pom.xml` is linked as a Maven project, a Gradle settings or build script as a Gradle build;
* the opened folder stays the project root and no build file is edited. A directory without
* either outside the project is attached as another root, where its sources are detected; one
* inside the project is already part of it.
*/
export async function importModuleFromExistingSources() {
const root = useProject.getState().project?.root;
if (!root || useProject.getState().project?.workspace || !isTauri()) return;
try {
const { toolWindowService } = await import("@/workbench/contributions");
toolWindowService().show("maven");
} catch {
/* Tests and hosts without the tool-window service still link the POM. */
}
const path = await choosePath({
title: tx`Import Module from Existing Sources`,
directory: true,
defaultPath: root,
});
if (!path) return;
const pom = mavenPomForImport(path);
if (!(await directoryListsPom(pom))) {
const found = await moduleImportKind(path);
if (!found) {
notifications().notify({
group: "tools",
level: "warning",
title: tx`Maven project was not imported`,
body: tx`This directory has no pom.xml, so it was not imported.`,
key: "maven-import-no-pom",
title: tx`Module was not imported`,
body: tx`Cannot read ${path}.`,
key: "module-import-unreadable",
});
return;
}
const { link, rejected } = classifyPickedPoms(root, [pom]);
const showTool = async (id: string) => {
try {
const { toolWindowService } = await import("@/workbench/contributions");
toolWindowService().show(id);
} catch {
/* Tests and hosts without the tool-window service still link the build. */
}
};
if (found.kind === "gradle") {
await showTool("gradle");
await linkGradleBuildFiles(root, [found.file]);
return;
}
if (found.kind === "sources") {
const dir = lexicalPath(comparablePath(found.dir));
const base = lexicalPath(comparablePath(root).replace(/\/$/, ""));
const name = dir.split("/").pop() || dir;
if (dir === base || isInsideRoot(base, dir)) {
notifications().notify({
group: "tools",
level: "info",
title: tx`Already in the project`,
body: tx`${name} is inside the opened project, so its sources are already part of it.`,
key: "module-import-inside",
});
return;
}
if (
await confirm({
title: tx`Import Module from Existing Sources`,
message: tx`${name} has no pom.xml or Gradle build file. Attach it to this project as another root? Its source folders are detected automatically.`,
ok: tx`Attach`,
})
)
await executeAction("project.attachFolder", path);
return;
}
await showTool("maven");
const { link, rejected } = classifyPickedPoms(root, [found.file]);
if (link.length) await setLinked(root, link, true);
if (rejected.length)
notifications().notify({
@@ -497,22 +558,19 @@ export async function importModuleFromExistingSources() {
});
}
/** One directory listing: the selection's own `pom.xml`, not a scan of its children. */
async function directoryListsPom(pom: string): Promise<boolean> {
const slash = pom.lastIndexOf("/");
const dir = slash > 0 ? pom.slice(0, slash) : slash === 0 ? "/" : "";
const name = pom.slice(slash + 1);
if (!dir) return false;
/** The names of the regular files (or links to one) in `dir`; `null` when it can't be listed. */
async function fileNames(dir: string): Promise<Set<string> | null> {
if (!dir) return null;
try {
const { call, commands } = await import("@/platform/ipc");
const entries = await call(commands.fsReadDir(dir));
return entries.some(
(entry) =>
(hostOs() === "windows" ? entry.name.toLowerCase() === name.toLowerCase() : entry.name === name) &&
(entry.kind === "file" || (entry.kind === "symlink" && entry.targetKind === "file")),
return new Set(
entries
.filter((entry) => entry.kind === "file" || (entry.kind === "symlink" && entry.targetKind === "file"))
.map((entry) => entry.name),
);
} catch {
return false;
return null;
}
}
@@ -534,6 +592,13 @@ export async function linkGradleProjects() {
filters: [{ name: "Gradle build files", extensions: ["gradle", "kts"] }],
});
if (!paths.length || useProject.getState().project?.root !== root || gen !== generation) return;
await linkGradleBuildFiles(root, paths);
}
/** Links the Gradle builds of `paths` (settings or build scripts) into the project at `root`. */
async function linkGradleBuildFiles(root: string, paths: string[]) {
const gen = generation;
if (useProject.getState().project?.trusted === false) return;
const model = await call(commands.gradleLinkProjects(paths));
if (useProject.getState().project?.root !== root || gen !== generation) return;
const configs = await call(commands.runConfigs()).catch(() => useBuild.getState().configs);
+29
Переглянути файл
@@ -101,6 +101,35 @@ describe("multiline output", () => {
expect(new Set(lines(11).map((line) => line.id)).size).toBe(lines(11).length);
});
it("keeps only the newest output of a flood that outpaces the console, and counts what it dropped", () => {
vi.useFakeTimers();
adoptSession(14);
// 8 MiB arrives before the next frame: twice what may wait for it.
const line = "x".repeat(1023) + "\n";
for (let i = 0; i < 64; i++) appendConsoleQueued(14, "stdout", line.repeat(128));
appendConsoleQueued(14, "stdout", "last\n");
vi.advanceTimersToNextFrame();
const output = lines(14);
expect(output.at(-1)!.text).toBe("last\n");
expect(output.slice(0, -1).every((l) => l.text === line)).toBe(true);
// At most 4 MiB was parsed; every line that never reached the console is counted.
expect(output.length).toBeLessThanOrEqual(4097);
expect(useDebug.getState().consoleDropped[14]).toBe(64 * 128 + 1 - output.length);
});
it("counts lines trimmed past the line cap and resets the count on Clear", () => {
adoptSession(15);
appendConsole(15, "stdout", "line\n".repeat(60_000));
expect(useDebug.getState().consoleDropped[15]).toBe(60_000 - lines(15).length);
clearConsole(15);
expect(useDebug.getState().consoleDropped[15]).toBe(0);
});
it("breaks a line longer than the Run console's limit", () => {
appendConsole(16, "stdout", "y".repeat(20_000) + "\n");
expect(lines(16).map((l) => l.text.length)).toEqual([8000, 8000, 4001]);
});
it("trims a multiline event by the configured character buffer", () => {
const current = settings.workflowSettings();
vi.spyOn(settings, "workflowSettings").mockReturnValue({
+86 -3
Переглянути файл
@@ -2,11 +2,20 @@ import { act, cleanup, render, screen, waitFor } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const devtoolsUrl = vi.hoisted(() => vi.fn());
const previewUrl = vi.hoisted(() => vi.fn());
const readText = vi.hoisted(() => vi.fn());
const remote = vi.hoisted(() => ({ on: false }));
vi.mock("@/platform/ipc", async (importOriginal) => {
const real = await importOriginal<typeof import("@/platform/ipc")>();
return { ...real, commands: { ...real.commands, flutterDevtoolsUrl: devtoolsUrl, fsReadText: readText } };
return {
...real,
commands: {
...real.commands,
flutterDevtoolsUrl: devtoolsUrl,
flutterWidgetPreviewUrl: previewUrl,
fsReadText: readText,
},
};
});
vi.mock("@/platform/remote", async (importOriginal) => ({
...(await importOriginal<typeof import("@/platform/remote")>()),
@@ -18,9 +27,16 @@ import { getContext } from "@/platform/context";
import { useProject } from "@/platform/project";
import { useContributions } from "@/workbench/contributions";
import { useFlutterDevices } from "@/workbench/flutterDevices";
import { DEVTOOLS_WINDOWS, devToolsUrl, refreshDevTools, registerDevToolsWindows } from "../flutter/devTools";
import { useFlutterRunApps, type FlutterRunApp } from "@/workbench/flutterRunApps";
import {
DEVTOOLS_WINDOWS,
devToolsUrl,
refreshDevTools,
registerDevToolsWindows,
WIDGET_PREVIEW_WINDOW,
} from "../flutter/devTools";
import { useDebug, type DebugSession } from "../state";
import { FlutterDevToolsTabs, FlutterDevToolsView } from "../ui/FlutterDevTools";
import { FlutterDevToolsTabs, FlutterDevToolsView, FlutterWidgetPreviewView } from "../ui/FlutterDevTools";
const server = "http://127.0.0.1:9100";
const look = { theme: "dark" as const, background: "1e1f22" };
@@ -41,8 +57,11 @@ const uriOf = (f: HTMLIFrameElement) => new URL(f.src).searchParams.get("uri");
describe("Flutter DevTools windows", () => {
beforeEach(() => {
useFlutterRunApps.setState({}, true);
devtoolsUrl.mockReset();
devtoolsUrl.mockResolvedValue({ status: "ok", data: server });
previewUrl.mockReset();
previewUrl.mockResolvedValue({ status: "ok", data: "http://127.0.0.1:56207" });
useDebug.setState({ sessions: {}, active: null });
remote.on = false;
});
@@ -86,9 +105,13 @@ describe("Flutter DevTools windows", () => {
"flutter-devtools-extensions": "onUse",
"flutter-inspector": undefined,
});
// Widget Preview too, starting nothing until it opens.
expect(useContributions.getState().toolWindows.get(WIDGET_PREVIEW_WINDOW)?.stripe).toBe("onUse");
expect(previewUrl).not.toHaveBeenCalled();
useProject.setState({ project: { root: "/tool" } as never });
await waitFor(() => expect(ids()).not.toContain("flutter-inspector"));
expect(ids()).not.toContain(WIDGET_PREVIEW_WINDOW);
expect(getContext().flutterDevTools).toBe(false);
// Adding the SDK dependency later brings the windows.
@@ -149,6 +172,43 @@ describe("Flutter DevTools windows", () => {
await waitFor(() => expect(uriOf(frames()[0]!)).toBe("ws://two"));
});
it("connects to the apps of Run tabs too, in the order they started", async () => {
const runApp = (session: string, extra: Partial<FlutterRunApp>): FlutterRunApp => ({
session,
name: session,
appId: "A",
device: "sim",
started: true,
supportsRestart: true,
live: true,
startedAt: 2,
...extra,
});
render(
<>
<FlutterDevToolsTabs />
<FlutterDevToolsView id="flutter-inspector" />
</>,
);
setSessions(session(1, { vmServiceUri: "ws://debug", startedAt: 1 }));
act(() =>
useFlutterRunApps.setState({
r1: runApp("r1", { vmServiceUri: "ws://run" }),
r2: runApp("r2", { startedAt: 3 }),
}),
);
await waitFor(() => expect(frames().map(uriOf)).toEqual(["ws://debug", "ws://run"]));
expect(frames().map((f) => f.hidden)).toEqual([true, false]);
expect(screen.getByText("sim")).toBeTruthy();
act(() => useFlutterRunApps.setState({ r1: runApp("r1", { vmServiceUri: "ws://run", live: false }) }));
await waitFor(() => expect(frames().map(uriOf)).toEqual(["ws://debug"]));
cleanup();
// The other pages stay on the latest app, ended or not.
render(<FlutterDevToolsView id="flutter-devtools" />);
await waitFor(() => expect(uriOf(frames()[0]!)).toBe("ws://run"));
});
it("shows why the server is missing and asks again only on Refresh", async () => {
devtoolsUrl.mockResolvedValue({ status: "error", error: { kind: "unavailable", message: "boom" } });
render(<FlutterDevToolsView id="flutter-deep-links" />);
@@ -160,4 +220,27 @@ describe("Flutter DevTools windows", () => {
expect(devtoolsUrl).toHaveBeenCalledTimes(2);
expect(new URL(frames()[0]!.src).pathname).toBe("/deep-links");
});
it("shows the Widget Preview page in the IDE's theme, and why it is missing until Refresh", async () => {
previewUrl.mockResolvedValue({
status: "error",
error: { kind: "unavailable", message: "Flutter Widget Preview needs Flutter 3.38 or later." },
});
render(<FlutterWidgetPreviewView />);
await screen.findByText(/needs Flutter 3\.38/);
expect(frames()).toHaveLength(0);
previewUrl.mockResolvedValue({ status: "ok", data: "http://127.0.0.1:56207" });
act(() => refreshDevTools(WIDGET_PREVIEW_WINDOW));
await waitFor(() => expect(frames()).toHaveLength(1));
expect(previewUrl).toHaveBeenCalledTimes(2);
expect(frames()[0]!.src).toBe("http://127.0.0.1:56207/?theme=dark");
expect(devtoolsUrl).not.toHaveBeenCalled();
});
it("starts no Widget Preview for a remote window", async () => {
remote.on = true;
render(<FlutterWidgetPreviewView />);
await screen.findByText("Flutter Widget Preview isn't available in a remote project yet");
expect(previewUrl).not.toHaveBeenCalled();
});
});
+135
Переглянути файл
@@ -0,0 +1,135 @@
import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const editable = vi.hoisted(() => vi.fn());
const editArgument = vi.hoisted(() => vi.fn());
vi.mock("@/platform/ipc", async (importOriginal) => {
const real = await importOriginal<typeof import("@/platform/ipc")>();
return { ...real, commands: { ...real.commands, lspEditableArguments: editable, lspEditArgument: editArgument } };
});
import type { EditableArgument } from "@/platform/ipc";
import {
choices,
defaultText,
parseInput,
shownArguments,
shownValue,
typeLabel,
usePropertyEditorCaret,
} from "../flutter/propertyEditor";
import { FlutterPropertyEditorView } from "../ui/FlutterPropertyEditor";
const arg = (name: string, extra: Partial<EditableArgument>): EditableArgument => ({
name,
documentation: null,
type: "string",
value: null,
hasArgument: false,
defaultValue: null,
displayValue: null,
isRequired: false,
isNullable: false,
isDeprecated: false,
isEditable: true,
notEditableReason: null,
options: null,
...extra,
});
const align = arg("textAlign", {
type: "enum",
isNullable: true,
options: ["TextAlign.left", "TextAlign.center"],
defaultValue: "TextAlign.left",
});
describe("Flutter Property Editor arguments", () => {
it("shows values and types as DevTools does", () => {
expect(typeLabel(align)).toBe("TextAlign?");
expect(typeLabel(arg("data", {}))).toBe("String");
expect(shownValue({ ...align, hasArgument: true, value: "TextAlign.center" })).toBe(".center");
expect(shownValue(arg("x", { hasArgument: true }))).toBe("null");
expect(shownValue(arg("x", { type: "double", hasArgument: true, displayValue: "kPad * 2" }))).toBe("kPad * 2");
expect(shownValue(align)).toBe("");
expect(defaultText(align)).toBe(".left");
const deprecated = arg("old", { isDeprecated: true });
expect(shownArguments([deprecated, { ...deprecated, name: "set", hasArgument: true }]).map((a) => a.name)).toEqual([
"set",
]);
});
it("offers a bool's or enum's values, with the expression the code passes", () => {
expect(choices(arg("x", { type: "bool" }))).toEqual(["true", "false"]);
expect(choices({ ...align, hasArgument: true, displayValue: "myAlign" })).toEqual([
".left",
".center",
"myAlign",
"null",
]);
expect(choices(arg("x", { type: "int" }))).toBeNull();
});
it("sends only values of the parameter's type", () => {
const int = arg("n", { type: "int" });
expect(parseInput(int, " 3 ")).toEqual({ value: 3 });
expect(parseInput(int, "3.5")).toBeUndefined();
expect(parseInput(int, "")).toBeUndefined();
expect(parseInput({ ...int, isNullable: true }, "")).toEqual({ value: null });
expect(parseInput(arg("d", { type: "double" }), "8.5")).toEqual({ value: 8.5 });
expect(parseInput(arg("s", {}), " a ")).toEqual({ value: " a " });
expect(parseInput(arg("b", { type: "bool" }), "false")).toEqual({ value: false });
expect(parseInput(align, ".center")).toEqual({ value: "TextAlign.center" });
expect(parseInput(align, "null")).toEqual({ value: null });
expect(parseInput(align, ".right")).toBeUndefined();
});
});
describe("Flutter Property Editor window", () => {
const caret = (line: number, col: number) => ({ doc: 7, pos: { line, col }, synced: () => Promise.resolve() });
beforeEach(() => {
editable.mockReset();
editArgument.mockReset().mockResolvedValue({ status: "ok", data: null });
});
afterEach(() => {
cleanup();
usePropertyEditorCaret.setState({ caret: null });
});
it("lists the arguments at the caret and applies an edit on Enter", async () => {
editable.mockResolvedValue({
status: "ok",
data: {
name: "Text",
documentation: "Creates a text widget.\n\nMore.",
arguments: [
arg("data", { hasArgument: true, value: "Hello", isRequired: true }),
arg("maxLines", { type: "int", isNullable: true }),
],
},
});
render(<FlutterPropertyEditorView />);
screen.getByText("Open a Dart file to edit widget arguments");
act(() => usePropertyEditorCaret.setState({ caret: caret(3, 10) }));
const data = await screen.findByDisplayValue("Hello");
expect(editable).toHaveBeenCalledWith(7, { line: 3, col: 10 });
screen.getByText("Creates a text widget.");
const lines = screen.getByLabelText(/maxLines/);
fireEvent.change(lines, { target: { value: "two" } });
expect(lines.getAttribute("aria-invalid")).toBe("true");
fireEvent.keyDown(lines, { key: "Enter" });
expect(editArgument).not.toHaveBeenCalled();
fireEvent.change(data, { target: { value: "Bye" } });
fireEvent.keyDown(data, { key: "Enter" });
expect(editArgument).toHaveBeenCalledWith(7, { line: 3, col: 10 }, "data", "Bye");
});
it("says when the caret isn't in a call", async () => {
editable.mockResolvedValue({ status: "ok", data: null });
render(<FlutterPropertyEditorView />);
act(() => usePropertyEditorCaret.setState({ caret: caret(0, 0) }));
await waitFor(() => screen.getByText("Place the caret in a widget constructor call to edit its arguments"));
});
});
+10 -1
Переглянути файл
@@ -62,7 +62,7 @@ import { startPageProfile, stopPageProfile } from "./js/profile";
import { activeCapturedSnapshot, openHeapDump, saveHeapDump } from "./heap/heapDumpFiles";
import { browserLaunch, browserLaunchConfig, browserUrl, installedDebugBrowser, isBrowserConfig } from "./browser";
import { warnPinnedFlutterDevice } from "@/workbench/flutterDevices";
import { DEVTOOLS_WINDOWS, devToolsUrl, refreshDevTools } from "./flutter/devTools";
import { DEVTOOLS_WINDOWS, devToolsUrl, refreshDevTools, WIDGET_PREVIEW_WINDOW } from "./flutter/devTools";
import { debugUnsupportedReason, launchConfigFor, withEnvFiles } from "./launch";
import { attachConfig } from "./attach";
import {
@@ -891,6 +891,15 @@ export function registerDebugActions(): () => void {
for (const w of DEVTOOLS_WINDOWS) if (!id || id === w.id) refreshDevTools(w.id);
},
},
{
id: "debug.refreshWidgetPreview",
title: "Refresh Flutter Widget Preview",
category: "Debug",
icon: "refresh",
description: "Flutter: load the Widget Preview page again",
when: "flutterDevTools",
run: () => refreshDevTools(WIDGET_PREVIEW_WINDOW),
},
step("debug.stepOver", "Step Over", "over", "step-over"),
step("debug.stepInto", "Step Into", "into", "step-into"),
step("debug.stepOut", "Step Out", "out", "step-out"),
+54 -14
Переглянути файл
@@ -8,6 +8,7 @@ import { call, commands, onIdeEvent } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { lazyComponent } from "@/ui";
import { registerToolWindow } from "@/workbench/contributions";
import { trackPropertyEditorCaret } from "./propertyEditor";
export interface DevToolsWindow {
id: string;
@@ -84,6 +85,13 @@ export function devToolsUrl(
return `${server}/${window.page}?${query}`;
}
export const WIDGET_PREVIEW_WINDOW = "flutter-widget-preview";
/** The Widget Preview page in the IDE's look; like DevTools, a loaded page keeps its own. */
export function widgetPreviewUrl(server: string, look: DevToolsLook): string {
return `${server}/?${new URLSearchParams({ theme: look.theme })}`;
}
/** Bumped by Refresh, per window: the page loads again, on a server started anew if it is gone. */
export const useDevToolsRefresh = create<Record<string, number>>(() => ({}));
@@ -91,13 +99,22 @@ export function refreshDevTools(id: string) {
useDevToolsRefresh.setState((s) => ({ [id]: (s[id] ?? 0) + 1 }));
}
const view = (name: "FlutterDevToolsView" | "FlutterDevToolsTabs" | "FlutterDevToolsRefresh") =>
lazyComponent(() => import("../ui/FlutterDevTools").then((m) => m[name]));
const view = (
name:
| "FlutterDevToolsView"
| "FlutterDevToolsTabs"
| "FlutterDevToolsRefresh"
| "FlutterWidgetPreviewView"
| "FlutterWidgetPreviewRefresh",
) => lazyComponent(() => import("../ui/FlutterDevTools").then((m) => m[name]));
/** A Flutter project's `pubspec.yaml`, by the rule the run and debug backends use. */
export const isFlutterPubspec = (text: string) => text.includes("sdk: flutter");
/** Keeps the tool windows registered while the project's root `pubspec.yaml` depends on Flutter. */
/**
* Keeps the tool windows, the Property Editor's and Widget Preview's too, registered while the
* project's root `pubspec.yaml` depends on Flutter.
*/
export function registerDevToolsWindows(): () => void {
let dispose: (() => void)[] | null = null;
const sync = (flutter: boolean) => {
@@ -107,20 +124,43 @@ export function registerDevToolsWindows(): () => void {
dispose = null;
return;
}
dispose ??= DEVTOOLS_WINDOWS.map((w, i) =>
dispose ??= [
...DEVTOOLS_WINDOWS.map((w, i) =>
registerToolWindow({
id: w.id,
title: w.title,
icon: w.icon,
anchor: "right",
order: 40 + i,
// Only the Inspector is on the stripe until the others are first opened.
...(w.id === "flutter-inspector" ? {} : { stripe: "onUse" as const }),
component: view("FlutterDevToolsView"),
headerActions: view("FlutterDevToolsRefresh"),
...(w.app === "each" ? { headerContent: view("FlutterDevToolsTabs") } : {}),
}),
),
registerToolWindow({
id: w.id,
title: w.title,
icon: w.icon,
id: "flutter-property-editor",
title: "Flutter Property Editor",
icon: "toolwindow-flutter-property-editor",
anchor: "right",
order: 40 + i,
// Only the Inspector is on the stripe until the others are first opened.
...(w.id === "flutter-inspector" ? {} : { stripe: "onUse" as const }),
component: view("FlutterDevToolsView"),
headerActions: view("FlutterDevToolsRefresh"),
...(w.app === "each" ? { headerContent: view("FlutterDevToolsTabs") } : {}),
order: 40 + DEVTOOLS_WINDOWS.length,
stripe: "onUse",
component: lazyComponent(() => import("../ui/FlutterPropertyEditor").then((m) => m.FlutterPropertyEditorView)),
}),
);
// Its server starts when the window first opens.
registerToolWindow({
id: WIDGET_PREVIEW_WINDOW,
title: "Flutter Widget Preview",
icon: "toolwindow-flutter-widget-preview",
anchor: "right",
order: 41 + DEVTOOLS_WINDOWS.length,
stripe: "onUse",
component: view("FlutterWidgetPreviewView"),
headerActions: view("FlutterWidgetPreviewRefresh"),
}),
trackPropertyEditorCaret(),
];
};
let pubspec: string | null = null;
let check = 0;
+116
Переглянути файл
@@ -0,0 +1,116 @@
/**
* The Flutter Property Editor (Android Studio's, from DevTools): the arguments of the call at
* the caret in a Dart file, as the Dart server's `dart/textDocument/editableArguments` lists
* them, set with `dart/textDocument/editArgument`. The server applies its edit like any
* `workspace/applyEdit`, so it is undone with the editor's Undo.
*/
import { EditorView } from "@codemirror/view";
import { create } from "zustand";
import { activeEditor, documentSynced, registerEditorContribution, useEditorRegistry } from "@/editor/api";
import type { ArgumentValue, EditableArgument, Pos } from "@/platform/ipc";
export interface PropertyEditorCaret {
doc: number;
pos: Pos;
/** Resolves once the editor's edits reached the backend document the server reads. */
synced: () => Promise<void>;
}
/** The caret of the active Dart editor; a new object on every move or edit. */
export const usePropertyEditorCaret = create<{
caret: PropertyEditorCaret | null;
}>(() => ({ caret: null }));
const isDart = (h: ReturnType<typeof activeEditor>) => h?.ctx.language === "dart" && !h.ctx.virtual;
function syncCaret() {
const h = activeEditor();
if (!h || !isDart(h)) return usePropertyEditorCaret.setState({ caret: null });
const head = h.view.state.selection.main.head;
const line = h.view.state.doc.lineAt(head);
const synced = h.view.state.facet(documentSynced) ?? (() => Promise.resolve());
usePropertyEditorCaret.setState({
caret: {
doc: h.ctx.doc,
pos: { line: line.number - 1, col: head - line.from },
synced,
},
});
}
/** Follows the caret of Dart editors while the Property Editor is registered. */
export function trackPropertyEditorCaret(): () => void {
const offContribution = registerEditorContribution({
id: "flutter.propertyEditor",
extensions: (ctx) =>
ctx.language === "dart"
? EditorView.updateListener.of((u) => {
if ((u.selectionSet || u.docChanged) && activeEditor()?.view === u.view) syncCaret();
})
: [],
});
const offRegistry = useEditorRegistry.subscribe((s, prev) => s.active !== prev.active && syncCaret());
syncCaret();
return () => {
offContribution();
offRegistry();
usePropertyEditorCaret.setState({ caret: null });
};
}
/** DevTools leaves out deprecated parameters the call doesn't pass. */
export const shownArguments = (args: readonly EditableArgument[]) =>
args.filter((a) => !a.isDeprecated || a.hasArgument);
const enumType = (a: EditableArgument) => a.options?.[0]?.split(".")[0] ?? "enum";
/** The Dart type, as DevTools shows it: `String?`, `TextAlign`. */
export function typeLabel(a: EditableArgument): string {
const t = a.type === "enum" ? enumType(a) : a.type === "string" ? "String" : a.type;
return a.isNullable ? `${t}?` : t;
}
/** `TextAlign.center` as `.center`, like DevTools and the dot shorthand the server writes. */
const short = (a: EditableArgument, v: string) =>
a.type === "enum" && v.startsWith(`${enumType(a)}.`) ? v.slice(enumType(a).length) : v;
/** What the call passes: the literal, else its expression; `null` for an explicit null, "" when not passed. */
export function shownValue(a: EditableArgument): string {
if (a.displayValue != null) return short(a, a.displayValue);
if (a.value != null) return short(a, String(a.value));
return a.hasArgument ? "null" : "";
}
/** The default, shown while the call doesn't pass the argument. */
export const defaultText = (a: EditableArgument) => (a.defaultValue == null ? "" : short(a, String(a.defaultValue)));
/** The values a `bool` or enum argument picks from; `null` for the others, which are typed. */
export function choices(a: EditableArgument): string[] | null {
if (a.type !== "bool" && a.type !== "enum") return null;
const values = a.type === "bool" ? ["true", "false"] : (a.options ?? []).map((o) => short(a, o));
const current = shownValue(a);
if (current && current !== "null" && !values.includes(current)) values.push(current);
if (a.isNullable) values.push("null");
return values;
}
/** The value to send for the text the user entered; `undefined` when it isn't one of the type. */
export function parseInput(a: EditableArgument, input: string): { value: ArgumentValue | null } | undefined {
const t = input.trim();
if (a.isNullable && (t === "null" || (t === "" && a.type !== "string"))) return { value: null };
switch (a.type) {
case "string":
return { value: input };
case "int":
return /^-?\d+$/.test(t) ? { value: Number(t) } : undefined;
case "double":
return t !== "" && Number.isFinite(Number(t)) ? { value: Number(t) } : undefined;
case "bool":
return t === "true" || t === "false" ? { value: t === "true" } : undefined;
case "enum": {
const value = t.startsWith(".") ? `${enumType(a)}${t}` : t;
return a.options?.includes(value) ? { value } : undefined;
}
}
return undefined;
}
+77 -11
Переглянути файл
@@ -138,6 +138,8 @@ interface DebugState {
/** Session shown in the Debug tool window / title bar. */
active: DebugSessionId | null;
console: Record<number, ConsoleLine[]>;
/** Lines of a session's console dropped from the front, as the Run console counts them. */
consoleDropped: Record<number, number>;
watches: string[];
/** Incremented on every stop; views re-pull data when it changes. */
stopSeq: number;
@@ -152,6 +154,7 @@ export const useDebug = create<DebugState>(() => ({
sessions: {},
active: null,
console: {},
consoleDropped: {},
watches: [],
stopSeq: 0,
variablesEpoch: 0,
@@ -207,6 +210,14 @@ export const useExecutionPoint = create<ExecutionPoint>(() => ({
/** Console buffer: at most this many physical lines per session. */
const MAX_CONSOLE_LINES = 50_000;
/** Longer lines are broken up, as in the Run console, so one blob can't stall rendering. */
const MAX_LINE_LENGTH = 8_000;
/**
* Output of one session waiting for the next frame, in characters. A program printing faster
* than the console parses keeps only the newest output (the rest would be trimmed anyway), so
* the backlog and each frame's work stay bounded instead of growing with the flood.
*/
const MAX_PENDING_CHARS = 4 * 1024 * 1024;
let lineSeq = 0;
/** ANSI state per session and output category (a colour can span several output events). */
const ansiStreams = new Map<DebugSessionId, Map<string, AnsiStream>>();
@@ -589,8 +600,13 @@ export function appendConsole(session: DebugSessionId, category: string, raw: st
const prev = s.console[session] ?? [];
const next = [...prev];
appendConsoleLines(next, category, spans);
trimConsole(next);
return { console: { ...s.console, [session]: next } };
const trimmed = trimConsole(next);
return {
console: { ...s.console, [session]: next },
...(trimmed
? { consoleDropped: { ...s.consoleDropped, [session]: (s.consoleDropped[session] ?? 0) + trimmed } }
: {}),
};
});
republishForPorts();
}
@@ -608,6 +624,7 @@ export function appendConsoleQueued(session: DebugSessionId, category: string, r
} else {
pendingOutput.push({ session, category, raw });
}
capPendingOutput(session);
if (outputFlushHandle === null) {
outputFlushHandle = {
raf: requestAnimationFrame(flushConsoleOutput),
@@ -616,13 +633,41 @@ export function appendConsoleQueued(session: DebugSessionId, category: string, r
}
}
/** Lines dropped from the front of the pending output, per session, until the next flush. */
const pendingDropped = new Map<DebugSessionId, number>();
/** Drops the oldest pending output of `session` past [MAX_PENDING_CHARS], whole lines at a time. */
function capPendingOutput(session: DebugSessionId) {
let total = 0;
for (const chunk of pendingOutput) if (chunk.session === session) total += chunk.raw.length;
let excess = total - MAX_PENDING_CHARS;
while (excess > 0) {
const at = pendingOutput.findIndex((chunk) => chunk.session === session);
const chunk = pendingOutput[at]!;
// Up to the end of the line that holds the excess; a chunk without a later newline goes whole.
const end = chunk.raw.indexOf("\n", Math.min(excess, chunk.raw.length) - 1);
const cut = end < 0 ? chunk.raw.length : end + 1;
let lines = 0;
for (let i = chunk.raw.indexOf("\n"); i >= 0 && i < cut; i = chunk.raw.indexOf("\n", i + 1)) lines++;
pendingDropped.set(session, (pendingDropped.get(session) ?? 0) + lines);
if (cut >= chunk.raw.length) pendingOutput.splice(at, 1);
else chunk.raw = chunk.raw.slice(cut);
excess -= cut;
}
}
function flushConsoleOutput() {
cancelOutputFlush();
if (pendingOutput.length === 0) return;
const chunks = pendingOutput.splice(0);
const dropped = new Map(pendingDropped);
pendingDropped.clear();
const printed: Array<[DebugSessionId, string]> = [];
useDebug.setState((s) => {
const consoleBySession = { ...s.console };
const droppedBySession = { ...s.consoleDropped };
for (const [session, count] of dropped)
if (s.sessions[session]) droppedBySession[session] = (droppedBySession[session] ?? 0) + count;
for (const { session, category, raw } of chunks) {
if (!s.sessions[session]) continue;
const spans = outputSpans(session, category, raw);
@@ -632,10 +677,11 @@ function flushConsoleOutput() {
const prev = consoleBySession[session] ?? [];
const next = [...prev];
appendConsoleLines(next, category, spans);
trimConsole(next);
const trimmed = trimConsole(next);
if (trimmed) droppedBySession[session] = (droppedBySession[session] ?? 0) + trimmed;
consoleBySession[session] = next;
}
return { console: consoleBySession };
return { console: consoleBySession, consoleDropped: droppedBySession };
});
republishForPorts();
for (const [session, text] of printed) debugServerPage(session, text);
@@ -775,15 +821,28 @@ function appendConsoleLines(lines: ConsoleLine[], category: string, spans: Span[
line.spans = [];
}
}
line.text += piece;
line.spans = appendSpans(line.spans, [{ ...span, text: piece }]);
if (piece === "\n") line = undefined;
let rest = piece;
while (rest) {
if (!line) {
line = { id: ++lineSeq, category, text: "", spans: [] };
lines.push(line);
}
const room = piece === "\n" ? 1 : MAX_LINE_LENGTH - line.text.length;
const part = rest.slice(0, Math.max(room, 0));
rest = rest.slice(part.length);
if (part) {
line.text += part;
line.spans = appendSpans(line.spans, [{ ...span, text: part }]);
}
// A full line continues on the next one.
if (rest || piece === "\n") line = undefined;
}
}
}
}
/** Drops the oldest lines once past the line or configured character cap. */
function trimConsole(lines: ConsoleLine[]) {
/** Drops the oldest lines once past the line or configured character cap; returns how many. */
function trimConsole(lines: ConsoleLine[]): number {
let drop = 0;
if (lines.length > MAX_CONSOLE_LINES) {
drop = lines.length - MAX_CONSOLE_LINES + Math.ceil(MAX_CONSOLE_LINES / 10);
@@ -801,12 +860,17 @@ function trimConsole(lines: ConsoleLine[]) {
}
}
if (drop > 0) lines.splice(0, drop);
return drop;
}
export function clearConsole(session: DebugSessionId) {
flushConsoleOutput();
ansiStreams.delete(session);
useDebug.setState((s) => ({ console: { ...s.console, [session]: [] } }));
pendingDropped.delete(session);
useDebug.setState((s) => ({
console: { ...s.console, [session]: [] },
consoleDropped: { ...s.consoleDropped, [session]: 0 },
}));
}
// --- lifecycle ---------------------------------------------------------------
@@ -838,6 +902,7 @@ export async function startPreparedSession(
}),
},
console: { ...s.console, [id]: [] },
consoleDropped: { ...s.consoleDropped, [id]: 0 },
active: id,
}));
publishContext();
@@ -1621,7 +1686,8 @@ export function resetSessions() {
ansiStreams.clear();
announcedPorts.clear();
serverPages.clear();
useDebug.setState({ sessions: {}, active: null, console: {}, stopSeq: 0, variablesEpoch: 0 });
pendingDropped.clear();
useDebug.setState({ sessions: {}, active: null, console: {}, consoleDropped: {}, stopSeq: 0, variablesEpoch: 0 });
useExecutionPoint.setState({ path: null, line: 0, top: true, values: {}, variables: {} });
publishContext();
}
+3
Переглянути файл
@@ -122,6 +122,8 @@ export function DebugServiceConsole({ sessionId }: { sessionId: number }) {
export function DebugConsole({ session, interactive = true }: { session: DebugSession; interactive?: boolean }) {
const lines = useDebug((s) => s.console[session.id]);
const dropped = useDebug((s) => s.consoleDropped[session.id] ?? 0);
const count = dropped.toLocaleString();
const scroller = useRef<HTMLDivElement>(null);
const inner = useRef<HTMLDivElement>(null);
// Scroll to End: follows new output; scrolling up turns it off, back to the end turns it on.
@@ -450,6 +452,7 @@ export function DebugConsole({ session, interactive = true }: { session: DebugSe
onClose={closeFind}
/>
)}
{dropped > 0 && <div className={styles.consoleNotice}>{tx`${count} earlier lines were discarded`}</div>}
<div
ref={scroller}
className={clsx(styles.consoleOutput, !softWrap && styles.noWrap)}
+7
Переглянути файл
@@ -273,6 +273,13 @@
min-height: 0;
display: flex;
}
.consoleNotice {
flex: none;
padding: 4px 12px;
font-size: var(--fs-small);
color: var(--fg-subtle);
border-bottom: 1px solid var(--border);
}
.consoleToolbar {
flex: none;
width: 32px;
+119 -23
Переглянути файл
@@ -2,54 +2,102 @@
import { useEffect, useMemo, useState } from "react";
import { create } from "zustand";
import { useTx } from "@/platform/i18n";
import { call, commands, type DebugSessionId } from "@/platform/ipc";
import { call, commands } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { isRemoteWindow } from "@/platform/remote";
import { IconButton, Tabs, type TabItem } from "@/ui";
import { useFlutterDevices } from "@/workbench/flutterDevices";
import { useFlutterRunApps } from "@/workbench/flutterRunApps";
import {
currentDevToolsLook,
DEVTOOLS_WINDOWS,
devToolsUrl,
useDevToolsRefresh,
WIDGET_PREVIEW_WINDOW,
widgetPreviewUrl,
type DevToolsWindow,
} from "../flutter/devTools";
import { isLive, useDebug, type DebugSession } from "../state";
import { isLive, useDebug } from "../state";
import styles from "./FlutterDevTools.module.css";
const SANDBOX = "allow-scripts allow-same-origin allow-forms allow-popups allow-downloads";
/** The Inspector tab chosen by hand; a new or remaining app is shown otherwise. */
const useInspectorTab = create<{ session: DebugSessionId | null }>(() => ({ session: null }));
const useInspectorTab = create<{ app: string | null }>(() => ({ app: null }));
const hasApp = (s: DebugSession) => !!s.vmServiceUri;
function useRunningApps(): DebugSession[] {
const sessions = useDebug((s) => s.sessions);
return useMemo(() => Object.values(sessions).filter((s) => hasApp(s) && isLive(s)), [sessions]);
/** A Flutter app with a VM Service: of a Debug session, or of a Run tab (`flutter run --machine`). */
interface FlutterApp {
key: string;
name: string;
device?: string | null;
uri: string;
live: boolean;
startedAt: number;
}
function shownApp(apps: DebugSession[], chosen: DebugSessionId | null) {
return apps.find((s) => s.id === chosen) ?? apps.at(-1);
/** Every app with a VM Service, ended ones too, oldest first. */
function useFlutterApps(): FlutterApp[] {
const sessions = useDebug((s) => s.sessions);
const runApps = useFlutterRunApps();
return useMemo(() => {
const debug = Object.values(sessions).flatMap((s) =>
s.vmServiceUri
? [
{
key: `debug:${s.id}`,
name: s.name,
device: s.flutterDevice,
uri: s.vmServiceUri,
live: isLive(s),
startedAt: s.startedAt ?? 0,
},
]
: [],
);
const run = Object.values(runApps).flatMap((a) =>
a.vmServiceUri
? [
{
key: `run:${a.session}`,
name: a.name,
device: a.device,
uri: a.vmServiceUri,
live: a.live,
startedAt: a.startedAt,
},
]
: [],
);
return [...debug, ...run].sort((a, b) => a.startedAt - b.startedAt);
}, [sessions, runApps]);
}
function useRunningApps(): FlutterApp[] {
const apps = useFlutterApps();
return useMemo(() => apps.filter((a) => a.live), [apps]);
}
function shownApp(apps: FlutterApp[], chosen: string | null) {
return apps.find((a) => a.key === chosen) ?? apps.at(-1);
}
type Server = { url: string } | { error: string };
/** The server's address; asks again on Refresh and when the project's trust changes. */
function useDevToolsServer(refresh: number): Server | null {
function useServer(start: typeof commands.flutterDevtoolsUrl, refresh: number): Server | null {
const trusted = useProject((s) => s.project?.trusted);
const request = `${refresh}/${trusted}`;
const [answer, setAnswer] = useState<{ request: string; server: Server } | null>(null);
useEffect(() => {
let live = true;
call(commands.flutterDevtoolsUrl()).then(
call(start()).then(
(url) => live && setAnswer({ request, server: { url } }),
(e: unknown) => live && setAnswer({ request, server: { error: e instanceof Error ? e.message : String(e) } }),
);
return () => {
live = false;
};
}, [request]);
}, [start, request]);
return answer?.request === request ? answer.server : null;
}
@@ -80,18 +128,18 @@ function Frame({
function Inspector({ server, window }: { server: string; window: DevToolsWindow }) {
const tx = useTx();
const apps = useRunningApps();
const chosen = useInspectorTab((s) => s.session);
const chosen = useInspectorTab((s) => s.app);
const shown = shownApp(apps, chosen);
if (!shown) return <div className={styles.message}>{tx("No running applications")}</div>;
// One page per app, kept while another is shown: each holds its own selection.
return apps.map((app) => (
<Frame key={app.id} server={server} window={window} uri={app.vmServiceUri} hidden={app !== shown} />
<Frame key={app.key} server={server} window={window} uri={app.uri} hidden={app !== shown} />
));
}
function LatestApp({ server, window }: { server: string; window: DevToolsWindow }) {
// Ended sessions count: the page stays on the last app until another one starts.
const uri = useDebug((s) => Object.values(s.sessions).findLast(hasApp)?.vmServiceUri);
// Ended apps count: the page stays on the last app until another one starts.
const uri = useFlutterApps().at(-1)?.uri;
return <Frame server={server} window={window} uri={uri} />;
}
@@ -110,7 +158,7 @@ function LocalView({ id }: { id: string }) {
const tx = useTx();
const window = DEVTOOLS_WINDOWS.find((w) => w.id === id)!;
const refresh = useDevToolsRefresh((s) => s[id] ?? 0);
const server = useDevToolsServer(refresh);
const server = useServer(commands.flutterDevtoolsUrl, refresh);
if (!server) return <div className={styles.message}>{tx("Loading Flutter DevTools…")}</div>;
if ("error" in server)
return (
@@ -127,20 +175,20 @@ function LocalView({ id }: { id: string }) {
export function FlutterDevToolsTabs() {
const tx = useTx();
const apps = useRunningApps();
const chosen = useInspectorTab((s) => s.session);
const chosen = useInspectorTab((s) => s.app);
const devices = useFlutterDevices((s) => s.list?.devices);
if (!apps.length) return null;
const items: TabItem[] = apps.map((app) => {
const device = devices?.find((d) => d.id === app.flutterDevice)?.name ?? app.flutterDevice ?? app.name;
return { id: String(app.id), label: device, text: device };
const device = devices?.find((d) => d.id === app.device)?.name ?? app.device ?? app.name;
return { id: app.key, label: device, text: device };
});
return (
<Tabs
variant="compact"
aria-label={tx("Running applications")}
items={items}
activeId={String(shownApp(apps, chosen)?.id)}
onSelect={(id) => useInspectorTab.setState({ session: +id as DebugSessionId })}
activeId={shownApp(apps, chosen)?.key ?? null}
onSelect={(app) => useInspectorTab.setState({ app })}
/>
);
}
@@ -157,3 +205,51 @@ export function FlutterDevToolsRefresh({ id }: { id: string }) {
/>
);
}
/** The `@Preview` widgets of the project, from its `flutter widget-preview` server. */
export function FlutterWidgetPreviewView() {
const tx = useTx();
// Like DevTools, the server would start on the remote machine, out of reach.
const content = isRemoteWindow() ? (
<div className={styles.message}>{tx("Flutter Widget Preview isn't available in a remote project yet")}</div>
) : (
<WidgetPreview />
);
return <div className={styles.pane}>{content}</div>;
}
function WidgetPreview() {
const tx = useTx();
const refresh = useDevToolsRefresh((s) => s[WIDGET_PREVIEW_WINDOW] ?? 0);
const server = useServer(commands.flutterWidgetPreviewUrl, refresh);
const [look] = useState(() => currentDevToolsLook());
// The first start compiles the preview environment, which can take a minute.
if (!server) return <div className={styles.message}>{tx("Starting Flutter Widget Preview…")}</div>;
if ("error" in server)
return (
<div className={styles.message}>
{tx("Flutter Widget Preview start-up failed")}: {server.error}
</div>
);
return (
<iframe
key={refresh}
className={styles.frame}
title={tx("Flutter Widget Preview")}
src={widgetPreviewUrl(server.url, look)}
sandbox={SANDBOX}
/>
);
}
export function FlutterWidgetPreviewRefresh() {
return (
<IconButton
icon="refresh"
size="small"
iconSize={16}
action="debug.refreshWidgetPreview"
title="Refresh Flutter Widget Preview"
/>
);
}
+51
Переглянути файл
@@ -0,0 +1,51 @@
.pane {
display: flex;
flex-direction: column;
gap: var(--space-2);
height: 100%;
overflow: auto;
padding: var(--space-2) var(--space-3);
font-family: var(--font-ui);
font-size: var(--fs-ui);
}
.widget {
color: var(--fg-strong);
font-weight: 600;
}
.doc {
color: var(--fg-muted);
}
.row {
display: flex;
flex-direction: column;
gap: var(--space-0-5);
}
.label {
display: flex;
gap: var(--space-2);
align-items: baseline;
}
.name {
color: var(--fg);
}
.deprecated {
color: var(--fg-deprecated);
text-decoration: line-through;
}
.type {
color: var(--fg-muted);
font-family: var(--font-mono);
font-size: var(--fs-small);
}
.error {
color: var(--danger);
font-size: var(--fs-small);
}
+156
Переглянути файл
@@ -0,0 +1,156 @@
/** The Flutter Property Editor tool window: the arguments of the call at the caret, editable. */
import { useEffect, useId, useState } from "react";
import clsx from "clsx";
import { useTx } from "@/platform/i18n";
import { call, commands, type ArgumentValue, type EditableArgument, type EditableArguments } from "@/platform/ipc";
import { EmptyState, Input, Select } from "@/ui";
import {
choices,
defaultText,
parseInput,
shownArguments,
shownValue,
typeLabel,
usePropertyEditorCaret,
type PropertyEditorCaret,
} from "../flutter/propertyEditor";
import styles from "./FlutterPropertyEditor.module.css";
/** Caret moves settle before the server is asked (DevTools waits 600 ms). */
const DEBOUNCE_MS = 300;
type Shown =
| { caret: PropertyEditorCaret; args: EditableArguments | null }
| { caret: PropertyEditorCaret; error: string };
const message = (e: unknown) => (e instanceof Error ? e.message : String(e));
export function FlutterPropertyEditorView() {
const tx = useTx();
const caret = usePropertyEditorCaret((s) => s.caret);
const [answer, setAnswer] = useState<Shown | null>(null);
const shown = caret ? answer : null;
const [failed, setFailed] = useState<{ name: string; error: string } | null>(null);
useEffect(() => {
if (!caret) return;
let live = true;
const timer = setTimeout(() => {
caret
.synced()
.then(() => call(commands.lspEditableArguments(caret.doc, caret.pos)))
.then(
(args) => live && setAnswer({ caret, args }),
(e: unknown) => live && setAnswer({ caret, error: message(e) }),
);
}, DEBOUNCE_MS);
return () => {
live = false;
clearTimeout(timer);
};
}, [caret]);
if (!shown) return <EmptyState title={tx("Open a Dart file to edit widget arguments")} />;
if ("error" in shown) return <EmptyState title={tx("Couldn't get the widget's arguments")}>{shown.error}</EmptyState>;
const { args } = shown;
if (!args) return <EmptyState title={tx("Place the caret in a widget constructor call to edit its arguments")} />;
const edit = (a: EditableArgument, value: ArgumentValue | null) => {
setFailed(null);
call(commands.lspEditArgument(shown.caret.doc, shown.caret.pos, a.name, value)).catch((e: unknown) =>
setFailed({ name: a.name, error: message(e) }),
);
};
const list = shownArguments(args.arguments);
const summary = args.documentation?.split("\n\n")[0];
return (
<div className={styles.pane}>
{args.name && <div className={styles.widget}>{args.name}</div>}
{summary && <div className={styles.doc}>{summary}</div>}
{list.length === 0 && <div className={styles.doc}>{tx("No editable arguments")}</div>}
{list.map((a) => (
<Row
key={`${args.name}/${a.name}`}
arg={a}
error={failed?.name === a.name ? failed.error : undefined}
onEdit={(v) => edit(a, v)}
/>
))}
</div>
);
}
function Row({
arg,
error,
onEdit,
}: {
arg: EditableArgument;
error?: string;
onEdit: (value: ArgumentValue | null) => void;
}) {
const id = useId();
const options = choices(arg);
return (
<div className={styles.row} title={arg.documentation ?? undefined}>
<label htmlFor={id} className={styles.label}>
<span className={clsx(styles.name, arg.isDeprecated && styles.deprecated)}>
{arg.name}
{arg.isRequired && "*"}
</span>
<span className={styles.type}>{typeLabel(arg)}</span>
</label>
{options ? (
<Select
id={id}
value={shownValue(arg) || null}
placeholder={defaultText(arg)}
options={options.map((o) => ({ value: o, label: o, verbatim: true }))}
disabled={!arg.isEditable}
title={arg.notEditableReason ?? undefined}
onChange={(v) => {
const parsed = v === shownValue(arg) ? undefined : parseInput(arg, v);
if (parsed) onEdit(parsed.value);
}}
/>
) : (
<TextField id={id} arg={arg} onEdit={onEdit} />
)}
{error && <div className={styles.error}>{error}</div>}
</div>
);
}
/** Applied on Enter or leaving the field; Escape restores what the code passes. */
function TextField({
id,
arg,
onEdit,
}: {
id: string;
arg: EditableArgument;
onEdit: (value: ArgumentValue | null) => void;
}) {
const shown = shownValue(arg);
// A draft for what the code passed when typing began: an edit or caret move replaces it.
const [draft, setDraft] = useState<{ base: string; text: string } | null>(null);
const text = draft?.base === shown ? draft.text : shown;
const setText = (t: string) => setDraft({ base: shown, text: t });
const parsed = text === shown ? undefined : parseInput(arg, text);
const commit = () => parsed && onEdit(parsed.value);
return (
<Input
id={id}
mono
value={text}
placeholder={defaultText(arg)}
invalid={text !== shown && !parsed}
disabled={!arg.isEditable}
title={arg.notEditableReason ?? undefined}
onChange={(e) => setText(e.currentTarget.value)}
onBlur={commit}
onKeyDown={(e) => {
if (e.key === "Enter") commit();
else if (e.key === "Escape") setText(shown);
}}
/>
);
}
+10 -2
Переглянути файл
@@ -5,6 +5,7 @@ import { userScopes } from "@/platform/scopes";
import { useEditorPrefs } from "@/platform/editorSettings";
import {
VIEW_MODES,
hasVisibleSelection,
previewTabEnabled,
setPreviewTabEnabled,
setScopeView,
@@ -83,10 +84,11 @@ const BEHAVIOR_OPTIONS: Array<[ToggleOption, string]> = [
export const OPTION_LABELS = [...APPEARANCE_OPTIONS, FOLDERS_FIRST, ...BEHAVIOR_OPTIONS];
/** Header controls of the Project tool window (IDEA: Locate, Expand/Collapse All). */
/** Header controls of the Project tool window. */
export function ProjectHeaderActions() {
// IDEA hides Select Opened File while Always Select Opened File keeps the tree in sync.
const alwaysSelect = useProjectTree((s) => s.options.autoscrollFromSource);
const hasSelection = useProjectTree(hasVisibleSelection);
return (
<>
{!alwaysSelect && (
@@ -98,7 +100,13 @@ export function ProjectHeaderActions() {
size="small"
/>
)}
<IconButton icon="expand-all" action="project.expandAll" title="Expand All" size="small" />
<IconButton
icon="expand-all"
action="project.expandSelected"
title="Expand Selected"
size="small"
disabled={!hasSelection}
/>
<IconButton icon="collapse-all" action="project.collapseAll" title="Collapse All" size="small" />
</>
);
+164
Переглянути файл
@@ -187,6 +187,170 @@ describe("ProjectView", () => {
await waitFor(() => expect(rows()).toEqual(["acme/w/acme", "build", "src", "App.kt", "Util.kt", "README.md"]));
});
it("restores visible expansion across workspace roots while a compacted folder is slow", async () => {
const left = "/left/src/nested/deep";
const right = "/right/src/package";
fs = new MemoryFs({
[`${left}/New.ts`]: "new",
[`${right}/Ready.ts`]: "ready",
"/left/closed/orphan/Skipped.ts": "",
"/left/ignored/inside/Hidden.ts": "",
});
fs.ignored.add("/left/ignored");
const gate = deferred<void>();
const read = fs.readDir.bind(fs);
const spy = vi.spyOn(fs, "readDir").mockImplementation(async (path) => {
if (path === left) await gate.promise;
return read(path);
});
const { showExcluded } = useProjectTree.getState().options;
setViewOption("showExcluded", false);
try {
setProjectFsForTests(fs, ROOT);
localStorage.setItem(
`openidea.projectTree.expanded:${ROOT}`,
JSON.stringify([
"/left",
"/left/src",
"/left/src/nested",
left,
"/right",
"/right/src",
right,
"/left/closed/orphan",
"/left/ignored",
"/left/ignored/inside",
]),
);
initProjectTree(ROOT, "Workspace", ["/left", "/right"]);
const { rows } = setup();
await waitFor(() => expect(rows()).toContain("Ready.ts"));
expect(spy).toHaveBeenCalledWith(left);
expect(rows()).not.toContain("New.ts");
gate.resolve();
await waitFor(() => expect(rows()).toContain("New.ts"));
expect(spy.mock.calls.map(([path]) => path).sort()).toEqual([
"/left",
"/left/src",
"/left/src/nested",
left,
"/right",
"/right/src",
right,
]);
} finally {
gate.resolve();
act(() => setViewOption("showExcluded", showExcluded));
}
});
it("reveals ready selected folders from the toolbar while a compacted sibling waits", async () => {
const blocked = `${ROOT}/slow/nested/leaf`;
fs = new MemoryFs(
{
[`${ROOT}/fast/pkg/leaf/Ready.ts`]: "ready",
[`${blocked}/Blocked.ts`]: "blocked",
[`${ROOT}/unselected/Skipped.ts`]: "",
[`${ROOT}/README.md`]: "",
"/outside/Linked.ts": "",
},
ROOT,
{ [`${ROOT}/linked-parent/link`]: "/outside" },
);
setProjectFsForTests(fs, ROOT);
const gate = deferred<void>();
const done = deferred<void>();
const read = fs.readDir.bind(fs);
const spy = vi.spyOn(fs, "readDir").mockImplementation(async (path) => {
if (path === blocked) await gate.promise;
const entries = await read(path);
if (path === blocked) done.resolve();
return entries;
});
setContext("projectOpen", true);
render(<ProjectHeaderActions />);
const { rows, row, tree } = setup();
const button = screen.getByRole("button", { name: "Expand Selected" });
expect(button).toBeDisabled();
expect(button).toHaveAttribute("data-tooltip", "Expand Selected");
expect(getAction("project.expandSelected")?.title).toBe("Expand Selected");
expect(getAction("project.expandAll")?.title).toBe("Expand All");
expect(await executeAction("project.expandSelected")).toBe(false);
await waitFor(() => expect(rows()).toContain("fast"));
fireEvent.mouseDown(row("README.md"));
expect(button).toBeEnabled();
expect(await executeAction("project.expandSelected")).toBe(true);
expect(spy.mock.calls).toEqual([[ROOT]]);
fireEvent.mouseDown(row("fast"));
fireEvent.mouseDown(row("linked-parent"), { metaKey: true });
fireEvent.mouseDown(row("slow"), { metaKey: true });
const selection = useProjectTree.getState().selected;
expect(selection).toEqual(new Set([`${ROOT}/fast`, `${ROOT}/linked-parent`, `${ROOT}/slow`]));
tree.scrollTop = 18;
const scrollTop = tree.scrollTop;
try {
fireEvent.click(button);
await waitFor(() => expect(rows()).toContain("Ready.ts"));
expect(spy).toHaveBeenCalledWith(blocked);
expect(rows()).not.toContain("Blocked.ts");
expect(rows()).toContain("link");
expect(rows()).not.toContain("Linked.ts");
expect(spy).not.toHaveBeenCalledWith(`${ROOT}/linked-parent/link`);
expect(spy).not.toHaveBeenCalledWith(`${ROOT}/unselected`);
expect(useProjectTree.getState().selected).toBe(selection);
expect(tree.scrollTop).toBe(scrollTop);
fireEvent.mouseDown(row("Ready.ts"));
await act(async () => void (await executeAction("project.collapseAll")));
await act(async () => {
gate.resolve();
await done.promise;
});
const root = row("acme");
expect(root).toHaveAttribute("aria-expanded", "false");
expect(rows()).toEqual(["acme/w/acme"]);
expect(button).toBeDisabled();
expect(useProjectTree.getState().listings.has(blocked)).toBe(false);
const paths = spy.mock.calls.map(([path]) => path);
expect(paths).toHaveLength(new Set(paths).size);
fireEvent.mouseDown(root);
fireEvent.keyDown(tree, { key: "ArrowRight" });
expect(root).toHaveAttribute("aria-expanded", "true");
expect(rows()).toContain("README.md");
expect(rows()).not.toContain("Ready.ts");
expect(rows()).not.toContain("Blocked.ts");
} finally {
gate.resolve();
}
});
it("closes every workspace root and reopens only the chosen root", async () => {
fs = new MemoryFs({ "/left/Left.ts": "left", "/right/Right.ts": "right" });
setProjectFsForTests(fs, ROOT);
initProjectTree(ROOT, "Workspace", ["/left", "/right"]);
setContext("projectOpen", true);
render(<ProjectHeaderActions />);
const { rows, row, tree } = setup();
await waitFor(() => expect(rows()).toEqual(["left/left", "Left.ts", "right/right", "Right.ts"]));
fireEvent.click(screen.getByRole("button", { name: "Collapse All" }));
expect(rows()).toEqual(["left/left", "right/right"]);
expect(row("left")).toHaveAttribute("aria-expanded", "false");
expect(row("right")).toHaveAttribute("aria-expanded", "false");
fireEvent.mouseDown(row("right"));
fireEvent.keyDown(tree, { key: "ArrowRight" });
expect(rows()).toEqual(["left/left", "right/right", "Right.ts"]);
expect(row("left")).toHaveAttribute("aria-expanded", "false");
expect(row("right")).toHaveAttribute("aria-expanded", "true");
});
it("opens the selected file in the right split with ⇧Enter; a folder still expands", async () => {
dispatchViaKeymap();
const { tree, row, rows } = setup();
+2 -1
Переглянути файл
@@ -90,6 +90,7 @@ import {
clearRevealRequest,
explainHiddenPath,
loadDir,
loadVisibleDirs,
loadOutline,
previewTabEnabled,
revealPath,
@@ -512,7 +513,7 @@ export function ProjectView() {
// Load folders that are expanded (restored state, reveal, chains) but not read yet.
useEffect(() => {
for (const p of info.pending) void loadDir(p);
loadVisibleDirs(info.pending);
}, [info.pending]);
// Restored file expansion and enabling Show Members also need outlines.
+12
Переглянути файл
@@ -45,6 +45,8 @@ import {
collapseAll,
currentModel,
expandAll,
expandSelected,
hasVisibleSelection,
modeShows,
reloadAll,
revealPath,
@@ -551,6 +553,16 @@ export function registerProjectActions(): () => void {
return expandAll(lead?.dir && !lead.root ? lead.key : undefined);
},
},
{
id: "project.expandSelected",
title: "Expand Selected",
category: "Project View",
icon: "expand-all",
when: OPEN,
keyWhen: FOCUS,
enabled: () => hasVisibleSelection(),
run: expandSelected,
},
{
id: "project.collapseAll",
title: "Collapse All",
+46 -1
Переглянути файл
@@ -1,6 +1,7 @@
import { describe, expect, it } from "vitest";
import { folderKind, outputFolderKind } from "./folderKind";
import type { RootFolder } from "@/platform/languageSettings";
import { validateProjectStructure, type RootFolder } from "@/platform/languageSettings";
import { directoryIconName } from "@/ui/folderPresentation";
const build = {
modules: new Map([
["", "maven"],
@@ -40,6 +41,13 @@ describe("JVM folder presentation", () => {
expect(kind(path, true)).toBe("excluded");
expect(outputFolderKind(path, new Map())).toBeNull();
});
it("shows packages below source sets a Gradle sync or an Eclipse .classpath reported", () => {
const noModules = { modules: new Map(), spring: false };
for (const detectedFrom of ["Gradle", "lib/.classpath"]) {
const rs: RootFolder[] = [{ path: "lib/src", kind: "source", detectedFrom }];
expect(folderKind({ path: "/p/lib/src/com/example", excluded: false }, rs, "/p", noModules)).toBe("package");
}
});
it("shows packages below custom marked JVM source roots", () => {
expect(kind("custom/com/example", false, [{ path: "custom", kind: "source", detectedFrom: null }])).toBe("package");
});
@@ -58,4 +66,41 @@ describe("JVM folder presentation", () => {
"does not guess output roles for %s",
(path) => expect(outputFolderKind(path, build.modules)).toBeNull(),
);
it("isolates output folder detection for attached workspace members from the primary relative key space", () => {
const emptyStructure = validateProjectStructure(undefined);
const attached = [
{ root: "/other", structure: emptyStructure, detected: [] },
{ root: "/web", structure: emptyStructure, detected: [] },
];
expect(
directoryIconName({
path: "/other/target/generated-sources/gen",
root: "/p",
roots: [],
attached,
build: {
modules: new Map([
["", "gradle"],
["/other", "maven"],
]),
spring: false,
},
}),
).toBe("folder-generated-source");
expect(
directoryIconName({
path: "/web/target/classes",
root: "/p",
roots: [],
attached,
build: {
modules: new Map([
["", "maven"],
["/other", "maven"],
]),
spring: false,
},
}),
).toBe("folder");
});
});
+6 -44
Переглянути файл
@@ -1,18 +1,11 @@
/** Folder icon kind in the project view, from the effective roots. */
import { rootFor, rootRole, type FolderRole, type RootFolder } from "@/platform/languageSettings";
import { basename, relativePath } from "@/platform/project";
import type { FolderKind } from "@/ui";
import type { ProjectNode } from "./model";
import { packageKindAt } from "./packages";
import type { RootFolder } from "@/platform/languageSettings";
import type { BuildPresentation } from "@/platform/projectPresentation";
import type { FolderKind } from "@/ui";
import { directoryFolderKind, outputFolderKind } from "@/ui/folderPresentation";
import type { ProjectNode } from "./model";
const ROLE_KIND: Record<FolderRole, FolderKind> = {
source: "source",
test: "test",
resources: "resources",
testResources: "testResources",
excluded: "excluded",
};
export { outputFolderKind };
/**
* Project Structure marks and roots detected from build files. Like IDEA, only
@@ -25,36 +18,5 @@ export function folderKind(
build?: BuildPresentation,
detected: readonly RootFolder[] = [],
): FolderKind {
const rel = root ? (node.path === root ? "" : relativePath(root, node.path)) : null;
const role = rel === null ? null : rootRole(roots, rel);
const exact = roots.find((r) => r.path === rel);
const output = rel === null ? null : outputFolderKind(rel, build?.modules ?? new Map());
if (role && (exact?.detectedFrom === null || output === "generatedSource" || output === "generatedTest"))
return ROLE_KIND[role];
const containing = rel === null ? null : rootFor(roots, rel);
if (node.excluded || containing?.kind === "excluded") return "excluded";
if (role) return ROLE_KIND[role];
if (output) return output;
if (rel !== null && (containing?.kind === "source" || containing?.kind === "test")) {
const inModule = [...(build?.modules.keys() ?? [])].some((dir) => !dir || rel.startsWith(`${dir}/`));
if (inModule || packageKindAt(rel, roots, detected) === "jvm") return "package";
}
return basename(node.path) === ".github" ? "github" : "plain";
}
/** Output roles are relative to detected JVM modules, never arbitrary package names. */
export function outputFolderKind(rel: string, modules: BuildPresentation["modules"]): FolderKind | null {
const parts = rel.split("/");
for (let i = 0; i < parts.length - 1; i++) {
const output = parts[i];
if (output !== "target" && output !== "build") continue;
const tool = modules.get(parts.slice(0, i).join("/"));
if (tool !== (output === "target" ? "maven" : "gradle")) continue;
const path = parts.slice(i + 1).join("/");
if (/^generated-test-sources(\/|$)/.test(path) || /^generated\/.*\btest\b/.test(path)) return "generatedTest";
if (/^(generated-sources|generated)(\/|$)/.test(path)) return "generatedSource";
if (/^(classes|test-classes)(\/|$)/.test(path)) return "compiled";
if (/^(site\/apidocs|apidocs|docs\/javadoc|javadoc)(\/|$)/.test(path)) return "javadoc";
}
return null;
return directoryFolderKind(node.path, roots, root, build, detected, !!node.excluded);
}
+44
Переглянути файл
@@ -0,0 +1,44 @@
import { describe, expect, it } from "vitest";
import type { RootFolder } from "@/platform/languageSettings";
import { javaPackageAt, pastedJavaClass, withJavaPackage } from "./javaPaste";
describe("Java code pasted into the Project view", () => {
it("is named after its first public top-level type, else its first", () => {
const text = "package a;\n/** Doc */\n@Deprecated class Helper {}\npublic final class Main<T> { class Inner {} }\n";
expect(pastedJavaClass(text)).toBe("Main");
expect(pastedJavaClass("record Point(int x, int y) {}\nenum Color { RED }")).toBe("Point");
expect(pastedJavaClass("public @interface Marker {}")).toBe("Marker");
expect(pastedJavaClass("interface Shape { double area(); }")).toBe("Shape");
});
it("is not code without a type: a statement, prose, a class only named in a comment", () => {
expect(pastedJavaClass("int x = 1;")).toBeNull();
expect(pastedJavaClass("hello world")).toBeNull();
expect(pastedJavaClass("// see class Foo\nfoo();")).toBeNull();
expect(pastedJavaClass("")).toBeNull();
});
it("takes the package of its folder below a Java source or test root", () => {
const roots: RootFolder[] = [
{ path: "app/src/main/java", kind: "source", detectedFrom: "app/pom.xml" },
{ path: "app/src/test/java", kind: "test", detectedFrom: "app/pom.xml" },
{ path: "web/src", kind: "source", detectedFrom: "web/package.json" },
];
expect(javaPackageAt("app/src/main/java/com/acme", roots)).toBe("com.acme");
expect(javaPackageAt("app/src/test/java/com", roots)).toBe("com");
expect(javaPackageAt("app/src/main/java", roots)).toBe("");
expect(javaPackageAt("docs", roots)).toBeNull();
expect(javaPackageAt("web/src/lib", roots)).toBeNull();
});
it("declares the folder's package, replacing or adding the statement", () => {
expect(withJavaPackage("package old.pkg;\n\nclass A {}", "com.acme")).toBe("package com.acme;\n\nclass A {}");
expect(withJavaPackage("import java.util.List;\nclass A {}", "com.acme")).toBe(
"package com.acme;\n\nimport java.util.List;\nclass A {}",
);
const same = "package com . acme;\nclass A {}";
expect(withJavaPackage(same, "com.acme")).toBe(same);
// Pasted into the source root itself: the default package keeps the code as it is.
expect(withJavaPackage("package old;\nclass A {}", "")).toBe("package old;\nclass A {}");
});
});
+66
Переглянути файл
@@ -0,0 +1,66 @@
// IDEA's Java file paste: Java code pasted into a folder of the Project view becomes
// `<Class>.java`, declaring the folder's package.
import { javaLanguage } from "@codemirror/lang-java";
import type { SyntaxNode } from "@lezer/common";
import { rootFor, type RootFolder } from "@/platform/languageSettings";
import { isJvmSourcePackage } from "@/ui/folderPresentation";
const TYPE_DECLARATIONS = new Set([
"ClassDeclaration",
"InterfaceDeclaration",
"EnumDeclaration",
"RecordDeclaration",
"AnnotationTypeDeclaration",
]);
const typeName = (text: string, declaration: SyntaxNode) => {
const name = declaration.getChild("Definition") ?? declaration.getChild("Identifier");
return name ? text.slice(name.from, name.to) : null;
};
const isPublic = (text: string, declaration: SyntaxNode) => {
const modifiers = declaration.getChild("Modifiers");
return !!modifiers && /(^|\s)public(\s|$)/.test(text.slice(modifiers.from, modifiers.to));
};
/**
* The class pasted Java code is named after: its first public top-level type, else its first
* top-level type; null when the text declares none (a statement, plain prose).
*/
export function pastedJavaClass(text: string): string | null {
if (!/\b(class|interface|enum|record)\b/.test(text)) return null;
const top = javaLanguage.parser.parse(text).topNode;
let first: string | null = null;
for (let node = top.firstChild; node; node = node.nextSibling) {
if (!TYPE_DECLARATIONS.has(node.name)) continue;
const name = typeName(text, node);
if (!name) continue;
if (isPublic(text, node)) return name;
first ??= name;
}
return first;
}
/**
* The package of the project-relative folder `rel`: its path below the Java source or test root
* it is in; null outside one, where a pasted file keeps the package it declares.
*/
export function javaPackageAt(rel: string, roots: readonly RootFolder[]): string | null {
if (!isJvmSourcePackage(rel, roots)) return null;
const root = rootFor(roots, rel)!;
const below = root.path ? rel.slice(root.path.length).replace(/^\/+/, "") : rel;
return below.split("/").filter(Boolean).join(".");
}
/**
* `text` declaring `pkg`: its package statement replaced, or one added in front. Unchanged for the
* default package (`""`), as in IDEA, which leaves the statement of code pasted into a source root.
*/
export function withJavaPackage(text: string, pkg: string): string {
if (!pkg) return text;
const declaration = javaLanguage.parser.parse(text).topNode.getChild("PackageDeclaration");
if (!declaration) return `package ${pkg};\n\n${text}`;
const name = declaration.getChild("ScopedIdentifier") ?? declaration.getChild("Identifier");
if (name && text.slice(name.from, name.to).replace(/\s+/g, "") === pkg) return text;
return `${text.slice(0, declaration.from)}package ${pkg};${text.slice(declaration.to)}`;
}
+1 -1
Переглянути файл
@@ -210,7 +210,7 @@ export function buildModel(
const visible = visibleEntries(listing, opts);
if (visible.length !== 1) break;
const only = visible[0]!;
if (!isDirEntry(only) || only.ignored !== entry.ignored || only.excluded !== entry.excluded) break;
if (only.kind !== "dir" || only.ignored !== entry.ignored || only.excluded !== entry.excluded) break;
if (placeholder && placeholder.parent === only.path) break;
end = only;
chain.push(only.path);
+103
Переглянути файл
@@ -21,6 +21,24 @@ import { MemoryFs, setProjectFsForTests } from "./fs";
import { initProjectTree, loadDir, setClipboard, setSelection, useProjectTree } from "./store";
import { setOsClipboardForTests } from "./clipboard";
const askMock = vi.hoisted(() => vi.fn());
const confirmMock = vi.hoisted(() => vi.fn());
vi.mock("@/workbench/messages", async (original) => ({
...(await original<typeof import("@/workbench/messages")>()),
ask: askMock,
confirm: confirmMock,
}));
const clipboardText = vi.hoisted(() => vi.fn(async () => ""));
vi.mock("@/platform/clipboard", async (original) => ({
...(await original<typeof import("@/platform/clipboard")>()),
readClipboardPlainText: clipboardText,
}));
const roots = vi.hoisted(() => vi.fn((): unknown[] => []));
vi.mock("@/platform/projectRoots", async (original) => ({
...(await original<typeof import("@/platform/projectRoots")>()),
currentRoots: roots,
}));
let fs: MemoryFs;
const notify = vi.fn();
@@ -134,6 +152,8 @@ describe("OS file imports", () => {
});
provideNotificationService({ notify });
notify.mockClear();
askMock.mockReset();
askMock.mockResolvedValue({ button: "copy", checked: false });
});
afterEach(() => {
@@ -175,6 +195,48 @@ describe("OS file imports", () => {
},
);
it.each([
["overwrite", "/p/target/local.txt", 1],
["skip", "/p/target/local.txt", 0],
["copy", "/p/target/local copy.txt", 1],
])("asks before importing over an existing file: %s", async (button, to, imports) => {
await fs.createFileBytes("/p/target/local.txt", new Uint8Array(3));
await loadDir("/p/target");
const imported = vi.spyOn(fs, "importLocal");
const deleted = vi.spyOn(fs, "delete");
askMock.mockResolvedValueOnce({ button, checked: false });
await importExternal(["/p/local.txt"], "/p/target");
expect(askMock).toHaveBeenCalledWith(
expect.objectContaining({ title: "File Already Exists", checkbox: undefined }),
);
expect(imported.mock.calls).toEqual(imports ? [["/p/local.txt", to, expect.anything()]] : []);
expect(deleted).toHaveBeenCalledTimes(button === "overwrite" ? 1 : 0);
expect(fs.nodes.get("/p/target/local.txt")).toEqual({ kind: "file", size: button === "overwrite" ? 6 : 3 });
});
it("applies one answer to the remaining conflicts and never overwrites a folder", async () => {
await fs.createFileBytes("/p/target/local.txt", new Uint8Array(3));
await fs.createDir("/p/target/dir");
await fs.createDir("/p/dir");
await loadDir("/p/target");
const imported = vi.spyOn(fs, "importLocal");
askMock.mockResolvedValueOnce({ button: "overwrite", checked: true });
await importExternal(["/p/local.txt", "/p/dir"], "/p/target");
expect(askMock).toHaveBeenCalledTimes(1);
expect(askMock).toHaveBeenCalledWith(expect.objectContaining({ checkbox: "Do this for the other conflicts" }));
expect(imported.mock.calls.map((c) => c[1])).toEqual(["/p/target/local.txt", "/p/target/dir copy"]);
});
it("stops the import when the conflict question is cancelled", async () => {
await fs.createFileBytes("/p/target/local.txt", new Uint8Array(3));
await loadDir("/p/target");
const imported = vi.spyOn(fs, "importLocal");
askMock.mockResolvedValueOnce({ button: "cancel", checked: false });
await importExternal(["/p/local.txt"], "/p/target");
expect(imported).not.toHaveBeenCalled();
expect(fs.nodes.get("/p/target/local.txt")).toEqual({ kind: "file", size: 3 });
});
it("reports upload failure and continues with the next file", async () => {
const imported = vi.spyOn(fs, "importLocal").mockRejectedValueOnce(new Error("SSH disconnected"));
await importExternal(["/missing.txt", "/p/local.txt"], "/p/target");
@@ -198,6 +260,47 @@ describe("OS file imports", () => {
expect(notify).not.toHaveBeenCalled();
});
it("turns pasted Java code into <Class>.java declaring the folder's package, asking before replacing", async () => {
roots.mockReturnValue([{ path: "target", kind: "source", detectedFrom: "pom.xml" }]);
fs = new MemoryFs({ "/p/target/com/acme": null }, "/p");
setProjectFsForTests(fs, "/p");
initProjectTree("/p", "p");
await loadDir("/p");
setOsClipboardForTests({});
const written: string[] = [];
const create = fs.createFileBytes.bind(fs);
vi.spyOn(fs, "createFileBytes").mockImplementation(async (path, data) => {
written.push(`${path}: ${new TextDecoder().decode(data)}`);
await create(path, data);
});
clipboardText.mockResolvedValue("package old;\r\n\r\npublic class Greeter {}\r\n");
await paste("/p/target/com/acme");
expect(written).toEqual(["/p/target/com/acme/Greeter.java: package com.acme;\n\npublic class Greeter {}\n"]);
expect(useProjectTree.getState().revealRequest?.path).toBe("/p/target/com/acme/Greeter.java");
// The file exists: kept when the user declines, replaced when they agree.
confirmMock.mockResolvedValueOnce(false);
await paste("/p/target/com/acme");
expect(written).toHaveLength(1);
confirmMock.mockResolvedValueOnce(true);
await paste("/p/target/com/acme");
expect(confirmMock).toHaveBeenCalledWith(
expect.objectContaining({ message: "File 'Greeter.java' already exists. Do you want to overwrite it?" }),
);
expect(written).toHaveLength(2);
// Outside a source root the code keeps its own package; text without a type is not pasted.
clipboardText.mockResolvedValue("package demo;\nclass Note {}");
await paste("/p");
expect(written.at(-1)).toBe("/p/Note.java: package demo;\nclass Note {}");
clipboardText.mockResolvedValue("System.out.println(1);");
await paste("/p");
expect(notify).toHaveBeenCalledWith(expect.objectContaining({ title: "No files on the clipboard" }));
expect(written).toHaveLength(3);
clipboardText.mockResolvedValue("");
roots.mockReturnValue([]);
});
it("says the clipboard is empty when it holds neither files nor an image", async () => {
setOsClipboardForTests({});
await paste("/p/target");
+114 -7
Переглянути файл
@@ -2,7 +2,7 @@
* File operations behind the project view's actions: new / rename / delete,
* internal copy-cut-paste, drag & drop moves and OS file imports.
*/
import { writeClipboardText } from "@/platform/clipboard";
import { readClipboardPlainText, writeClipboardText } from "@/platform/clipboard";
import { createElement, Fragment } from "react";
import { askUsagesDetected, fileUsages, showFileUsages, viewUsages } from "@/editor/refactor";
import { executeAction, getAction } from "@/platform/actions";
@@ -14,13 +14,15 @@ import {
revealInFileManager,
} from "@/platform/fileManager";
import { maybeEditorService, notifications } from "@/workbench/contributions";
import { ask, confirmChecked } from "@/workbench/messages";
import { ask, confirm, confirmChecked } from "@/workbench/messages";
import { osClipboard } from "./clipboard";
import { lastFileRefactoring, nextFileOperation, runFileRefactoring, undoFileRefactoring } from "./fileRefactor";
import { openFileRefactorDialog, rememberedOptions } from "./FileRefactorDialogs";
import { beginLocalImport, projectFs } from "./fs";
import { renameCopiedJavaType } from "./javaCopy";
import { IpcError, isCancelled } from "@/platform/ipc";
import { javaPackageAt, pastedJavaClass, withJavaPackage } from "./javaPaste";
import { currentRoots } from "@/platform/projectRoots";
import { IpcError, isCancelled, isTauri } from "@/platform/ipc";
import { MEMBER_PREFIX, type ProjectNode } from "./model";
import {
isInside,
@@ -51,7 +53,7 @@ import { tx, txPart } from "@/platform/i18n";
import { hostOs, isRemoteWindow } from "@/platform/remote";
import { usePlatform } from "@/platform/platformInfo";
import { pathToCopy, type PathKind } from "@/platform/copyPath";
import { projectFolder, useProject } from "@/platform/project";
import { projectFolder, relativePath, useProject } from "@/platform/project";
export type { PathKind } from "@/platform/copyPath";
/** Nodes that may be renamed, moved or deleted (not roots, groups or library sources). */
@@ -586,6 +588,8 @@ export function copySelection(cut: boolean) {
/** Files or an image on the OS clipboard, cached: `canPaste` runs while a menu renders. */
let osHasFiles = false;
let osHasImage = false;
/** The clipboard holds Java code, which Paste turns into a file. */
let osHasJava = false;
/** Keeps Paste enabled for what Explorer copied; called when the window gains focus. */
export async function refreshOsClipboard() {
@@ -604,6 +608,10 @@ async function readOsClipboard(): Promise<string[] | null> {
if (get().clipboard !== clipboard) return null;
osHasFiles = external.length > 0;
osHasImage = image;
// Only the desktop app reads the text without asking; in a browser Paste still tries. Checked on
// every window focus, so a huge clipboard is not parsed for the menu item.
const text = !osHasFiles && !image && isTauri() ? await readClipboardPlainText().catch(() => "") : "";
osHasJava = text.length <= 1_000_000 && !!pastedJavaClass(text);
// Our remote text write removes file URLs, so any files were copied later.
// A failed write leaves ownership uncertain; retain the remote copy then.
if (handedOff && (clipboard?.remote ? external.length > 0 : !sameFiles(external, clipboard?.paths)))
@@ -612,7 +620,7 @@ async function readOsClipboard(): Promise<string[] | null> {
}
export function canPaste(): boolean {
return !!get().clipboard?.paths.length || osHasFiles || osHasImage;
return !!get().clipboard?.paths.length || osHasFiles || osHasImage || osHasJava;
}
/**
@@ -640,6 +648,7 @@ export async function paste(target = targetFolder()) {
return pasteFromOsClipboard(external, target);
if (!clipboard?.paths.length) {
if (await pasteImage(target)) return;
if (await pasteJavaCode(target)) return;
notifications().notify({ level: "info", title: "No files on the clipboard" });
return;
}
@@ -654,6 +663,45 @@ export async function paste(target = targetFolder()) {
});
}
/**
* Java code on the clipboard becomes `<Class>.java` in `target`, declaring the folder's package
* inside a source root, and opens (IDEA's Java file paste). Asks before replacing a file of that
* name. False when the clipboard holds no Java type.
*/
async function pasteJavaCode(target: string): Promise<boolean> {
const text = (await readClipboardPlainText().catch(() => "")).replace(/\r\n?/g, "\n");
const className = pastedJavaClass(text);
if (!className) return false;
const name = `${className}.java`;
const root = get().root ?? target;
const pkg = javaPackageAt(target === root ? "" : relativePath(root, target), currentRoots());
const path = joinPath(target, name);
await loadDir(target);
const exists = (get().listings.get(target) ?? []).some((e) => e.name === name);
if (
exists &&
!(await confirm({
title: tx("Paste"),
message: tx`File '${name}' already exists. Do you want to overwrite it?`,
ok: "Overwrite",
}))
)
return true;
const fs = projectFs(root);
try {
// The replaced file goes to Local History, like any delete.
if (exists) await fs.delete(path);
await fs.createFileBytes(path, new TextEncoder().encode(pkg === null ? text : withJavaPackage(text, pkg)));
} catch (e) {
fail(tx`Cannot paste ${name}`, e);
return true;
}
await loadDir(target, true);
revealPath(path, true);
await maybeEditorService()?.openFile(path, { focus: true });
return true;
}
/**
* Saves the clipboard's image in `target` as `img.png`, or `img_1.png`, `img_2.png`
* … when taken, and selects it. False when the clipboard holds no image.
@@ -723,9 +771,41 @@ function openCopyDialogFor(paths: string[], target: string, dir?: boolean) {
});
}
type ConflictChoice = "overwrite" | "skip" | "copy";
/**
* A file dropped or pasted from outside the project whose name is taken in `target`: replace
* the existing one, skip it, or keep both under a new name (`Foo copy.kt`). A folder can't
* be overwritten. `null` cancels the rest of the import.
*/
async function askNameConflict(
name: string,
target: string,
dir: boolean,
more: boolean,
): Promise<{ choice: ConflictChoice; all: boolean } | null> {
const folder = nameOf(target) || target;
const r = await ask({
title: dir ? "Folder Already Exists" : "File Already Exists",
body: tx`${name} already exists in ${folder}.`,
icon: "warning",
buttons: [
...(dir ? [] : [{ id: "overwrite", label: "Overwrite" }]),
{ id: "skip", label: "Skip" },
{ id: "copy", label: "Create Copy", primary: true },
],
checkbox: more ? "Do this for the other conflicts" : undefined,
});
return r.button === "overwrite" || r.button === "skip" || r.button === "copy"
? { choice: r.button, all: r.checked }
: null;
}
/**
* Moves or copies `paths` into `target`. Copies take `name` (a single item) or
* get a non-conflicting name (`Foo copy.kt`); moves refuse to overwrite.
* get a non-conflicting name (`Foo copy.kt`); moves refuse to overwrite. Files
* from outside the project (`local`) whose name is taken ask first: overwrite,
* skip or keep both.
* Returns whether anything changed (for copies: the first copy's path).
*/
export async function transfer(
@@ -750,6 +830,9 @@ export async function transfer(
let first: string | null = null;
const newName = name;
const upload = source === "local" && isRemoteWindow() ? beginLocalImport() : undefined;
const ask = source === "local" && !(paths.length === 1 && newName);
let conflictsLeft = ask ? paths.filter((p) => isTaken(nameOf(p))).length : 0;
let forAll: ConflictChoice | null = null;
try {
for (const src of paths) {
if (upload?.cancelled) break;
@@ -765,9 +848,33 @@ export async function transfer(
}
const srcIsDir =
get().listings.has(src) || currentModel().byKey.get(currentModel().keyOfPath.get(src) ?? src)?.dir === true;
const finalName = paths.length === 1 && newName ? newName : uniqueName(name, isTaken, srcIsDir);
let finalName = paths.length === 1 && newName ? newName : uniqueName(name, isTaken, srcIsDir);
let replace = false;
if (ask && isTaken(name)) {
conflictsLeft--;
// A dropped folder isn't in the listings: what decides is the entry already there.
const existing = (get().listings.get(target) ?? []).find((e) =>
caseInsensitive ? e.name.toLowerCase() === name.toLowerCase() : e.name === name,
);
const folder = existing?.kind !== "file";
let choice: ConflictChoice | null = forAll;
if (!choice) {
// oxlint-disable-next-line no-await-in-loop -- one question per conflicting file, in order
const answer = await askNameConflict(name, target, folder, conflictsLeft > 0);
if (!answer) break;
choice = answer.choice;
if (answer.all) forAll = choice;
}
if (choice === "skip") continue;
// A folder is never overwritten: "for all" keeps both instead.
replace = choice === "overwrite" && !folder;
if (replace) finalName = name;
}
const to = joinPath(target, finalName);
try {
// The replaced file goes to Local History, like any delete.
// oxlint-disable-next-line no-await-in-loop -- the file is replaced before its copy is written
if (replace) await fs.delete(to);
if (source === "local") {
// oxlint-disable-next-line no-await-in-loop -- cancellation is checked per source; each import feeds the taken-name set
const skipped = await fs.importLocal(src, to, upload);
+3 -10
Переглянути файл
@@ -1,11 +1,9 @@
/** Which "New › Package" flavour a folder offers, from the project's roots. */
import { rootFor, type RootFolder } from "@/platform/languageSettings";
import { isJvmSourcePackage } from "@/ui/folderPresentation";
import type { PackageKind } from "./paths";
// `Gradle` marks the source sets a Gradle sync reported (ide-host `with_gradle_roots`).
const JVM_BUILD = /^Gradle$|(^|\/)(pom\.xml|build\.gradle(\.kts)?|\.classpath)$/;
const PY_BUILD = /(^|\/)(pyproject\.toml|setup\.py|setup\.cfg|Pipfile|requirements\.txt)$/;
const JVM_DIR = /(^|\/)(java|kotlin|scala|groovy)$/;
const moduleDir = (buildFile: string) =>
buildFile.includes("/") ? buildFile.slice(0, buildFile.lastIndexOf("/")) : "";
@@ -20,13 +18,8 @@ export function packageKindAt(
roots: readonly RootFolder[],
detected: readonly RootFolder[] = [],
): PackageKind | null {
const root = rootFor(roots, rel);
if (root?.kind === "excluded") return null;
if (
(root?.kind === "source" || root?.kind === "test") &&
(JVM_BUILD.test(root.detectedFrom ?? "") || JVM_DIR.test(root.path))
)
return "jvm";
if (rootFor(roots, rel)?.kind === "excluded") return null;
if (isJvmSourcePackage(rel, roots)) return "jvm";
const python = [...roots, ...detected].some(
(r) => r.detectedFrom && PY_BUILD.test(r.detectedFrom) && within(rel, moduleDir(r.detectedFrom)),
);
+33 -2
Переглянути файл
@@ -1,7 +1,15 @@
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { FileEntry } from "@/bindings";
import { setProjectFsForTests, type ProjectFs } from "./fs";
import { applyFsChange, initProjectTree, loadDir, selectModel, setSelection, useProjectTree } from "./store";
import {
applyFsChange,
initProjectTree,
loadDir,
loadVisibleDirs,
selectModel,
setSelection,
useProjectTree,
} from "./store";
const ROOT = "/p";
const FILES = 3;
@@ -101,6 +109,29 @@ afterEach(() => {
});
describe("applyFsChange reload of many folders", () => {
it("keeps an unfinished reload separate from newly visible listings", async () => {
const fs = new TreeFs(10);
loadedTree(fs);
const listings = new Map(listingsOf());
listings.delete(dirPath(6));
listings.delete(dirPath(7));
useProjectTree.setState({ listings });
let release!: () => void;
fs.gates.set(dirPath(9), new Promise<void>((resolve) => (release = resolve)));
const reload = applyFsChange(modify(fs, [1, 9]));
try {
loadVisibleDirs([dirPath(6), dirPath(7)]);
await vi.waitFor(() => expect(listingsOf().get(dirPath(7))).toEqual(fs.list(dirPath(7))));
expect(listingsOf().get(dirPath(1))).toBe(listings.get(dirPath(1)));
} finally {
release();
await reload;
}
expect(listingsOf().get(dirPath(1))).toEqual(fs.list(dirPath(1)));
expect(listingsOf().get(dirPath(9))).toEqual(fs.list(dirPath(9)));
});
it("builds the model once and caps the concurrent reads, however many folders changed", async () => {
const fs = new TreeFs(300);
loadedTree(fs);
+193 -1
Переглянути файл
@@ -6,14 +6,18 @@ import {
reloadArchiveDirs,
reloadLoadedDirs,
currentModel,
collapseAll,
expandAll,
expandSelected,
explainHiddenPath,
hidingOption,
initProjectTree,
loadDir,
loadVisibleDirs,
revealPath,
setExpanded,
setSelection,
setViewMode,
setViewOption,
toggleExpanded,
useProjectTree,
@@ -104,6 +108,88 @@ describe("lazy loading", () => {
});
});
describe("visible folder batches", () => {
const folders = ["/p/docs", "/p/src/main/kotlin/com/acme"];
it("publishes multiple listings in one frame", async () => {
const frame = vi.spyOn(window, "requestAnimationFrame").mockReturnValue(1);
try {
loadVisibleDirs(folders);
await vi.waitFor(() => expect(frame).toHaveBeenCalledTimes(1));
expect([...useProjectTree.getState().listings]).toEqual([]);
frame.mock.calls[0]![0](0);
expect([...useProjectTree.getState().listings.keys()]).toEqual(folders);
} finally {
frame.mockRestore();
}
});
it("publishes a shared visible read before a direct load resolves", async () => {
const frame = vi.spyOn(window, "requestAnimationFrame").mockReturnValue(1);
const read = vi.spyOn(fs, "readDir");
try {
loadVisibleDirs(folders);
await loadDir("/p/docs");
expect(read.mock.calls).toEqual(folders.map((path) => [path]));
expect(
useProjectTree
.getState()
.listings.get("/p/docs")
?.map((entry) => entry.name),
).toEqual(["guide.md"]);
} finally {
frame.mockRestore();
}
});
it("includes a completed visible read when planning a watcher refresh", async () => {
const frame = vi.spyOn(window, "requestAnimationFrame").mockReturnValue(1);
try {
loadVisibleDirs(folders);
await vi.waitFor(() => expect(frame).toHaveBeenCalledTimes(1));
await fs.createFile("/p/docs/new.md");
await applyFsChange({ created: ["/p/docs/new.md"], modified: [], removed: [] });
expect(
useProjectTree
.getState()
.listings.get("/p/docs")
?.map((entry) => entry.name),
).toEqual(["guide.md", "new.md"]);
} finally {
frame.mockRestore();
}
});
it("flushes only fresh reads after reopening a project", async () => {
const frame = vi.spyOn(window, "requestAnimationFrame").mockReturnValue(1);
const read = vi.spyOn(fs, "readDir");
try {
loadVisibleDirs(folders);
await vi.waitFor(() => expect(frame).toHaveBeenCalledTimes(1));
initProjectTree(null);
await fs.createFile("/p/docs/new.md");
initProjectTree(ROOT, "proj");
loadVisibleDirs(folders);
await loadDir("/p/docs");
expect(read.mock.calls).toEqual([...folders, ...folders].map((path) => [path]));
expect(
useProjectTree
.getState()
.listings.get("/p/docs")
?.map((entry) => entry.name),
).toEqual(["guide.md", "new.md"]);
} finally {
frame.mockRestore();
}
});
});
describe("refresh of excluded folders", () => {
it("reloads only the folders the tree has loaded", async () => {
await loadDir(ROOT);
@@ -240,10 +326,116 @@ describe("reveal and expand", () => {
});
it("expands everything below a folder", async () => {
await expandAll();
await loadDir(ROOT);
setSelection(new Set(["/p/src"]), "/p/src");
await expandSelected();
const s = useProjectTree.getState();
expect(s.expanded.has("/p/src/main/kotlin/com/acme")).toBe(true);
expect(visibleInfo(currentModel(), s.expanded).visible.has("/p/src/main/kotlin/com/acme/App.kt")).toBe(true);
expect(s.listings.has("/p/docs")).toBe(false);
});
});
describe("Expand Selected", () => {
it("drops buffered selected listings on cancellation while publishing restored folders", async () => {
fs = new MemoryFs({ "/a/one.ts": "", "/b/two.ts": "", "/selected/file.ts": "", "/blocked/file.ts": "" }, ROOT);
setProjectFsForTests(fs, ROOT);
initProjectTree(ROOT, "workspace", ["/a", "/b", "/blocked", "/selected"]);
const frame = vi.spyOn(window, "requestAnimationFrame").mockReturnValue(1);
const read = fs.readDir.bind(fs);
let release!: () => void;
const gate = new Promise<void>((resolve) => (release = resolve));
vi.spyOn(fs, "readDir").mockImplementation(async (path) => {
if (path === "/blocked") await gate;
return read(path);
});
try {
setSelection(new Set(["/selected", "/blocked"]), "/blocked");
const expansion = expandSelected();
loadVisibleDirs(["/a", "/b"]);
await vi.waitFor(() => expect(frame).toHaveBeenCalledTimes(1));
collapseAll();
await expansion;
release();
frame.mock.calls[0]![0](0);
expect([...useProjectTree.getState().listings.keys()]).toEqual(["/a", "/b"]);
expect(useProjectTree.getState().expanded).toEqual(new Set());
} finally {
release();
frame.mockRestore();
}
});
it("opens selected workspace members past 400 directories while skipping excluded folders and links", async () => {
const files = Object.fromEntries(Array.from({ length: 405 }, (_, i) => [`/a/dir${i}/nested/file.ts`, ""]));
fs = new MemoryFs(
{ ...files, "/a/excluded/file.ts": "", "/b/src/app.ts": "", "/c/skip.ts": "", "/outside/file.ts": "" },
ROOT,
{ "/a/link": "/outside" },
);
fs.ignored.add("/a/excluded");
setProjectFsForTests(fs, ROOT);
initProjectTree(ROOT, "workspace", ["/a", "/b", "/c"]);
const read = vi.spyOn(fs, "readDir");
setSelection(new Set(["/a", "/b"]), "/b");
await expandSelected();
const state = useProjectTree.getState();
expect(state.expanded.has("/a/dir404/nested")).toBe(true);
expect(visibleInfo(currentModel(), state.expanded).visible.has("/b/src/app.ts")).toBe(true);
const paths = read.mock.calls.map(([path]) => path);
expect(paths).toHaveLength(813);
expect(new Set(paths).size).toBe(paths.length);
expect(paths).not.toContain("/c");
expect(paths).not.toContain("/a/excluded");
expect(paths).not.toContain("/a/link");
});
it.each([
{ action: "Collapse All", interrupt: collapseAll, root: ROOT, expanded: [] },
{
action: "switching panes and back",
interrupt: () => {
setViewMode("projectFiles");
setViewMode("project");
},
root: ROOT,
expanded: [ROOT],
},
{
action: "opening another project",
interrupt: () => initProjectTree("/other", "Other"),
root: "/other",
expanded: ["/other"],
},
])("cancels queued expansion work after $action", async ({ interrupt, root, expanded }) => {
fs = new MemoryFs(Object.fromEntries(Array.from({ length: 20 }, (_, i) => [`/p/dir${i}/child/file.ts`, ""])), ROOT);
setProjectFsForTests(fs, ROOT);
await loadDir(ROOT);
const read = fs.readDir.bind(fs);
let release!: () => void;
const gate = new Promise<void>((resolve) => (release = resolve));
const spy = vi.spyOn(fs, "readDir").mockImplementation(async (path) => {
await gate;
return read(path);
});
setSelection(new Set([ROOT]), ROOT);
const expansion = expandSelected();
await vi.waitFor(() => expect(spy).toHaveBeenCalledTimes(8));
const started = spy.mock.calls.slice();
interrupt();
await expansion;
release();
await new Promise((resolve) => requestAnimationFrame(resolve));
expect(spy.mock.calls).toEqual(started);
const state = useProjectTree.getState();
expect(state.expanded).toEqual(new Set(expanded));
expect([...state.listings.keys()]).toEqual(root === ROOT ? [ROOT] : []);
});
});
+194 -35
Переглянути файл
@@ -35,6 +35,7 @@ import {
mergeListing,
planRefresh,
visibleEntries,
visibleInfo,
unityPathVisible,
type Placeholder,
type ProjectNode,
@@ -327,10 +328,21 @@ export const currentModel = () => selectModel(get());
// Lifecycle
let generation = 0;
const inflight = new Map<string, Promise<void>>();
interface Expansion {
paths: Set<string>;
opened: Map<string, string | null>;
cancel: () => void;
}
let activeExpansion: Expansion | undefined;
const inflight = new Map<string, { promise: Promise<void>; batch?: ListingBatch; expansion?: Expansion }>();
type ListingBatch = "reload" | "visible";
/** Listings read by a batch and not applied yet; `reload` marks folders that were loaded when read. */
const pending = new Map<string, { entries: readonly FileEntry[]; reload: boolean }>();
const pending = new Map<
string,
{ entries: readonly FileEntry[]; reload: boolean; batch: ListingBatch; expansion?: Expansion }
>();
let persistTimer: ReturnType<typeof setTimeout> | undefined;
let visibleFlush: number | undefined;
/** Resets the view for a newly opened project, restoring its expansion state. */
export function initProjectTree(
@@ -339,9 +351,12 @@ export function initProjectTree(
members: readonly string[] | null = null,
unity: UnityProjectInfo | null = null,
) {
cancelExpansion();
generation++;
inflight.clear();
pending.clear();
if (visibleFlush !== undefined) cancelAnimationFrame(visibleFlush);
visibleFlush = undefined;
outlineInflight.clear();
clearTimeout(persistTimer);
modeExpanded.clear();
@@ -418,6 +433,7 @@ export function setViewMode(mode: ViewMode) {
const s = get();
if (mode === "unity" && !s.unity) return;
if (s.mode === mode) return;
cancelExpansion();
modeExpanded.set(s.mode, s.expanded);
autoExpanded.clear();
writeJson(MODE_KEY, mode);
@@ -474,6 +490,7 @@ export function setChangedFiles(paths: readonly string[]) {
}
export function setExpanded(expanded: ReadonlySet<string>) {
cancelExpansion();
set({ expanded });
persistExpanded();
}
@@ -550,59 +567,106 @@ async function withReadSlot<T>(read: () => Promise<T>): Promise<T> {
}
}
/** Applies the batched listings in one update, so the tree model is built once for all of them. */
function flushPending() {
const { listings } = get();
function flushPending(batch: ListingBatch) {
const { listings, expanded } = get();
let next: Map<string, readonly FileEntry[]> | undefined;
for (const [path, { entries, reload }] of pending) {
for (const [path, result] of pending) {
if (result.batch !== batch) continue;
pending.delete(path);
if (result.expansion && result.expansion !== activeExpansion) continue;
// A folder dropped while the batch was reading stays dropped.
if (reload && !listings.has(path)) continue;
const merged = mergeListing(listings.get(path), entries);
if (result.reload && !listings.has(path)) continue;
const merged = mergeListing(listings.get(path), result.entries);
if (merged !== listings.get(path)) (next ??= new Map(listings)).set(path, merged);
}
pending.clear();
if (next) set({ listings: next });
let opened: Set<string> | undefined;
if (batch === "visible" && activeExpansion) {
for (const [key, path] of activeExpansion.opened) {
if (!expanded.has(key) && (path === null || (next ?? listings).has(path)))
(opened ??= new Set(expanded)).add(key);
}
activeExpansion.opened.clear();
}
if (next || opened) set({ listings: next ?? listings, expanded: opened ?? expanded });
if (opened) persistExpanded();
}
function scheduleVisibleListings() {
visibleFlush ??= requestAnimationFrame(flushVisibleListings);
}
function flushVisibleListings() {
if (visibleFlush === undefined) return;
cancelAnimationFrame(visibleFlush);
visibleFlush = undefined;
flushPending("visible");
}
/** Loads (or reloads) one folder. Concurrent calls for the same folder share a request. */
export function loadDir(path: string, force = false): Promise<void> {
return load(path, force, false);
return load(path, force);
}
/**
* With `batched`, the listing waits in `pending` for `flushPending` and the read takes one of `READ_SLOTS`;
* a later read of the same folder replaces it, so a flush never applies a listing older than one already read.
*/
function load(path: string, force: boolean, batched: boolean): Promise<void> {
/** Loads the expanded folders currently waiting for their children. */
export function loadVisibleDirs(paths: readonly string[]) {
const batch = paths.length > 1 ? "visible" : undefined;
for (const path of paths) if (!activeExpansion?.paths.has(path)) void load(path, false, batch);
}
function load(path: string, force: boolean, batch?: ListingBatch, expansion?: Expansion): Promise<void> {
const { root, listings } = get();
if (!root || isGroupKey(path)) return Promise.resolve();
if (!force && listings.has(path)) return Promise.resolve();
const running = inflight.get(path);
if (running) return running;
const gen = generation;
const running = inflight.get(path);
if (running) {
if (running.expansion) {
running.expansion = expansion;
running.batch = batch;
}
if (batch) return running.promise;
return running.promise.then(() => {
if (gen === generation && pending.get(path)?.batch === "visible") flushVisibleListings();
});
}
const buffered = pending.get(path);
if (!force && buffered && (!buffered.expansion || buffered.expansion === activeExpansion)) {
if (batch) return Promise.resolve();
if (buffered.batch === "visible") {
buffered.expansion = undefined;
flushVisibleListings();
return Promise.resolve();
}
}
const reload = listings.has(path);
const p = (async () => {
const request = { promise: Promise.resolve(), batch, expansion };
const isCurrent = () => gen === generation && (!request.expansion || request.expansion === activeExpansion);
request.promise = (async () => {
try {
const read = () => projectFs(root).readDir(path);
const entries = await (batched ? withReadSlot(read) : read());
if (gen !== generation) return;
if (batched) pending.set(path, { entries, reload });
else {
const read = () => (isCurrent() ? projectFs(root).readDir(path) : Promise.resolve(null));
const entries = await (batch === "reload" || expansion ? withReadSlot(read) : read());
if (!entries || !isCurrent()) return;
if (request.batch) {
pending.set(path, { entries, reload, batch: request.batch, expansion: request.expansion });
// Restoring many expanded folders yields several replies in one frame
if (request.batch === "visible") scheduleVisibleListings();
} else {
pending.delete(path);
putListing(path, entries);
}
// Compact Middle Packages needs to look one level down a single-folder chain.
const s = get();
if (treeOptions(s).compact) {
if (!request.expansion && treeOptions(s).compact) {
const visible = visibleEntries(entries, treeOptions(s));
const only = visible.length === 1 ? visible[0]! : null;
if (only && isDirEntry(only) && !only.ignored && !s.listings.has(only.path)) {
const next = load(only.path, false, batched);
if (batched) await next;
if (only && isRecursiveFolder(only) && !s.listings.has(only.path) && !activeExpansion?.paths.has(only.path)) {
const next = load(only.path, false, request.batch);
if (request.batch === "reload") await next;
}
}
} catch (e) {
if (gen !== generation) return;
if (!isCurrent()) return;
pending.delete(path);
const s = get();
if (e instanceof IpcError && (e.kind === "notFound" || e.kind === "invalidInput")) {
const listings = new Map(s.listings);
@@ -618,14 +682,19 @@ function load(path: string, force: boolean, batched: boolean): Promise<void> {
if (gen === generation) inflight.delete(path);
}
})();
inflight.set(path, p);
return p;
inflight.set(path, request);
return request.promise;
}
function isRecursiveFolder(entry: FileEntry): boolean {
return entry.kind === "dir" && !entry.ignored && !entry.excluded;
}
/** Re-reads `paths` as one batch: bounded concurrent reads, one update of the listings. */
async function reloadDirs(paths: readonly string[]) {
await Promise.all(paths.map((p) => load(p, true, true)));
flushPending();
const gen = generation;
await Promise.all(paths.map((p) => load(p, true, "reload")));
if (gen === generation) flushPending("reload");
}
/** Applies a backend `fsChanged` event: reloads affected loaded folders only. */
@@ -635,6 +704,7 @@ export async function applyFsChange(event: {
removed: string[];
ignoreRules?: string[];
}) {
flushVisibleListings();
const s = get();
if (!s.root) return;
const plan = planRefresh(event, new Set(s.listings.keys()));
@@ -680,6 +750,7 @@ export async function applyFsChange(event: {
/** Re-reads the folders among `dirs` the tree has loaded; the rest stay unread. */
export async function reloadLoadedDirs(dirs: readonly string[]) {
flushVisibleListings();
const { listings } = get();
await reloadDirs(dirs.filter((p) => listings.has(p)));
}
@@ -689,6 +760,7 @@ export async function reloadLoadedDirs(dirs: readonly string[]) {
* a library jar in place (a SNAPSHOT installed again), which no file watcher reports.
*/
export async function reloadArchiveDirs() {
flushVisibleListings();
const { listings } = get();
const inArchive = (p: string) => p.endsWith("!") || p.includes("!/") || p.includes("!\\");
await reloadDirs([...listings.keys()].filter(inArchive));
@@ -696,6 +768,7 @@ export async function reloadArchiveDirs() {
/** Re-reads every loaded folder (View › Reload from Disk). */
export async function reloadAll() {
flushVisibleListings();
const { listings } = get();
await reloadDirs([...listings.keys()]);
}
@@ -945,9 +1018,95 @@ export async function expandAll(from?: string, limit = 400) {
setExpanded(toExpand);
}
export function hasVisibleSelection(state = get()): boolean {
if (!state.selected.size) return false;
const { visible } = visibleInfo(selectModel(state), state.expanded);
for (const key of state.selected) if (visible.has(key)) return true;
return false;
}
/** Opens the selected subtrees as their directory listings become available. */
export function expandSelected(): Promise<void> {
const { expanded, mode, selected } = get();
const model = currentModel();
const { visible } = visibleInfo(model, expanded);
const roots = [...selected].filter((key) => visible.has(key) && isExpandableFolder(model.byKey.get(key)));
if (!roots.length) return Promise.resolve();
cancelExpansion();
if (isFilteredMode(mode)) {
const keys = new Set(roots);
for (const key of keys) for (const child of model.children.get(key) ?? []) if (child.dir) keys.add(child.key);
setExpanded(new Set([...expanded, ...keys]));
return Promise.resolve();
}
return new Promise((resolve) => {
const expansion: Expansion = { paths: new Set(), opened: new Map(), cancel: resolve };
activeExpansion = expansion;
const queue: string[] = [];
const visited = new Set<string>();
let cursor = 0;
let running = 0;
const enqueue = (key: string) => {
if (visited.has(key)) return;
visited.add(key);
queue.push(key);
if (!isGroupKey(key)) expansion.paths.add(pathOfKey(key));
};
const visit = async (key: string) => {
if (isGroupKey(key)) {
for (const child of model.children.get(key) ?? []) if (isExpandableFolder(child)) enqueue(child.key);
expansion.opened.set(key, null);
} else {
const path = pathOfKey(key);
await load(path, false, "visible", expansion);
if (activeExpansion !== expansion) return;
const state = get();
const entries = pending.get(path)?.entries ?? state.listings.get(path);
if (!entries) return;
for (const child of visibleEntries(entries, treeOptions(state)))
if (isRecursiveFolder(child)) enqueue(keyLike(key, child.path));
expansion.opened.set(key, path);
}
scheduleVisibleListings();
};
const pump = () => {
if (activeExpansion !== expansion) return;
while (running < READ_SLOTS && cursor < queue.length) {
running++;
void visit(queue[cursor++]!).finally(() => {
running--;
pump();
});
}
if (running) return;
flushVisibleListings();
if (activeExpansion === expansion) activeExpansion = undefined;
resolve();
};
for (const key of roots) enqueue(key);
pump();
});
}
function isExpandableFolder(node: ProjectNode | undefined): boolean {
return !!node?.dir && !node.placeholder && !node.ignored && !node.excluded && !node.symlink;
}
function cancelExpansion() {
const expansion = activeExpansion;
if (!expansion) return;
activeExpansion = undefined;
expansion.cancel();
}
export function collapseAll() {
const { root, mode } = get();
if (root) setExpanded(new Set(mode === "project" || mode === "projectFiles" ? [root] : []));
if (get().root) setExpanded(new Set());
}
// ---------------------------------------------------------------------------
+18 -1
Переглянути файл
@@ -296,9 +296,26 @@ describe("project view modes", () => {
});
it("expands library folders in their own namespace", async () => {
await store.expandAll(pyKey("/p/.venv/lib/site-packages"));
const key = pyKey("/p/.venv/lib/site-packages");
store.setExpanded(new Set(["\u0000group:externalLibraries", "\u0000group:externalLibraries/< Python 3.12 >"]));
store.setSelection(new Set([key]), key);
await store.expandSelected();
const expanded = useProjectTree.getState().expanded;
expect(expanded.has(pyKey("/p/.venv/lib/site-packages/req"))).toBe(true);
expect(expanded.has("/p/.venv/lib/site-packages/req")).toBe(false);
});
it("opens only selected file paths in a filtered pane, including overlapping folders", async () => {
setOpenFiles(["/p/src/nested/deep/app.ts", "/p/docs/notes/guide.md"]);
setViewMode("openFiles");
store.setExpanded(new Set(["/p", "/p/src"]));
store.setSelection(new Set(["/p/src", "/p/src/nested"]), "/p/src/nested");
await store.expandSelected();
expect(useProjectTree.getState().expanded).toEqual(
new Set(["/p", "/p/src", "/p/src/nested", "/p/src/nested/deep"]),
);
expect([...useProjectTree.getState().listings]).toEqual([]);
});
});
+5 -3
Переглянути файл
@@ -56,7 +56,8 @@ import { isJvmRun } from "./threadDump/actions";
import { closeRunTab, runTabMenu } from "./runTabs";
import { showApplicationUpdate, useApplicationUpdates } from "./applicationUpdate";
import { isUpdatable } from "./updatePolicies";
import { hotReload, hotRestart, supportsHotReload } from "./flutterHotReload";
import { useFlutterRunApps } from "@/workbench/flutterRunApps";
import { canHotReload, hotReload, hotRestart, supportsHotReload } from "./flutterHotReload";
import { configIcon } from "./configs";
import { agentName } from "./agentConfig";
import { archivedAgentSessions, closeAgentArchive } from "./agentRuns";
@@ -114,6 +115,7 @@ export function SessionPanel({
const hasTests = !!rt?.tests;
const canUpdateApplication = isUpdatable(session.config);
const hasFlutterActions = supportsHotReload(session.config);
const reloadable = canHotReload(session, useFlutterRunApps());
const canDumpThreads = isJvmRun(session.config);
// Eight standard buttons with group spacing and insets, then 24 px plus gap per extra button.
const fullToolbarWidth =
@@ -301,14 +303,14 @@ export function SessionPanel({
icon="hot-reload"
title="Hot Reload"
shortcut={shortcutLabel("run.flutterHotReload")}
disabled={!acceptsInput(session)}
disabled={!reloadable}
onClick={() => hotReload(session.id)}
/>
<IconButton
icon="refresh"
title="Hot Restart"
shortcut={shortcutLabel("run.flutterHotRestart")}
disabled={!acceptsInput(session)}
disabled={!reloadable}
onClick={() => hotRestart(session.id)}
/>
</>
+90 -10
Переглянути файл
@@ -28,9 +28,11 @@ import {
provideToolWindowService,
type ToolWindowService,
} from "@/workbench/contributions";
import { hotReloadSession, supportsHotReload } from "./flutterHotReload";
import { useFlutterRunApps } from "@/workbench/flutterRunApps";
import { hotReloadSession, supportsHotReload, syncFlutterRunApps } from "./flutterHotReload";
import { machineLine } from "./flutterMachine";
import { SessionPanel } from "./RunView";
import { resetRuns, startRun, useRun } from "./store";
import { resetRuns, runtime, startRun, useRun } from "./store";
const flutter = (args: string[] = [], extra: Partial<RunConfig> = {}): RunConfig => ({
id: "flutter:run",
@@ -47,12 +49,38 @@ const flutter = (args: string[] = [], extra: Partial<RunConfig> = {}): RunConfig
});
const current = (id: string) => useRun.getState().sessions.find((s) => s.id === id)!;
const event = (name: string, params: object) => JSON.stringify([{ event: name, params }]);
const WS = "ws://127.0.0.1:50300/abc=/ws";
/** Starts `flutter run --machine` and has it print `lines`, up to `app.started`. */
async function startedApp(...lines: string[]) {
const session = (await startRun(flutter(["--machine"])))!;
const channel = ipc.runStart.mock.calls.at(-1)![1] as { onmessage: (c: unknown) => void };
const out = [
event("daemon.connected", { version: "0.6.1", pid: 1 }),
event("app.start", { appId: "A1", deviceId: "sim-1", supportsRestart: true, mode: "debug" }),
"Launching lib/main.dart on iPhone in debug mode...",
event("app.debugPort", { appId: "A1", port: 50300, wsUri: WS }),
event("app.started", { appId: "A1" }),
...lines,
];
channel.onmessage({ kind: "stdout", text: out.map((l) => `${l}\n`).join("") });
await vi.waitFor(() => expect(useFlutterRunApps.getState()[session.id]?.started).toBe(true));
return session;
}
const consoleText = (id: string) =>
runtime(id)!
.console.textChunks()
.map((c) => c.text)
.join("");
const button = (name: string) => screen.queryByRole("button", { name: new RegExp(`^${name}`) });
beforeEach(() => {
resetRuns();
ipc.runStart.mockClear();
ipc.runStdin.mockClear();
useFlutterRunApps.setState({}, true);
provideToolWindowService({ show: vi.fn(), isVisible: () => true } as unknown as ToolWindowService);
provideNotificationService({ notify: () => undefined });
});
@@ -61,37 +89,89 @@ describe("Flutter hot reload in the Run tool window", () => {
it("applies only to flutter run in a mode with hot reload", () => {
expect(supportsHotReload(flutter())).toBe(true);
expect(supportsHotReload(flutter(["-d", "macos", "--flavor", "dev"]))).toBe(true);
for (const flag of ["--release", "--profile", "--jit-release", "--no-hot", "--trace-startup", "--machine"])
expect(supportsHotReload(flutter(["--machine"]))).toBe(true);
for (const flag of ["--release", "--profile", "--jit-release", "--no-hot", "--trace-startup"])
expect(supportsHotReload(flutter([flag]))).toBe(false);
expect(supportsHotReload(flutter([], { args: ["test"] }))).toBe(false);
expect(supportsHotReload(flutter([], { kind: "shell" }))).toBe(false);
});
it("puts both buttons after Stop and sends their keys to the process", async () => {
const session = (await startRun(flutter()))!;
it("follows the app from the --machine events and shows its output as plain lines", async () => {
const session = await startedApp(
event("app.log", { appId: "A1", log: "flutter: hello" }),
event("app.progress", { appId: "A1", id: "1", progressId: "hot.reload", message: "Performing hot reload..." }),
event("app.progress", { appId: "A1", id: "1", progressId: "hot.reload", finished: true }),
"Reloaded 1 of 700 libraries in 250ms.",
JSON.stringify([{ id: 1, result: { code: 0, message: "Reloaded 1 of 700 libraries" } }]),
event("daemon.logMessage", { level: "error", message: "Lost connection to device." }),
JSON.stringify([{ id: 2, result: { code: 1, message: "Reload rejected" } }]),
);
expect(useFlutterRunApps.getState()[session.id]).toMatchObject({
appId: "A1",
device: "sim-1",
vmServiceUri: WS,
supportsRestart: true,
live: true,
});
await vi.waitFor(() =>
expect(consoleText(session.id)).toBe(
[
"Launching lib/main.dart on iPhone in debug mode...",
"flutter: hello",
"Performing hot reload...",
"Reloaded 1 of 700 libraries in 250ms.",
"Lost connection to device.",
"Reload rejected",
"",
].join("\n"),
),
);
expect(machineLine(session.id, "[{not json")).toBe("[{not json\n");
});
it("puts both buttons after Stop and sends app.restart requests", async () => {
const session = await startedApp();
render(<SessionPanel session={current(session.id)} />);
const names = screen.getAllByRole("button").map((b) => b.getAttribute("aria-label") ?? "");
const stop = names.findIndex((n) => n.startsWith("Stop"));
expect(names[stop + 1]).toMatch(/^Hot Reload/);
expect(names[stop + 2]).toMatch(/^Hot Restart/);
expect(hotReloadSession()?.id).toBe(session.id);
fireEvent.click(button("Hot Reload")!);
fireEvent.click(button("Hot Restart")!);
expect(ipc.runStdin.mock.calls).toEqual([
[9, "r"],
[9, "R"],
const sent = ipc.runStdin.mock.calls.map(([id, data]) => {
expect(id).toBe(9);
expect(data).toMatch(/\n$/);
return JSON.parse(data as string)[0].params;
});
expect(sent).toEqual([
{ appId: "A1", fullRestart: false, pause: false, reason: "manual" },
{ appId: "A1", fullRestart: true, pause: false, reason: "manual" },
]);
});
it("disables the buttons once the process ended", async () => {
const session = (await startRun(flutter()))!;
it("disables the buttons until the app started", async () => {
const session = (await startRun(flutter(["--machine"])))!;
render(<SessionPanel session={current(session.id)} />);
expect(button("Hot Reload")).toHaveProperty("disabled", true);
expect(hotReloadSession()).toBeUndefined();
});
it("disables the buttons once the process ended, and ends the app", async () => {
const session = await startedApp();
useRun.setState((s) => ({
sessions: s.sessions.map((x) => (x.id === session.id ? { ...x, status: "finished" as const } : x)),
}));
syncFlutterRunApps(useRun.getState().sessions);
render(<SessionPanel session={current(session.id)} />);
expect(button("Hot Reload")).toHaveProperty("disabled", true);
expect(button("Hot Restart")).toHaveProperty("disabled", true);
expect(hotReloadSession()).toBeUndefined();
// DevTools pages stay on an ended app's address until another starts.
expect(useFlutterRunApps.getState()[session.id]).toMatchObject({ live: false, vmServiceUri: WS });
syncFlutterRunApps([]);
expect(useFlutterRunApps.getState()[session.id]).toBeUndefined();
});
it("shows no buttons for other configurations", async () => {
+41 -9
Переглянути файл
@@ -1,22 +1,54 @@
/** Hot reload from the Run tool window: `flutter run` takes `r` and `R` as commands on stdin. */
/** Hot reload from the Run tool window: `app.restart` requests to `flutter run --machine` (see `flutterMachine.ts`). */
import type { RunConfig } from "@/platform/ipc";
import { acceptsInput, useRun, writeTerminal, type RunSession } from "./store";
import { useFlutterRunApps } from "@/workbench/flutterRunApps";
import { acceptsInput, isLive, useRun, writeTerminal, type RunSession } from "./store";
/** Options that turn off `flutter run`'s hot mode, or (`--machine`) replace its key commands with JSON. */
const NO_HOT_KEYS = new Set(["--release", "--profile", "--jit-release", "--no-hot", "--trace-startup", "--machine"]);
/** Options that turn off `flutter run`'s hot mode. */
const NO_HOT = new Set(["--release", "--profile", "--jit-release", "--no-hot", "--trace-startup"]);
export function supportsHotReload(config: RunConfig): boolean {
return config.kind === "flutter" && config.args[0] === "run" && !config.args.some((arg) => NO_HOT_KEYS.has(arg));
return config.kind === "flutter" && config.args[0] === "run" && !config.args.some((arg) => NO_HOT.has(arg));
}
const canHotReload = (session: RunSession) => supportsHotReload(session.config) && acceptsInput(session);
/** The session's app started and takes reloads. */
export function canHotReload(session: RunSession, apps = useFlutterRunApps.getState()): boolean {
const app = apps[session.id];
return supportsHotReload(session.config) && acceptsInput(session) && !!app?.started && app.supportsRestart;
}
/** The active session when it can reload, else the newest one that can. */
export function hotReloadSession(): RunSession | undefined {
const { sessions, activeSession } = useRun.getState();
const active = sessions.find((s) => s.id === activeSession);
return active && canHotReload(active) ? active : [...sessions].reverse().find(canHotReload);
return active && canHotReload(active) ? active : [...sessions].reverse().find((s) => canHotReload(s));
}
export const hotReload = (sessionId: string) => writeTerminal(sessionId, "r");
export const hotRestart = (sessionId: string) => writeTerminal(sessionId, "R");
let requestId = 0;
function restart(sessionId: string, fullRestart: boolean) {
const appId = useFlutterRunApps.getState()[sessionId]?.appId;
if (!appId) return;
const request = {
id: ++requestId,
method: "app.restart",
params: { appId, fullRestart, pause: false, reason: "manual" },
};
writeTerminal(sessionId, `${JSON.stringify([request])}\n`);
}
export const hotReload = (sessionId: string) => restart(sessionId, false);
export const hotRestart = (sessionId: string) => restart(sessionId, true);
/** Marks the apps of ended Run tabs as ended, and forgets those of closed ones. */
export function syncFlutterRunApps(sessions: readonly RunSession[]) {
const apps = useFlutterRunApps.getState();
let next: typeof apps | null = null;
for (const [id, app] of Object.entries(apps)) {
const session = sessions.find((s) => s.id === id);
if (session && (isLive(session) || !app.live)) continue;
next ??= { ...apps };
if (session) next[id] = { ...app, live: false, started: false };
else delete next[id];
}
if (next) useFlutterRunApps.setState(next, true);
}
+90
Переглянути файл
@@ -0,0 +1,90 @@
/**
* `flutter run --machine`, as the Flutter plugin runs apps: stdout is JSON-RPC, one bracketed
* array of messages per line, as from `flutter daemon`. The events keep the Run tab's app in
* `useFlutterRunApps` (its id, device, VM Service and whether it started), and the console
* shows the app's own output and the tool's messages as plain lines.
*/
import type { RunConfig } from "@/platform/ipc";
import { useFlutterRunApps, type FlutterRunApp } from "@/workbench/flutterRunApps";
import { TestStdout } from "./testing/types";
export const isFlutterMachineRun = (c: RunConfig) =>
c.kind === "flutter" && c.args[0] === "run" && c.args.includes("--machine");
type Params = Record<string, unknown>;
const text = (v: unknown) => (typeof v === "string" ? v : null);
const line = (v: unknown) => {
const s = text(v);
return s ? (s.endsWith("\n") ? s : `${s}\n`) : "";
};
function patch(session: string, p: Partial<FlutterRunApp>) {
const app = useFlutterRunApps.getState()[session];
if (app) useFlutterRunApps.setState({ [session]: { ...app, ...p } });
}
/** The console text of one message. */
function message(session: string, m: { event?: unknown; params?: Params; result?: unknown; error?: unknown }) {
const p = m.params ?? {};
switch (m.event) {
case "app.start":
patch(session, { appId: text(p.appId), device: text(p.deviceId), supportsRestart: p.supportsRestart === true });
return "";
case "app.debugPort":
patch(session, { vmServiceUri: text(p.wsUri) ?? undefined });
return "";
case "app.started":
patch(session, { started: true });
return "";
case "app.stop":
patch(session, { started: false });
return line(p.error);
case "app.log":
case "daemon.logMessage":
return line(p.log ?? p.message);
case "app.progress":
return p.finished ? "" : line(p.message);
case undefined: {
// The answer to `app.restart`: only a failure says something.
if (m.error) return line(typeof m.error === "string" ? m.error : JSON.stringify(m.error));
const result = m.result as { code?: unknown; message?: unknown } | null | undefined;
return result && result.code !== 0 ? line(result.message) : "";
}
default:
return "";
}
}
/** The console text of a stdout line; lines outside the protocol show as they are. */
export function machineLine(session: string, raw: string): string {
if (!raw.startsWith("[{")) return `${raw}\n`;
let messages: unknown;
try {
messages = JSON.parse(raw);
} catch {
return `${raw}\n`;
}
if (!Array.isArray(messages)) return `${raw}\n`;
return messages.map((m) => message(session, m ?? {})).join("");
}
/** Starts following the app of a Run tab about to launch `config`; the result decodes its stdout. */
export function flutterMachineOutput(session: string, config: RunConfig): TestStdout {
useFlutterRunApps.setState({
[session]: {
session,
name: config.name,
appId: null,
device: null,
started: false,
supportsRestart: false,
live: true,
startedAt: Date.now(),
},
});
return new TestStdout(
() => undefined,
(raw) => machineLine(session, raw),
);
}
+5 -3
Переглянути файл
@@ -101,15 +101,17 @@ describe("Flutter run configurations", () => {
]);
});
it("runs on the toolbar's device", async () => {
it("runs on the toolbar's device, with --machine", async () => {
const launch = await flutterType.prepareLaunch!(config([]));
expect(launch.args.slice(-2)).toEqual(["-d", "macos"]);
expect(launch.args.slice(-3)).toEqual(["-d", "macos", "--machine"]);
expect(notify).not.toHaveBeenCalled();
});
it("keeps a pinned device and warns when it is not connected", async () => {
const pinned = config(["-d", "X1"]);
expect((await flutterType.prepareLaunch!(pinned)).args).toEqual(pinned.args);
expect((await flutterType.prepareLaunch!(pinned)).args).toEqual([...pinned.args, "--machine"]);
const machine = config(["-d", "X1", "--machine"]);
expect((await flutterType.prepareLaunch!(machine)).args).toEqual(machine.args);
expect(notify).toHaveBeenCalledWith(expect.objectContaining({ level: "warning", key: "flutter.pinnedDevice" }));
});
+3 -1
Переглянути файл
@@ -94,6 +94,8 @@ export const flutterType: RunConfigTypeContribution = {
async prepareLaunch(config) {
warnPinnedFlutterDevice(config);
const device = pinnedFlutterDevice(config) ? null : flutterDeviceFor(config);
return device ? { ...config, args: [...config.args, "-d", device] } : config;
// As the Flutter plugin runs apps: hot reload and DevTools go through the JSON protocol.
const machine = config.args[0] === "run" && !config.args.includes("--machine") ? ["--machine"] : [];
return { ...config, args: [...config.args, ...(device ? ["-d", device] : []), ...machine] };
},
};
+4 -1
Переглянути файл
@@ -27,6 +27,7 @@ import {
registerTitleItem,
registerToolWindow,
} from "@/workbench/contributions";
import { useFlutterRunApps } from "@/workbench/flutterRunApps";
import { restartFlutterDaemon, selectFlutterDevice, useFlutterDevices } from "@/workbench/flutterDevices";
import { chooserJustClosed, ConfigChooserOverlay } from "./ConfigChooser";
import {
@@ -77,7 +78,7 @@ import {
showApplicationUpdate,
updatableSessions,
} from "./applicationUpdate";
import { hotReload, hotReloadSession, hotRestart } from "./flutterHotReload";
import { hotReload, hotReloadSession, hotRestart, syncFlutterRunApps } from "./flutterHotReload";
import { registerFlutterBuildActions } from "./flutterBuild";
import { npmGutter } from "./npmGutter";
import { launchSettingsGutter } from "./launchSettingsGutter";
@@ -943,8 +944,10 @@ export function activate(): () => void {
const cmake = selected ?? s.configs.find((c) => c.kind === "cmake" && c.args[0] === "--build");
setContext("run.cmakeBuild", cmakeBuildId(cmake, s.configs));
setContext("run.updatableRunning", updatableSessions().length > 0);
syncFlutterRunApps(s.sessions);
setContext("run.flutterHotReloadable", !!hotReloadSession());
}),
useFlutterRunApps.subscribe(() => setContext("run.flutterHotReloadable", !!hotReloadSession())),
// Agent tabs (`run_command`): the archive keeps at most Settings' number of them.
useRun.subscribe((s, prev) => {
if (s.sessions !== prev.sessions) trimAgentArchive();
+6 -2
Переглянути файл
@@ -55,6 +55,7 @@ import { moveToReportedClasses } from "./testing/jvm";
import { RubyTestOutput } from "./testing/ruby";
import { TeamcityOutput } from "./testing/teamcity";
import type { TestStdout } from "./testing/types";
import { flutterMachineOutput, isFlutterMachineRun } from "./flutterMachine";
import { recordTestStates } from "./testing/states";
import { failedTestPaths, leafTestPaths, rerunFailedConfigs, testsConfigs } from "./testing/rerun";
import { testsBySubproject } from "./testing/gradleSubprojects";
@@ -1129,8 +1130,11 @@ async function startRunIn(
if (!check && launch.kind === "tomcat") useRun.setState({ activeSession: sessionId });
if (runtimes.get(sessionId)?.generation !== generation) return getSession(sessionId) ?? null;
}
// Debug launches read the agent's output lines: never through a terminal.
if ((options.launch || launch.isTest) && launch.emulateTerminal) launch = { ...launch, emulateTerminal: false };
const machine = isFlutterMachineRun(launch);
if (machine) rt.stdout = flutterMachineOutput(sessionId, config);
// Debug launches read the agent's output lines, `flutter run --machine` speaks JSON: never through a terminal.
if ((options.launch || launch.isTest || machine) && launch.emulateTerminal)
launch = { ...launch, emulateTerminal: false };
if (launch.emulateTerminal) rt.terminal = new TerminalOutput();
patchSession(sessionId, { terminal: !!launch.emulateTerminal });
let started =
+18 -1
Переглянути файл
@@ -2,6 +2,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { act, fireEvent, render, screen, within } from "@testing-library/react";
import { registerAction } from "@/platform/actions";
import { clearContext, getContext, setContext, type ContextKeys } from "@/platform/context";
import { useProject } from "@/platform/project";
import { projectKey } from "@/platform/search";
import type { SeDeps } from "../everywhere/controller";
const defaultFindFiles: SeDeps["findFiles"] = async (q) =>
@@ -168,7 +170,7 @@ describe("Search Everywhere dialog", () => {
});
it("⌥↑ / ⌥↓ browse the tab's search history and restore the draft", async () => {
localStorage.removeItem("openidea.search.everywhereHistory.v1");
localStorage.removeItem(projectKey("openidea.search.everywhereHistory.v1"));
pushSearchHistory("all", "older");
pushSearchHistory("all", "newer");
pushSearchHistory("files", "other tab");
@@ -188,6 +190,21 @@ describe("Search Everywhere dialog", () => {
expect(searchHistory("all")).toEqual(["newer", "older"]);
});
it("keeps each project's Search Everywhere history apart (#5758)", () => {
const before = useProject.getState().project;
const open = (root: string) => useProject.setState({ project: { root, name: "p", isGit: false } as never });
try {
open("/work/a");
pushSearchHistory("all", "FooService");
open("/work/b");
expect(searchHistory("all")).toEqual([]);
open("/work/a");
expect(searchHistory("all")).toEqual(["FooService"]);
} finally {
useProject.setState({ project: before });
}
});
it("⇥ cycles scopes and repeating the scope action toggles non-project items", async () => {
render(<SearchEverywhereOverlay />);
act(() => showSearchEverywhere("all"));
+11
Переглянути файл
@@ -316,6 +316,17 @@ describe("Find in Files popup", () => {
expect(screen.getByRole("button", { name: "Open in Find Window" })).toBeEnabled();
});
it("clicking a scope tab keeps focus in the search field", async () => {
render(<FindInFilesOverlay />);
act(() => showFindPopup(false, { query: "order" }));
await settle();
const down = new MouseEvent("mousedown", { bubbles: true, cancelable: true });
screen.getByRole("tab", { name: "Module" }).dispatchEvent(down);
expect(down.defaultPrevented).toBe(true);
fireEvent.click(screen.getByRole("tab", { name: "Module" }));
expect(useFindPopup.getState().scopeTab).toBe("module");
});
it("closing remembers the search text", async () => {
render(<FindInFilesOverlay />);
act(() => showFindPopup(false, { query: "order" }));
+4 -2
Переглянути файл
@@ -1,5 +1,6 @@
import { create } from "zustand";
import { getContext, type ContextKeys } from "@/platform/context";
import { projectKey } from "@/platform/search";
import { loadJson, saveJson } from "../common/open";
import type { ProjectFileSet } from "@/platform/ipc";
import type { SeTab } from "./model";
@@ -135,8 +136,9 @@ interface HistoryEntry {
query: string;
}
/** The open project's history: it names the project's own symbols and files. */
function loadHistory(): HistoryEntry[] {
const v = loadJson<unknown>(HISTORY_KEY, []);
const v = loadJson<unknown>(projectKey(HISTORY_KEY), []);
return Array.isArray(v)
? v.filter((x): x is HistoryEntry => typeof x?.tab === "string" && typeof x?.query === "string")
: [];
@@ -153,5 +155,5 @@ export function pushSearchHistory(tab: SeTab, query: string) {
const q = query.trim();
if (!q) return;
const rest = loadHistory().filter((e) => e.tab !== tab || e.query !== q);
saveJson(HISTORY_KEY, [{ tab, query: q }, ...rest].slice(0, MAX_HISTORY));
saveJson(projectKey(HISTORY_KEY), [{ tab, query: q }, ...rest].slice(0, MAX_HISTORY));
}
Loaded 100 of 156 files, more files were not shown because too many files have changed in this diff. Show more