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

..
Автор SHA1 Повідомлення Дата
l0ng-ai 7cc52d7ed9 fix(flutter): compile the Flutter tests on Windows
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 test build failed under -D warnings.
2026-11-25 18:49:55 +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
guiqingle520 f597ae8c81 fix(project-tree): keep the error wavy underline from being clipped (#5820)
The Project view's label and label group hide overflow for the ellipsis, and the error label reserved only 2px below its text for an underline offset by 3px, so WebView2 clipped the wave into faint dots. The label group and the error label now reserve 4px above and below with a matching negative margin, which leaves the row height unchanged.

Closes #5802

Co-authored-by: guiqingle520 <[email protected]>
2026-11-25 16:11:42 +08:00
l0ng-ai eb036f2b67 fix(mcp): ask agents to read the workspace roots before their first project task (#5822)
The MCP server's instructions and get_workspace_roots only asked for the
roots when the user asked about directories or a change looked like it might
span projects. An agent that took its working directory for the whole
workspace never got there, and missed the projects attached in the IDE.

Both now say to call get_workspace_roots before the first project-related
operation in a session, and spell out what the answer means: projectRoot is
the project the connection serves and the default base for paths, roots is
the workspace scope to search and read rather than a list of projects to
change, and neither changes the agent's working directory or permissions.
The instructions also say to ask again after the user switches or attaches
a project. Clients that load tool descriptions lazily still see the rule in
the initialize instructions.

Fixes #5751
2026-11-25 16:10:45 +08:00
l0ng-ai ad95695588 fix(new-project): name a .NET project's top folder after its solution (#5819)
With "Create solution" checked and a solution name that differs from the
project name, the new project's top folder was still named after the project
(MyProject/MySolution.slnx, MyProject/MyProject/MyProject.csproj).

Generators can now give the project folder its own name with a `directory`
template; .NET uses the solution name, so the result is
MySolution/MySolution.slnx and MySolution/MyProject/MyProject.csproj. Without
a solution, or with an empty name, the folder is the project's as before. The
New Project dialog shows that folder in its path hint and checks it for an
existing non-empty folder.

Fixes #5732
2026-11-25 16:08:44 +08:00
l0ng-ai 9e6c29a7b7 fix(editor): highlight <style lang="less"> in Vue files with the Less grammar (#5818)
A Vue file's <style> block switched grammar only for lang="scss" and
lang="sass"; lang="less" was parsed as plain CSS, so Less variables,
nested rules and mixin calls lost their highlighting. It now uses
@codemirror/lang-less, which was already in the lockfile through
@codemirror/language-data and is now a direct dependency.

Fixes #5745
2026-11-25 16:03:55 +08:00
l0ng-ai 89fa6cb02c fix(maven): run the IDE's own Maven goals by plugin coordinates (#5814)
Offline, Maven resolves a plugin prefix (help:, dependency:) only from the
org.apache.maven.plugins group metadata in the local repository. A repository
filled from a private mirror often lacks it even when the plugin jar is there,
so every offline reload failed with "No plugin found for prefix 'help'".

The sync's effective POM and dependency tree, the resource and web build
probes (help:evaluate) and the single-file classpath probe
(dependency:build-classpath) now name the plugin by its coordinates: the
newest 3.x version already in the local repository the run resolves into
(-Dmaven.repo.local, then the -s settings, then the user's default), else a
pinned version. Offline with no cached dependency plugin, the tree still
falls back to the project's own version.

Fixes #5757
2026-11-25 15:57:02 +08:00
l0ng-ai 6f284741b3 fix(index): reconcile a changed folder one level deep and throttle snapshot refreshes (#5813)
A file changing at the project root put the root on the reconcile list, and the
reconcile walked it whole: every couple of seconds while a program wrote a log
there, the index re-read the entire project and rewrote its snapshot.

A reported folder the index already has files below is now listed one level
deep: its own files, plus subfolders that appeared (walked whole) or are gone
(their files dropped). Unknown folders are still walked whole. Snapshot
refreshes keep at least 10s apart; any index write drops the snapshot anyway,
so this only affects how fast the next startup is.

Fixes #5749
2026-11-25 15:51:23 +08:00
l0ng-ai 4b253d368e fix(index): don't show Indexing while a program writes its log in the project (#5812)
Every change the watcher reports queues its folder for a reconcile scan two seconds later, and every scan raised the Indexing flag and task. A debugged app writing to logs/ inside the project therefore kept Indexing in the status bar for as long as it ran. Subtree scans now run quietly and only show Indexing once they find 200 or more files to parse; full scans show it as before.

Part of #5792
2026-11-25 15:44:47 +08:00
184 змінених файлів з 6430 додано та 896 видалено

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.
+2 -1
Переглянути файл
@@ -26,9 +26,10 @@ pub fn plan(root: &Path, model: &BuildModel, module: &Path, cache: &Path) -> Ide
let module = dunce::canonicalize(root.join(module))?;
if let Some(p) = model.maven.as_ref().and_then(|m| m.projects.iter().find(|p| root.join(&p.dir) == module)) {
let mut args = p.options.clone();
let repo = crate::maven::local_repository_for(&p.options);
args.extend([
"process-resources".into(),
"help:evaluate".into(),
crate::maven::plugin_goal("help:evaluate", repo.as_deref()),
"-Dexpression=project.build.outputDirectory".into(),
format!("-Doutput={}", manifest.display()),
]);
+3 -1
Переглянути файл
@@ -361,7 +361,9 @@ fn classpaths(
if compile_first {
args.push("compile");
}
args.extend(["dependency:build-classpath", output_arg.as_str(), scope_arg.as_str(), "-q"]);
let build_classpath =
maven::plugin_goal("dependency:build-classpath", maven::local_repository_for(&top.options).as_deref());
args.extend([build_classpath.as_str(), output_arg.as_str(), scope_arg.as_str(), "-q"]);
let top_dir = subdir(root, &top.dir);
let owned_args: Vec<String> = args.into_iter().map(str::to_owned).collect();
let out = process::run_bounded(&top.command, &owned_args, &top_dir, &top.env, cancel, |_, _| {}).map_err(|e| {
+71
Переглянути файл
@@ -517,6 +517,59 @@ pub fn local_repository_of(settings: &Path) -> Option<PathBuf> {
Some(PathBuf::from(repo.replace("${user.home}", &home)))
}
/// The local repository a Maven run with these options resolves into: `-Dmaven.repo.local=`
/// first, then `<localRepository>` of the `-s` settings, then the user's default.
pub fn local_repository_for(options: &[String]) -> Option<PathBuf> {
if let Some(repo) = options.iter().find_map(|a| a.strip_prefix("-Dmaven.repo.local=")) {
return Some(PathBuf::from(repo));
}
let mut args = options.iter();
while let Some(arg) = args.next() {
let path = match arg.as_str() {
"-s" | "--settings" => args.next().map(String::as_str),
_ => arg.strip_prefix("-s=").or_else(|| arg.strip_prefix("--settings=")),
};
if let Some(path) = path {
return local_repository_of(Path::new(path)).or_else(default_local_repo);
}
}
default_local_repo()
}
/// A goal of the IDE's own (`help:evaluate`, `dependency:build-classpath`, …) by its plugin's
/// coordinates rather than its prefix: offline, Maven resolves a prefix only from group metadata
/// in the local repository, which a repository filled from a private mirror often lacks even when
/// the plugin itself is there. Uses the newest 3.x version already in `repo`, so nothing is
/// downloaded, else a pinned one.
pub fn plugin_goal(goal: &str, repo: Option<&Path>) -> String {
let (prefix, goal) = goal.split_once(':').expect("prefix:goal");
let (artifact, pinned) = match prefix {
"help" => ("maven-help-plugin", "3.5.1"),
"dependency" => ("maven-dependency-plugin", "3.8.1"),
_ => unreachable!("not a goal of the IDE's own: {prefix}"),
};
let version = repo.and_then(|repo| newest_local_plugin(repo, artifact, 3)).unwrap_or_else(|| pinned.to_owned());
format!("org.apache.maven.plugins:{artifact}:{version}:{goal}")
}
/// The newest release of `org.apache.maven.plugins:<artifact>` whose jar is in `repo`,
/// from major version `min_major` up.
pub(crate) fn newest_local_plugin(repo: &Path, artifact: &str, min_major: u64) -> Option<String> {
let dir = repo.join("org/apache/maven/plugins").join(artifact);
let parse = |v: &str| v.split('.').map(|n| n.parse::<u64>().ok()).collect::<Option<Vec<u64>>>();
std::fs::read_dir(&dir)
.ok()?
.flatten()
.filter_map(|e| e.file_name().into_string().ok())
.filter_map(|v| parse(&v).map(|n| (n, v)))
.filter(|(n, v)| {
n.first().is_some_and(|&major| major >= min_major)
&& dir.join(v).join(format!("{artifact}-{v}.jar")).is_file()
})
.max()
.map(|(_, v)| v)
}
impl Resolver {
fn new(local_repo: Option<PathBuf>, profiles: &[String]) -> Self {
Self::new_with_jdk(local_repo, profiles, None)
@@ -2557,6 +2610,24 @@ mod tests {
assert!(local_repository_of(&tmp.path().join("missing.xml")).is_none());
}
#[test]
fn ide_goals_resolve_from_the_repository_the_run_uses() {
let tmp = tempfile::tempdir().unwrap();
let settings = tmp.path().join("settings.xml");
std::fs::write(&settings, "<settings><localRepository>/srv/m2</localRepository></settings>").unwrap();
let s = settings.to_string_lossy().into_owned();
let opts = |a: &[&str]| a.iter().map(|s| s.to_string()).collect::<Vec<_>>();
assert_eq!(local_repository_for(&opts(&["-s", &s])), Some(PathBuf::from("/srv/m2")));
assert_eq!(local_repository_for(&opts(&[&format!("--settings={s}")])), Some(PathBuf::from("/srv/m2")));
let explicit = opts(&["-s", &s, "-Dmaven.repo.local=/tmp/r"]);
assert_eq!(local_repository_for(&explicit), Some(PathBuf::from("/tmp/r")));
// No repository known: a pinned version, still by coordinates.
assert_eq!(
plugin_goal("dependency:build-classpath", None),
"org.apache.maven.plugins:maven-dependency-plugin:3.8.1:build-classpath"
);
}
#[test]
fn effective_pom_goals_come_from_the_local_repository_it_is_given() {
let tmp = tempfile::tempdir().unwrap();
+54 -36
Переглянути файл
@@ -86,22 +86,37 @@ const MAVEN_CACHE_VERSION: u32 = 1;
/// `dependency:tree` of a plugin version whose `-Dverbose` lists the occurrences Maven
/// omitted (conflicts, duplicates): verbose output was dropped in 3.0 and is back since 3.2.
/// Offline, it is used only when an earlier sync downloaded it; otherwise the project's own
/// plugin version is, which may be cached instead.
/// Offline, it is used only when an earlier sync downloaded it; otherwise the newest version
/// in the local repository is.
const DEPENDENCY_TREE: &str = "org.apache.maven.plugins:maven-dependency-plugin:3.8.1:tree";
const DEPENDENCY_TREE_JAR: &str =
"org/apache/maven/plugins/maven-dependency-plugin/3.8.1/maven-dependency-plugin-3.8.1.jar";
/// The goals that read the effective POM into `effective` and the verbose dependency trees;
/// `repo` is the local repository the build resolves from.
/// `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());
vec![
"help:effective-pom".into(),
format!("-Doutput={}", effective.to_string_lossy()),
if pinned { DEPENDENCY_TREE.into() } else { "dependency:tree".into() },
"-Dverbose".into(),
]
let tree = if pinned {
DEPENDENCY_TREE.to_owned()
} else {
repo.and_then(|repo| maven::newest_local_plugin(repo, "maven-dependency-plugin", 2)).map_or_else(
|| "dependency:tree".to_owned(),
|v| format!("org.apache.maven.plugins:maven-dependency-plugin:{v}:tree"),
)
};
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
@@ -367,25 +382,8 @@ pub fn sync_maven(
verbose: true,
..MavenCache::default()
};
// Where the build resolves its jars, and therefore where the plugin goals are read
// from: `-Dmaven.repo.local=` first, then `<localRepository>` of the `-s` settings,
// then the user's default repository (which `plugin()` resolves itself).
let local_repo: Option<PathBuf> =
options.maven_options.iter().find_map(|a| a.strip_prefix("-Dmaven.repo.local=")).map(PathBuf::from).or_else(
|| {
let mut args = options.maven_options.iter();
while let Some(arg) = args.next() {
let path = match arg.as_str() {
"-s" | "--settings" => args.next().map(String::as_str),
_ => arg.strip_prefix("-s=").or_else(|| arg.strip_prefix("--settings=")),
};
if let Some(path) = path {
return maven::local_repository_of(Path::new(path));
}
}
None
},
);
// Where the build resolves its jars, and therefore where the plugin goals are read from.
let repo = maven::local_repository_for(&options.maven_options);
let mut errors: Vec<String> = Vec::new();
for (n, top) in model.projects.iter().filter(|p| !p.aggregated).enumerate() {
let effective = cache_dir.join(format!("effective-pom-{n}.xml"));
@@ -407,7 +405,6 @@ pub fn sync_maven(
if !options.profiles.is_empty() {
args.push(format!("-P{}", options.profiles.join(",")));
}
let repo = local_repo.clone().or_else(maven::default_local_repo);
args.extend(maven_sync_goals(&effective, options.offline, repo.as_deref()));
progress(SyncProgress { message: format!("Reading {}", top.display_name), fraction: None });
let command = options.maven_command.as_deref().unwrap_or(&top.command);
@@ -425,7 +422,7 @@ pub fn sync_maven(
}
})?;
let effective_projects = std::fs::read_to_string(&effective)
.map(|t| maven::parse_effective_pom_in(&t, local_repo.as_deref()))
.map(|t| maven::parse_effective_pom_in(&t, repo.as_deref()))
.unwrap_or_default();
let trees = maven::parse_dependency_tree(&out.text);
for (key, plugins, deps) in effective_projects {
@@ -953,11 +950,32 @@ mod tests {
#[test]
fn sync_reads_verbose_trees_with_a_pinned_plugin_unless_offline_without_it() {
let tmp = tempfile::tempdir().unwrap();
let online = maven_sync_goals(Path::new("e.xml"), false, None);
assert_eq!(online, ["help:effective-pom", "-Doutput=e.xml", DEPENDENCY_TREE, "-Dverbose"]);
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: `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[2], "dependency:tree");
assert!(offline.contains(&"-Dverbose".to_owned()));
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()));
assert_eq!(offline[0], "org.apache.maven.plugins:maven-help-plugin:3.4.0:effective-pom");
assert_eq!(offline[2], "org.apache.maven.plugins:maven-dependency-plugin:3.6.1:tree");
// Downloaded by an online sync: offline keeps using it, the project's version may be missing.
let jar = tmp.path().join(DEPENDENCY_TREE_JAR);
std::fs::create_dir_all(jar.parent().unwrap()).unwrap();
@@ -1029,7 +1047,7 @@ mod tests {
let cache = tmp.path().join("cache");
sync_maven(&root, &cache, &SyncOptions::default(), &CancellationToken::new(), &|_| {}).unwrap();
let args = std::fs::read_to_string(root.join("mvnw-args")).unwrap();
assert!(args.contains("help:effective-pom"), "args: {args}");
assert!(args.contains("maven-help-plugin:"), "args: {args}");
let loaded = crate::load_linked(&root, &cache, None, &Default::default(), &Default::default());
let maven = loaded.maven.unwrap();
assert!(maven.synced_at.is_some() && maven.sync_error.is_none(), "{:?}", maven.sync_error);
@@ -1054,6 +1072,6 @@ mod tests {
let args = std::fs::read_to_string(root.join("mvnd-args")).unwrap();
// `-T1` pins the daemon serial so the dependency trees stay parseable.
assert!(args.contains("-T1"), "args: {args}");
assert!(args.contains("help:effective-pom"), "args: {args}");
assert!(args.contains("maven-help-plugin:"), "args: {args}");
}
}
+4 -7
Переглянути файл
@@ -137,19 +137,16 @@ pub fn build(root: &Path, model: &BuildModel, id: &str, cache: &Path) -> IdeResu
// POM's effective identity first; profiles and -D options can change its GAV.
let output = cache.join("artifact-project.txt");
let mut probe = top.options.clone();
let evaluate =
crate::maven::plugin_goal("help:evaluate", crate::maven::local_repository_for(&top.options).as_deref());
probe.extend([
"-f".into(),
root.join(&p.pom).to_string_lossy().into_owned(),
"help:evaluate".into(),
evaluate.clone(),
"-Dexpression=project.id".into(),
format!("-Doutput={}", output.display()),
]);
args.extend([
"-DskipTests".into(),
"package".into(),
"help:evaluate".into(),
format!("-Doutput={}", manifest.display()),
]);
args.extend(["-DskipTests".into(), "package".into(), evaluate, format!("-Doutput={}", manifest.display())]);
return Ok(WebBuild {
command: top.command.clone(),
args,
+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();
+4 -2
Переглянути файл
@@ -33,8 +33,10 @@ fn get_workspace_roots() -> Tool {
"get_workspace_roots",
"Returns the root directories of the IDE workspace: this project and the trusted projects attached to it
in the same window, as absolute paths. A task works in one directory, but its workspace can hold several projects.
Call this when asked about the workspace, project or working directories, and before planning a change that may span
projects. Other tools reach an attached project by its root as `projectPath`.",
Call this before the first project-related operation in a session, and when asked about the workspace, project or
working directories. `projectRoot` is the project this connection serves, the default base for paths; `roots` is
every project in the workspace, the scope to search and read, not a list of projects to change. It doesn't change the
working directory or permissions. Other tools reach an attached project by its root as `projectPath`.",
|call| async move {
let root = call.root().to_path_buf();
let mut roots = vec![root.clone()];
+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
+1 -1
Переглянути файл
@@ -112,7 +112,7 @@ done
let calls = fs::read_to_string(root.join("calls")).unwrap();
assert!(calls.lines().next().unwrap().contains("-pl app -am"), "{calls}");
assert!(calls.lines().all(|line| line.contains(&format!("-P member-{index}"))), "{calls}");
assert!(calls.contains("dependency:build-classpath"), "{calls}");
assert!(calls.contains(":build-classpath"), "{calls}");
}
}
+12
Переглянути файл
@@ -305,6 +305,18 @@ impl PathFilter {
builder.build().flatten().filter(|e| e.file_type().is_some_and(|t| t.is_dir())).map(|e| e.into_path()).collect()
}
/// The folders directly in `dir` that the index would walk.
pub(crate) fn child_dirs(&self, dir: &Path) -> Vec<PathBuf> {
let Some(mut builder) = self.walker(dir) else { return Vec::new() };
builder
.max_depth(Some(1))
.build()
.flatten()
.filter(|e| e.depth() == 1 && e.file_type().is_some_and(|t| t.is_dir()))
.map(|e| e.into_path())
.collect()
}
pub(crate) fn directories_with_names(&self, names: &HashSet<&OsStr>) -> Vec<PathBuf> {
let matches = parking_lot::Mutex::new(Vec::new());
for root in self.roots() {
+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}")))?
};
+28
Переглянути файл
@@ -1281,3 +1281,31 @@ fn reconciling_a_few_changed_files_does_not_show_indexing() {
assert_eq!(announced(&events), 0, "a log being written must not show Indexing");
assert!(files(&idx, "app.log").contains(&"logs/app.log".to_owned()), "the log is still indexed");
}
/// #5749: a file at the project root changing must not re-walk the whole project when the
/// touched folders are reconciled, yet folders that appear or vanish there are still picked up.
#[test]
fn reconciling_a_root_change_lists_only_that_folder() {
let fx = sample();
let idx = fx.open();
// Written behind the index's back, deep in a folder it already knows.
fx.write("src/order/Unreported.java", "class Unreported {}\n");
// A new folder, a vanished one and an unreported file next to the changed root file.
fx.write("fresh/deep/Fresh.java", "class Fresh {}\n");
std::fs::remove_dir_all(fx.root.join("docs")).unwrap();
fx.write("Unlisted.txt", "x\n");
let log = fx.write("app.log", "line\n");
idx.update(std::slice::from_ref(&log), &[]);
assert!(idx.wait_idle(WAIT));
// The touched folders are reconciled once the snapshot delay has passed.
std::thread::sleep(Duration::from_millis(300));
assert!(idx.wait_idle(WAIT));
assert!(files(&idx, "app.log").contains(&"app.log".to_owned()), "the changed file is indexed");
assert!(files(&idx, "Unlisted").contains(&"Unlisted.txt".to_owned()), "the root folder is listed");
assert!(files(&idx, "Fresh").contains(&"fresh/deep/Fresh.java".to_owned()), "a new folder is walked");
assert!(files(&idx, "maintenance").is_empty(), "a vanished folder's files are dropped");
assert!(files(&idx, "main.rs").contains(&"src/main.rs".to_owned()), "other folders keep their files");
assert!(files(&idx, "Unreported").is_empty(), "known subfolders are not re-walked");
}
+95 -20
Переглянути файл
@@ -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")
});
@@ -36,6 +37,13 @@ const PROGRESS_EVERY: Duration = Duration::from_millis(250);
const SNAPSHOT_DELAY: Duration = Duration::from_secs(2);
#[cfg(test)]
const SNAPSHOT_DELAY: Duration = Duration::from_millis(50);
/// The shortest gap between two snapshot refreshes. Any index write drops the snapshot (see
/// `Store::apply`), so a later refresh only makes the next startup faster; a project whose files
/// keep changing (a log written inside it) would otherwise rewrite it every couple of seconds.
#[cfg(not(test))]
const SNAPSHOT_EVERY: Duration = Duration::from_secs(10);
#[cfg(test)]
const SNAPSHOT_EVERY: Duration = Duration::ZERO;
/// A subtree scan with fewer files to parse runs without showing "Indexing" (see `scan`).
const QUIET_SCAN_FILES: usize = 200;
pub(crate) const MAX_RECENT: usize = 50;
@@ -77,6 +85,8 @@ pub(crate) struct Shared {
idle: Condvar,
/// Coalesced post-update snapshot refresh.
snapshot_due: Mutex<Option<Instant>>,
/// When the snapshot was last refreshed (see [`SNAPSHOT_EVERY`]).
snapshot_saved: Mutex<Option<Instant>>,
/// Directories whose watcher events still need reconciliation before a
/// refreshed snapshot can be trusted.
pending_dirs: Mutex<HashSet<PathBuf>>,
@@ -105,6 +115,7 @@ impl Shared {
wake: Condvar::new(),
idle: Condvar::new(),
snapshot_due: Mutex::default(),
snapshot_saved: Mutex::default(),
pending_dirs: Mutex::default(),
}
}
@@ -474,7 +485,7 @@ impl Shared {
}
fn full_scan(&self, found: Option<Vec<Found>>, guard: SystemTime) {
self.scan(None, found, guard);
self.scan(None, &[], found, guard);
// Parsing every file churns through far more memory than the index keeps.
ide_core::memory::release_free_pages();
}
@@ -499,7 +510,16 @@ impl Shared {
/// reconciled after each burst of changes) shows it only once it has
/// [`QUIET_SCAN_FILES`] or more files to parse: a program writing its log inside the project
/// would otherwise keep "Indexing" in the status bar for as long as it runs.
fn scan(&self, dirs: Option<&[PathBuf]>, prewalked: Option<Vec<Found>>, guard: SystemTime) -> Option<ScanCounts> {
///
/// Indexed files the walk didn't see are dropped when they are below one of `dirs` (all of
/// them for a full scan) or directly in one of `shallow`.
fn scan(
&self,
dirs: Option<&[PathBuf]>,
shallow: &[PathBuf],
prewalked: Option<Vec<Found>>,
guard: SystemTime,
) -> Option<ScanCounts> {
let started = Instant::now();
let mut task = dirs.is_none().then(|| self.start_scan());
@@ -520,7 +540,10 @@ impl Shared {
found.iter().filter_map(|f| prev_hash_if_stale(&d, f).map(|h| (f, h))).collect();
let stale: Vec<PathBuf> = d
.paths()
.filter(|p| dirs.is_none_or(|dirs| dirs.iter().any(|dir| p.starts_with(dir))))
.filter(|p| {
dirs.is_none_or(|dirs| dirs.iter().any(|dir| p.starts_with(dir)))
|| p.parent().is_some_and(|parent| shallow.iter().any(|dir| dir == parent))
})
.filter(|p| !seen.contains(p.as_path()))
.cloned()
.collect();
@@ -624,6 +647,7 @@ impl Shared {
}
let snapshot_elapsed = snapshot_started.elapsed();
*self.snapshot_due.lock() = None;
*self.snapshot_saved.lock() = Some(Instant::now());
if let Some(task) = task {
self.indexing.store(false, Ordering::SeqCst);
self.sink.emit(IdeEvent::Task {
@@ -778,17 +802,67 @@ impl Shared {
}
let mut due = self.snapshot_due.lock();
if due.is_none() {
*due = Some(Instant::now() + SNAPSHOT_DELAY);
let soonest = self.snapshot_saved.lock().map(|saved| saved + SNAPSHOT_EVERY);
*due = Some((Instant::now() + SNAPSHOT_DELAY).max(soonest.unwrap_or(Instant::now())));
}
}
/// Reconciles the folders the watcher reported since the last snapshot, then refreshes it.
/// A folder the index already has files below is listed one level deep: its own files, plus
/// any subfolder that appeared (walked whole) or is gone (its files dropped). A folder it
/// knows nothing below is walked whole. Walking known folders whole would re-read the entire
/// project after every change to a file at its root.
fn reconcile(&self, dirs: &[PathBuf]) {
let filter = self.filter();
// The subfolders each reported folder has indexed files in; absent when it has none.
let mut known: HashMap<&Path, HashSet<PathBuf>> = HashMap::new();
{
let d = self.data.read();
for path in d.paths() {
for dir in dirs {
let Ok(rest) = path.strip_prefix(dir) else { continue };
let subdirs = known.entry(dir.as_path()).or_default();
let mut parts = rest.components();
if let (Some(first), Some(_)) = (parts.next(), parts.next()) {
subdirs.insert(dir.join(first));
}
}
}
}
let mut found = Vec::new();
let mut trees = Vec::new();
let mut shallow = Vec::new();
for dir in dirs {
let Some(indexed) = known.get(dir.as_path()) else {
found.extend(filter.walk(dir, &self.cancelled));
trees.push(dir.clone());
continue;
};
found.extend(filter.list_dir(dir));
shallow.push(dir.clone());
for sub in filter.child_dirs(dir) {
if !indexed.contains(&sub) {
found.extend(filter.walk(&sub, &self.cancelled));
trees.push(sub);
}
}
// Gone from disk; a subfolder only hidden from the listing (an extra content root
// or a newly excluded folder) is handled by its own root or the rule-change rescan.
trees.extend(indexed.iter().filter(|sub| std::fs::symlink_metadata(sub).is_err()).cloned());
}
// Reported folders may nest; parse each file once.
let mut unique = HashSet::new();
found.retain(|f| unique.insert(f.path.clone()));
self.scan(Some(&trees), &shallow, Some(found), SystemTime::now());
}
fn save_snapshot_now(&self) {
let dirs: Vec<PathBuf> = self.pending_dirs.lock().drain().collect();
if !dirs.is_empty() {
// Reconcile the directories touched since the last scan before
// recording their mtimes; otherwise a missed watcher event could be
// blessed into the manifest.
self.scan(Some(&dirs), None, SystemTime::now());
self.reconcile(&dirs);
return;
}
if let Some(store) = &self.store {
@@ -800,6 +874,7 @@ impl Shared {
}
}
*self.snapshot_due.lock() = None;
*self.snapshot_saved.lock() = Some(Instant::now());
}
fn persist(&self, puts: &[(String, FileRecord)], deletes: &[String], durable: bool) {
@@ -905,7 +980,7 @@ impl Shared {
}
}
if !rescan {
self.scan(Some(&roots), None, SystemTime::now());
self.scan(Some(&roots), &[], None, SystemTime::now());
changed.retain(|p| !roots.iter().any(|root| p.starts_with(root)));
removed.retain(|p| !roots.iter().any(|root| p.starts_with(root)));
}
@@ -1195,7 +1270,7 @@ mod metric_tests {
batch.extend([sub.join(format!("f{i}.txt")), sub, root.join("gone")]);
}
std::fs::write(root.join("keep.txt"), "x").unwrap();
shared.scan(None, None, SystemTime::now()).unwrap();
shared.scan(None, &[], None, SystemTime::now()).unwrap();
assert_eq!(shared.data.read().file_count, 41);
std::fs::remove_dir_all(root.join("gone")).unwrap();
@@ -1219,7 +1294,7 @@ mod metric_tests {
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
std::fs::write(p, "x").unwrap();
}
shared.scan(None, None, SystemTime::now()).unwrap();
shared.scan(None, &[], None, SystemTime::now()).unwrap();
assert_eq!(shared.data.read().file_count, 7);
std::fs::remove_dir_all(root.join("gone")).unwrap();
@@ -1254,11 +1329,11 @@ mod metric_tests {
for i in 0..count {
std::fs::write(root.join(format!("file_{i}.unknown")), "plain").unwrap();
}
let cold = shared.scan(None, None, SystemTime::now()).unwrap();
let cold = shared.scan(None, &[], None, SystemTime::now()).unwrap();
assert_eq!((cold.discovered, cold.metadata_reused, cold.scheduled), (count, 0, count));
assert_eq!(cold.outcomes, ExtractionCounts { unsupported: count, ..Default::default() });
assert_eq!(shared.data.read().file_count as usize, count);
let hot = shared.scan(None, None, SystemTime::now()).unwrap();
let hot = shared.scan(None, &[], None, SystemTime::now()).unwrap();
assert_eq!((hot.discovered, hot.metadata_reused, hot.scheduled), (count, count, 0));
assert_eq!(hot.outcomes.total(), 0);
}
@@ -1270,7 +1345,7 @@ mod metric_tests {
let shared = shared(&root);
let path = root.join("main.rs");
std::fs::write(&path, "fn main() {}").unwrap();
shared.scan(None, None, SystemTime::now()).unwrap();
shared.scan(None, &[], None, SystemTime::now()).unwrap();
let (found, hash) = {
let data = shared.data.read();
let e = data.get(&path).unwrap();
@@ -1290,10 +1365,10 @@ mod metric_tests {
let path = root.join("main.rs");
std::fs::write(&path, "fn main() {}\n").unwrap();
let shared = shared(&root);
let cold = shared.scan(None, None, SystemTime::now()).unwrap();
let cold = shared.scan(None, &[], None, SystemTime::now()).unwrap();
assert_eq!((cold.discovered, cold.metadata_reused, cold.scheduled), (1, 0, 1));
assert_eq!(cold.outcomes, ExtractionCounts { symbol_extractions: 1, ..Default::default() });
let hot = shared.scan(None, None, SystemTime::now()).unwrap();
let hot = shared.scan(None, &[], None, SystemTime::now()).unwrap();
assert_eq!((hot.discovered, hot.metadata_reused, hot.scheduled), (1, 1, 0));
assert_eq!(hot.outcomes, ExtractionCounts::default());
// Force a metadata mismatch without a timestamp-resolution-dependent sleep.
@@ -1304,7 +1379,7 @@ mod metric_tests {
rec.mtime = rec.mtime.wrapping_add(1);
let (entry, symbols) = FileEntry::new(path.clone(), "main.rs".into(), rec);
shared.data.write().insert(entry, symbols);
let touched = shared.scan(None, None, SystemTime::now()).unwrap();
let touched = shared.scan(None, &[], None, SystemTime::now()).unwrap();
assert_eq!((touched.discovered, touched.metadata_reused, touched.scheduled), (1, 0, 1));
assert_eq!(touched.outcomes, ExtractionCounts { hash_reused: 1, ..Default::default() });
assert_eq!(shared.data.read().symbol_count, 1);
@@ -1360,13 +1435,13 @@ mod metric_tests {
{
let mut index = shared(&root);
index.store = Some(Store::open(&cache, &root, "metrics-test").unwrap());
assert_eq!(index.scan(None, None, SystemTime::now()).unwrap().outcomes.symbol_extractions, 1);
assert_eq!(index.scan(None, &[], None, SystemTime::now()).unwrap().outcomes.symbol_extractions, 1);
}
let mut index = shared(&root);
index.store = Some(Store::open(&cache, &root, "metrics-test").unwrap());
let found = index.walk_roots(None);
index.load_persisted(&found);
let counts = index.scan(None, Some(found), SystemTime::now()).unwrap();
let counts = index.scan(None, &[], Some(found), SystemTime::now()).unwrap();
assert_eq!((counts.discovered, counts.metadata_reused, counts.scheduled), (1, 1, 0));
assert_eq!(counts.outcomes, ExtractionCounts::default());
assert_eq!(index.data.read().symbol_count, 1);
@@ -1383,7 +1458,7 @@ mod metric_tests {
{
let mut index = shared(&root);
index.store = Some(Store::open(&cache, &root, "metrics-test").unwrap());
assert_eq!(index.scan(None, None, SystemTime::now()).unwrap().outcomes.symbol_extractions, 1);
assert_eq!(index.scan(None, &[], None, SystemTime::now()).unwrap().outcomes.symbol_extractions, 1);
}
let mut index = shared(&root);
index.store = Some(Store::open(&cache, &root, "metrics-test").unwrap());
@@ -1432,7 +1507,7 @@ mod metric_tests {
{
let mut index = shared(&root);
index.store = Some(Store::open(&cache, &root, "metrics-test").unwrap());
index.scan(None, None, SystemTime::now()).unwrap();
index.scan(None, &[], None, SystemTime::now()).unwrap();
}
let mut index = shared(&root);
index.store = Some(Store::open(&cache, &root, "metrics-test").unwrap());
@@ -1483,7 +1558,7 @@ mod metric_tests {
});
index
});
assert!(index.scan(None, None, SystemTime::now()).is_none());
assert!(index.scan(None, &[], None, SystemTime::now()).is_none());
assert!(index.is_cancelled());
assert!(!index.indexing.load(Ordering::Relaxed));
assert_eq!(index.data.read().file_count, 1);
@@ -1494,7 +1569,7 @@ mod metric_tests {
let dir = tempfile::tempdir().unwrap();
let shared = shared(dir.path());
shared.cancel();
assert!(shared.scan(None, None, SystemTime::now()).is_none());
assert!(shared.scan(None, &[], None, SystemTime::now()).is_none());
assert!(!shared.indexing.load(Ordering::Relaxed));
}
}
+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())]);
+7 -2
Переглянути файл
@@ -168,8 +168,13 @@ impl Session<'_> {
"instructions": format!(
"Built-in OpenIDEA tools for {about}: they see the files as the IDE has them and, \
for a project open in a window, its editors. The project's workspace can include other \
projects attached to it: call `get_workspace_roots` to list them before answering about \
workspace directories or planning a change across projects."
projects attached to it, which a session's working directory doesn't show. Before the \
first project-related operation in a session, call `get_workspace_roots`: its \
`projectRoot` is the project this connection serves and the default base for paths, and \
its `roots` are every project in the IDE workspace. That is the scope to search and read, \
not a list of projects to change; it doesn't change your working directory or \
permissions. Pass another root as `projectPath` to reach that project. Call it again \
when the user switches projects or attaches one."
),
})
}
+2
Переглянути файл
@@ -282,6 +282,8 @@ async fn a_folder_served_in_the_background_answers_initialize_list_and_call() {
let init = rpc_for(&s, &inside, "initialize", json!({})).await;
let instructions = init["result"]["instructions"].as_str().unwrap();
assert!(instructions.contains(inventory.to_str().unwrap()), "{instructions}");
// Clients that load tool descriptions lazily still learn to establish the workspace first (#5751).
assert!(instructions.contains("first project-related operation in a session, call `get_workspace_roots`"));
let list = rpc_for(&s, &inside, "tools/list", json!({})).await;
assert_eq!(list["result"]["tools"][0]["description"], format!("Names {}", inventory.display()), "{list}");
let call = rpc_for(&s, &inside, "tools/call", json!({ "name": "where" })).await;
+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()
}
+1
Переглянути файл
@@ -127,6 +127,7 @@ pub(crate) fn info(def: &Def) -> GeneratorInfo {
description: def.description.clone(),
git: def.git,
fields: def.fields.iter().map(field).collect(),
directory: def.directory.clone(),
dynamic: def.service.is_some(),
}
}
+18 -4
Переглянути файл
@@ -57,6 +57,16 @@ fn with_defaults(def: &Def, name: &str, values: &Values) -> Values {
out
}
/// The project folder's name: the generator's `directory` template (the solution name of a
/// .NET project with a solution), or the project name.
fn project_folder(def: &Def, name: &str, values: &Values) -> String {
def.directory
.as_deref()
.map(|t| render(t, values).trim().to_owned())
.filter(|folder| !folder.is_empty())
.unwrap_or_else(|| name.to_owned())
}
/// The fields a project service adds to the form (its metadata); empty for other generators.
pub fn options(id: &str, values: &Values, cancel: &CancellationToken) -> IdeResult<Vec<Field>> {
let def = def(id).ok_or_else(|| unknown(id))?;
@@ -398,15 +408,19 @@ pub(crate) fn create_with(
if let Some(e) = name_error(name) {
return Err(IdeError::invalid(e));
}
let values = with_defaults(def, name, &req.values);
let folder = project_folder(def, name, &values);
if let Some(e) = name_error(&folder) {
return Err(IdeError::invalid(e));
}
let location = req.location.to_path_buf();
if !location.is_dir() {
std::fs::create_dir_all(&location)?;
}
let target = location.join(name);
let target = location.join(&folder);
if target_taken(&target) {
return Err(IdeError::invalid(format!("{} already exists and is not empty", target.display())));
}
let values = with_defaults(def, name, &req.values);
let search = search_path();
let mut missing = def
@@ -420,10 +434,10 @@ pub(crate) fn create_with(
return Err(IdeError::unavailable(format!("`{}`{need} is required to create this project", r.program)));
}
let staging = Staging(location.join(format!(".{name}.openidea-new-{}", std::process::id())));
let staging = Staging(location.join(format!(".{folder}.openidea-new-{}", std::process::id())));
let _ = std::fs::remove_dir_all(&staging.0);
std::fs::create_dir_all(&staging.0)?;
let project = staging.0.join(name);
let project = staging.0.join(&folder);
download_service(def, &values, &staging.0, &project, cancel, emit)?;
let creates_dir = def.steps.iter().any(|s| s.cwd == Cwd::Parent && s.applies(&values));
+16
Переглянути файл
@@ -169,6 +169,17 @@ fn dotnet_pins_the_sdk_and_creates_a_solution() {
let (pin, lines) = render(&[("solution", "false")]);
assert_eq!(pin, None);
assert_eq!(lines, ["dotnet new console --name Shop --output . --language C#", "dotnet new gitignore"]);
// #5732: the top folder is the solution's (Store/Store.slnx, Store/Shop/Shop.csproj), as in
// Rider and Visual Studio; without a solution `solution-name` isn't sent and it is the project's.
let folder = |pairs: &[(&str, &str)]| {
let given = pairs.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect();
project_folder(def, "Shop", &with_defaults(def, "Shop", &given))
};
assert_eq!(folder(&[("solution-name", "Store")]), "Store");
assert_eq!(folder(&[]), "Shop");
assert_eq!(folder(&[("solution", "false")]), "Shop");
assert_eq!(folder(&[("solution-name", " ")]), "Shop");
}
#[cfg(unix)]
@@ -198,6 +209,11 @@ fn dotnet_templates_see_the_selected_sdk_before_running() {
let pin: serde_json::Value = serde_json::from_slice(&std::fs::read(project.join("global.json")).unwrap()).unwrap();
assert_eq!(pin["sdk"]["version"], "10.0.400");
assert_eq!(std::fs::read_to_string(parent_pin).unwrap(), inherited);
// A solution named apart from the project names the folder.
let req = request("dotnet", tmp.path(), "Api", &[("sdk", "10.0.400"), ("solution-name", "Store")]);
let project = create_with(&def, &req, &CancellationToken::new(), &|_| {}).unwrap();
assert_eq!(project, tmp.path().join("Store"));
assert!(project.join("global.json").is_file());
}
/// `dotnet` of a runtime-only install: `--version` fails ("No .NET SDKs were found").
+8
Переглянути файл
@@ -30,6 +30,11 @@ pub(crate) struct Def {
pub requires: Vec<RequireDef>,
#[serde(default)]
pub fields: Vec<FieldDef>,
/// The project folder's name, when it isn't the project name: a template over the fields
/// (.NET's solution name). Steps that create the folder themselves (`cwd = "parent"`) can't
/// use it.
#[serde(default)]
pub directory: Option<String>,
#[serde(default)]
pub service: Option<ServiceDef>,
/// Generation runs: the service's zip, `steps`, `files`, then `after`.
@@ -280,6 +285,9 @@ pub struct GeneratorInfo {
/// Offer "Create Git repository".
pub git: bool,
pub fields: Vec<Field>,
/// The project folder's name when it isn't the project name: a template over the fields
/// shown (a hidden field has its default), like [`Field::default`]; empty renders the name.
pub directory: Option<String>,
/// More fields come from `scaffold_options` (a project service's metadata).
pub dynamic: bool,
}
+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);
});
+1
Переглянути файл
@@ -9,6 +9,7 @@ const java: GeneratorInfo = {
order: 1,
description: "A plain Java application built with Maven or Gradle.",
git: true,
directory: null,
dynamic: false,
fields: [
{
+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();
});
+4
Переглянути файл
@@ -3,6 +3,9 @@ name = ".NET"
group = ".NET"
icon = "project-dotnet"
description = "A .NET project from dotnet new."
# With a solution, the top folder is named after it (MySolution/MyProject/MyProject.csproj).
# `solution-name` is sent only while "Create solution" is checked; otherwise it renders the name.
directory = "{{solution-name}}"
# `dotnet --version` fails without an SDK (a runtime-only install). Blazor Web App and the
# other templates' current options need SDK 8.
@@ -50,6 +53,7 @@ type = "checkbox"
default = "true"
hint = "As in Visual Studio: the solution file at the top, the project in its own folder."
[[fields]]
id = "solution-name"
label = "Solution name:"
+1
Переглянути файл
@@ -52,6 +52,7 @@
"@codemirror/lang-html": "^6.4.12",
"@codemirror/lang-java": "^6.0.2",
"@codemirror/lang-javascript": "^6.2.5",
"@codemirror/lang-less": "^6.0.2",
"@codemirror/lang-markdown": "^6.5.2",
"@codemirror/lang-sass": "^6.0.2",
"@codemirror/lang-sql": "^6.10.0",
Створено
+3
Переглянути файл
@@ -31,6 +31,9 @@ importers:
'@codemirror/lang-javascript':
specifier: ^6.2.5
version: 6.2.5
'@codemirror/lang-less':
specifier: ^6.0.2
version: 6.0.2
'@codemirror/lang-markdown':
specifier: ^6.5.2
version: 6.5.2
+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
+89 -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. */
@@ -7403,6 +7483,11 @@ export type GeneratorInfo = {
/** Offer "Create Git repository". */
git: boolean,
fields: Field[],
/**
* The project folder's name when it isn't the project name: a template over the fields
* shown (a hidden field has its default), like [`Field::default`]; empty renders the name.
*/
directory: string | null,
/** More fields come from `scaffold_options` (a project service's metadata). */
dynamic: boolean,
};
@@ -9104,6 +9189,7 @@ export type LanguagesSettings = {
markdown?: MarkdownSettings,
arduino?: ArduinoSettings,
zig?: ZigSettings,
flutter?: FlutterSettings,
};
export type LargeCommitFile = {
@@ -12590,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
+10
Переглянути файл
@@ -16,6 +16,16 @@ describe("vue language mode", () => {
expect(tree).toMatch(/RuleSet\(ClassSelector.*RuleSet\(ClassSelector/s);
});
it('highlights Less inside <style lang="less">', async () => {
const support = await loadSupport(findLanguageDescription("Vue", "/p/a.vue")!);
const src = `<template><div/></template>\n<style lang="less">\n@c: red;\n.a { .b { color: @c; } .m(); }\n</style>`;
const tree = support!.language.parser.parse(src).toString();
// Less-only syntax: a top-level @-variable declaration, a mixin call and a nested rule.
expect(tree).toContain("StyleSheet(Declaration(AtKeyword");
expect(tree).toContain("Inclusion(ClassSelector");
expect(tree).toMatch(/RuleSet\(ClassSelector.*RuleSet\(ClassSelector/s);
});
it("still parses a plain <style> block as CSS", async () => {
const support = await loadSupport(findLanguageDescription("Vue", "/p/a.vue")!);
const tree = support!.language.parser
+6 -4
Переглянути файл
@@ -1,11 +1,12 @@
/**
* Vue single-file components: `@codemirror/lang-vue`'s parser over an HTML
* base that also highlights `<style lang="scss|sass">` with the Sass grammar —
* stock `vue()` parses every `<style>` as plain CSS, which loses the SCSS
* colours.
* base that also highlights `<style lang="scss|sass">` with the Sass grammar
* and `<style lang="less">` with the Less one — stock `vue()` parses every
* `<style>` as plain CSS, which loses their variables, nesting and mixins.
*/
import { indentNodeProp, LanguageSupport, type LRLanguage, type TreeIndentContext } from "@codemirror/language";
import { html } from "@codemirror/lang-html";
import { lessLanguage } from "@codemirror/lang-less";
import { sassLanguage } from "@codemirror/lang-sass";
import { vue } from "@codemirror/lang-vue";
@@ -27,13 +28,14 @@ export function vueLanguage(): LanguageSupport {
const base = html({
selfClosingTags: true,
// `<style>` without `lang` (or with `lang="css"`) keeps HTML's own CSS
// nesting; only an explicit SCSS/Sass dialect re-parses it.
// nesting; only an explicit SCSS/Sass/Less dialect re-parses it.
nestedLanguages: [
{
tag: "style",
attrs: (a) => a.lang === "scss" || a.lang === "sass",
parser: sassLanguage.parser,
},
{ tag: "style", attrs: (a) => a.lang === "less", parser: lessLanguage.parser },
],
});
const language = (base.language as LRLanguage).configure({ props: [indentNodeProp.add({ Element: elementIndent })] });
+66 -64
Переглянути файл
@@ -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;
@@ -86,26 +89,31 @@
}
.bar {
display: flex;
flex-wrap: wrap;
flex-wrap: nowrap;
align-items: center;
gap: var(--space-0-5);
gap: var(--space-1);
padding: 4px 6px 6px;
cursor: default;
}
.toolbar {
display: flex;
flex: 1;
flex-wrap: wrap;
flex: 1 1 0;
flex-wrap: nowrap;
align-items: center;
min-width: 0;
overflow: hidden;
gap: var(--space-0-5);
font-size: var(--fs-small);
}
.toolbar > button {
flex: 0 1 auto;
min-width: 0;
}
.actions {
display: flex;
flex: none;
align-items: center;
gap: var(--space-1);
margin-left: auto;
}
/* Attach/reference buttons share the send button's 24px footprint and chrome. */
/* Plain toolbar icons, framed only on hover like the rest of the IDE's toolbars. */
@@ -114,21 +122,60 @@
height: var(--h-control);
}
.spacer {
flex: 1;
display: none;
}
.configPicker,
.modelControl {
display: flex;
flex: 0 1 auto;
min-width: 0;
}
.modelControl {
align-items: center;
}
.modelControl > .chip {
flex: 0 1 auto;
min-width: 0;
}
.configPicker > button {
min-width: 0;
max-width: 100%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.inlineSetting {
flex: none;
}
.collapsed {
display: none;
}
.compactDetail {
display: none;
}
.settingsMenu {
display: none;
flex: none;
}
.settingsMenuVisible {
display: flex;
}
/* Applied only synchronously during JS overflow measurement (never painted). */
.toolbarMeasuring > *,
.toolbarMeasuring .configPicker,
.toolbarMeasuring .modelControl,
.toolbarMeasuring .modelControl > .chip,
.toolbarMeasuring .chip,
.toolbarMeasuring .configPicker > button {
flex: none;
max-width: none;
}
.toolbarMeasuring .collapsed,
.toolbarMeasuring .settingsMenu {
display: flex;
}
.toolbarMeasuring .compactDetail {
display: inline-grid;
}
.settingsPopup {
width: min(320px, calc(100vw - 24px));
@@ -154,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 {
@@ -336,54 +386,6 @@
padding: 8px 14px 2px;
border-top: 1px solid var(--border);
}
@container agent-composer (max-width: 600px) {
/* Narrow: keep one row of icons next to the agent picker. The model/mode pickers
collapse into the settings menu, so nothing has to wrap onto a second line. */
.bar {
flex-direction: row;
align-items: center;
gap: var(--space-1-5);
}
.toolbar {
flex-wrap: nowrap;
}
.toolbar > button,
.toolbar > .configPicker {
flex: 0 1 auto;
min-width: 0;
}
.configPicker > button {
min-width: 0;
max-width: 100%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.chipDetail {
display: none;
}
.modelDetail {
flex-shrink: 0;
max-width: 65%;
}
.inlineSetting {
display: none;
}
.settingsMenu {
display: flex;
flex: none;
margin-left: auto;
}
.actions {
width: auto;
flex: none;
margin-left: 0;
justify-content: flex-end;
}
.actions .spacer {
display: none;
}
}
.pickerValue {
display: inline-flex;
align-items: baseline;
+3 -1
Переглянути файл
@@ -1323,7 +1323,9 @@ export function Composer(props: ComposerProps) {
)}
<div ref={hostRef} className={styles.field} />
<div className={styles.bar} onMouseDown={(e) => e.stopPropagation()}>
<div className={styles.toolbar}>{props.toolbar}</div>
<div className={styles.toolbar} data-composer-toolbar="">
{props.toolbar}
</div>
<div className={styles.actions}>
<IconButton
ref={addAnchor}
+101 -14
Переглянути файл
@@ -1,7 +1,7 @@
import { fireEvent, render, screen, within } from "@testing-library/react";
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { AgentConfigOption } from "@/bindings";
import { ConfigPickers, configPickerOptions } from "./ConfigPickers";
import { ConfigPickers, computeOverflowLayout, configPickerOptions } from "./ConfigPickers";
import { useAgents } from "./store";
beforeEach(() => {
@@ -95,7 +95,7 @@ describe("configPickerOptions", () => {
});
});
it("shows Cursor approvals separately from its execution mode and sends the choice", () => {
it("tucks Cursor approvals into the mode popup as a switch and sends the choice", () => {
const option = (id: string, category: string, values: string[]): AgentConfigOption => ({
id,
category,
@@ -110,19 +110,19 @@ it("shows Cursor approvals separately from its execution mode and sends the choi
})),
});
const onChange = vi.fn();
render(
<ConfigPickers
config={[
option("mode", "mode", ["Agent", "Plan", "Ask"]),
option("openidea.cursor.approval", "approval", ["ask", "bypass"]),
]}
onChange={onChange}
/>,
);
expect(screen.getByText("Agent")).toBeVisible();
fireEvent.click(screen.getByLabelText("Approvals"));
fireEvent.click(screen.getByRole("option", { name: "Bypass approvals" }));
const cfg = [
option("mode", "mode", ["Agent", "Plan", "Ask"]),
option("openidea.cursor.approval", "approval", ["ask", "bypass"]),
];
const { rerender } = render(<ConfigPickers config={cfg} onChange={onChange} />);
expect(screen.getByRole("button", { name: "Mode" })).toHaveTextContent("Agent");
expect(screen.queryByRole("button", { name: "Approvals" })).not.toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Mode" }));
fireEvent.click(screen.getByRole("switch", { name: "Bypass approvals" }));
expect(onChange).toHaveBeenCalledWith("openidea.cursor.approval", "bypass");
rerender(<ConfigPickers config={cfg} values={{ "openidea.cursor.approval": "bypass" }} onChange={onChange} />);
expect(screen.getByRole("button", { name: "Mode" })).toHaveTextContent("AgentBypass");
});
it("shows Allow All as a switch and sends on/off values", () => {
@@ -501,4 +501,91 @@ describe("model settings", () => {
render(<ConfigPickers config={copilotConfig(null)} onChange={vi.fn()} />);
expect(screen.getByRole("button", { name: "Model" })).toHaveAttribute("aria-haspopup", "listbox");
});
it("omits off switches from multi-setting summaries and shows them concisely when on", () => {
const cfg = copilotConfig();
cfg.push(
{
id: "context",
name: "Context",
category: "model_config",
description: null,
current: "500k",
via: "option",
values: [value("500k", "500K")],
},
{
id: "fast",
name: "Fast",
category: "model_config",
description: null,
current: "false",
via: "option",
values: [value("false", "Off"), value("true", "Fast")],
},
);
const { rerender } = render(<ConfigPickers config={cfg} onChange={vi.fn()} />);
const settings = screen.getByRole("button", { name: /^Model settings:/ });
expect(settings).toHaveTextContent("medium · 500K");
expect(settings).toHaveAttribute("title", expect.stringContaining("Fast: Off"));
rerender(<ConfigPickers config={cfg} values={{ fast: "true" }} onChange={vi.fn()} />);
expect(screen.getByRole("button", { name: /^Model settings:/ })).toHaveTextContent("medium · 500K · Fast");
});
});
describe("computeOverflowLayout", () => {
const base = {
gap: 2,
fixedWidths: [38, 220], // agent icon + model/settings
secondaryWidths: [120, 90], // mode (with detail) + collaboration mode
detailWidth: 45,
detailIndex: 0,
menuWidth: 24,
};
it("keeps everything visible when the toolbar fits", () => {
// 38 + 220 + 120 + 90 + 3*2 = 474
expect(computeOverflowLayout({ ...base, available: 500 })).toEqual({
compactDetail: false,
collapsedCount: 0,
});
});
it("hides chip detail before collapsing any secondary picker", () => {
// 474 - 45 = 429
expect(computeOverflowLayout({ ...base, available: 440 })).toEqual({
compactDetail: true,
collapsedCount: 0,
});
});
it("collapses trailing secondary pickers one by one as space shrinks", () => {
// Keep mode (full 120) + menu (24): 38 + 220 + 120 + 24 + 3*2 = 408
expect(computeOverflowLayout({ ...base, available: 410 })).toEqual({
compactDetail: false,
collapsedCount: 1,
});
// Keep mode (compact 75) + menu (24): 38 + 220 + 75 + 24 + 3*2 = 363
expect(computeOverflowLayout({ ...base, available: 370 })).toEqual({
compactDetail: true,
collapsedCount: 1,
});
// Collapse all secondary pickers into the menu:
expect(computeOverflowLayout({ ...base, available: 320 })).toEqual({
compactDetail: false,
collapsedCount: 2,
});
});
it("does nothing when unmeasured (available <= 0) or when there are no secondary items", () => {
expect(computeOverflowLayout({ ...base, available: 0 })).toEqual({
compactDetail: false,
collapsedCount: 0,
});
expect(computeOverflowLayout({ ...base, available: 100, secondaryWidths: [] })).toEqual({
compactDetail: false,
collapsedCount: 0,
});
});
});
+269 -52
Переглянути файл
@@ -1,7 +1,7 @@
/**
* Model and settings controls shared by the New Task and session composers.
*/
import { useEffect, useRef, useState } from "react";
import { useEffect, useLayoutEffect, useRef, useState } from "react";
import clsx from "clsx";
import type { AgentConfigOption } from "@/bindings";
import { useTx } from "@/platform/i18n";
@@ -74,6 +74,103 @@ function switchValues(option: AgentConfigOption): { on: string; off: string } |
return on && off ? { on, off } : null;
}
interface ModeApprovalSwitch {
on: string;
off: string;
/** Switch label inside the Mode popup footer (e.g. "Allow All", "Bypass approvals"). */
label: string;
/** Concise detail shown on the Mode chip when enabled (e.g. "Allow All", "Bypass"). */
chipLabel: string;
}
/** A two-state permissions or approval option tucked as a switch inside the Mode popup. */
function modeApprovalSwitch(option: AgentConfigOption): ModeApprovalSwitch | null {
if (option.category === "permissions") {
const sw = switchValues(option);
return sw ? { ...sw, label: option.name, chipLabel: option.name } : null;
}
if (option.category === "approval" && option.values.length === 2) {
const on = option.values.find((v) => v.value.toLowerCase() === "bypass");
const off = option.values.find((v) => v !== on);
if (on && off) {
return { on: on.value, off: off.value, label: on.name || option.name, chipLabel: "Bypass" };
}
}
return null;
}
export interface OverflowInput {
available: number;
gap: number;
fixedWidths: readonly number[];
secondaryWidths: readonly number[];
detailWidth: number;
detailIndex: number;
menuWidth: number;
}
export interface OverflowLayout {
/** Hide secondary detail text inside chips (e.g. "Allow All" / "Bypass") before collapsing items. */
compactDetail: boolean;
/** Number of trailing secondary items moved into the overflow settings menu. */
collapsedCount: number;
}
/**
* Decides how many secondary pickers fit on a single toolbar row before spilling into the
* settings menu: first drops optional chip detail labels, then collapses trailing secondary
* items one by one from right to left.
*/
export function computeOverflowLayout({
available,
gap,
fixedWidths,
secondaryWidths,
detailWidth,
detailIndex,
menuWidth,
}: OverflowInput): OverflowLayout {
if (available <= 0 || secondaryWidths.length === 0) {
return { compactDetail: false, collapsedCount: 0 };
}
const fixedCount = fixedWidths.length;
const fixedTotal = fixedWidths.reduce((sum, w) => sum + w, 0);
const widthFor = (kept: number, compactDetail: boolean): number => {
const hasMenu = kept < secondaryWidths.length;
const itemCount = fixedCount + kept + (hasMenu ? 1 : 0);
if (itemCount === 0) return 0;
let total = fixedTotal;
for (let i = 0; i < kept; i++) total += secondaryWidths[i]!;
if (compactDetail && detailWidth > 0 && detailIndex >= 0 && detailIndex < kept) {
total -= detailWidth;
}
if (hasMenu) total += menuWidth;
return total + gap * (itemCount - 1);
};
if (widthFor(secondaryWidths.length, false) <= available) {
return { compactDetail: false, collapsedCount: 0 };
}
if (detailWidth > 0 && detailIndex >= 0 && widthFor(secondaryWidths.length, true) <= available) {
return { compactDetail: true, collapsedCount: 0 };
}
for (let collapsed = 1; collapsed <= secondaryWidths.length; collapsed++) {
const kept = secondaryWidths.length - collapsed;
if (kept === 0) return { compactDetail: false, collapsedCount: collapsed };
if (widthFor(kept, false) <= available) {
return { compactDetail: false, collapsedCount: collapsed };
}
if (detailWidth > 0 && detailIndex >= 0 && detailIndex < kept && widthFor(kept, true) <= available) {
return { compactDetail: true, collapsedCount: collapsed };
}
}
return { compactDetail: false, collapsedCount: secondaryWidths.length };
}
const selected = (option: AgentConfigOption, value: string | null) =>
option.values.find((v) => v.value === value) ?? null;
@@ -103,7 +200,9 @@ export function ConfigPickers({
}) {
const tx = useTx();
const [open, setOpen] = useState(false);
const [overflow, setOverflow] = useState<OverflowLayout>({ compactDetail: false, collapsedCount: 0 });
const anchor = useRef<HTMLButtonElement>(null);
const menuRef = useRef<HTMLDivElement>(null);
const options = mainOptions(config);
if (modelRefresh?.draft && !options.some((o) => o.category === "model"))
options.unshift({
@@ -124,53 +223,144 @@ export function ConfigPickers({
const tuckedEffort = combinedModel ? (effort ?? null) : null;
const tuckedModelConfig = new Set(modelConfigs.map((o) => o.id));
const mode = options.find((o) => o.category === "mode");
const allowAll = mode && options.find((o) => switchValues(o));
const allowAll = mode && options.find((o) => !!modeApprovalSwitch(o));
const inline = options.filter(
(o) => o !== effort && o !== allowAll && !(combinedModel && tuckedModelConfig.has(o.id)),
);
if (effort && !tuckedEffort) inline.splice(model ? inline.indexOf(model) + 1 : 0, 0, effort);
// The compact menu holds everything but the model, effort, and model-specific parameters.
const collapsible = inline.filter((o) => o.category !== "model" && o !== effort);
// The overflow menu holds everything except the model, effort, and model-specific parameters.
const secondary = options.filter(
(o) => o.category !== "model" && o !== effort && !(combinedModel && tuckedModelConfig.has(o.id)),
);
const signature = [
...inline.map((o) => `${o.id}:${valueOf(o) ?? ""}`),
...(tuckedEffort ? [`${tuckedEffort.id}:${valueOf(tuckedEffort) ?? ""}`] : []),
...modelConfigs.map((o) => `${o.id}:${valueOf(o) ?? ""}`),
allowAll ? `${allowAll.id}:${valueOf(allowAll) ?? ""}` : "",
modelRefresh?.loadingSettings ? "loading" : "",
].join("|");
useLayoutEffect(() => {
const menuEl = menuRef.current;
const toolbar = menuEl?.closest<HTMLElement>("[data-composer-toolbar]");
if (!toolbar) return;
const measure = () => {
const style = getComputedStyle(toolbar);
const padX = (parseFloat(style.paddingLeft) || 0) + (parseFloat(style.paddingRight) || 0);
const available = toolbar.getBoundingClientRect().width - padX;
if (available <= 0) return;
toolbar.classList.add(styles.toolbarMeasuring!);
const gap = parseFloat(style.columnGap) || 0;
const fixedWidths: number[] = [];
const secondaryWidths: number[] = [];
let detailWidth = 0;
let detailIndex = -1;
let menuWidth = 0;
for (const child of Array.from(toolbar.children) as HTMLElement[]) {
if (child.hasAttribute("data-config-menu")) {
menuWidth = child.getBoundingClientRect().width;
continue;
}
if (child.hasAttribute("data-config-secondary")) {
const idx = secondaryWidths.length;
secondaryWidths.push(child.getBoundingClientRect().width);
const detail = child.querySelector<HTMLElement>("[data-chip-detail]");
if (detail) {
const chipGap = parseFloat(getComputedStyle(detail.parentElement!).columnGap) || 0;
detailWidth = detail.getBoundingClientRect().width + chipGap;
detailIndex = idx;
}
continue;
}
const w = child.getBoundingClientRect().width;
if (w > 0) fixedWidths.push(w);
}
toolbar.classList.remove(styles.toolbarMeasuring!);
const next = computeOverflowLayout({
available,
gap,
fixedWidths,
secondaryWidths,
detailWidth,
detailIndex,
menuWidth,
});
setOverflow((prev) => {
if (prev.compactDetail === next.compactDetail && prev.collapsedCount === next.collapsedCount) return prev;
if (prev.collapsedCount > 0 && next.collapsedCount === 0) setOpen(false);
return next;
});
};
measure();
const ro = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(measure);
ro?.observe(toolbar);
const mo = typeof MutationObserver === "undefined" ? null : new MutationObserver(measure);
mo?.observe(toolbar, { childList: true });
return () => {
ro?.disconnect();
mo?.disconnect();
};
}, [signature, tx]);
const collapsedCount = Math.min(overflow.collapsedCount, collapsible.length);
const modeIndex = mode ? collapsible.indexOf(mode) : -1;
const modeVisible = modeIndex >= 0 && modeIndex < collapsible.length - collapsedCount;
const approval = secondary.find((o) => o.category === "approval" || o.category === "mode");
const summary = secondary.map((o) => `${tx(o.name)}: ${selected(o, valueOf(o))?.name ?? tx("Default")}`).join(" · ");
return (
<>
{inline.map((o) => (
<span
key={o.id}
className={clsx(styles.configPicker, o.category !== "model" && o !== effort && styles.inlineSetting)}
>
{o === model && combinedModel ? (
<ModelPicker
model={o}
modelValue={valueOf(o)}
settings={(tuckedEffort ? [tuckedEffort, ...modelConfigs] : modelConfigs)
.filter((opt) => opt.values.length > 0)
.map((opt) => ({ ...opt, current: valueOf(opt) }))}
onChange={onChange}
modelRefresh={modelRefresh}
/>
) : o === mode && allowAll ? (
<ModePicker
mode={o}
modeValue={valueOf(o)}
allowAll={allowAll}
allowAllValue={valueOf(allowAll)}
onChange={onChange}
/>
) : (
<ConfigPicker option={o} value={valueOf(o)} onChange={onChange} />
)}
{o === model && !combinedModel && modelRefresh?.loadingSettings && <LoadingSettingsChip />}
</span>
))}
{inline.map((o) => {
const secondaryIndex = collapsible.indexOf(o);
const isSecondary = secondaryIndex >= 0;
const collapsed = isSecondary && secondaryIndex >= collapsible.length - collapsedCount;
return (
<span
key={o.id}
data-config-secondary={isSecondary ? "" : undefined}
className={clsx(styles.configPicker, isSecondary && styles.inlineSetting, collapsed && styles.collapsed)}
>
{o === model && combinedModel ? (
<ModelPicker
model={o}
modelValue={valueOf(o)}
settings={(tuckedEffort ? [tuckedEffort, ...modelConfigs] : modelConfigs)
.filter((opt) => opt.values.length > 0)
.map((opt) => ({ ...opt, current: valueOf(opt) }))}
onChange={onChange}
modelRefresh={modelRefresh}
/>
) : o === mode && allowAll ? (
<ModePicker
mode={o}
modeValue={valueOf(o)}
allowAll={allowAll}
allowAllValue={valueOf(allowAll)}
compactDetail={overflow.compactDetail}
onChange={onChange}
/>
) : (
<ConfigPicker option={o} value={valueOf(o)} onChange={onChange} />
)}
{o === model && !combinedModel && modelRefresh?.loadingSettings && <LoadingSettingsChip />}
</span>
);
})}
{secondary.length > 0 && (
<div className={styles.settingsMenu}>
<div
ref={menuRef}
data-config-menu=""
className={clsx(styles.settingsMenu, collapsedCount > 0 && styles.settingsMenuVisible)}
>
<IconButton
ref={anchor}
icon={approval ? modeIcon(valueOf(approval) ?? "") : "settings"}
icon={!modeVisible && approval ? modeIcon(valueOf(approval) ?? "") : "settings"}
title={`${tx("Agent settings")}: ${summary}`}
aria-label={tx("Agent settings")}
aria-haspopup="dialog"
@@ -264,13 +454,23 @@ function settingValue(option: AgentConfigOption) {
return selected(option, option.current) ?? option.values[0];
}
function settingsSummary(options: AgentConfigOption[], tx: ReturnType<typeof useTx>) {
return options
.map((o) => {
const label = settingValue(o)?.name ?? tx("Default");
return o.category === "thought_level" || isContextOption(o.id) ? label : `${tx(o.name)}: ${label}`;
})
.join(" · ");
function settingsSummary(options: AgentConfigOption[], tx: ReturnType<typeof useTx>, includeInactiveSwitches = false) {
const format = (o: AgentConfigOption) => {
const current = settingValue(o);
const label = current?.name ?? tx("Default");
const sw = switchValues(o);
if (sw) {
const isOn = current?.value === sw.on;
if (!includeInactiveSwitches && !isOn && options.length > 1) return null;
return isOn ? tx(o.name) : `${tx(o.name)}: ${label}`;
}
return o.category === "thought_level" || o.category === "context_tier" || isContextOption(o.id)
? label
: `${tx(o.name)}: ${label}`;
};
const parts = options.map(format).filter((p): p is string => p !== null);
if (parts.length > 0) return parts.join(" · ");
return options.map((o) => `${tx(o.name)}: ${settingValue(o)?.name ?? tx("Default")}`).join(" · ");
}
function ModelPicker({
@@ -298,6 +498,7 @@ function ModelPicker({
: (selectedModel?.name ?? (modelRefresh ? modelValue : null) ?? tx("Default"));
const shown = settings.filter((o) => o.values.length > 0);
const summary = settingsSummary(shown, tx);
const fullSummary = settingsSummary(shown, tx, true);
const toggle = (which: "models" | "settings") => {
if (open === which) return setOpen(null);
if (which === "models") modelRefresh?.onOpen?.();
@@ -316,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 />
@@ -327,13 +528,17 @@ function ModelPicker({
type="button"
className={clsx(styles.chip, styles.modelDetail)}
aria-label={tx`Model settings: ${summary}`}
title={tx`Configure ${modelName}…`}
title={
fullSummary && fullSummary !== summary
? `${tx`Configure ${modelName}…`} (${fullSummary})`
: tx`Configure ${modelName}…`
}
aria-haspopup="dialog"
aria-expanded={open === "settings"}
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>
)
)}
@@ -507,27 +712,35 @@ function CostBadge({ category }: { category: string | null | undefined }) {
);
}
/** The mode menu, with the agent's on/off permissions option (Allow All) as a switch under it. */
/** The mode menu, with the agent's two-state permissions or approval option as a switch under it. */
function ModePicker({
mode,
modeValue,
allowAll,
allowAllValue,
compactDetail = false,
onChange,
}: {
mode: AgentConfigOption;
modeValue: string | null;
allowAll: AgentConfigOption;
allowAllValue: string | null;
compactDetail?: boolean;
onChange: (option: string, value: string) => void;
}) {
const tx = useTx();
const [open, setOpen] = useState(false);
const anchor = useRef<HTMLButtonElement>(null);
const toggle = switchValues(allowAll)!;
const toggle = modeApprovalSwitch(allowAll)!;
const current = selected(mode, modeValue);
const on = allowAllValue === toggle.on;
const summary = `${tx(mode.name)}: ${current?.name ?? tx("Default")} · ${tx(allowAll.name)}: ${on ? tx("On") : tx("Off")}`;
const approvalText =
allowAll.category === "approval"
? (selected(allowAll, allowAllValue)?.name ?? (on ? tx("On") : tx("Off")))
: on
? tx("On")
: tx("Off");
const summary = `${tx(mode.name)}: ${current?.name ?? tx("Default")} · ${tx(allowAll.name)}: ${approvalText}`;
return (
<>
<button
@@ -540,10 +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={styles.chipDetail}>{tx(allowAll.name)}</span>}
<Icon name="chevron-down" size={14} className={styles.chipChevron} />
{on && (
<span className={clsx(styles.chipDetail, compactDetail && styles.compactDetail)} data-chip-detail="">
{tx(toggle.chipLabel)}
</span>
)}
<Icon name="chevron-down" size={12} className={styles.chipChevron} />
</button>
<Popup
open={open}
@@ -573,10 +790,10 @@ function ModePicker({
))}
</div>
<div className={styles.modeFooter}>
<span title={allowAll.description ?? undefined}>{tx(allowAll.name)}</span>
<span title={allowAll.description ?? undefined}>{tx(toggle.label)}</span>
<Toggle
checked={on}
aria-label={tx(allowAll.name)}
aria-label={tx(toggle.label)}
onChange={(checked) => onChange(allowAll.id, checked ? toggle.on : toggle.off)}
/>
</div>
+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);
}
+2 -2
Переглянути файл
@@ -249,8 +249,8 @@ it("switches Cursor per-model context and fast options cleanly without sending s
};
useAgents.setState({ providers: [cursor], draft: savedDraft({ provider: "cursor", config: {} }) });
render(<HomeEditor />);
// Cursor defaults fast off even though the agent reported true, and formats context concisely.
expect(settingsButton()).toHaveTextContent("high · 256k · Fast: Off");
// Cursor defaults fast off even though the agent reported true, and omits off switches from multi-setting summaries.
expect(settingsButton()).toHaveTextContent("high · 256k");
await chooseModel("gemini-4-neon");
expect(settingsButton()).toHaveTextContent("high · 300k");
fireEvent.click(screen.getByRole("button", { name: "Start" }));
-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 -3
Переглянути файл
@@ -36,7 +36,14 @@ import {
T,
hasIcon,
} from "@/ui";
import { effectiveValues, fieldError, isVisible, versionAtLeast, type Values } from "./newProjectTemplate";
import {
effectiveValues,
fieldError,
isVisible,
projectFolder,
versionAtLeast,
type Values,
} from "./newProjectTemplate";
import { defaultProjectDirectory, openProjectInWindow } from "./windows";
import styles from "./newProject.module.css";
@@ -243,7 +250,8 @@ function NewProjectDialog({ onClose }: { onClose: () => void }) {
setEdited((all) => ({ ...all, [selected]: { ...(all[selected] ?? {}), [id]: value } }));
const syntaxError = projectNameError(name);
const path = location.trim() && !syntaxError ? joinPath(location.trim(), name) : "";
const folder = projectFolder(generator?.directory, fields, name, ownValues);
const path = location.trim() && !syntaxError ? joinPath(location.trim(), folder) : "";
const nameError =
syntaxError ?? (path && takenPath === path ? "A folder with this name already exists and is not empty" : null);
@@ -267,7 +275,7 @@ function NewProjectDialog({ onClose }: { onClose: () => void }) {
let live = true;
const dir = location.trim();
const timer = setTimeout(() => {
call(commands.scaffoldTargetTaken(dir, name.trim()))
call(commands.scaffoldTargetTaken(dir, folder))
.then((taken) => live && setTakenPath(taken ? path : null))
.catch(() => {});
}, 150);
+1
Переглянути файл
@@ -19,6 +19,7 @@ const empty: GeneratorInfo = {
description: "An empty folder to add files to.",
git: true,
fields: [],
directory: null,
dynamic: false,
};
const dotnet: GeneratorInfo = {
+13 -1
Переглянути файл
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
import type { Field } from "@/platform/ipc";
import { effectiveValues, fieldError, isVisible, render } from "../newProjectTemplate";
import { effectiveValues, fieldError, isVisible, projectFolder, render } from "../newProjectTemplate";
const text = (id: string, defaultValue: string, pattern: string | null = null): Field => ({
id,
@@ -46,4 +46,16 @@ describe("new project field templates", () => {
expect(fieldError(g, "com.example")).toBeNull();
expect(fieldError(g, "com..example")).not.toBeNull();
});
it("names the project folder after a .NET solution only while one is created", () => {
const solution: Field = { ...text("solution", "true"), kind: { type: "checkbox" } };
const fields = [solution, { ...text("solution-name", "{{name}}"), visible: { solution: ["true"] } }];
const folder = (edited: Record<string, string>) => projectFolder("{{solution-name}}", fields, "Shop", edited);
expect(folder({})).toBe("Shop");
expect(folder({ "solution-name": "Store" })).toBe("Store");
// Unchecked, the hidden name isn't sent and the folder is the project's.
expect(folder({ "solution-name": "Store", solution: "false" })).toBe("Shop");
expect(folder({ "solution-name": " " })).toBe("Shop");
expect(projectFolder(null, fields, " Shop ", { "solution-name": "Store" })).toBe("Shop");
});
});
+22
Переглянути файл
@@ -76,6 +76,28 @@ export function isVisible(field: Field, values: Values): boolean {
return Object.entries(field.visible).every(([id, allowed]) => allowed.includes(values[id] ?? ""));
}
/**
* The project folder's name: the generator's `directory` template (a .NET solution's name) over
* the values the form sends — a hidden field falls back to its default, as `ide-scaffold` does —
* or the project name.
*/
export function projectFolder(
directory: string | null | undefined,
fields: readonly Field[],
name: string,
edited: Values,
): string {
if (!directory) return name.trim();
const shown = effectiveValues(fields, name, edited);
const sent = Object.fromEntries(
Object.entries(edited).filter(([id]) => {
const field = fields.find((f) => f.id === id);
return !field || isVisible(field, shown);
}),
);
return render(directory, effectiveValues(fields, name, sent)).trim() || name.trim();
}
/** `a` ≥ `b`, comparing the numeric parts of dotted versions (`ide-scaffold`'s `version_at_least`). */
export function versionAtLeast(a: string, b: string): boolean {
const parts = (s: string) => {
+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);
}}
/>
);
}
Loaded 100 of 184 files, more files were not shown because too many files have changed in this diff. Show more