дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-05 09:41:34 +02:00
Порівняти коміти
43
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
b7b97f5b79 | ||
|
|
735fe5dd30 | ||
|
|
0cfd17979b | ||
|
|
41165bb8c0 | ||
|
|
91264713e7 | ||
|
|
71a4f7cb63 | ||
|
|
dfa632cf18 | ||
|
|
f1425854fb | ||
|
|
752650b971 | ||
|
|
d33ee53c92 | ||
|
|
57eac70018 | ||
|
|
497948eeff | ||
|
|
834846840b | ||
|
|
a393bcdcc2 | ||
|
|
08f6079316 | ||
|
|
0db493b944 | ||
|
|
2a90677e4f | ||
|
|
fed9a00dd9 | ||
|
|
f034d96ed4 | ||
|
|
eead66df7d | ||
|
|
0dccfafa90 | ||
|
|
6fba7e9424 | ||
|
|
475e35281b | ||
|
|
387670573f | ||
|
|
48aac102e1 | ||
|
|
2d7353e39f | ||
|
|
912da2551b | ||
|
|
06bd43e46f | ||
|
|
b9a5b8d90b | ||
|
|
92917d1c26 | ||
|
|
4f0ab6c968 | ||
|
|
43fdb0aba7 | ||
|
|
d65d58a4e8 | ||
|
|
d3792e5667 | ||
|
|
d0bffb5e90 | ||
|
|
8e26003894 | ||
|
|
372d23b7e4 | ||
|
|
dc35952cf4 | ||
|
|
2622c9d778 | ||
|
|
c878fb1edc | ||
|
|
9ca7a297e1 | ||
|
|
b748a4cfbc | ||
|
|
5be5487ac6 |
No files matched your search
@@ -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
|
||||
|
||||
Створено
@@ -4252,16 +4252,20 @@ name = "ide-core"
|
||||
version = "0.1.51"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"dirs 6.0.0",
|
||||
"dunce",
|
||||
"encoding_rs",
|
||||
"libc",
|
||||
"portable-pty",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2 0.10.9",
|
||||
"specta",
|
||||
"specta-typescript",
|
||||
"tempfile",
|
||||
"thiserror 2.0.21",
|
||||
"tokio-util",
|
||||
"tracing",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
|
||||
@@ -6,6 +6,13 @@
|
||||
[Simple Icons](https://github.com/simple-icons/simple-icons), retrieved through
|
||||
Iconify (`simple-icons:angular`, `simple-icons:astro`, `simple-icons:cplusplus`, `simple-icons:dart`, `simple-icons:deepseek`, `simple-icons:django`, `simple-icons:dotnet`, `simple-icons:elixir`, `simple-icons:express`, `simple-icons:fastapi`, `simple-icons:flask`, `simple-icons:flutter`, `simple-icons:go`, `simple-icons:haskell`, `simple-icons:html5`, `simple-icons:kotlin`, `simple-icons:ktor`, `simple-icons:laravel`, `simple-icons:nestjs`, `simple-icons:nextdotjs`, `simple-icons:nodedotjs`, `simple-icons:nuxt`, `simple-icons:openjdk`, `simple-icons:phoenixframework`, `simple-icons:php`, `simple-icons:python`, `simple-icons:quarkus`, `simple-icons:ruby`, `simple-icons:rubyonrails`, `simple-icons:rust`, `simple-icons:scala`, `simple-icons:springboot`, `simple-icons:svelte`, `simple-icons:swift`, `simple-icons:symfony`, `simple-icons:vite`, `simple-icons:zig`) and filled with the brand colors (the standard icon grey for black logos). Licensed under [CC0 1.0 Universal](https://github.com/simple-icons/simple-icons/blob/develop/LICENSE.md).
|
||||
|
||||
## Microsoft ConPTY
|
||||
|
||||
`crates/ide-core/resources/conpty/` contains the unmodified Microsoft Windows Console
|
||||
ConPTY runtime 1.25.260930003, embedded in Windows builds. Copyright (c) Microsoft
|
||||
Corporation. Licensed under MIT; see its [license](crates/ide-core/resources/conpty/LICENSE)
|
||||
and [package provenance](crates/ide-core/resources/conpty/README.md).
|
||||
|
||||
## Project Lombok
|
||||
|
||||
`java/lombok/lombok-1.18.48-openidea.3.jar` contains Project Lombok v1.18.48 with the Equinox
|
||||
@@ -66,7 +73,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.
|
||||
|
||||
@@ -95,6 +95,8 @@ const DEPENDENCY_TREE_JAR: &str =
|
||||
/// The goals that read the effective POM into `effective` and the verbose dependency trees;
|
||||
/// `repo` is the local repository the build resolves from. Both goals name their plugin by
|
||||
/// coordinates: offline, a prefix resolves only from group metadata the repository may lack.
|
||||
/// Offline without a cached 3.x `maven-help-plugin`, `effective-pom` is skipped so `mvn -o`
|
||||
/// still resolves the dependency tree instead of failing to download the help plugin.
|
||||
fn maven_sync_goals(effective: &Path, offline: bool, repo: Option<&Path>) -> Vec<String> {
|
||||
let pinned = !offline || repo.is_some_and(|repo| repo.join(DEPENDENCY_TREE_JAR).is_file());
|
||||
let tree = if pinned {
|
||||
@@ -105,12 +107,16 @@ fn maven_sync_goals(effective: &Path, offline: bool, repo: Option<&Path>) -> Vec
|
||||
|v| format!("org.apache.maven.plugins:maven-dependency-plugin:{v}:tree"),
|
||||
)
|
||||
};
|
||||
vec![
|
||||
maven::plugin_goal("help:effective-pom", repo),
|
||||
format!("-Doutput={}", effective.to_string_lossy()),
|
||||
tree,
|
||||
"-Dverbose".into(),
|
||||
]
|
||||
let has_help =
|
||||
!offline || repo.is_some_and(|repo| maven::newest_local_plugin(repo, "maven-help-plugin", 3).is_some());
|
||||
let mut goals = Vec::with_capacity(4);
|
||||
if has_help {
|
||||
goals.push(maven::plugin_goal("help:effective-pom", repo));
|
||||
goals.push(format!("-Doutput={}", effective.to_string_lossy()));
|
||||
}
|
||||
goals.push(tree);
|
||||
goals.push("-Dverbose".into());
|
||||
goals
|
||||
}
|
||||
|
||||
/// The settings' Maven options for the sync runs: the thread count (`-T`, also
|
||||
@@ -947,19 +953,24 @@ mod tests {
|
||||
let help = "org.apache.maven.plugins:maven-help-plugin:3.5.1:effective-pom";
|
||||
let online = maven_sync_goals(Path::new("e.xml"), false, Some(tmp.path()));
|
||||
assert_eq!(online, [help, "-Doutput=e.xml", DEPENDENCY_TREE, "-Dverbose"]);
|
||||
// Offline with neither plugin cached: the tree falls back to the project's own version.
|
||||
// Offline with neither plugin cached: `effective-pom` is skipped so `mvn -o` does not fail
|
||||
// on an uncached `maven-help-plugin`, and the tree falls back to the project's own version.
|
||||
let offline = maven_sync_goals(Path::new("e.xml"), true, Some(tmp.path()));
|
||||
assert_eq!(offline, [help, "-Doutput=e.xml", "dependency:tree", "-Dverbose"]);
|
||||
// #5757: offline, plugins in the local repository are named by their coordinates, since
|
||||
// the prefix needs group metadata a repository filled from a private mirror may lack.
|
||||
for (artifact, version) in
|
||||
[("maven-help-plugin", "3.4.0"), ("maven-help-plugin", "2.2"), ("maven-dependency-plugin", "3.6.1")]
|
||||
{
|
||||
assert_eq!(offline, ["dependency:tree", "-Dverbose"]);
|
||||
// #5757 / #5844: offline, plugins in the local repository are named by their coordinates,
|
||||
// since the prefix needs group metadata a repository filled from a private mirror may lack;
|
||||
// a repository with `maven-dependency-plugin` but no 3.x `maven-help-plugin` runs only the tree.
|
||||
for (artifact, version) in [("maven-help-plugin", "2.2"), ("maven-dependency-plugin", "3.6.1")] {
|
||||
let jar =
|
||||
tmp.path().join(format!("org/apache/maven/plugins/{artifact}/{version}/{artifact}-{version}.jar"));
|
||||
std::fs::create_dir_all(jar.parent().unwrap()).unwrap();
|
||||
std::fs::write(&jar, "").unwrap();
|
||||
}
|
||||
let offline = maven_sync_goals(Path::new("e.xml"), true, Some(tmp.path()));
|
||||
assert_eq!(offline, ["org.apache.maven.plugins:maven-dependency-plugin:3.6.1:tree", "-Dverbose"]);
|
||||
let help_jar = tmp.path().join("org/apache/maven/plugins/maven-help-plugin/3.4.0/maven-help-plugin-3.4.0.jar");
|
||||
std::fs::create_dir_all(help_jar.parent().unwrap()).unwrap();
|
||||
std::fs::write(&help_jar, "").unwrap();
|
||||
// A version folder without its jar (only the POM was fetched) doesn't count.
|
||||
std::fs::create_dir_all(tmp.path().join("org/apache/maven/plugins/maven-help-plugin/3.10.0")).unwrap();
|
||||
let offline = maven_sync_goals(Path::new("e.xml"), true, Some(tmp.path()));
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "ide-clipboard"
|
||||
description = "The OS clipboard's file list (Explorer <-> project view) and pasted images: Windows CF_HDROP / PNG / CF_DIB or macOS NSPasteboard, no window or message loop"
|
||||
description = "The OS clipboard's file list (file manager <-> project view) and pasted images: Windows CF_HDROP / PNG / CF_DIB, macOS NSPasteboard, Linux text/uri-list via GTK"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
@@ -16,8 +16,12 @@
|
||||
//! thread: AppKit and WebKit also access the general pasteboard there, and its
|
||||
//! mutable type cache cannot be protected by a mutex in this crate.
|
||||
//!
|
||||
//! Other platforms (`text/uri-list` on X11) are not wired up: [`files`] is
|
||||
//! empty and [`set_files`] fails there.
|
||||
//! Linux keeps it as `text/uri-list` (Dolphin, Nautilus and most file
|
||||
//! managers) or GNOME's `x-special/gnome-copied-files` (`copy` or `cut`, then
|
||||
//! one URI per line), read and written through the GTK clipboard on X11 and
|
||||
//! Wayland alike; [`request_files`] reads it without blocking the main loop.
|
||||
//! Other platforms are not wired up: [`files`] is empty and [`set_files`]
|
||||
//! fails there.
|
||||
//!
|
||||
//! [`png`] reads an image (a screenshot) for the project view's Paste, which
|
||||
//! saves it as a file: `public.png` or `public.tiff` on macOS, the registered
|
||||
@@ -79,6 +83,7 @@ const HEADER: usize = 20;
|
||||
|
||||
/// The absolute paths on the clipboard, empty when it holds no file list.
|
||||
/// Read failures remain errors so callers can retain an internal copy.
|
||||
/// Empty on Linux, where [`request_files`] reads it.
|
||||
pub fn files() -> std::io::Result<Vec<PathBuf>> {
|
||||
imp::files()
|
||||
}
|
||||
@@ -101,7 +106,7 @@ pub fn set_files(paths: &[PathBuf]) -> bool {
|
||||
/// line. An editor paste inserts names, not the absolute paths the file list
|
||||
/// keeps for Explorer (#1878; IDEA's text flavor is names too). A path with no
|
||||
/// file name (a root like `C:\`) keeps its whole path.
|
||||
#[cfg(any(windows, target_os = "macos", test))]
|
||||
#[cfg(any(windows, target_os = "macos", target_os = "linux", test))]
|
||||
fn names_text(paths: &[PathBuf], separator: &str) -> String {
|
||||
paths
|
||||
.iter()
|
||||
@@ -112,6 +117,82 @@ fn names_text(paths: &[PathBuf], separator: &str) -> String {
|
||||
.join(separator)
|
||||
}
|
||||
|
||||
/// The `file://` URIs in a `text/uri-list` or `x-special/gnome-copied-files`
|
||||
/// payload as local paths: comments, the `copy`/`cut` line and URIs for other
|
||||
/// hosts or schemes are skipped.
|
||||
#[cfg(any(target_os = "linux", all(test, unix)))]
|
||||
fn uri_list_paths(text: &str) -> Vec<PathBuf> {
|
||||
text.lines().map(str::trim).filter(|line| !line.starts_with('#')).filter_map(uri_to_path).collect()
|
||||
}
|
||||
|
||||
/// A local `file://` URI (`file:///a%20b` or `file://localhost/a%20b`) as a
|
||||
/// path; its percent-escapes are raw bytes, as GLib writes them.
|
||||
#[cfg(any(target_os = "linux", all(test, unix)))]
|
||||
fn uri_to_path(uri: &str) -> Option<PathBuf> {
|
||||
use std::os::unix::ffi::OsStringExt;
|
||||
let rest = uri.strip_prefix("file://")?;
|
||||
let path = if rest.starts_with('/') { rest } else { rest.strip_prefix("localhost")? };
|
||||
let path = path.split(['?', '#']).next()?;
|
||||
if !path.starts_with('/') {
|
||||
return None;
|
||||
}
|
||||
let hex = |b: u8| (b as char).to_digit(16).map(|d| d as u8);
|
||||
let bytes = path.as_bytes();
|
||||
let mut out = Vec::with_capacity(bytes.len());
|
||||
let mut i = 0;
|
||||
while i < bytes.len() {
|
||||
let escaped =
|
||||
(bytes[i] == b'%').then(|| Some((hex(*bytes.get(i + 1)?)? << 4) | hex(*bytes.get(i + 2)?)?)).flatten();
|
||||
match escaped {
|
||||
Some(b) => {
|
||||
out.push(b);
|
||||
i += 3;
|
||||
}
|
||||
None => {
|
||||
out.push(bytes[i]);
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(PathBuf::from(std::ffi::OsString::from_vec(out)))
|
||||
}
|
||||
|
||||
/// `path` as a `file://` URI, every byte outside the unreserved set and `/`
|
||||
/// percent-escaped.
|
||||
#[cfg(any(target_os = "linux", all(test, unix)))]
|
||||
fn file_uri(path: &std::path::Path) -> String {
|
||||
use std::fmt::Write;
|
||||
use std::os::unix::ffi::OsStrExt;
|
||||
let mut uri = String::from("file://");
|
||||
for &b in path.as_os_str().as_bytes() {
|
||||
if b.is_ascii_alphanumeric() || b"/-._~".contains(&b) {
|
||||
uri.push(b as char);
|
||||
} else {
|
||||
let _ = write!(uri, "%{b:02X}");
|
||||
}
|
||||
}
|
||||
uri
|
||||
}
|
||||
|
||||
/// Reads the clipboard's file list without blocking: `text/uri-list` first,
|
||||
/// then GNOME's list, and calls `done` with the paths (empty without a list).
|
||||
/// Call on the main thread; `done` runs there later.
|
||||
#[cfg(target_os = "linux")]
|
||||
pub fn request_files(done: impl FnOnce(Vec<PathBuf>) + 'static) {
|
||||
use gtk::gdk::{Atom, SELECTION_CLIPBOARD};
|
||||
fn paths_in(data: >k::SelectionData) -> Vec<PathBuf> {
|
||||
// A failed request has a negative length and no data.
|
||||
if data.length() <= 0 { Vec::new() } else { uri_list_paths(&String::from_utf8_lossy(&data.data())) }
|
||||
}
|
||||
gtk::Clipboard::get(&SELECTION_CLIPBOARD).request_contents(&Atom::intern(imp::URI_LIST), move |board, data| {
|
||||
let paths = paths_in(data);
|
||||
if !paths.is_empty() {
|
||||
return done(paths);
|
||||
}
|
||||
board.request_contents(&Atom::intern(imp::GNOME_COPIED), move |_, data| done(paths_in(data)));
|
||||
});
|
||||
}
|
||||
|
||||
/// `DROPFILES` for `paths`, in the wide form so names outside the ANSI code
|
||||
/// page survive. Empty paths are skipped.
|
||||
pub fn encode(paths: &[PathBuf]) -> Vec<u8> {
|
||||
@@ -728,8 +809,25 @@ mod imp {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
pub const URI_LIST: &str = "text/uri-list";
|
||||
#[cfg(target_os = "linux")]
|
||||
pub const GNOME_COPIED: &str = "x-special/gnome-copied-files";
|
||||
|
||||
pub fn has_files() -> bool {
|
||||
false
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
gtk::Clipboard::get(>k::gdk::SELECTION_CLIPBOARD).wait_for_targets().is_some_and(|targets| {
|
||||
targets.into_iter().any(|target| {
|
||||
let name = target.name();
|
||||
name == URI_LIST || name == GNOME_COPIED
|
||||
})
|
||||
})
|
||||
}
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
{
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
pub fn has_image() -> bool {
|
||||
@@ -747,6 +845,33 @@ mod imp {
|
||||
Ok(Vec::new())
|
||||
}
|
||||
|
||||
/// Offers `paths` as `text/uri-list` (KDE and most file managers), GNOME's
|
||||
/// list (Nautilus, Thunar) and their names as text, rendered on request.
|
||||
#[cfg(target_os = "linux")]
|
||||
pub fn set_files(paths: &[PathBuf]) -> bool {
|
||||
use gtk::{TargetEntry, TargetFlags};
|
||||
let uris: Vec<String> = paths.iter().map(|p| super::file_uri(p)).collect();
|
||||
let uri_list: String = uris.iter().map(|uri| format!("{uri}\r\n")).collect();
|
||||
let gnome = format!("copy\n{}", uris.join("\n"));
|
||||
let names = super::names_text(paths, "\n");
|
||||
let entry = |name: &str, info: u32| TargetEntry::new(name, TargetFlags::empty(), info);
|
||||
let targets = [
|
||||
entry(URI_LIST, 0),
|
||||
entry(GNOME_COPIED, 1),
|
||||
entry("UTF8_STRING", 2),
|
||||
entry("text/plain;charset=utf-8", 2),
|
||||
entry("text/plain", 2),
|
||||
];
|
||||
gtk::Clipboard::get(>k::gdk::SELECTION_CLIPBOARD).set_with_data(&targets, move |_, data, info| match info {
|
||||
0 => data.set(&data.target(), 8, uri_list.as_bytes()),
|
||||
1 => data.set(&data.target(), 8, gnome.as_bytes()),
|
||||
_ => {
|
||||
let _ = data.set_text(&names);
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
pub fn set_files(_paths: &[PathBuf]) -> bool {
|
||||
false
|
||||
}
|
||||
@@ -769,6 +894,28 @@ mod tests {
|
||||
list.iter().map(PathBuf::from).collect()
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn file_manager_uri_lists_become_paths() {
|
||||
// Dolphin: CRLF-separated `text/uri-list`, with a comment line.
|
||||
let kde = "# copied\r\nfile:///home/u/a%20b.txt\r\nfile://localhost/home/u/%E6%A1%8C%E9%9D%A2\r\n";
|
||||
assert_eq!(uri_list_paths(kde), paths(&["/home/u/a b.txt", "/home/u/桌面"]));
|
||||
// Nautilus/Thunar: `copy` or `cut`, then one URI per line.
|
||||
assert_eq!(uri_list_paths("cut\nfile:///tmp/x\nfile:///tmp/y"), paths(&["/tmp/x", "/tmp/y"]));
|
||||
// Other hosts and schemes are not local files.
|
||||
assert!(uri_list_paths("file://server/share/x\nhttps://example.com/x\nsmb:///x").is_empty());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn written_uris_read_back_as_the_same_paths() {
|
||||
let list = paths(&["/home/u/a b#1%.txt", "/home/u/桌面/项目", "/tmp/plain-name_1.~"]);
|
||||
let uris: Vec<String> = list.iter().map(|p| file_uri(p)).collect();
|
||||
assert_eq!(uris[0], "file:///home/u/a%20b%231%25.txt");
|
||||
assert_eq!(uris[2], "file:///tmp/plain-name_1.~");
|
||||
assert_eq!(uri_list_paths(&uris.join("\r\n")), list);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_written_list_reads_back_unchanged() {
|
||||
let list = paths(&["C:/work/project/a.txt", "C:/work/project/sub"]);
|
||||
|
||||
@@ -15,12 +15,16 @@ specta.workspace = true
|
||||
specta-typescript.workspace = true
|
||||
thiserror.workspace = true
|
||||
tokio-util.workspace = true
|
||||
portable-pty.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
sha2 = "0.10"
|
||||
tempfile.workspace = true
|
||||
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
libc = "0.2"
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
windows-sys = { version = "0.61", features = ["Wdk_System_SystemServices", "Win32_Foundation", "Win32_Globalization", "Win32_Security", "Win32_System_Diagnostics_ToolHelp", "Win32_System_IO", "Win32_System_JobObjects", "Win32_System_Registry", "Win32_System_SystemInformation", "Win32_System_Threading"] }
|
||||
dirs.workspace = true
|
||||
tracing.workspace = true
|
||||
windows-sys = { version = "0.61", features = ["Wdk_System_SystemServices", "Win32_Foundation", "Win32_Globalization", "Win32_Security", "Win32_System_Console", "Win32_System_Diagnostics_ToolHelp", "Win32_System_IO", "Win32_System_JobObjects", "Win32_System_LibraryLoader", "Win32_System_Registry", "Win32_System_SystemInformation", "Win32_System_Threading"] }
|
||||
@@ -0,0 +1,21 @@
|
||||
Copyright (c) Microsoft Corporation. All rights reserved.
|
||||
|
||||
MIT License
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,39 @@
|
||||
# Bundled Windows console host
|
||||
|
||||
Unmodified files from Microsoft's MIT-licensed
|
||||
[Microsoft.Windows.Console.ConPTY 1.25.260930003](https://www.nuget.org/packages/Microsoft.Windows.Console.ConPTY/1.25.260930003).
|
||||
The system ConPTY on Windows 10 build 19045 consumes alternate-screen transitions; xterm then
|
||||
puts full-screen applications' redraws in normal scrollback. A current console host
|
||||
preserves those transitions, including while resizing and updating a running TUI.
|
||||
|
||||
The package is pinned, checked in and embedded by `ide-core`, so desktop, server,
|
||||
Run and debugger builds work offline and do not depend on another installed IDE.
|
||||
Only the target architecture is embedded, along with its MIT license. `src/pty.rs`
|
||||
extracts them atomically to a versioned user cache and preloads the DLL's absolute
|
||||
path before portable-pty initializes.
|
||||
Windows reuses that module when portable-pty loads `conpty.dll` by name. Loading
|
||||
failure is logged and falls back to the system backend. Windows builds before
|
||||
19041 also retain the system backend.
|
||||
|
||||
Source archive:
|
||||
`https://api.nuget.org/v3-flatcontainer/microsoft.windows.console.conpty/1.25.260930003/microsoft.windows.console.conpty.1.25.260930003.nupkg`
|
||||
|
||||
Archive SHA-256: `02b07b349af66d801159bdf9e440d4a1ce78bb951f37fc8609731665afdae7ee`
|
||||
|
||||
For each architecture, `conpty.dll` comes from
|
||||
`runtimes/win-<arch>/native/conpty.dll`, and `OpenConsole.exe` from
|
||||
`build/native/runtimes/<arch>/OpenConsole.exe` in that archive. Preserve the pair and
|
||||
the license when updating; update `VERSION` in `src/pty.rs` and these checksums too.
|
||||
|
||||
| File | SHA-256 |
|
||||
| --------------------- | ------------------------------------------------------------------ |
|
||||
| arm64/conpty.dll | `151a02355227710c20c9f8f1eaf68ac4668aa09cdc921adc7ec661804d8eb1bf` |
|
||||
| arm64/OpenConsole.exe | `4313825a3ba634d113cc6ed3bc8ce735e3c19d360cecd985794787479469f91f` |
|
||||
| x64/conpty.dll | `feeef341d891643c62d30b6b07800bc70f0bc148f44cb8c3bee84aa557ae805a` |
|
||||
| x64/OpenConsole.exe | `3d66b23d0a71bb8eed2b77edc8b9df9bf54ce6c8fb74c863a30e760997f80586` |
|
||||
| x86/conpty.dll | `d145f621bf64a9da3b7395587ddef9831ca404805d8987ec8c9903d0c4603d93` |
|
||||
| x86/OpenConsole.exe | `e3e475547d57da0689dc9fc5e0101d10390e2a4719a6eb5dcad569f6cb33c1a3` |
|
||||
|
||||
Verification: `cargo test -p ide-core pty::`. `pty::checksums` checks the embedded files against the table above on every platform. The native PTY test launches a child
|
||||
console application and requires alternate-screen entry and exit to reach the
|
||||
reader; a system ConPTY that consumes them fails this check.
|
||||
Бінарний файл не відображається.
Бінарний файл не відображається.
Бінарний файл не відображається.
Бінарний файл не відображається.
Бінарний файл не відображається.
Бінарний файл не відображається.
@@ -25,6 +25,7 @@ pub mod project_dir;
|
||||
pub mod project_env;
|
||||
pub mod project_roots;
|
||||
pub mod proxy_settings;
|
||||
pub mod pty;
|
||||
pub mod real_path;
|
||||
pub mod remote_settings;
|
||||
pub mod settings;
|
||||
|
||||
@@ -0,0 +1,254 @@
|
||||
//! The PTY backend shared by terminals, Run consoles and debugger launchers.
|
||||
|
||||
pub fn native_pty_system() -> Box<dyn portable_pty::PtySystem + Send> {
|
||||
#[cfg(windows)]
|
||||
windows::initialize();
|
||||
portable_pty::native_pty_system()
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
mod windows {
|
||||
use std::fs;
|
||||
use std::io::{self, Write};
|
||||
use std::os::windows::ffi::OsStrExt;
|
||||
use std::path::Path;
|
||||
use std::sync::OnceLock;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use windows_sys::Win32::Foundation::FreeLibrary;
|
||||
use windows_sys::Win32::System::LibraryLoader::{
|
||||
GetProcAddress, LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR, LOAD_LIBRARY_SEARCH_SYSTEM32, LoadLibraryExW,
|
||||
};
|
||||
|
||||
const VERSION: &str = "1.25.260930003";
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
const RUNTIME: (&str, &[u8], &[u8]) = (
|
||||
"x64",
|
||||
include_bytes!("../resources/conpty/x64/conpty.dll"),
|
||||
include_bytes!("../resources/conpty/x64/OpenConsole.exe"),
|
||||
);
|
||||
#[cfg(target_arch = "aarch64")]
|
||||
const RUNTIME: (&str, &[u8], &[u8]) = (
|
||||
"arm64",
|
||||
include_bytes!("../resources/conpty/arm64/conpty.dll"),
|
||||
include_bytes!("../resources/conpty/arm64/OpenConsole.exe"),
|
||||
);
|
||||
#[cfg(target_arch = "x86")]
|
||||
const RUNTIME: (&str, &[u8], &[u8]) = (
|
||||
"x86",
|
||||
include_bytes!("../resources/conpty/x86/conpty.dll"),
|
||||
include_bytes!("../resources/conpty/x86/OpenConsole.exe"),
|
||||
);
|
||||
|
||||
pub(super) fn initialize() -> bool {
|
||||
static BUNDLED: OnceLock<bool> = OnceLock::new();
|
||||
*BUNDLED.get_or_init(|| {
|
||||
if !crate::platform::windows_build_number().is_some_and(|build| build >= 19041) {
|
||||
return false;
|
||||
}
|
||||
match load() {
|
||||
Ok(()) => true,
|
||||
Err(error) => {
|
||||
tracing::warn!(%error, "bundled ConPTY unavailable; using the system terminal backend");
|
||||
false
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn load() -> io::Result<()> {
|
||||
let cache = dirs::cache_dir().ok_or_else(|| io::Error::other("no user cache directory"))?;
|
||||
let directory = cache.join("OpenIDEA").join("conpty").join(VERSION).join(RUNTIME.0);
|
||||
fs::create_dir_all(&directory)?;
|
||||
install(&directory.join("LICENSE.txt"), include_bytes!("../resources/conpty/LICENSE"))?;
|
||||
install(&directory.join("OpenConsole.exe"), RUNTIME.2)?;
|
||||
let library = directory.join("conpty.dll");
|
||||
install(&library, RUNTIME.1)?;
|
||||
let wide: Vec<u16> = library.as_os_str().encode_wide().chain(Some(0)).collect();
|
||||
// portable-pty 0.9 opens conpty.dll by name. Preload our verified absolute path:
|
||||
// Windows reuses this module, without adding the project directory to DLL search.
|
||||
// SAFETY: the path is terminated and the module is retained for the process lifetime.
|
||||
let module = unsafe {
|
||||
LoadLibraryExW(
|
||||
wide.as_ptr(),
|
||||
std::ptr::null_mut(),
|
||||
LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_SYSTEM32,
|
||||
)
|
||||
};
|
||||
if module.is_null() {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
for name in [c"CreatePseudoConsole", c"ResizePseudoConsole", c"ClosePseudoConsole"] {
|
||||
// SAFETY: `module` is loaded and each name is a terminated export name.
|
||||
if unsafe { GetProcAddress(module, name.as_ptr().cast()) }.is_none() {
|
||||
// SAFETY: no PTY uses this rejected module yet; release our load reference.
|
||||
unsafe { FreeLibrary(module) };
|
||||
return Err(io::Error::other("bundled ConPTY lacks the portable-pty exports"));
|
||||
}
|
||||
}
|
||||
// Keep this reference for the process lifetime, including between PTY sessions.
|
||||
tracing::info!(path = %library.display(), version = VERSION, "loaded bundled ConPTY");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn install(path: &Path, data: &[u8]) -> io::Result<()> {
|
||||
if fs::read(path).is_ok_and(|existing| existing == data) {
|
||||
return Ok(());
|
||||
}
|
||||
static NEXT: AtomicU64 = AtomicU64::new(0);
|
||||
let pending =
|
||||
path.with_extension(format!("{}-{}.tmp", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
|
||||
let result = (|| {
|
||||
let mut file = fs::OpenOptions::new().write(true).create_new(true).open(&pending)?;
|
||||
file.write_all(data)?;
|
||||
file.sync_all()?;
|
||||
drop(file);
|
||||
match fs::rename(&pending, path) {
|
||||
Ok(()) => Ok(()),
|
||||
Err(_) if fs::read(path).is_ok_and(|existing| existing == data) => Ok(()),
|
||||
Err(error) => Err(error),
|
||||
}
|
||||
})();
|
||||
let _ = fs::remove_file(pending);
|
||||
result
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn installs_atomically_and_repairs_incomplete_files() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("conpty.dll");
|
||||
fs::write(&path, b"partial").unwrap();
|
||||
std::thread::scope(|scope| {
|
||||
for _ in 0..8 {
|
||||
let path = &path;
|
||||
scope.spawn(move || install(path, b"complete runtime").unwrap());
|
||||
}
|
||||
});
|
||||
assert_eq!(fs::read(&path).unwrap(), b"complete runtime");
|
||||
assert_eq!(fs::read_dir(dir.path()).unwrap().count(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn loads_the_bundled_backend() {
|
||||
assert!(initialize());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn conpty_output_child() {
|
||||
if std::env::var_os("OPENIDEA_CONPTY_TEST_CHILD").is_none() {
|
||||
return;
|
||||
}
|
||||
use windows_sys::Win32::System::Console::{
|
||||
ENABLE_VIRTUAL_TERMINAL_PROCESSING, GetConsoleMode, GetStdHandle, STD_OUTPUT_HANDLE, SetConsoleMode,
|
||||
};
|
||||
// SAFETY: the inherited console output handle and a local writable mode word.
|
||||
unsafe {
|
||||
let output = GetStdHandle(STD_OUTPUT_HANDLE);
|
||||
let mut mode = 0;
|
||||
assert_ne!(GetConsoleMode(output, &mut mode), 0);
|
||||
assert_ne!(SetConsoleMode(output, mode | ENABLE_VIRTUAL_TERMINAL_PROCESSING), 0);
|
||||
}
|
||||
std::io::stdout()
|
||||
.write_all(b"\x1b[?1049h\x1b[2J\x1b[HWorking (3m 19s)\x1b[1;1H\x1b[2KWorking (2m 59s)\x1b[?1049l\r\nVT_DONE\r\n")
|
||||
.unwrap();
|
||||
std::io::stdout().flush().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn conpty_preserves_alternate_screen_transitions() {
|
||||
use std::io::Read;
|
||||
use std::sync::mpsc;
|
||||
use std::time::{Duration, Instant};
|
||||
let pair = super::super::native_pty_system().openpty(portable_pty::PtySize::default()).unwrap();
|
||||
let mut reader = pair.master.try_clone_reader().unwrap();
|
||||
let mut writer = pair.master.take_writer().unwrap();
|
||||
let mut command = portable_pty::CommandBuilder::new(std::env::current_exe().unwrap());
|
||||
command.args(["--exact", "pty::windows::tests::conpty_output_child", "--nocapture"]);
|
||||
command.env("OPENIDEA_CONPTY_TEST_CHILD", "1");
|
||||
let mut child = pair.slave.spawn_command(command).unwrap();
|
||||
drop(pair.slave);
|
||||
let (tx, rx) = mpsc::channel();
|
||||
let reading = std::thread::spawn(move || {
|
||||
let mut bytes = [0; 4096];
|
||||
while let Ok(count) = reader.read(&mut bytes) {
|
||||
if count == 0 || tx.send(bytes[..count].to_vec()).is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
let deadline = Instant::now() + Duration::from_secs(10);
|
||||
let mut output = Vec::new();
|
||||
let mut cursor_replied = false;
|
||||
while Instant::now() < deadline {
|
||||
if let Ok(bytes) = rx.recv_timeout(Duration::from_millis(50)) {
|
||||
output.extend_from_slice(&bytes);
|
||||
if !cursor_replied && output.windows(4).any(|s| s == b"\x1b[6n") {
|
||||
writer.write_all(b"\x1b[1;1R").unwrap();
|
||||
cursor_replied = true;
|
||||
}
|
||||
if output.windows(7).any(|s| s == b"VT_DONE") {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
drop(writer);
|
||||
drop(pair.master);
|
||||
reading.join().unwrap();
|
||||
let output = String::from_utf8_lossy(&output);
|
||||
assert!(output.contains("\x1b[?1049h"), "alternate screen entry missing: {output:?}");
|
||||
assert!(output.contains("\x1b[?1049l"), "alternate screen exit missing: {output:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The embedded runtime is the pinned NuGet package's files (`resources/conpty/README.md`).
|
||||
#[cfg(test)]
|
||||
mod checksums {
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
const FILES: [(&str, &[u8], &str); 6] = [
|
||||
(
|
||||
"arm64/conpty.dll",
|
||||
include_bytes!("../resources/conpty/arm64/conpty.dll"),
|
||||
"151a02355227710c20c9f8f1eaf68ac4668aa09cdc921adc7ec661804d8eb1bf",
|
||||
),
|
||||
(
|
||||
"arm64/OpenConsole.exe",
|
||||
include_bytes!("../resources/conpty/arm64/OpenConsole.exe"),
|
||||
"4313825a3ba634d113cc6ed3bc8ce735e3c19d360cecd985794787479469f91f",
|
||||
),
|
||||
(
|
||||
"x64/conpty.dll",
|
||||
include_bytes!("../resources/conpty/x64/conpty.dll"),
|
||||
"feeef341d891643c62d30b6b07800bc70f0bc148f44cb8c3bee84aa557ae805a",
|
||||
),
|
||||
(
|
||||
"x64/OpenConsole.exe",
|
||||
include_bytes!("../resources/conpty/x64/OpenConsole.exe"),
|
||||
"3d66b23d0a71bb8eed2b77edc8b9df9bf54ce6c8fb74c863a30e760997f80586",
|
||||
),
|
||||
(
|
||||
"x86/conpty.dll",
|
||||
include_bytes!("../resources/conpty/x86/conpty.dll"),
|
||||
"d145f621bf64a9da3b7395587ddef9831ca404805d8987ec8c9903d0c4603d93",
|
||||
),
|
||||
(
|
||||
"x86/OpenConsole.exe",
|
||||
include_bytes!("../resources/conpty/x86/OpenConsole.exe"),
|
||||
"e3e475547d57da0689dc9fc5e0101d10390e2a4719a6eb5dcad569f6cb33c1a3",
|
||||
),
|
||||
];
|
||||
|
||||
#[test]
|
||||
fn embedded_runtime_matches_the_pinned_package() {
|
||||
for (name, bytes, expected) in FILES {
|
||||
let actual: String = Sha256::digest(bytes).iter().map(|b| format!("{b:02x}")).collect();
|
||||
assert_eq!(actual, expected, "{name}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -1061,7 +1061,8 @@ fn reap_on_exit(mut child: Box<dyn portable_pty::Child + Send + Sync>, exited: A
|
||||
/// starts a launcher that gives the program its terminal, and the program reads input only from
|
||||
/// a terminal), forwards its output to the console, and keeps the terminal for typed input.
|
||||
pub(crate) fn run_in_terminal(s: &Arc<Session>, args: &Value) -> Result<Value, String> {
|
||||
use portable_pty::{CommandBuilder, PtySize, native_pty_system};
|
||||
use ide_core::pty::native_pty_system;
|
||||
use portable_pty::{CommandBuilder, PtySize};
|
||||
let argv: Vec<String> = args
|
||||
.get("args")
|
||||
.and_then(Value::as_array)
|
||||
|
||||
@@ -658,8 +658,7 @@ impl DbManager {
|
||||
let config = self.sources()?.into_iter().find(|s| s.id == id).and_then(|s| s.ssh).map(|s| s.config);
|
||||
if let Some(c) = config.filter(|c| !c.trim().is_empty()) {
|
||||
let save = self.ssh.config(&c).map(|c| c.save_secret).unwrap_or(save);
|
||||
self.ssh.set_secret(&c, secret, save);
|
||||
return Ok(());
|
||||
return self.ssh.set_secret(&c, secret, save);
|
||||
}
|
||||
self.remember(self.saved_for(id), secrets::ssh_key(id), secret, save).await
|
||||
}
|
||||
@@ -760,7 +759,9 @@ impl DbManager {
|
||||
} else {
|
||||
if let Some(s) = ssh_secret {
|
||||
let save = self.ssh.config(config)?.save_secret;
|
||||
self.ssh.set_secret(config, Some(s), save);
|
||||
if let Err(e) = self.ssh.set_secret(config, Some(s), save) {
|
||||
tracing::warn!("could not save the SSH credential: {}", e.message);
|
||||
}
|
||||
}
|
||||
self.ssh.session(config).await?
|
||||
})
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
};
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
@@ -27,17 +27,21 @@ pub fn data_dir(identifier: &str) -> Result<PathBuf, String> {
|
||||
}
|
||||
|
||||
/// `$OPENIDEA_LOG_DIR/<identifier>` when set, else `~/Library/Logs/<identifier>` on macOS and
|
||||
/// `<local data>/<identifier>/logs` elsewhere (Tauri's `app_log_dir`).
|
||||
/// `logs` in the local data directory elsewhere (Tauri's `app_log_dir`), so a custom location
|
||||
/// from Settings › System Settings › Caches moves the logs too.
|
||||
pub fn log_dir(identifier: &str) -> Result<PathBuf, String> {
|
||||
let os = if cfg!(target_os = "macos") {
|
||||
dirs::home_dir().map(|home| home.join("Library/Logs").join(identifier))
|
||||
} else {
|
||||
dirs::data_local_dir().map(|dir| dir.join(identifier).join("logs"))
|
||||
};
|
||||
match std::env::var_os(LOG_ENV).filter(|v| !v.is_empty()) {
|
||||
Some(var) => resolve_env(LOG_ENV, Some(var), None, identifier),
|
||||
None => os.ok_or_else(|| "cannot find the log directory".into()),
|
||||
if let Some(var) = std::env::var_os(LOG_ENV).filter(|v| !v.is_empty()) {
|
||||
return resolve_env(LOG_ENV, Some(var), None, identifier);
|
||||
}
|
||||
if cfg!(target_os = "macos") {
|
||||
return dirs::home_dir()
|
||||
.map(|home| home.join("Library/Logs").join(identifier))
|
||||
.ok_or_else(|| "cannot find the log directory".into());
|
||||
}
|
||||
startup_local_data_dir(identifier)
|
||||
.or_else(|_| local_data_dir(identifier))
|
||||
.map(|dir| dir.join("logs"))
|
||||
.map_err(|_| "cannot find the log directory".into())
|
||||
}
|
||||
|
||||
/// The directory under `$<env>` when set (absolute, not created here), else under the OS directory.
|
||||
@@ -217,6 +221,74 @@ fn apply_custom_migration_in(path: &Path, local: &Path) {
|
||||
}
|
||||
}
|
||||
|
||||
/// WebView2's profile (localStorage, IndexedDB, cookies) inside the directory the windows
|
||||
/// are given, which on Windows is the local data directory.
|
||||
pub const WEBVIEW_PROFILE: &str = "EBWebView";
|
||||
|
||||
/// Browser caches in a WebView2 profile: rebuilt on demand, so not copied across volumes.
|
||||
const WEBVIEW_CACHES: [&str; 6] = ["Cache", "Code Cache", "GPUCache", "DawnCache", "GrShaderCache", "ShaderCache"];
|
||||
|
||||
/// Brings WebView2's profile into `local` before the first window opens: from a scheduled
|
||||
/// move's source (Settings › System Settings › Caches), else from the default directory, where
|
||||
/// windows kept it before they followed a custom location. Runs synchronously, as a window
|
||||
/// started meanwhile would create an empty profile; a profile already in `local` is never
|
||||
/// merged into or replaced, and a failed move leaves the old one in place.
|
||||
pub fn adopt_webview_profile(identifier: &str, local: &Path) {
|
||||
let scheduled = migration_path(identifier)
|
||||
.and_then(|path| fs::read(path).ok())
|
||||
.and_then(|bytes| serde_json::from_slice::<CustomMigration>(&bytes).ok())
|
||||
.filter(|job| job.to == local)
|
||||
.map(|job| job.from);
|
||||
adopt_webview_profile_from(scheduled.into_iter().chain(local_data_dir(identifier).ok()), local);
|
||||
}
|
||||
|
||||
fn adopt_webview_profile_from(sources: impl IntoIterator<Item = PathBuf>, local: &Path) {
|
||||
let target = local.join(WEBVIEW_PROFILE);
|
||||
if target.try_exists().unwrap_or(true) {
|
||||
return;
|
||||
}
|
||||
let Some(source) = sources
|
||||
.into_iter()
|
||||
.filter(|dir| dir != local)
|
||||
.map(|dir| dir.join(WEBVIEW_PROFILE))
|
||||
.find(|profile| fs::symlink_metadata(profile).is_ok_and(|m| m.is_dir()))
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let result = fs::create_dir_all(local).and_then(|()| match rename_missing(&source, &target) {
|
||||
Err(error) if rename_failure(&error) == RenameFailure::Copy => {
|
||||
let staging = local.join(format!(".migration-{}", uuid::Uuid::new_v4()));
|
||||
let copied = copy_profile(&source, &staging).and_then(|()| rename_missing(&staging, &target));
|
||||
if staging.exists() {
|
||||
let _ = remove_entry(&staging);
|
||||
}
|
||||
copied.and_then(|()| remove_entry(&source))
|
||||
}
|
||||
other => other,
|
||||
});
|
||||
match result {
|
||||
Ok(()) => tracing::info!(?source, ?target, "moved the WebView profile to the local data directory"),
|
||||
Err(error) => tracing::warn!(?source, ?target, %error, "cannot move the WebView profile; starting a new one"),
|
||||
}
|
||||
}
|
||||
|
||||
/// [`copy_tree`] without the profile's browser caches.
|
||||
fn copy_profile(source: &Path, target: &Path) -> io::Result<()> {
|
||||
let metadata = fs::symlink_metadata(source)?;
|
||||
if !metadata.is_dir() {
|
||||
return copy_tree(source, target);
|
||||
}
|
||||
fs::create_dir(target)?;
|
||||
for entry in fs::read_dir(source)? {
|
||||
let entry = entry?;
|
||||
if WEBVIEW_CACHES.iter().any(|name| entry.file_name() == *name) {
|
||||
continue;
|
||||
}
|
||||
copy_profile(&entry.path(), &target.join(entry.file_name()))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Entries of a local-data tree that move to a newly chosen directory.
|
||||
/// Non-relocatable tool installs (virtual environments with absolute interpreter
|
||||
/// paths) stay behind and are reinstalled on demand, as in `migrate_entries`;
|
||||
@@ -552,6 +624,46 @@ fn relative_wrapper(text: &str, source: &Path) -> String {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_webview_profile_moves_into_a_custom_local_directory_once() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let (default, custom) = (tmp.path().join("default"), tmp.path().join("custom"));
|
||||
let storage = default.join(WEBVIEW_PROFILE).join("Default/Local Storage");
|
||||
fs::create_dir_all(&storage).unwrap();
|
||||
fs::write(storage.join("leveldb"), "history").unwrap();
|
||||
adopt_webview_profile_from([default.clone()], &custom);
|
||||
let moved = custom.join(WEBVIEW_PROFILE).join("Default/Local Storage/leveldb");
|
||||
assert_eq!(fs::read_to_string(&moved).unwrap(), "history");
|
||||
assert!(!default.join(WEBVIEW_PROFILE).exists());
|
||||
// A profile already in place is never replaced by an older one.
|
||||
fs::create_dir_all(default.join(WEBVIEW_PROFILE)).unwrap();
|
||||
adopt_webview_profile_from([default.clone()], &custom);
|
||||
assert!(default.join(WEBVIEW_PROFILE).exists());
|
||||
assert_eq!(fs::read_to_string(&moved).unwrap(), "history");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_default_directory_keeps_its_own_profile() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let profile = tmp.path().join(WEBVIEW_PROFILE);
|
||||
fs::create_dir_all(&profile).unwrap();
|
||||
adopt_webview_profile_from([tmp.path().to_path_buf()], tmp.path());
|
||||
assert!(profile.is_dir());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_copied_profile_leaves_the_browser_caches_behind() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let source = tmp.path().join("source");
|
||||
fs::create_dir_all(source.join("Default/Cache/Cache_Data")).unwrap();
|
||||
fs::create_dir_all(source.join("Default/IndexedDB")).unwrap();
|
||||
fs::write(source.join("Default/Cache/Cache_Data/f_1"), "x").unwrap();
|
||||
fs::write(source.join("Default/IndexedDB/db"), "kept").unwrap();
|
||||
copy_profile(&source, &tmp.path().join("copy")).unwrap();
|
||||
assert_eq!(fs::read_to_string(tmp.path().join("copy/Default/IndexedDB/db")).unwrap(), "kept");
|
||||
assert!(!tmp.path().join("copy/Default/Cache").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn config_data_and_log_dirs_follow_the_os_unless_their_variable_is_set() {
|
||||
let os = Some(PathBuf::from("/os"));
|
||||
|
||||
@@ -190,6 +190,8 @@ impl Host {
|
||||
let sink_for: SinkFactory = diagnostics_store::recording_sink_factory(diagnostics.clone(), sink_for);
|
||||
let global_settings = SettingsStore::load(&config_dir, None);
|
||||
let ssh = Arc::new(ide_ssh::SshManager::new(data_dir.join("ssh-passwords.json")));
|
||||
let migration = ssh.clone();
|
||||
runtime.spawn_blocking(move || migration.start_password_migration());
|
||||
ssh.set_configs(global_settings.effective().ssh.configs);
|
||||
let host = Self {
|
||||
plugin_host: RwLock::default(),
|
||||
@@ -399,6 +401,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 +531,7 @@ impl Host {
|
||||
for project in self.projects() {
|
||||
project.flutter.kill();
|
||||
project.devtools.kill();
|
||||
project.widget_preview.kill();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -570,6 +574,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();
|
||||
|
||||
@@ -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);
|
||||
@@ -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,
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
@@ -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.",
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -4,8 +4,10 @@
|
||||
//! given belong to the server's [`ide_ssh::SshManager`], not the desktop's.
|
||||
use crate::Host;
|
||||
use ide_command::command;
|
||||
use ide_core::IdeResult;
|
||||
use ide_core::event::NotifyLevel;
|
||||
use ide_core::remote_settings::SshConfiguration;
|
||||
use ide_core::{IdeError, IdeEvent, IdeResult};
|
||||
use ide_ssh::secrets::LegacyPasswordAction;
|
||||
|
||||
/// Test Connection: connects with `config` as edited (not necessarily saved).
|
||||
#[command(trust = always)]
|
||||
@@ -15,8 +17,23 @@ pub async fn ssh_test(host: &Host, config: SshConfiguration, secret: Option<Stri
|
||||
|
||||
/// Remembers the password / passphrase of configuration `id` (`None` forgets it).
|
||||
#[command(trust = always)]
|
||||
pub fn ssh_set_secret(host: &Host, id: String, secret: Option<String>, save: bool) {
|
||||
host.ssh.set_secret(&id, secret, save);
|
||||
pub fn ssh_set_secret(host: &Host, window: &str, id: String, secret: Option<String>, save: bool) {
|
||||
if let Err(e) = host.ssh.set_secret(&id, secret, save) {
|
||||
host.window_sink(window).emit(IdeEvent::Notify {
|
||||
level: NotifyLevel::Warning,
|
||||
title: "Could not save credential".into(),
|
||||
body: Some(e.message),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// `Some` means legacy credentials remain in plaintext on this host.
|
||||
#[command(trust = always)]
|
||||
pub async fn ssh_legacy_passwords(host: &Host, action: LegacyPasswordAction) -> IdeResult<Option<String>> {
|
||||
let ssh = host.ssh.clone();
|
||||
tokio::task::spawn_blocking(move || ssh.resolve_legacy_passwords(action))
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()))?
|
||||
}
|
||||
|
||||
/// Whether a password is saved under `key` (an FTP deployment server's).
|
||||
@@ -52,6 +69,7 @@ ide_command::domain!(
|
||||
ssh:
|
||||
ssh_connected,
|
||||
ssh_disconnect,
|
||||
ssh_legacy_passwords,
|
||||
ssh_needs_secret,
|
||||
ssh_password_saved,
|
||||
ssh_set_secret,
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -2,6 +2,26 @@ mod common;
|
||||
|
||||
use ide_host::{Host, HostConfig, ops};
|
||||
|
||||
#[tokio::test]
|
||||
async fn startup_moves_legacy_ssh_credentials_without_opening_a_project_or_connection() {
|
||||
use ide_ssh::secrets::testing::{files_containing, use_memory_store};
|
||||
|
||||
use_memory_store();
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let config = common::host_config(tmp.path());
|
||||
std::fs::create_dir_all(&config.data_dir).unwrap();
|
||||
std::fs::write(config.data_dir.join("ssh-passwords.json"), r#"{"box":"legacy-fixture"}"#).unwrap();
|
||||
let host = Host::new(config);
|
||||
tokio::time::timeout(std::time::Duration::from_secs(5), async {
|
||||
while !files_containing(tmp.path(), "legacy-fixture").is_empty() {
|
||||
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("startup migration");
|
||||
assert_eq!(host.ssh.password("box").as_deref(), Some("legacy-fixture"));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn split_storage_keeps_user_history_and_uses_local_tools_and_caches() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -136,7 +136,8 @@ async fn ssh_server(home: &Path, server_home: &Path, project: &Path) -> Arc<ide_
|
||||
save_secret: true,
|
||||
..Default::default()
|
||||
}]);
|
||||
ssh.set_secret("local-test", Some("secret".into()), true);
|
||||
ide_ssh::secrets::testing::use_memory_store();
|
||||
ssh.set_secret("local-test", Some("secret".into()), true).unwrap();
|
||||
assert!(ssh.session("local-test").await.is_err(), "unknown host key first");
|
||||
ssh.trust_host("local-test").await.unwrap();
|
||||
ssh.session("local-test").await.unwrap()
|
||||
|
||||
@@ -10,6 +10,30 @@ use std::path::Path;
|
||||
use std::sync::{Arc, Mutex, mpsc};
|
||||
use std::time::Duration;
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_failed_credential_save_warns_the_window_but_keeps_the_session_password() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let config = common::host_config(tmp.path());
|
||||
std::fs::create_dir_all(config.data_dir.join("ssh-passwords.json")).unwrap();
|
||||
let (tx, rx) = mpsc::channel();
|
||||
let host = Host::new(HostConfig {
|
||||
sink_for: Box::new(move |_| {
|
||||
let tx = tx.clone();
|
||||
Arc::new(move |e| tx.send(e).unwrap())
|
||||
}),
|
||||
..config
|
||||
});
|
||||
ide_host::ops::ssh::ssh_set_secret(&host, "main", "box".into(), Some("test-value".into()), true);
|
||||
let warning = rx.try_iter().find_map(|e| match e {
|
||||
IdeEvent::Notify { level: ide_core::event::NotifyLevel::Warning, body, .. } => body,
|
||||
_ => None,
|
||||
});
|
||||
let warning = warning.expect("the window should be told saving failed");
|
||||
assert!(warning.contains("session only"));
|
||||
assert!(!warning.contains("test-value"));
|
||||
assert_eq!(host.ssh.password("box").as_deref(), Some("test-value"));
|
||||
}
|
||||
|
||||
fn read_until(rx: &mpsc::Receiver<String>, needle: &str) -> String {
|
||||
let mut all = String::new();
|
||||
while !all.contains(needle) {
|
||||
@@ -38,7 +62,8 @@ async fn host_with_ssh_box(tmp: &Path, exec: ide_ssh::testing::ExecFn) -> (Arc<H
|
||||
save_secret: true,
|
||||
..Default::default()
|
||||
}]);
|
||||
ssh.set_secret("box", Some("secret".into()), true);
|
||||
ide_ssh::secrets::testing::use_memory_store();
|
||||
ssh.set_secret("box", Some("secret".into()), true).unwrap();
|
||||
assert!(ssh.session("box").await.is_err(), "unknown host key first");
|
||||
ssh.trust_host("box").await.unwrap();
|
||||
|
||||
|
||||
@@ -80,7 +80,7 @@ async fn welcome_window_browses_selected_ssh_host_without_executing_commands() {
|
||||
auth: SshAuth::Password,
|
||||
..Default::default()
|
||||
}]);
|
||||
ssh.set_secret("selected-host", Some("secret".into()), false);
|
||||
ssh.set_secret("selected-host", Some("secret".into()), false).unwrap();
|
||||
assert!(ssh.session("selected-host").await.is_err());
|
||||
ssh.trust_host("selected-host").await.unwrap();
|
||||
|
||||
|
||||
@@ -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}")))?
|
||||
};
|
||||
|
||||
@@ -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")
|
||||
});
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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),
|
||||
}
|
||||
@@ -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())]);
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
|
||||
@@ -3,9 +3,10 @@
|
||||
|
||||
use crate::utf8::OutputDecoder;
|
||||
use crate::{OutputChunk, RunAttach, RunConfig, RunInfo};
|
||||
use ide_core::pty::native_pty_system;
|
||||
use ide_core::{IdeError, IdeEvent, IdeResult, RunId, SharedSink};
|
||||
use parking_lot::Mutex;
|
||||
use portable_pty::{CommandBuilder, MasterPty, PtySize, native_pty_system};
|
||||
use portable_pty::{CommandBuilder, MasterPty, PtySize};
|
||||
use std::collections::{BTreeMap, VecDeque};
|
||||
use std::io::{Read, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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()));
|
||||
}
|
||||
}
|
||||
@@ -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.
|
||||
|
||||
@@ -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,7 +1,7 @@
|
||||
//! App-wide SSH connections, one per SSH configuration, shared by every
|
||||
//! feature that works on that host (deployment, run targets, data sources).
|
||||
|
||||
use crate::secrets::SecretFile;
|
||||
use crate::secrets::{LegacyPasswordAction, SecretFile};
|
||||
use crate::session::{ConnectError, Session, UnknownHostKey};
|
||||
use crate::target::{SshFiles, SshTarget};
|
||||
use ide_core::remote_settings::{SshAuth, SshConfiguration};
|
||||
@@ -14,6 +14,7 @@ use std::sync::Arc;
|
||||
pub struct SshManager {
|
||||
files: SshFiles,
|
||||
saved: SecretFile,
|
||||
startup_migration: std::sync::Once,
|
||||
/// Secrets entered this session (not saved, or not yet), by configuration id.
|
||||
entered: Mutex<HashMap<String, String>>,
|
||||
configs: RwLock<Vec<SshConfiguration>>,
|
||||
@@ -34,7 +35,8 @@ impl SshManager {
|
||||
pub fn with_files(secrets: PathBuf, files: SshFiles) -> Self {
|
||||
Self {
|
||||
files,
|
||||
saved: SecretFile::new(secrets),
|
||||
saved: SecretFile::ssh_passwords(secrets),
|
||||
startup_migration: std::sync::Once::new(),
|
||||
entered: Mutex::default(),
|
||||
configs: RwLock::default(),
|
||||
sessions: Mutex::default(),
|
||||
@@ -47,6 +49,19 @@ impl SshManager {
|
||||
&self.files
|
||||
}
|
||||
|
||||
pub fn start_password_migration(&self) {
|
||||
self.startup_migration.call_once(|| match self.saved.resolve_legacy(LegacyPasswordAction::Retry) {
|
||||
Ok(None) => {}
|
||||
Ok(Some(why)) => tracing::warn!("ssh-passwords.json still contains legacy plaintext credentials: {why}"),
|
||||
Err(e) => tracing::warn!("could not check ssh-passwords.json: {}", e.message),
|
||||
});
|
||||
}
|
||||
|
||||
pub fn resolve_legacy_passwords(&self, action: LegacyPasswordAction) -> IdeResult<Option<String>> {
|
||||
self.start_password_migration();
|
||||
self.saved.resolve_legacy(action)
|
||||
}
|
||||
|
||||
/// Replaces the configurations (Settings › SSH Configurations); sessions of
|
||||
/// changed or removed ones are closed, secrets of removed ones forgotten.
|
||||
pub fn set_configs(&self, configs: Vec<SshConfiguration>) {
|
||||
@@ -86,7 +101,7 @@ impl SshManager {
|
||||
|
||||
/// Remembers the password / passphrase of configuration `id` for the session,
|
||||
/// and in the saved passwords with `save` (`None` forgets it).
|
||||
pub fn set_secret(&self, id: &str, secret: Option<String>, save: bool) {
|
||||
pub fn set_secret(&self, id: &str, secret: Option<String>, save: bool) -> IdeResult<()> {
|
||||
match &secret {
|
||||
Some(s) => {
|
||||
self.entered.lock().insert(id.to_owned(), s.clone());
|
||||
@@ -96,12 +111,13 @@ impl SshManager {
|
||||
}
|
||||
}
|
||||
match (secret, save) {
|
||||
(Some(s), true) => {
|
||||
if let Err(e) = self.saved.set(id, &s) {
|
||||
tracing::warn!("could not save the SSH password: {}", e.message);
|
||||
}
|
||||
(Some(s), true) => self.saved.set(id, &s).map_err(|e| {
|
||||
IdeError::unavailable(format!("The credential was kept for this session only. {}", e.message))
|
||||
}),
|
||||
_ => {
|
||||
self.saved.delete(id);
|
||||
Ok(())
|
||||
}
|
||||
_ => self.saved.delete(id),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -25,6 +25,14 @@ static LOCK: Mutex<()> = Mutex::new(());
|
||||
/// Reads the secrets of an older version's file, by key (`None`: not that format).
|
||||
pub type Legacy = fn(serde_json::Value) -> Option<BTreeMap<String, String>>;
|
||||
|
||||
#[derive(Clone, Copy, Deserialize, Serialize, specta::Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum LegacyPasswordAction {
|
||||
Check,
|
||||
Retry,
|
||||
RemovePlaintext,
|
||||
}
|
||||
|
||||
/// Where the secrets are kept: the default credential store, or a stand-in in tests.
|
||||
pub trait Vault: Send + Sync {
|
||||
fn available(&self) -> bool;
|
||||
@@ -77,6 +85,7 @@ pub struct SecretFile {
|
||||
path: PathBuf,
|
||||
legacy: Legacy,
|
||||
vault: Arc<dyn Vault>,
|
||||
keep_legacy_until_moved: bool,
|
||||
}
|
||||
|
||||
/// The file's contents. `id` keeps the credentials of different data directories
|
||||
@@ -87,6 +96,11 @@ struct Index {
|
||||
keys: BTreeSet<String>,
|
||||
}
|
||||
|
||||
enum Stored {
|
||||
Index(Index),
|
||||
Legacy(BTreeMap<String, String>),
|
||||
}
|
||||
|
||||
enum Contents {
|
||||
Index(Index),
|
||||
/// An older version's file that could not be moved, and why.
|
||||
@@ -122,12 +136,17 @@ impl SecretFile {
|
||||
Self::with_legacy(path, |v| serde_json::from_value(v).ok())
|
||||
}
|
||||
|
||||
/// For the startup migration with a user-visible choice to retry or discard.
|
||||
pub(crate) fn ssh_passwords(path: PathBuf) -> Self {
|
||||
Self { keep_legacy_until_moved: true, ..Self::new(path) }
|
||||
}
|
||||
|
||||
pub fn with_legacy(path: PathBuf, legacy: Legacy) -> Self {
|
||||
Self::with_vault(path, legacy, Arc::new(DefaultStore))
|
||||
}
|
||||
|
||||
pub fn with_vault(path: PathBuf, legacy: Legacy, vault: Arc<dyn Vault>) -> Self {
|
||||
Self { path, legacy, vault }
|
||||
Self { path, legacy, vault, keep_legacy_until_moved: false }
|
||||
}
|
||||
|
||||
pub fn get(&self, key: &str) -> Option<String> {
|
||||
@@ -222,23 +241,75 @@ impl SecretFile {
|
||||
})
|
||||
}
|
||||
|
||||
fn load(&self) -> Contents {
|
||||
let value = match std::fs::read(&self.path) {
|
||||
Err(_) => return Contents::Index(Index { id: new_id(), keys: BTreeSet::new() }),
|
||||
Ok(bytes) => match serde_json::from_slice::<serde_json::Value>(&bytes) {
|
||||
Ok(v) => v,
|
||||
Err(e) => return self.set_aside(&e.to_string()),
|
||||
},
|
||||
fn read(&self) -> std::io::Result<Stored> {
|
||||
use std::io::{Error, ErrorKind};
|
||||
let bytes = match std::fs::read(&self.path) {
|
||||
Err(e) if e.kind() == ErrorKind::NotFound => {
|
||||
return Ok(Stored::Index(Index { id: new_id(), keys: BTreeSet::new() }));
|
||||
}
|
||||
other => other?,
|
||||
};
|
||||
let value = serde_json::from_slice::<serde_json::Value>(&bytes)
|
||||
.map_err(|_| Error::new(ErrorKind::InvalidData, "invalid JSON"))?;
|
||||
if let Ok(index) = serde_json::from_value::<Index>(value.clone()) {
|
||||
return Contents::Index(index);
|
||||
return Ok(Stored::Index(index));
|
||||
}
|
||||
match (self.legacy)(value) {
|
||||
Some(old) => self.migrate(old),
|
||||
None => self.set_aside("unknown format"),
|
||||
(self.legacy)(value).map(Stored::Legacy).ok_or_else(|| Error::new(ErrorKind::InvalidData, "unknown format"))
|
||||
}
|
||||
|
||||
fn load(&self) -> Contents {
|
||||
match self.read() {
|
||||
Ok(Stored::Index(index)) => Contents::Index(index),
|
||||
Ok(Stored::Legacy(old)) => self.migrate(old),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::InvalidData => self.set_aside(&e.to_string()),
|
||||
Err(e) => Contents::Plaintext(BTreeMap::new(), format!("{}: {e}", self.path.display())),
|
||||
}
|
||||
}
|
||||
|
||||
/// `Some` means plaintext remains. Never overwrite an index that another window
|
||||
/// already migrated; an unreadable file is set aside, as on any other access.
|
||||
pub(crate) fn resolve_legacy(&self, action: LegacyPasswordAction) -> IdeResult<Option<String>> {
|
||||
off_runtime(|| {
|
||||
let _g = LOCK.lock();
|
||||
let old = match self.read() {
|
||||
Ok(Stored::Legacy(old)) => old,
|
||||
Ok(Stored::Index(_)) => return Ok(None),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::InvalidData => {
|
||||
return match self.set_aside(&e.to_string()) {
|
||||
Contents::Index(_) => Ok(None),
|
||||
Contents::Plaintext(_, why) => Err(unavailable(&why)),
|
||||
};
|
||||
}
|
||||
Err(e) => return Err(unavailable(&format!("{}: {e}", self.path.display()))),
|
||||
};
|
||||
if matches!(action, LegacyPasswordAction::Check) && !old.is_empty() {
|
||||
return Ok(Some("Migration is incomplete.".into()));
|
||||
}
|
||||
if matches!(action, LegacyPasswordAction::RemovePlaintext) || old.is_empty() {
|
||||
// A partial move may already have secured some keys. Preserve their
|
||||
// namespace without needing the vault to be unlocked to remove plaintext.
|
||||
let pending = self.pending_path();
|
||||
let index = match std::fs::read_to_string(&pending) {
|
||||
Ok(id) if !id.trim().is_empty() => Index { id: id.trim().into(), keys: old.into_keys().collect() },
|
||||
Ok(_) => return Err(unavailable("empty migration id")),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Index { id: new_id(), keys: BTreeSet::new() },
|
||||
Err(e) => return Err(unavailable(&format!("{}: {e}", pending.display()))),
|
||||
};
|
||||
self.write(&index)?;
|
||||
if let Err(e) = std::fs::remove_file(&pending)
|
||||
&& e.kind() != std::io::ErrorKind::NotFound
|
||||
{
|
||||
tracing::warn!("saved passwords: could not remove {}: {e}", pending.display());
|
||||
}
|
||||
return Ok(None);
|
||||
}
|
||||
Ok(match self.migrate(old) {
|
||||
Contents::Index(_) => None,
|
||||
Contents::Plaintext(_, why) => Some(why),
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// An unreadable file is renamed rather than overwritten (it may index
|
||||
/// credentials, or hold secrets); the store starts over.
|
||||
fn set_aside(&self, why: &str) -> Contents {
|
||||
@@ -262,8 +333,8 @@ impl SecretFile {
|
||||
}
|
||||
|
||||
/// Moves an older version's secrets to the credential store, key by key; a secret
|
||||
/// the store refuses for good (too long, say) is forgotten, and the user is asked
|
||||
/// for it again. The old file is replaced only when everything else was moved.
|
||||
/// the store refuses for good (too long, say) is forgotten unless the caller
|
||||
/// offers explicit recovery. The old file is replaced only when everything else was moved.
|
||||
/// Until then the id waits in `<file>.migrating`, so a retry after a failure or a
|
||||
/// crash overwrites the same credentials instead of copying them again.
|
||||
fn migrate(&self, old: BTreeMap<String, String>) -> Contents {
|
||||
@@ -287,7 +358,7 @@ impl SecretFile {
|
||||
Ok(()) => {
|
||||
index.keys.insert(key.clone());
|
||||
}
|
||||
Err(e @ (StoreError::TooLong(..) | StoreError::Invalid(..))) => {
|
||||
Err(e @ (StoreError::TooLong(..) | StoreError::Invalid(..))) if !self.keep_legacy_until_moved => {
|
||||
tracing::warn!("saved passwords: {key} does not fit the credential store and is forgotten: {e}");
|
||||
}
|
||||
Err(e) => {
|
||||
@@ -425,6 +496,82 @@ mod tests {
|
||||
|
||||
const OLD: &str = r#"{"https://a.example": "me\nold-a", "https://b.example": "me\nold-b"}"#;
|
||||
|
||||
#[test]
|
||||
fn a_pending_plaintext_migration_can_be_retried_or_explicitly_discarded() {
|
||||
use LegacyPasswordAction::{Check, RemovePlaintext, Retry};
|
||||
for discard in [false, true] {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let path = tmp.path().join("ssh-passwords.json");
|
||||
let vault = Arc::new(FakeVault::default());
|
||||
let file = with_fake(&path, &vault);
|
||||
assert!(file.resolve_legacy(Check).unwrap().is_none());
|
||||
assert!(!path.exists());
|
||||
std::fs::write(&path, OLD).unwrap();
|
||||
vault.fail("https://b.example", platform);
|
||||
assert!(file.resolve_legacy(Retry).unwrap().is_some());
|
||||
assert!(file.resolve_legacy(Check).unwrap().is_some());
|
||||
assert_eq!(std::fs::read_to_string(&path).unwrap(), OLD);
|
||||
if discard {
|
||||
assert!(file.resolve_legacy(RemovePlaintext).unwrap().is_none());
|
||||
}
|
||||
vault.heal();
|
||||
assert!(file.resolve_legacy(Retry).unwrap().is_none());
|
||||
// A stale action from another window cannot erase a migrated index.
|
||||
assert!(file.resolve_legacy(RemovePlaintext).unwrap().is_none());
|
||||
assert_eq!(files_containing(tmp.path(), "old-"), Vec::<PathBuf>::new());
|
||||
assert_eq!(file.get("https://a.example").as_deref(), Some("me\nold-a"));
|
||||
assert_eq!(file.get("https://b.example").as_deref(), (!discard).then_some("me\nold-b"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn removing_plaintext_needs_no_vault_and_sets_an_unknown_format_aside() {
|
||||
use LegacyPasswordAction::{RemovePlaintext, Retry};
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let path = tmp.path().join("ssh-passwords.json");
|
||||
let vault = Arc::new(FakeVault { absent: true, ..Default::default() });
|
||||
let file = with_fake(&path, &vault);
|
||||
std::fs::write(&path, OLD).unwrap();
|
||||
assert!(file.resolve_legacy(Retry).unwrap().is_some());
|
||||
assert!(file.resolve_legacy(RemovePlaintext).unwrap().is_none());
|
||||
assert!(files_containing(tmp.path(), "old-").is_empty());
|
||||
assert!(file.keys().is_empty());
|
||||
std::fs::write(&path, "unknown-format").unwrap();
|
||||
assert!(file.resolve_legacy(RemovePlaintext).unwrap().is_none());
|
||||
let aside = files_containing(tmp.path(), "unknown-format");
|
||||
assert_eq!(aside.len(), 1);
|
||||
assert_ne!(aside[0], path);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ssh_keeps_the_only_copy_until_the_user_can_choose_what_to_do() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let path = tmp.path().join("ssh-passwords.json");
|
||||
let vault = Arc::new(FakeVault::default());
|
||||
let file = SecretFile { vault: vault.clone(), ..SecretFile::ssh_passwords(path.clone()) };
|
||||
vault.fail("box", || StoreError::TooLong("password".into(), 2560));
|
||||
std::fs::write(&path, r#"{"box":"legacy-value"}"#).unwrap();
|
||||
assert!(file.resolve_legacy(LegacyPasswordAction::Retry).unwrap().is_some());
|
||||
assert_eq!(file.get("box").as_deref(), Some("legacy-value"));
|
||||
assert_eq!(files_containing(tmp.path(), "legacy-value"), std::slice::from_ref(&path));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_malformed_ssh_file_is_set_aside_instead_of_blocking_new_saves() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let path = tmp.path().join("ssh-passwords.json");
|
||||
let vault = Arc::new(FakeVault::default());
|
||||
let file = SecretFile { vault: vault.clone(), ..SecretFile::ssh_passwords(path.clone()) };
|
||||
std::fs::write(&path, "{ malformed").unwrap();
|
||||
assert!(file.resolve_legacy(LegacyPasswordAction::Check).unwrap().is_none());
|
||||
let aside = files_containing(tmp.path(), "{ malformed");
|
||||
assert_eq!(aside.len(), 1);
|
||||
assert_ne!(aside[0], path);
|
||||
file.set("box", "new-value").unwrap();
|
||||
assert_eq!(file.get("box").as_deref(), Some("new-value"));
|
||||
assert!(files_containing(tmp.path(), "new-value").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn saved_secrets_never_reach_disk() {
|
||||
use_memory_store();
|
||||
|
||||
@@ -4,10 +4,11 @@
|
||||
mod integration;
|
||||
mod scrollback;
|
||||
|
||||
use ide_core::pty::native_pty_system;
|
||||
use ide_core::utf8::Utf8Decoder;
|
||||
use ide_core::{IdeError, IdeEvent, IdeResult, SharedSink, TerminalId};
|
||||
use parking_lot::{Condvar, Mutex};
|
||||
use portable_pty::{ChildKiller, CommandBuilder, MasterPty, PtySize, native_pty_system};
|
||||
use portable_pty::{ChildKiller, CommandBuilder, MasterPty, PtySize};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
|
||||
@@ -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**.
|
||||
|
||||
|
||||
@@ -46,6 +46,11 @@ through the app-wide SSH configurations.
|
||||
Saved passwords and passphrases go to the macOS Keychain, Windows Credential Manager or the Secret Service on Linux,
|
||||
never to a settings file. The **+**, **−** and copy buttons above the list add, remove and duplicate configurations.
|
||||
|
||||
Older versions stored saved credentials in plaintext in `ssh-passwords.json`. On startup, OpenIDEA moves them into
|
||||
the OS credential store. If the file still contains passwords, unlock the store and choose **Retry migration**, or
|
||||
choose **Remove plaintext copy** and re-enter any credentials that were not migrated. New credentials that cannot
|
||||
be saved are kept only for the session. Migration does not change old backups: rotate any exposed password.
|
||||
|
||||
### `~/.ssh/config` support
|
||||
|
||||
OpenIDEA has its own SSH client and reads `~/.ssh/config` itself. It understands `Host`, `Match`, `Include`,
|
||||
|
||||
@@ -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**。
|
||||
|
||||
|
||||
@@ -38,6 +38,10 @@ OpenIDEA 通过 SSH 连接;在 Windows 上也可以直接连入 WSL 发行版
|
||||
保存的密码和密码短语存放在 macOS 钥匙串、Windows 凭据管理器或 Linux 的 Secret Service 中,不会写进设置文件。列表上方的
|
||||
**+**、**−** 和复制按钮用于添加、移除和复制配置。
|
||||
|
||||
旧版本会在 `ssh-passwords.json` 中明文保存凭据。OpenIDEA 会在启动时将它们迁移到系统凭据库。
|
||||
如果文件中仍有密码,可以解锁凭据库后选择**重试迁移**,也可以选择**移除明文副本**,并在下次使用时重新输入未迁移的凭据。
|
||||
无法保存的新凭据仅在当前会话中有效。迁移不会更改旧备份;如果备份中的密码已泄露,请更换密码。
|
||||
|
||||
### `~/.ssh/config` 支持
|
||||
|
||||
OpenIDEA 自带 SSH 客户端,自行读取 `~/.ssh/config`,支持 `Host`、`Match`、`Include`、`HostName`、`User`、`Port`、
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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: "",
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
@@ -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();
|
||||
|
||||
@@ -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[] =>
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
@@ -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");
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
//! The OS clipboard's file list, so the project view and Explorer exchange files.
|
||||
//! The OS clipboard's file list, so the project view and the file manager exchange files.
|
||||
|
||||
use ide_command::desktop_command;
|
||||
#[cfg(any(target_os = "macos", target_os = "linux"))]
|
||||
@@ -83,7 +83,21 @@ pub async fn clipboard_text(app: AppHandle) -> IdeResult<Option<String>> {
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn clipboard_file_list(app: AppHandle) -> IdeResult<Vec<String>> {
|
||||
with_clipboard(app, || Ok(ide_clipboard::files()?.iter().map(|p| slash(p)).collect())).await
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
let (tx, rx) = tokio::sync::oneshot::channel();
|
||||
app.run_on_main_thread(move || {
|
||||
ide_clipboard::request_files(move |paths| {
|
||||
let _ = tx.send(paths);
|
||||
})
|
||||
})
|
||||
.map_err(|error| IdeError::internal(format!("Cannot dispatch clipboard access to the main thread: {error}")))?;
|
||||
Ok(rx.await.unwrap_or_default().iter().map(|p| slash(p)).collect())
|
||||
}
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
{
|
||||
with_clipboard(app, || Ok(ide_clipboard::files()?.iter().map(|p| slash(p)).collect())).await
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the clipboard holds files: cheap, for the Paste item's enabled state.
|
||||
|
||||
@@ -275,6 +275,12 @@ pub fn run() {
|
||||
})
|
||||
.on_window_event(|window, event| match event {
|
||||
tauri::WindowEvent::CloseRequested { .. } => {
|
||||
// A dead web engine never answers the page's close handler: close the window here.
|
||||
#[cfg(windows)]
|
||||
if windows_webview_recovery::browser_failed(window.app_handle()) {
|
||||
let _ = window.destroy();
|
||||
return;
|
||||
}
|
||||
#[cfg(target_os = "linux")]
|
||||
linux_window_state::save_before_close(window.app_handle());
|
||||
if let Some(w) = window.try_state::<WindowsState>() {
|
||||
|
||||
@@ -13,6 +13,10 @@
|
||||
//! inside the window, so with several monitors its candidate window opens on the wrong
|
||||
//! one. Through the compositor (Mutter hands text-input to Fcitx's IBus frontend) it
|
||||
//! follows the caret, so GNOME Wayland sessions drop `GTK_IM_MODULE=fcitx`.
|
||||
//!
|
||||
//! WSLg's Wayland compositor has no usable GPU path for WebKitGTK (Mesa reports an
|
||||
//! incompatible driver and the window stays blank); its X server works, so WSL uses X11
|
||||
//! unless `GDK_BACKEND` is set.
|
||||
|
||||
const DISABLE_DMABUF: &str = "WEBKIT_DISABLE_DMABUF_RENDERER";
|
||||
const DISABLE_EXPLICIT_SYNC: &str = "__NV_DISABLE_EXPLICIT_SYNC";
|
||||
@@ -21,6 +25,10 @@ const IM_MODULE: &str = "GTK_IM_MODULE";
|
||||
/// Run before other threads start (`set_var`).
|
||||
#[cfg(target_os = "linux")]
|
||||
pub fn configure() {
|
||||
if use_x11_on_wsl(|k| std::env::var(k).ok()) {
|
||||
tracing::info!("WSLg: GDK_BACKEND=x11");
|
||||
unsafe { std::env::set_var("GDK_BACKEND", "x11") };
|
||||
}
|
||||
let nvidia = ["/proc/driver/nvidia/version", "/sys/module/nvidia"].iter().any(|p| std::path::Path::new(p).exists());
|
||||
if disable_explicit_sync(|k| std::env::var(k).ok(), nvidia) {
|
||||
tracing::info!("Wayland with the NVIDIA driver: {DISABLE_EXPLICIT_SYNC}=1");
|
||||
@@ -43,6 +51,12 @@ fn drop_fcitx_module(var: impl Fn(&str) -> Option<String>) -> bool {
|
||||
gnome && var(IM_MODULE).is_some_and(|m| matches!(m.trim(), "fcitx" | "fcitx5")) && gdk_wayland(&var)
|
||||
}
|
||||
|
||||
/// Under WSL with WSLg's X server available, unless the user chose a GDK backend.
|
||||
fn use_x11_on_wsl(var: impl Fn(&str) -> Option<String>) -> bool {
|
||||
let set = |k: &str| var(k).is_some_and(|v| !v.is_empty());
|
||||
(set("WSL_DISTRO_NAME") || set("WSL_INTEROP")) && set("DISPLAY") && !set("GDK_BACKEND")
|
||||
}
|
||||
|
||||
/// GTK 3's IBus input method module (`ibus-gtk3`), wherever the distribution keeps it.
|
||||
#[cfg(target_os = "linux")]
|
||||
fn gtk_ibus_module_installed() -> bool {
|
||||
@@ -163,6 +177,16 @@ mod tests {
|
||||
assert!(!drop_fcitx_module(env(&[gnome[0], gnome[1], (IM_MODULE, "ibus")])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wsl_uses_x11_unless_a_backend_is_chosen() {
|
||||
let wslg = [("WSL_DISTRO_NAME", "Ubuntu-24.04"), ("WAYLAND_DISPLAY", "wayland-0"), ("DISPLAY", ":0")];
|
||||
assert!(use_x11_on_wsl(env(&wslg)));
|
||||
assert!(use_x11_on_wsl(env(&[("WSL_INTEROP", "/run/WSL/1_interop"), ("DISPLAY", ":0")])));
|
||||
assert!(!use_x11_on_wsl(env(&[wslg[0], wslg[1], wslg[2], ("GDK_BACKEND", "wayland")])));
|
||||
assert!(!use_x11_on_wsl(env(&[wslg[0], wslg[1]])), "no X server");
|
||||
assert!(!use_x11_on_wsl(env(&[wslg[1], wslg[2]])), "not WSL");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_the_users_input_method_module() {
|
||||
let vars = [("WAYLAND_DISPLAY", "wayland-0"), ("XMODIFIERS", "@im=ibus"), (IM_MODULE, "wayland")];
|
||||
|
||||
@@ -76,6 +76,10 @@ impl AppState {
|
||||
// Caches: the previous tree moves first, so a pending invalidation still
|
||||
// wipes what was just moved.
|
||||
let identifier = app.config().identifier.clone();
|
||||
// Windows: the WebView2 profile follows the local data directory too, and must be in
|
||||
// place before the first window opens (the scheduled move below runs before them too).
|
||||
#[cfg(windows)]
|
||||
ide_host::data_dirs::adopt_webview_profile(&identifier, &local_data_dir);
|
||||
ide_host::data_dirs::apply_custom_migration(&identifier, &local_data_dir);
|
||||
// File › Invalidate Caches… requested at the last run.
|
||||
let removed = ide_workspace::caches::apply_pending(&data_dir, &local_data_dir);
|
||||
|
||||
@@ -850,8 +850,18 @@ fn build_project_window(app: &AppHandle, mut config: WindowConfig) -> IdeResult<
|
||||
}
|
||||
#[cfg(target_os = "linux")]
|
||||
let show_after_build = crate::linux_window_state::prepare(app, &mut config);
|
||||
// Windows opens a project window at the configured size (window-state restores only the
|
||||
// maximized flag there), which Restore Down returns to.
|
||||
#[cfg(windows)]
|
||||
if let Ok(Some(monitor)) = app.primary_monitor() {
|
||||
let area = monitor.work_area().size.to_logical::<f64>(monitor.scale_factor());
|
||||
let min = (config.min_width.unwrap_or(0.0), config.min_height.unwrap_or(0.0));
|
||||
let (size, min) = fit_new_window((config.width, config.height), min, (area.width, area.height));
|
||||
(config.width, config.height) = size;
|
||||
(config.min_width, config.min_height) = (Some(min.0), Some(min.1));
|
||||
}
|
||||
let window = WebviewWindowBuilder::from_config(app, &config)
|
||||
.and_then(|b| dev_font_preferences(b).on_new_window(open_popup_in_browser).build())
|
||||
.and_then(|b| dev_font_preferences(webview_profile(app, b)).on_new_window(open_popup_in_browser).build())
|
||||
.map_err(|e| IdeError::internal(format!("cannot create window: {e}")))?;
|
||||
#[cfg(target_os = "linux")]
|
||||
decorate_csd(&window);
|
||||
@@ -1689,7 +1699,7 @@ pub fn open_auxiliary_window(app: &AppHandle, caller: &WebviewWindow, aux: AuxWi
|
||||
// display's Space, so macOS keeps it too.
|
||||
#[cfg(target_os = "linux")]
|
||||
let builder = builder.and_then(|b| b.parent(&parent));
|
||||
let window = builder.and_then(|b| dev_font_preferences(b).build()).map_err(|e| {
|
||||
let window = builder.and_then(|b| dev_font_preferences(webview_profile(app, b)).build()).map_err(|e| {
|
||||
windows.forget(&label);
|
||||
IdeError::internal(format!("cannot create {} window: {e}", aux.kind.name()))
|
||||
})?;
|
||||
@@ -2104,6 +2114,18 @@ fn fit_over_parent(
|
||||
rx.recv_timeout(FIT_ON_MAIN_TIMEOUT).map_err(|_| tauri::Error::FailedToReceiveMessage)
|
||||
}
|
||||
|
||||
/// A new window's size and minimum size (logical pixels) shrunk to fit `area`, the work area of
|
||||
/// the monitor it opens on: the default 1440×900 is taller than a 1920×1080 laptop screen at
|
||||
/// 150 % scaling once the taskbar is taken off.
|
||||
#[cfg_attr(not(windows), allow(dead_code))]
|
||||
fn fit_new_window(size: (f64, f64), min: (f64, f64), area: (f64, f64)) -> ((f64, f64), (f64, f64)) {
|
||||
if area.0 <= 0.0 || area.1 <= 0.0 {
|
||||
return (size, min);
|
||||
}
|
||||
let size = (size.0.min(area.0), size.1.min(area.1));
|
||||
(size, (min.0.min(size.0), min.1.min(size.1)))
|
||||
}
|
||||
|
||||
/// Centres the settings window over its owner, inside the owner's monitor work area. The window
|
||||
/// may still be on another display with a different scale, so its size is converted with its own
|
||||
/// scale and its position is given in physical pixels.
|
||||
@@ -2196,6 +2218,23 @@ fn open_popup_in_browser<R: tauri::Runtime>(
|
||||
tauri::webview::NewWindowResponse::Deny
|
||||
}
|
||||
|
||||
/// On Windows every window keeps WebView2's profile (localStorage, IndexedDB) in the local
|
||||
/// data directory, so a custom location from Settings › System Settings › Caches holds it too;
|
||||
/// Tauri would always use the default one. All windows share it: one WebView2 browser process
|
||||
/// serves a single profile folder.
|
||||
fn webview_profile<'a>(
|
||||
app: &AppHandle,
|
||||
builder: WebviewWindowBuilder<'a, tauri::Wry, AppHandle>,
|
||||
) -> WebviewWindowBuilder<'a, tauri::Wry, AppHandle> {
|
||||
#[cfg(windows)]
|
||||
if let Some(state) = app.try_state::<AppState>() {
|
||||
return builder.data_directory(state.host.local_data_dir.clone());
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
let _ = app;
|
||||
builder
|
||||
}
|
||||
|
||||
/// Reproduce WKWebView's user-font restriction before WKWebView creation. The
|
||||
/// private selector and environment override are absent from release builds.
|
||||
#[cfg(all(debug_assertions, target_os = "macos"))]
|
||||
@@ -2926,6 +2965,19 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_new_window_fits_the_work_area() {
|
||||
// 1920×1080 at 150 % with a 48-pixel taskbar (#5750).
|
||||
let area = (1280.0, 1032.0 / 1.5);
|
||||
assert_eq!(fit_new_window((1440.0, 900.0), (400.0, 500.0), area), ((1280.0, 688.0), (400.0, 500.0)));
|
||||
// A minimum larger than the screen gives way too.
|
||||
assert_eq!(fit_new_window((1440.0, 900.0), (400.0, 800.0), area).1, (400.0, 688.0));
|
||||
// A large screen keeps the configured size; an unknown work area changes nothing.
|
||||
let big = ((1440.0, 900.0), (400.0, 500.0));
|
||||
assert_eq!(fit_new_window(big.0, big.1, (2560.0, 1400.0)), big);
|
||||
assert_eq!(fit_new_window(big.0, big.1, (0.0, 0.0)), big);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn settings_bounds_fit_current_work_area() {
|
||||
for (parent, size, work, expected) in [
|
||||
|
||||
@@ -1,29 +1,45 @@
|
||||
//! Native recovery for a WebView2 browser crash. The webview can no longer show its own UI.
|
||||
//! Native recovery for a WebView2 browser crash. The webview can no longer show its own UI:
|
||||
//! not the prompt, not the title bar's close button (the window draws its own), and it never
|
||||
//! answers a close request. So the prompt is a native message box on its own thread, and the
|
||||
//! windows close without asking the page.
|
||||
|
||||
use parking_lot::Mutex;
|
||||
use std::collections::HashSet;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::time::Duration;
|
||||
use tauri::{AppHandle, Manager, Webview, Wry, plugin};
|
||||
use tauri_plugin_dialog::{DialogExt, MessageDialogButtons, MessageDialogKind};
|
||||
use webview2_com::{
|
||||
Microsoft::Web::WebView2::Win32::{
|
||||
COREWEBVIEW2_PROCESS_FAILED_KIND, COREWEBVIEW2_PROCESS_FAILED_KIND_BROWSER_PROCESS_EXITED, ICoreWebView2,
|
||||
ICoreWebView2ProcessFailedEventArgs2,
|
||||
COREWEBVIEW2_PROCESS_FAILED_KIND, COREWEBVIEW2_PROCESS_FAILED_KIND_BROWSER_PROCESS_EXITED,
|
||||
COREWEBVIEW2_PROCESS_FAILED_REASON, ICoreWebView2, ICoreWebView2ProcessFailedEventArgs2,
|
||||
},
|
||||
ProcessFailedEventHandler,
|
||||
};
|
||||
use windows::core::Interface;
|
||||
|
||||
/// How long Restart waits for the event loop to restart the app before restarting the process
|
||||
/// itself (a main thread stuck in a call to the dead browser never handles the request).
|
||||
const RESTART_GRACE: Duration = Duration::from_secs(10);
|
||||
|
||||
#[derive(Default)]
|
||||
struct Recovery {
|
||||
announced_browsers: Mutex<HashSet<u32>>,
|
||||
/// A browser process exited: the pages can't answer close requests any more.
|
||||
failed: AtomicBool,
|
||||
}
|
||||
|
||||
impl Recovery {
|
||||
fn announce(&self, browser_pid: u32) -> bool {
|
||||
self.failed.store(true, Ordering::SeqCst);
|
||||
self.announced_browsers.lock().insert(browser_pid)
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the web engine has failed, so a window must close without asking its page.
|
||||
pub fn browser_failed(app: &AppHandle) -> bool {
|
||||
app.try_state::<Recovery>().is_some_and(|r| r.failed.load(Ordering::SeqCst))
|
||||
}
|
||||
|
||||
pub fn init() -> plugin::TauriPlugin<Wry> {
|
||||
plugin::Builder::new("webview-recovery")
|
||||
.setup(|app, _| {
|
||||
@@ -62,21 +78,38 @@ fn listen(core: &ICoreWebView2, app: AppHandle, label: String) -> windows::core:
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
let exit_code = args.cast::<ICoreWebView2ProcessFailedEventArgs2>().ok().and_then(|args| {
|
||||
let details = args.cast::<ICoreWebView2ProcessFailedEventArgs2>().ok();
|
||||
// SAFETY (all three): queried from the live callback arguments on this thread.
|
||||
let exit_code = details.as_ref().and_then(|args| {
|
||||
let mut code = 0;
|
||||
// SAFETY: queried from the live callback arguments on this thread.
|
||||
unsafe { args.ExitCode(&mut code) }.ok().map(|()| code)
|
||||
});
|
||||
tracing::error!(window = %label, browser_pid, ?exit_code, "WebView2 browser process exited unexpectedly");
|
||||
// Dispatch from a worker so Wry queues the prompt instead of running it
|
||||
// inline inside WebView2's STA callback.
|
||||
let app = app.clone();
|
||||
tauri::async_runtime::spawn_blocking(move || {
|
||||
let handle = app.clone();
|
||||
if let Err(error) = app.run_on_main_thread(move || show_recovery(handle)) {
|
||||
tracing::error!(%error, "cannot show WebView2 recovery prompt");
|
||||
}
|
||||
let reason = details.as_ref().and_then(|args| {
|
||||
let mut reason = COREWEBVIEW2_PROCESS_FAILED_REASON::default();
|
||||
unsafe { args.Reason(&mut reason) }.ok().map(|()| reason.0)
|
||||
});
|
||||
let description = details.as_ref().and_then(|args| {
|
||||
let mut description = Default::default();
|
||||
unsafe { args.ProcessDescription(&mut description) }.ok().map(|()| webview2_com::take_pwstr(description))
|
||||
});
|
||||
tracing::error!(
|
||||
window = %label,
|
||||
browser_pid,
|
||||
?exit_code,
|
||||
?reason,
|
||||
?description,
|
||||
"WebView2 browser process exited unexpectedly"
|
||||
);
|
||||
// Not through the main thread: it may be stuck in a call to the dead browser, and the
|
||||
// prompt must not run inline inside WebView2's STA callback either.
|
||||
let app = app.clone();
|
||||
if let Err(error) = std::thread::Builder::new().name("webview-recovery".into()).spawn(move || {
|
||||
if ask_restart() {
|
||||
restart(&app);
|
||||
}
|
||||
}) {
|
||||
tracing::error!(%error, "cannot show WebView2 recovery prompt");
|
||||
}
|
||||
Ok(())
|
||||
}));
|
||||
let mut token = 0;
|
||||
@@ -84,26 +117,37 @@ fn listen(core: &ICoreWebView2, app: AppHandle, label: String) -> windows::core:
|
||||
unsafe { core.add_ProcessFailed(&handler, &mut token) }
|
||||
}
|
||||
|
||||
fn show_recovery(app: AppHandle) {
|
||||
let mut dialog = app
|
||||
.dialog()
|
||||
.message(
|
||||
"The Windows web engine stopped unexpectedly. Restart OpenIDEA to recover the interface. \
|
||||
This restarts all OpenIDEA windows. Unsaved edits may be lost.",
|
||||
/// A native message box, on top of every window: true for Restart (OK).
|
||||
fn ask_restart() -> bool {
|
||||
use windows_sys::Win32::UI::WindowsAndMessaging::{
|
||||
IDOK, MB_ICONERROR, MB_OKCANCEL, MB_SETFOREGROUND, MB_TOPMOST, MessageBoxW,
|
||||
};
|
||||
let wide = |s: &str| s.encode_utf16().chain(Some(0)).collect::<Vec<u16>>();
|
||||
let text = wide(
|
||||
"The Windows web engine stopped unexpectedly, so OpenIDEA's windows can no longer respond.\n\n\
|
||||
Choose OK to restart OpenIDEA and recover the interface. This restarts all OpenIDEA windows; \
|
||||
unsaved edits may be lost.",
|
||||
);
|
||||
let title = wide("OpenIDEA");
|
||||
// SAFETY: both strings are NUL-terminated and outlive the call; no owner window.
|
||||
let answer = unsafe {
|
||||
MessageBoxW(
|
||||
std::ptr::null_mut(),
|
||||
text.as_ptr(),
|
||||
title.as_ptr(),
|
||||
MB_OKCANCEL | MB_ICONERROR | MB_TOPMOST | MB_SETFOREGROUND,
|
||||
)
|
||||
.title("OpenIDEA")
|
||||
.kind(MessageDialogKind::Error)
|
||||
.buttons(MessageDialogButtons::OkCancelCustom("Restart OpenIDEA".into(), "Cancel".into()));
|
||||
if let Some(window) = crate::windows::target_window(&app).filter(|w| w.is_visible().unwrap_or(false)) {
|
||||
dialog = dialog.parent(&window);
|
||||
}
|
||||
dialog.show(move |restart| {
|
||||
if restart {
|
||||
// The normal quit waits for a response from each webview. The failed browser
|
||||
// cannot answer, so restart through Tauri's native exit path.
|
||||
app.request_restart();
|
||||
}
|
||||
});
|
||||
};
|
||||
answer == IDOK
|
||||
}
|
||||
|
||||
fn restart(app: &AppHandle) {
|
||||
// The normal quit waits for a response from each webview. The failed browser cannot
|
||||
// answer, so restart through Tauri's native exit path.
|
||||
app.request_restart();
|
||||
std::thread::sleep(RESTART_GRACE);
|
||||
tracing::error!("the event loop did not restart OpenIDEA; restarting the process");
|
||||
tauri::process::restart(&app.env());
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -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
|
||||
@@ -646,6 +650,7 @@ spring_route_sources trusted desktop bin
|
||||
ssh_askpass_answer always desktop bindings sync
|
||||
ssh_connected always project_host bindings sync
|
||||
ssh_disconnect always project_host bindings sync
|
||||
ssh_legacy_passwords always project_host bindings async
|
||||
ssh_needs_secret always project_host bindings sync
|
||||
ssh_open_terminal always desktop bindings async
|
||||
ssh_password_saved always project_host bindings sync
|
||||
|
||||
+88
-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<{
|
||||
/**
|
||||
@@ -1849,6 +1878,8 @@ export const commands = {
|
||||
/** Ids of the configurations with an open connection. */
|
||||
sshConnected: () => __TAURI_INVOKE<string[]>("ssh_connected"),
|
||||
sshDisconnect: (id: string) => __TAURI_INVOKE<void>("ssh_disconnect", { id }),
|
||||
/** `Some` means legacy credentials remain in plaintext on this host. */
|
||||
sshLegacyPasswords: (action: LegacyPasswordAction) => typedError<string | null, IdeError>(__TAURI_INVOKE("ssh_legacy_passwords", { action })),
|
||||
/** Whether connecting with configuration `id` needs a password first. */
|
||||
sshNeedsSecret: (id: string) => typedError<boolean, IdeError>(__TAURI_INVOKE("ssh_needs_secret", { id })),
|
||||
/**
|
||||
@@ -3620,6 +3651,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 +6475,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 +7311,24 @@ export type FlutterEmulator = {
|
||||
platformType: string | null,
|
||||
};
|
||||
|
||||
/** The Flutter plugin's "Flutter SDK path". */
|
||||
export type FlutterSettings = {
|
||||
/**
|
||||
* Flutter SDK root (holding `bin/flutter`); its `flutter` and Dart replace the ones on
|
||||
* `PATH`. Empty = `PATH`.
|
||||
*/
|
||||
sdk?: string,
|
||||
};
|
||||
|
||||
/** What `flutter --version --machine` reports of an SDK. */
|
||||
export type FlutterVersion = {
|
||||
/** SDK root (not part of Flutter's answer). */
|
||||
root?: string,
|
||||
frameworkVersion?: string,
|
||||
channel?: string | null,
|
||||
dartSdkVersion?: string | null,
|
||||
};
|
||||
|
||||
export type FocusedEditor = {
|
||||
path: IpcPath,
|
||||
/** Zero-based lines and UTF-16 columns, end exclusive. */
|
||||
@@ -9109,6 +9191,7 @@ export type LanguagesSettings = {
|
||||
markdown?: MarkdownSettings,
|
||||
arduino?: ArduinoSettings,
|
||||
zig?: ZigSettings,
|
||||
flutter?: FlutterSettings,
|
||||
};
|
||||
|
||||
export type LargeCommitFile = {
|
||||
@@ -9202,6 +9285,8 @@ export type Launch_Serialize = {
|
||||
editor: EditorLaunch_Serialize | null,
|
||||
};
|
||||
|
||||
export type LegacyPasswordAction = "check" | "retry" | "removePlaintext";
|
||||
|
||||
/** One SDK or library with its source folders (`< Python 3.12 (.venv) >`). */
|
||||
export type LibraryGroup = {
|
||||
/** Display name, e.g. `Python 3.12 (.venv)`. */
|
||||
@@ -12595,7 +12680,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
|
||||
|
||||
@@ -90,6 +90,8 @@
|
||||
color: var(--fg-subtle);
|
||||
font-size: var(--fs-small);
|
||||
font-variant-numeric: tabular-nums;
|
||||
min-width: 3ch;
|
||||
text-align: end;
|
||||
}
|
||||
/* Pin and Archive appear beside the age while the pointer is on the row. */
|
||||
.rowActions {
|
||||
@@ -107,6 +109,20 @@
|
||||
.row:has(.rowActions:focus-within) .age {
|
||||
margin-left: 0;
|
||||
}
|
||||
/* The status mark sits in a fixed slot just before the age, so marks form a column. */
|
||||
.status {
|
||||
flex: none;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 16px;
|
||||
margin-left: auto;
|
||||
}
|
||||
.row:has(.status) .age,
|
||||
.row:hover .status,
|
||||
.row:has(.rowActions:focus-within) .status {
|
||||
margin-left: 0;
|
||||
}
|
||||
.rowAction {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
|
||||
@@ -422,8 +422,6 @@ export function AgentsView() {
|
||||
n.task.title
|
||||
)}
|
||||
</span>
|
||||
{/* Ready tasks say so by their group; the others show what they're doing. */}
|
||||
{n.task.status !== "ready" && <TaskStatusIcon status={n.task.status} />}
|
||||
{unread.has(n.task.id) && (
|
||||
<span className={styles.unreadDot} role="img" aria-label={tx("Unread")} title={tx("Unread")} />
|
||||
)}
|
||||
@@ -442,6 +440,13 @@ export function AgentsView() {
|
||||
{canArchive(n.task) &&
|
||||
rowButton("Archive", "archive", () => void executeAction("agents.archiveTasks", [n.task.id]))}
|
||||
</span>
|
||||
{/* Ready tasks say so by their group; the others show what they're doing, in a column
|
||||
beside the age so the marks line up whatever the title length. */}
|
||||
{n.task.status !== "ready" && (
|
||||
<span className={styles.status}>
|
||||
<TaskStatusIcon status={n.task.status} />
|
||||
</span>
|
||||
)}
|
||||
<span className={styles.age}>{age(n.task.updatedMs ?? 0)}</span>
|
||||
</span>
|
||||
);
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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}
|
||||
|
||||
@@ -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,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -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 />
|
||||
@@ -325,15 +526,19 @@ function ModelPicker({
|
||||
!unavailable && (
|
||||
<button
|
||||
type="button"
|
||||
className={clsx(styles.chip, styles.modelDetail)}
|
||||
className={styles.chip}
|
||||
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>
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
|
||||
@@ -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" }));
|
||||
|
||||
@@ -257,7 +257,6 @@
|
||||
background: none;
|
||||
color: var(--link);
|
||||
font-size: var(--fs-small);
|
||||
cursor: pointer;
|
||||
}
|
||||
.codeMore:hover {
|
||||
background: var(--bg-hover);
|
||||
|
||||
@@ -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 var(--space-1-5);
|
||||
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: var(--space-1-5);
|
||||
}
|
||||
.meterGroup {
|
||||
display: inline-flex;
|
||||
flex: 0 1 auto;
|
||||
align-items: center;
|
||||
min-width: 0;
|
||||
height: 22px;
|
||||
gap: var(--space-1-5);
|
||||
}
|
||||
.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 {
|
||||
@@ -1862,6 +1916,18 @@
|
||||
flex: none;
|
||||
color: var(--fg-muted);
|
||||
}
|
||||
.toolDir {
|
||||
flex: none;
|
||||
max-width: 140px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
padding: 0 4px;
|
||||
border-radius: var(--radius-small);
|
||||
background: var(--bg-hover);
|
||||
color: var(--fg-muted);
|
||||
font-size: var(--agent-fs-small, var(--fs-small));
|
||||
}
|
||||
.toolPath {
|
||||
flex: none;
|
||||
max-width: 180px;
|
||||
@@ -1937,8 +2003,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);
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -72,7 +72,6 @@
|
||||
color: var(--link);
|
||||
font: inherit;
|
||||
font-size: var(--fs-small);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.resetBtn:hover {
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -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}
|
||||
|
||||
@@ -17,7 +17,7 @@ import {
|
||||
type TurnRow,
|
||||
} from "./conversationRows";
|
||||
import { Fold } from "./Folds";
|
||||
import { samePropsExcept, shortTitle } from "./shared";
|
||||
import { commandTitle, samePropsExcept, shortTitle } from "./shared";
|
||||
import { ThoughtEntry, ToolEntry } from "./toolEntries";
|
||||
|
||||
/** "Edited 2 files · Read 4 files": what a run of work did; "Reasoning" when it only thought. */
|
||||
@@ -124,7 +124,9 @@ export const ProcessRun = memo(function ProcessRun({
|
||||
const live = [...tools].reverse().find(({ entry }) => liveTool(entry))?.entry;
|
||||
const last = row.entries.at(-1)!.entry;
|
||||
const current = live
|
||||
? shortTitle(task, live.title || live.kind)
|
||||
? live.kind === "execute"
|
||||
? commandTitle(task, live.title || live.kind).title
|
||||
: shortTitle(task, live.title || live.kind)
|
||||
: working && last.type === "thought"
|
||||
? tx("Thinking")
|
||||
: null;
|
||||
|
||||
@@ -376,7 +376,6 @@ export function SessionComposer({
|
||||
/>
|
||||
<SessionStatus
|
||||
task={task}
|
||||
entries={entries}
|
||||
head={head}
|
||||
changes={changes}
|
||||
commits={commits}
|
||||
|
||||
@@ -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>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -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]);
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { AgentTask } from "@/bindings";
|
||||
import { commandTitle } from "./shared";
|
||||
|
||||
const task = { cwd: "/repo/app" } as AgentTask;
|
||||
|
||||
describe("commandTitle", () => {
|
||||
it("drops a cd into the task's own folder", () => {
|
||||
expect(commandTitle(task, "cd /repo/app && git grep -n foo")).toEqual({ title: "git grep -n foo", dir: null });
|
||||
expect(commandTitle(task, "cd . ; ls")).toEqual({ title: "ls", dir: null });
|
||||
});
|
||||
|
||||
it("keeps another folder as the place the command ran", () => {
|
||||
expect(commandTitle(task, "cd /repo/app-icons && pnpm test")).toEqual({
|
||||
title: "pnpm test",
|
||||
dir: "/repo/app-icons",
|
||||
});
|
||||
expect(commandTitle(task, `cd "/repo/my app/" && ls`)).toEqual({ title: "ls", dir: "/repo/my app" });
|
||||
});
|
||||
|
||||
it("leaves commands without a leading cd, or that are only a cd, as they are", () => {
|
||||
expect(commandTitle(task, "git status && cd x && ls")).toEqual({ title: "git status && cd x && ls", dir: null });
|
||||
expect(commandTitle(task, "cd /tmp")).toEqual({ title: "cd /tmp", dir: null });
|
||||
expect(commandTitle(task, "cat /repo/app/src/a.ts")).toEqual({ title: "cat src/a.ts", dir: null });
|
||||
});
|
||||
});
|
||||
@@ -21,6 +21,21 @@ export type UserEntry = Extract<AgentEntry, { type: "user" }>;
|
||||
/** Agent-written titles with the task's own folder dropped from paths. */
|
||||
export const shortTitle = (task: AgentTask, title: string) => title.replaceAll(`${task.cwd}/`, "");
|
||||
|
||||
/** A leading `cd <dir> &&` (or `;`), with the directory quoted or bare. */
|
||||
const LEADING_CD = /^\s*cd\s+("[^"]+"|'[^']+'|\S+)\s*(?:&&|;)\s*/;
|
||||
|
||||
/**
|
||||
* A command's title without the `cd <dir> &&` agents put before every call, and the folder it
|
||||
* moved to when that is not the task's own: the command is what tells calls apart.
|
||||
*/
|
||||
export function commandTitle(task: AgentTask, title: string): { title: string; dir: string | null } {
|
||||
const match = LEADING_CD.exec(title);
|
||||
if (!match || match[0].length === title.length) return { title: shortTitle(task, title), dir: null };
|
||||
const dir = match[1]!.replace(/^(["'])(.*)\1$/, "$2").replace(/\/+$/, "");
|
||||
const rest = shortTitle(task, title.slice(match[0].length));
|
||||
return { title: rest, dir: dir === task.cwd || dir === "." ? null : dir };
|
||||
}
|
||||
|
||||
/**
|
||||
* `memo`'s comparison for props rebuilt with every render without changing: a prop named in
|
||||
* `by` is equal when its rule says so, any other prop when it is the same value.
|
||||
|
||||
@@ -16,7 +16,7 @@ import { cancelTask } from "../store";
|
||||
import { openChangeDiff } from "./ChangesTab";
|
||||
import { Fold } from "./Folds";
|
||||
import { liveTool } from "./conversationRows";
|
||||
import { shortTitle, useNow } from "./shared";
|
||||
import { commandTitle, shortTitle, useNow } from "./shared";
|
||||
|
||||
/** A location as the agent reported it: absolute on any platform, or relative to the task's folder. */
|
||||
const isAbsolute = (path: string) => path.startsWith("/") || /^[A-Za-z]:[\\/]/.test(path) || path.startsWith("\\\\");
|
||||
@@ -104,13 +104,22 @@ export const ToolEntry = memo(function ToolEntry({
|
||||
const live = liveTool(entry);
|
||||
const took = toolDuration(entry);
|
||||
const run = entry.kind === "execute" ? toolRun(entry) : null;
|
||||
const title = shortTitle(task, entry.title || entry.kind);
|
||||
// Commands lose the `cd <dir> &&` agents start them with; another folder shows as a tag.
|
||||
const { title, dir } =
|
||||
entry.kind === "execute"
|
||||
? commandTitle(task, entry.title || entry.kind)
|
||||
: { title: shortTitle(task, entry.title || entry.kind), dir: null };
|
||||
// A title that already names the file ("Read pom.xml") needs no second link to it.
|
||||
const links =
|
||||
entry.kind === "execute" ? [] : entry.locations.slice(0, 3).filter((path) => !title.includes(basename(path)));
|
||||
const head = (
|
||||
<>
|
||||
<Icon name={TOOL_ICONS[entry.kind] ?? "run"} size={14} className={styles.toolKindIcon} />
|
||||
{dir && (
|
||||
<span className={styles.toolDir} title={dir}>
|
||||
{basename(dir)}
|
||||
</span>
|
||||
)}
|
||||
<span className={styles.toolTitle} title={entry.title || entry.kind}>
|
||||
{title}
|
||||
</span>
|
||||
|
||||
@@ -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) => {
|
||||
|
||||
Loaded 100 of 202 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Заблокувати користувача