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

...
Автор SHA1 Повідомлення Дата
l0ng-ai b7b97f5b79 feat(agents): drop the leading cd from command titles
Agents start most shell commands with `cd <dir> &&`, which pushes the command itself out of the row. Command titles now show only the command; when it ran in a folder other than the task's, that folder appears as a small tag before it (full path on hover). The running-command hint in a grouped run's summary uses the same title.
2026-11-25 19:41:28 +08:00
l0ng-ai 735fe5dd30 feat(agents): show task status marks in a column beside the age (#5885)
The status mark (spinner, usage-limit clock, needs-input warning, ...) moves from right after the title to a fixed slot just before the age, so marks line up across rows regardless of title length. The age gets a minimum width so the column stays put between "now", "3m" and "12d".
2026-11-25 19:37:53 +08:00
l0ng-ai 0cfd17979b fix(agents): use spacing tokens for the session asset pill gaps (#5886)
The three gaps added to Session.module.css were raw 6px values, which the spacing-scale test rejects on main; they now use --space-1-5.
2026-11-25 19:30:01 +08:00
Deng Liuтаdengliu 41165bb8c0 fix(ssh): migrate legacy saved credentials at startup (#5786)
Host startup now moves legacy plaintext SSH passwords and key passphrases from
ssh-passwords.json into the OS credential store, without waiting for the next
SSH connection. When the move cannot finish, each workbench shows a sticky
warning with Retry migration and a confirmed Remove plaintext copy, which keeps
credentials already moved. A credential that cannot be saved stays for the
session and the requesting window is warned. An unreadable ssh-passwords.json
is set aside (renamed, never deleted) like the other secret files, so it no
longer blocks saving new credentials.

Co-authored-by: dengliu <[email protected]>
2026-11-25 19:27:09 +08:00
l0ng-ai 91264713e7 fix(linux): use X11 under WSLg (#5748)
Started from a WSL shell, GTK opens WSLg's Wayland display, where Mesa has no usable GPU driver for WebKitGTK and the window stays blank. Under WSL (WSL_DISTRO_NAME or WSL_INTEROP set) with an X display available, OpenIDEA now sets GDK_BACKEND=x11 before GTK starts; an explicit GDK_BACKEND is kept, and nothing changes outside WSL.

Fixes #5178
2026-11-25 18:54:43 +08:00
l0ng-ai 71a4f7cb63 fix(windows): keep the WebView profile and logs in a custom data location (#5838)
With a custom local data directory (Settings > System Settings > Caches), the WebView2 profile and the logs now move there too. On Windows both window builders pass the local data directory, so all windows share one profile; an existing EBWebView profile is moved before the first window opens (rename on the same volume, otherwise a copy that skips browser caches), and a profile already in place is never replaced. Outside macOS logs go to <local data>/logs; OPENIDEA_LOG_DIR still wins.

Fixes #5776
2026-11-25 18:53:59 +08:00
l0ng-aiтаenenH dfa632cf18 fix(terminal): bundle the ConPTY runtime on Windows (#5752)
Windows builds embed Microsoft's MIT-licensed ConPTY runtime (Microsoft.Windows.Console.ConPTY 1.25.260930003, pinned and unmodified, checksums tested), because the system ConPTY on Windows 10 19045 drops alternate-screen transitions and full-screen programs leave duplicate rows in scrollback. The runtime is written to a versioned user cache and conpty.dll is preloaded from that absolute path; terminals, Run consoles and debugger launchers share the PTY factory. Older builds or a load failure keep the system ConPTY.

Fixes #2692

Co-authored-by: enenH <[email protected]>
2026-11-25 18:53:47 +08:00
l0ng-ai f1425854fb fix(linux): paste files copied in the file manager into the project view (#5834)
On Linux the project view now reads and writes the clipboard's file list: text/uri-list (Dolphin, Nautilus and most file managers) with a fallback to GNOME's x-special/gnome-copied-files, through the GTK clipboard on X11 and Wayland. Copy offers both lists and the file names as text. file:// URIs are decoded as raw bytes; other hosts and schemes are skipped.

Fixes #5737
2026-11-25 18:53:34 +08:00
l0ng-ai 752650b971 fix(windows): show the WebView2 recovery prompt reliably and let windows close (#5705)
When the WebView2 browser process exits, the recovery prompt is now a native, topmost message box on its own thread with no owner window, so it no longer depends on the main thread or the failed window. Restart falls back to restarting the process itself if the event loop doesn't act within 10 s. Once the browser has failed, closing a window destroys it without asking the page. The log records the failure reason and process description.

Fixes #5369
2026-11-25 18:53:27 +08:00
l0ng-ai d33ee53c92 fix(windows): open a project window no larger than the screen's work area (#5817)
On Windows a project window opened at the configured 1440x900 and Restore Down returned to it, which ran under the taskbar on small or scaled screens (1920x1080 at 150%). The new window's size and minimum size are now shrunk to the primary monitor's work area.

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

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

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

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

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

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

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

Closes #5844

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

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

Fixes #5807
2026-11-25 17:39:26 +08:00
86 змінених файлів з 1764 додано та 197 видалено

No files matched your search

+2 -1
Переглянути файл
@@ -23,6 +23,7 @@ on:
- "Cargo.lock"
- "src/features/run/**"
- "src/features/debugger/**"
- "src/features/build/**"
- "src/features/build-tools/**"
- "src/platform/**"
- "src/workbench/**"
@@ -105,7 +106,7 @@ jobs:
# ide-lsp/dap/run/sdk/tools.
unused='^crates/(ide-agent|ide-analysis|ide-android|ide-cli|ide-clipboard|ide-coverage|ide-db|ide-docker|ide-fonts|ide-github|ide-http|ide-mcp|ide-notebook|ide-profiler|ide-scaffold|ide-spell|ide-ssh|ide-vcs|ide-web)/'
# The workflow's paths, less those handled per language below.
smoke='^(crates/|Cargo\.(toml|lock)$|src/features/(run|debugger|build-tools)/|src/platform/|src/workbench/|src/ui/|src/editor/(api|navigationProviders|relatedProviders|core/cm/(cornerInset|iconArea)|lsp/(availability|diagnostics|files|hint|lsp|positions))\.ts$|src/bindings\.ts$|src/styles/tokens\.css$|src/test/setup\.ts$|src-tauri/icons/128x128\.png$|smoke/|vite\.config\.ts$|tsconfig\.json$|package\.json$|pnpm-(lock|workspace)\.yaml$|patches/|\.github/workflows/language-smoke\.yml$|\.github/tool-versions\.env$)'
smoke='^(crates/|Cargo\.(toml|lock)$|src/features/(run|debugger|build|build-tools)/|src/platform/|src/workbench/|src/ui/|src/editor/(api|navigationProviders|relatedProviders|core/cm/(cornerInset|iconArea)|lsp/(availability|diagnostics|files|hint|lsp|positions))\.ts$|src/bindings\.ts$|src/styles/tokens\.css$|src/test/setup\.ts$|src-tauri/icons/128x128\.png$|smoke/|vite\.config\.ts$|tsconfig\.json$|package\.json$|pnpm-(lock|workspace)\.yaml$|patches/|\.github/workflows/language-smoke\.yml$|\.github/tool-versions\.env$)'
langs=""
while read -r f; do
case "$f" in
Створено
+4
Переглянути файл
@@ -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",
]
+7
Переглянути файл
@@ -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
+24 -13
Переглянути файл
@@ -95,6 +95,8 @@ const DEPENDENCY_TREE_JAR: &str =
/// The goals that read the effective POM into `effective` and the verbose dependency trees;
/// `repo` is the local repository the build resolves from. Both goals name their plugin by
/// coordinates: offline, a prefix resolves only from group metadata the repository may lack.
/// Offline without a cached 3.x `maven-help-plugin`, `effective-pom` is skipped so `mvn -o`
/// still resolves the dependency tree instead of failing to download the help plugin.
fn maven_sync_goals(effective: &Path, offline: bool, repo: Option<&Path>) -> Vec<String> {
let pinned = !offline || repo.is_some_and(|repo| repo.join(DEPENDENCY_TREE_JAR).is_file());
let tree = if pinned {
@@ -105,12 +107,16 @@ fn maven_sync_goals(effective: &Path, offline: bool, repo: Option<&Path>) -> Vec
|v| format!("org.apache.maven.plugins:maven-dependency-plugin:{v}:tree"),
)
};
vec![
maven::plugin_goal("help:effective-pom", repo),
format!("-Doutput={}", effective.to_string_lossy()),
tree,
"-Dverbose".into(),
]
let has_help =
!offline || repo.is_some_and(|repo| maven::newest_local_plugin(repo, "maven-help-plugin", 3).is_some());
let mut goals = Vec::with_capacity(4);
if has_help {
goals.push(maven::plugin_goal("help:effective-pom", repo));
goals.push(format!("-Doutput={}", effective.to_string_lossy()));
}
goals.push(tree);
goals.push("-Dverbose".into());
goals
}
/// The settings' Maven options for the sync runs: the thread count (`-T`, also
@@ -947,19 +953,24 @@ mod tests {
let help = "org.apache.maven.plugins:maven-help-plugin:3.5.1:effective-pom";
let online = maven_sync_goals(Path::new("e.xml"), false, Some(tmp.path()));
assert_eq!(online, [help, "-Doutput=e.xml", DEPENDENCY_TREE, "-Dverbose"]);
// Offline with neither plugin cached: the tree falls back to the project's own version.
// Offline with neither plugin cached: `effective-pom` is skipped so `mvn -o` does not fail
// on an uncached `maven-help-plugin`, and the tree falls back to the project's own version.
let offline = maven_sync_goals(Path::new("e.xml"), true, Some(tmp.path()));
assert_eq!(offline, [help, "-Doutput=e.xml", "dependency:tree", "-Dverbose"]);
// #5757: offline, plugins in the local repository are named by their coordinates, since
// the prefix needs group metadata a repository filled from a private mirror may lack.
for (artifact, version) in
[("maven-help-plugin", "3.4.0"), ("maven-help-plugin", "2.2"), ("maven-dependency-plugin", "3.6.1")]
{
assert_eq!(offline, ["dependency:tree", "-Dverbose"]);
// #5757 / #5844: offline, plugins in the local repository are named by their coordinates,
// since the prefix needs group metadata a repository filled from a private mirror may lack;
// a repository with `maven-dependency-plugin` but no 3.x `maven-help-plugin` runs only the tree.
for (artifact, version) in [("maven-help-plugin", "2.2"), ("maven-dependency-plugin", "3.6.1")] {
let jar =
tmp.path().join(format!("org/apache/maven/plugins/{artifact}/{version}/{artifact}-{version}.jar"));
std::fs::create_dir_all(jar.parent().unwrap()).unwrap();
std::fs::write(&jar, "").unwrap();
}
let offline = maven_sync_goals(Path::new("e.xml"), true, Some(tmp.path()));
assert_eq!(offline, ["org.apache.maven.plugins:maven-dependency-plugin:3.6.1:tree", "-Dverbose"]);
let help_jar = tmp.path().join("org/apache/maven/plugins/maven-help-plugin/3.4.0/maven-help-plugin-3.4.0.jar");
std::fs::create_dir_all(help_jar.parent().unwrap()).unwrap();
std::fs::write(&help_jar, "").unwrap();
// A version folder without its jar (only the POM was fetched) doesn't count.
std::fs::create_dir_all(tmp.path().join("org/apache/maven/plugins/maven-help-plugin/3.10.0")).unwrap();
let offline = maven_sync_goals(Path::new("e.xml"), true, Some(tmp.path()));
+1 -1
Переглянути файл
@@ -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
+151 -4
Переглянути файл
@@ -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: &gtk::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(&gtk::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(&gtk::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"]);
+5 -1
Переглянути файл
@@ -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"] }
+21
Переглянути файл
@@ -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.
+39
Переглянути файл
@@ -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.
Бінарний файл не відображається.
Бінарний файл не відображається.
Бінарний файл не відображається.
Бінарний файл не відображається.
Бінарний файл не відображається.
Бінарний файл не відображається.
+1
Переглянути файл
@@ -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;
+254
Переглянути файл
@@ -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}");
}
}
}
+2 -1
Переглянути файл
@@ -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)
+4 -3
Переглянути файл
@@ -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 -1
Переглянути файл
@@ -213,7 +213,7 @@ impl FlutterDaemon {
Self(Arc::new(Shared { root, sink, executable, state: Mutex::default() }))
}
#[cfg(test)]
#[cfg(all(test, unix))]
fn with_executable(root: PathBuf, sink: SharedSink, executable: Option<PathBuf>) -> Self {
Self::new(root, sink, Box::new(move || executable.clone()))
}
+1 -1
Переглянути файл
@@ -146,7 +146,7 @@ impl ToolServer {
self.0.changed.notify_all();
}
#[cfg(test)]
#[cfg(all(test, unix))]
pub(crate) fn is_stopped(&self) -> bool {
matches!(self.0.state.lock().status, Status::Stopped)
}
+121 -9
Переглянути файл
@@ -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"));
+2
Переглянути файл
@@ -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(),
+20 -6
Переглянути файл
@@ -391,8 +391,10 @@ async fn start_inner(
if config.command.is_empty() {
return Err(IdeError::invalid("run configuration has no command"));
}
let on_target = config.extras.target.as_deref().is_some_and(|t| !t.is_empty());
add_java_agents(&mut config, &on_output, !on_target);
// A JVM on a run target gets no plugin agents; a local one gets them once its JDK is resolved.
if config.extras.target.as_deref().is_some_and(|t| !t.is_empty()) {
add_java_agents(&mut config, &on_output, None);
}
// Settings › Run Targets: over SSH, or in a container.
if config.kind == "tomcat" && config.extras.target.as_deref().is_some_and(|t| !t.is_empty()) {
return Err(IdeError::invalid("Tomcat Local requires the local machine"));
@@ -483,6 +485,8 @@ async fn start_inner(
);
ide_sdk::go::apply_to_run(&mut config, &settings.languages.go.build_tags);
}
let run_dir = project.root.join(config.cwd.as_deref().unwrap_or(Path::new("")));
add_java_agents(&mut config, &on_output, Some(&run_dir));
if config.command == ide_sdk::godot::COMMAND {
return Err(IdeError::unavailable(ide_sdk::godot::NOT_FOUND));
}
@@ -555,14 +559,24 @@ async fn start_inner(
/// Plugins' Java agents (`[[contributes.javaAgents]]`, granted `java.agent`) for the JVM of an
/// Application, Spring Boot or JAR Application configuration started on this machine. A JVM on a
/// run target gets none; the console says so, and why an approved agent was left out.
fn add_java_agents(config: &mut RunConfig, on_output: &Emit<OutputChunk>, local: bool) {
fn add_java_agents(config: &mut RunConfig, on_output: &Emit<OutputChunk>, run_dir: Option<&Path>) {
if !ide_run::java_agent::applies(&config.kind) {
return;
}
let java = std::path::Path::new(&config.command);
let agents = ide_run::java_agent::current_for(Some(java));
// The JVM the launch starts: a bare `java` (what generated configurations name) is looked
// up the way the process start finds it, so the `jdk` filter of `vmOptions` sees that JDK.
let java = run_dir.and_then(|dir| {
let search = ide_run::wrap::search_path_in(config, dir);
let home = config
.env
.get("JAVA_HOME")
.map(std::path::PathBuf::from)
.or_else(|| std::env::var_os("JAVA_HOME").map(std::path::PathBuf::from));
ide_run::java_agent::launched_java(&config.command, &search, home.as_deref())
});
let agents = ide_run::java_agent::current_for(java.as_deref());
let say = |text: &str| on_output(OutputChunk::System { text: format!("{text}\n") });
if !local {
if run_dir.is_none() {
if !agents.options.is_empty() {
say(
"Plugin Java agents were not added: they load only into JVMs started on this machine, not on a run target.",
+21 -3
Переглянути файл
@@ -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,
+20
Переглянути файл
@@ -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();
+2 -1
Переглянути файл
@@ -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()
+26 -1
Переглянути файл
@@ -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();
+1 -1
Переглянути файл
@@ -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();
+1 -1
Переглянути файл
@@ -320,7 +320,7 @@ mod tests {
})
.unwrap();
assert_eq!(json, "{\"threadDump\":{}}");
let prefix = format!("Thread.dump_to_file -format=json \"{}/threads-42-", dir.display());
let prefix = format!("Thread.dump_to_file -format=json \"{}", dir.join("threads-42-").display());
assert!(sent.starts_with(&prefix) && sent.ends_with(".json\""), "{sent}");
assert!(is_empty(&dir));
}
+57
Переглянути файл
@@ -123,6 +123,27 @@ fn is_jetbrains_jdk(java: &Path) -> bool {
release_field(java, "IMPLEMENTOR").is_some_and(|v| v.to_ascii_lowercase().contains("jetbrains"))
}
/// The JVM a configuration whose command is `command` starts, for the JDK filter. A path is
/// itself. A bare `java` is the first one on `search`, as the launch finds it; when that is
/// no JDK's own launcher (macOS's `/usr/bin/java` stub, which runs `JAVA_HOME`'s), it is
/// `java_home`'s. `None` when neither is found.
pub fn launched_java(command: &str, search: &std::ffi::OsStr, java_home: Option<&Path>) -> Option<PathBuf> {
let path = Path::new(command);
if path.components().count() > 1 {
return Some(path.to_path_buf());
}
let windows = cfg!(windows);
let found =
ide_core::process::find_executable_in(command, search, windows, std::env::var("PATHEXT").ok().as_deref());
if let Some(java) = &found
&& release_field(java, "JAVA_VERSION").is_some()
{
return found;
}
let java = java_home.map(|home| home.join("bin").join(if windows { "java.exe" } else { "java" }));
java.filter(|java| java.is_file()).or(found)
}
/// `KEY="value"` from the JDK `release` file next to `bin/java` (or JDK 8's `jre/bin/java`).
fn release_field(java: &Path, key: &str) -> Option<String> {
let java = std::fs::canonicalize(java).unwrap_or_else(|_| java.to_path_buf());
@@ -226,6 +247,42 @@ fn split_text(text: &str) -> Vec<String> {
mod tests {
use super::*;
/// A JDK home with `bin/java` and a `release` file naming `implementor`.
#[cfg(unix)]
fn jdk(root: &Path, name: &str, implementor: &str) -> PathBuf {
let home = root.join(name);
std::fs::create_dir_all(home.join("bin")).unwrap();
std::fs::write(home.join("bin/java"), "#!/bin/sh\n").unwrap();
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(home.join("bin/java"), std::fs::Permissions::from_mode(0o755)).unwrap();
std::fs::write(home.join("release"), format!("JAVA_VERSION=\"21\"\nIMPLEMENTOR=\"{implementor}\"\n")).unwrap();
home
}
#[cfg(unix)]
#[test]
fn a_bare_java_is_the_one_the_launch_finds() {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().unwrap();
let jbr = jdk(dir.path(), "jbr", "JetBrains s.r.o.");
let openjdk = jdk(dir.path(), "openjdk", "Eclipse Adoptium");
// A JDK's own launcher on the search path is what runs, whatever JAVA_HOME says.
let search = std::env::join_paths([jbr.join("bin")]).unwrap();
let java = launched_java("java", &search, Some(&openjdk)).unwrap();
assert!(jdk_allows(Some(&java), Some("jetbrains")));
// A stub outside any JDK (macOS /usr/bin/java) runs JAVA_HOME's.
let stub = dir.path().join("usr/bin");
std::fs::create_dir_all(&stub).unwrap();
std::fs::write(stub.join("java"), "#!/bin/sh\n").unwrap();
std::fs::set_permissions(stub.join("java"), std::fs::Permissions::from_mode(0o755)).unwrap();
let search = std::env::join_paths([stub]).unwrap();
let java = launched_java("java", &search, Some(&jbr)).unwrap();
assert!(jdk_allows(Some(&java), Some("jetbrains")));
assert!(!jdk_allows(launched_java("java", &search, Some(&openjdk)).as_deref(), Some("jetbrains")));
// A path is itself.
assert_eq!(launched_java("/opt/jdk/bin/java", &search, Some(&jbr)), Some(PathBuf::from("/opt/jdk/bin/java")));
}
fn strings(a: &[&str]) -> Vec<String> {
a.iter().map(|s| (*s).to_owned()).collect()
}
+2 -1
Переглянути файл
@@ -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};
+24 -8
Переглянути файл
@@ -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),
}
}
+162 -15
Переглянути файл
@@ -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();
+2 -1
Переглянути файл
@@ -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};
+5
Переглянути файл
@@ -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`,
+4
Переглянути файл
@@ -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`、
+10 -10
Переглянути файл
@@ -313,8 +313,8 @@ for (const surface of ["new", "task"] as const) {
const settings = page.getByRole("button", { name: /^Model settings:/ });
await settings.click();
await expect(page.getByRole("button", { name: "Back to models" })).toHaveCount(0);
await page.getByRole("radio", { name: "Thorough" }).click();
await page.getByRole("radio", { name: "1M" }).click();
await page.getByRole("option", { name: "Thorough" }).click();
await page.getByRole("option", { name: "1M" }).click();
await expect(settings).toHaveText("Thorough · 1M");
await page.keyboard.press("Escape");
await expect(box(page)).toHaveText("Review the project structure");
@@ -418,7 +418,7 @@ test("Settings and effort popup exclude the agent shortcut", async ({ workbench:
await expect(search).toHaveValue("keymap");
await settings.getByRole("button", { name: "Cancel", exact: true }).click();
await effortLabel(page).click();
const popup = page.getByRole("radiogroup", { name: "Effort Level", exact: true });
const popup = page.getByRole("listbox", { name: "Effort Level", exact: true });
await expect(popup).toBeVisible();
await page.keyboard.press("Alt+t");
expect(await ipcCalls(page, "agent_set_config")).toEqual([]);
@@ -642,10 +642,10 @@ test("New Task discovers uncached model effort before the first prompt", async (
await page.evaluate(() => document.dispatchEvent(new Event("test:model-settings-ready")));
await expectEffort(page, "Quick");
await effortLabel(page).click();
const efforts = page.getByRole("radiogroup", { name: "Effort Level", exact: true });
await expect(efforts.getByRole("radio", { name: "Quick", exact: true })).toBeVisible();
await expect(efforts.getByRole("radio", { name: "Thorough", exact: true })).toBeVisible();
await expect(efforts.getByRole("radio", { name: "Gentle", exact: true })).toHaveCount(0);
const efforts = page.getByRole("listbox", { name: "Effort Level", exact: true });
await expect(efforts.getByRole("option", { name: "Quick", exact: true })).toBeVisible();
await expect(efforts.getByRole("option", { name: "Thorough", exact: true })).toBeVisible();
await expect(efforts.getByRole("option", { name: "Gentle", exact: true })).toHaveCount(0);
await page.keyboard.press("Escape");
await expect(box(page)).toHaveText("Keep this first task unsent");
await expectNoSubmission(page);
@@ -675,9 +675,9 @@ test("an existing chat can choose effort for a refreshed model before sending",
await expect(modelButton(page)).toHaveAttribute("title", /^Model: Swift\b/);
await expectEffort(page, "Quick");
await effortLabel(page).click();
const efforts = page.getByRole("radiogroup", { name: "Effort Level", exact: true });
await expect(efforts.getByRole("radio", { name: "Gentle", exact: true })).toHaveCount(0);
await efforts.getByRole("radio", { name: "Thorough", exact: true }).click();
const efforts = page.getByRole("listbox", { name: "Effort Level", exact: true });
await expect(efforts.getByRole("option", { name: "Gentle", exact: true })).toHaveCount(0);
await efforts.getByRole("option", { name: "Thorough", exact: true }).click();
await page.keyboard.press("Escape");
await expectEffort(page, "Thorough");
await expect(send).toBeEnabled();
+6 -7
Переглянути файл
@@ -413,8 +413,7 @@ test("keeps chat history readable and selections free of timestamps and status l
expect(selected).not.toMatch(/AM|PM|5s|Reasoning|Requesting task context/);
await page.keyboard.press("ControlOrMeta+c");
expect(await page.evaluate(() => navigator.clipboard.readText())).toBe(selected);
// The finished turn's reasoning is folded with its work.
await stream.locator("[class*='_turnFold_'] > summary").click();
// The latest turn stays open: its reasoning shows as its own collapsed row.
await stream.locator("[class*='_thought_'] > summary").click();
await expect(stream.locator("[class*='_thoughtPreview_']")).toHaveText("Requesting task context");
await expect(stream.locator("[class*='_thoughtBody_'] strong")).toHaveText("Requesting task context");
@@ -795,8 +794,7 @@ test("Find in Conversation skips user-select:none summaries and closed <details>
}, TASK);
const stream = page.locator("[class*='_stream_']:visible");
const runSummary = stream.locator("details[class*='_processRun_'] > summary");
await runSummary.click();
// A command is its own row, outside the reasoning's run.
await expect(stream.getByText("stop_bash")).toBeVisible();
await stream.focus();
@@ -894,13 +892,14 @@ test("indents process-run thoughts and tool calls clearly and aligns output-less
entries: new Map([
[
task.id,
// Reasoning and read-only calls group into one run; commands and edits would be rows of their own.
[
{ type: "thought", text: "**Checking CI Status**\n\nInspecting workflow runs." },
{
type: "tool",
id: "t1",
title: "gh pr checks 3631 --repo l0ng-ai/openidea",
kind: "execute",
kind: "fetch",
status: "completed",
locations: [],
output: "All checks pending",
@@ -911,7 +910,7 @@ test("indents process-run thoughts and tool calls clearly and aligns output-less
type: "tool",
id: "t2",
title: "read_bash",
kind: "other",
kind: "read",
status: "completed",
locations: [],
output: "E2E pass",
@@ -921,7 +920,7 @@ test("indents process-run thoughts and tool calls clearly and aligns output-less
type: "tool",
id: "t3",
title: "read_bash",
kind: "other",
kind: "read",
status: "running",
locations: [],
output: "",
+14 -9
Переглянути файл
@@ -40,13 +40,17 @@ const entries: AgentEntry[] = Array.from({ length: 80 }, (_, turn): AgentEntry[]
},
]).flat();
async function openHistory(page: Page) {
/** Opens the 80-turn chat; `foldTurns` folds each earlier turn's work into one row. */
async function openHistory(page: Page, foldTurns = false) {
await page.goto("/");
await page.getByRole("tree", { name: "Project" }).waitFor();
await page.evaluate(
async ({ task, entries }) => {
async ({ task, entries, foldTurns }) => {
const path = "/src/features/agents/store.ts";
const projectPath = "/src/platform/project.ts";
const store = await import(path);
const { useProject } = await import(projectPath);
useProject.setState({ settings: { agents: { foldTurns } } });
store.useAgents.setState({
loaded: true,
error: null,
@@ -58,10 +62,12 @@ async function openHistory(page: Page) {
});
store.openTaskInEditorLocation(task.id);
},
{ task, entries },
{ task, entries, foldTurns },
);
const stream = page.locator("[class*='_stream_']:visible");
await expect(stream.locator(":scope > *")).toHaveCount(80 * 3);
// A turn shows its request, the read and the reasoning runs, the command, the edit and the reply;
// folded, its work is one row. The latest turn stays open.
await expect(stream.locator(":scope > *")).toHaveCount(foldTurns ? 79 * 3 + 6 : 80 * 6);
await page.evaluate(() => document.fonts.ready);
return stream;
}
@@ -85,7 +91,7 @@ for (const placement of ["editor", "toolWindow"] as const) {
);
// The working indicator ends the conversation, after its rows; the turn ends with a reply.
await expect(stream.getByRole("status").getByText("Writing…", { exact: true })).toBeVisible();
await expect(stream.locator(":scope > *")).toHaveCount(80 * 3 + 1);
await expect(stream.locator(":scope > *")).toHaveCount(80 * 6 + 1);
await expect.poll(() => stream.evaluate((el) => el.scrollHeight - el.clientHeight - el.scrollTop)).toBeLessThan(2);
const timer = await page.evaluate(async (id) => {
const path = "/src/features/agents/store.ts";
@@ -186,7 +192,7 @@ for (const selected of [false, true]) {
}
test("opens a folded turn with the keyboard and jumps back to the latest reply", async ({ page }) => {
const stream = await openHistory(page);
const stream = await openHistory(page, true);
await stream.evaluate((el) => {
el.scrollTop = 0;
});
@@ -197,9 +203,8 @@ test("opens a folded turn with the keyboard and jumps back to the latest reply",
await summary.focus();
await page.keyboard.press("Enter");
await expect(fold).toHaveAttribute("open", "");
const run = fold.locator("[class*='_processRun_']").first();
await expect(run).toBeVisible();
await run.locator(":scope > summary").click();
// A folded turn lists its work without nesting runs.
await expect(fold.locator("[class*='_processRun_']")).toHaveCount(0);
await expect(fold.getByText("read src/module-0.ts", { exact: true })).toBeVisible();
await summary.focus();
await page.keyboard.press("Space");
+16 -2
Переглянути файл
@@ -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.
+6
Переглянути файл
@@ -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>() {
+24
Переглянути файл
@@ -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")];
+4
Переглянути файл
@@ -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);
+54 -2
Переглянути файл
@@ -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 [
+78 -34
Переглянути файл
@@ -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)]
+1
Переглянути файл
@@ -650,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
+4
Переглянути файл
@@ -1878,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 })),
/**
@@ -9283,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)`. */
+16
Переглянути файл
@@ -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;
+7 -2
Переглянути файл
@@ -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>
);
+17 -10
Переглянути файл
@@ -1,17 +1,20 @@
/* A framed text area (IDEA text field frame), with the pickers in its bottom row. */
/* A framed text area (IDEA Islands surface), with compact pickers in its bottom row. */
.composer {
container: agent-composer / inline-size;
min-width: 0;
position: relative;
display: flex;
flex-direction: column;
border-radius: var(--radius-control);
background: var(--bg-field, var(--bg-button));
box-shadow: inset 0 0 0 1px var(--border-button);
border-radius: var(--radius-toolbar-button);
background: var(--bg-elev);
box-shadow: inset 0 0 0 1px var(--border-popup);
cursor: text;
transition: box-shadow var(--dur-fast) var(--ease);
transition:
background var(--dur-fast) var(--ease),
box-shadow var(--dur-fast) var(--ease);
}
.composer:focus-within {
background: var(--bg-field, var(--bg-button));
box-shadow:
inset 0 0 0 1px var(--focus-ring),
0 0 0 1px var(--focus-ring);
@@ -47,8 +50,8 @@
must land in the editable text, or they focus the bare scroller and no caret appears.
A host sets --composer-min-height rather than overriding the rule, so stylesheet order can't undo it. */
.field :global(.cm-content) {
min-height: var(--composer-min-height, 44px);
padding: var(--space-2) var(--space-2) var(--space-0-5);
min-height: var(--composer-min-height, 38px);
padding: 9px 12px 4px;
caret-color: var(--fg-strong);
white-space: pre-wrap;
overflow-wrap: anywhere;
@@ -100,6 +103,7 @@
min-width: 0;
overflow: hidden;
gap: var(--space-0-5);
font-size: var(--fs-small);
}
.toolbar > button {
flex: 0 1 auto;
@@ -197,14 +201,17 @@
.chip {
display: inline-flex;
align-items: center;
gap: var(--space-1-5);
gap: var(--space-1);
height: var(--h-control);
min-width: 0;
padding: 0 4px 0 6px;
border-radius: var(--radius-control);
border-radius: var(--radius-toolbar-button);
color: var(--fg-secondary);
font-size: var(--fs-small);
white-space: nowrap;
transition: background var(--dur-fast) var(--ease);
transition:
background var(--dur-fast) var(--ease),
color var(--dur-fast) var(--ease);
}
.chip.chipLoading,
.chip.chipLoading:hover {
+5 -5
Переглянути файл
@@ -517,7 +517,7 @@ function ModelPicker({
onClick={() => toggle("models")}
>
<span className={styles.chipValue}>{modelName}</span>
<Icon name="chevron-down" size={14} className={styles.chipChevron} />
<Icon name="chevron-down" size={12} className={styles.chipChevron} />
</button>
{!unavailable && modelRefresh?.loadingSettings ? (
<LoadingSettingsChip />
@@ -526,7 +526,7 @@ function ModelPicker({
!unavailable && (
<button
type="button"
className={clsx(styles.chip, styles.modelDetail)}
className={styles.chip}
aria-label={tx`Model settings: ${summary}`}
title={
fullSummary && fullSummary !== summary
@@ -538,7 +538,7 @@ function ModelPicker({
onClick={() => toggle("settings")}
>
<span className={styles.chipValue}>{summary}</span>
<Icon name="chevron-down" size={14} className={styles.chipChevron} />
<Icon name="chevron-down" size={12} className={styles.chipChevron} />
</button>
)
)}
@@ -753,14 +753,14 @@ function ModePicker({
title={summary}
onClick={() => setOpen((v) => !v)}
>
<Icon name={on ? "unlock" : modeIcon(current?.value ?? "")} size={14} />
<Icon name={on ? "unlock" : modeIcon(current?.value ?? "")} size={13} />
<span className={styles.chipValue}>{current?.name ?? tx("Default")}</span>
{on && (
<span className={clsx(styles.chipDetail, compactDetail && styles.compactDetail)} data-chip-detail="">
{tx(toggle.chipLabel)}
</span>
)}
<Icon name="chevron-down" size={14} className={styles.chipChevron} />
<Icon name="chevron-down" size={12} className={styles.chipChevron} />
</button>
<Popup
open={open}
-1
Переглянути файл
@@ -257,7 +257,6 @@
background: none;
color: var(--link);
font-size: var(--fs-small);
cursor: pointer;
}
.codeMore:hover {
background: var(--bg-hover);
+17 -5
Переглянути файл
@@ -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,7 +1154,7 @@
flex-wrap: wrap;
align-items: center;
align-content: flex-start;
gap: 0 6px;
gap: 0 var(--space-1-5);
color: var(--fg-subtle);
font-size: var(--fs-small);
font-variant-numeric: tabular-nums;
@@ -1166,7 +1166,7 @@
align-items: center;
min-width: 0;
height: 22px;
gap: 6px;
gap: var(--space-1-5);
}
.meterGroup {
display: inline-flex;
@@ -1174,7 +1174,7 @@
align-items: center;
min-width: 0;
height: 22px;
gap: 6px;
gap: var(--space-1-5);
}
.meterDivider {
flex: none;
@@ -1916,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;
+32 -16
Переглянути файл
@@ -1,24 +1,25 @@
/* Session Pull Requests, Issues, References, and Artifacts pills above the composer. */
/* Session Pull Requests, Issues, References, and Artifacts pills above the composer.
Flat like Chip / statusChip: no frame at rest, toolbar hover when interactive. */
.bar {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: var(--space-1-5);
gap: var(--space-0-5);
min-width: 0;
padding: 0 2px;
padding: 0;
}
.pill {
display: inline-flex;
align-items: center;
gap: var(--space-1-5);
height: 24px;
gap: var(--space-1);
height: 22px;
max-width: 100%;
min-width: 0;
padding: 0 8px;
border: 1px solid var(--border-popup);
border-radius: var(--radius-control);
background: var(--bg-elev);
padding: 0 4px 0 6px;
border: 0;
border-radius: var(--radius-toolbar-button);
background: transparent;
color: var(--fg-secondary);
font: inherit;
font-size: var(--fs-small);
@@ -26,17 +27,30 @@
white-space: nowrap;
transition:
background var(--dur-fast) var(--ease),
border-color var(--dur-fast) var(--ease),
color var(--dur-fast) var(--ease);
}
.pill:hover,
.pill[aria-expanded="true"] {
background: var(--bg-hover);
border-color: var(--border-strong);
background: var(--bg-toolbar-hover);
color: var(--fg-strong);
}
.pill:focus-visible {
outline: 2px solid var(--focus-ring);
outline-offset: -2px;
}
.pillIcon {
flex: none;
color: var(--fg-muted);
}
.pill:hover .pillIcon,
.pill[aria-expanded="true"] .pillIcon {
color: inherit;
}
.pillLabel {
min-width: 0;
overflow: hidden;
@@ -63,7 +77,7 @@
}
.sectionHeader {
padding: 4px 12px;
padding: 4px 14px;
color: var(--fg-muted);
font-size: var(--fs-small);
font-weight: 600;
@@ -75,13 +89,15 @@
display: flex;
align-items: center;
gap: var(--space-1);
min-height: 28px;
padding: 1px 6px 1px 10px;
min-height: 26px;
margin: 0 6px;
padding: 1px 4px 1px 8px;
border-radius: var(--radius-selection, 5px);
}
.row:hover,
.row:focus-within {
background: var(--bg-hover);
background: var(--bg-tree-hover, var(--bg-hover));
}
.rowMain {
+3 -3
Переглянути файл
@@ -514,7 +514,7 @@ export function SessionAssets({ task, entries, head, onFocusComposer }: SessionA
>
<Icon name={issueCount === 1 ? issueIcon(assets.createdIssues[0]!.state) : "issue-open"} size={13} />
<span className={styles.pillLabel}>{issuePillLabel}</span>
{issueCount > 1 && <Icon name="chevron-down" size={11} className={styles.chevron} />}
<Icon name="chevron-down" size={11} className={styles.chevron} />
</button>
<AssetPopup
open={activeCategory === "issues"}
@@ -538,7 +538,7 @@ export function SessionAssets({ task, entries, head, onFocusComposer }: SessionA
aria-expanded={activeCategory === "references"}
onClick={() => toggle("references")}
>
<Icon name="toolwindow-bookmarks" size={13} />
<Icon name="toolwindow-bookmarks" size={13} className={styles.pillIcon} />
<span className={styles.pillLabel}>{refPillLabel}</span>
<Icon name="chevron-down" size={11} className={styles.chevron} />
</button>
@@ -564,7 +564,7 @@ export function SessionAssets({ task, entries, head, onFocusComposer }: SessionA
aria-expanded={activeCategory === "artifacts"}
onClick={() => toggle("artifacts")}
>
<Icon name="artifact" size={13} />
<Icon name="artifact" size={13} className={styles.pillIcon} />
<span className={styles.pillLabel}>{artifactPillLabel}</span>
<Icon name="chevron-down" size={11} className={styles.chevron} />
</button>
-1
Переглянути файл
@@ -72,7 +72,6 @@
color: var(--link);
font: inherit;
font-size: var(--fs-small);
cursor: pointer;
}
.resetBtn:hover {
+7
Переглянути файл
@@ -1,4 +1,11 @@
.submit {
--button-radius: var(--radius-toolbar-button);
width: var(--h-control);
padding: 0;
}
.submit:disabled {
background: var(--bg-toolbar-hover);
color: var(--fg-faint);
box-shadow: none;
}
+4 -2
Переглянути файл
@@ -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;
+9
Переглянути файл
@@ -132,6 +132,14 @@ function useOffscreenRows(
mark();
const rows = new MutationObserver(mark);
rows.observe(el, { childList: true });
// Earlier rows load in front of the first one shown, which then loses its author header while
// it may be off-screen: lay it out again, or it keeps the height it had with the header.
const authors = new MutationObserver((records) => {
for (const { target } of records)
if (target.parentNode === el) (target as Element).removeAttribute("data-measured");
mark();
});
authors.observe(el, { subtree: true, attributes: true, attributeFilter: ["data-author"] });
const resize = new ResizeObserver(() => {
window.clearTimeout(timer);
timer = window.setTimeout(() => {
@@ -144,6 +152,7 @@ function useOffscreenRows(
cancelAnimationFrame(frame);
window.clearTimeout(timer);
rows.disconnect();
authors.disconnect();
resize.disconnect();
};
}, [ref, visible, enabled, fitWindowWidth, fontZoom]);
+26
Переглянути файл
@@ -0,0 +1,26 @@
import { describe, expect, it } from "vitest";
import type { AgentTask } from "@/bindings";
import { commandTitle } from "./shared";
const task = { cwd: "/repo/app" } as AgentTask;
describe("commandTitle", () => {
it("drops a cd into the task's own folder", () => {
expect(commandTitle(task, "cd /repo/app && git grep -n foo")).toEqual({ title: "git grep -n foo", dir: null });
expect(commandTitle(task, "cd . ; ls")).toEqual({ title: "ls", dir: null });
});
it("keeps another folder as the place the command ran", () => {
expect(commandTitle(task, "cd /repo/app-icons && pnpm test")).toEqual({
title: "pnpm test",
dir: "/repo/app-icons",
});
expect(commandTitle(task, `cd "/repo/my app/" && ls`)).toEqual({ title: "ls", dir: "/repo/my app" });
});
it("leaves commands without a leading cd, or that are only a cd, as they are", () => {
expect(commandTitle(task, "git status && cd x && ls")).toEqual({ title: "git status && cd x && ls", dir: null });
expect(commandTitle(task, "cd /tmp")).toEqual({ title: "cd /tmp", dir: null });
expect(commandTitle(task, "cat /repo/app/src/a.ts")).toEqual({ title: "cat src/a.ts", dir: null });
});
});
+15
Переглянути файл
@@ -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.
+11 -2
Переглянути файл
@@ -16,7 +16,7 @@ import { cancelTask } from "../store";
import { openChangeDiff } from "./ChangesTab";
import { Fold } from "./Folds";
import { liveTool } from "./conversationRows";
import { shortTitle, useNow } from "./shared";
import { commandTitle, shortTitle, useNow } from "./shared";
/** A location as the agent reported it: absolute on any platform, or relative to the task's folder. */
const isAbsolute = (path: string) => path.startsWith("/") || /^[A-Za-z]:[\\/]/.test(path) || path.startsWith("\\\\");
@@ -104,13 +104,22 @@ export const ToolEntry = memo(function ToolEntry({
const live = liveTool(entry);
const took = toolDuration(entry);
const run = entry.kind === "execute" ? toolRun(entry) : null;
const title = shortTitle(task, entry.title || entry.kind);
// Commands lose the `cd <dir> &&` agents start them with; another folder shows as a tag.
const { title, dir } =
entry.kind === "execute"
? commandTitle(task, entry.title || entry.kind)
: { title: shortTitle(task, entry.title || entry.kind), dir: null };
// A title that already names the file ("Read pom.xml") needs no second link to it.
const links =
entry.kind === "execute" ? [] : entry.locations.slice(0, 3).filter((path) => !title.includes(basename(path)));
const head = (
<>
<Icon name={TOOL_ICONS[entry.kind] ?? "run"} size={14} className={styles.toolKindIcon} />
{dir && (
<span className={styles.toolDir} title={dir}>
{basename(dir)}
</span>
)}
<span className={styles.toolTitle} title={entry.title || entry.kind}>
{title}
</span>
+44
Переглянути файл
@@ -0,0 +1,44 @@
import { describe, expect, it } from "vitest";
import type { RootFolder } from "@/platform/languageSettings";
import { javaPackageAt, pastedJavaClass, withJavaPackage } from "./javaPaste";
describe("Java code pasted into the Project view", () => {
it("is named after its first public top-level type, else its first", () => {
const text = "package a;\n/** Doc */\n@Deprecated class Helper {}\npublic final class Main<T> { class Inner {} }\n";
expect(pastedJavaClass(text)).toBe("Main");
expect(pastedJavaClass("record Point(int x, int y) {}\nenum Color { RED }")).toBe("Point");
expect(pastedJavaClass("public @interface Marker {}")).toBe("Marker");
expect(pastedJavaClass("interface Shape { double area(); }")).toBe("Shape");
});
it("is not code without a type: a statement, prose, a class only named in a comment", () => {
expect(pastedJavaClass("int x = 1;")).toBeNull();
expect(pastedJavaClass("hello world")).toBeNull();
expect(pastedJavaClass("// see class Foo\nfoo();")).toBeNull();
expect(pastedJavaClass("")).toBeNull();
});
it("takes the package of its folder below a Java source or test root", () => {
const roots: RootFolder[] = [
{ path: "app/src/main/java", kind: "source", detectedFrom: "app/pom.xml" },
{ path: "app/src/test/java", kind: "test", detectedFrom: "app/pom.xml" },
{ path: "web/src", kind: "source", detectedFrom: "web/package.json" },
];
expect(javaPackageAt("app/src/main/java/com/acme", roots)).toBe("com.acme");
expect(javaPackageAt("app/src/test/java/com", roots)).toBe("com");
expect(javaPackageAt("app/src/main/java", roots)).toBe("");
expect(javaPackageAt("docs", roots)).toBeNull();
expect(javaPackageAt("web/src/lib", roots)).toBeNull();
});
it("declares the folder's package, replacing or adding the statement", () => {
expect(withJavaPackage("package old.pkg;\n\nclass A {}", "com.acme")).toBe("package com.acme;\n\nclass A {}");
expect(withJavaPackage("import java.util.List;\nclass A {}", "com.acme")).toBe(
"package com.acme;\n\nimport java.util.List;\nclass A {}",
);
const same = "package com . acme;\nclass A {}";
expect(withJavaPackage(same, "com.acme")).toBe(same);
// Pasted into the source root itself: the default package keeps the code as it is.
expect(withJavaPackage("package old;\nclass A {}", "")).toBe("package old;\nclass A {}");
});
});
+66
Переглянути файл
@@ -0,0 +1,66 @@
// IDEA's Java file paste: Java code pasted into a folder of the Project view becomes
// `<Class>.java`, declaring the folder's package.
import { javaLanguage } from "@codemirror/lang-java";
import type { SyntaxNode } from "@lezer/common";
import { rootFor, type RootFolder } from "@/platform/languageSettings";
import { isJvmSourcePackage } from "@/ui/folderPresentation";
const TYPE_DECLARATIONS = new Set([
"ClassDeclaration",
"InterfaceDeclaration",
"EnumDeclaration",
"RecordDeclaration",
"AnnotationTypeDeclaration",
]);
const typeName = (text: string, declaration: SyntaxNode) => {
const name = declaration.getChild("Definition") ?? declaration.getChild("Identifier");
return name ? text.slice(name.from, name.to) : null;
};
const isPublic = (text: string, declaration: SyntaxNode) => {
const modifiers = declaration.getChild("Modifiers");
return !!modifiers && /(^|\s)public(\s|$)/.test(text.slice(modifiers.from, modifiers.to));
};
/**
* The class pasted Java code is named after: its first public top-level type, else its first
* top-level type; null when the text declares none (a statement, plain prose).
*/
export function pastedJavaClass(text: string): string | null {
if (!/\b(class|interface|enum|record)\b/.test(text)) return null;
const top = javaLanguage.parser.parse(text).topNode;
let first: string | null = null;
for (let node = top.firstChild; node; node = node.nextSibling) {
if (!TYPE_DECLARATIONS.has(node.name)) continue;
const name = typeName(text, node);
if (!name) continue;
if (isPublic(text, node)) return name;
first ??= name;
}
return first;
}
/**
* The package of the project-relative folder `rel`: its path below the Java source or test root
* it is in; null outside one, where a pasted file keeps the package it declares.
*/
export function javaPackageAt(rel: string, roots: readonly RootFolder[]): string | null {
if (!isJvmSourcePackage(rel, roots)) return null;
const root = rootFor(roots, rel)!;
const below = root.path ? rel.slice(root.path.length).replace(/^\/+/, "") : rel;
return below.split("/").filter(Boolean).join(".");
}
/**
* `text` declaring `pkg`: its package statement replaced, or one added in front. Unchanged for the
* default package (`""`), as in IDEA, which leaves the statement of code pasted into a source root.
*/
export function withJavaPackage(text: string, pkg: string): string {
if (!pkg) return text;
const declaration = javaLanguage.parser.parse(text).topNode.getChild("PackageDeclaration");
if (!declaration) return `package ${pkg};\n\n${text}`;
const name = declaration.getChild("ScopedIdentifier") ?? declaration.getChild("Identifier");
if (name && text.slice(name.from, name.to).replace(/\s+/g, "") === pkg) return text;
return `${text.slice(0, declaration.from)}package ${pkg};${text.slice(declaration.to)}`;
}
+53
Переглянути файл
@@ -22,9 +22,21 @@ import { initProjectTree, loadDir, setClipboard, setSelection, useProjectTree }
import { setOsClipboardForTests } from "./clipboard";
const askMock = vi.hoisted(() => vi.fn());
const confirmMock = vi.hoisted(() => vi.fn());
vi.mock("@/workbench/messages", async (original) => ({
...(await original<typeof import("@/workbench/messages")>()),
ask: askMock,
confirm: confirmMock,
}));
const clipboardText = vi.hoisted(() => vi.fn(async () => ""));
vi.mock("@/platform/clipboard", async (original) => ({
...(await original<typeof import("@/platform/clipboard")>()),
readClipboardPlainText: clipboardText,
}));
const roots = vi.hoisted(() => vi.fn((): unknown[] => []));
vi.mock("@/platform/projectRoots", async (original) => ({
...(await original<typeof import("@/platform/projectRoots")>()),
currentRoots: roots,
}));
let fs: MemoryFs;
@@ -248,6 +260,47 @@ describe("OS file imports", () => {
expect(notify).not.toHaveBeenCalled();
});
it("turns pasted Java code into <Class>.java declaring the folder's package, asking before replacing", async () => {
roots.mockReturnValue([{ path: "target", kind: "source", detectedFrom: "pom.xml" }]);
fs = new MemoryFs({ "/p/target/com/acme": null }, "/p");
setProjectFsForTests(fs, "/p");
initProjectTree("/p", "p");
await loadDir("/p");
setOsClipboardForTests({});
const written: string[] = [];
const create = fs.createFileBytes.bind(fs);
vi.spyOn(fs, "createFileBytes").mockImplementation(async (path, data) => {
written.push(`${path}: ${new TextDecoder().decode(data)}`);
await create(path, data);
});
clipboardText.mockResolvedValue("package old;\r\n\r\npublic class Greeter {}\r\n");
await paste("/p/target/com/acme");
expect(written).toEqual(["/p/target/com/acme/Greeter.java: package com.acme;\n\npublic class Greeter {}\n"]);
expect(useProjectTree.getState().revealRequest?.path).toBe("/p/target/com/acme/Greeter.java");
// The file exists: kept when the user declines, replaced when they agree.
confirmMock.mockResolvedValueOnce(false);
await paste("/p/target/com/acme");
expect(written).toHaveLength(1);
confirmMock.mockResolvedValueOnce(true);
await paste("/p/target/com/acme");
expect(confirmMock).toHaveBeenCalledWith(
expect.objectContaining({ message: "File 'Greeter.java' already exists. Do you want to overwrite it?" }),
);
expect(written).toHaveLength(2);
// Outside a source root the code keeps its own package; text without a type is not pasted.
clipboardText.mockResolvedValue("package demo;\nclass Note {}");
await paste("/p");
expect(written.at(-1)).toBe("/p/Note.java: package demo;\nclass Note {}");
clipboardText.mockResolvedValue("System.out.println(1);");
await paste("/p");
expect(notify).toHaveBeenCalledWith(expect.objectContaining({ title: "No files on the clipboard" }));
expect(written).toHaveLength(3);
clipboardText.mockResolvedValue("");
roots.mockReturnValue([]);
});
it("says the clipboard is empty when it holds neither files nor an image", async () => {
setOsClipboardForTests({});
await paste("/p/target");
+53 -5
Переглянути файл
@@ -2,7 +2,7 @@
* File operations behind the project view's actions: new / rename / delete,
* internal copy-cut-paste, drag & drop moves and OS file imports.
*/
import { writeClipboardText } from "@/platform/clipboard";
import { readClipboardPlainText, writeClipboardText } from "@/platform/clipboard";
import { createElement, Fragment } from "react";
import { askUsagesDetected, fileUsages, showFileUsages, viewUsages } from "@/editor/refactor";
import { executeAction, getAction } from "@/platform/actions";
@@ -14,13 +14,15 @@ import {
revealInFileManager,
} from "@/platform/fileManager";
import { maybeEditorService, notifications } from "@/workbench/contributions";
import { ask, confirmChecked } from "@/workbench/messages";
import { ask, confirm, confirmChecked } from "@/workbench/messages";
import { osClipboard } from "./clipboard";
import { lastFileRefactoring, nextFileOperation, runFileRefactoring, undoFileRefactoring } from "./fileRefactor";
import { openFileRefactorDialog, rememberedOptions } from "./FileRefactorDialogs";
import { beginLocalImport, projectFs } from "./fs";
import { renameCopiedJavaType } from "./javaCopy";
import { IpcError, isCancelled } from "@/platform/ipc";
import { javaPackageAt, pastedJavaClass, withJavaPackage } from "./javaPaste";
import { currentRoots } from "@/platform/projectRoots";
import { IpcError, isCancelled, isTauri } from "@/platform/ipc";
import { MEMBER_PREFIX, type ProjectNode } from "./model";
import {
isInside,
@@ -51,7 +53,7 @@ import { tx, txPart } from "@/platform/i18n";
import { hostOs, isRemoteWindow } from "@/platform/remote";
import { usePlatform } from "@/platform/platformInfo";
import { pathToCopy, type PathKind } from "@/platform/copyPath";
import { projectFolder, useProject } from "@/platform/project";
import { projectFolder, relativePath, useProject } from "@/platform/project";
export type { PathKind } from "@/platform/copyPath";
/** Nodes that may be renamed, moved or deleted (not roots, groups or library sources). */
@@ -586,6 +588,8 @@ export function copySelection(cut: boolean) {
/** Files or an image on the OS clipboard, cached: `canPaste` runs while a menu renders. */
let osHasFiles = false;
let osHasImage = false;
/** The clipboard holds Java code, which Paste turns into a file. */
let osHasJava = false;
/** Keeps Paste enabled for what Explorer copied; called when the window gains focus. */
export async function refreshOsClipboard() {
@@ -604,6 +608,10 @@ async function readOsClipboard(): Promise<string[] | null> {
if (get().clipboard !== clipboard) return null;
osHasFiles = external.length > 0;
osHasImage = image;
// Only the desktop app reads the text without asking; in a browser Paste still tries. Checked on
// every window focus, so a huge clipboard is not parsed for the menu item.
const text = !osHasFiles && !image && isTauri() ? await readClipboardPlainText().catch(() => "") : "";
osHasJava = text.length <= 1_000_000 && !!pastedJavaClass(text);
// Our remote text write removes file URLs, so any files were copied later.
// A failed write leaves ownership uncertain; retain the remote copy then.
if (handedOff && (clipboard?.remote ? external.length > 0 : !sameFiles(external, clipboard?.paths)))
@@ -612,7 +620,7 @@ async function readOsClipboard(): Promise<string[] | null> {
}
export function canPaste(): boolean {
return !!get().clipboard?.paths.length || osHasFiles || osHasImage;
return !!get().clipboard?.paths.length || osHasFiles || osHasImage || osHasJava;
}
/**
@@ -640,6 +648,7 @@ export async function paste(target = targetFolder()) {
return pasteFromOsClipboard(external, target);
if (!clipboard?.paths.length) {
if (await pasteImage(target)) return;
if (await pasteJavaCode(target)) return;
notifications().notify({ level: "info", title: "No files on the clipboard" });
return;
}
@@ -654,6 +663,45 @@ export async function paste(target = targetFolder()) {
});
}
/**
* Java code on the clipboard becomes `<Class>.java` in `target`, declaring the folder's package
* inside a source root, and opens (IDEA's Java file paste). Asks before replacing a file of that
* name. False when the clipboard holds no Java type.
*/
async function pasteJavaCode(target: string): Promise<boolean> {
const text = (await readClipboardPlainText().catch(() => "")).replace(/\r\n?/g, "\n");
const className = pastedJavaClass(text);
if (!className) return false;
const name = `${className}.java`;
const root = get().root ?? target;
const pkg = javaPackageAt(target === root ? "" : relativePath(root, target), currentRoots());
const path = joinPath(target, name);
await loadDir(target);
const exists = (get().listings.get(target) ?? []).some((e) => e.name === name);
if (
exists &&
!(await confirm({
title: tx("Paste"),
message: tx`File '${name}' already exists. Do you want to overwrite it?`,
ok: "Overwrite",
}))
)
return true;
const fs = projectFs(root);
try {
// The replaced file goes to Local History, like any delete.
if (exists) await fs.delete(path);
await fs.createFileBytes(path, new TextEncoder().encode(pkg === null ? text : withJavaPackage(text, pkg)));
} catch (e) {
fail(tx`Cannot paste ${name}`, e);
return true;
}
await loadDir(target, true);
revealPath(path, true);
await maybeEditorService()?.openFile(path, { focus: true });
return true;
}
/**
* Saves the clipboard's image in `target` as `img.png`, or `img_1.png`, `img_2.png`
* … when taken, and selects it. False when the clipboard holds no image.
+11
Переглянути файл
@@ -316,6 +316,17 @@ describe("Find in Files popup", () => {
expect(screen.getByRole("button", { name: "Open in Find Window" })).toBeEnabled();
});
it("clicking a scope tab keeps focus in the search field", async () => {
render(<FindInFilesOverlay />);
act(() => showFindPopup(false, { query: "order" }));
await settle();
const down = new MouseEvent("mousedown", { bubbles: true, cancelable: true });
screen.getByRole("tab", { name: "Module" }).dispatchEvent(down);
expect(down.defaultPrevented).toBe(true);
fireEvent.click(screen.getByRole("tab", { name: "Module" }));
expect(useFindPopup.getState().scopeTab).toBe("module");
});
it("closing remembers the search text", async () => {
render(<FindInFilesOverlay />);
act(() => showFindPopup(false, { query: "order" }));
+1
Переглянути файл
@@ -778,6 +778,7 @@ function FindInFilesDialog() {
}))}
activeId={s.scopeTab}
onSelect={(id) => selectScope(id as ScopeTab)}
keepFocusOnClick
/>
<div className={styles.scopeDetail}>
{s.scopeTab === "directory" && (
+2
Переглянути файл
@@ -8,10 +8,12 @@ import { onIdeEvent } from "@/platform/ipc";
import { registerOverlay } from "@/workbench/contributions";
import { dropAskpass, enqueueAskpass, useAskpass } from "./askpass";
import { AskpassHost } from "./AskpassDialog";
import { startPasswordMigrationNotice } from "./passwordMigration";
import { chooseSshSession, SSH_SETTINGS_PAGE, startSshSession } from "./session";
export function activate(): () => void {
const disposers = [
startPasswordMigrationNotice(),
registerOverlay({ id: "ssh.askpass", component: AskpassHost }),
onIdeEvent("askpass", (e) => enqueueAskpass({ id: e.id, prompt: e.prompt, kind: e.kind, remember: e.remember })),
onIdeEvent("askpassDone", (e) => dropAskpass(e.id)),
+57
Переглянути файл
@@ -0,0 +1,57 @@
import type { LegacyPasswordAction } from "@/bindings";
import { tx } from "@/platform/i18n";
import { call, commands, isTauri } from "@/platform/ipc";
import { notifications } from "@/workbench/contributions";
import { confirm } from "@/workbench/messages";
export function startPasswordMigrationNotice(): () => void {
let disposed = false;
const key = "ssh.legacyPasswords";
async function resolve(action: LegacyPasswordAction) {
if (
action === "removePlaintext" &&
!(await confirm({
title: tx("Remove plaintext copy"),
message: tx("Passwords and passphrases not yet in the credential store will need to be entered again."),
ok: tx("Remove plaintext copy"),
icon: "warning",
}))
)
return;
if (disposed) return;
const retry = { label: tx("Retry migration"), run: () => void resolve("retry") };
try {
const pending = await call(commands.sshLegacyPasswords(action));
if (disposed) return;
if (pending !== null) {
notifications().notify({
key,
level: "warning",
sticky: true,
title: tx("Saved credentials are still in plaintext"),
body: `${tx("Unlock the OS credential store and retry, or remove the plaintext copy in ssh-passwords.json.")} ${tx(pending)}`,
actions: [retry, { label: tx("Remove plaintext copy"), run: () => void resolve("removePlaintext") }],
});
} else if (action !== "check") {
notifications().notify({
key,
level: "info",
title: tx("No legacy plaintext credentials remain in ssh-passwords.json"),
});
}
} catch (e) {
if (!disposed)
notifications().notify({
key,
level: "error",
title: tx("Could not check or update ssh-passwords.json"),
body: e instanceof Error ? e.message : String(e),
actions: [retry],
});
}
}
if (isTauri()) void resolve("check");
return () => {
disposed = true;
};
}
+29
Переглянути файл
@@ -1,8 +1,37 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import * as ipc from "@/platform/ipc";
import { DEFAULT_SSH_CONFIG, type SshConfigValid } from "@/platform/remoteSettings";
import * as contributions from "@/workbench/contributions";
import * as messages from "@/workbench/messages";
import { answerAskpass, askpassAnswer, askpassTitle, dropAskpass, enqueueAskpass, useAskpass } from "./askpass";
import { startPasswordMigrationNotice } from "./passwordMigration";
import { type ConnectDeps, openSshTerminal, sessionItems, sshRemedy } from "./session";
it("offers recovery for legacy plaintext but never removes it without confirmation", async () => {
vi.spyOn(ipc, "isTauri").mockReturnValue(true);
const migrate = vi.spyOn(ipc.commands, "sshLegacyPasswords").mockResolvedValue({ status: "ok", data: "locked" });
const confirm = vi.spyOn(messages, "confirm").mockResolvedValueOnce(false).mockResolvedValueOnce(true);
const notify = vi.fn<contributions.NotificationService["notify"]>();
vi.spyOn(contributions, "notifications").mockReturnValue({ notify });
const dispose = startPasswordMigrationNotice();
try {
await vi.waitFor(() => expect(notify).toHaveBeenCalledOnce());
const actions = notify.mock.calls[0]![0].actions!;
actions.find((a) => a.label === "Remove plaintext copy")!.run();
await vi.waitFor(() => expect(confirm).toHaveBeenCalledOnce());
expect(migrate.mock.calls).toEqual([["check"]]);
actions.find((a) => a.label === "Retry migration")!.run();
await vi.waitFor(() => expect(notify).toHaveBeenCalledTimes(2));
migrate.mockResolvedValue({ status: "ok", data: null });
actions.find((a) => a.label === "Remove plaintext copy")!.run();
await vi.waitFor(() => expect(notify).toHaveBeenLastCalledWith(expect.objectContaining({ level: "info" })));
expect(migrate.mock.calls).toEqual([["check"], ["retry"], ["removePlaintext"]]);
} finally {
dispose();
vi.restoreAllMocks();
}
});
describe("askpass queue", () => {
beforeEach(() => useAskpass.setState({ queue: [] }));
+18 -1
Переглянути файл
@@ -161,17 +161,22 @@
overflow: hidden;
text-overflow: ellipsis;
}
/* Checkable changes tree in the Shelve / Create Patch dialogs. */
/* Checkable changes tree in the Shelve / Create Patch / Rollback dialogs. */
.fileTree {
display: flex;
flex-direction: column;
height: 260px;
margin: 0 14px;
border: 1px solid var(--border);
border-radius: var(--radius-small);
overflow: hidden;
}
.fileTreeView {
flex: 1;
min-width: 0;
min-height: 0;
/* Override Tree's `height: 100%`: WebKit doesn't resolve percentage heights against a flex-basis height. */
height: auto;
}
.fileTreeRow {
composes: fileRow;
@@ -244,6 +249,12 @@
max-width: 100%;
font-size: var(--fs-ui);
}
/* A bare inline span puts its inline-flex checkbox child on the text baseline,
lifting it above the sibling controls; keep the tooltip wrapper centred. */
.pushOptionWrap {
display: inline-flex;
align-items: center;
}
.pushTargetBar {
display: flex;
flex-wrap: wrap;
@@ -911,12 +922,18 @@
.comparisonTree {
flex: 1;
min-width: 0;
min-height: 0;
/* Stretch instead of Tree's `height: 100%`: WebKit doesn't resolve percentage heights against a flex-basis height. */
height: auto;
align-self: stretch;
border: 1px solid var(--border);
}
.comparisonWithDiff .comparisonTree {
flex: 0 0 30%;
}
.comparisonDiff {
display: flex;
flex-direction: column;
flex: 1;
min-width: 0;
min-height: 0;
+4 -1
Переглянути файл
@@ -1265,7 +1265,10 @@ function PushDialog({
resizable="both"
footerStart={
<div className={styles.pushOptions}>
<span title={protectedTarget ? `Force push to protected branch '${target}' is prohibited` : undefined}>
<span
className={styles.pushOptionWrap}
title={protectedTarget ? `Force push to protected branch '${target}' is prohibited` : undefined}
>
<Checkbox
checked={force && forceAvailable}
disabled={!forceAvailable || inspection.fetching}
+2 -1
Переглянути файл
@@ -6110,5 +6110,6 @@
"Couldn't roll back": "No se pudo revertir",
"This message and the ones after it are removed, and the files the agent changed since go back to how they were before it was sent. The message returns to the composer.": "Este mensaje y los posteriores se eliminan, y los archivos que el agente modificó desde entonces vuelven a como estaban antes de enviarlo. El mensaje vuelve al cuadro de texto.",
"This clears the entire conversation, puts the files the agent changed back as they were when the task started, and starts a fresh agent session with this message.": "Esto borra toda la conversación, devuelve los archivos que el agente modificó a como estaban al empezar la tarea e inicia una nueva sesión del agente con este mensaje.",
"Resets in {resetIn}": "Se restablece en {resetIn}"
"Resets in {resetIn}": "Se restablece en {resetIn}",
"Cannot paste {name}": "No se puede pegar {name}"
}
+2 -1
Переглянути файл
@@ -5753,5 +5753,6 @@
"Couldn't roll back": "Impossible de revenir en arrière",
"This message and the ones after it are removed, and the files the agent changed since go back to how they were before it was sent. The message returns to the composer.": "Ce message et les suivants sont supprimés, et les fichiers modifiés par l'agent depuis reviennent à leur état d'avant l'envoi. Le message revient dans la zone de saisie.",
"This clears the entire conversation, puts the files the agent changed back as they were when the task started, and starts a fresh agent session with this message.": "Cela efface toute la conversation, remet les fichiers modifiés par l'agent dans leur état du début de la tâche et démarre une nouvelle session de l'agent avec ce message.",
"Resets in {resetIn}": "Réinitialisation dans {resetIn}"
"Resets in {resetIn}": "Réinitialisation dans {resetIn}",
"Cannot paste {name}": "Impossible de coller {name}"
}
+2 -1
Переглянути файл
@@ -6220,5 +6220,6 @@
"Couldn't roll back": "롤백할 수 없습니다",
"This message and the ones after it are removed, and the files the agent changed since go back to how they were before it was sent. The message returns to the composer.": "이 메시지와 이후 메시지가 제거되고, 그 이후 에이전트가 변경한 파일은 메시지를 보내기 전 상태로 돌아갑니다. 메시지는 입력란으로 돌아갑니다.",
"This clears the entire conversation, puts the files the agent changed back as they were when the task started, and starts a fresh agent session with this message.": "전체 대화를 지우고, 에이전트가 변경한 파일을 작업 시작 시점의 상태로 되돌린 뒤, 이 메시지로 새 에이전트 세션을 시작합니다.",
"Resets in {resetIn}": "{resetIn} 후 재설정"
"Resets in {resetIn}": "{resetIn} 후 재설정",
"Cannot paste {name}": "{name}을(를) 붙여넣을 수 없습니다"
}
+2 -1
Переглянути файл
@@ -5918,5 +5918,6 @@
"Couldn't roll back": "Nie udało się wycofać",
"This message and the ones after it are removed, and the files the agent changed since go back to how they were before it was sent. The message returns to the composer.": "Ta wiadomość i kolejne zostaną usunięte, a pliki zmienione od tego czasu przez agenta wrócą do stanu sprzed jej wysłania. Wiadomość wróci do pola tekstowego.",
"This clears the entire conversation, puts the files the agent changed back as they were when the task started, and starts a fresh agent session with this message.": "To wyczyści całą rozmowę, przywróci pliki zmienione przez agenta do stanu z początku zadania i rozpocznie nową sesję agenta z tą wiadomością.",
"Resets in {resetIn}": "Resetuje się za {resetIn}"
"Resets in {resetIn}": "Resetuje się za {resetIn}",
"Cannot paste {name}": "Nie można wkleić {name}"
}
+2 -1
Переглянути файл
@@ -5933,5 +5933,6 @@
"Couldn't roll back": "Não foi possível reverter",
"This message and the ones after it are removed, and the files the agent changed since go back to how they were before it was sent. The message returns to the composer.": "Esta mensagem e as seguintes são removidas, e os arquivos que o agente alterou desde então voltam a como estavam antes do envio. A mensagem volta para a caixa de texto.",
"This clears the entire conversation, puts the files the agent changed back as they were when the task started, and starts a fresh agent session with this message.": "Isso limpa toda a conversa, devolve os arquivos que o agente alterou a como estavam no início da tarefa e inicia uma nova sessão do agente com esta mensagem.",
"Resets in {resetIn}": "Redefine em {resetIn}"
"Resets in {resetIn}": "Redefine em {resetIn}",
"Cannot paste {name}": "Não é possível colar {name}"
}
+1
Переглянути файл
@@ -371,6 +371,7 @@
"Make configurations pinned by default": "Закреплять конфигурации по умолчанию",
"A finished pinned tab stays open: a later run opens a new tab instead of taking its place.": "Завершённая закреплённая вкладка остаётся открытой: последующий запуск откроет новую вкладку вместо замены текущей.",
"Cannot paste the image into {name}": "Не удалось вставить изображение в {name}",
"Cannot paste {name}": "Не удалось вставить {name}",
"New Worktree from '{name}'…": "Новый Worktree из «{name}»…",
"Prune Worktrees": "Очистить Worktree",
"Prune Worktrees…": "Очистить Worktree…",
+1
Переглянути файл
@@ -143,6 +143,7 @@
"Make configurations pinned by default": "Yapılandırmaları varsayılan olarak sabitle",
"A finished pinned tab stays open: a later run opens a new tab instead of taking its place.": "Tamamlanmış sabitlenmiş sekme açık kalır; sonraki çalıştırma bu sekmenin yerine yeni bir sekme açar.",
"Cannot paste the image into {name}": "Görsel {name} içine yapıştırılamıyor",
"Cannot paste {name}": "{name} yapıştırılamıyor",
"Worktree Conflict": "Çalışma Ağacı Çakışması",
"Branch '{branch}' is already checked out in a worktree at:\n{path}": "'{branch}' dalı zaten şu konumdaki çalışma ağacında kullanılıyor:\n{path}",
"Checkout Anyway": "Yine de Geçiş Yap",
+10
Переглянути файл
@@ -132,6 +132,7 @@
"Make configurations pinned by default": "預設固定執行/偵錯分頁",
"A finished pinned tab stays open: a later run opens a new tab instead of taking its place.": "固定的分頁結束後會保留:之後的執行會開啟新分頁,而不是取代它。",
"Cannot paste the image into {name}": "無法將圖片貼上為 {name}",
"Cannot paste {name}": "無法貼上 {name}",
"Worktree Conflict": "工作樹衝突",
"Branch '{branch}' is already checked out in a worktree at:\n{path}": "分支 '{branch}' 已在以下位置的工作樹中籤出:\n{path}",
"Checkout Anyway": "仍然簽出",
@@ -2634,6 +2635,15 @@
"Results": "結果",
"Resume Program": "繼續執行程式",
"Retry": "重試",
"Retry migration": "重試移轉",
"Remove plaintext copy": "移除明文副本",
"Saved credentials are still in plaintext": "已儲存的認證仍以明文存放",
"Unlock the OS credential store and retry, or remove the plaintext copy in ssh-passwords.json.": "請解鎖系統認證存放區後重試,或移除 ssh-passwords.json 中的明文副本。",
"Migration is incomplete.": "移轉尚未完成。",
"Passwords and passphrases not yet in the credential store will need to be entered again.": "尚未移轉至認證存放區的密碼和通行片語需要重新輸入。",
"No legacy plaintext credentials remain in ssh-passwords.json": "ssh-passwords.json 中已無舊版明文認證",
"Could not check or update ssh-passwords.json": "無法檢查或更新 ssh-passwords.json",
"Could not save credential": "無法儲存認證",
"Return to the start of the selected frame's method": "傳回所選幀所在方法的開頭",
"Reveal in Project View": "在專案檢視中顯示",
"Reverse patch": "反向補丁",
+10
Переглянути файл
@@ -381,6 +381,7 @@
"Make configurations pinned by default": "默认固定运行/调试标签页",
"A finished pinned tab stays open: a later run opens a new tab instead of taking its place.": "固定的标签页结束后会保留:之后的运行会打开新标签页,而不是替换它。",
"Cannot paste the image into {name}": "无法将图片粘贴为 {name}",
"Cannot paste {name}": "无法粘贴 {name}",
"New Worktree from '{name}'…": "从“{name}”新建工作树…",
"Prune Worktrees": "清理工作树",
"Prune Worktrees…": "清理工作树…",
@@ -3125,6 +3126,15 @@
"Results": "结果",
"Resume Program": "恢复程序",
"Retry": "重试",
"Retry migration": "重试迁移",
"Remove plaintext copy": "移除明文副本",
"Saved credentials are still in plaintext": "已保存的凭据仍以明文存储",
"Unlock the OS credential store and retry, or remove the plaintext copy in ssh-passwords.json.": "请解锁系统凭据库并重试,或移除 ssh-passwords.json 中的明文副本。",
"Migration is incomplete.": "迁移未完成。",
"Passwords and passphrases not yet in the credential store will need to be entered again.": "尚未迁移到凭据库的密码和密码短语需要重新输入。",
"No legacy plaintext credentials remain in ssh-passwords.json": "ssh-passwords.json 中已无旧版明文凭据",
"Could not check or update ssh-passwords.json": "无法检查或更新 ssh-passwords.json",
"Could not save credential": "无法保存凭据",
"Return to the start of the selected frame's method": "返回所选帧所在方法的开头",
"Reveal in Project View": "在项目视图中显示",
"Reverse patch": "反向补丁",
+2 -1
Переглянути файл
@@ -7,7 +7,8 @@
flex-direction: column;
min-width: 0;
min-height: 0;
height: 100%;
/* Stretch inside [data-panel]'s row flex box: `height: 100%` fails to resolve against a flex-basis height in WebKit. */
align-self: stretch;
}
.handle {
position: relative;
+12
Переглянути файл
@@ -169,6 +169,18 @@ describe("Tabs interactions", () => {
expect(onClose).toHaveBeenCalledWith("b");
});
it("leaves focus where it was on click only when the strip asks to", () => {
const { rerender } = render(<Tabs items={items} activeId="b" onSelect={() => {}} keepFocusOnClick />);
const down = () => {
const event = new MouseEvent("mousedown", { bubbles: true, cancelable: true });
screen.getByRole("tab", { name: "C" }).dispatchEvent(event);
return event.defaultPrevented;
};
expect(down()).toBe(true);
rerender(<Tabs items={items} activeId="b" onSelect={() => {}} />);
expect(down()).toBe(false);
});
it("keeps Shift+click selection where the strip does not opt in", () => {
const onClose = vi.fn();
const onSelect = vi.fn();
+7
Переглянути файл
@@ -158,6 +158,11 @@ export interface TabsProps {
closePosition?: "right" | "left";
/** `vertical`: a column of tabs (editor tabs placed left / right); always scrolls, `layout` is ignored. */
orientation?: "horizontal" | "vertical";
/**
* Clicking a tab leaves keyboard focus where it was (a scope strip under a search field, like the
* Find in Files scopes); keyboard navigation of a focused strip is unchanged.
*/
keepFocusOnClick?: boolean;
}
export function Tabs({
@@ -180,6 +185,7 @@ export function Tabs({
hiddenTabsOnly = false,
closePosition = "right",
orientation = "horizontal",
keepFocusOnClick = false,
...aria
}: TabsProps) {
const vertical = orientation === "vertical";
@@ -496,6 +502,7 @@ export function Tabs({
tabIndex={selected || (!activeId && index === 0) ? 0 : -1}
className={clsx(styles.tabButton, item.dimmed && styles.dimmed)}
style={item.color ? { color: item.color } : undefined}
onMouseDown={keepFocusOnClick ? (e) => e.preventDefault() : undefined}
onClick={(e) => {
// Shift+click is mouse-only: a keyboard Enter with Shift held still selects.
if (closeOnShiftClick && e.shiftKey && e.detail > 0 && closable) {